L-stages in ill-founded countable model of ZFC

Question: I apologize that I need a preamble in which I digress into philosophy, but here it goes:
One of the perceived goals of set-theory is to provide a foundation for mathematics.  Natural, rational, real numbers and other structures can be defined inside set-theory.  However, students reason about these numbers and structures independently of set-theory. Numbers for example are not naturally perceived as sets, they are atomic, and sets are only needed to collect things.
Even in the context of model theory, I feel that I am allowed to work with a model of set-theory, put it aside for a moment, and think about non-set-theoretic objects. They all may coexist independently. I may believe that our "real" sets are sufficiently correctly described by ZFC, so that I believe in the existence of ordinals up to and beyond say $\omega_1$, again
alongside other non-set-theoretic atomic objects and structures. I may also have a notion of countable and uncountable collections independent of a concrete set-theoretical framework. Countable collections are enumerable, uncountable are not. This is the key idea of Cantors' diagonalization - there is no exhaustive enumeration of the reals.
End of preamble.
Assume a model of ZFC which is presented as a directed graph: The model universe is the collection of vertices, the element relation is the collection of edges. Vertices are atomic, they are not sets, they represent sets.  I choose this representation to avoid distracting concepts around real set membership.
Given such presentation of a model, one can identify some exemplary model-sets. The empty set of the model is represented by the vertex with no inbound edges. The set $\{\emptyset\}$ is represented by the vertex with not inbound edges except the one originating from the empty-set-vertex. And so on.
Define an external mapping $\operatorname{Vert}(s)$ which maps a model-set $s$ to the collection of vertices that represent $s$'s model-elements. Whatever $s$ is, $\operatorname{Vert}(s)$ is a countable collection of vertices, if the model is countable.
Assume we have an ill-founded countable model and want to identify various stages of the constructible universe of that model.
Wikipedia defines: $L_\alpha = \bigcup_{\beta < \alpha} \operatorname{Def} (L_\beta)$
It is not clear to me which ordinals I need to use to construct stages. Is it the "real" ones or the ones the model sees? However, I have an issue with both choices.
Choice 1: Use real (i.e. external) ordinals. I assume that the stages $L_\circ$ satisfy $L_\alpha \subsetneq L_\beta$ for $\alpha < \beta$. If this is so, this should translate to $\operatorname{Vert}(L_\alpha) \subsetneq \operatorname{Vert}(L_\beta)$ for $\alpha < \beta$. Then according to [1], with $\omega_1$ begin externally uncountable, $\operatorname{Vert}(L_{\omega_1})$ should be an uncountable collection of vertices, which is impossible.
Choice 2: Use in-model ordinals. According to [2] there is an infinite reverse path of ordinal-vertices: $\alpha_0 \leftarrow \alpha_1 \leftarrow \alpha_2 \cdots$
How is $L_{\alpha_0}$ even well-defined, when there is no base-case for the recursive definition?
[1] limit of uncountable strictly increasing sequence of sets
[2] Infinite decreasing ordinal chain in ill-founded countable model
Comment: I think this question would benefit from trimming - I really don't see what the preamble has to do with the question proper. To be honest, I don't see the point of any of the question before the paragraph beginning "Assume we have" - that's where the actual mathematical question starts, and the philosophical aside doesn't seem to relate to it.
Answer: Every model $M$ of $\mathsf{ZFC}$, ill-founded or not, has its own version $L^M$ of the $L$-hierarchy constructed internally. The levels of $L^M$ are indexed by the $M$-ordinals.
While the $M$-ordinals may be ill-founded externally, they appear well-founded internally. This makes ordinal-indexed constructions work well from $M$'s perspective: $M$ doesn't "see" a descending sequence in its own ordinals, so as far as $M$ is concerned there is (for example) only one possible candidate for $L_{\alpha_0}$. Note that we know this has to be the case ahead of time since $\mathsf{ZFC}$ proves that transfinite recursion works as desired and $M\models\mathsf{ZFC}$.
Note that countability concerns and the cardinality of $M$ don't enter into this. Moreover, nothing special about the $L$-hierarchy is being used here, simply its status as a definable transfinite recursion construction.

EDIT: Per the comments below, I think it's a good idea for me to give a toy example of an "internal construction."
Let $\Sigma$ be the language consisting of a single constant symbol $0$, a single binary relation symbol $<$, a single unary function symbol $s$, and a single unary relation symbol $U$. Consider the theory $T$ whose axioms say the following:

$<$ is a linear order with least element $0$, where each element has an immediate successor given by $s$ and each element other than $0$ has an immediate predecessor.

$U(0)\wedge\neg U(s(0))\wedge \neg U(s(s(0))\wedge\neg U(s(s(s(0))))$, and $\forall x(U(x)\leftrightarrow U(s(s(s(s(x))))))$. (Intuitively, this says that $U$ names the elements divisible by $4$.)

Finally, the full first-order induction scheme for all $\Sigma$-formulas.

There is an obvious "standard" model of $T$, but - per compactness - $T$ also has lots of "nonstandard" models (= models where $<$ is ill-founded). Let $M$ be a nonstandard model of $T$, and consider the following imagined dialogue between Alice and Bob:
Alice makes a particular claim about the definable ("internal") structure of $M$:

There is exactly one $M$-definable unary relation $E$ such that $E(0^M)$ and for all $x\in M$ we have $E(x)\leftrightarrow \neg E(s^M(x))$.

Bob takes issue with this.

"Wait a second!" Bob reasonably objects. "Clearly $E$ is meant to denote the set of even numbers. But (in the absence of addition or multiplication) we define evenness recursively, using the ordering alone, and this doesn't work in $M$ since $<^M$ is ill-founded!"

"Yes," Alice responds, "that's true - the most natural approach to producing such an $E$ doesn't work. However, consider the formula $\eta(x)\equiv U(x)\vee U(s(s(x))).$ Then we have $$M\models \eta(0)\wedge\forall x(\eta(x)\leftrightarrow\neg \eta(s(x)))$$ as desired."

"Well, that's not really fair," Bob says, "that was sort of a loophole: you've just reconstructed a desired relation from other built-in structure. Isn't that cheating?"

"It would be cheating if that additional structure weren't part of $M$ itself," Alice answers. "I'm not claiming that we don't need $U$, but it would be silly not to use it if we're given it."

"... OK, I think I see why I'm dissatisfied," Bob says. "You've used some of the 'extra structure' of $M$ to produce a definable function with the desired properties. But why should it be unique? By making things depend on structure other than $<$ alone, you've raised the possibility of having multiple such definable relations which disagree - which would clearly ruin your day."

"True," admits Alice. "But I haven't used all the axioms of $T$ yet! Keep in mind I also have the induction scheme (which is first-order, so permits nonstandard models). Suppose $\psi(x)$ were some other formula such that $M\models\psi(0)\wedge\forall x(\psi(x)\leftrightarrow\psi(s(s(x)))$. Consider the new formula $\theta(x)\equiv \eta(x)\leftrightarrow\psi(x)$. We have $\theta(0)$ (trivially) and $\forall x(\theta(x)\rightarrow\theta(s(x)))$ (go by cases). So by our induction scheme we get $\forall x\theta(x)$, or to put it another way $\forall x(\eta(x)\leftrightarrow\psi(x))$. So $\psi$ defines the same relation on $M$ as $\theta$."

The same thing is going on with the $L$-hierarchy internal to a nonstandard model $M$. While ill-foundedness implies that the $M$-ordinals alone are insufficient for such a construction even if we went beyond first-order logic, the $M$-ordinals together with the rest of $M$ give $M$ the power to produce a definable relation with the desired properties, and additional properties of $M$ (e.g. Foundation) ensure that exactly one definable relation with the desired properties exists. Moreover, there is a single formula which defines the desired definable relation within $M$ for every model $M$ (we don't have to use different formulas in different models).
Comment: @Damian: You can argue that any programmer in C should be able to produce the same results as someone who is writing a software in Python or Common Lisp. And yet, you find different software is written in different languages, usually to highlight strengths of the chosen language over another. Saying that a graph theorist could derive all of set theory since a model of ZFC can be seen as a graph is too reductionist and it misses the big picture of where the strength of the structure and theory lie in.
Comment: @Damian "What makes ZFC special that we care what it internally perceives as well-founded?" As model theorists, we always care about the definable sets in a structure and the "internal second-order" behavior of those definable sets, and well-foundedness is important to $\mathsf{ZFC}$. "What is an internal sequence anyway in the context of directed graphs?" Just write down the definition of "sequence" in the language of set theory and replace each "$\in$" with the edge relation. "At which point would a graph theorist care about internal sequences?" I don't know, I'm not a graph theorist.
Comment: What makes ZFC special that we care what it internally perceives as well-founded? What is an internal sequence anyway in the context of directed graphs? I assume one could translate Wikipedia's definition into a native graph construction. Begin with zero vertices, add the correct vertices and edges in each step. The external well-foundedness of the index set would be one ingredient to the construction's well-definedness. At which point would a graph theorist care about internal sequences?
Comment: My point is that a graph theorist should be able to produce the same results as a set theorist as long as he knows how to apply the definition of the construction. It is the choice of the set theorist to interpret some vertex as a sequence, it is not a necessity of model theory.

The graph theorist is given a graph without context and a recipe to recursively construct subgraphs. He cannot construct the subgraph of $L_{\alpha_0}$ because it is ill-defined. $L_\circ$ is not a construction, it is a description at best. I wouldn't be surprised if $L_\circ$ is ambiguous even in a fixed model.
Comment: @Damian "My point is that a graph theorist should be able to produce the same results as a set theorist as long as he knows how to apply the definition of the construction" They can. "It is the choice of the set theorist to interpret some vertex as a sequence, it is not a necessity of model theory." ??? "He cannot construct the subgraph of $L_{\alpha_0}$ because it is ill-defined" That's **wrong**. "$L_\circ$ is not a construction, it is a description at best." That's also **wrong**.  "I wouldn't be surprised if $L_\circ$ is ambiguous even in a fixed model." Well, math is surprising sometimes.
Comment: @Damian It may help to think of it this way. There is a particular **extremely complicated** formula $\varphi(x,y)$ in the language of graph theory such that, when $M$ is a "ZFC-graph,"$\varphi(x,y)$ defines in $M$ a relation between "$M$-ordinals" and certain other vertices of $M$ and this relation satisfies certain graph-theoretic properties - for example, the set of vertices in $M$ which appear as right coordinates of pairs satisfying $\varphi$ constitutes the smallest definable subset of $M$ which is itself a "ZFC-graph" (think about the classical "minimality" of $L$). (con'td)
Comment: Intuitively, $\varphi(x,y)$ means "$y\in L_x$." All of this can be parsed by a graph theorist, the only point of difference between the graph theorist and the set theorist being that the graph theorist **might not care** about this particular extremely complicated formula. The "internal transfinite recursion" nature of $\varphi$ is a precise property, having to do with the graph-theoretic rephrasing of the set-theoretic recursion theorem, and understanding such internal constructions is crucial to studying ill-founded models of set theory.
Comment: Maybe stepping back from ZFC will help me. Let us have a definition in the context of PA: $K(0) := 1$, $K(s(n)) := -K(n)$.
Consider a nonstandard countable model. Presumably there is a chain $\cdots, n_{-2}, n_{-1}, n_0, n_1, n_2, \cdots$ with $n_{i+1} = s(n_i)$. Is $K(n_0)$ positive or negative?
Comment: I am sorry to have chosen numbers, I should have used true/false, black/white. My point is that the definition might work for the initial segment of the model, but is, I think, ill-defined for those on the $\mathbb{Z}$-like chain. This is how I see the definition of $L_\circ$ right now.
Comment: @Damian OK, do the following. Within the language of arithmetic there is a particular formula $\varphi(x,y)$ which we can prove in $\mathsf{PA}$ defines a function $K$ with the following properties: $K(n)=n$ mod $2$ for example: $K(0)=0$, $K(x)=0$ implies $K(s(x))=1$, and $K(x)=1$ implies $K(s(x))=0$. Now for each $M\models\mathsf{ZFC}$ (ill-founded or not) and each $n\in M$ (nonstandard or not) we can ask "What is $K(n)$ (in the sense of $M$)?" **And $M$ will have an answer to that**. To us in the "standard" universe this may look silly if $n$ is nonstandard. (cont'd)
Comment: But there's nothing problematic about this at all. Things only look weird if we expect $M$ to hew too closely to "standard reality." Instead, we need to think in the following way: the theorems we prove about our various recursive constructions are $\mathsf{PA}$-theorems, and so must hold in any model of $\mathsf{PA}$, standard or not. So **every model of $\mathsf{PA}$ has its "own version" of the usual arithmetical constructions**, no matter how weird that may look.
Comment: @Damian "My point is that the definition might work for the initial segment of the model, but is, I think, ill-defined for those on the $\mathbb{Z}$-like chain." That is, again, **incorrect**. (Also there is no "**the** $\mathbb{Z}$-chain" - there are many, many, many different $\mathbb{Z}$-chains. I think you instead mean "ill-founded part.") "This is how I see the definition of $L_\circ$ right now." That will change over time as you come to better understand illfounded models.
Comment: "And M will have an answer to that". Do you need to introduce $K$ as a new function symbol for that?
Comment: @Damian No. Really there's no need for the notation $K$ at all here, that's just convenient notation given how we write arguments in natural language. Forget $K$; the point is that we have some formula $\varphi(x,y)$ in the language of $\mathsf{PA}$ such that $\mathsf{PA}$ proves: for each $x$ there is exactly one $y$ such that $\varphi(x,y)$, and that $y$ is either $0$ or $1$; $\varphi(0,0)$; $\forall x(\varphi(x,0)\leftrightarrow\neg \varphi(s(x),0))$. In any model $M\models \mathsf{PA}$ we get a function $K_M:M\rightarrow M$ given by $K_M(x)$ = the unique $y$ so that $M\models\varphi(x,y)$.
Comment: (E.g. $\varphi(x,y)\equiv (y=0\vee y=s(0))\wedge\exists z(z+z+y=x)$.) One special case of this is the standard model's version, $K_\mathbb{N}$. We may think of $K_\mathbb{N}$ as being **built from only the ordering**, and certainly this breaks down for nonstandard models: we can have $M_1,M_2\models\mathsf{PA}$ with  isomorphic underlying orders (that is, $M_1\upharpoonright \{<\}\cong M_2\upharpoonright \{<\}$) which nonetheless have $K_{M_1}\not=K_{M_2}$. But so what? A model $M$ of $\mathsf{PA}$ is **more than just an ordering**, and the construction of $K_M$ uses that additional structure.
Comment: @Damian I've added a toy example of an "internal construction" (+ subsequent analysis) which may help clarify things.
Comment: @Noah, given a model of PA, $\varphi$ and some $x$, one would need to search the whole model for a fitting $z$ to figure out $y$. One needs the whole model in advance. This is ok, as $\varphi$'s task is not to construct its ambient universe.
For the $L$ construction, Wikipedia states "... quantifiers interpreted to range over the previous stage". My definition of $K$ also used previously known things to define a new thing. This property got lost when translated into $\varphi$. So I don't know if we have different opinions what should count as a construction, or if the example is unsuitable.


Loop doesn't work when using try and catch on android

Question: private MediaPlayer player;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    player = MediaPlayer.create(this, R.raw.main);
    player.setLooping(true);
        try {
        player.prepare();
        player.start();
    } catch (IllegalStateException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

    public void onPause() {
    super.onPause();}

protected void onStop() {
    super.onStop();
    player.stop();
    player = null;}

I tried to play some music while the activity is running, it's working very well but the loop is not.
Without the try/catch it works fine but the music starts before the activity is fully loaded.
Can anyone tell me how to make the music run with the 'prepare' function and so the music will loop?
Comment: Please follow this link , this may help you [http://stackoverflow.com/questions/11951420/how-do-i-loop-my-media-player-files][1]

  [1]: http://stackoverflow.com/questions/11951420/how-do-i-loop-my-media-player-files
Comment: Did I misunderstand the question? Are you having trouble with `setLooping` or the try catch block?
Answer: You need to call setLooping(true) after you call prepare()


To what degree can/should you overprovision a mail server?

Question: I'm considering setting up a mail server as a side offering to my hosting business.
I know that other providers won't "reserve" the disk space for an account (i.e. 15GB for gmail), but to what degree can one overbook the available storage in terms of accounts promised and actual disk space?
Comment: This is both opinion based and about capacity planning, and neither is a good fit for this Q/A site. But maintaining a mail service is hard: your customers start having issues both with inbound spam and outbound mail getting on block lists. It is probably best to leave this for the professional email providers.
Comment: I don't think this can be meaningfully answered without basing the answer on what unspecified time interval you will need, and what time interval you will have (including the worst timing possible), when adding new disk space to both production environment and backup space. What maximum mail size would you like to accept? Will you setup some rate limiting on top of per-user quotas?
Comment: With the advent of webmail and most user consuming their email from multiple devices, people don't accept POP3 anymore . They'll leave all their mail on the server. Unless you actively purge old messages expect that people will only start cleaning up their mailbox once they start getting "quota exceeded" warnings. Eventually you'll need to actually deliver close to what you sold. How quickly that happens depends on your users, but might be anticipated with good monitoring and capacity management practices. Don't forget how much additional  storage for replication and/or backup will be needed.
Comment: will your "side offering" be  "best effort", or "guaranteed delivery/up-time; backup; antivirus/spam checks;  ..." ?
Comment: Monitor usage and set up alerting. The answer to this will vary enormously depending on your clients.
Comment: Offering *"unlimited"* or severely over-provisioned email storage was an option back in the day when a hosting provider could get away with only offering  POP3 access and a single INBOX. Most POP3 clients defaulted to deleting all messages from the server after retrieval and effectively actively used mailboxes only stored a handful of unread messages but were empty most of the time and your worst concern were forgotten/abandoned mailboxes that could grow indefinitely.
Answer: Consider not over-provisioning at all, initially.
Understand that some features, such as indexed full text search, can significantly increase your storage overhead beyond the basic "how many GiB of mail are accepted in one box". These days spam filters like to have a substantial "working area" as well, your server could at times be working on 100 junk submissions at the same time, none of which are eventually accepted, yet still should not impede your ability to process legitimate mail flows.
Slap a few cheap 2TB disk into your RAID, and set a reminder to check after 50, 100 and 200 users are registered. Mailboxes generally grow indefinitely, so there is no way you are not making storage extensions and scaling (in both primary storage and emergency recovery) a key part of the operation anyway.

I do not believe doing email as a side offer can be remotely profitable these days: The involved mechanisms for a pleasant experience just became too complex - yet not overly depending on user count - to justify anything but operating professionally, specialized & at scale. Hence, what you spend on the first 200 users is not really relevant. Besides, the first few users will not hit the disk anyway, because everything fits in RAM, so you can start cheap and buy proper solid state storage later, when you do know actual usage patterns and growth over time.
Comment: Thank you for your answer. I will reconsider my idea, or perhaps find a reasonable reseller of email services.


How to serialze the correct fields that are stored on has a has_many through relation table

Question: I have a has_many through relationship. But I need to serialize a field stored on the relation table as workflow_state.
To do this I have to access the relation table directly.
Here is the current serializer I have:
class OrderSerializer < ActiveModel::Serializer

  attributes :id, :number, :slug, :quoted, :invoiced, :paid, :reciepted, :void, :refund, :workflow_state
  has_one :table
  has_one :user
  has_one :quote
  has_one :reciept
  has_many :items

  class RecieptSerializer < ActiveModel::Serializer
    attributes :id, :order_number, :number, :slug, :cost, :paid, :vat, :total, :change
  end

  class UserSerializer < ActiveModel::Serializer
    attributes :id, :name, :email
  end

  class QuoteSerializer < ActiveModel::Serializer
    attributes :id, :order_number, :number, :slug, :cost, :vat, :total
  end

  class TableSerializer < ActiveModel::Serializer
    attributes :id, :number, :position
  end

  def items
    customized_items = []

    object.items.each do |item|
      # Assign object attributes (returns a hash)
      # ===========================================================
      custom_item = item.attributes
      # has_one w/only specified attributes
      custom_item[:category] = item.category.slice(:id, :name, :icon)
      custom_item[:workflow_state] = item.order_items.find_by_item_id(item.id).workflow_state
      customized_items.push(custom_item)
    end

    return customized_items
  end
end

The issue is it gives the correct type of response however the field it shows is wrong says 'created' for all items. But when I check the database, the field is "preparing".
Response:
{
    "order": {
        "id": 7,
        "number": 7,
        "slug": "61b8a5ad-b3f9-4492-b7d7-2c61684c4988",
        "quoted": true,
        "invoiced": false,
        "paid": false,
        "reciepted": false,
        "void": false,
        "refund": false,
        "workflow_state": "preparing",
        "table": {
            "id": 9,
            "number": 9,
            "position": "Bar"
        },
        "user": {
            "id": 1,
            "name": "admin",
            "email": "firstname.lastname@example.com"
        },
        "quote": {
            "id": 7,
            "order_number": 7,
            "number": 7,
            "slug": "43f0ca98-84dc-4e6d-8062-f3f1ef1f2e5f",
            "cost": "22.0",
            "vat": "0.0",
            "total": "22.0"
        },
        "reciept": null,
        "items": [
            {
                "id": 1,
                "name": "Eggs bendict",
                "icon": "breakfast",
                "cost": "5.5",
                "price": "7.5",
                "description": "Eggs on toasted muffins with holindais sauce",
                "category_id": 1,
                "organisation_id": 1,
                "created_at": "2020-06-26T07:45:44.603Z",
                "updated_at": "2020-06-26T07:45:44.603Z",
                "category": {
                    "id": 1,
                    "name": "Breakfast",
                    "icon": "breakfast"
                },
                "workflow_state": "created"
            },
            {
                "id": 1,
                "name": "Eggs bendict",
                "icon": "breakfast",
                "cost": "5.5",
                "price": "7.5",
                "description": "Eggs on toasted muffins with holindais sauce",
                "category_id": 1,
                "organisation_id": 1,
                "created_at": "2020-06-26T07:45:44.603Z",
                "updated_at": "2020-06-26T07:45:44.603Z",
                "category": {
                    "id": 1,
                    "name": "Breakfast",
                    "icon": "breakfast"
                },
                "workflow_state": "created"
            },
            {
                "id": 1,
                "name": "Eggs bendict",
                "icon": "breakfast",
                "cost": "5.5",
                "price": "7.5",
                "description": "Eggs on toasted muffins with holindais sauce",
                "category_id": 1,
                "organisation_id": 1,
                "created_at": "2020-06-26T07:45:44.603Z",
                "updated_at": "2020-06-26T07:45:44.603Z",
                "category": {
                    "id": 1,
                    "name": "Breakfast",
                    "icon": "breakfast"
                },
                "workflow_state": "created"
            },
            {
                "id": 13,
                "name": "Fries",
                "icon": "fries",
                "cost": "5.5",
                "price": "7.5",
                "description": "Fries",
                "category_id": 5,
                "organisation_id": 1,
                "created_at": "2020-06-26T07:45:44.636Z",
                "updated_at": "2020-06-26T07:45:44.636Z",
                "category": {
                    "id": 5,
                    "name": "Sides",
                    "icon": "fries"
                },
                "workflow_state": "created"
            }
        ]
    }
}

What I'm thinking is this:
custom_item[:workflow_state] = item.order_items.find_by_item_id(item.id).workflow_state

Its probably serializing the first item that in order_items with item id as specified.
Is there a better way to serialise a field from the relation table for a given relation?
Answer: I refactored the whole app to not use a has_many :through relationship.


Maximixing the speed of particle rendering on HTML5

Question: I am doing an experiment and attempting to improve the max particle count before frame-rates start to drop in HTML5 Canvas.
I'm using requestAnimationFrame, I'm using drawImage from a canvas as this seems to be the fastest method for rendering images (as tested on jsPerf).
There's a working jsFiddle here: http://fiddle.jshell.net/bewYC/5/
You might have to refresh or re-run a few times to get it to work (no idea why but it just doesn't want to run on the first page load.)
As is, my computer running Chrome 22 can maintain 60FPS with about 5,000 particles. With every step above that, FPS starts to drop. If I remove drawImage() and just calculate the particles' positions, my processor doesn't max out until well over 10X as many particles.
What I want to know:
Is there is a faster way to render a large amount of particles (say 40,000 for example) than using a loop with drawImage in it? I especially want to know this about JavaScript/Canvas, but if you only have knowledge about another language such as Java or C#, then please share anyway.
Comment: In my experience, 5,000 particles at 60fps in Canvas is pretty damn good. If you're not adverse to WebGL, then [WebGL2D](https://github.com/gameclosure/webgl-2d) is very likely a simple drop in and should yield much better performance. I have also found that recent versions of Firefox seem to perform better with `drawImage` than Chrome does.
Comment: For what it's worth, my simple, largely unoptimized [particle editor](http://city41.github.com/particle.js/v2/) can't get nearly that good of performance. But, I am not just using `drawImage`, I am rendering to an off screen buffer and using `source-atop` which is very expensive.
Comment: It's a fast computer, and I've used every kind of optimization I've been able to find so far. For instance, `clearRect` instead of drawing a new background, using `drawImage` instead of `fillRect` or `putImagedata`. Drawing with `drawImage` from another canvas is faster than drawing from an actual image object, etc. Mostly I think the 5,000 can just be accredited to my 2600k running at 4.8ghz.
Comment: Those all sound like good changes to me. I dunno, canvas still isn't all *that* performant, sadly. btw, your fiddle doesn't work most of the time because you need to wait for the image to load before proceeding. I also had to switch to a different image as I kept getting a 403: http://fiddle.jshell.net/bewYC/7/
Comment: @MattGreer Thank you for pointing out the image loading! That was bugging me big time but I just ignored it.  I wouldn't really try to implement a particle engine of 50,000 particles in a game on Canvas, I  know there are better options, I just wanted to see if I could push it farther for fun.
Answer: For this problem, using WebGL (or other "3D" API as appropriate for your platform) is nearly always the best way to do it. Compositing lots of images ("textures", rather) at moving positions is exactly what graphics hardware is designed to be good for. Modern browsers do use GPU acceleration for performing 2D-Canvas drawing operations, but there is still JavaScript requesting the drawing of each individual image, and that's the problem.
I recommend you check out WebGL — for simple things like a particle system it's not hard to program at all, and you can easily render thousands of particles. Your JavaScript simply provides an array containing the positions of all the particles.
An advanced technique is to put the simulation of the particles as well on the GPU, thus requiring no JavaScript to execute per-particle at all. I have myself written a GPU particle simulator in my GLToy. Here it's configured for 80,000 particles and that achieves 60 FPS on my laptop. In fact, the limitation in that particular configuration is the fill-rate of the smooth particles; if we just use points I can push it up to 300,000 particles. And I am no wizard of graphics programming; I'm sure someone who knows exactly what to do could push it further.
(P.S. links may be fragile as I revise GLToy; if you don't get the named effects please let me know so I can fix the links.)
Comment: Heya, links broken


Capturar dados seguindo padrão até último espaço

Question: Estou tentando fazer um scrapping de um site, e gostaria de capturar o valor que segue o padrão abaixo:
Advogado: XXXXX Número do Processo: XXXXXX OutroCampo: XXXXX

geralmente o que separa essas informações é um espaço, então seria o que seria capturado é, por exemplo, Advogado: Bill Gates(aqui teria um espaço/tab)
Padrão:
NOME_DO_CAMPO:(espaço opcional)Valor a ser capturado(espaço final)
Comecei com esse regex, mas ele só captura o início e não o valor "entre"
regex: \w+:\s{1}
Answer: Ter espaços como o delimitador de campos, e permitir espaços nos valores do campo pode se tornar um problema. É improvável, mas se o nome do advogado for "Número do Processo: XXXXXX OutroCampo: XXXXX" fica difícil de validar.
De qualquer forma imagino que o que você queira seja um simples '/^Advogado:\s?(.*)\s?Número do Processo/'. Não há porque validar uma sequencia de letras com \w+ já que a primeira palavra sempre será Advogado.
Exemplo:
$entrada = "Advogado: Bill Gates Número do Processo: XXXXXX OutroCampo: XXXXX";
preg_match('/^Advogado:\s?(.*)\s?Número do Processo/', $entrada, $match);

//toda a expressão 'Advogado: Bill Gates Número do Processo'
echo $match[0];

echo '
';

//apenas o match entre parenteses 'Bill Gates'
echo $match[1];

Comment: Se os dados podem variar, sugiro que edite a pergunta e coloque mais alguns casos. Mas já adianto que, se tanto o valor do campo (nome e sobrenomes) quanto o que vem depois ("Número do processo") estão separados por espaços, fica meio difícil saber onde termina um e começa outro
Comment: É porque o campo (Advogado) pode variar, ai usei o \w+
Comment: e o "número do processo" também
Answer: Veja se é disso que precisa:
<?php

$string = 'Advogado: XXX XX Número do Processo: XX XXXX OutroCampo: XXX XX';

preg_match_all('/(Advogado\:)(.+?)(Número\sdo\sProcesso\:)(.+?)(OutroCampo\:)(.+?)$/', $string, $matches);

echo 'MATCHES:
';
echo 'Advogado: '.$matches[2][0].'
';
echo 'Processo: '.$matches[4][0].'
';
echo 'Outro campo: '.$matches[6][0].'
';

echo '
';
print_r($matches);
echo '
';

Saída:

MATCHES:
Advogado: XXX XX
Processo: XX XXXX
Outro campo: XXX XX
Array
(
    [0] => Array
        (
            [0] => Advogado: XXX XX Número do Processo: XX XXXX OutroCampo: XXX XX
        )

    [1] => Array
        (
            [0] => Advogado:
        )

    [2] => Array
        (
            [0] =>  XXX XX
        )

    [3] => Array
        (
            [0] => Número do Processo:
        )

    [4] => Array
        (
            [0] =>  XX XXXX
        )

    [5] => Array
        (
            [0] => OutroCampo:
        )

    [6] => Array
        (
            [0] =>  XXX XX
        )

)

Exemplo no RegEx101.com


Erro ao executar relatório no Reporting Services do SQL Server

Question: Está ocorrendo o seguinte erro ao executar algum relatório do Reporting Services:

"Erro no processamento de relatório. (rsProcessingAborted) Não é
  possível criar uma conexão com a fonte de dados 'Produção'.
  (rsErrorOpeningConnection) A network-related or instance-specific
  error occurred while establishing a connection to SQL Server. The
  server was not found or was not accessible. Verify that the instance
  name is correct and that SQL Server is configured to allow remote
  connections. (provider: Named Pipes Provider, error: 40 - Could not
  open a connection to SQL Server)"

Procedimentos realizados:

Habilitado TCP/IP e Pipe Name nas configurações do SQL Server;
Todos os serviços do SQL Server startados;
Permitida conexão remota na instância do banco;
Firewall e antivírus desabilitados no servidor.
Comment: Espero que isso ajude: [named-pipes-provider-error-40](https://stackoverflow.com/questions/9945409/how-do-i-fix-the-error-named-pipes-provider-error-40-could-not-open-a-connec)
Comment: ôpa @CaiodePaulaSilva, já tinha realizado todos esses passos.
Comment: O erro acontece com qualquer relatório ou com algum relatório específico? Esse relatório funcionava antes ou sempre deu esse erro? O erro acontece quando o relatório é disparado de alguma máquina específica ou de qualquer uma?
Answer: Opção 1
Resolver esse problema é fácil:

Vá ate o executar (Win+R)

Digite services.msc

Reinicie o MSSQLSERVER

Traduzido de :
StackOverflow
Opção 2
A primeira coisa que eu tentaria é obter um pouco mais de informação sobre o erro

Essa mensagem dada é bastante genérica.

Você pode ativar erros remotos conforme a mensagem de erro e replicar o erro.
Para obter mais informações.
Ativar erros remotos
Ou verificar os logs de erros do Report Server para ver qual erro foi registrado.
%programfiles%\Microsoft SQL Server\<SQL Server Instance>\Reporting Services\LogFiles\
A próxima etapa seria conectar como o usuário da fonte de dados ao banco de dados, executar qualquer código / procedimentos armazenados que o log esteja usando com os mesmos parâmetros que você está usando ao executar o relatório e ver se ocorrem erros.
Traduzido de :
StackOverflow
Outras leituras: Microsoft


How to set up environment variables in react native

Question: I'm making a react native app that makes a request to my server hosted on heroku.
Should I be hiding the URL of my server and if so how can I add an environment variable to a react native project?
I have made a .env file and then have done this:
console.log(process.env.URL)

Which is returning undefined - I am also using expo if that makes a difference.
Answer: If you use Expo, there is an easy way to create environment variables.
In your app.json file
{
 "expo": {
   "extra": {
     "URL": "https://..."
   }
 }
}

After that, you will need to install the expo-constant package.
expo install expo-constants

And, to get the info in your app:
import Constants from "expo-constants";

console.log(Constants.manifest.extra.URL);

Answer: One library that I like to use that works for bare react native and expo is react-native-dotenv

Install it npm i react-native-dotenv

Add a .env file with your variables

MY_ENV_VARIABLE=SECRET_PASSWORD

Add the babel plugin to .babelrc file.

{
  "plugins": [
    ["module:react-native-dotenv"]
  ]
}

Import and use it

import { MY_ENV_VARIABLE } from "react-native-dotenv";

function doSomething() {
  console.log(MY_ENV_VARIABLE);
}

Comment: I have tried that but it didnt work, Seems like the developer stopped making updates to it?
Comment: @NotaGuruDotCom maintainer of react-native-dotenv. The library has transferred ownership. Updates are actively being done!


Prob. 2, Sec. 28 in Munkres' TOPOLOGY, 2nd ed: Compactness of $[0,1]$ in the lower limit topology

Question: Let $\mathbb{R}_l$ denote the set of real numbers with the topology having as a basis all the half open intervals $[a,b)$ on the real line.
Then is the closed interval $[0,1]$ compact as a subspace of $\mathbb{R}_l$?
My effort:

Let
  $$A \ \colon= \ \left\{ \ {1 \over 2 } - {1 \over {n+1}} \ \colon \ n \in \mathbb{N} \ \right\} = \left\{ \ 0, \frac{1}{6}, \frac{1}{4}, \frac{3}{10}, \frac{1}{3}, \frac{5}{14}, \frac{3}{8}, \frac{7}{18}, \frac{2}{5}, \ldots \right\}.$$
Then $A$ is an infinite subset of $[0,1]$, but, as we show below, $A$ has no limit points in $[0, 1]$ in the lower limit topology.
Case 1:
If $x \in \left[ \frac{1}{2}, 1 \right]$, then
  $$ 1 \geq x \geq \frac{1}{2},$$
  and so for any real number $y > x$, the open set $[x, y) \cap [0,1]$, for example,  contains $x$ but contains no point of $A$.
Case 2:
If $x \in \left( 0, \frac{1}{2} \right)$, then
  $$ 0 < x < \frac{1}{2}, $$
  and so
  $$ 0 < \frac{1}{2} - x < \frac{1}{2}, $$
  and hence
  $$ \frac{1}{\frac{1}{2} - x } > 2.$$
  Thus there exists an $N \in \mathbb{N}$ such that
  $$2 \leq N \leq \frac{1}{\frac{1}{2} - x } < N+1,  $$
  that is,
  $$ N+1 > \frac{1}{\frac{1}{2} - x } \geq N \geq 2, $$
  which implies that
  $${1 \over {N+1}} <   {1 \over 2 } - x \leq  {1 \over N  } \leq { 1 \over 2 }.$$
  So
  $$ 0 \leq {1 \over 2 } -  {1 \over N } \  \leq \  x  \ < \    {1 \over 2 } - {1 \over {N+1}}.$$
Thus if $x \neq \frac{1}{2} - \frac{1}{N}$, then the open set
  $$ \left[ x,   {1 \over 2 } - {1 \over {N+1}} \right) = \left[x,   {1 \over 2 } - {1 \over {N+1}} \right) \cap [0, 1] $$
  contains  $x$ but this open set contains no point of $A$.
And, if $x = \frac{1}{2} - \frac{1}{N}$, then $x \in A$ and thus the open set
  $$ \left[ x,   {1 \over 2 } - {1 \over {N+1}} \right) = \left[x,   {1 \over 2 } - {1 \over {N+1}} \right) \cap [0, 1] $$
  contains  $x$  and  but this open set contains no point of $A$ other than $x$ itself.
Case 3: If $x = 0$, then the open set $\left[0, \frac{1}{10} \right)$ contains only one point of $A$, namely the point $x = 0$ itself.
Thus our set $A$ has no limit points in $[0, 1]$ as a subspace of $\mathbb{R}_l$.

Is the above reasoning correct?
Answer: Yes, it's correct.
You can also display an open cover with no finite subcover. One such is
$$ \mathscr{U} \colon= \left\{ \, \left[1-\frac1n,1-\frac1{n+1} \right) \, \colon \, n \in \Bbb Z^+ \,  \right\} \cup \big\{ \, \{ 1 \} \big\}.  $$
Each of these sets, except $\{ 1 \}$, is open in $\Bbb R_\ell$; $\{1\}$ is open in the subspace $[0,1]$, and $\mathscr{U}$ is a partition of $[0,1]$, so no proper subcollection of it covers $[0,1]$.
We note that for $n = 1$,
$$ \left[ 1 - \frac1n, 1-\frac1{n+1} \right) = \left[ 0, \frac12 \right), $$
which contains the point $0$.
Let $x \in (0, 1)$. Then
$$ 0 < x < 1, $$
and so
$$ 0 < 1-x < 1, $$
which implies
$$ \frac1{1-x} > 1, $$
and so there exists an $N \in \mathbb{Z}^+$ such that $N \geq 2$ and
$$ 1 \leq N-1  \leq  \frac1{1-x} < N, $$
which implies
$$ 1 \geq \frac1{N-1} \geq  1-x > \frac1N, $$
which in turn implies
$$ 0 \geq \frac1{N-1} - 1 \geq -x > \frac1N  - 1, $$
and hence
$$ 0 \leq 1 - \frac1{N-1} \leq x < 1 - \frac1N. $$
Let us put
$$ K \colon= N-1. $$
Then
$$ x \in \left[ 1 - \frac1{K}, 1 - \frac1{K+1} \right). $$
Comment: @SaaqibMahmood: $\Bbb R_\ell$ is not limit-point compact: the infinite set $\left\{1-2^{-n}:n\in\Bbb N\right\}$ has no limit point in $\Bbb R_\ell$.
Comment: We can also use the set $A$ of the Q: Let $a_n=(1/2)-1/(n+1).$ Then $\{1/2,2\}\cup \{[a_n,a_{n+1}): n\in \Bbb N\}$ is an open cover with no finite sub-cover.
Comment: @BrianM.Scott you have only shown that $[0, 1]$, as a subspace of $\mathbb{R}_\ell$, is not compact. However, there are topological spaces that are limit-point compact but not compact. What is your take?
Comment: In my previous comment, $\{1/2,2\}$ should be $\{[1/2,2)\}.$


$GL_2(\mathbb{C})$ acting on extended complex numbers.

Question:
Let $GL_2(\mathbb{C})$ the general linear group of order two on complex. We can define a action from $GL_2(\mathbb{C})$ on $\mathbb{C}^*$ as
  $$\begin{bmatrix}{a}&{b}\\{c}&{d}\end{bmatrix}\cdot z=\displaystyle\frac{az+b}{cz+d} $$
  prove that there exist only one orbit i.e for every $z\in \mathbb{C}^*$ we have $L_2(\mathbb{C})z=\mathbb{C}$.

I'd appreciate a hint to solve this problem. I think that for a given $z,w\in \mathbb{C}^*$ I should find a matrix $A\in GL_2(\mathbb{C})$ such that $A\cdot z =w$ but I don't know how.
Thanks!
Answer: You have exactly the right idea!  The only question left is how one finds such a transformation.
Hint: If $z \neq 0$, we can always find a suitable transformation with $b = c = 0$
Comment: A rotation and an expansion. Thanks!


Service returning before all http calls have completed

Question: I have a controller calling a service, which performs a number of http calls and returns back a set of data to my controller. The problem i am facing is that my service returns some data (typically emtpy) before all the http calls have been completed, and as a result, $scope.myForksLinks is undefined.
Controller:
myService.getMyData()
    .then(function(response) {

        $scope.myUrl = response.myForksLinks;

    });

MyService:
handleResolveReject() {
    return promise.then(function(v) {
        return {v:v, status: "resolved"};
    }, function(e) {
        return {e:e, status: "rejected"};
    });
},

getMyData() {

    const that = this;
    var deferred = that._$q.defer();
    var httpResponse = [];

    var httpLinks = [
        {myTablesLinks: this.tablesLinks}, // this.tablesLinks = [http://tablelink1.come, http://anotherTableLink.com]
        {myGlassesLinks: this.glassesLinks},
        {myPlatesLinks: this.platesLinks},
        {myCupsLinks: this.cupsLinks},
        {myForksLinks: this.forksLinks},
    ]

    var getData = function() {
        _.forEach(httpLinks, function(httpSet, k) {
            _.forEach(httpSet, function(links, httpName) {
                var promises = [];

                angular.forEach(links, function(link) {
                    var promise = that._$http({
                        method: 'GET',
                        url: link + '/my/end/point',
                        responseType: 'json'
                    });
                    promises.push(promise)
                });

                return Promise.all(promises.map(that.handleResolveReject))
                    .then(function(results)) {

                        httpResponse.push({httpName: results.filter(x => x.status === 'resolved')});

                    });
            });
        });

        return httpResponse;
    };

    deferred.resolve(getData());
    return deferred.promise;

}

Comment: Maybe it's a `Promise.all` of `Promise.all`s?
Comment: `function(e) {
        return {v:v, status: "rejected"};
    }` this function throws. So `handleResolveReject` doesn't handle promise rejection.
Comment: @YuryTarabanko - it shouldnt, as its using the Reflect pattern here: https://stackoverflow.com/questions/31424561/wait-until-all-es6-promises-complete-even-rejected-promises
Comment: @OamPsy I'm not sure what the heck is "Reflect pattern". But your function when called throws ReferenceError because `v` is not defined. So the promise you return from `handleResolveReject` still rejects making entire `Promise.all` result to reject fast.
Comment: @YuryTarabanko updated code, there was a typo copying. Added link to Reflecf in previous response.
Answer: Something along these lines:
var allPromises = [];
_.forEach(httpLinks, function (httpSet, k) {
    allPromises = _.map(httpSet, function (links, httpName) {
        var promises = [];
        angular.forEach(links, function (link) {
            var promise = that._$http({
                method: 'GET',
                url: link + '/my/end/point',
                responseType: 'json'
            });
            promises.push(promise);
        });

        return Promise.all(promises.map(that.handleResolveReject))
            .then(function (results) {
                httpResponse.push({ httpName: results.filter(x => x.status === 'resolved') });
            });
    });
});
Promise.all(allPromises).then(() => {
    // here you go
})

Comment: Thanks, do I still need to use deferred??
Comment: Not really.. I am not sure how Angular JS promises work.
Comment: Oops.. forgot `Promise.all(allPromises).then()`
Comment: Thanks, that solved that issue. Now I get Cannot red property 'then' of undefined. From my controller call
Comment: Anything new happened?
Comment: @OamPsy angularjs has an alternative [`$q.all(allPromises)`](https://docs.angularjs.org/api/ng/service/$q#all)
Comment: @AlekseySolovey - q.all is an option, however it does not handle rejects great


In Organum and Species Counterpoint why is one of the voices always in whole notes?

Question: Edit: It was pointed out to me that counterpoint spawned from the Organum style of music. For more context, here's information from two sources I just read. "Two  styles of Organum existed during this period (1) note-against-note and (2) florid  many-notes against long-held notes called melismas." "Florid organum is A twelfth-century style of two-voice polyphony in which the lower voice sustains relatively long notes while the upper voice sings note groups of varying length above each note of the lower voice."
In Organum and Species Counterpoint, why is one of the voices always in whole notes, is it because that voice is to create the underlying harmony for the other voice? Are the long held notes pitch specific, as in are they always Tonic, 4th, Dominant and Octave?
Comment: The real answer is probably because that's how people wanted to write it. Same reason why most rock is in 4/4 time. It's the style.
Comment: I remember the long notes in species counterpoint shortening to half notes partway through the species list.
Comment: When I think of organum I think of pieces like Perotin's "Sederunt," in which the long sustained notes are actually a pre-existing melodic line, expanded to enormous proportions. In this case the notes wouldn't be selected for their own sake; they're just the notes of the tune. Imagine writing a piece in which one voice was the opening line of "Twinkle twinkle little star," but with each syllable being held for 10-20 measures.
Answer: I think you should not equate organum to species counterpoint.
Organum is from around 1200, but Fux's Gradus ad Parnassum is from 1725. They are totally different time periods and not the same style. Additional, organum was an actual musical style, whereas species counterpoint was a teaching method.
In organum you can think of the long notes like drones or pedal tones. It was a way to "thicken" the sound, just like parallel organum thickened the sound.
In species counterpoint the whole notes are essentially a way to simplify rhythm so the student can focus on relative motion between voices.
Also, keep in mind those species counterpoint lines in whole notes are supposed to exhibit good melodic shape and independence from the other voices, which is different from organum pedal tones and parallel voices. The voices in organum either work as pedals, not melodies, or duplicate parts in parallel, which does not achieve melodic independence.
Answer: Pieces counterpoint is a drill, not sa compositional tool. Using whole notes is a convention. It is based on the technique used for centuries of laying out a Chant melody in long notes and adding more voices. Fux simplified the ideas and made them into a teaching method.
Comment: Interesting. I have seen some music from those centuries. That use breve, longa, & maxima notes. This link (https://louis.pressbooks.pub/exploringarts/chapter/introduction-to-music/) says, "Around the late 12th century, a particular style of organum developed in the Cathedral of Notre Dame in Paris. This style involved holding out the notes of a Gregorian chant while a very active new melody was sung above it." So, my main questions are still sort of the same. But now also pertaining to "organum".
Comment: @Lecifer - And I'm betting that we use whole notes instead of anything longer because breves are already rare and exotic in modern sheet music and longa and maxima notes are pretty much nonexistent there.
Comment: @Lecifer - I suspect we don't use half notes instead for low species because the melismas on top would start demanding some *really* short notes. My transcription of Meta Knight's most often used boss theme is already hard enough to read in 5/4 time with 16th-note quintuplets - my transcription of a remix of another video game theme named "Zaghnol Comes" is hell to read in 6/8 time with **64th notes**. Yes, I sometimes regret not putting that transcription in 6/4 time instead, especially since my public version has ridiculously many 32nd notes.


Do Integrals over Fractals Exist?

Question: Given, for example, a line integral like
$$
\int_\gamma f \; ds
$$
with $f$ not further defined, yet.

What happens, if the contour $\gamma$ happens to be a fractal curve?

Since all fractal curves (to my knowledge) are not differentiable and have an infinite length, we should run into some trouble. Further questions of interest are:

What happens if the integral is taken over a Julia Set?
What happens in the case of a space-filling curve? Do we get a surface integral then?

I'd be glad, if anybody could wrap her/his 2.79-Hausdorff-dimensional brain surface around it!
Comment: As for applications: people do solve the Laplace equation or the wave equation in the interior of the Koch snowflake, and to do that they need to compute integrals on the boundary curve and so on. This is motivated for concrete applications.
Comment: Lebesgue integration http://en.wikipedia.org/wiki/Lebesgue_integration can integrate very nasty domains I believe
Comment: @ThomasRot: Do you know example or an application of those integrals?
Comment: Any Riemann integrable function is Lebesgue integrable with the same value, so all integrals you know are computable in Lebesgue sense. Applications where the Riemann integral is insufficient are abundant. It often comes up in statistics/stochastics/probability theory I believe
Comment: [related](http://en.wikipedia.org/wiki/Stochastic_calculus)
Comment: @NickKidman related, but not quite what I was looking for. Are there examples, where the integral is, for example, taken over [Koch's Snowflake](http://en.wikipedia.org/wiki/Koch_snowflake)?
Comment: @MarianoSuárez-Alvarez I think for the snowflake case it's ok to say: Cool! Do you have a link to something where this actually done?
Comment: I mentioned  the snowflake as a random example, people do these things in general... As for links, not really: but I am sure Google should be able to find this easily!
Answer: Re @Thomas Rot's comment: Lebesgue integration is just the thing here. However, if the fractal in question is a subset of some nice measure space, e.g. $\mathbb{R}^n,$ then the measure one will use in the Lebesgue integration shouldn't be the inherited Lebesgue measure. Otherwise, one gets dumb results: the Lebesgue measure of a subset of $\mathbb{R}^n$ of strictly fractional Hausdorff dimension is, almost by definition, 0.
Instead, one must use the Hausdorff measure as specified in, say, Stein and Shakarchi's book Real Analysis, on pages 325--327. The definition is that the exterior $\alpha$-dimensional Hausdorff measure of a subset $E \subset \mathbb{R}^d$ is $$m_\alpha^\ast(E) = \lim_{\delta \to 0} \inf \left\{\sum_k(\mbox{diam }F_k)^\alpha\ \left|\ E \subset \bigcup_{k=1}^\infty F_k,\ \mbox{diam }F_k \leq \delta\ \forall k\right.\right\}.$$ One can show that this is in fact an outer measure in the sense of Caratheodory, and restricting it to Borel sets yields a measure. The Hausdorff dimension of a Borel subset $E\subset \mathbb{R}^n$ is the infimum over all $\alpha$ with $m_\alpha^\ast(E) = 0.$ Equivalently it is the supremum over all $\alpha$ with $m_\alpha^\ast(E) = \infty.$
With this measure one can, presumably, do Lebesgue integration and differentiation as usual. (One might still get boring results: say the set has Hausdorff dimension $\delta.$ It might be the case that the set's $\delta$-dimensional Hausdorff measure is 0.)
This is just general measure theory, though. As far as I know, oriented integration theory (e.g. line integrals and Stokes's theorem) hasn't yet been generalized to fractals, though there is a notion of Laplacian on some fractals, as explained in an article of Strichartz.
If one is content to remain with general measure theory, one gets the following eerie result, Theorem 3.1 in Chapter 7 of Stein and Shakarchi:
There exists a curve $\mathcal{P}:[0,1] \to [0,1]\times [0,1]$ such that

$\mathcal{P}$ is continuous and surjective.
The image under $\mathcal{P}$ of any subinterval $[a,b] \subset [0,1]$ is
a compact subset of the square of (two-dimensional) Lebesgue measure $b - a.$
There are subsets $Z_1 \subset [0,1]$ and $Z_2 \subset [0,1]\times[0,1],$ each of measure zero, such that $\mathcal{P}|_{[0,1]\setminus Z_1}:[0,1]\setminus Z_1 \to [0,1]\times [0,1] \setminus Z_2$ is bijective and measure preserving!

(cue eerie music)
Comment: Is there a geometric explanation or a layman's analogy that would explain how a fractal is bijective and measure-preserving?
Comment: Could you help answering [this](http://math.stackexchange.com/q/38173/19341) question?
Comment: Generator in the continuum hypotheses?
Comment: the link to your homepage is dead
Answer: Sure, there are several ways to integrate over fractals. Jenny Harrison has worked out a lot using chains, Boris Katz has some papers you could look up... there is this using fractal measures http://arxiv.org/pdf/chao-dyn/9804006.pdf, and http://www.minet.uni-jena.de/geometrie/publicat/pdffiles/iwrtff1_ptrf98.pdf using fractional calculus. I have been formulating methods using the hyperreal number system, where, for instance, the limit case of the Cantor middle thirds set is a set of closed infinitesimal length intervals. An integral over infinitesimal elements can be defined, then the integrals summed over the whole fractal. See also "Analysis on Fractals" by Robert Strichartz.
John Starrett
Comment: @user110946, do you have references for the papers by by Harrison and Katz?
Comment: Thanks for the links. I like Zyczkowski's way of writing!
Comment: My paper on the technique will be appearing in the American Mathematical Monthly later this year. It is called Hyperreal Fractals and Integration.
Comment: Here is Harrison's paper: https://www.doi.org/10.1007/s12220-013-9433-6

Do Integrals over Fractals Exist?


Display main menu for logged in users only

Question: I'm new to drupal and using the latest version (7.x). I want hide the Main Menu in all pages until user log-in to the site. I set the Main Menu block role set to "Authenticated Users" only. But I can see the Main Menu on all pages as anonymous user.
How could I hide the Main Menu for anonymous user and show them once logged In ?
Comment: Check your **page.tpl** file, may be its rendering **Main menu**. If it is from **page.tpl** then just add the `condition` before rendering the Main menu.
Answer: If you are assigning main menu (as block) to region, you can control it's visibility by "Visibility settings". If you are rendering it in .tpl.php file then you can do it like this: Example (bartik's page.tpl.php):
<?php if ($main_menu && user_is_logged_in()): ?>

    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>

<?php endif; ?>

Answer:
When you move to the menu block configure settings there is tab for role.
You can restrict it to authenticated users only.
This would work.
Answer: Use this module https://www.drupal.org/project/menu_item_visibility
The module uses the exact same UI used for block visibility settings for familiarity.


Possible to map a directory to another server (for independant Wordpress install)?

Question: We have EC2 instances that I would like to not contain a wordpress install, and instead ideally map a folder to a different server, and run it under the same domain.
For some reason, this is escaping me. My thoughts are to map that folder.
I have seen this question asked here:
https://stackoverflow.com/questions/984834/map-virtual-directory-to-another-web-server-in-apache
And there were split opinions on Mod_proxy & mod_rewrite.
Is there another alternative to look into?
Reasons I am looking to keep wordpress off our server:
Traffic; Custom Configurations of SQL; Security; Possible incompatibilities with Apache configs, and Redundancy.
Comment: Why not use a subdomain like everyone else? Then you don't have to do all this insanity.
Comment: penalties to subdomains
Comment: What penalties to subdomains? Have you read some bad information about SEO on the Internet?
Answer: I'm not sure that mod_rewrite would work here. mod_proxy definitely will though, this is the way that we run it.
It can get tricky when running over SSL, we had to set some custom headers to get redirects sorted, but it's definitely possible to do it.
It's definitely worth trying to keep wordpress isolated - should help limit the damage if it's compromised.
Sample config:
<code><VirtualHost *:80>
  <LocationMatch "/wordpress">
    ProxyPassMatch https://wordpress.example.com
  </LocationMatch>
</VirtualHost>
</code>
Comment: We ran a wildcard domain SSL, so we could blog. subdomain to /folder; we tried mod proxy but found speed impacts.

so instead we put security policies on production servers preventing any data transfer, we then replicated the blog for a locked down admin server, and now we update patch, etc, there, then when done we git commit and use a deploy solution to push to our load balanced production servers.
Comment: @Daniel Scott...please share a sample config.


Stopping a threadpool on satisfied condition

Question: I'm using the ExecutorService to process thousands of small independent tasks. Each task, on completion, stores the result (which is either true of false).
So, instead of processing all of the tasks, I want to shutdown the threadpool prematurely, if a task has found the answer!
It feels like I'm missing something very obvious here...
Comment: How many cores do you have?  If you have say 4 cores, the optimal number of tasks may be 4. Perhaps you can have a small number of tasks which check all the results and a common flag to determine when to stop.
Answer: Consider using the invokeAny method.  It returns when just one is done.
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAny(java.util.Collection)
Comment: Actually, when one is done without throwing an exception. Which means that task results shouldn't be true/false but an exception unless the task found the answer.
Comment: I've tried invokeAny, where I've thrown an exception if task's result was false, but that ends the processing prematurely because I've caught that exception (because invokeAny is in a try-catch block). Is my solution to throw an exception on true, instead of false result?
Comment: invokeAny returns when any of the invoked callables return a value.  If you do not want the false results considered in this, throw an exception.
Comment: Ah yes, it works fine. My problem was throwing the RuntimeException on Interrupted & Execution exceptions. Thanks!
Answer: The desire you express reminds me of a Klein bottle, where there's little distinction maintained between what's "inside" and what's "outside." Here, the tasks submitted to the ExecutorService need to know that they must notify a latching gate outside the thread pool and shut it down when first transitioning from having seen no true task outcomes to having seen at least one.
I won't write the code for you, but I'll sketch the solution. It may help to define an interface on which the tasks must call when they complete:
interface TaskObserver
{
  void completed(boolean result);
}

Each task instance can be constructed with a reference to such a TaskObserver, on which the task body will call just before it completes and yields control back to the invoking ExecutorService. You could even write a base class to assist in participating in this protocol:
public abstract class ObservableTask implements Callable<Boolean>
{
  protected ObservableTask(TaskObserver observer)
  {
    if (null == observer)
      throw NullPointerException();
    observer_ = observer;
  }

  public final Boolean call()
  {
    final boolean result = evaluate();
    observer_.completed(result);
    return result;
  }

  protected abstract boolean evaluate();

  private final TaskObserver observer_;
}

Alternately, instead of using extension to define tasks, you could write a concrete class like this that accepts a reference to a Callable<Boolean> in its constructor in addition to the TaskObserver reference, and works through delegation instead.
Moving on, the implementation of TaskObserver will store an AtomicBoolean, which must be set to false initially. The body of the completed(boolean) method must attempt to set the AtomicBoolean from false to true if the result passed to completed(boolean) is true. If the transition from false to true is successful, shut down the ExecutorService and stop submitting any more tasks; any subsequent calls calls to the TaskObserver will come from tasks that had already been submitted and were too far along to comply with a cancellation request.
public void complete(boolean result)
{
  if (result &&
      latch_.compareAndSet(false, true))
  {
    // Set a flag to cease submitting new tasks.
    service_.shutdownNow();
    if (!service_.awaitTermination(timeoutMagnitude, timeoutUnit))
    {
      // Report a problem in shutting down the pool in a timely manner.
    }
  }
}

If that's not enough of a push to get you started, please follow up with additional questions.


Postgresql , comparar time extraido de um timestamp

Question: Necessito extrair as horas e minutos de um timestamp no mysql, eu tentei usar o maketime();
CREATE OR REPLACE FUNCTION agendar(dia timestamp) returns bool as
$$
declare

hora time := extract(hour from dia);
minuto time := extract(minute from dia);

horaminuto := maketime(hora,minuto,0);

porém acusa de sintaxe incorreta.
Eu preciso extrair a data e a hora para comparar e ver se o horario do timestamp atingiu ou não um limite de tempo. Por exemplo, um comercio que abre as 9:30 da manhã, preciso verificar se a hora que foi passada no timestamp se passa antes ou depois desse horario
Comment: A assinatura da função make_time é make_time(hour int, min int, sec double precision) e retorna um time.
A assinatura da função extract é extract(field from timestamp) e retorna um double precision.
Portanto a declaração das variáveis hora e minuto como time está incorreta, deveriam ser double precision ou mesmo um int.
Comment: Uma dúvida: você está trabalhando com o MySQL (como no texto de sua pergunta) ou com o PostgreSQL (como está na tag)?
Answer: Não entendi muito bem sua função, onde ela retorna o valor, onde declara variável, comparação... Eu estou acostumado com procedimentos ao invés de funções, talvez por isso, mas vamos lá, talvez te ajude um pouco a resolver sem criar uma função.
Você pode extrair as horas através desta função:
SELECT DATE_FORMAT(datetimeVariable, '%H') AS 'hora' FROM tabela

Onde o %H significa o flag de horas, por exemplo, para extrair minutos seria o flag %i:
SELECT DATE_FORMAT(datetimeVariable, '%i') AS 'minuto' FROM tabela

Agora se você quer uma maneira mais simples de comparar diretamente, tenta com essa função aqui:
SELECT Count(*) AS 'valido' FROM tabelaHorarios
WHERE TIME_TO_SEC(TIME(primeiroDatetime)) > TIME_TO_SEC('09:30:00') AND
id='1'

O que acontece é que, ele vai retornar 0 se o primeiroDatetime não tiver passado das 9h30, do contrário, um valor maior do que 1, para quantos dados ele encontrar... o id você define qual valor da tabela você quer testar... Por que isso? Provavelmente seu sistema vai comparar 1 mês do comércio, para ver em que dias fechou, certo? Você pode definir um range do mês inteiro e contar quantos dias do mês o comércio abriu após as 9h30...


Better Exposed Filters

Question: I have created a view block to display filter options. But in BEF settings I dont get check box options. Can anybody help me out.
Thank you in advance
embeeke
Comment: Can you please add screenshot?
Comment: Hello and welcome. You stated a fact. Could you please now ask a question?
Comment: how to add filters as checkbox list using BEFs.
Comment: Have you read the BEF module documentation it says: "Most BEF features are available with filters that have a limited number of options" Make sure the field you using as exposed filter have limited number of options.
Comment: Can you please elaborate @MutantMahesh
Comment: @embeeke BEF's documentation says that BEF features are available for filters that have limited number of options, that means any field which have a limited number of option can be exposed as select list or checkboxes e.g term reference field have limited terms then it can be exposed as BEF. but not node title which can't be exposed as BEF checkboxes because there can be any number of nodes on a drupal site.
Comment: @embeeke from your screenshot it looks like you are using term reference field as exposed filter, then BEF should give checkboxes option. If its not working in your case then try with dev version of BEF module.
Comment: @mutantMahesh Hi i tried d dev version. But nothing changed.
Comment: Can you provide the detailed info of the field you are using as exposed filter?
Comment: i am using 5 fields with term references. added them in view fields, exposed them as filters and in BEF settings i am not able to get the checkbox options
Answer: I tried on my local with

drupal 7.30-dev
views 7.x-3.7
better exposed filter 7.x-3.0-beta4

Added term reference field in article content type. Created a view, added this term reference field as exposed filter i was able to get the checkboxes for tid.
Make sure the term reference field setting is set to "Dropdown" and Use Ajax options is set to "yes".

After setting term reference field setting to "Dropdown" i was able to see the "Checkbox/radio buttons" options in better exposed filter setting.
Comment: Hey thank you so much, i got it. But the auto submit feature is not working. can you guide me on this.. Thank you
Comment: In BEF setting there is option for Autosubmit. Check that option. you can see that in above screenshot. Please accept answer if that helped.
Comment: ya i checked autosubmit option. and another problem is, i get an error after creating the view "An illegal choice has been detected. Please contact the site administrator."
Comment: This error occurs when I select dropdown as filter criteria setting
Comment: Have you created those option in hook_form_alter? or modified the select list options in other way? This error occur due to type mismatch. This error occur when you add new value in a select list which is other then the type of value allowed in that list. For example if you add 'string' value in select list option if only 'integer' values are allowed in that select list.
Comment: no i have not created anything in hook_form_alter
Comment: There are lots of questions asked for this problem. See here http://drupal.stackexchange.com/search?q=An+illegal+choice+has+been+detected you may find you answer. Please accept my answer if that helped. Thanks

Better Exposed Filters


Inverse element in a magma

Question: Given $(S,*)$ a magma and an identity element $e$. The inverse of $x\in S$ is $y$ such that $x*y=e=y*x$.
Is it correct to say that if $x$ is the inverse of $y$ then $y$ is the inverse of $x$?
Answer: It is correct to say that, if $x$ is an inverse of $y$ then $y$ is an inverse of $x$, the property $x*y=e=y*x$ is symmetric, it remains the same after swapping $x$ and $y$ and getting $y*x=e=x*y$.
Without associativity you won't be able to prove that inverses are unique however.
Comment: Quite. @AndreaK, observe the indefinite articles.

Inverse element in a magma


Conditional Probability Equivalence

Question: I am reading this paper here: http://www.utm.utoronto.ca/~weisber3/articles/SobervBJPS3.SP.pdf which claims on page 10 that $p(E \wedge [H_x \wedge \sim R]) + p(E \wedge [H_x \wedge E])= p(H_x \wedge E)$. I am having trouble seeing this equivalence.
Any help is appreciated; thank you in advance.
Answer: It doesn't.  That step is erroneous, as is the one prior (the sum-rule is only valid when the two events are mutually exclusive, which they clearly are not).
However, both are also unnecessary, as: $[E\wedge [H_x\wedge \neg R]] \vee [E\wedge [H_x\wedge E]]) = E\wedge H_x$ , thus you immediately have the desired result.
$$p([E\wedge [H_x\wedge \neg R]] \vee [E\wedge [H_x\wedge E]])
\\[2ex] = p([[E\wedge H_x]\wedge \neg R]\vee [[E\wedge H_x]\wedge E])
\\[2ex] = p([[E\wedge H_x]\wedge \neg R]\vee [E\wedge H_x])
\\[2ex] = p([E\wedge H_x])
$$
Comment: There is some confusion in your response. You say that the step is erroneous however you say that $[E∧[H_x∧\sim R]]∨[E∧[H_x∧E]]) = E∧H_x$ does hold. However, this is equivalent to exactly the sequence of equalities which you have given.

So which is it - do you think that the equality which I am asking about is erroneous or is it redundant? It cannot be both.
Comment: @letsmakemuffinstogether   It's a case of two wrongs accidentally make a right.  The author knew where to go but wandered off on a false path to get there. $$p([E\wedge [H_x\wedge\neg R]] \vee [E\wedge [H_x\wedge E]]) \underbrace{\neq p(E\wedge [H_x\wedge \neg R]) + p(E\wedge[H_x\wedge E]) \neq}_{\text{but ignore this as the end terms are equal to each other}} p(E\wedge H_x)$$$$p([E\wedge [H_x\wedge\neg R]] \vee [E\wedge [H_x\wedge E]]) = p(E\wedge H_x)$$
Comment: I do not accept that the first inequality is an inequality; $\sim R$ and $E$ are probabilistically independent so it is a valid inference to conclude that $p([E\wedge [H_x\wedge\neg R]] \vee [E\wedge [H_x\wedge E]]) \underbrace = p(E\wedge [H_x\wedge \neg R]) + p(E\wedge[H_x\wedge E])$. How is the first inequality an inequality?
Comment: @letsmakemuffinstogether That is for **mutually exclusive** events (also known as *disjoint* events). It is *not* the case for independent events; where in fact: $$p(A\vee B) = p(A)+p(B)-p(A\wedge B) \\ \mathop{=}^{\text{ind}} p(A)+p(B)-p(A)p(B)$$
Comment: My mistake in using the incorrect terminology. This being so, I still maintain that $\sim R$ and $E$ are $\bf{mutually \ exclusive}$ events. As defined on page 10 of the paper, $\sim R$ is defined as ``I do not return to check my net in two weeks' time" and $E$ is defined as: ``I'll find fish that are 10+ inches are in the net". This follows because it is not possible for someone to fail to check their net yet also $find$ fish in their net as 10+ inches.  Or do you dispute this? Do you at least grant that $if$ $R$ and $E$ are mutually exclusive events, then the equality holds?

Conditional Probability Equivalence


How to handle caching on a Drupal 8 custom Views access plugin that checks a User's Profile's field value

Question: I have a custom Views access plugin that check access against a value in the current User's Profile (entity) field value.
The plugin works but if I change the profile field value the access does not check again until the cache is cleared. I know this is an issue with setting up the cache tags/contexts but I cannot not figure out what is needed so that the cache is cleared when the user profile is updated.
Right now I'm not using any cache tags/contexts in my View access plug and I've tried various combinations without luck. Help!
Current cache functions:
<code>public function getCacheMaxAge() {
    return Cache::PERMANENT;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return ['user'];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    $profile = \Drupal::entityManager()->getStorage('profile')->loadByUser(user_load(\Drupal::currentUser()->id()), 'employee');
return $profile->getCacheTags();
  }
</code>
Answer: A Views access plugin implements CacheableDependencyInterface. So you probably need to set a tag and a context for the current user in these methods:
<code>  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return Cache::PERMANENT;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return ['user'];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return ['user:' . \Drupal::currentUser()->id()];
  }
</code>
Comment: Thank you! I was not adding the current user ID to getCacheTags - makes perfect sense now.
Comment: Actually, I spoke too soon. The caching is still not clearing properly. The cache tags example you provided is using the user object but the field value that I am changing is on the Profile object for the user. Is there a way to set the cache contexts to use the Profile object of the user?
Comment: I've supposed you mean with user profile the core user entity, because core often refers to the user content form as profile, but if this is from a contrib module, then load the profile entity the same like you did for the field value and return the cache tag from this entity `$profile->getCacheTags()`. This is only for the tag, the context is still a dependency on the current user.
Comment: Thanks again. I still can't get it to work. And, yes, sorry, by profile I was referring to the contrib profile module that creates 'profile' entities for the user objects. I've edited my original question to include my current cache functions. I am loading the profile entity in getCacheTags() and returning it as return $profile->getCacheTags() - the getCacheContexts() is set to return ['user']
Comment: How would this work for anon user. For example, test a language variable...


Is this ambiguity in the use of prime notation to denote a derivative?

Question: Consider the function $f(x)$ and let $g(x)=f(cx)$.
By the definition of derivative
$$f'(x)=\frac{df(x)}{dx}=\lim\limits_{h \to 0} \frac{f(x+h)-f(x)}{h}\tag{1}$$
and so the definition of $f'(cx)$ is
$$f'(cx)=\frac{df(cx)}{d(cx)}=\lim\limits_{h \to 0} \frac{f(cx+h)-f(cx)}{h}\tag{2}$$
Also
$$g'(x) = \lim\limits_{h \to 0} \frac{g(x+h)-g(x)}{h}$$
$$=\lim\limits_{h \to 0} \frac{f(c(x+h))-f(cx)}{h}$$
$$=\lim\limits_{h \to 0} \frac{f(cx+ch)-f(cx)}{h}$$
$$=c\lim\limits_{h \to 0} \frac{f(cx+ch)-f(cx)}{ch}$$
$$=cf'(cx)$$
Hence
$$g'(x)=cf'(cx)$$
I am not sure if I am seeing an inexistent ambiguity, but $f'(cx)$ seems like ambiguous notation.
As defined above in $(2)$, $f'(cx)$ means the derivative of $f$ relative to $cx$, evaluated at a point we call $cx$, .
Note that this is different than the derivative of $f$ relative to $x$ evaluated at a point $cx$: this derivative is $g'(x)=\frac{df(cx)}{dx}$. In "prime" notation, how do we denote this latter derivative? It would seem to be $f'(cx)$, but I think either this is incorrect, or the definition given in $(2)$ is somehow non-standard.
For example, let $$f(x)=3x^3$$ $$g(x)=f(cx)=3c^3x^3$$
Then
$$f'(x)=\frac{df(x)}{dx}=9x^2$$
$$\left.\frac{df(x)}{dx}\right \vert_{x=cx}=9c^2x^2\ \ (=f'(cx)???)$$
$$g'(x)=\frac{df(cx)}{dx}=c\frac{df(cx)}{d(cx)}=c\cdot f'(cx)=c\cdot 9c^2x^2= 9c^3x^2\tag{3}$$
In this example, $f'(cx)=\frac{df(cx)}{d(cx)}=9c^2x^2$ according to definition I gave in $(2)$.
But perhaps more intuitively, it could also be $f'(cx)= \left.\frac{df(x)}{dx}\right \vert_{x=cx}=9c^2x^2$
Note that both uses of $f'(cx)$ lead to the same result in this example.
Which use of $f'(cx)$ is the "correct" or "standard" one?
Comment: $f'(cx)$ means $f'$ evaluated at $cx$. It is not equal to $g'(x)$.
Comment: As I derived in my question, $g'(x)=cf'(cx)$. However, the definition of $f'(cx)$ is given in $(2)$. Is the latter definition correct/standard?
Answer: This is definitely potentially confusing, but not an ambiguity.
The object written $f$ is a function, which takes an input and gives an output. The object written $f'$ is also a function, which is defined using the function $f$. If $f$ is the function which squares its input (usually written like $f(x)=x^2$), then $f'$ is the function which doubles its input (usually written like $f'(x)=2x$). It's also true that $f'(cx)=2cx$, because $f'(cx)$ does not mean "the derivative of $f(cx)$," it means "the function $f'$ evaluated at an input of $cx$."
Your expression (2) is a correct application of the definition (1), although it would be odd to call it a definition itself. I do not know of a way to write "the derivative of $f(cx)$ as a function of $x$" in prime notation, besides by writing a new function $g(x)$ defined by the rule $g(x)=f(cx)$, from which "the derivative of $f(cx)$ as a function of $x$" is $g'(x)$.
Comment: Actually I think the root of the confusion is the expression $g'(x)=\frac{df(cx)}{dx}$. We can't actually write $f'(cx)$ here, because as you said, there is no prime notation for "the derivative of $f(cx)$ relative to $x$".
Comment: @evianpring Yes, $\frac{df(x)}{dx}\bigg|_{x=cx}=\frac{df(cx)}{d(cx)}$.
Comment: How do you conciliate your explanation with my definition $(2)$? Is my definition non-standard? According to that definition, and using your example, we'd have: $f(x)=x^2$, $f(cx)=(cx)^2$, $f'(cx)=2cx$.
Comment: @evianpring I've updated my answer. The expression in (2) follows logically from the definition of the function $f'$ from (1).
Comment: Is $\left . \frac{df(x)}{dx} \right \vert_{x=cx}=\frac{df(cx)}{d(cx)}$ a true statement for all x? The left side means "the derivative function $f'$ evaluated at a point $cx$, ie the value of the slope of $f$ at $cx$", the right side means "the derivative of the function $f$ at a point $cx$, ie the slope of  of $f$  at $cx$". Writing it out like this, it would seem this is true.
Comment: @evianpring: $(f \circ c \cdot \mathrm{id})'$
Answer: I just want to emphasize one thing. You don't take the derivative of a function "relative to something". The derivative of a function $f:\mathbb R \to \mathbb R$ is always taken "with respect to" one thing and one thing only: its entry.
If you want to see how the quantity $f(cx)$ varies when $x$ varies, then you should think of it as defining a new function $g$ by $g(x)=f(cx)$ (because you want to vary $x$) and then differentiating this new function $g$.
My main point is that you have one operation that acts on functions and spits out functions: the derivative. It takes $f$ and gives you $f'$ back. It takes $g$ and gives you $g'$ back. After that, you can evaluate these functions wherever you want. The relation that you correctly found
$$g'(x) = cf'(cx)$$
reads like this: when you evaluate the function $g'$ at the point $x$, you obtain the same number as if you were to evaluate the function $f'$ at the point $cx$ and multiply the result by $c$.
That's it. No "with respect to"s involved.
Answer: This is just a supplementary part to the nice answer of @KarlSchildkraut. I think it is helpful to consider the complete definition of functions and look at their relationship somewhat more detailed.
The setting more detailed:
We start with a differentiable function
\begin{align*}
&f:\mathbb{R}\to\mathbb{R}\\
&x\mapsto f(x)
\end{align*}
When we now consider
\begin{align*}
g(x)=f(cx)
\end{align*}
we have a function $h$
\begin{align*}
&h:\mathbb{R}\to\mathbb{R}\\
&x\mapsto h(x)=cx\\
\end{align*}
and a function $g$
\begin{align*}
&g:\mathbb{R}\to\mathbb{R}\\
&x\mapsto g(x)=\left(f\circ h\right)(x)\\
\end{align*}
which is the composition of $f$ with $h$. It follows according to the definition of $h$ and $g$ :
\begin{align*}
g(x)=\left(f\circ h\right)(x)=f(h(x))=f(cx)
\end{align*}
Differentiation: Two different situations
As @KarlSchildkraut said there is no ambiguity, but we have different situations instead. On the one hand we have
\begin{align*}
\color{blue}{f^{\prime}(cx)=f^{\prime}(u)\big|_{u=cx}}
\end{align*}
which is the differentiated function $f$ evaluated at a point $u=cx$. On the other hand we have
\begin{align*}
\color{blue}{g^{\prime}(x)}&\color{blue}{=\left(f\circ h\right)^{\prime}(x)}=\left(f(h(x)\right)^{\prime}=\left(f(cx)\right)^{\prime}\\
&=f^{\prime}(h(x))h^{\prime}(x)\\
&\,\,\color{blue}{=f^{\prime}(cx)c}
\end{align*}
which is the differentiation of a composition of functions. So, we have two different situations.
Comment: And just to make it crystal clear, after the last step we could write $=f'(u) \vert_{u=cx}c$, correct?
Comment: @evianpring: Yes, this is correct.


How can I delete a poorly named vocabulary?

Question: I've created a couple of vocabularies programmatically, and accidentally included some spaces in the machine names (caused by bad data in an input CSV). I can't delete these vocabularies with Vocabulary::load($vid)->delete();, even though I can see the vocabularies names with
dsm(taxonomy_vocabulary_get_names());, while load($vid) returns NULL.
Any ideas on how I can delete these vocabularies? I was able to delete all the terms in a vocabulary, but the reference remains under admin/structure/taxonomy.
Comment: I assume you tried to delete them via the UI?
Comment: I did.  It seemed to partially delete the vocabulary and left it in an unstable state
Answer: Where are you calling that code? Is the $vid really right? You say it has spaces in it? Did you try to delete them from the UI?
Under /admin/structure/taxonomies where you have all vocabularies listed, open the operations dropdown and click "Edit vocabulary".

On the next page click "Delete".
Answer: Try to delete it from UI if that doesn't work. Install devel_generate module which is included in devel module as a sub module and select option to generate vocabulary and give count as 0. Don't forget to select delete existing vocabulary. It will delete existing vocabulary which will solve your problem.
Answer: To clarify - deleting the vocabulary through the UI allowed some of the menu choices, but not others.
I fixed it by doing a database dump and edited the dump with a search and replace (my vocabulary to my_vocabuary) and then importing the edited dump before deleting with the UI.
Not an elegant solution, but it worked.
Comment: did you try with devel_generate , If I remember correctly I was have similar issue and got resolved by it.


What is the shortest non-trivial logical deduction about overlapping circles?

Question: For line segments in a 1D infinite space the shortest non-trivial statement I can think of is:
"For line segments $A$, $B$ and $C$. If there are regions where (at least) $A$ and $B$ overlap and regions where $B$ and $C$ overlap and regions where $A$ and $C$ overlap there must be a region where $A$, $B$ and $C$ overlap."
Now in a 2D infinite plane with a number of filled circles $A,B,C,D...$ , you are told some incomplete information about if there are areas where the circles overlap and which circles these are. What it the simplest non-trivial logical deduction that one could make from this information about overlaps in the same sort of way as was done with line segments?
Comment: If you really just want the "simplest" deduction then this is surely opinion-based.
Comment: Well OK, by simplest I mean fewest circles and shortest statement.
Comment: Same as the line segments.  If A and B intersect, B and C intersect, C and A intersect, then there is a region (possibly a point) where all 3 intersect
Comment: @NazimJ Not true! You could have a hole in the middle!
Answer:
If three or more (but only finitely-many) circular regions in the plane are such that any three have a point in common, then all of them have a point in common.

(The case of three regions is, of course, tautological, but including it makes for the most-complete statement of the result.) This, and OP's segment example, are special cases of Helly's Theorem, which can be expressed as:

If $d+1$ or more (but only finitely-many) convex subsets of $\mathbb{R}^d$ are such that any $d+1$ of them have a point in common, then all of them have a point in common.

(Again, the case of $d+1$ subsets is tautological.) As the Wikipedia article notes, the version of the theorem for infinitely-many regions requires the regions to be compact as well as convex.

It's worth noting that the topology of $\mathbb{R}^d$ is important here. If OP's example were not about segments on the line but arcs on a circle, pairwise intersections do not imply a common intersection. Nor does the statement I mentioned if "circular regions in the plane" is replaced by "caps on the sphere".
Comment: Thanks. That answers the question.
Comment: BTW Is there a version of Helly's theoream where the N-spheres are on a the surface of an (N+1)-sphere?
Comment: A web search for "Helly theorem on sphere" turns up a number of references to "Helly-type" results.


Certificate Not showing on the Web console

Question: On a Windows 2008 R2, with an AD level of Windows 2008 R2
We need to create a cert to allow user/admin to enroll via the Web service page (https://CA/certsrv/)
On CA, right-click Certificate template and select manage
In the certificate template, we've created a duplicate of an existing cert, and configured it with a new name
- The cert has domain computer with read/enroll permission
- Supply in the request is selected
I ran certutil -setCAtemplates  to add it to the cert template
On the web service page https://CA/certsrv > Request a certificate > Advanced certificate request > Create and submit a request to this CA, we only see a short list of certificate template
Does anyone have idea to how to publish a cert to be shown on the web page?
What step am I missing here
Answer: The two most common problems I see with this are either permissions related or template version related.
The user logged into the certsrv site needs to have both Read and Enroll permissions on the certificate template.  If they don't, it won't show up in the list of available templates.
Also when duplicating the template, you were likely asked what version to make it and given an option of "Windows Server 2003" or "Windows Server 2008".  The certsrv web site is only compatible with the Windows Server 2003 based templates which I think corresponds to version 2.  Ironically, this same limitation is present all the way through Windows Server 2012 R2. The certsrv site still can't use version 3 templates. Here's the related KB article as you found:
Version 3 (CNG) Templates Will Not Appear in Windows Server 2008 or Windows Server 2008 R2 Certificate Web Enrollment
Comment: Thank you for your answer. Mine had the required permissions on it (read/enroll). I did see a pattern that only pre-2003 were listed. I've used the same process to duplicate another cert to validate my steps and set it to 2003 instead of 2008, and it did showed up. My issue with the certsrv site not show my certificate was infact related to version3 as you have suggested. I wouldn't have thought to look at compatibility without your answer. TY https://support.microsoft.com/en-us/kb/2015796
Comment: Man I knew there was a KB article for it. I just couldn't find it the when I looked. They should reallly update it to apply to 2012 and 2012 R2 as well.
Comment: Having read several articles on this problem using Windows Server 2008 R2 (this is in a lab), stumbled upon this answer - my problem was the same - had to create a new template based on compatibility with "Windows Server 2003" and then it showed up in the certsrv site.  +1


Sequência de Fibonacci em C

Question: Tô fazendo um exercício da faculdade em que o usuário deve digitar um número e o programa deve retornar a sequência de Fibonacci. Porém, segundo o professor, ele deveria começar no 0 (ZERO), mas meu programa começa no 1.
Obs.: O professor já corrigiu e não aceitará mais modificações, eu quero mesmo é entender porque meu programa não imprimi o zero, uma vez que declarei a = 0.
Programa:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <locale.h>

main() {

    setlocale(LC_ALL, "Portuguese");

    int a, b, auxiliar, i, n;

    a = 0;
    b = 1;

    printf("Digite um número: ");
    scanf("%d", &n);
    printf("\nSérie de Fibonacci:\n\n");
    printf("%d\n", b);

    for(i = 0; i < n; i++) {

        auxiliar = a + b;
        a = b;
        b = auxiliar;

        printf("%d\n", auxiliar);
    }
}

Desde já agradeço galera.
Comment: Porque o seu primeiro elemento da sequência é `b`, não `a`; veja `printf("%d\n", b)`
Comment: Cara, que erro ridículo...
Agradeço aí brother. Vou criar uma resposta com a resolução. Abraços.
Comment: Mas você quer alterar o programa para que comece com fib(0) ? Para que fique 0, 1, 1, 2, 3, 5 ... ?
Comment: Não, @Isac, ele quereria fazer `printf("%d\n", a);` no lugar de `printf("%d\n", b);` porque ele é uma pessoa engraçada... [facepalm]
Answer: Na verdade, faltaram algumas coisas:

O printf("%d\n", b); deveria ser if (n >= 1) printf("%d\n", b);
Antes da linha acima, teria que vir if (n >= 0) printf("%d\n", a);
O for teria que ser for (i = 2; i <= n; i++) { ... }

O { ... } acima significa:
{
    auxiliar = a + b;
    a = b;
    b = auxiliar;

    printf("%d\n", auxiliar);
}

Answer: int i, n, a=0, b=1, pt=0;
printf("Informe um número, para ter sua sequência de Fibonacci\n");
scanf("%i", &n);
i=1;
do{
  if(i==1){
  b=0;
  }
  if(i==2){
  a=0;
  b=1;
   }
  if(i==3){
   a=0;
   b=1;
  }
  pt=a+b;
  a=b;
  b=pt;
  i++;
  printf("%d\n", pt);
  }
while(i<=n && pt<n);
do{
  if(i==1){
  b=0;
  }
  if(i==2){
  a=0;
  b=1;
   }
  if(i==3){
   a=0;
   b=1;
  }
if(n>=1 &&n<=6){
  pt=a+b;
  a=b;
  b=pt;
  i++;
  printf("%d\n", pt);

}
}
while(i>n && pt<n);

return 0;

}
cara tá ai o programa completo sem erros da para fazer algumas alterações para deixar ele mais enxuto mas funciona mesmo assim
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Answer: #include <stdio.h>

int main(void)
{
    int n, fib = 0, aux = 0;
    printf("Informe um numero para calcular a seq. de Fibonacci.\n ");

    scanf("%d", &n);
    while(fib <1000)//Só vai mostrar até 1000
    {
        printf("%d-", fib);
        fib = fib + aux;
        aux = n;
        n = fib;
    }
  return 0;
}

Comment: Por favor, adicione mais detalhes para expandir sua resposta, como um código que funcione ou citações de documentação.

Sequência de Fibonacci em C


How can I remove the default generated  tags in view's result?

Question: I am using a views in my drupal web site. I have set 'style' to 'Unformatted' and 'Row style' to 'Fields'
Also I have Rewrote the output of the field with my HTML tags.
But I have a problem in the result.
Every row is located inside a [div] tag
for example the first row is located in

How can I setup the view in order to remove this extra [div] tag ?!?!?
I don't need this wrapper.
Answer: The easiest thing to do is copy the template files from "sites/all/modules/views/theme/" into you theme (I normally make a "views/" subdirectory).
If you want to make this change for all themes, edit "views-view-unformatted.tpl.php".
If you want to just change that view, edit the view then click on the Theme: Information link.  It will show the template suggestions for the view.  Copy
If you want to make this change for all themes, copy "views-view-unformatted.tpl.php" to the proper name, and edit that file.
In both cases, make sure you clear the Drupal caches to make sure the system finds the new files.
Answer: If you don't want to touch the theme you could use Semantic Views module to strip all the extra div's.
Comment: @MPD it does on my site :)
Comment: Does the Drupal 7 version work well?
Comment: @nathan6137, thanks.  I have been hesitant to use it on a client site b/c there hasn't been activity of the project in a while.
Comment: Semantic Views is not necessary if you are using Views 3.x - the functionality of SV is wrapped into Views core. http://drupal.org/node/740686
Comment: @sheena_d, did all of the SV functioality get folded in?  I thought it was just fields and that you couldn't pick elements for things like how rows in an unformatted list get generated.
Comment: @MPD - you're right, I was remembering wrong. You can assign a class to the row wrapper, but you cannot actually affect it from the Views UI.
Answer: This solution combines and builds on David Paul's and MDP's solutions and  removes the
 in a consistent way for all views that are properly configured without additional modules.
Drupal 7 & 8+
Step 1:
Disable all class configurations in the Style options of the view's Format section.
You must do this for any and all views that you want to remove the wrapper from:

Drupal 7
Step 2: Copy views-view-unformatted.tpl.php from the Views module into your theme's templates folder  and modify the logic to ignore the div when classes are empty.
Change the following lines from:
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
  <?php print $row; ?>

to:
<?php if ($classes_array[$id]) : ?><div class="<?php print $classes_array[$id]; ?>"><?php endif; ?>
  <?php print $row; ?>
<?php if ($classes_array[$id]) : ?>
<?php endif; ?>

Drupal 8+
Step 2: Copy views-view-unformatted.html.twig from the Views module into your theme's templates/views/ folder  and modify the logic to ignore the div when {{row.attributes}} are empty.
Change the following lines from:

  {{ row.content }}

to:
{% if default_row_class or row.attributes is not empty %}

  {{ row.content }}

{% else %}
  {{ row.content }}
{% endif %}

Honestly, I'm not sure why the Views module doesn't do this itself...  its a total WTF and could be a nice improvement for Themer's eXperience.
Comment: THIS is the correct answer
Comment: I've added instructions now for Drupal 8 to this answer.
Comment: Should be the accepted answer in my opinion.
Comment: would be even better if the row-class could be added to the row.content without creating that extra div at all
Comment: Not sure I understand how that would work.  This is literally the only wrapper you get around the views results,  the only other wrappers are at the individual row level.
Answer: You want to look into the Theming: Information section and override one of the styled templates for your view. That's where the stuff happens. Be sure to use the Rescan button when you create an appropriately named tpl file, so that Drupal picks it up.
Answer: To remove this in Drupal 7 you can click on the Fields settings and turn off "Provide default wrapper elements"
Answer: If you're on Drupal 7 then you don't need to play with template files to remove the wrapper divs.  Those wrappers come as part of the output, which suggests they can be controlled in the view, which they can.
Under FORMAT > Show: fields | settings - click settings, then uncheck the wrapper option.  That's it.
Comment: that is not entirely true, even if you uncheck wrapper options, views would not let you remove all divs
Answer: I have achieved this by overriding views-view.tpl.php file. Copy this file from views module into your theme directory and remove the beginning wrapper.

Also remove the div wrapping the $rows.


different object type returned than the one in function body swift objc

Question: I have been searching day and night for this. I seem to be the first one getting such an annoying error. I have a swift app and have imported an objective C framework(XlsxReaderWriter) by cocoa pods. Everything is working except Nothing is returned as the type specified in the functions in the objective C framework. Everything is returned as Any.
Forexample;
inputFile: BRAWorksheet = file.workbook.worksheets![0] //this gives me a compile error saying "Can not assign value of type Any to BRAWorksheet"

and here is the property declaration in objective C
- (NSArray *)worksheets {
    NSMutableArray *worksheets = @[].mutableCopy;

    for (BRASheet *sheet in _sheets) {
        BRAWorksheet *worksheet = [self.relationships relationshipWithId:sheet.identifier];
        worksheet.styles = _styles;
        worksheet.sharedStrings = _sharedStrings;
        worksheet.calcChain = _calcChain;
        [worksheets addObject:worksheet];
    }

    return worksheets.count ? worksheets : nil;
}

even in the documentation for the library, that is how they do it;
var firstWorksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0]

So can anyone tell me what this strange error is please?? I am getting desperate.
PS: I do not want to cast for some reasons
Answer: Instead of NSArray *, set the return type of the method to NSArray<BRAWorksheet *> *.
Comment: Thank you @Charles Srstka. But can you edit your question and include the updated version of `Worksheets`? I dont have enough experience in Objective C
Comment: In the body of your code, you can just do the same thing to the declaration: change `NSMutableArray *worksheets` to `NSMutableArray  *`. In general, you should always add the contained type in brackets after NS(Mutable)Array, if you're interacting with Swift. `NSArray  *` will bridge to `[Foo]`, whereas just `NSArray *` will bridge to `[Any]`.