This is a pictorial overview to Home Construction. I am going to walk you through the process. I have also placed in bold type each Trade (contractor)that was involved in each segment of the building process. I have to limit the number of pictures to keep the pages from getting too large.
You may notice in the pictures that we started home construction in the winter, and finished in the summer. We had a total of 9 months of construction, and 2 of rain. Yes, it rained non-stop as soon as we got our financing. Weather is one of the reasons that I suggest you go for the longest duration you can on your home construction loan, as long as the terms are the same.
I have concentrated my pictures on the outside of the house during home construction. I wanted to give more of the basic structure than the finishing. Let' get started!
Most of us do not think a road is any big deal, Right? Wrong! I found out real quick that it was a major concern in home construction. You must have a good road to get materials and trucks in with dirt, concrete etc... Find yourself a good dirt and excavation contractor that is a road building expert and he will bring in the right material so your road is passable in all weather conditions. If it is not, you are going to suffer serious delays in your home construction project.
We put our septic system in before the pad, because it was easier to access the site to install it prior, to home construction. Usually it is put in later in the home construction process so nobody runs over it and destroys anything. If you are not on city water, and sewer you are going to need a well, and a septic system. Most counties require a permit. When you apply for the permit they will supply you with a list of licensed Septic System installers, if you ask. In our county we had to have a septic plan done by a certified septic system designer then apply for the permit. Then it was installed, and inspected. It is not that complicated, your local county will walk you through it.
Dirt is not cheap! You would think it would be. Nope! We brought in 106 loads to build up our pad prior to home construction. We had the pad built then we had it core sampled by a soil testing service. The soil testing service gave us a report and we sent it to a civil engineer for recommendations for the foundation prior to home construction.
We live down south where the soil has a high consistency of clay so we put in Bell Bottom Piers below the slab to give it stability. We put one at every intersecting footer and every nine feet under the supporting walls as recommended by the civil engineer for our home construction.
These are a pictures of the foundation forms prior to pouring the concrete. As you will notice, the Plumber has put in his piping below the pour. The electrician has also put the conduit for the kitchen island, and floor plugs in the great room.
You will also notice all of the steel that we put in the foundation. In our area, one of the largest home repair industries is foundation repair. Why you ask? Good Question!
Our area also has the highest use of post tension foundations for home construction. Post tension foundations use far less steal rebar in the foundation. The method uses steal cables that are placed in the foundation before the pour, and after the concrete sets up they then tension the cables to give the foundation strength. Unless it is done just right you have problems. The problems are cracking and settling that shows up many years later, and guess who pays then? Your right! The homeowner you, or me. The Builder, has no liability after several years. So why would a builder use this method, you ask? Outstanding Question again! Because it is cheaper method of home construction, that's why!
One more point; I would suggest when you are choosing your concrete contractor bid the foundation project turnkey. In other words ask for his price for a completed foundation according to your specifications. Why? Many people told me to buy my own materials, and hire the different crafts, to do my foundation. That I would save money in the long run. I would have to hire a form framing or set crew a form fill crew to dig the footers and form the dirt so the concrete guys could put the steel in and then pour. I would have to coordinate all the materials to be on site and on time then get each one of these crews to do it. This also is contingent that it does not rain in the process.
Sounds like a pain doesn't it? I decided to take the easy road and turnkey bid the project. My concrete guy was pouring when I was in grade school so he was competent, and I did my Research and found a good one. He lined everything up on his end, the only thing I had to line up was bringing in the plumber and the electrician to put in anything that went in the foundation or ground. Once that was done the concrete guy took over and did his thing.
After the fill dirt was in and the forms set and everything was ready to pour, guess what happened? Yep, It came a 4-inch rain and washed it all away. Guess who had to pay to fix it? Not me, the concrete guy! Remember I bid it turnkey. That means he does not get any money until I have a completed foundation.
Now we are ready to pour the foundation. This one is pretty self-explanatory. I put a shot of the concrete pumper truck and the concrete guys at work. It was really great watching these guys work!
Framing my favorite part of Home Construction! Why? Because it is when your house starts to look like a house. Another reason to love it is, you get to see the shape of your dream home. It also goes up very fast. They had the whole place framed in 3 weeks by the framing carpenters.
A couple of points to remember here. Keep a close eye on the progress, use your plans, and measure to see if everything is where it should be. If something is a couple of inches off do not have a coronary. Do have one if it is a doorway or a window opening. They don't look too good with a gap in them.
If you do you RESEARCH prior to home construction you will find a good Framer. Remember the Building Contractor page. If not, go look and come back here, I have more home construction to show you.
One more thing that is important that I don't think I have mentioned is get to know your contractors doing your home construction. No! This is not Research! Well it is sort of, but what I mean is really get to know them. Your crew will have a foreman, get to know him, ask questions and get his opinion. Bring them a cold drink, buy some donuts, show some good will. Believe me they are not used to it. The General Contractors usually treat these guys like dirt. So it pays to be different, why?
I got to know my Framing Foreman, and he had no problem approaching me about anything (related to the job). The basis of this trust started right after they had put the floor decking down for the second floor. I measured one of the closets, and it was longer than it should be. I asked him if he could explain. He looked at the plans and apologized, and said they would tear out the flooring and make it right. We had another look at it, and then decided why not make an additional small closet instead of waste the material. So later we added a door and it is now a hot water heater closet. I had bought that material for my home construction and he had wasted it. So maybe I should have gone nuts, and made him pay.
Later on in the framing the Foreman came and asked me to come up in the attic above the master bedroom. He showed me how with just a little material I could have a room measuring 22' x 14'. He had already figured the additional cost of lumber, and just wanted to know if I wanted to do it. Let's see a giant room for $1500 dollars of lumber (it costs more for the other materials to finish it but not much) you bet I did. They knocked it out in a couple of hours and it is now my media room upstairs. The point is the Contractors will help you with your home construction, if you are approachable. Get to know them, and listen to them. These guys know home construction, and they are building your house!
Now we are moving ahead with our home construction, we have the windows in, roof decking done, the felt down on the roof, and the cornice done (cornice is the siding, facial boards, soffit and outside trim). My framer also had a cornice crew that came in after the framing was done.
The cornice guys, are very different than framers. They are finishing the outside of the house. The framers are putting up sticks at an alarming rate. The cornice goes slower, because it must fit right, and look good.
One very good reason to have the framers and the cornice people work for the same contractor on your home construction is, one directly follows the other. If the framing is not right, the windows won't fit properly, and the cornice won't go on right. If it doesn't, they go back to the other crew, and it get's corrected.
One quick note on windows. Windows are one of your biggest expenses in home construction. Do your homework, and find a regional manufacturer of windows, and buy from them. Unless you want really high end windows, you can save as much as 50% by going directly to the factory. Do it the same way as you did your other materials for home construction, get a bid from your plans. They deliver right to your house, and most of them have a 5-year warranty.
Now we will spend a little time on inside home construction. This is a picture of a firebox in the study that has been set. We used a separate contractor to set the firebox's . Many of the insulation contract companies will do both setting the fireboxes and insulating the house. We are not ready for insulation yet, we have to top out the plumbing, rough wire the house, and rough in the Heating and Air Conditioning.
Now we are getting all the guts of the systems of the house put in, plumbing piping, rough electrical wiring, and Heating and Air Conditioning duct work.
It is to be noted here that all three of these crafts are trying to get their part of the home construction done at the same time. You certainly want them to get done as soon as they can because the home construction loan interest clock is ticking. That means they are all in each others space and it can be circus sometimes. They tend to whine about the other one getting in the way. Just give them a little cheese with their whine! Sorry, couldn't resist!
Now we are back outside of our home construction and this is right after we had the outside painted by the painting contractor. A couple of notes here. I did my RESEARCH and found a good painter for the outside. So what could go wrong?
A little story for your amusement is in order. My wife was watching the painters on her day off, thank God. She had picked the color at the paint store and given them the paint chip number and the paint she wanted.
By the way, spend the money for the highest quality paint. You don't want to do it again in 3 years. All the General Contractors will slip cheap paint in and it will fail quickly. Good paint lasts a long time. Labor is far more expensive than paint!
Ok, back to the story. The painters took their paint chip index in and handed it to the paint store guy and said give me this color. The paint store guy put the index example in his machine, you know the one that you can match any color in the world using the computer. He then mixed up 25 gallons of the stuff and the painters brought it back. They preceded to put it on the house. My wife called me at work in horror, she said, "the painters have painted half the house and it is the wrong color" so I got in the car and went to investigate. Of course when I got there the painters were at a full stop and confused.
The part of the house they had painted was a washed out white ugly gray nasty color. We had picked a regal gray. OK, what gives! What had happened is my wife had picked the color at the paint store and given the painter the number of the paint and the type of paint. The painter proceeded to pick up his color index off the dash of his truck that had been in the sun for 5 years and handed the matching color number to the paint store attendant. The problem with the chip was it had faded to a terrible white color and the computer did it's job and duplicated it.
It was not funny at the time but it is now. What can you learn from this? Buy the paint yourself and you don't have any miscommunication. Another good reason as told to my wife by one of the paint store guys is as follows: Some of the unscrupulous painters will buy cheaper paint and put it in empty buckets of the good paint. You think you are getting the good stuff. So buy it yourself and ask for the buckets when they are done. It is also a good idea to keep an eye on them while they work at least until they get a good start.
Of course if you do you Research and find the good ones you can relax somewhat. But, what have I said over and over. Knowledge is power, so get the power, study and learn. Go to the Knowledge Center and check it out!
At his stage of home construction we put on the roofing. We choose composition because it is durable and I didn't want to pay for a metal roof. Clearly the metal would last longer, but I like the way the architectural composition looks, and it was 50% less. One note about roofing make sure you get a good roofing company with a good warranty. In other words do your Research. There he goes again!
The warranty is especially important if you have a roof with complicated angles and many valleys. We do, and we have had a couple of leaks. We could have gone with the low bid Roofer but choose a company with a good reputation and a 5 year warranty, it has paid off!
One more quick thing about the home construction process. We decided to paint the outside before putting on the roof. The reason is simple, to avoid over spray from the painters. One thing you must do is felt the roof as soon as the decking goes down. Then paint the outside and get the roof down as quickly as possible. Felt alone will leak if given enough time.
Now we put on the stone. We choose cultured stone because it does not weigh as much. Weight is a key factor in foundation construction. The more weight the more you have to put in the foundation. Oh, you need a Masonary contractor to do this. Do your Research!
Ok! Let's talk about the inside for a few minutes and then I must finish up. I will add some more pictures later if you want me to of the inside, but for now you have a good overview of the process. For more information on home construction go to the Building Knowledge Center. We have put many resources there for you to educate yourself.
The interior is where things slow down in home construction. The finish work seems to take forever. After the rough in of electrical, plumbing and heating and air conditioning you are ready for insulation in the walls. The attic insulation comes later after most every thing is done up there. If you have your Air Handlers for your Heating and Air Conditioning units up there that all must be finished prior to insulation. It is a good idea to have all that done and check the drains for leaks on the units prior to insulation. Leaks are easier to find before all that fluffy itchy stuff is in your way.
I hope you get the picture of how home construction is all a progression. Pick out some good books in the Knowledge Center and learn the home construction process. Like I said, on the Home Page if a regular guy like me can do it just think what somebody as smart as you can do!


250 ml natural organic rose conditioner from Urtekram.
SKU: URT-83718. Categories: Brands, Urtekram International AG, Cosmetics, Hair Care, Shampoo & Conditioners. Tags: natural conditioner, organic hair conditioner, rose conditioner.
We have filled the bottle with nature's own moisturisers aloe vera and glycerine – gentle care for normal hair with a delicate rose scent.


text:
All-Time Mount Rushmore: Baltimore Ravens
Home/NFL/The NFL's Top Free Agents of 2020
FeaturedNFL
The NFL's Top Free Agents of 2020
Devon Withers
Want more from The Athletes Hub? Check out our Instagram page for more insight!
The upcoming season is only weeks away, with games of some sort taking place every weekend now up until February of 2020. While it's fun to bet on the current favorites, what about the future of select superstars? Here is where we breakdown the headline free agents of 2020.
ProSports Media
Quarterback: Dallas Cowboys Dak Prescott
The Dallas Cowboys will face a number of contract negotiations in the next two seasons, but none will be more important than Dak Prescott. With a starting record of 32-16, the two sides have mutual interest in a contract extension. With Carson Wentz earning $128M in his newest extension, that could be the standard for the two-time NFC East winner.
Other Names Include: Tampa Bay Buccaneers Jameis Winston, Tennessee Titans Marcus Mariota
Harry How, Getty Images
Running Back: Los Angeles Chargers Melvin Gordon
Despite an injury history, Los Angeles Chargers' Melvin Gordon is currently holding out for either a new contract or trade. With an impressive 38 TD over the last four seasons, this comes from missing 12 games in the process. The running back market is a bit depleted at the moment, so it'll be interesting to see whether Gordon starts in Week 1 against the Indianapolis Colts.
Other Names Include: Tennessee Titans Derrick Henry, Houston Texans Lamar Miller, Cleveland Browns Kareem Hunt
Capital Sports Report
Wide Receiver: Kansas City Chiefs Tyreek Hill
After clearing all allegations of child abuse this summer, Hill will be in the spotlight for the entirety of 2019. In just 30 games, he has totaled 3,255 yards and 25 TD. Although this segment is dedicated for wide receivers, it's hard to ignore the fact that Hill also has 5 TD on special teams. The Chiefs will need to decide whether his talent outweighs his baggage by the end of the upcoming season.
Other Names Include: Dallas Cowboys Amari Cooper, Cincinnati Bengals AJ Green, Denver Broncos Emmanuel Sanders
Mike Stobe, Getty Images
Tight End: Indianapolis Colts Eric Ebron
In his first season under the Indianapolis Colts, Eric Ebron found himself with 13 TD. To put that into perspective, Ebron totaled 11 TD in his previous four seasons with the Detroit Lions. As a borderline elite tight end in the eyes of most, we should be on watch for the Colts, who also need to address the contract of Jack Doyle; someone who's been with Indianapolis the past six seasons.
Other Names Include: Los Angeles Chargers Hunter Henry, Cincinnati Bengals Tyler Eifert, Indianapolis Colts Jack Doyle
Offensive Line: Chicago Bears Cody Whitehair
The offensive line is often overlooked, and many believe that Cody Whitehair is the next member of the Chicago Bears to receive a long-term extension. Last season, Whitehair was the only member of the Bears offense to play every single snap. His rookie contract concludes at the end of the 2019 season, so let's see if he lands the extension he deserves.
Other Names Include: Washington Redskins Brandon Scherff, Cleveland Browns J.C. Tretter, Green Bay Packers Bryan Bulaga
Defensive Line: Kansas City Chiefs Chris Jones
According to the latest reports, the Kansas City Chiefs and Chris Jones have been in communication in regards to an extension. In 2018, Jones led the team in sacks with 15.5; which ranked 3rd in the league as well. In order to be eligible for a new contract, Jones needs to report to training camp no later than August 6th.
Other Names Include: New York Jets Leonard Williams, Detroit Lions Mike Daniels, Los Angeles Rams Michael Brockers
Linebacker: Houston Texans Jadeveon Clowney
With the franchise tag becoming a looming issue in the NFL, Jadeveon Clowney has become the latest victim in this sense. With reports that Clowney will not report to the Houston Texans until the last possible moment, the two sides have remained in touch, despite the holdout. Unless a trade takes places within the coming weeks, Clowney will eventually join the team in preparation of the new season.
Other Names Include: Atlanta Falcons Vic Beasley, Los Angeles Rams Dante Fowler Jr, Pittsburgh Steelers Bud Dupree
Kyusung Gong
Defensive Back: Los Angeles Rams Aqib Talib
Coming off the IR, Aqib is marked as the most experienced headline player in the upcoming free agency pool. At the age of 33, Talib is scheduled to make $8M next season. Having played with four different franchises in the past, it's important to remember that Los Angeles has multiple contracts to address next offseason. Last season marked the second time Talib totaled only 1 interception. The time before that? The 2017 season with the Denver Broncos.
Other Names Include: Denver Broncos Chris Harris, Dallas Cowboys Byron Jones, Los Angeles Rams Marcus Peters
Featured Image: NY Post
The Top 5 NBA Players under 6'0"
Carmelo Anthony's Career Not Over Quite Yet

redpajama_set_name: RedPajamaCommonCrawl


text:
require "rails_helper"

describe "basic authentication for xml requests" do
  let(:form_list) { "/m/#{get_mission.compact_name}/formList" }

  before do
    @user = create(:user)
  end

  context "when not already logged in" do
    # `fooé:bar` base64 encoded with Latin-1 output (instead of UTF-8).
    let(:bad_headers) { {"HTTP_AUTHORIZATION" => "Basic Zm9v6TpiYXI="} }

    it "should be required" do
      get form_list
      assert_response :unauthorized
      expect(response.headers["WWW-Authenticate"]).to eq('Basic realm="Application"')
    end

    it "should gracefully handle invalid Latin-1 encoding" do
      get form_list, headers: bad_headers
      assert_response :unauthorized
      expect(response.headers["WWW-Authenticate"]).to eq('Basic realm="Application"')
    end
  end

  context "when already logged in via web" do
    before do
      login(@user)
    end

    it "should not be required" do
      get form_list
      assert_response :success
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<template name="home">

Hello World!

{{greeting}}

</template>


text:
using std::unordered_map;
using std::unordered_multimap;
#include <list>
#include <vector>

#include <fst/flags.h>
#include <fst/log.h>

#include <fst/vector-fst.h>

DECLARE_bool(fst_default_cache_gc);
DECLARE_int64(fst_default_cache_gc_limit);

namespace fst {

// Options for controlling caching behavior; higher level than CacheImplOptions.
struct CacheOptions {
  bool gc;          // Enables GC.
  size_t gc_limit;  // Number of bytes allowed before GC.

  explicit CacheOptions(bool gc = FLAGS_fst_default_cache_gc,
                        size_t gc_limit = FLAGS_fst_default_cache_gc_limit)
      : gc(gc), gc_limit(gc_limit) {}
};

// Options for controlling caching behavior, at a lower level than
// CacheOptions; templated on the cache store and allows passing the store.
template <class CacheStore>
struct CacheImplOptions {
  bool gc;            // Enables GC.
  size_t gc_limit;    // Number of bytes allowed before GC.
  CacheStore *store;  // Cache store.
  bool own_store;     // Should CacheImpl takes ownership of the store?

  explicit CacheImplOptions(bool gc = FLAGS_fst_default_cache_gc,
                            size_t gc_limit = FLAGS_fst_default_cache_gc_limit,
                            CacheStore *store = nullptr)
      : gc(gc), gc_limit(gc_limit), store(store), own_store(true) {}

  explicit CacheImplOptions(const CacheOptions &opts)
      : gc(opts.gc), gc_limit(opts.gc_limit), store(nullptr), own_store(true) {}
};

// Cache flags.
FST_CONSTEXPR const uint32 kCacheFinal = 0x0001;   // Final weight has been cached.
FST_CONSTEXPR const uint32 kCacheArcs = 0x0002;    // Arcs have been cached.
FST_CONSTEXPR const uint32 kCacheInit = 0x0004;    // Initialized by GC.
FST_CONSTEXPR const uint32 kCacheRecent = 0x0008;  // Visited since GC.
FST_CONSTEXPR const uint32 kCacheFlags =
    kCacheFinal | kCacheArcs | kCacheInit | kCacheRecent;

// Cache state, with arcs stored in a per-state std::vector.
template <class A, class M = PoolAllocator<A>>
class CacheState {
 public:
  using Arc = A;
  using Label = typename Arc::Label;
  using StateId = typename Arc::StateId;
  using Weight = typename Arc::Weight;

  using ArcAllocator = M;
  using StateAllocator =
      typename ArcAllocator::template rebind<CacheState<A, M>>::other;

  // Provides STL allocator for arcs.
  explicit CacheState(const ArcAllocator &alloc)
      : final_(Weight::Zero()),
        niepsilons_(0),
        noepsilons_(0),
        arcs_(alloc),
        flags_(0),
        ref_count_(0) {}

  CacheState(const CacheState<A> &state, const ArcAllocator &alloc)
      : final_(state.Final()),
        niepsilons_(state.NumInputEpsilons()),
        noepsilons_(state.NumOutputEpsilons()),
        arcs_(state.arcs_.begin(), state.arcs_.end(), alloc),
        flags_(state.Flags()),
        ref_count_(0) {}

  void Reset() {
    final_ = Weight::Zero();
    niepsilons_ = 0;
    noepsilons_ = 0;
    ref_count_ = 0;
    flags_ = 0;
    arcs_.clear();
  }

  Weight Final() const { return final_; }

  size_t NumInputEpsilons() const { return niepsilons_; }

  size_t NumOutputEpsilons() const { return noepsilons_; }

  size_t NumArcs() const { return arcs_.size(); }

  const Arc &GetArc(size_t n) const { return arcs_[n]; }

  // Used by the ArcIterator<Fst<Arc>> efficient implementation.
  const Arc *Arcs() const { return !arcs_.empty() ? &arcs_[0] : nullptr; }

  // Accesses flags; used by the caller.
  uint32 Flags() const { return flags_; }

  // Accesses ref count; used by the caller.
  int RefCount() const { return ref_count_; }

  void SetFinal(Weight weight) { final_ = std::move(weight); }

  void ReserveArcs(size_t n) { arcs_.reserve(n); }

  // Adds one arc at a time with all needed book-keeping; use PushArc and
  // SetArcs for a more efficient alternative.
  void AddArc(const Arc &arc) {
    arcs_.push_back(arc);
    if (arc.ilabel == 0) ++niepsilons_;
    if (arc.olabel == 0) ++noepsilons_;
  }

  // Adds one arc at a time with delayed book-keeping; finalize with SetArcs().
  void PushArc(const Arc &arc) { arcs_.push_back(arc); }

  // Finalizes arcs book-keeping; call only once.
  void SetArcs() {
    for (const auto &arc : arcs_) {
      if (arc.ilabel == 0) ++niepsilons_;
      if (arc.olabel == 0) ++noepsilons_;
    }
  }

  // Modifies nth arc.
  void SetArc(const Arc &arc, size_t n) {
    if (arcs_[n].ilabel == 0) --niepsilons_;
    if (arcs_[n].olabel == 0) --noepsilons_;
    if (arc.ilabel == 0) ++niepsilons_;
    if (arc.olabel == 0) ++noepsilons_;
    arcs_[n] = arc;
  }

  // Deletes all arcs.
  void DeleteArcs() {
    niepsilons_ = 0;
    noepsilons_ = 0;
    arcs_.clear();
  }

  void DeleteArcs(size_t n) {
    for (size_t i = 0; i < n; ++i) {
      if (arcs_.back().ilabel == 0) --niepsilons_;
      if (arcs_.back().olabel == 0) --noepsilons_;
      arcs_.pop_back();
    }
  }

  // Sets status flags; used by the caller.
  void SetFlags(uint32 flags, uint32 mask) const {
    flags_ &= ~mask;
    flags_ |= flags;
  }

  // Mutates reference counts; used by the caller.

  int IncrRefCount() const { return ++ref_count_; }

  int DecrRefCount() const { return --ref_count_; }

  // Used by the ArcIterator<Fst<Arc>> efficient implementation.
  int *MutableRefCount() const { return &ref_count_; }

  // Used for state class allocation.
  void *operator new(size_t size, StateAllocator *alloc) {
    return alloc->allocate(1);
  }

  // For state destruction and memory freeing.
  static void Destroy(CacheState<Arc> *state, StateAllocator *alloc) {
    if (state) {
      state->~CacheState<Arc>();
      alloc->deallocate(state, 1);
    }
  }

 private:
  Weight final_;                         // Final weight.
  size_t niepsilons_;                    // # of input epsilons.
  size_t noepsilons_;                    // # of output epsilons.
  std::vector<Arc, ArcAllocator> arcs_;  // Arcs representation.
  mutable uint32 flags_;
  mutable int ref_count_;  // If 0, available for GC.
};

// Cache store, allocating and storing states, providing a mapping from state
// IDs to cached states, and an iterator over these states. The state template
// argument must implement the CacheState interface. The state for a StateId s
// is constructed when requested by GetMutableState(s) if it is not yet stored.
// Initially, a state has a reference count of zero, but the user may increment
// or decrement this to control the time of destruction. In particular, a state
// is destroyed when:
//
// 1. This instance is destroyed, or
// 2. Clear() or Delete() is called, or
// 3. Possibly (implementation-dependently) when:
//    - Garbage collection is enabled (as defined by opts.gc),
//    - The cache store size exceeds the limits (as defined by opts.gc_limits),
//    - The state's reference count is zero, and
//    - The state is not the most recently requested state.
//
// template <class S>
// class CacheStore {
//  public:
//   using State = S;
//   using Arc = typename State::Arc;
//   using StateId = typename Arc::StateId;
//
//   // Required constructors/assignment operators.
//   explicit CacheStore(const CacheOptions &opts);
//
//   // Returns nullptr if state is not stored.
//   const State *GetState(StateId s);
//
//   // Creates state if state is not stored.
//   State *GetMutableState(StateId s);
//
//   // Similar to State::AddArc() but updates cache store book-keeping.
//   void AddArc(State *state, const Arc &arc);
//
//   // Similar to State::SetArcs() but updates cache store book-keeping; call
//   // only once.
//   void SetArcs(State *state);
//
//   // Similar to State::DeleteArcs() but updates cache store book-keeping.
//
//   void DeleteArcs(State *state);
//
//   void DeleteArcs(State *state, size_t n);
//
//   // Deletes all cached states.
//   void Clear();
//
//   // Iterates over cached states (in an arbitrary order); only needed if
//   // opts.gc is true.
//   bool Done() const;      // End of iteration.
//   StateId Value() const;  // Current state.
//   void Next();            // Advances to next state (when !Done).
//   void Reset();           // Returns to initial condition.
//   void Delete();          // Deletes current state and advances to next.
// };

// Container cache stores.

// This class uses a vector of pointers to states to store cached states.
template <class S>
class VectorCacheStore {
 public:
  using State = S;
  using Arc = typename State::Arc;
  using StateId = typename Arc::StateId;
  using StateList = std::list<StateId, PoolAllocator<StateId>>;

  // Required constructors/assignment operators.
  explicit VectorCacheStore(const CacheOptions &opts) : cache_gc_(opts.gc) {
    Clear();
    Reset();
  }

  VectorCacheStore(const VectorCacheStore<S> &store)
      : cache_gc_(store.cache_gc_) {
    CopyStates(store);
    Reset();
  }

  ~VectorCacheStore() { Clear(); }

  VectorCacheStore<State> &operator=(const VectorCacheStore<State> &store) {
    if (this != &store) {
      CopyStates(store);
      Reset();
    }
    return *this;
  }

  // Returns nullptr if state is not stored.
  const State *GetState(StateId s) const {
    return s < state_vec_.size() ? state_vec_[s] : nullptr;
  }

  // Creates state if state is not stored.
  State *GetMutableState(StateId s) {
    State *state = nullptr;
    if (s >= state_vec_.size()) {
      state_vec_.resize(s + 1, nullptr);
    } else {
      state = state_vec_[s];
    }
    if (!state) {
      state = new (&state_alloc_) State(arc_alloc_);
      state_vec_[s] = state;
      if (cache_gc_) state_list_.push_back(s);
    }
    return state;
  }

  // Similar to State::AddArc() but updates cache store book-keeping
  void AddArc(State *state, const Arc &arc) { state->AddArc(arc); }

  // Similar to State::SetArcs() but updates cache store book-keeping; call
  // only once.
  void SetArcs(State *state) { state->SetArcs(); }

  // Deletes all arcs.
  void DeleteArcs(State *state) { state->DeleteArcs(); }

  // Deletes some arcs.
  void DeleteArcs(State *state, size_t n) { state->DeleteArcs(n); }

  // Deletes all cached states.
  void Clear() {
    for (StateId s = 0; s < state_vec_.size(); ++s) {
      State::Destroy(state_vec_[s], &state_alloc_);
    }
    state_vec_.clear();
    state_list_.clear();
  }

  // Iterates over cached states (in an arbitrary order); only works if GC is
  // enabled (o.w. avoiding state_list_ overhead).
  bool Done() const { return iter_ == state_list_.end(); }

  StateId Value() const { return *iter_; }

  void Next() { ++iter_; }

  void Reset() { iter_ = state_list_.begin(); }

  // Deletes current state and advances to next.
  void Delete() {
    State::Destroy(state_vec_[*iter_], &state_alloc_);
    state_vec_[*iter_] = nullptr;
    state_list_.erase(iter_++);
  }

 private:
  void CopyStates(const VectorCacheStore<State> &store) {
    Clear();
    state_vec_.reserve(store.state_vec_.size());
    for (StateId s = 0; s < store.state_vec_.size(); ++s) {
      State *state = nullptr;
      const auto *store_state = store.state_vec_[s];
      if (store_state) {
        state = new (&state_alloc_) State(*store_state, arc_alloc_);
        if (cache_gc_) state_list_.push_back(s);
      }
      state_vec_.push_back(state);
    }
  }

  bool cache_gc_;                               // Supports iteration when true.
  std::vector<State *> state_vec_;              // Vector of states (or null).
  StateList state_list_;                        // List of states.
  typename StateList::iterator iter_;           // State list iterator.
  typename State::StateAllocator state_alloc_;  // For state allocation.
  typename State::ArcAllocator arc_alloc_;      // For arc allocation.
};

// This class uses a hash map from state IDs to pointers to cached states.
template <class S>
class HashCacheStore {
 public:
  using State = S;
  using Arc = typename State::Arc;
  using StateId = typename Arc::StateId;

  using StateMap =
      std::unordered_map<StateId, State *, std::hash<StateId>,
                         std::equal_to<StateId>,
                         PoolAllocator<std::pair<const StateId, State *>>>;

  // Required constructors/assignment operators.
  explicit HashCacheStore(const CacheOptions &opts) {
    Clear();
    Reset();
  }

  HashCacheStore(const HashCacheStore<S> &store) {
    CopyStates(store);
    Reset();
  }

  ~HashCacheStore() { Clear(); }

  HashCacheStore<State> &operator=(const HashCacheStore<State> &store) {
    if (this != &store) {
      CopyStates(store);
      Reset();
    }
    return *this;
  }

  // Returns nullptr if state is not stored.
  const State *GetState(StateId s) const {
    const auto it = state_map_.find(s);
    return it != state_map_.end() ? it->second : nullptr;
  }

  // Creates state if state is not stored.
  State *GetMutableState(StateId s) {
    auto *&state = state_map_[s];
    if (!state) state = new (&state_alloc_) State(arc_alloc_);
    return state;
  }

  // Similar to State::AddArc() but updates cache store book-keeping.
  void AddArc(State *state, const Arc &arc) { state->AddArc(arc); }

  // Similar to State::SetArcs() but updates internal cache size; call only
  // once.
  void SetArcs(State *state) { state->SetArcs(); }

  // Deletes all arcs.
  void DeleteArcs(State *state) { state->DeleteArcs(); }

  // Deletes some arcs.
  void DeleteArcs(State *state, size_t n) { state->DeleteArcs(n); }

  // Deletes all cached states.
  void Clear() {
    for (auto it = state_map_.begin(); it != state_map_.end(); ++it) {
      State::Destroy(it->second, &state_alloc_);
    }
    state_map_.clear();
  }

  // Iterates over cached states (in an arbitrary order).
  bool Done() const { return iter_ == state_map_.end(); }

  StateId Value() const { return iter_->first; }

  void Next() { ++iter_; }

  void Reset() { iter_ = state_map_.begin(); }

  // Deletes current state and advances to next.
  void Delete() {
    State::Destroy(iter_->second, &state_alloc_);
    state_map_.erase(iter_++);
  }

 private:
  void CopyStates(const HashCacheStore<State> &store) {
    Clear();
    for (auto it = store.state_map_.begin(); it != store.state_map_.end();
         ++it) {
      state_map_[it->first] =
          new (&state_alloc_) State(*it->second, arc_alloc_);
    }
  }

  StateMap state_map_;                          // Map from state ID to state.
  typename StateMap::iterator iter_;            // State map iterator.
  typename State::StateAllocator state_alloc_;  // For state allocation.
  typename State::ArcAllocator arc_alloc_;      // For arc allocation.
};

// Garbage-colllection cache stores.

// This class implements a simple garbage collection scheme when
// 'opts.gc_limit = 0'. In particular, the first cached state is reused for each
// new state so long as the reference count is zero on the to-be-reused state.
// Otherwise, the full underlying store is used. The caller can increment the
// reference count to inhibit the GC of in-use states (e.g., in an ArcIterator).
//
// The typical use case for this optimization is when a single pass over a
// cached
// FST is performed with only one-state expanded at a time.
template <class CacheStore>
class FirstCacheStore {
 public:
  using State = typename CacheStore::State;
  using Arc = typename State::Arc;
  using StateId = typename Arc::StateId;

  // Required constructors/assignment operators.
  explicit FirstCacheStore(const CacheOptions &opts)
      : store_(opts),
        cache_gc_(opts.gc_limit == 0),  // opts.gc ignored historically.
        cache_first_state_id_(kNoStateId),
        cache_first_state_(nullptr) {}

  FirstCacheStore(const FirstCacheStore<CacheStore> &store)
      : store_(store.store_),
        cache_gc_(store.cache_gc_),
        cache_first_state_id_(store.cache_first_state_id_),
        cache_first_state_(store.cache_first_state_id_ != kNoStateId
                               ? store_.GetMutableState(0)
                               : nullptr) {}

  FirstCacheStore<CacheStore> &operator=(
      const FirstCacheStore<CacheStore> &store) {
    if (this != &store) {
      store_ = store.store_;
      cache_gc_ = store.cache_gc_;
      cache_first_state_id_ = store.cache_first_state_id_;
      cache_first_state_ = store.cache_first_state_id_ != kNoStateId
                               ? store_.GetMutableState(0)
                               : nullptr;
    }
    return *this;
  }

  // Returns nullptr if state is not stored.
  const State *GetState(StateId s) const {
    // store_ state 0 may hold first cached state; the rest are shifted by 1.
    return s == cache_first_state_id_ ? cache_first_state_
                                      : store_.GetState(s + 1);
  }

  // Creates state if state is not stored.
  State *GetMutableState(StateId s) {
    // store_ state 0 used to hold first cached state; the rest are shifted by
    // 1.
    if (cache_first_state_id_ == s) {
      return cache_first_state_;  // Request for first cached state.
    }
    if (cache_gc_) {
      if (cache_first_state_id_ == kNoStateId) {
        cache_first_state_id_ = s;  // Sets first cached state.
        cache_first_state_ = store_.GetMutableState(0);
        cache_first_state_->SetFlags(kCacheInit, kCacheInit);
        cache_first_state_->ReserveArcs(2 * kAllocSize);
        return cache_first_state_;
      } else if (cache_first_state_->RefCount() == 0) {
        cache_first_state_id_ = s;  // Updates first cached state.
        cache_first_state_->Reset();
        cache_first_state_->SetFlags(kCacheInit, kCacheInit);
        return cache_first_state_;
      } else {  // Keeps first cached state.
        cache_first_state_->SetFlags(0, kCacheInit);  // Clears initialized bit.
        cache_gc_ = false;                            // Disables GC.
      }
    }
    auto *state = store_.GetMutableState(s + 1);
    return state;
  }

  // Similar to State::AddArc() but updates cache store book-keeping.
  void AddArc(State *state, const Arc &arc) { store_.AddArc(state, arc); }

  // Similar to State::SetArcs() but updates internal cache size; call only
  // once.
  void SetArcs(State *state) { store_.SetArcs(state); }

  // Deletes all arcs
  void DeleteArcs(State *state) { store_.DeleteArcs(state); }

  // Deletes some arcs
  void DeleteArcs(State *state, size_t n) { store_.DeleteArcs(state, n); }

  // Deletes all cached states
  void Clear() {
    store_.Clear();
    cache_first_state_id_ = kNoStateId;
    cache_first_state_ = nullptr;
  }

  // Iterates over cached states (in an arbitrary order). Only needed if GC is
  // enabled.
  bool Done() const { return store_.Done(); }

  StateId Value() const {
    // store_ state 0 may hold first cached state; rest shifted + 1.
    const auto s = store_.Value();
    return s ? s - 1 : cache_first_state_id_;
  }

  void Next() { store_.Next(); }

  void Reset() { store_.Reset(); }

  // Deletes current state and advances to next.
  void Delete() {
    if (Value() == cache_first_state_id_) {
      cache_first_state_id_ = kNoStateId;
      cache_first_state_ = nullptr;
    }
    store_.Delete();
  }

 private:
  CacheStore store_;              // Underlying store.
  bool cache_gc_;                 // GC enabled.
  StateId cache_first_state_id_;  // First cached state ID.
  State *cache_first_state_;      // First cached state.
};

// This class implements mark-sweep garbage collection on an underlying cache
// store. If GC is enabled, garbage collection of states is performed in a
// rough approximation of LRU order once when 'gc_limit' bytes is reached. The
// caller can increment the reference count to inhibit the GC of in-use state
// (e.g., in an ArcIterator). With GC enabled, the 'gc_limit' parameter allows
// the caller to trade-off time vs. space.
template <class CacheStore>
class GCCacheStore {
 public:
  using State = typename CacheStore::State;
  using Arc = typename State::Arc;
  using StateId = typename Arc::StateId;

  // Required constructors/assignment operators.
  explicit GCCacheStore(const CacheOptions &opts)
      : store_(opts),
        cache_gc_request_(opts.gc),
        cache_limit_(opts.gc_limit > kMinCacheLimit ? opts.gc_limit
                                                    : kMinCacheLimit),
        cache_gc_(false),
        cache_size_(0) {}

  // Returns 0 if state is not stored.
  const State *GetState(StateId s) const { return store_.GetState(s); }

  // Creates state if state is not stored
  State *GetMutableState(StateId s) {
    auto *state = store_.GetMutableState(s);
    if (cache_gc_request_ && !(state->Flags() & kCacheInit)) {
      state->SetFlags(kCacheInit, kCacheInit);
      cache_size_ += sizeof(State) + state->NumArcs() * sizeof(Arc);
      // GC is enabled once an uninited state (from underlying store) is seen.
      cache_gc_ = true;
      if (cache_size_ > cache_limit_) GC(state, false);
    }
    return state;
  }

  // Similar to State::AddArc() but updates cache store book-keeping.
  void AddArc(State *state, const Arc &arc) {
    store_.AddArc(state, arc);
    if (cache_gc_ && (state->Flags() & kCacheInit)) {
      cache_size_ += sizeof(Arc);
      if (cache_size_ > cache_limit_) GC(state, false);
    }
  }

  // Similar to State::SetArcs() but updates internal cache size; call only
  // once.
  void SetArcs(State *state) {
    store_.SetArcs(state);
    if (cache_gc_ && (state->Flags() & kCacheInit)) {
      cache_size_ += state->NumArcs() * sizeof(Arc);
      if (cache_size_ > cache_limit_) GC(state, false);
    }
  }

  // Deletes all arcs.
  void DeleteArcs(State *state) {
    if (cache_gc_ && (state->Flags() & kCacheInit)) {
      cache_size_ -= state->NumArcs() * sizeof(Arc);
    }
    store_.DeleteArcs(state);
  }

  // Deletes some arcs.
  void DeleteArcs(State *state, size_t n) {
    if (cache_gc_ && (state->Flags() & kCacheInit)) {
      cache_size_ -= n * sizeof(Arc);
    }
    store_.DeleteArcs(state, n);
  }

  // Deletes all cached states.
  void Clear() {
    store_.Clear();
    cache_size_ = 0;
  }

  // Iterates over cached states (in an arbitrary order); only needed if GC is
  // enabled.
  bool Done() const { return store_.Done(); }

  StateId Value() const { return store_.Value(); }

  void Next() { store_.Next(); }

  void Reset() { store_.Reset(); }

  // Deletes current state and advances to next.
  void Delete() {
    if (cache_gc_) {
      const auto *state = store_.GetState(Value());
      if (state->Flags() & kCacheInit) {
        cache_size_ -= sizeof(State) + state->NumArcs() * sizeof(Arc);
      }
    }
    store_.Delete();
  }

  // Removes from the cache store (not referenced-counted and not the current)
  // states that have not been accessed since the last GC until at most
  // cache_fraction * cache_limit_ bytes are cached. If that fails to free
  // enough, attempts to uncaching recently visited states as well. If still
  // unable to free enough memory, then widens cache_limit_.
  void GC(const State *current, bool free_recent, float cache_fraction = 0.666);

  // Returns the current cache size in bytes or 0 if GC is disabled.
  size_t CacheSize() const { return cache_size_; }

  // Returns the cache limit in bytes.
  size_t CacheLimit() const { return cache_limit_; }

 private:
  static FST_CONSTEXPR const size_t kMinCacheLimit = 8096;  // Minimum cache limit.

  CacheStore store_;       // Underlying store.
  bool cache_gc_request_;  // GC requested but possibly not yet enabled.
  size_t cache_limit_;     // Number of bytes allowed before GC.
  bool cache_gc_;          // GC enabled
  size_t cache_size_;      // Number of bytes cached.
};

template <class CacheStore>
void GCCacheStore<CacheStore>::GC(const State *current, bool free_recent,
                                  float cache_fraction) {
  if (!cache_gc_) return;
  VLOG(2) << "GCCacheStore: Enter GC: object = "
          << "(" << this << "), free recently cached = " << free_recent
          << ", cache size = " << cache_size_
          << ", cache frac = " << cache_fraction
          << ", cache limit = " << cache_limit_ << "\n";
  size_t cache_target = cache_fraction * cache_limit_;
  store_.Reset();
  while (!store_.Done()) {
    auto *state = store_.GetMutableState(store_.Value());
    if (cache_size_ > cache_target && state->RefCount() == 0 &&
        (free_recent || !(state->Flags() & kCacheRecent)) && state != current) {
      if (state->Flags() & kCacheInit) {
        size_t size = sizeof(State) + state->NumArcs() * sizeof(Arc);
        if (size < cache_size_) {
          cache_size_ -= size;
        }
      }
      store_.Delete();
    } else {
      state->SetFlags(0, kCacheRecent);
      store_.Next();
    }
  }
  if (!free_recent && cache_size_ > cache_target) {  // Recurses on recent.
    GC(current, true, cache_fraction);
  } else if (cache_target > 0) {  // Widens cache limit.
    while (cache_size_ > cache_target) {
      cache_limit_ *= 2;
      cache_target *= 2;
    }
  } else if (cache_size_ > 0) {
    FSTERROR() << "GCCacheStore:GC: Unable to free all cached states";
  }
  VLOG(2) << "GCCacheStore: Exit GC: object = "
          << "(" << this << "), free recently cached = " << free_recent
          << ", cache size = " << cache_size_
          << ", cache frac = " << cache_fraction
          << ", cache limit = " << cache_limit_ << "\n";
}

template <class CacheStore>
FST_CONSTEXPR const size_t GCCacheStore<CacheStore>::kMinCacheLimit;

// This class is the default cache state and store used by CacheBaseImpl.
// It uses VectorCacheStore for storage decorated by FirstCacheStore
// and GCCacheStore to do (optional) garbage collection.
template <class Arc>
class DefaultCacheStore
    : public GCCacheStore<FirstCacheStore<VectorCacheStore<CacheState<Arc>>>> {
 public:
  explicit DefaultCacheStore(const CacheOptions &opts)
      : GCCacheStore<FirstCacheStore<VectorCacheStore<CacheState<Arc>>>>(opts) {
  }
};

namespace internal {

// This class is used to cache FST elements stored in states of type State
// (see CacheState) with the flags used to indicate what has been cached. Use
// HasStart(), HasFinal(), and HasArcs() to determine if cached and SetStart(),
// SetFinal(), AddArc(), (or PushArc() and SetArcs()) to cache. Note that you
// must set the final weight even if the state is non-final to mark it as
// cached. The state storage method and any garbage collection policy are
// determined by the cache store. If the store is passed in with the options,
// CacheBaseImpl takes ownership.
template <class State,
          class CacheStore = DefaultCacheStore<typename State::Arc>>
class CacheBaseImpl : public FstImpl<typename State::Arc> {
 public:
  using Arc = typename State::Arc;
  using StateId = typename Arc::StateId;
  using Weight = typename Arc::Weight;

  using Store = CacheStore;

  using FstImpl<Arc>::Type;
  using FstImpl<Arc>::Properties;

  explicit CacheBaseImpl(const CacheOptions &opts = CacheOptions())
      : has_start_(false),
        cache_start_(kNoStateId),
        nknown_states_(0),
        min_unexpanded_state_id_(0),
        max_expanded_state_id_(-1),
        cache_gc_(opts.gc),
        cache_limit_(opts.gc_limit),
        cache_store_(new CacheStore(opts)),
        new_cache_store_(true),
        own_cache_store_(true) {}

  explicit CacheBaseImpl(const CacheImplOptions<CacheStore> &opts)
      : has_start_(false),
        cache_start_(kNoStateId),
        nknown_states_(0),
        min_unexpanded_state_id_(0),
        max_expanded_state_id_(-1),
        cache_gc_(opts.gc),
        cache_limit_(opts.gc_limit),
        cache_store_(opts.store ? opts.store : new CacheStore(CacheOptions(
                                                   opts.gc, opts.gc_limit))),
        new_cache_store_(!opts.store),
        own_cache_store_(opts.store ? opts.own_store : true) {}

  // Preserve gc parameters. If preserve_cache is true, also preserves
  // cache data.
  CacheBaseImpl(const CacheBaseImpl<State, CacheStore> &impl,
                bool preserve_cache = false)
      : FstImpl<Arc>(),
        has_start_(false),
        cache_start_(kNoStateId),
        nknown_states_(0),
        min_unexpanded_state_id_(0),
        max_expanded_state_id_(-1),
        cache_gc_(impl.cache_gc_),
        cache_limit_(impl.cache_limit_),
        cache_store_(new CacheStore(CacheOptions(cache_gc_, cache_limit_))),
        new_cache_store_(impl.new_cache_store_ || !preserve_cache),
        own_cache_store_(true) {
    if (preserve_cache) {
      *cache_store_ = *impl.cache_store_;
      has_start_ = impl.has_start_;
      cache_start_ = impl.cache_start_;
      nknown_states_ = impl.nknown_states_;
      expanded_states_ = impl.expanded_states_;
      min_unexpanded_state_id_ = impl.min_unexpanded_state_id_;
      max_expanded_state_id_ = impl.max_expanded_state_id_;
    }
  }

  ~CacheBaseImpl() override { if (own_cache_store_) delete cache_store_; }

  void SetStart(StateId s) {
    cache_start_ = s;
    has_start_ = true;
    if (s >= nknown_states_) nknown_states_ = s + 1;
  }

  void SetFinal(StateId s, Weight weight) {
    auto *state = cache_store_->GetMutableState(s);
    state->SetFinal(std::move(weight));
    static FST_CONSTEXPR const auto flags = kCacheFinal | kCacheRecent;
    state->SetFlags(flags, flags);
  }

// Disabled to ensure PushArc not AddArc is used in existing code
// TODO(sorenj): re-enable for backing store
#if 0
  // AddArc adds a single arc to a state and does incremental cache
  // book-keeping. For efficiency, prefer PushArc and SetArcs below
  // when possible.
  void AddArc(StateId s, const Arc &arc) {
    auto *state = cache_store_->GetMutableState(s);
    cache_store_->AddArc(state, arc);
    if (arc.nextstate >= nknown_states_)
      nknown_states_ = arc.nextstate + 1;
    SetExpandedState(s);
    static FST_CONSTEXPR const auto flags = kCacheArcs | kCacheRecent;
    state->SetFlags(flags, flags);
  }
#endif

  // Adds a single arc to a state but delays cache book-keeping. SetArcs must
  // be called when all PushArc calls at a state are complete. Do not mix with
  // calls to AddArc.
  void PushArc(StateId s, const Arc &arc) {
    auto *state = cache_store_->GetMutableState(s);
    state->PushArc(arc);
  }

  // Marks arcs of a state as cached and does cache book-keeping after all
  // calls to PushArc have been completed. Do not mix with calls to AddArc.
  void SetArcs(StateId s) {
    auto *state = cache_store_->GetMutableState(s);
    cache_store_->SetArcs(state);
    const auto narcs = state->NumArcs();
    for (size_t a = 0; a < narcs; ++a) {
      const auto &arc = state->GetArc(a);
      if (arc.nextstate >= nknown_states_) nknown_states_ = arc.nextstate + 1;
    }
    SetExpandedState(s);
    static FST_CONSTEXPR const auto flags = kCacheArcs | kCacheRecent;
    state->SetFlags(flags, flags);
  }

  void ReserveArcs(StateId s, size_t n) {
    auto *state = cache_store_->GetMutableState(s);
    state->ReserveArcs(n);
  }

  void DeleteArcs(StateId s) {
    auto *state = cache_store_->GetMutableState(s);
    cache_store_->DeleteArcs(state);
  }

  void DeleteArcs(StateId s, size_t n) {
    auto *state = cache_store_->GetMutableState(s);
    cache_store_->DeleteArcs(state, n);
  }

  void Clear() {
    nknown_states_ = 0;
    min_unexpanded_state_id_ = 0;
    max_expanded_state_id_ = -1;
    has_start_ = false;
    cache_start_ = kNoStateId;
    cache_store_->Clear();
  }

  // Is the start state cached?
  bool HasStart() const {
    if (!has_start_ && Properties(kError)) has_start_ = true;
    return has_start_;
  }

  // Is the final weight of the state cached?
  bool HasFinal(StateId s) const {
    const auto *state = cache_store_->GetState(s);
    if (state && state->Flags() & kCacheFinal) {
      state->SetFlags(kCacheRecent, kCacheRecent);
      return true;
    } else {
      return false;
    }
  }

  // Are arcs of the state cached?
  bool HasArcs(StateId s) const {
    const auto *state = cache_store_->GetState(s);
    if (state && state->Flags() & kCacheArcs) {
      state->SetFlags(kCacheRecent, kCacheRecent);
      return true;
    } else {
      return false;
    }
  }

  StateId Start() const { return cache_start_; }

  Weight Final(StateId s) const {
    const auto *state = cache_store_->GetState(s);
    return state->Final();
  }

  size_t NumArcs(StateId s) const {
    const auto *state = cache_store_->GetState(s);
    return state->NumArcs();
  }

  size_t NumInputEpsilons(StateId s) const {
    const auto *state = cache_store_->GetState(s);
    return state->NumInputEpsilons();
  }

  size_t NumOutputEpsilons(StateId s) const {
    const auto *state = cache_store_->GetState(s);
    return state->NumOutputEpsilons();
  }

  // Provides information needed for generic arc iterator.
  void InitArcIterator(StateId s, ArcIteratorData<Arc> *data) const {
    const auto *state = cache_store_->GetState(s);
    data->base = nullptr;
    data->narcs = state->NumArcs();
    data->arcs = state->Arcs();
    data->ref_count = state->MutableRefCount();
    state->IncrRefCount();
  }

  // Number of known states.
  StateId NumKnownStates() const { return nknown_states_; }

  // Updates number of known states, taking into account the passed state ID.
  void UpdateNumKnownStates(StateId s) {
    if (s >= nknown_states_) nknown_states_ = s + 1;
  }

  // Finds the mininum never-expanded state ID.
  StateId MinUnexpandedState() const {
    while (min_unexpanded_state_id_ <= max_expanded_state_id_ &&
           ExpandedState(min_unexpanded_state_id_)) {
      ++min_unexpanded_state_id_;
    }
    return min_unexpanded_state_id_;
  }

  // Returns maximum ever-expanded state ID.
  StateId MaxExpandedState() const { return max_expanded_state_id_; }

  void SetExpandedState(StateId s) {
    if (s > max_expanded_state_id_) max_expanded_state_id_ = s;
    if (s < min_unexpanded_state_id_) return;
    if (s == min_unexpanded_state_id_) ++min_unexpanded_state_id_;
    if (cache_gc_ || cache_limit_ == 0) {
      if (expanded_states_.size() <= s) expanded_states_.resize(s + 1, false);
      expanded_states_[s] = true;
    }
  }

  bool ExpandedState(StateId s) const {
    if (cache_gc_ || cache_limit_ == 0) {
      return expanded_states_[s];
    } else if (new_cache_store_) {
      return cache_store_->GetState(s) != nullptr;
    } else {
      // If the cache was not created by this class, then the cached state needs
      // to be inspected to update nknown_states_.
      return false;
    }
  }

  const CacheStore *GetCacheStore() const { return cache_store_; }

  CacheStore *GetCacheStore() { return cache_store_; }

  // Caching on/off switch, limit and size accessors.

  bool GetCacheGc() const { return cache_gc_; }

  size_t GetCacheLimit() const { return cache_limit_; }

 private:
  mutable bool has_start_;                   // Is the start state cached?
  StateId cache_start_;                      // ID of start state.
  StateId nknown_states_;                    // Number of known states.
  std::vector<bool> expanded_states_;        // States that have been expanded.
  mutable StateId min_unexpanded_state_id_;  // Minimum never-expanded state ID
  mutable StateId max_expanded_state_id_;    // Maximum ever-expanded state ID
  bool cache_gc_;                            // GC enabled.
  size_t cache_limit_;       // Number of bytes allowed before GC.
  CacheStore *cache_store_;  // The store of cached states.
  bool new_cache_store_;     // Was the store was created by class?
  bool own_cache_store_;     // Is the store owned by class?

  CacheBaseImpl &operator=(const CacheBaseImpl &impl) = delete;
};

// A CacheBaseImpl with the default cache state type.
template <class Arc>
class CacheImpl : public CacheBaseImpl<CacheState<Arc>> {
 public:
  using State = CacheState<Arc>;

  CacheImpl() {}

  explicit CacheImpl(const CacheOptions &opts)
      : CacheBaseImpl<CacheState<Arc>>(opts) {}

  CacheImpl(const CacheImpl<Arc> &impl, bool preserve_cache = false)
      : CacheBaseImpl<State>(impl, preserve_cache) {}

 private:
  CacheImpl &operator=(const CacheImpl &impl) = delete;
};

}  // namespace internal

// Use this to make a state iterator for a CacheBaseImpl-derived FST, which must
// have Arc and Store types defined. Note this iterator only returns those
// states reachable from the initial state, so consider implementing a
// class-specific one.
//
// This class may be derived from.
template <class FST>
class CacheStateIterator : public StateIteratorBase<typename FST::Arc> {
 public:
  using Arc = typename FST::Arc;
  using StateId = typename Arc::StateId;
  using Weight = typename Arc::Weight;

  using Store = typename FST::Store;
  using State = typename Store::State;
  using Impl = internal::CacheBaseImpl<State, Store>;

  CacheStateIterator(const FST &fst, Impl *impl)
      : fst_(fst), impl_(impl), s_(0) {
    fst_.Start();  // Forces start state.
  }

  bool Done() const final {
    if (s_ < impl_->NumKnownStates()) return false;
    for (StateId u = impl_->MinUnexpandedState(); u < impl_->NumKnownStates();
         u = impl_->MinUnexpandedState()) {
      // Forces state expansion.
      ArcIterator<FST> aiter(fst_, u);
      aiter.SetFlags(kArcValueFlags, kArcValueFlags | kArcNoCache);
      for (; !aiter.Done(); aiter.Next()) {
        impl_->UpdateNumKnownStates(aiter.Value().nextstate);
      }
      impl_->SetExpandedState(u);
      if (s_ < impl_->NumKnownStates()) return false;
    }
    return true;
  }

  StateId Value() const final { return s_; }

  void Next() final { ++s_; }

  void Reset() final { s_ = 0; }

 private:
  const FST &fst_;
  Impl *impl_;
  StateId s_;
};

// Used to make an arc iterator for a CacheBaseImpl-derived FST, which must
// have Arc and State types defined.
template <class FST>
class CacheArcIterator {
 public:
  using Arc = typename FST::Arc;
  using StateId = typename Arc::StateId;
  using Weight = typename Arc::Weight;

  using Store = typename FST::Store;
  using State = typename Store::State;
  using Impl = internal::CacheBaseImpl<State, Store>;

  CacheArcIterator(Impl *impl, StateId s) : i_(0) {
    state_ = impl->GetCacheStore()->GetMutableState(s);
    state_->IncrRefCount();
  }

  ~CacheArcIterator() { state_->DecrRefCount(); }

  bool Done() const { return i_ >= state_->NumArcs(); }

  const Arc &Value() const { return state_->GetArc(i_); }

  void Next() { ++i_; }

  size_t Position() const { return i_; }

  void Reset() { i_ = 0; }

  void Seek(size_t a) { i_ = a; }

  FST_CONSTEXPR uint32 Flags() const { return kArcValueFlags; }

  void SetFlags(uint32 flags, uint32 mask) {}

 private:
  const State *state_;
  size_t i_;

  CacheArcIterator(const CacheArcIterator &) = delete;
  CacheArcIterator &operator=(const CacheArcIterator &) = delete;
};

// Use this to make a mutable arc iterator for a CacheBaseImpl-derived FST,
// which must have types Arc and Store defined.
template <class FST>
class CacheMutableArcIterator
    : public MutableArcIteratorBase<typename FST::Arc> {
 public:
  using Arc = typename FST::Arc;
  using StateId = typename Arc::StateId;
  using Weight = typename Arc::Weight;

  using Store = typename FST::Store;
  using State = typename Store::State;
  using Impl = internal::CacheBaseImpl<State, Store>;

  // User must call MutateCheck() in the constructor.
  CacheMutableArcIterator(Impl *impl, StateId s) : i_(0), s_(s), impl_(impl) {
    state_ = impl_->GetCacheStore()->GetMutableState(s_);
    state_->IncrRefCount();
  }

  ~CacheMutableArcIterator() override { state_->DecrRefCount(); }

  bool Done() const final { return i_ >= state_->NumArcs(); }

  const Arc &Value() const final { return state_->GetArc(i_); }

  void Next() final { ++i_; }

  size_t Position() const final { return i_; }

  void Reset() final { i_ = 0; }

  void Seek(size_t a) final { i_ = a; }

  void SetValue(const Arc &arc) final { state_->SetArc(arc, i_); }

  uint32 Flags() const final { return kArcValueFlags; }

  void SetFlags(uint32, uint32) final {}

 private:
  size_t i_;
  StateId s_;
  Impl *impl_;
  State *state_;

  CacheMutableArcIterator(const CacheMutableArcIterator &) = delete;
  CacheMutableArcIterator &operator=(const CacheMutableArcIterator &) = delete;
};

// Wrap existing CacheStore implementation to use with ExpanderFst.
template <class CacheStore>
class ExpanderCacheStore {
 public:
  using State = typename CacheStore::State;
  using Arc = typename CacheStore::Arc;
  using StateId = typename Arc::StateId;
  using Weight = typename Arc::Weight;

  explicit ExpanderCacheStore(const CacheOptions &opts = CacheOptions())
      : store_(opts) {}

  template <class Expander>
  State *FindOrExpand(Expander &expander, StateId s) {  // NOLINT
    auto *state = store_.GetMutableState(s);
    if (state->Flags()) {
      state->SetFlags(kCacheRecent, kCacheRecent);
    } else {
      StateBuilder builder(state);
      expander.Expand(s, &builder);
      state->SetFlags(kCacheFlags, kCacheFlags);
      store_.SetArcs(state);
    }
    return state;
  }

 private:
  CacheStore store_;

  struct StateBuilder {
    State *state;

    explicit StateBuilder(State *state_) : state(state_) {}

    void AddArc(const Arc &arc) { state->PushArc(arc); }

    void SetFinal(Weight weight) { state->SetFinal(std::move(weight)); }
  };
};

}  // namespace fst

#endif  // FST_CACHE_H_


text:
Q: How to toggle an individual pin out on an 8 bit shift register (Python - Raspberry Pi) I'm fairly new to the Raspberry Pi and trying to wrap my head around the code I need to use the 8 bit shift register to control a set of relays I have managed to hook up.
The tutorial was one of the many 8-bit shift tutorials for blinking LED.
I can't wrap my head around how to alter the code to get the system to treat either a set of individual variables (relay1, relay2, etc) or relay[0,0,0,0,0,0,0,0] as a set of toggle type switches.
So that when a relay is triggered-only that relay is altered (on to off and vice versa) and the other ones don't cycle.
while True:                       # execute loop forever
    for y in range(8):            # loop for counting up 8 times
        IO.output(data,1)         # pull up the data pin for every bit.
        time.sleep(clock_cycle)   # wait for 100ms
        IO.output(clock, 1)       # pull CLOCK pin high
        time.sleep(clock_cycle)
        IO.output(clock,0)        # pull CLOCK pin down, to send a rising edge
        IO.output(data,0)         # clear the DATA pin
        IO.output(shift,1)        # pull the SHIFT pin high to put the 8 bit data out parallel
        time.sleep(clock_cycle)
        IO.output(shift,0)        # pull down the SHIFT pin

Can someone show me what I'm pretty sure is a simple piece of code for setting individual outputs to on or off?

redpajama_set_name: RedPajamaStackExchange


Hey all you Romantics! Good to be on board for Star Citizen. I have really enjoyed the Twitch stream and Hull Truth videos. Thanks for sharing your real life story Wes and for starting this awesome community.
I have been involved with MMO's since the EQ days (ewww, I know), but have been limited as to the games I can play due to school, work, and married life. I am however looking forward to Star Citizen and having some coordinated space battles! Cant wait for some form of coordinated multi-player action (hopefully soon).
I owned an Aurora and upgraded it to a 300i, and hope to later get the Freelancer. I applied to the corp on the SC website and hope to become a member!
Welcome Chez! It's great to have you man. I played quite a bit of EQ1 myself. Those corpse runs! CAN SOMEONE DRAG MY CORPSE PLS!


Earlier than Herbalife, I was not very healthy nor was I very happy. I had CANCER – stage II Carcinoma of the left breast, identified in 1984. I had an excision and axillary clearance. Twenty one (21 out of thirty three (33)axillary lymph nodes eliminated, contained Metastatic disease. I used to be given Adjuvant Chemotherapy as well as native Irradiation to the area. A bone scan revealed some increased uptake in the left tibia and within the head of the femur, but later X-rays of those areas were unremarkable. In 1985 in the lung, a left higher lobe occlusion was famous. A effective needle aspiration was performed and no malignant disease was found. Nurse practitioners (NP) are advanced apply registered nurses that handle acute and persistent medical conditions, each bodily and psychological, via historical past and bodily exam and the ordering of diagnostic assessments and medical remedies. NPs are certified to diagnose medical problems, order remedies, perform advanced procedures, prescribe medicines, and make referrals for a variety of acute and persistent medical situations inside their scope of practice. Their schooling features a Bachelor of Science in Nursing (BSN) or different undergraduate diploma, and requires a license as a registered nurse (RN) and experience as an RN in a health care setting. They have to graduate from an accredited graduate (MSN) or doctoral (DNP) program and obtain a board certification.
Former Bush administration Solicitor Basic Paul Clement, arguing in assist of the Vinson resolution, agreed that whereas it could be permissible for Congress to require insurance coverage or different payment by these being handled in an emergency room, because they would already be in the stream of commerce," it was a really completely different matter to require them to pay prospectively for future care.
Advances in medical sciences, technology, and society at massive, have significantly improved life expectancy and health of populations throughout the globe in current a long time. These advancements have in flip led to demands and aims which pose new challenges to societies. In high revenue countries, the affordability of health service systems is underneath pressure. On the similar time, low and center revenue countries seek to build up their health service techniques with restricted resources – typically hindered by humanitarian crises.
A coconut palm/tree can yield 150 – 200 coconuts a season and every coconut holds 200ml – 1000ml of water – this relies on upon cultivar measurement and sort. Coconut palms develop plentifully along the shores of tropical situations. We actually don't fully understand the non secular realm however we do realize it does positively impact our bodily and emotional health and effectively-being. So, search the truth, build a relationship with God, and revel in improved health and properly-being.
It's essential to remain healthy and shield your loved ones, so you owe it to your self to know time period life insurance coverage vs. entire life insurance The knowledge may make a giant difference in your loved ones's health and happiness if something ought to occur to you. There are methods to regulate this accelerated growing older course of however one should remember to follow each suggestion on a daily basis to attain the specified results.


The Algarve sea is the result of Atlantic ocean meets the Mediterranean sea, the result being a cooler water to the west towards the Atlantic and warmer temperatures going east towards the Mediterranean sea.
The sea is another important part of the Algarve lifestyle, one that's also closely bound to nature. You can see locals wading into the Atlantic at low tide to find cockles and barnacles, and all along the coast, fishermen, who learnt the trade from their fathers, go out for squid and octopus, for sardines and tuna. Against this backdrop of real life is the layer for holidaymakers.
There is an abundance of several kinds of fish, making it a staple diet for a lot of the population.
If you take one of the many cruises on offer across the Algarve you can visit the most beautiful caves that line up the west coast towards Sagres or you can simply sail out for an intense and unique experience and see dolphins, turtles or seabirds in the wild.


text:
from datetime import datetime, timedelta
import json
from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.datastructures import SortedDict
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from corehq.apps.domain.models import Domain
from dimagi.utils.couch.cache import cache_core
from dimagi.utils.logging import notify_exception
from dimagi.utils.web import json_handler

import corehq.apps.style.utils as style_utils

register = template.Library()

@register.filter
def JSON(obj):
    return mark_safe(json.dumps(obj, default=json_handler))

@register.filter
def to_javascript_string(obj):
    # seriously: http://stackoverflow.com/a/1068548/8207
    return mark_safe(JSON(obj).replace('</script>', '<" + "/script>'))

@register.filter
def BOOL(obj):
    try:
        obj = obj.to_json()
    except AttributeError:
        pass

    return 'true' if obj else 'false'

@register.filter
def dict_lookup(dict, key):
    '''Get an item from a dictionary.'''
    return dict.get(key)

@register.filter
def array_lookup(array, index):
    '''Get an item from an array.'''
    if index < len(array):
        return array[index]

@register.simple_tag
def dict_as_query_string(dict, prefix=""):
    '''Convert a dictionary to a query string, minus the initial ?'''
    return "&".join(["%s%s=%s" % (prefix, key, value) for key, value in dict.items()])

@register.filter
def add_days(date, days=1):
    '''Return a date with some days added'''
    span = timedelta(days=days)
    try:
        return date + span
    except:
        return datetime.strptime(date,'%m/%d/%Y').date() + span

@register.filter
def concat(str1, str2):
    """Concatenate two strings"""
    return "%s%s" % (str1, str2)

try:
    from resource_versions import resource_versions
except (ImportError, SyntaxError):
    resource_versions = {}

@register.simple_tag
def static(url):
    resource_url = url
    version = resource_versions.get(resource_url)
    url = settings.STATIC_URL + url
    is_less = url.endswith('.less')
    if version and not is_less:
        url += "?version=%s" % version
    return url

@register.simple_tag
def cachebuster(url):
    return resource_versions.get(url, "")

@register.simple_tag
def new_static(url, **kwargs):
    """Caching must explicitly be defined on tags with any of the extensions
    that could be compressed by django compressor. The static tag above will
    eventually turn into this tag.
    :param url:
    :param kwargs:
    :return:
    """
    can_be_compressed = url.endswith(('.less', '.css', '.js'))
    use_cache = kwargs.pop('cache', False)
    use_versions = not can_be_compressed or use_cache

    resource_url = url
    url = settings.STATIC_URL + url
    if use_versions:
        version = resource_versions.get(resource_url)
        if version:
            url += "?version=%s" % version

    return url

@register.simple_tag
def domains_for_user(request, selected_domain=None):
    """
    Generate pulldown menu for domains.
    Cache the entire string alongside the couch_user's doc_id that can get invalidated when
    the user doc updates via save.
    """
    domain_list = []
    if selected_domain != 'public':
        cached_domains = cache_core.get_cached_prop(request.couch_user.get_id, 'domain_list')
        if cached_domains:
            domain_list = [Domain.wrap(x) for x in cached_domains]
        else:
            try:
                domain_list = Domain.active_for_user(request.couch_user)
                cache_core.cache_doc_prop(request.couch_user.get_id, 'domain_list', [x.to_json() for x in domain_list])
            except Exception:
                if settings.DEBUG:
                    raise
                else:
                    domain_list = Domain.active_for_user(request.user)
                    notify_exception(request)
    domain_list = [dict(
        url=reverse('domain_homepage', args=[d.name]),
        name=d.long_display_name()
    ) for d in domain_list]
    context = {
        'is_public': selected_domain == 'public',
        'domain_list': domain_list,
        'current_domain': selected_domain,
    }
    template = {
        style_utils.BOOTSTRAP_2: 'hqwebapp/partials/domain_list_dropdown.html',
        style_utils.BOOTSTRAP_3: 'style/includes/domain_list_dropdown.html',
    }[style_utils.bootstrap_version(request)]
    return mark_safe(render_to_string(template, context))

@register.simple_tag
def list_my_orgs(request):
    org_list = request.couch_user.get_organizations()
    lst = list()
    lst.append('
')
    for org in org_list:
        default_url = reverse("orgs_landing", args=[org.name])
        lst.append('
%s
' % (default_url, org.title))
    lst.append('
')

    return "".join(lst)

@register.simple_tag
def commcare_user():
    return _(settings.COMMCARE_USER_TERM)

@register.simple_tag
def hq_web_user():
    return _(settings.WEB_USER_TERM)

@register.filter
def mod(value, arg):
    return value % arg

# This is taken from https://code.djangoproject.com/ticket/15583
@register.filter(name='sort')
def listsort(value):
    if isinstance(value, dict):
        new_dict = SortedDict()
        key_list = value.keys()
        key_list.sort()
        for key in key_list:
            new_dict[key] = value[key]
        return new_dict
    elif isinstance(value, list):
        new_list = list(value)
        new_list.sort()
        return new_list
    else:
        return value
listsort.is_safe = True

@register.filter(name='getattr')
def get_attribute(obj, arg):
    """ Get attribute from obj

    Usage: {{ couch_user|getattr:"full_name" }}
    """
    return getattr(obj, arg, None)

@register.filter
def pretty_doc_info(doc_info):
    return render_to_string('hqwebapp/pretty_doc_info.html', {
        'doc_info': doc_info,
    })

@register.filter
def toggle_enabled(request, toggle_name):
    import corehq.toggles
    toggle = getattr(corehq.toggles, toggle_name)
    return (
        (hasattr(request, 'user') and toggle.enabled(request.user.username)) or
        (hasattr(request, 'domain') and toggle.enabled(request.domain))
    )


text:
Video: Frosty the Inappropriate Snowman
Ed MorrisseyPosted at 1:36 pm on December 4, 2009
From the network that brought you the Janet Jackson-Justin Timberlake "wardrobe malfunction" in the middle of a B&D Super Bowl dance number comes a web promo for the children's holiday classic Frosty the Snowman. Mediate's Rachel Sklar can barely contain her disgust at the NSFW promo, which uses the Frosty animation to discuss porn, women's breasts, and sadomasochism. Maybe CBS should have taken its own advice and left this classic untouched:
Yes that's right: CBS has taken that favorite holiday classic and defiled it with porn, boobs and a pretty clear reference to crabs.
As a promo for Frosty, airing on Dec. 18th, CBS has recut scenes from the animated favorite into two videos, one with audio from the crass, womanizing Barney from "How I Met Your Mother" and the other from the crass, womanizing Charlie from "Two and a Half Men." As a result, the videos — while awesomely featuring Mediaite fan fave Neil Patrick Harris (as well as the voice of Charlie Sheen) — trade off a pretty funny result for grownups with a pretty sacriligious result for kids. Who, by the way, presumably know how to Google, and thus an innocent search for "Frosty The Snowman CBS" would lead to multiple page one results for Frosty the Promiscuous Potty-Mouth.
If this was a mash-up by a private citizen that would be one thing, but this is an official promo by the network, linking the holiday classic forever with notions of sex in front of a classroom of people and picking up single mothers in the parking lot of Chuck E. Cheese. Yes, I think it's funny; no, I don't think it's a good idea. Really, CBS?
Yes, unfortunately, really. When I was a teenage Dr. Demento fan, there was a hilarious spoof of the "Frosty" song with drug references, but CBS knew better than to use it as a promo for a children's holiday special. Which network exec thought this was a bright idea? Looks like the Tiffany Network needs a lump of coal in its stocking this season.


Do you need relief for your sore hard-working feet? As everyone knows, we rely on our feet an awful lot. They get us to where we need to go, they endure a lot of pressure and they truly deserve a good pampering.
This is where Kendall Gelthotics come in handy. GelThotics are designed to be placed under the removeable innersole. Made from soft, "skin friendly" pure silicone, they will never breakdown, will not retain moisture or odors and will make all of your shoes more comfortable.
I have a favorite pair of dress boots, for example. They are so cute, but I would much rather just look at them then wear them. So, I took a chance and inserted a pair of Kendall Gelthotics into my boots. I then really put some mileage on those boots when I went Christmas shopping for a day at the mall. I was surprised and elated that not only were my feet comfortable, but they did not feel sweaty or yucky. I felt like I could actually run a marathon in my boots, which I might add, had heels. Needless to say, I am completely sold on Kendall Gel Thotics! They come in all sizes, so you will not have any problems getting them to fit.
Tags: gel shoe inserts, foot pain relief.


text:
Pokémon Scarlet and Violet will have DLCs according to leaker
Mega Evolution could be coming to the game as part of the DLC.
by Darryl Lara published November 29, 2022 November 29, 2022
The latest entries in the Pokémon series of games, Scarlet and Violet, have been very successful in terms of their sales numbers. Despite the issues, the latest installments of the famed video game franchise sold over 10 million copies in just three days. They have also been the most pre-ordered games in the series to date.
Mega Evolutions could be making a return according to leaked information.
While the development team has a lot of work ahead to address issues with the games, it seems that the twin games are poised to receive DLC sometime in the future. Now, a known leaker has just shared information about a major feature in the DLC.
Riddler Khu, a popular and reputable leaker in the Pokémon community, has a track record for leaking info online. The leaker has revealed information regarding games such as Pokémon Brilliant Diamond and Shining Pearl, Pokémon Legends: Arceus, and Pokémon Scarlet and Violet. Khu teased starter Pokémon before their announcement and revealed several key Pokémon.
On November 3, 2022, Riddler Khu posted a tweet seemingly hinting at DLC for Pokémon Scarlet and Violet. The leaker is known to post information through riddles that the community needs to solve.
This was a dlc riddle in every sense, btw.
— Khu's Riddle School in Titan (@Riddler_Khu) November 28, 2022
This particular post contained images of Pokémon gimmicks throughout the franchise: Mega Evolution, Z-Moves, Dynamaxing/Gigantamaxing, and Terastallization. The tweet then asked fans which of the gimmicks was different from the rest. The community concluded it was Mega Evolution since the other three take place in only one region. Mega Evolution can happen in the Kalos and Hoenn regions of the Pokémon world.
Riddler Khu replied that the tweet was a "DLC riddle in every sense" hinting that the answer would lead fans to a major feature added to a future DLC. The leaker followed up the tweet with "Mega", confirming the community's conclusion was correct.
Fans have been speculating that players could be returning to Kalos from Pokemon X and Y. Kalos is located in France while the Paldea region is in Spain and Portugal. These countries are located next to each other and it could mean that the DLC would open up the Kalos region to Pokémon Scarlet and Violet players.
The DLC may add the Kalos region to Scarlet and Violet.
It would be exciting for players to explore a new region in Pokémon Scarlet and Violet. This would be one of the few times that two regions are featured in one game. However, it's all speculation at this point, as Riddler Khu is never direct with the information they reveal. It will be interesting to see Mega Evolution in Pokémon Scarlet and Violet as well.
Either way, fans will have to wait for an official announcement from Game Freak and The Pokémon Company about any DLC. For now, players are keenly waiting for a patch to address the performance issues that have been plaguing the game since launch.
Game Freak, Nintendo, Pokemon Scarlet, Pokemon Violet, The Pokémon Company
Posted by Darryl Lara
Darryl has been gaming since the early 90s, loves to read books and watch TV. He spends his free time outside of gaming and books by riding his motorcycle and taking photographs. You can find Darryl on Instagram. Check him out on Steam and Xbox too.


I have an LG G3 and Proscan tablet both running android and have installed google play on both under the same e-mail account but my apps are not synchronized (specifically boom beach). It is almost as if each device is running a separate version of google play independent from the other even though they are registered to the exact same e-mail account with the same information. Any help would be greatly appreciated. Thanks.
Welcome to Android Central! What do you mean the apps aren't synchronized? Do you mean that some apps appear on one device but not the other? This may be due to incompatibility with one of the devices--more likely the Proscan tablet, since off-brand devices tend to have more incompatibility issues than the more mainstream ones.
Why won't my phone stay on after unplugging it from the charger?
Zip code and phone # format?
How do I clear content and cache?