Different approaches to differentiability in $L^2$

Question: We can use different approaches to differentiability of $L^2(\mathbb{R})$ functions, e.g. we can say that $f\in L^2(\mathbb{R})$ is differentiable iff $f$ has a differentiable version (representative). In this case $f$ has a strong derivative. Or we can consider differentiability almost everywhere, though in this case we can lose a lot of information about a function, for example both constant function and Cantor function would have $0$ as a derivative.
I'm interested in three following approaches to define derivative in $L^2$:
we say that $g$ is derivative of $f$ iff

there exist such $c\in\mathbb{R}$ and version $\tilde{f}$ of $f$ that $\tilde{f}(x)=\int\limits_0^xg(t)dt+c$
for all $\varphi\in C_0^\infty(\mathbb{R})$ we have $\int\limits_{\mathbb{R}} (g\varphi)=-\int\limits_{\mathbb{R}} (f\varphi')$
$\hat{g}(\xi)=2\pi i\xi\hat{f}(\xi)$

First one is the most intuitive. For any $g\in L^2(\mathbb{R})$  the integral exists since $L^2[c,x]\subset L^1[c,x]$.
Second approach is based on embedding $L^2(\mathbb{R})$ into the space of generalized functions, taking derivative there and getting back to $L^2(\mathbb{R})$ if possible. Here we have to choose the space of base functions, and the smaller this space is, the wider the set of differentiable functions becomes. So the natural question is what particular space of base function should we choose to make this definition equivalent to the first one (or the third).
Third approach comes from the property of Fourier transform for strong derivatives.
So my questions are about equivalency of those three approaches and the problem of choosing the space of base function in the second one.
Answer: Let $f,g \in L^2(\mathbb{R})$. Consider the following three (slightly corrected variants of your) definitions:

The function $g$ is a derivative of $f$ if there exists $\tilde{f}$ with $\tilde{f} = f$ a.e and $\tilde{f}(y) - \tilde{f}(x) = \int_x^y g(t) \, dt$ for all $x,y \in \mathbb{R}$.
The function $g$ is a derivative of $f$ if for all $\varphi \in C^{\infty}_c(\mathbb{R})$ we have $\int_{\mathbb{R}} g \varphi = -\int_{\mathbb{R}} f \varphi'$.
The function $g$ is a derivative of $f$ if $\hat{g}(\xi) = 2\pi i \xi \hat{f}(\xi)$.

Definition one was modified because your definition doesn't work even if $f$ is $C^1$ unless $f(c) = 0$ and also to handle functions that might a priori not be continuous. Definition two was modified because even if $f$ is $C^1$, integration by parts introduces a sign factor and we've also replaced the space of tests functions $C^{\infty}_0(\mathbb{R})$ (which I interpret as smooth functions vanishing at infinity) by $C^{\infty}_c(\mathbb{R})$ (smooth functions with compact support) because otherwise, the integrals aren't even necessarily defined.
It turns out that all three variants above are equivalent and in this case, we say that $f$ belongs to the Sobolev space $H^1(\mathbb{R}) = W^{1,2}(\mathbb{R})$. You can find the proof of the equivalences above in most books that talk about Sobolev spaces (for example, in "Functional Analysis, Sobolev Spaces and Partial Differential Equations" by Haim Brezis and in "Partial Differential Equations" by Lawrence C. Evans).
Comment: Thank you for the answer! That's what I meant, I made those mistakes out of sloppiness :( Also by $C_0^\infty$ I meant smooth functions with compact support. I've corrected it in the question. Thanks for the conformation of equivalence, gonna go hit the books :)
Comment: From Brezis's book: "To define $W^{1,p}$ one can also use the language of distributions (see L. Schwartz [1] or A. Knapp [2]).<...> When $I = \mathbb{R}$ and $p = 2$, Sobolev spaces can also be
defined using the Fourier transform; see, e.g., J. L. Lions–E. Magenes [1], P. Malliavin
[1], H. Triebel [1], L. Grafakos [1]. **We shall not take this viewpoint here.**"
Comment: That's why I also added Evans's book. He discusses the Fouriet point of view.
Comment: Okey, I just thought of another one. For any $f\in L^2$ we can choose a sequence $\{\varphi_n\}$ of $C_0^\infty$-functions that converges to $f$ in sence of $L^2$-norm. If there exist such $g\in L^2$ that $\{\varphi_n'\}$ converges to $g$, we could say that $g$ is derivative of $f$. Is $g$ invariant under different chose of $\{\varphi_n\}$? Will it be weak derivative?
Comment: This is also equivalent. By dominated convergence theorem and integration by parts, you can show that $g$ is a weak derivative of $f$ in the sense of definition $(2)$ above and by uniqueness of the weak derivatives, it will be invariant under different choices of approximating sequences. The other direction is harder. Unfortunately, I don't know of a single reference that discusses all of this.
Comment: Great, thanks! By all of this you mean all approaches to define weak derivative? Do you know where to look up the proof of the other direction which you say is harder?
Comment: Yeah. Regarding the harder direction, you can find it in the book "Sobolev Spaces" by Robert A. Adams, page 70, corollary 3.23 (for the more general case of $\mathbb{R}^n$).


is this song written in dorian or mixolydian mode?

Question: i have a question about the modes hopefully someone sees this
if a song follows a chord progression of
verse
Bb-Ab-Eb
Bb-Ab-Eb
then pre chorus
Ab-Eb-Bb //
Ab-Eb-Db-Eb
and then the chorus is
Bb-Ab-Eb
Bb-Ab-Eb
verse 2 (same chords as verse 1)
pre chorus 2 (same chords as pre chorus 2)
...
is it in Bb mixolydian mode or Dorian mode? i thought it was mixolydian until i heard the Db. but then again that Db is only present twice in the whole song.
thoughts? i hope someone can help me with this :) thanks everyone!
Comment: Dorian surely not. And if it was mixolydian ... how could you explain all the Bb chords? I would not bother a lot about the modes, but if you want to know my opininion, I would say this key  is Eb major beginning V-IV with a borrowed chord Db as substitution of the dominant Bb.
Comment: @AlbrechtHügli - My thought also.
Comment: @AlbrechtHügli thank you! But I would say Bb is the key because it feels like the tonal home of the song. Like, the whole song revolves around it. Eb major doesn't feel that way at all so it's pretty confusing to me
Answer: Certainly not Dorian. Dorian is a minor mode, having m3. Since there are no minor chords in sight, it cannot be that.
With B♭ E♭ and A♭ chords, it sits quite well to being in key E♭, the D♭ being ♭7, which is not unusual, and could point to E♭ Mixolydian, which would indeed contain a D♭ note. Mixolydian has a 'seventh' sound to it, and the chords may well be 7ths - none here though. E♭ major seems likely. What's the key sig?
Comment: thank you for your answer at first I thought it could be Eb mixolydian also (the Db could be a 7th chord - I got the chords by ear, and sorry I posted this very late) or just Eb major. but I'd say Bb is the key signature because Bb just feels like the tonal home of the song meanwhile Eb doesn't. For example when I play Bb at the end of the song it sounds like a perfect ending but that is not the case with Eb. I hope i explained it well
Answer: All the chords are Bb, Ab, Eb in that order (which eschews a descending fifth progression, common in rock) ...except the one Db which is just interposed between two Eb chords.
The only thing you can get from that is a likely key signature of three flats with a Db thrown in.
You could label it like a blues turnaround V IV I that would make the tonic Eb and the Db is a bit of Mixolydian color thrown in as a bVII. As Albrecht said bVII can be viewed as a substitution for V (in terms of melody both can harmonize the tone F.)
But we need to know something about the phrasing to really know what is the tonic. Bar lines, harmonic rhythm (that's how long you hold each chord), or the actual melody. If we go with your sense that Bb is the tonic, then it could be labelled like I bVII IV where the Db is a borrowed bIII.
Either way seems OK provided the tonic is identified appropriately. Either analysis brings in some aspect of Mixolydian (a lowered seventh degree in major.)


Find the area of parallel surface

Question: Q: Consider a surface $M$ with regular parametrization $X:U_{open}\subset \mathbb{R}^2 \rightarrow \mathbb{R}^3$ and define the parallel surface $M_t$ by
$$Y(u,v)=X(u,v) + tN(u,v)$$
where $N(u,v)$ is the unit normal on $X$ at point $(u,v)$ and $t$ is a constant. And Show that $$\text{Area}(M_t)=\text{Area}(M)-2t \int_ M H \text{ d}A+t^2\int_M K\text{ d}A$$
where $H$ and $K$ are the mean curvature and Gaussian curvature, respectively.

First, I want to find out what $Y_u \times Y_v$ equals to so that I can apply
$$\text{Area}(M_t)=\int_{M_t}\| Y_u \times Y_v\| \text{ d}u\text{d}v$$
$Y_u=X_u+tN_u=X_u(1-tk_1)$
$Y_v=X_v+tN_v=X_v(1-tk_2)$
where $k_1$ and $k_2$ are the principal curvature of $X$
Therefore,
$$Y_u \times Y_v=(1-2tH+t^2K)X_u \times X_v$$
And,
\begin{equation}
\begin{split}
\text{Area}(M_t) & =\int_{M}\| (1-2tH+t^2K)X_u \times X_v\| \text{ d}u\text{d}v \\
 & = \int_{M} (1-2tH+t^2K)\|X_u \times X_v\| \text{ d}u\text{d}v \\
 & = \text{Area}(M) -2t \int_{M}H \| X_u \times X_v \|\text{ d}u\text{d}v + t^2\int_{M}K \|X_u \times X_v \| \text{ d}u\text{d}v
\end{split}
\end{equation}
I don't know how to simplify this to
$$ \text{Area}(M_t)  =  \text{Area}(M) -2t \int_{M}H \text{ d}A + t^2\int_{M}K \text{ d}A$$
Answer: In terms of any ($C^1$) parameterization $X(u, v)$ of a surface, the area element is
$$dA = \left\vert\left\vert X_u \times X_v\right\vert\right\vert \,du\,dv,$$
so you can simply substitute.
Comment: Oh, thanks. Forgot about what I learnt in vector calculus.
Comment: You're welcome, I'm glad it was useful.

Find the area of parallel surface


Show that $\int _0^x\left[\int _0^tf\left(u\right)du\:\right]dt\:=\:\int _0^x\:\:f\left(u\right)\left(x-u\right)du$ Notation confusion

Question: Show that $\int _0^x\left[\int _0^tf\left(u\right)du\:\right]dt\:=\:\int _0^x\:\:f\left(u\right)\left(x-u\right)du$ EDIT: (USING integration by parts)
Okay I think I have few ideas how to do this. I am confident that I need to use integration by parts. So $\int \:uv'=uv-\int \:u'v$
Let $u = [\int _0^tf\left(u\right)du \space]$  and $v'$ = 1
Now problem is with the notation and how everything is setup. There are so many variables, the $x$, the $u$ and the $t$.  Now I am very confused how to find $u'$ and $v$. Would $u'$ be $f(t)$ or $f(u)$ or $f(x)$? and same goes with $v$, would this be $t$, $u$ or $x$ and how can you tell and differentiate??
Otherwise I can I can do the question.
Comment: Does this answer your question? [Let $f$ be continuous. Then $\int_{0}^{x}\left[\int_{0}^{t}f\left(u\right)du\right]dt=\int_{0}^{x}f\left(u\right)\left(x-u\right)du$](https://math.stackexchange.com/questions/4107044/let-f-be-continuous-then-int-0x-left-int-0tf-leftu-rightdu-rig)
Answer: Let $$g(t)=\int_{0}^{t} f(u) du \implies g'(t)=f(t)$$
Then $$I(x)=\int_{0}^{x} \left( \int_{0}^{t} f(u) du \right) dt= \int_{0}^{x} g(t). 1 dt$$
Integrate by parts$$I(x)=g(t) t|_{0}^{x}-\int_{0}^{x} g'(t) t dt \implies x \int_{0}^{x} f(t) dt-\int_{0}^{x}tf(t) dt dt$$
$$\implies I(x)=\int_{0}^{x} (x-t) f(t) dt.$$
The name of the integration variable is always dummy it could be $t$ or $y$ or $z$.
Answer: You do not need to use integration by parts - this is a simple application of Fubini's theorem, which states that
$$\int_X\left(\int_Yf(x,y) dy\right)dx = \int_Y\left(\int_Xf(x,y) dx\right)dy $$
Here you have two variables - $u$ and $t$, with the limits being$$0\leq t\leq x$$ $$0 \leq u \leq t$$
Suppose $t$ is on the horizontal axis and $u$ is on the vertical axis  - then can you visualise what the region of integration looks like? (It's triangular)
Now, we want to flip the order of integration - as long as we preserve the original region, we can do so. If you followed the above step, you will realise that we can re-write the above region as
$$0 \leq u \leq x$$
$$u \leq t \leq x$$
Hence the integral can be re-written as
$$\int_0^x\left[\int_u^xf(u)dt\right]du$$
Now $f(u)$ does not depend on $t$ hence you can treat it as a constant and get the required expression
Comment: Hi Sreevisan, thanks for your answer, I am just a kid, I have no idea what that is and also my teacher wants me to use integration by parts


What is meant by k-anonymity and l-diversity, and what is difference between them?

Question: What is meant by k-anonymity and l-diversity, and what is difference between them? This concept is used in the following IEEE paper.
Comment: how on earth was this not a real question?  is my answer not a real answer?  how can "what are X and Y and how do they differ?" be misunderstood?
Comment: For explanations of k-anonymity and l-diversity, see [this article](https://missingdata.wordpress.com/2007/08/23/k-anonymity-and-l-diversity/). (I found this at the end of a Google search for `k-anonymity l-diversity`.)
Answer: an anonymised dataset contains multiple fields that can be used to identify someone (eg. age, sex, location).  even if one field is not unique, a combination of them may be (eg. there may be only 1 male aged 54 in squatsville).  k-anonymity greater than 1 means that even with all fields you don't identify a single person - you identify "k" people.
but that's not enough, because all k people identified by a distinct set of the different fields might be associated with the same value - if there are 10 different 54 year-old males in squatsville and they all wear ladies clothes, then you know that bob, who is 54 and lives in squatsville, wears ladies clothes.  so you need diversity within the group identified by the fields.  l-diversity means that the group contains "l" (the letter L, not the digit 1) different values.
[no offense intended - seriously - to cross-dressers.  i just wanted something mildly amusing that wasn't, well, cancer...]
and a reference - http://www.cs.colostate.edu/~cs656/reading/ldiversity.pdf
Comment: [assuming you're serious] well, you wouldn't know they were called bob.  but if there were 10 males aged 54 in squatsville and they covered 3 different categories then l is 3 (see "principle 2" in section 4.1 of the paper i just linked to).
Comment: I laughed so hard, also very well explained!
Comment: +1 for the vivid and life-like examples :)
Comment: Good clear explanation, but I have a question. If there are 3 Bobs who  wear women clothing, 4 who wear women underwear, and the rest who wear only mens-wear, that would give an l-diversity of 3?
Comment: Ah yes, I read 'Bob' as being one of the identifying fields. Thanks for the answer.


Twisted PerspectiveBroker callRemote from wsgi webapp

Question: I'm writing a wsgi application that needs to use Twisted PerspectiveBroker to call some remote methods. The problem is that the wsgi needs to return a rendered webpage, but the calls to the Twisted service are asynchronous. So basically my web app needs to call the remote methods, then do some other stuff, then it has to wait for the remote calls to finish, then render the page and return it to the client.
What is the best way to do this?
I am currently planning on using Flask to write the app.
Answer: A WSGI application runs in its own thread (or process).  When running in Twisted's WSGI container, that is a different thread than the reactor is running in.  Most of Twisted's APIs are not thread-safe: they may only be called in the reactor thread.
So, the basic way to call a Twisted API from a WSGI application is using reactor.callFromThread, which is thread-safe and which causes a function to be called in the reactor thread:
...
reactor.callFromThread(pbRemote.callRemote, "someMethod", some, args)

However, this discards the result, which you you probably want.  It's simple to build an API on top of reactor.callFromThread that preserves the result, though, and there's an implementation of that in Twisted, too:
from twisted.internet.threads import blockingCallFromThread

...
result = blockingCallFromThread(reactor, pbRemote.callRemote, "someMethod", some, args)

This call will block until the Deferred returned by callRemote fires and then it will return the result of that Deferred.
If you want to make the call, do some other work, and then wait for the call to finish, you have to get a little bit creative.  You need to make the call and get the actual Deferred it returns, but not block on it:
resultHolder = blockingCallFromThread(
    reactor, lambda: [pbRemote.callRemote("someMethod", some, args)])

And then you can do what other work you need to do.  And when you're ready to wait for the result of the PB call:
result = blockingCallFromThread(reactor, lambda: resultHolder[0])

This is all rather more awkward than using Twisted in a single-threaded scenario, so it may indeed be easier to use Twisted Web's native APIs rather than build a WSGI application.  Remember that one of the primary goals of WSGI is to allow applications to be developed that are portable across different servers - Twisted, Apache, etc.  If you're actually using Twisted APIs in your WSGI application, then it's not portable at all.
Answer: You can return server.NOT_DONE_YET to tell twisted.web the request is not finished. And then call request.write() and request.finish() to finish the request later, for example:
from twisted.web import server, resource

class MyResource(resource.Resource):
    def render_GET(self, request):
        # the call will return defer, that will notify us when it finish
        d = delayCall()
        # finish the request
        def finisn_req(data):
            request.write(data)
            request.finish()
        d.addCallback(finisn_req)
        # tell twisted.web that this request is not finished, yet
        return server.NOT_DONE_YET

Comment: Should have mentioned it, I'm planning on using Flask to write the webapp, unless it is a lot easier to use Twisted web.
Comment: Then how about write a broker, accept XML-RPC with Twisted, call to your server. Flask -> XML-RPC Broker -> Your server?


Is there any way to ask a ReportViewer if the result of the query inside a Report will yield more than 65k rows?

Question: I have my reports in a Reporting Services server, inside my .rdl there is a query that accepts parameters. I pass those parameters with an instance of ReportViewer. I have a method that downloads the result of the report in Excel format without using the ReportViewer directly. The method is the following:
private void CreateEXCEL(Dictionary<string, string> parametros, string nombreReporte)
{
    // Variables
    Warning[] warnings;
    string[] streamIds;
    string mimeType = string.Empty;
    string encoding = string.Empty;
    string extension = string.Empty;

    // Setup the report viewer object and get the array of bytes
    string ReportServerURL = ConfigurationManager.AppSettings["ReportServerCompletitudURL"];
    string ReportName = ConfigurationManager.AppSettings["ReportNameRankingVentaPDV"] + "/" + nombreReporte;

    MyReportViewer.Reset();

    MyReportViewer.ProcessingMode = ProcessingMode.Remote;
    MyReportViewer.ServerReport.ReportPath = ReportName;
    MyReportViewer.ServerReport.ReportServerUrl = new Uri(ReportServerURL);

    List<ReportParameter> parameters = new List<ReportParameter>();

    foreach (var d in parametros)
    {
        parameters.Add(new ReportParameter(d.Key, d.Value));
    }

    MyReportViewer.ServerReport.SetParameters(parameters);

    byte[] bytes = MyReportViewer.ServerReport.Render("EXCEL", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

    // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
    Response.Buffer = true;
    Response.Clear();
    Response.ContentType = mimeType;
    Response.AddHeader("content-disposition", "attachment; filename=" + nombreReporte + "." + extension);
    Response.BinaryWrite(bytes); // create the file
    Response.Flush(); // send it to the client to download

}

Now the idea is that I can't create a file with more that 65536 rows as an Excel file, the idea is to "Ask" if the result of the query inside the Report will yield more than 65k rows, then use csv format.
I dont see that reportviewer server control have a method that checks the result of the query.
I don't want to use pagebreaks inside the SSRS reports. Is there any way to ask in my code behind?
Answer: Not sure if this helps but this is a work around for exporting to excel.
Create a parent group on the tablix (or table, or list) and in the Group on: field enter the expression below.
Add Page break between each instance of a group
=CInt(Ceiling(RowNumber(nothing)/65000))

See Question on Here.
Comment: Would you happen to know if this expression in my "Details" Group will suffice?

In Disabled property:
`=IIF(rownumber(nothing) mod 10000=0,false,true)`
BreakLocation: `End`

If I want to download the .xls in my Microsoft VS 2008 where I load my report it works. But If I try to download it from the app it doesn't.
Answer: I found the solution to this particular problem like this:
Put this expression in my "Details" Group. In Disabled property: =IIF(rownumber(nothing) mod 10000=0,false,true) BreakLocation: End.
After this change, I can save this excel divided in different worksheets in the same excel sheet for every 10k rows. I tried doing the ceiling but if you have a rownumber expression inside that group it wont work.


Flink Streaming: Unexpected charaters in serialized String messages

Question: My stream is producing records of type Tuple2<String,String>
.toString() output (usr12345,{"_key":"usr12345","_temperature":46.6})
where the key is usr12345 and value is {"_key":"usr12345","_temperature":46.6}
The .print() on the stream outputs the value correctly:
(usr12345,{"_key":"usr12345","_temperature":46.6})
But when I write the stream to Kafka the key becomes  usr12345 (with a white space at the beginning) and the value ({"_key":"usr12345","_temperature":46.6}
Notice the space at the beginning of the key and the left parenthesis at the beginning of the value.
Very strange. Why this might happen?
Here is the serialization code:
TypeInformation<String> resultType = TypeInformation.of(String.class);

KeyedSerializationSchema<Tuple2<String, String>> schema =
      new TypeInformationKeyValueSerializationSchema<>(resultType, resultType, env.getConfig());

FlinkKafkaProducer010.FlinkKafkaProducer010Configuration flinkKafkaProducerConfig = FlinkKafkaProducer010.writeToKafkaWithTimestamps(
      stream,
      "topic",
      schema,
      kafkaProducerProperties);

Comment: What you have described is a bit weird, Have you tried creating a kafka sink and doing stream.addsink(kafkaSink)? May be that solves the issue?
Comment: @BiplobBiswas Well, I followed the instructions described in Flink Kafka documentation. https://ci.apache.org/projects/flink/flink-docs-release-1.3/dev/connectors/kafka.html#kafka-producer According to that this is the right way to use the Java, Kafka 0.10+ which I'm using.
Answer: The TypeInformationKeyValueSerializationSchema serializes data with Flink's custom serializers which means that the result has to be interpreted as binary data. Flink's String serializer writes the length of the String followed encoding all characters.
I would assume that you deserialize the Kafka topic with a plain String deserializer. For the key, the serialized length is interpreted as a whitespace character. For the value, the length is interpreted as '('.
Try to use a different serializer which serializes the key and value as plain strings or use a compatible deserializer.


Maximum overs for a bowler in a reduced over match

Question: In the limited overs cricket match, the overs can be divided between bowlers by maximum 10 per bowler in ODI and 5 in T20.
If an one day match gets interrupted by rain and started after some time by reducing the overs to 40 or 36 or any, what is the maximum no. of overs allowed for a bowler to bowl?
The above scenario is for both the innings or only for second innings.
How will it be for T20I?
Comment: The quota of a bowler in T20 is four overs. Not five overs.
Answer: Actually, maximum overs allowed per players is decided by dividing total overs by 5.
E.g. in ODI allowed overs per players = Total overs / 5 = 50/5 = 10 overs. T20I = 20/5 = 4 overs.
Law 12.6 from ICC's Standard One Day International Match Playing Conditions PDF

Law 12.6 Number of Overs per Bowler
No bowler shall bowl more than 10 overs in an innings.
In a delayed or interrupted match where the overs are reduced for both
  teams or for the team bowling second, no bowler may bowl more than
  one-fifth of the total overs allowed.
Where the total overs is not divisible by 5, one additional over shall be allowed
  to the maximum number per bowler necessary to make up the balance.

So in the interrupted matches, the same formula is used. E.g. suppose an ODI match is reduced to 40 overs then maximum allowed overs per player is 40/5 = 8. Another example: in case the match is reduced to 36 overs then maximum allowed overs per player is 35/5 = 7 and one player can bowl that remaining extra over i.e. total 7 + 1 = 8 overs.
Edit (regarding your another query):

If the match get started with 50 overs per side, after 22 overs gets bowled the match gets interrupted by rain with 4 bowlers used, by sharing 7,7,6,2 overs per bowler. Then the match get restarted with 32 overs per side. Now, how the overs will get divided?

In such situation the same rule is applied. E.g. here maximum overs per bowler is 30/5 = 6 plus any two bowlers can bowl remaining two overs each. I.e. two bowlers can bowl maximum 7 overs and others can bowl 6 overs each. Since two three bowlers have already bowled their quota, they won't be able to bowl further. And captain have to bowl with additional bowler as remaining 10 overs can't be completed with two bowlers when one has already bowled 2 overs.
Comment: @SportsFan - Yes same rules apply for T20I as well. See [ICC's Standard T20I Match Playing Conditions *PDF*](http://icc-live.s3.amazonaws.com/cms/media/about_docs/524ac4f092e53-05%20Standard%20T20_2013_19%2009%2013.pdf)
Comment: @hridayesh: AFAIK, in such case where a 50 overs match is reduced to 32 overs, two bowlers will be able to bowl 7 overs while 3 will be able to bowl 6 overs each. However, since two bowlers have already bowled more than their quota, they won't be able to bowl rest overs. And remaining 10.5 will be distributed between remaining 3 bowlers in similar way of how 32 overs were distributed (i.e. 4,3.3 & 3).
Comment: If 37 overs means, two bowlers allowed to bowl 8 overs. is it?
Comment: @SportsFan - Yes it is. If 39 then 4 players can bowl 8 overs.
Comment: Same rules for T20I?
Comment: I have a question regarding the sam topic, if the match get started with 50 overs per side, after 22 overs gets bowled the match gets interrupted by rain with 4 bowlers used, by sharing 7,7,6,2 overs per bowler. Then the match get restarted with 32 overs per side. Now, how the overs will get divided?
Comment: I have one more question for which cant find answer. What if 50 over match gets restricted to 32 over after bowling 21.3 overs and 3 bowlers bowled 10, 9.3, 2 overs. How remaining overs will be divided, and who will finish the remaining over when play resumes?


Augmented and Diminished (Fifth) Chords Baroque Notation

Question: Hello ¿Does anybody know what is the baroque notation of Augmented & Diminished (Fifth) chords?
I'm talking about of chords like this: C-E-G# & C-E-Gb
I need the baroque notation, for example: V6/4.
My problem is that I don't now what the notation is for those chords in fundamental state (C-E-G# & C-E-Gb) and in their inversions (E-G#-C and G#-C-E | E-Gb-C Gb-C-E).
I tried, based in another notations, to guess the notation and i have come with the following:
Augmented

Fundamental: I 5+
1º Inversion: I 6/3
2º Inversion: I 6/4-

Diminished

Fundamental: I 5-
1º Inversion: I 6/3-
2º Inversion: I  6-/4-

Help is appreciated.
Answer: The use of Roman Numerals started after the Baroque so what is written in the original question is a more modern usage (it's pretty good in itself.)
In the Baroque, the bass note (not the chord root) is indicated on a staff. Then intervals above that bass are indicated with numbers following a few rules. The third is not indicated unless it has an accidental. The fifth is omitted in root position. The key signature is important.
In the key of C major, the root position chords are just the notes. In the first inversion, the bass is indicated so a note E with the symbol 6 means E, its third G, and its 6th C and is thus the first inversion of a C chord. Most of the theory in the Baroque was written in terms of intervals. The second inversion of a C major chord would be a G with 64 over it. (Modern use is to indicate the chord root by letter and the chord form from the figured bass, also quick to read but not the same thing.)
A sharpened interval is sometimes written with a / through the number or a + or a # before the number. A flattened interval is written mostly with a b before the number (flat sign), rarely with . A # or b with no number applies to the third above the root.
A C augmented chord would have a C note ($100) in the bass and a #5 as the figure, C#5.  In C major, a C minor chord would be C b (I really have to figure out how to insert staff notaton.) C diminished would be Cb5b. Note that B diminished is just D6 (D, its third F, and its sixth, B). It's close to being a keyboard tablature.
This site has an introduction. http://openmusictheory.com/thoroughbassFigures.html
There are other books, Arnold.s and CPE Bach's come to mind.
Quick list of augmented chord: C augmented C not #3, first inversion E# note 6
, second inversion G# note, 64. Italian Sixth in C major: Ab on the bass line 4#6.
Comment: Sorry, didn't know that roman numerals are from modern usage, i need the numbers of the inversion and fundamental states for a Entry Test. Your response is greatly appreciated. Edit: I was taught that the slashed number means that is diminished or lowered by a step. Thanks for your time and words.
Comment: No problem. They most likely used a forward slash for raising and backward for lowering because it saved copiest's times.


coldfusion continue keyword within IF block in cfscript / Odd behaviour

Question: Has anyone noticed this odd behaviour with the Continue word. It seems to kill all following code in the template when used within an If statement.
I tested this in CF and Lucee with http://cflive.net/
eg:
<cfscript>
    writeoutput('test1, loop
');
    for (x = 0; x > 5; x++) {
        writeoutput(' gonna continue?');
        continue;
        writeoutput('continued within');
    }
    writeoutput('Out of loop..

');
    writeoutput('test2, if
');
    oURL = true;
    if (oURL) {
        writeoutput(' gonna continue?');
        continue; // seems to kill all following code
        writeoutput('continued within');
    }
    writeoutput(' out of If..');
    writeoutput(' end');
    for (x = 0; x > 5; x++) {
        writeoutput('loop:' & x);
    }
</cfscript>

Comment: @Scp - FWIW, I do see the same result, but .. am curious, why use `continue` inside an if statement, instead of restructuring the if block? Usually continue is designed to work with loops.  Not sure what the expected behavior is when used outside of a loop...
Comment: Continue would abort processing of the rest of the code within a loop. Seems to be working correctly to me. Docs http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec0a0e0-7fdf.html#WSc3ff6d0ea77859461172e0811cbec0a0e0-7fe7
Comment: I think, using `continue` or  `break` out side loop will just work like an `abort`, since there is not next loop to go to.
Answer: I would imagine it kills all following code if used outside of a loop construct.
The idea of cfcontinue is to skip executing all code following the command and to resume processing at the top of the loop.
I guess what is happening is that the cfml engine stops executing code once it gets to the cfcontinue command and is looking for where it can resume processing which is unknown if outside of a loop.
Comment: (Edit) @SCP - In addition, if you try the equivalent if statement in CFML, CF throws a context validation error "The tag must be nested inside a cfloop tag". So it sounds like the real issue, or bug if you will, is that cfscript does not warn that the command is being used in a way that was not intended or supported.


Correct way to set up DNS primary/secondary/... for redundancy and latency reduction?

Question: I thought DNS primary/secondary for redundancy purposes was straightforward. My understanding is that you should have a primary and at least one secondary, and that you should set up your secondary in a geographically different location, but also behind a different router (see for example https://serverfault.com/questions/48087/why-are-there-several-nameservers-for-my-domain)
Currently, we have two name servers both in our main data center.  Recently, we've suffered some outages for various reasons that took out both name servers, and left us and our customers without working DNS for a few hours.  I've asked my sysadmin team to finish setting up a DNS server in another data center and configure it as the secondary name server.
However, our sysadmins claim that this doesn't help much if the other data center is not at least as dependable as the primary data center.  They claim that most clients will still fail to look up properly, or time out too long, when the primary data center is down.
Personally, I'm convinced we're not the only company with this kind of problem and that it most likely is already a solved problem.  I can't imagine all those internet companies being affected by our kind of problem.  However, I can't find good online docs that explain what happens in failure cases (for example, client timeouts) and how to work around them.
What arguments can I use to poke holes in our sysadmins' reasoning ? Any online resources I can consult to better understand the problems they claim exist ?
Some additional notes after reading the replies:

we're on Linux
we have additional complicated DNS needs; our DNS entries are managed by some custom software, with BIND currently slaving from a Twisted DNS implementation, and some views in the mix as well.  However we're completely capable of setting up our own DNS servers at another data center.
I'm talking about authoritative DNS for outsiders to find our servers, not recursive DNS servers for our local clients.
Answer: There is a really great, albeit quite technical "Best Practices" document that may prove useful when combating your sysadmin.   http://www.cisco.com/web/about/security/intelligence/dns-bcp.html
If he/she doesn't recognize the validity of articles written by Cisco, then you might as well stop arguing with the sysadmin - go up a level of management.
Many other "Best Practices" document recommend separating your primary and secondary nameservers not only by IP block, but by physical location.  In fact, RFC 2182 recomends that secondary DNS services be geographically separated. For many companies, this means renting a server in another datacenter, or subscribing to a hosted DNS provider such as ZoneEdit or UltraDNS.
Answer:
However, our sysadmins claim that this
  doesn't help much if the other data
  center is not at least as dependable
  as the primary data center. They claim
  that most clients will still fail to
  look up properly, or time out too
  long, when the primary data center is
  down.

Ah, the focus is dependable.  It sounds like they are taking a jab at your link to the outside, rather than setting up secondary DNS.  All the same, do set up secondary DNS and proceed from there.  It will help with the load and will prop things up in a pinch...but do inquire as to why they think the other location is not dependable.

Personally, I'm convinced we're not
  the only company with this kind of
  problem and that it most likely is
  already a solved problem. I can't
  imagine all those internet companies
  being affected by our kind of problem.

You're not the only company, and this has probably been rehashed a million times in companies the world over.

However, I can't find good online docs
  that explain what happens in failure
  cases (for example, client timeouts)
  and how to work around them.
What arguments can I use to poke holes
  in our sysadmins' reasoning ? Any
  online resources I can consult to
  better understand the problems they
  claim exist ?

I'm talking about authoritative DNS for outsiders to find our servers, not
  recursive DNS servers for our local
  clients.

You can do all kinds of things, including setting up an external DNS service that is registered as the authority for your zone, but secretly making the (outside) authoritative servers secondaries to your own (inside) DNS servers.  This configuration is horrible, wrong, shows that I am truly an evil SysAdmin, and a kitten dies every time I recommend it.  But it does two things:

You get your DNS service to handle the brunt of the load, rendering questions about the capacity of your own (internal) DNS as moot.
You get your DNS service to stay up while your in-house DNS servers may be down, so it doesn't matter how dependable your link is - what matters is how dependable your DNS service provider is.

The reasons that this is the wrong thing to do:

You would be setting up what is called a "stealth nameserver", because while it will show up in your zone records, and you can query the IP for the name of the server, it will never be touched by the outside.  Client queries will never reach it.
While your DNS would continue to operate fine (because your hosted service would address the issue) it doesn't mean that any websites you have would work if your internet connection was down, that is to say, it only addresses half of the issue.  It really does sound like there are other issues that the admins are concerned about.
Comment: Perhaps my definition differs, but I use a "hidden master" setup, and since the master is never referenced in the zone files, I believe that to be a slightly more secure setup. The server still responds authoritatively, provides a single point of update, and is not accessible to outside requests.
Comment: comment is +1 on why I do it this way. :) I forgot to mention, with a little iptables magic, you can make port 53 only respond to outside requests from just the secondaries, making it very secure indeed.  Still, it's not entirely "kosher" and can create issues.  Try running a domain through intodns.com sometime and see what it reports...
Answer: Unfortunately the Linux DNS resolver doesn't seem to have direct support for detecting and doing failovers for DNS servers. It keeps feeding requests to your primary resolving nameserver, waits for a configured timeout, attempts again, etc.
This often means up to 30s delays for any request. Without first trying the secondary as long as the primary is down.
I wanted to solve this as our Amazon EC2 resolving nameserver is unreachable for many of our workers. This causes big delays in our processes and even downtime in some cases because we rely on resolution. I wanted a good failover to Google / Level3 nameservers in case Amazon's went down again. And fall back ASAP, because then Amazon will resolve hostnames to local addresses where applicable, resolving in lower latency for instance to instance communication.
But whatever the usecase, there's a need for better failover. I wanted to solve this.
I wanted to stay away from proxy-ing daemons, services, etc. As that would just introduce more
Single Point Of Failures. I wanted to use as archaic & robust a technology as I could.
I decided to use crontab & bash, and wrote nsfailover.sh.  Hope this helps.
Comment: found via ddg `linux first dns server is down second works but is slow`
Answer: It sounds like the problem is that clients—which could be anyone, anywhere—see two DNS servers and if one fails, they either do not failover to the secondary server or there is a long timeout before they do.
I agree that the primary and secondary DNS servers should be located at different facilities as a best practice, but I don't see how that would fix this particular problem.
If the client is going to insist on querying a specific IP address, ignoring the secondary's IP address (or taking a while to timeout to it), then you simply have to come up with a solution that keeps that IP address working, even if the primary server is down.
Some directions to explore would be a load balancer that can redirect traffic for a single IP address to multiple servers at different data centers; or perhaps anycast routing.
Comment: Most linux clients default to a 5 second timeout which is a killer. Second DNS server or not, once the primary is down, it'll be so slow, it'll appear down.
Answer: As long as each of your datacenters is on different circuits (ideally with different upstream providers far up into the cloud), you can setup pretty reliable DNS with just the two datacenters. You simply need to make sure your registrar of choice populates the appropriate glue records to the big servers in the sky.
Our setup is:

2 physical datacenters (separate
circuits, ISPs, and upstream providers)
2 physical query servers in a
cluster behind a SLB at each facility
2 load balancing devices to serve
specific records that we want to
manage the balance of between the two datacetners
hidden master internally accessible
by both server clusters (I believe very strongly in hidden master setups for security)

This setup has been effective enough to give us roughly 5 9's of uptime over the last 6 or 7 years, even with the occasional server downtime for updates, etc. If you're willing to spend a few additional dollars, you can look at outsourced hosting of the zone with someone like ultradns...
As to the load conversation that KPWINC mentioned, that is 100% correct. If your smallest datacenter can't handle 100% of your load, then you are likely boned anyway because your outage is going to occur when you least want it =)
I take the maximum load from all my edge routers, add them all together, and then divide by 0.65...that is the minimum bandwidth that we must have at each datacenter. I put that rule into place about 5 years ago, with some documents to justify it I gathered from CCO and about the internet, and it has never failed us. However, you must check those stats at least quarterly. We had our traffic increase almost 3 fold between November and February last year and I was not prepared for it. That bright side is that the situation did allow me to generate some very clear hard data that says at 72% load on our WAN circuit, we start dropping packets. No additional justification has ever been required of me for more bandwidth.
Answer: Thomas,
After reading your update I've revised my post (previous post has reference to Windows software).
It almost sounds to me like your sysadmin(s) are telling you that your secondary location doesn't have the necessary hardware to handle the FULL LOAD?
It sounds as if he's saying, "Hey buddy, if our primary location (which includes the primary DNS) goes down then DNS is the LEAST of our worries because if COLO1 is down then COLO2 can't handle the load anyway."
If THAT is the case, then I would suggest you look over your infrastructure and try and come up with a better design.  This is easier said than done, especially now that you're live in a production environment.
All that aside, in a perfect world, COLO1 and COLO2 would be able to stand alone and handle your load.
Once that was in place... the DNS is really nothing more than having enough DNS servers with a fast enough refresh and if one side fails you can rewrite your DNS to point to the servers that are UP.
I've used this method in small to reasonable sized environments and it works great.  Failover typically takes less than 10 minutes.
You just have to make sure your DNS servers can handle the extra load of a short TTL (time to live).
Hope this helps.
Comment: This was kind of my thought too, but I want to know how they do it:-)
Answer: I realized from reading your description that it's not clear whether you mean authoritative DNS for outsiders to find your servers, or recursive DNS servers for your local clients.  The behavior of those two is very different.
For authoritative DNS servers, the "clients" will be other DNS servers which have caching and plenty of intelligence.  They'll tend to try multiple servers at once if the first one is at all slow, and will tend to prefer the one that gives them faster replies.  Downtime for one data center in that case would have a very slight performance impact.
For recursive DNS servers, the clients are your local clients that probably have the DNS servers listed in DHCP.  They'll try their servers in the listed order every time, with a painfully long (several seconds) timeout before moving from the first server to the second server.
If your primary datacenter is down, nobody will be able to reach those servers anyways, but often the errors from that are more intelligible than the errors from unreachable DNS servers.  "couldn't contact server" or "connection timed out" instead of "couldn't find server" or "no such server".  For instance, most SMTP servers will queue up mail for a week if they see the server in DNS but just can't reach it; if they can't find it in DNS at all they may immediately refuse to even try to deliver it to your domain.
Secondary DNS being geographically and network-separated is a good thing.  You might be able to trade secondary DNS with a friendly company, and there's plenty of DNS providers you can pay to do it for you.  Some registrars have secondary DNS as a service, too.
Answer: Your sysadmins are (mostly) wrong.
The recursive servers that query your authoritative servers will notice very rapidly if either site is unresponsive.
Yes, there's some chance that clients may experience very modest DNS resolution delays when there's an outage, but they'll only be a second or two, and once the client's own DNS servers have learned that one of the servers is down they'll use the remaining servers in preference to the failed one.
If necessary (to appease the sysadmins) continue to run two servers at your primary data center, but do put at least one more outside.
Comment: Do you have a reference for this?
Comment: The default linux config doesn't cache down'd nameservers. This applies also to a few linux based appliances (such as our IP phones), which means that when the primary goes down, the dns queries take so long because every query tries the primary, waits 5 seconds, then tries the secondary, that things basically stop working under load.
Answer: A secondary dns server never hurts, depending on where it is hosted it will give you more or less functionality.
If your primary host fails,  a secondary can take over no matter if it's sitting next to it or in a remote location.  If however your datacenter uplink fails you might still get DNS replies from the server in another
datacenter but you won't be able to reach your servers anyhow.  So your end users won't directly benefit from the secondary DNS in the remote location.
Different clients react in other ways to DNS servers not being available so there's some truth to clients timing out, but not all.
A secondary DNS in a remote datacenter will, however, still be capable to resolve the IP address of the server you want to reach so you can debug the routing and see when they come up again.  And if you have set up secondary MX servers correctly you won't even lose any mail.


MaxEnt distribution of $x\in(-\infty,\infty)$ with given mean?

Question: The MaxEnt distribution of $x\in[0,\infty)$ with given mean is the exponential. The MaxEnt distribution of $x \in (-\infty,\infty)$ with given mean and variance is the Gaussian. Is there a MaxEnt distribution of $x \in (-\infty,\infty)$, when only the mean is given?
Update: Without loss of generality, the mean $\mu = 0$. Now on second thought I can see how this can be problematic, because any distribution symmetric around zero can be made "more entropic" by flattening it a bit more, and more, eventually approaching a uniform distribution, which is improper in $(-\infty,\infty)$.
How can I make this argument more precise and show that there is no MaxEnt distribution with given mean on $(-\infty, \infty)$? Otherwise, is there an alternative way to define a "MaxEnt" distribution with given mean on the whole real line?
Answer: The argument is precise enough, I think. Just take a normal distribution with zero mean and variance $\sigma^2$, ane let the variance tend to infinity, then the entropy grows without bound.
So there is no maximum-entropy distribution with the given constraints.


I want to get the text from a JTextField

Question: I'm trying to code a game where the user try's to guess a number, randomly generated between 1 and 10, I need to know how to get the text from the JTextField
<code>    JFrame frame = new JFrame("The Guessing Game");
    frame.setVisible(true);
    frame.setSize(400, 300);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

    JPanel panel = new JPanel();

    JButton rndbutton = new JButton("Click to create random nubmer!");
    panel.add(rndbutton);
    frame.add(panel);

    JTextField tField = new JTextField(15);
    panel.add(tField);

    //^^ The GUI code ^^

    game.game();
}
</code>
}
Comment: When you asked the question, did it not suggest duplicates?
Comment: `tField.getText()` http://stackoverflow.com/questions/5752307/how-to-retrieve-value-from-jtextfield-in-java-swing
Comment: it is pretty straight forward - just call the `getText()` method of your JTextField. Or is ur question not clear?
Answer: Use:
<code>tField.getText()
</code>
If you're not sure how to do something, you should first check the documentation to see if there's a function for it. Searching on Google is also a good idea.
Comment: Also, this question may have been answered before on stack overflow, so you should do a search on stack overflow first.


Contextual links in block disabled when using Twig Tweak and UUID

Question: In my taxonomy-term--NAME.html.twig I use a reference field to load a 'block_content'.
{% for item in term.field_blocks %}
  {% set uuid =  item.entity.uuid.value %}
  {{ drupal_block('block_content:' ~ uuid) }}
{% endfor %}

The block is rendered correctly but without the 'contextual links' (quick edit on front-end).
When I look into the twig_tweak module, I see you can add an array with configuration options.
public function drupalBlock($id, array $configuration = [], $wrapper = TRUE) {

    $configuration += ['label_display' => BlockPluginInterface::BLOCK_LABEL_VISIBLE];

    /** @var \Drupal\Core\Block\BlockPluginInterface $block_plugin */
    $block_plugin = \Drupal::service('plugin.manager.block')
      ->createInstance($id, $configuration);
    ...
}

Does anyone know how I can change the twig-rule to something like this:
{{ drupal_block('block_content:' ~ uuid, {show_contextual_links:true}) }}

I found this question, but that is not correct:
Programatically render block with contextual links (in php)
Answer: I was able to do it like this:

  {{ drupal_contextual_links('block_content:block_content=1008:langcode:') }}
  {{ drupal_entity('block_content', 1008) }}

Answer: When you use {{ drupal_entity('block_content', 'content_block_id') }}, Drupal skips the block template, which contains the code for contextual links. If you use {{ drupal_block('plugin_id') }}, it will apply the block template, including title, links and other attributes.
If you look at the default block template in Classy (block.html.twig):
{%
  set classes = [
    'block',
    'block-' ~ configuration.provider|clean_class,
    'block-' ~ plugin_id|clean_class,
  ]
%}

  {{ title_prefix }}
  {% if label %}

{{ label }}

  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {{ content }}
  {% endblock %}

The {{ title_suffix }} part contains the code that renders the contextual links.


Labels inside input fields - cant click on text when in FORM, but can within LABEL

Question: http://jsfiddle.net/ndreckshage/sPHBd/
Can anyone help with this code? I'm trying to use a plugin from this site http://attardi.org/labels2/#info
If you notice in the jsfiddle, if you click on the text (email/password) it doesnt activate the text field, but if you click on the text area (not text itself, it works fine)
And in the lowest example, it works correctly
Thanks for any help
Comment: The hell are you trying to do with this code? Why would you need JavaScript or better yet jQuery for this?
Comment: There're a lot better jQuery plugins for `placeholder`, yes that's its name. google it.
Answer: The problem is solved. Check it out :  http://jsfiddle.net/sPHBd/1/
Comment: The problem was, you were assigning the class `input` to the element ``, it must be a ``


Inequality $\frac{1}{x}>\frac{1}{y}$ when $y>0$ has the same solutions as..

Question: Inequality $\frac{1}{x}>\frac{1}{y}$ when $y>0$ has the same solutions as..
a) $x>y$
b) It should say $y>x$
c) $y-x>1$
d) none of three above
Correct answer: d)
My procedure: If x=0,01 and y=0,1 then a) & c) must be false. However, I can not manage to find a counter "example" to b). It seems to me that if the inequality which is posed in the question above should be true then $y>0$ implies that $x>0$. Otherwise the inequality sign does not seem hold. If both variables must be positive then does it not imply that $y>x$?
Comment: There is some typo in your multiple choices...
Comment: What is option (b)?  [Welcome to Math.SE!](https://math.meta.stackexchange.com/a/4928/290189) Please use MathJax.
For some basic information about writing math at this site see e.g. [basic help on mathjax notation](/help/notation),
[mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020),
[main meta site math tutorial](//meta.stackexchange.com/a/70559)
and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: Also, where did option c go?
Answer: Note that for $y>0$
$$\frac1x>\frac1y\iff \frac1x-\frac1y>0\iff \frac{y-x}{xy}>0$$
that is (for $x,y\neq 0$)

$x>0$ and $x<y$

or

$x<0$ and $x>y$
Comment: I get the same result but the exam paper says d). 0>y>x but it is not possible according to the condition in the question. It seems to me that the answer should be B) but they said d).
Comment: B indeed is not correct since we need to specify more conditions for the solution.
Comment: In other words y>x works only for x>0, thus option B is wrong.
Comment: But should we not only give an answer to the scenario when y>0 and not when y<0? It seems like you took to account the scenario when 0>x>y, that solution is outside the definition of the inequality?
Comment: I'm referring to x>0 not y.
Comment: For x<0 and y>0 the inequality does not seem to hold. Ex, 1/-1>1/2 if x=-1 and y=2? Oh! That is why it is wrong! Because y>x holds even if y=2, and x=-1, but our given inequality does not, thus they do not have the same answers! Thanks!
Comment: Yes indeed it is true only if x>0 and for x<0 we obtain a condition in contradiction with the given y>0.
Answer: $$\frac{1}{x} > \frac{1}{y} > 0$$ along with $y>0$ implies that $ 0<x<y$
For example $ y=5$ and $x=4,  1/4>1/5$ , and $5>4>0$
Comment: I agree with you, would you say that my answer shert is wrong? Gimusi agreed with my answer sheet and disagreed with you.
Comment: Your answer is correct.  Your example is well posed and clear.
Answer: The most obvious reason why (b) is wrong is that $y=1$ and $x=0$ is a solution to $y>x$, but is not a solution to $1/x>1/y$. Hence they do not have the same set of solutions.
However, other examples include anything with $y>0$ and $x<0$. That is a solution to $y>x$, but not $1/x>1/y$ with $y>0$.
Explained in another way. It is true that $1/x>1/y$ combined with $y>0$ implies that $x>0$. However, $y>x$ and $y>0$ does not imply that $x>0$, therefore the solution sets cannot be equivalent!
Comment: I understood it as y>x contains the solutions that 1/x>1/y has but y>x has some solutions which 1/x>1/y does not have, thus they do not have equivalent solutions.
Comment: @IGotAQuestion Yes, that is correct. The condition $(y>x) \wedge (y>0)$ has strictly more solutions than $(1/x>1/y) \wedge (y>0)$.


On a no ball, can both batsmen carry the stumps and run forever?

Question: When a bowler oversteps (or in rare cases, has the back foot touching the return crease) during the delivery stride, the umpire usually calls a no ball while the ball is still in play. On hearing this call, both batsmen could pluck out all three stumps at their end, and run with them to score runs for as long as they like!
From Law 28 (The Wicket is down) (quoted below), the fielding side won't be able to remake the wicket, so neither batsman can be run out. Without doubt, the batsmen doing this would be considered against spirit of the game, but is there anything in the Laws which prohibit it?

1. Wicket put down
(a) The wicket is put down if a bail is completely removed from the
top of the stumps, or a stump is struck out of the ground,
...
The wicket is also put down if a fielder strikes or pulls a stump out
of the ground in the same manner.
...
3. Remaking wicket
If a wicket is broken or put down while the ball is in play, it shall
not be remade by an umpire until the ball is dead. See Law 23 (Dead
ball). Any fielder may, however, while the ball is in play,
(i) replace a bail or bails on top of the stumps.
(ii) put back one or more stumps into the ground where the wicket
originally stood.
Answer: If a batsman carries the stumps deliberately, he is actually obstructing the field.
Law 37 (Obstructing the field):

1. Out Obstructing the field
Either batsman is out Obstructing the field if he wilfully attempts to obstruct or distract the fielding side by word or action. In particular, but not solely, it shall be regarded as obstruction and either batsman will be out Obstructing the field if while the ball is in play and after the striker has completed the act of playing the ball.

So if he carry the stump after playing the ball he is obstructing the field.
Law 24 (No ball):

16. Out from a No ball
When No ball has been called, neither batsman shall be out under any
   of the Laws except 33 (Handled the ball), 34 (Hit the ball twice), 37
   (Obstructing the field) or 38 (Run out).

So as per the laws he will be given out.
Comment: This answer is right, but the second half of the first quote (starting "In particular..." is not relevant: the second half of that sentence, not included above, says (paraphrasing) "... if the batsman strikes the ball twice".


How to store a list in client side in asp.net

Question: I have a page that includes a wizard with 3 step.
step 1 is nothing that matter.
but in step 2 I have some fields that I want to add their value in a class named Stages. In page load I call a list of Stages like this: List<Stages> temp = new List<Stages>;
If the user clicks 'save_btn' I add fields of step2 in a Stages item and add this item in the temp (list).  That works fine.
But after that click I want to stay in step 2 and refill the fields and add another item if user wants. But its not working. The temp list is set to null after that click. I don't know how tell asp to not renew the list. I tried if (!IsPostBack) but still not working.
List<Stages> temp;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        temp = new List<Stages>();
}
protected void save_stage_Click(object sender, EventArgs e)
{
    Stages stg = new Stages()
    {
        description_1 = stage_description_1.Text,
        description_2 = stage_description_2.Text,
        description_3 = stage_description_3.Text,
        description_4 = stage_description_4.Text,
    };
    temp.Add(stg);
}

Answer: You can use session:
Session["stg"] = stg;

var list = (List<Stages>)Session["stg"];

Store List to session
Comment: very helpfull link. thanx


Equivalent of proper scoring rule for point forecasts

Question: Proper scoring rule is a concept used for evaluating density forecasts. What would be an equivalent for evaluating point forecasts? E.g. mean squared error seems like a proper metric for evaluating forecasts that target the expected value of the underlying random variable. This is because the forecast that truly minimizes the expected squared error (the population counterpart of the mean squared error) actually is the expected value. Meanwhile, mean absolute error does not seem proper for the same goal. On the other hand, it would seem proper when the target is the median of the underlying random variable. So what term is there to describe the propriety of a metric for evaluating point forecasts?
Comment: @Dave, are they, though? [Wikipedia's entry](https://en.wikipedia.org/wiki/Brier_score) suggests Brier score involves the estimated probabilities rather than the predicted class labels.
Comment: Aren't most predictions point forecasts?
Comment: What would that be? As I understand it, the point of scoring rules is that you are fitting your model to the labels, but you try to predict the (unobserved) probabilities, so you want to assess and possibly fix the predicted probabilities. With point predictions, you are directly predicting the values, so to assess your model you can *just* look at the metrics that are appropriate for the problem.
Comment: So scoring-like scenario would be if your predicted values were something like aggregates (e.g. group means) and you wanted to fit your model to them but you cared about predicting the individual-level data (de-aggregated), so you would like to validate and fix the individual predictions. But we have other ways of dealing with problems like this than scoring rules.
Comment: @Tim, in my understanding, propriety of scoring rules is about ranking competing forecasts, not assessing individual forecasts or trying to improve them. Now, a point prediction targets some function of the pdf, e.g. the mean, the median, a quantile or such. In a forecasting competition, this target should be specified explicitly. Yet some competitions judge the same forecast by multiple criteria: MSE, MAE, MAPE etc. This does not make much sense. (Why judge a prediction that targets the mean by how close it gets to the median?) And thus the need for the term I am looking for.
Comment: @Dave, sure, they are.
Comment: @RichardHardy if your aim it to minimize squared error, why would you train it or evaluate using absolute error (or something else) if you can train it using squared error..? This is what I mean by saying that in point predictions you can do it directly, where you (usually) cannot directly train or evaluate on probabilities. It doesn'e seem to need a specific name.
Comment: @Tim, at the stage of forecast evaluation, training is irrelevant, so we can leave it out of the discussion. (And we know well that the training loss function does not have to match the evaluation loss function for best results in terms of out-of-sample evaluation loss, though it often would, but that is another topic. See also [this](https://stats.stackexchange.com/questions/470626/why-is-using-squared-error-the-standard-when-absolute-error-is-more-relevant-to/470786#470786).) I am interested in proper ranking in forecasting competitions and related uses.
Comment: Of most forecasts are point forecasts then aren't the usual scoring rules the ones you want?
Comment: @Dave, scoring rules (including proper ones) are defined for density forecasts. I am looking for an equivalent for point forecasts.
Comment: You mean Brier score and log loss?
Comment: @Dave, I mean in general. I have not seen scoring rules discussed in any other context.
Comment: It seems like Brier score and log loss are scoring rules for point forecasts.
Comment: @Dave, I got an answer; check it out.
Comment: @QMath, thank you, this is helpful!
Comment: Terminology-wise, you may be looking for the term "scoring function"? (outlined briefly in the second paragraph [here](https://en.m.wikipedia.org/wiki/Scoring_rule)) This appears to be the point forecast analogue of scoring rules. I'm not sure of the effectiveness/validity, but one could apply proper scoring rules to point forecasts by representing the point forecast as a deterministic distribution ($F(x) = H(x - y), x \in \mathbb{R}$, where y is your point prediction and $H$ is the right-continuous Heaviside Step function.
Comment: Propriety/Strict Propriety also seems to apply similarly to the point prediction case as if $S$ is our scoring metric (function from $\mathcal{D}^{2}$ to the reals where $\mathcal{D}$ is the space our data takes values in), $d \in \mathcal{D}$ is a data point, and $p \in \mathcal{D}$ is our point prediction, then $S$ is proper if $S(d, d) \leq S(d, p)$ for all $d, p \in \mathcal{D}$ and is additionally strictly proper if equality only occurs when $p = d$ (our point prediction is exactly the value we're trying to predict). Metrics such as the pointwise MSE seem to have the latter property.
Answer: As mentioned by QMath, the term (strictly) consistent scoring function is used in the statistical literature to describe functions which evaluate point predictions based on the same principles as (strictly) proper scoring rules.
The (slightly simplified) definition uses a set $A$ of possible point forecasts, a set $O$ of observations, a set $\mathcal{F}$ of distributions, and a statistical property/functional $T: \mathcal{F} \to A$. Examples of functionals are the mean or the median, as already mentioned in the question. A scoring function is a function $S : A \times O \to \mathbb{R}$. It is consistent for $T$ if
$$
\mathbb{E}_{Y\sim F} \, S(T(F), Y) \le \mathbb{E}_{Y\sim F} \, S(x, Y)
$$
for all $x \in A$ and $F \in \mathcal{F}$. It is strictly consistent if equality holds if and only if $x=T(F)$. The fact that $T(F)$ is a minimizer is of course simply convention.
The idea behind this is (analogous to proper scoring rules) that the point forecast $T(F)$ resulting from the true underlying distribution of $Y$ will receive the lowest score/loss on average. Similar to their proper scoring rule counterpart, they enable forecast rankings and can be used to do regression or train ML models, for a desired statistical property. The most popular examples are squared error (for the mean) and absolute error (for the median).
Two additional points relating to the discussion below the question:

Proper scoring rules are not restricted to density forecasts. They assess probabilistic predictions. Depending on how you deal with your distributions, you can use different scoring rules. For instance, you can define them for the CDF or even the characteristic function.
Tim stated above that "with point predictions, you are directly predicting the values". The theory behind scoring functions sees this slightly different. There we have some distribution of the target in mind and for some reason, we have to reduce this to a single point, e.g. the mean. So if a value $x$ is reported, this is not a statement, that the forecaster believes, that the observation will be $x$. It is a piece of statistical information. This becomes obvious when dealing with discretely distributed data: A forecaster can report $x=3.5$ here since they want to report the mean, but for a forecaster who wants to predict the observation, a non-integer forecast makes no sense at all.

For more details, see Making and evaluating point forecasts especially Section 3.2. (The definition there is for set-valued forecasts, so it is more general, but less intuitive, I think)
Comment: This is very helpful. I agree with point 1; I meant it your way but was sloppy with my phrasing. I used *density* as I do not find the term *probabilistic* completely adequate here, but perhaps that is because I am not a native speaker. Also, you could edit the post to specify that it is specifically section 3.2 of *Making and evaluating point forecasts* that addresses my question? That may help the other readers. Also, did you mean $O$ instead of $0$ in $S: A \times 0 \to \mathbb{R}$?
Comment: @RichardHardy Glad to hear. The zero is a typo of course.


Software newbie needs help with sound libraries

Question: I am a complete newbie with home recording so I need to understand a couple of things.
I want to record my guitar using software such as GarageBand or Logic Pro. One way to do it is to directly connect my amplifier (with its sound effects) through my audio interface to the computer and record directly tracks.
I am so confused on how I can use computer software for modelling amplifiers directly on my computer though. In other words, how can I record and which software can I use in order to record tracks by plugging the guitar directly to the audio interface and get tones and effects from some software? And which software is compatible with those recording programs?
E.g. I see so many people talking about Native Instruments.
Any kind of hint will be greatly appreciated.

After a lot of digging and research I managed to understand what is going on. I will leave my own reply so that other people who were lost like me can find an easy solution.
Comment: The question is not at all about "sound libraries" (which is something quite different), but recording software and effects. Do you something like Garage Band already? A computer? Do you have an audio interface? Maybe you should read up on some basics first. Try Wikipedia and look at the link lists on the bottom of the page. https://en.wikipedia.org/wiki/Digital_audio_workstation
Answer: Right. The "Sound libraries" you hear about refers to virtual instruments for midi controllers. Theres a whole world of them.
For guitar virtual amps, thats a different matter. Its still VST (And/Or AU for macs) but we're talking about effects not instruments.
Theres a number of good Guitar ones. Personally I'm not a fan of Native Instruments Guitar Rig , to me it sounds very..... Zoom-ish. But others might differ on that. Guitar Rigs an ageing system though. Amplitubes another old school one. Less bells and whistles but to my ears a nicer tone in its amp cabs.
Going up the food chain a bit, theres Waves GTR stuff. They are OK. Not great but not terrible. Slate has a guitar effect system too that sounds a bit less digital.
What you REALLY want though are the amp modelling plugins that let you use Cabinet and Amplifier Impulses. These will give you a sound much closer to the real thing in terms of modelling amplifier behavior.
If you want instruments your choice is to either get a midi keyboard, or use a guitar-to-midi setup , either as an external add-on to your guitar (I'm told the fishman systems amazing) or as a VST system like Jam Origins Midi Guitar which converts an audio signal from the guitar to a midi signal to control VST instruments. I should warn you though that these are fiddly things. Guitars don't behave the same as Keyboards, and sometimes its hit and miss how well the system works.
Regarding Sound Libraries, Kontakt is a sample player thats used by the bulk of the libraries out there. Its about $400ish~ on its own, but its usually purchased as part of the Komplete library which is an absolutely monster sized grab bag of stuff.
If your looking for something within your budget and are specifically looking for midi instruments to be driven by a keyboard or a guitar-to-midi setup, a cheap option is EastWest composer cloud which is a monthly $20 subscription to an utterly gigantic collection of instruments. Bascially a full orchestra, plus specific brass/wind/strings/percussion libraries, a collection called Goliath which has countless instruments, Some choirs, some loop things for he hip hop people, and the excellent Stormdrum series. I should give fair warning though the Play engine (East wests alternative to Kontakt) is brutal on system resources so you want a meaty machine to run it on, and a big SSD to fit the data.
For DAW software, Garage band isn't terrible, and its basically a beginners version of the excellent logic, which itself comes with an instrument library comparable to NI or EastWests libraries. Theres also Studio One which is rapidly becoming a favorite for many pro studio folk.
Theres one though worth looking into if your on a budget, Mixcraft which is PC only I think(Maybe?) and is actually really damn good for its $100 asking price.
Comment: Wow, thanks! So, I have been using Amplitube and I am super happy about it! Do you think there is something of higher quality and if yes which product do you refer to? Also, I have discovered all those stuff you mention about! I just want sounds (instrument plug ins) to play with my midi keyboard and everything is so expensive. Here and there there are some free stuff but nothing I have found is remarkable.
Comment: What sort of music are you interested in making?
Comment: For guitar stuff I mainly am interested in prog metal. But since I also play jazz I would like to know what are the options generically. Please, do not waste time searching for me, only tell me if you already know! Thanks!
Comment: Re guitar stuff: Honestly if Amplitube is working for you, stick with it. Perhaps look at something like Studio Devil's stuff for Impulse responsed Amp head and Cabinet modelling.
As for instruments, have a look at EastWests composer cloud if you can live with a subscription. Its $20ish a month, but the orchestra in there is used in real world film scores and the like. Plus if its not living up to expectations, you can always cancel. and if its *really* living up to expectations, you can buy the individual libraries. Its a monster.

Of course if your cashed up NI Komplete is amazing.
Answer: Try Audacity a free software for track based recording and editing.
Connect you instrument's audio output into you computer mic (audio input) and select "Windows WASAPI" (in windows) and click recording button on audacity.
Comment: I use GarageBand and Logic Pro X. I know how to operate it to some basic level but whatI miss is plug-ins with good sounds. Apparently there is a whole Apple library. Other solutions are software like Native Instrument's Kontakt. But, all of them are so expensive. I would like to get some plug-ins with say oriental instruments but free. The question above is similar but for guitar sounds (amps and effects).
Comment: Im kind of surprised your not finding Logic's library sufficient. For Oriental (Asian and Middle east) , the EastWest composer cloud has Ra and a few other libraries that cover a lot of instruments from China, Japan, Indonesia and the middle east (Turkey, Iran, etc)
Comment: I should note Audacity is *completely* unsuitable for this purpose. It cant do Midi and thus can't do virtual instruments which is what the OP is asking about.


Distutils appharently fails with a (working) SWIG extension

Question: I am wrapping via SWIG a C library in a python module, here called "myExample". If I compile:
$swig -python myExample.i
$gcc -c myExample_wrap.c -I /usr/lib/python2.7 -fPIC -std=c99
$ld -shared myExample_wrap.so -llapacke -o _myExample.so

I obtain a full working module (liblapacke is necessary for some functions I used). Now I'd like to make this module installable via "pip install".
According to the distutils section (https://docs.python.org/2.7/distutils/setupscript.html), I wrote my setup.py file:
from distutils.core import setup, Extension
setup(name='myExample',
version='0.1',
ext_modules=[Extension('_myExample',['myExample.i'], libraries= ['lapacke'])] )

and edited MANIFEST.in in a way to preserve the sources and avoid problems like in similar questions on this website (i.e. just including myExample.h and myExample.c). Then I run:
$python setup.py sdist

and obtained the package installable via "pip install". It seemed done (no errors, no warnings), but...it does not work. In this installable module ("_myExample.so" - notice the underscore, it seems to be required by distutils [maybe does it hide an answer?]) some methods are different, some are missing, etc... Consequently I decided to to one step per time. By just compiling:
$python setup.py build_ext

I already obtained the same problem: the final module is different from the one obtained via the usual compilation explained at the beginning.
Summing up: given a SWIG interface, compiling it traditionally or compiling it via distutils produces a different result. How could it be possible? Is my setup.py wrong? Is there maybe an alternative way for obtaining a pip-installable module without relying on distutils or setuptools(which produces the same problems)?
Ps: the wrap code is very long and so I cannot unfortunately give a detailed list, but I am fully available in adding more in case of need. For instance, the manually compiled interface successfully contains the "AdaptiveInterpolation" (working fine), while the distutil-produced one have "AdaptiveInterpolation_set", "AdaptiveInterpolation_get", or there are a lot of methods starting with "new_" (absent in my original code).
Comment: I think it's worth adding example source code so that one could reproduce the problem locally
Answer: Practically, there are two options for distribution of such package: bdist_wheel and sdist.
Let's take SWIG's example from the docs for distutils.
example.h
int fact(int n);

example.c
#include "example.h"

int fact(int n) {
    if (n == 0) {
        return 1;
    }
    else {
        return n * fact(n - 1);
    }
}

example.i
%module example

%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}

int fact(int n);

Let's build a SWIG interface, which by default produces example_wrap.c.
swig -python example.i

Wheel
Python Wheels is a modern distribution format which simplifies distribution of pre-built packages (i.e. users of the package will not need a compiler, development headers and the like to install it). To use it we'll need setuptools and wheel (can be installed with pip or from OS repositories, sudo apt-get install python-wheel python-setuptools).
setup.py
from setuptools import setup, Extension

setup(
  name = 'example',
  version = '0.1',
  author = 'SWIG Docs',
  description = 'Simple swig example from docs',
  ext_modules = [
    Extension('_example', sources = ['example_wrap.c', 'example.c'])],
  py_modules = ['example'],
  package_data = {'': ['example.h']}  # needed for sdist
)

You can build the wheel with:
python setup.py bdist_wheel

On my machine it produces example-0.1-cp27-cp27mu-linux_x86_64.whl which I can install with pip and test like python -c 'import example; print(example.fact(5))'. Note the filename. It encodes compatible Python version, ABI and platform. Here's listing of the contents (unzip -l ...).
Archive:  example-0.1-cp27-cp27mu-linux_x86_64.whl
  Length      Date    Time    Name
---------  ---------- -----   ----
     2609  2018-02-24 11:06   example.py
    70968  2018-02-24 13:31   _example.so
       10  2018-02-24 14:58   example-0.1.dist-info/DESCRIPTION.rst
      290  2018-02-24 14:58   example-0.1.dist-info/metadata.json
       17  2018-02-24 14:58   example-0.1.dist-info/top_level.txt
      105  2018-02-24 14:58   example-0.1.dist-info/WHEEL
      193  2018-02-24 14:58   example-0.1.dist-info/METADATA
      617  2018-02-24 14:58   example-0.1.dist-info/RECORD
---------                     -------
    74809                     8 files

To build wheels with better compatibility, you can, for instance, look at manylinux.
Source
sdist stands for source distribution, which means your users will need to have a compiler and relevant development dependencies. Source distribution is built with:
python setup.py sdist

Produced example-0.1.tar.gz contains (tar -tf ...):
example-0.1/
example-0.1/example.c
example-0.1/PKG-INFO
example-0.1/example.egg-info/
example-0.1/example.egg-info/PKG-INFO
example-0.1/example.egg-info/dependency_links.txt
example-0.1/example.egg-info/top_level.txt
example-0.1/example.egg-info/SOURCES.txt
example-0.1/setup.cfg
example-0.1/example.py
example-0.1/setup.py
example-0.1/example_wrap.c
example-0.1/example.h


Qual a diferença entre "test" e "spec" em testes automatizados?

Question: A pergunta e duvidas abaixo abordam Node.js, TypeScript e JavaScript. Não sei se os conceitos abaixo se aplicam a outras plataformas/linguagens de programação.

Estou estudando sobre testes automatizados (TA) usando Jest e TypeScript e me surgiu uma dúvida quanto a nomeação dos arquivos de testes. Em alguns projetos que analisei, alguns arquivos estão sendo nomeados de maneira diferente. Alguns possuem a nomenclatura .test.ts e outros .spec.ts. Até o presente momento da publicação desta pergunta, eu tinha em mente que test ou spec não tinham nenhuma diferença semântica, ambos serviam apenas para identificar que aquele arquivo é um arquivo de teste, porém as distintas nomeações dos arquivos fez surgir a dúvida sobre o assunto.
Estudando e pesquisando sobre TA, encontrei boas respostas sobre o assunto que me ajudou a entender bastante do conceito, mas nada que esclarecesse minha duvida. Por exemplo, esta excelente resposta do @utluiz em que fala sobre conceitos de testes, eu destaco 2 seguintes pontos:

Teste Unitário: testa partes específicas do sistema, como classes e métodos.

Teste de Integração: testa vários componentes de um sistema funcionando de uma só vez.

Vamos ter essa afirmação em mente.
Agora vamos de código para exemplificar a minha dúvida. Na pasta de testes, tenho 2 arquivos de testes que basicamente o que eles fazem é testar o recurso de cadastrar um novo administrador no sistema. Agora vamos ao primeiro arquivo e ainda vou destacar o nome do arquivo:

O primeiro se chama admin-signup.test.ts e neste arquivo de teste, ele injeta mocks de dependências para dentro do módulo de serviço (AdminServices):

import * as AdminServices from '@naointeressa';

const adminData =  {...}

const AdminRepositoryMock =  {...}

const validatorMock =  {...}

const bcryptMockValidPass = {...}

describe('any', () => {
  it('should ...', async () => {
    const sut = await AdminServices.createAdminService(
      AdminRepositoryMock,
      validatorMock,
      bcryptMockValidPass
    )
    const newAdmin = await sut.createAdmin(adminData)

    expect(newAdmin.name).toBeDefined()
    expect(newAdmin.email).toBeDefined()
  })

  ...
})

O segundo se chama admin-signup.spec.ts e este se difere do anterior pois ele não injeta mocks, mas sim as verdadeiras dependências do módulo de serviço (AdminServices):

import * as AdminServices from '@naointeressa';
import * as AdminRepository from '@naointeressa';
import * as crypto from '@naointeressa';
import validator from '@naointeressa';

describe('any', () => {
  it('should ...', async () => {
    const sut = await AdminServices.createAdminService(
      AdminRepository,
      validator,
      cryptoObject,
    );
    const newAdmin = await sut.createAdmin(adminData);

    expect(newAdmin.name).toBeDefined();
    expect(newAdmin.email).toBeDefined();
  });
});

Foi nesse código (simplificado obviamente) que me surgiu essa duvida em relação a nomeação dos arquivos de testes.
Eu fiz uma análise dos exemplos acima citados e cheguei ao seguinte pensamento:

Usamos .test.ts quando o nosso arquivo de teste não testa nenhum recurso externo da nossa aplicação (banco de dados, API externas, chamadas HTTP, etc...), ou seja, para testes que seguem a citação 1 da resposta do @utluiz.

Usamos .spec.ts quando o teste atravessa camadas externas da aplicação (outros módulos, bibliotecas, banco de dados, etc...), ou seja, para a citação 2 da resposta do @utluiz. Testes end-2-end também teriam esse tipo de nomenclatura de arquivos (citação Teste de Sistema na resposta do @utluiz, me corrijam se estiver errado).

Porém não estou seguro da minha conclusão acima. Estou estudando mais sobre testes e ainda fico com algumas duvidas, então, sobre a minha duvida de nomenclaturas, eu pergunto:

Existem diferenças semânticas entre nomear um arquivo como .test.ts e .spec.ts?

Se a reposta da pergunta acima é sim, o meu pensamento sobre onde usar determinada nomenclatura está correto? Se não, e qual contexto eu devo usar um ou outro?

Ou se não existe diferença semântica entre os nomes, posso adotar qualquer um, e todos eles tem o mesmo propósito... indicar que um arquivo é um arquivo de teste?

Cheguei a pensar que spec vem de algo específico, ou seja, se o teste testa uma funcionalidade muito simples e minúscula da aplicação como por exemplo uma função que verifica se um campo de email não é vazio ('') e só, nada a mais. Mas não me ajudou a sanar a duvida. Gostaria de uma resposta definitiva.
Comment: @LuizFelipe Acho que tem sim pois está com cara do conceito ter vindo daqui: https://stackoverflow.com/a/37502922/2241463
Comment: Não acho que a pergunta tenha relação com TypeScript ao ponto de justificar a tag.
Comment: É, @Piovezan, pode ser.
Comment: @LuizFelipe Senti um certo ar contrariado aí :) Eu não entendo disso, só fiquei curioso sobre o tal termo "spec" sendo aplicado a testes automatizados e fui procurar o que poderia ser, mas não me aprofundei na pesquisa para chegar a uma conclusão definitiva.
Comment: @Piovezan, nada disso!! :P Foi apenas concordância mesmo. :))
Answer:
Existem diferenças semânticas entre nomear um arquivo como .test.ts e .spec.ts?

Não formalmente. O Jest não convenciona nenhum tipo de "sufixo" no nome do arquivo. Acaba sendo uma convenção adotada por alguns grupos de pessoa para organizar melhor as próprias suites de testes.
A maioria das pessoas, pelo que vejo, utiliza somente um dos sufixos. Como .test.js ou .spec.js. Vai do gosto e da forma como a pessoa escreve os testes – como disse, não tem regra oficial.
Pode-se dizer que, testes escritos em formato que mais se assemelham a uma especificação, utilizar .spec.js seja mais "semanticamente correto". Vai por aí.

Se a reposta da pergunta acima é sim, o meu pensamento sobre onde usar determinada nomenclatura está correto? Se não, e qual contexto eu devo usar um ou outro?

A resposta da pergunta anterior foi não – a nível oficial do Jest. No entanto, desenvolvedores de uma organização podem, por exemplo, convencionar o uso de .test.js para uma coisa e .spec.js para outra.
Nesse caso, cria-se uma diferenciação semântica, mas é limitada à entidade que a estabeleceu.
Quando essa distinção é criada, pode-se, por exemplo, utilizar assim:

.spec.js para testes que visam especificar alguma parte do código (como documentar uma feature através de código, por exemplo). Nesse sentido, é mais comumente utilizado no contexto de testes unitários.

.test.js para os demais. Como testes de integração mais genéricos no qual o objetivo não é criar uma "especificação em código".

Mas no geral não é nada maior que isso, até porque o nome do arquivo pouco interfere no funcionamento dos testes. O importante, como muita coisa na programação, é a manutenção da consistência. Nesse sentido, como o Jest não convencionada nada em relação à nomenclatura dos arquivos, cabe ao desenvolvedor escolher ou criar uma convenção e tentar a seguir sem muitos desvios.

Ou se não existe diferença semântica entre os nomes, posso adotar qualquer um, e todos eles tem o mesmo propósito... indicar que um arquivo é um arquivo de teste?

Teste é teste. Essa é a semântica. No caso de uma diferença significativa entre o funcionamento dos testes (como integração ou unidade), pode fazer sentido semântico mudar a "convenção de sufixos" para refletir a semântica estabelecida. Vai do programador (ou da equipe – ou seja lá quem toma as decisões :P).
Utiliza-se um sufixo como .test.js ou .spec.js para que o test runner consiga achar os arquivos de teste mais facilmente, sem precisar analisar o arquivo em si. A partir daí o programador pode customizar como a busca será feita e customizar a nomenclatura.
No seu caso, você utilizou .spec.js para integração e .test.js para unidade. Mas tenha certeza que há quem faz o contrário (e está tudo bem).

Note que procurei ser pouco assertivo nesta resposta, uma vez que esse tópico é extremamente subjetivo e altamente fragmentado (no sentido de que é muito comum ver várias pessoas utilizarem convenções distintas). Claro que há convenções mais comuns, mas ainda sim são convenções não oficiais.
Comment: _"Teste é teste"_ , vou tatuar no meu braço! Foi uma excelente resposta, deu pra entender que para o exemplo acima citado foi apenas um padrão interno adotado. Nos meu testes, fiz ajustes para que no config do Jest, testes unitários façam match de arquivos `.test` e para testes de integ. ou e2e façam match de arquivos `.spec`. Nesse caso, como é uma escolha livre, decidir distinguir do jeito que achei melhor para especificar o tipo de teste a ser executado.


how to make 5 days disable after user current date selection excluding weekends

Question: suppose i have selected 17/01/2019 then  5 days must be disable. this date must change dynamically according to date selection.
<code>$('.datepickstart').datepicker({
     autoclose: true,
     todayHighlight: true,
     format: 'dd/mm/yyyy',
     daysOfWeekDisabled: [0, 6],
     startDate: date
    });
    $('.datepickstart').datepicker().on('changeDate', function(e) {
        var temp = $(this).datepicker('getDate');
      var d = new Date(temp);
      console.log(d);
      d.setDate(d.getDate() + 5);
      console.log(e.date);
      $('#datepickstart').datepicker('maxDate',e.date);
    });
</code>
Comment: have u tried  $('.datepickstart').on('change', ?
Comment: yes i have try above code with on change
Answer: Try setStartDate instead of maxDate
<code>$(".datepickstart").datepicker({
     autoclose: true,
     todayHighlight: true,
     format: 'dd/mm/yyyy',
     daysOfWeekDisabled: [0, 6],
     startDate: date,
    }).on('changeDate', function (selected) {
            var temp = $(this).datepicker('getDate');
            var numberOfDaysToAdd = 5;
            temp.setDate(temp.getDate() + numberOfDaysToAdd);
            $('.datepickstart').datepicker('setStartDate',temp);
});
</code>

and check this Maybe you will get some help

2 dependent datepickers with min and max date


Openvpn setting up new CA.cert, server key on old setup

Question: I mistakenly deleted keys folder with ca.cert, server.key and dh2048.perm. I have multiple clients located various places which are still connecting with server.
I want to generate new set of ca.cert,server.key and dh2048.perm and client keys without affecting those clients which are already connecting with the server. What could be the feasible solution?
Is it okay to go ahead and use build-server-key, build-ca and build-dh for new clients that I will deploy on the same server or do I need to have a complete different setup? I am not sure how old clients are still connecting!
Thanks in advance!
Answer: Have you restarted your OpenVPN server? If you didn't that would explain why the clients are able to connect: the server has read the files you deleted at its startup and so it's able to verify the certificates presented by the clients (the server only needs to have the contents of the CA certificate to verify them).
Regarding the feasible solution…
Well, one way is to create another OpenVPN instance listening on a separate port (say, on Debian and its derivatives this works out of the box — by creating another configuration file with a different port(s) configured).
You should create a completely different CA setup (PKI) for that istance.
You could then re-roll the key+certificate pair for all the existing clients using that new CA and deploy them — with the necessary tweaks in their configuration files to account for a different server port — on the existing clients, effectively switching them over to the new server.
After that update you can reconfigure the original OpenVPN instance to use
the new CA setup — basically just making its configuration identical to
the second instance, modulo the original port(s).
After that switchover you'll end up with two identical OpenVPN instances
which only differ in the ports they listen on.
So you can then iterate over your clients once again — this time changing the configured ports back to target the original instance.
After that sequence is completed, you'll have all the clients updated.
TL;DR

Create a new PKI.
Setup a separate OpenVPN instance using that PKI.
Re-roll new key+cert+CA cert bundles for the existing clients.
Update the existing clients with those bundles, retargeting them
to the new OpenVPN instance one-by-one.
Reconfigure the original instance to use the new PKI.
Update the existing clients to target the original instance again.
Comment: Thank you @kostix for detailed solution. No, I have not restarted the server and hence as you mentioned deployed clients are still working. Only problem with re-configuring clients is that those are already deployed geographically different place and we can not get them back. Is it okay to create another instance on the same server and continue with that new CA-setup for rest of the clients?
Comment: @DarshanJoshi, yes but as soon as you restart your working instance, the existing clients seize to work. I'm afraid, you might want to do some "remotely-controlled" work on the clients. Is it possible to update them via some remote-access admin solution (like TeamViewer) or some such?


Nuxt is generating unwanted routes, when splitting .vue files. How do I get only the routes I want?

Question: In my Nuxt project, I split up the .vue files in the pages directory to something like:
pages/
  index.vue
  shop/
    index.vue
    shop.js
    shop.pug
    shop.scss
  login/
    index.vue
    login.js
    login.pug
    login.scss

with the shop/index.vue, and login/index.vue src-ing their respective js/pug/scss files.
The routes for /, /shop, /login are working as expected, but I see that some other routes are also being generated: /shop/shop, and /login/login -- which are coming from the shop.js and login.js files I am assuming.
How do I prevent that? I just want it to use index.vue, or any .vue files for generating the routes.
Comment: Edited my answer.
Comment: Does answer work?
Comment: Hi, the `.nuxtignore` file does not seem to be working in my environment (Express server). But the ignorePrefix option as per your reference works. I would like to use something like `.nuxtignore`, I'll be opening an issue on Nuxt's github about this.

Edit: for now I'm using the `ignore` property for nuxt.config.js. Thanks for the reference!
Answer: Put .nuxtignore file in your root.
File content:
pages/**/*.js
Reference


Check my proof $\int_{-\infty}^{\infty} \int_{-\infty}^{\infty} \sin(x^2+y^2) \, dx \, dy$ diverges

Question: I am trying to prove that $\int_{-\infty}^{\infty} \int_{-\infty}^{\infty} \sin(x^2+y^2)\, dx\,dy$ diverges and I did it like this:
$x=r\cos \theta$, $y=r\sin\theta$, $\theta \in [0,2\pi]$, $r\in [0,\infty]$, and the jacobian is $r$:
$$\int_{-\infty}^\infty \int_{-\infty}^\infty \sin(x^2+y^2) \, dx \, dy=\int_0^{2\pi}\int_{0}^\infty r\sin(r^2) \, dr \, d\theta = 2\pi \int_0^\infty r\sin(r^2) \, dr$$
Use the variable change $v=r^2$, $dv=2r \, dr$ and so:
$$2\pi \int_0^\infty r\sin(r^2)\,dr = 2\pi \int_{0}^{\infty}r\sin(v)\,\frac{dv}{2r}=\pi \int_0^\infty \sin(v) \, dv $$
I checked wolfram, and it says that $\int_0^\infty \sin(x) \, dx$ diverges, so I must conclude that the original integral diverges as well.
But how do I actually prove that $\int_0^\infty \sin(x)\,dx$ diverges?
Comment: on the other hand, $\int \sin(x^2)$ converges.
Comment: Prove that is oscilates infinitely many times.
Comment: The integral does not diverge to infinity instead it does not exist. To prove that then you have to follow the comment by chubakueno.
Comment: @AthanagorWurlitzer The idiosyncrasies of $n$-integration is mind-boggling.
Comment: @CameronWilliams it is a good counter-example to Fubini, when the convergence is only in the sense of Riemann.
Comment: @AthanagorWurlitzer Very good point. I'll keep this in my toolbox of counterexamples ;)
Answer: We can compute the limiting integral by writing $$\int_0^\infty \sin(x) dx = \lim_{b\to\infty}\int_0^b \sin(x) dx = \lim_{b\to\infty} ( \cos(b)-1 )$$ We know that the limit $\lim_{b\to\infty} \cos(b)$ diverges. This means the integral diverges as well.
Comment: And is the rest of my proof valid?
Comment: Yes the rest of the proof looks fine to me.
Comment: But [W|A](http://www.wolframalpha.com/input/?i=limit+cos+x+as+x-%3Einfinity) says $\lim_{b\to\infty}\cos b=-1\;\text{or}\;1$.
Comment: Wolfram Alpha is wrong in this case. The terms are bounded but they do not converge.