Can every real number be written as unique infinite decimals?

Question: A slightly variation of this question: Can every real number be represented by a (possibly infinite) decimal?
Here I restrict my discussion into infinite decimals (without ending with infinite zeros starting from somewhere along the number):
My question is a straightforward one, is this representation unique?
Comment: No, a famous counterexample is $0.999 \dots = 1$.
Comment: This violates my assumption, since 1.000000000... consist of "infinite zeros" at the end of the decimal expression
Comment: Ok. I misunderstood your question then.
Comment: The unique ambiguity arises exactly when you have $0.9999999...=1.000000...$ (or $0.45999...= 0.460000...$ and so on), so, avoinding this case, representation in decimals is unique.
Comment: My hunch told me that it is correct. But somehow I cannot construct a rigorous proof of it.
Comment: The numbers which end in infinite zeros are all integer fractions with the denominator some integer power of 10. Maybe that can help to formulate something.
Comment: Yes, every nonterminating decimal number has a unique decimal representation.
Answer: Firstly note the following, where $(a_i)$ are the digits of some decimal expansion:
$$\sum_{i=n}^\infty a_i 10^{-i}\le \sum_{i=n}^\infty 9. 10^{-i}=10^{-(n-1)}$$
The first bit follows from a comparison of the coefficients and the second is just a geometric progression calculation — it's essentially the "0.999...=1" result.
Now suppose we have two different decimal expansions $\sum_{i=m}^\infty a_i 10^{-i}$ and $\sum_{i=m}^\infty b_i 10^{-i}$ which differ for the first time when $i=n-1$. Without loss of generality, assume $a_{n-1}<b_{n-1}$, so $a_{n-1}+1\le b_{n-1}$. We have
$$\begin{align}
\sum_{i=m}^\infty a_i 10^{-i}&=\sum_{i=m}^{n-2} a_i 10^{-i}+a_{n-1}10^{-(n-1)}+\sum_{i=n}^\infty a_i 10^{-i} \\
&\le\sum_{i=m}^{n-2} a_i 10^{-i}+a_{n-1}10^{-(n-1)}+10^{-(n-1)} \\
&\le\sum_{i=m}^{n-2} a_i 10^{-i}+b_{n-1}10^{-(n-1)}
\end{align}$$
However, because the $a_i$s and $b_i$s match for $i \le n-2$,
$$\begin{align}
\sum_{i=m}^\infty b_i 10^{-i}&=\sum_{i=m}^{n-2} a_i 10^{-i}+b_{n-1}10^{-(n-1)}+\sum_{i=n}^\infty b_i 10^{-i} \\
&\ge \sum_{i=m}^\infty a_i 10^{-i}+\sum_{i=n}^\infty b_i 10^{-i}
\end{align}$$
So equality of the two expansions can only possibly be achieved if $\sum_{i=n}^\infty b_i 10^{-i}=0$, which is not the case if you insist on the decimal expansions being infinite. Thus an infinite decimal expansion of a number is unique.


Atiyah-Singer theorem and the projection of a non-compact space on a compact one

Question: Although this question is related to physics, its origin is purely mathematical.
Suppose the formal expression
$$
\tag 1 \text{det}(iD), \quad iD \equiv i\gamma^{\mu}D_{\mu} = \partial_{\mu} - iA_{\mu}P_{L}
$$
Here:

$iD$ is elliptic operator called also the Dirac operator. It acts in the space of Dirac spinors realizing the $\left(\frac{1}{2}, 0\right) \oplus \left(0,\frac{1}{2}\right)$ representation of the double covering of the Lorentz group;
The actual manifold is the 3+1-dimensional Minkowski space, with the metric $g_{\mu\nu} = \text{diag}(1,-1,-1,-1)$;
$\gamma_{\mu}$ is the set of 4 Dirac gamma-matrices realizing 4-dimensional Clifford algebra;
$\partial_{\mu} = \frac{\partial}{\partial x^{\mu}}$ is the covariant derivative
$P_{L} = \frac{1}{2}(1 - \gamma_{5})$ is the projector on the sub-space $\left( \frac{1}{2}, 0\right)$, which is also called left chirality projector
$A_{\mu}$ is the vector field being in adjoint representation of some gauge group ($U(1), SU(2)$ and so on), called the gauge field; it smoothly decreases to the so-called pure gauge $A_{\mu} \to g\partial_{\mu}g^{-1}$, where $g$ is the gauge transformation element;

In order to calculate $(1)$ people usually say following.
1) Since it is elliptic, then in compact manifolds it has discrete set of eigenfunctions $\psi_{n}(x), \kappa_{n}(x)$ with corresponding eigenvalues $\lambda_{n}, \lambda_{n}^{*}$, defined by
$$
iD\psi_{n} = \lambda_{n}\psi_{n}, \quad (iD)^{\dagger}\kappa_{n} = \lambda_{n}^{*}\kappa_{n};
$$
2) The Minkowski space-time manifold is non-compact; we can also make the so-called Euclidean continuation naively defined by introducing the Euclidean coordinate $x^{E}_{0}= ix_{0}$ and work with Euclidean space $R^{4}$, whose manifold is also non-compact;
3) However, in the theory given above we can project the Euclidean space $R^{4}$ on the 5-dimensional hypersphere $S^{4}$, which is compact manifold;
4) Therefore, $(1)$ can be given as the product of eigenvalues $\lambda_{n}$, which leads to Atiyah-Singer theorem (analytical index is equal to topological index).

My question
Why can we make the projection $R^{4} \to S^{4}$ in the given theory?
Answer: I think the above $\det(iD)$ you wrote is not the Atiyah-Singer index theorem. Rather it is something related, usually referred to under the name of "regularized determinants". The idea is to regularize the determinant of a pseudo-differential operator using zeta functions by extending the case of the compact manifold.
Now since the regularized determinants are defined by trace of pseudo-differntial operators, which is effectively an integral over $\Delta\subseteq X\times X$, the integral would not change with a 1-point compactification. So the claim then trivially follows. Of course there are other choices available (like identifying it with the upper half hemisphere, etc), but I think this is the only one making sense in your context.
It should be pointed out that it make no sense to say Atiyah-Singer and "topological index" are involved at here. In its most naive setting, the topological index is reduced to the Euler characteristic, and it should be obvious to you that $\chi(\mathbb{R}^{4})\not=\chi(\mathbb{S}^{4})$. There is no kernel, cokernel or non-compact extension of Fedosov's formula relevant at here.


Interests calculation

Question: I'm trying to figure out how banks calculate their loan interests.
Let's say i ask the bank for 125 329,00 $ at a fixed interest rate of 0.99% over 240 months. In my own calc, I estimated a total loan interest of 12 522.18 $.
Something like 52.18 $ month, a monthly payment of 574.38 $ with the pay back.
But looking at the banks' offer I see 575,82 $  (+1.44 $ diff) and I cant see any possible explanation for this. Am I doing something wrong?
Answer: Hint: The equation to calculate the monthly payment is
$$125329\cdot \left(1+\frac{0.0099}{12}\right)^{240}=x\cdot \frac{\left(1+\frac{0.0099}{12}\right)^{240}-1}{\frac{0.0099}{12}},$$
where $x=575.82$ is the constant monthly payment and $\frac{i}{12}=\frac{0.0099}{12}$ is the monthly interest rate.
Comment: Thank you so much for your explanation and for providing the equation. It really helped me understanding how interests can be represented and calculated.
Comment: @Lothre1 It pleases me, that the answer has helped. You're welcome.

Interests calculation


How to quantify the improvement in application performance after installing a squid proxy

Question: We conducted a load test on our web application and we found that once the load goes beyond 40 users the server response time goes up drastically. (It was a 256MB RAM cloud machine).
So we installed squid reverse proxy in front of the apache server. Interestingly when we started load testing, we realized that the server is performing pretty well even for larger loads. We have a reason to be happy but then we want to know what exactly is causing this performance improvements.
We would like to know the following things

Which requests are cached and which are not.
Cache Hits : Cache Miss

Where should I look for this information ?
Comment: What tool are you using to perform the load testing?
Comment: Apache JMeter.......
Answer: Squid access/cache log parsing is one way to do that, but there are other ways, too.
You should use Squid SNMP MIB (if you already use SNMP for monitoring your servers) for general statistics about hit/miss ratio.
squidclient is an excellent command line tool for querying Squid status. It can show you cached objects, Squid process status, cached IP addresses, disk subsystem status, open file descriptors and whatnot. Try squidclient -h your_squid_host -p your_squid_port -u your_user -w your_password mgr:menu for all possible options. User and password can be configured in squid.conf.
Here are the possible options for squidclient:
 mem                    Memory Utilization      public
 cbdata                 Callback Data Registry Contents public
 events                 Event Queue     public
 squidaio_counts        Async IO Function Counters      public
 coss                   COSS Stats      public
 diskd                  DISKD Stats     public
 config                 Current Squid Configuration     hidden
 ipcache                IP Cache Stats and Contents     public
 fqdncache              FQDN Cache Stats and Contents   public
 idns                   Internal DNS Statistics public
 external_acl           External ACL stats      public
 http_headers           HTTP Header Statistics  public
 menu                   This Cachemanager Menu  public
 shutdown               Shut Down the Squid Process     hidden
 reconfigure            Reconfigure the Squid Process   hidden
 offline_toggle         Toggle offline_mode setting     hidden
 info                   General Runtime Information     public
 filedescriptors        Process Filedescriptor Allocation       public
 objects                All Cache Objects       public
 vm_objects             In-Memory and In-Transit Objects        public
 openfd_objects         Objects with Swapout files open public
 pending_objects        Objects being retreived from the network        public
 client_objects         Objects being sent to clients   public
 io                     Server-side network read() size histograms      public
 counters               Traffic and Resource Counters   public
 peer_select            Peer Selection Algorithms       public
 digest_stats           Cache Digest and ICP blob       public
 5min                   5 Minute Average of Counters    public
 60min                  60 Minute Average of Counters   public
 utilization            Cache Utilization       public
 histograms             Full Histogram Counts   public
 active_requests        Client-side Active Requests     public
 store_digest           Store Digest    public
 storedir               Store Directory Stats   public
 store_check_cachable_stats     storeCheckCachable() Stats      public
 store_io               Store IO Interface Stats        public
 pconn                  Persistent Connection Utilization Histograms    public
 refresh                Refresh Algorithm Statistics    public
 delay                  Delay Pool Levels       public
 forward                Request Forwarding Statistics   public
 client_list            Cache Client List       public
 asndb                  AS Number Database      public
 server_list            Peer Cache Statistics   public
 non_peers              List of Unknown sites sending ICP messages      public

Answer: Get the Calamaris package (http://cord.de/tools/squid/calamaris/).  This reads your squid log files (assuming you turned on logging) and outputs reports which should give you what you are looking for.
Answer:
goes beyond 40 users

This is a meaningless measure for webserver load.

(It was a 256MB RAM cloud machine)...So we installed squid reverse proxy

Without seeing a lot of data about how your system is behaving I would guess that the performance problems are a result of the limited amount of memory on the server; adding squid will have reduced this further.

server is performing pretty well

gosh. That's very unexpected - are you sure you optimized the webserver first?
Calamaris will give you lots of details about what squid is doing.
Comment: Learn to avoid rhetoric when answering the real question.


Docker: service 'image' must be a mapping not a string

Question: I'm install openvpn-status and npm install not work for me so I use docker instead. And when using docker-compose I got the error:
docker-compose up docker-compose.yml
ERROR: In file './docker-compose.yml', service 'image' must be a mapping not a string.

here is my docker-compose.yml
version: '2'
services:
  openvpn-status:
  image: auspexeu/openvpn-status
  container_name: openvpn-status
  volumes:
    - './status-cfg/cfg.json:/usr/src/app/cfg.json'
  ports:
    - 8080:3013
  restart: "unless-stopped"

Very appreciate with any solutions from you :D
Thanks
Answer: Your indentation is incorrect. With the version 2-3 format, under services is your service names, and under those service names are the settings for each service.
version: '2'
services:
  openvpn-status:
    image: auspexeu/openvpn-status
    container_name: openvpn-status
    volumes:
      - './status-cfg/cfg.json:/usr/src/app/cfg.json'
    ports:
      - 8080:3013
    restart: "unless-stopped"


How to compare a value of a single column over multiple columns in the same row using pandas?

Question: I have a dataframe that looks like this:
np.random.seed(21)
df = pd.DataFrame(np.random.randn(8, 4), columns=['A', 'B1', 'B2', 'B3'])
df['current_State'] = [df['B1'][0], df['B1'][1], df['B2'][2], df['B2'][3], df['B3'][4], df['B3'][5], df['B1'][6], df['B2'][7]]
df

I need to create a new column that contains the name of the column where the value of 'current_State' is the same, this is the desired output:

I tried many combinations of apply and lambda functions but without success. Any help is very welcome!
Answer: You can compare the current_State column with all the remaining columns to create a boolean mask, then use idxmax along axis=1 on this mask to get the name of the column where the value in the given row equal to corresponding value in current_State:
c = 'current_State'
df['new_column'] = df.drop(c, 1).eq(df[c], axis=0).idxmax(1)

In case if there is a possibility that there are no matching values we can instead use:
c = 'current_State'
m = df.drop(c, 1).eq(df[c], axis=0)
df['new_column'] = m.idxmax(1).mask(~m.any(1))

>>> df

          A        B1        B2        B3  current_State new_column
0 -0.051964 -0.111196  1.041797 -1.256739      -0.111196         B1
1  0.745388 -1.711054 -0.205864 -0.234571      -1.711054         B1
2  1.128144 -0.012626 -0.613200  1.373688      -0.613200         B2
3  1.610992 -0.689228  0.691924 -0.448116       0.691924         B2
4  0.162342  0.257229 -1.275456  0.064004       0.064004         B3
5 -1.061857 -0.989368 -0.457723 -1.984182      -1.984182         B3
6 -1.476442  0.231803  0.644159  0.852123       0.231803         B1
7 -0.464019  0.697177  1.567882  1.178556       1.567882         B2

Comment: Great answer considering OP only posted an image (frowned upon).  So curiouis how you obtained the values for the DataFrame (hopefully did have to enter by hand)?
Comment: Thanks @DarrylG i didn't entered the values by hand :) I guess you missed the part in the question where the code to generate the sample dataframe is given.
Comment: @ShubhamSharma--yes, I missed that line.  Thanks for pointing it out.  Upvoted OP question (in addtion to your answer) for the thorough posts.
Comment: Thank you very much, @Shubham, for your answer, that was a quite elegant solution and works perfectly in my case
Comment: @DianaMenesesGustin Glad i could help!


Using date and rules to publish and unpublish content

Question: I have two scenarios:

I have a meditation content type that need to show in a view when the date field = today's date. I want a view to show a meditation every year on the same date.
I need to create a new node of a certain content type every week where the date field has a start date of today's date and a relative end date of + 13 days.

How to create those two scenarios using rules? I am trying to understand rules scheduler. I think it can solve both scenarios.
Comment: You haven't asked a question here. You've listed some criteria for a view, and I'm not sure sure about the 2nd scenario. In both these scenarios, you've not explain how they relate to the title of question.
Answer: Create a new node of a certain content type using rules
Use rules action "Create entity" to create a node, whereas "node" is a type of entity.
For the fields that you want to provide some value for (as part of your rules action), make sure to add a Rules conditions - "Entity has field" (with the field corresponding to each such field). Doing so will ensure they are available in the Rules action (to set a value for it).
Repeat the creation of such new node
Use the rules scheduler as explained in the video about "Repeating scheduled events". The "clue" here is:

as the last action of your rule, you reschedule the same rule to be executed again after +13 days from today on. Or maybe execute the rule again "weekly" (as per your details in "2.").
the very first time (today + 13 days) you need to trigger the execution of this rule manually (from the rules UI). Since there doesn't seem to be any event in your question that you can use to trigger this rule.

Video tutorials
If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.
PS: Your question seems to contain 2 questions, of which "1." is not clear to me (something about creating a view?). After you enhance your question (as suggested by Shawn also), I might enhance my answer also.
Comment: Thank you for the comprehensive answer. for question 1: I have added 365 content of a node type meditation. I have a view that shows only one meditation which is today's meditation. for example: today's meditation is 9/18/2015. I need this content to show in this view on 9/18/16, 9/18/17, etc. So I was thinking maybe I need to sort the meditation by publish date and execute a rule that unpublish each meditation after 364 days of publishing it and another rule to publish each meditation after 1 year of publish.
Comment: For Question 2
How can I use rules to create a new node and schedule it so that it publish after 13 days at 5 am or every other Monday at 5 am? I watched the video and I am still trying to figure it out.


Why are these sufficient conditions for $\liminf$?

Question: My professor today stated that to show that $\liminf a_n=A$ it is sufficient to show
If
$1.\,a_n\geq b_n,\,\,\forall n\in\mathbb{N}$
$2.\,a_{n_k}\leq c_k,\,\,\forall k\in\mathbb{N}$
$3.\lim c_k=\lim b_n=A,\,\,n,k\to\infty$
then
$\liminf a_n=A,\,\,n\to\infty$

What is the idea or intuition behind this? I somewhat see a squeeze theorem and maybe(?) the use of Cauchy sequences, but it is not clear to me how we can go from needing to evaluate $\liminf$ to simply evaluating $\lim$.
Comment: $\lim a_n = A$ implies $\liminf a_n = A$, thus the third condition is all you need.
Comment: @MathematicsStudent1122 That is a typo, it should be $c_k$
Comment: What does $a_{n_k}$ mean?
Comment: @MathematicsStudent1122 it is a subsequence of $a_n$
Answer: Let $D = \liminf a_n$. We have that $D \leq \lim \inf a_{n_k}$, since the $\lim \inf$ of the  full sequence is at most the $\liminf$ of any subsequence. Since $\lim \inf a_{n_k} \leq \lim \inf c_k = \lim c_k = A$, we get that $D \leq A$.
On the other hand, since $a_n \geq b_n$ for each $n$, $D \geq \lim \inf b_n = \lim b_n = A$.
Thus $D=A$.
Comment: Perfect, thank you. The same conditions would be sufficient for $\limsup$ correct? Except, with the inequality signs reversed.


Can a runner be on base in baseball when it is his turn to bat?

Question: I don't know if this is actually possible based on 3 outs in an inning, but is it possible to be on base when it is your turn to bat? If so what happens to your at-bat.
Scenario would be lead-off batter gets on can the order return to his turn at bat before he scores?
Single, then on 3rd base when he is up to bat?
Does this make sense?
Thanks
Answer: Apart from batting out of order, the answer is no.
The whole purpose of batting is to hit the ball to obtain the right to run the bases. So a batter can't get on base without hitting the ball first (unless he walks).
Counting home plate (where you bat), there are potentially four base runners. Three outs ends the inning, so there can be at most two outs, with the inning continuing. That accounts for six men.
There are nine men on the baseball team, which means that there will be at least three more men ahead of you before you can bat again if you've just scored a run.
Comment: re your edit, or gets hit by the pitch, or reaches on a dropped third strike, or is granted the base due to catcher's interference....
Comment: @waxeagle: I consider all of those "walks," with the most usual one being "base on balls."
Answer: Ok did some more googling and came across section 6.07 of the MLB rules (http://mlb.mlb.com/mlb/official_info/official_rules/batter_6.jsp).
It allows for 1 player to bat out of order as long as no appeal is made.
Example #6 covers this scenario:

"PLAY (6). Daniel walks and Abel comes to bat. Daniel was an improper
  batter, and if an appeal is made before the first pitch to Abel, Abel
  is out, Daniel is removed from base, and Baker is the proper batter.
  There is no appeal, and a pitch is made to Abel. Daniels walk is now
  legalized, and Edward thereby becomes the proper batter. Edward can
  replace Abel at any time before Abel is put out or becomes a runner.
  He does not do so. Abel flies out, and Baker comes to bat. Abel was an
  improper batter, and if an appeal is made before the first pitch to
  Baker, Edward is out, and the proper batter is Frank. There is no
  appeal, and a pitch is made to Baker. Abels out is now legalized, and
  the proper batter is Baker. Baker walks. Charles is the proper batter.
  Charles flies out. Now Daniel is the proper batter, but he is on
  second base. Who is the proper batter? RULING: The proper batter is
  Edward. When the proper batter is on base, he is passed over, and the
  following batter becomes the proper batter."
Comment: @Bob [This link has a lot of cases of this happening](http://www.retrosheet.org/outturn.htm)
Comment: has there been a case in the major leagues where someone batted out of order and the opposition did not notice it?
Answer: Mathematically impossible. The lineup can only advanced 5 places maximum before the inning is over due to 3 outs or before you're forced home because batters reaching base safely. You'd have to advanced the lineup 8 places to be at bat again.
Comment: This doesn't add anything to the answers above, and might be better as a comment.


ggplot2 function for filling a circle under a horizonal line?

Question: I am trying to plot a circle in R, then fill a portion above a horizontal line with one color, and a portion below a horizontal line with another color, but I can't quite get it to work.
I've gotten so far as to draw the circle I want, plot a rectangle on top to "erase" the portion of the circle that should be transparent. However, I can't do a similar thing to get the other portion of the circle to layer on top because the white rectangle would cover the first circle.
Ideally, I'd love a way to just define a chord and then remove anything on one side of the chord.
Here's the simple code I have now and an example of what it creates:
ggplot()+
  geom_circle(aes(x0=0,y0=0,r=1,fill="red"),color=NA)+
  geom_rect(aes(xmin=-1,ymin=-0.5,xmax=1,ymax=1),fill="white",color=NA)+
  theme_void()

I was hoping to produce a full circle with the portion seen above in red and the rest of the circle filled in blue.
If it helps, here's the answer for what I want to do in python! How to draw a filled arc in matplotlib But not in R.
Answer: Use ggforce::geom_circle() to make the larger portion of the circle, and ggplot2::geom_ribbon() to make the smaller portion. You'll have to compute the points for geom_ribbon() manually as shown in my example.
library(dplyr)
library(ggplot2)
library(ggforce)

y_cut <- -.5

c_pts <- tibble(
    deg = 0:360,
    r = 1,
    x = r * cos((deg * pi)/180),
    y = r * sin((deg * pi)/180)
  ) %>%
  filter(y <= y_cut)

ggplot() +
  geom_circle(
    aes(x0 = 0, y0 = 0, r = 1),
    fill = "blue",
    color = NA
  ) +
  geom_ribbon(
    data = c_pts,
    aes(x, ymin = y, ymax = y_cut),
    fill = "red",
    color = NA
  ) +
  theme_void()

Comment: Thank you! Gorgeous work. I can definitely build from here.


How to make billing cycles available as product attributes?

Question: On our current billing system (from which we are trying to switch to Drupal Commerce) customers can select a product and then easily select between monthly, quarterly and yearly payment periods. In other words, billing cycles can be selected as product attributes.
And I can't figure out how to make billing cycles available as product attributes on a DC setup. According to the instructions on Commerce License Billing products are bound to billing cycle types. Does that mean I have to create three different products (for each monthly, quarterly and yearly billing cycles) for every single good or service product we offer on our website to customers? Doesn't make much sense for websites selling tens different types of services. I would appreciate if someone could point me to the right direction of configuring this.
Answer: Yes, you need to create different products that are linked to the billing license configurations you want. This means that if you want monthly, quarterly, and yearly billing options, these would each be tied to products and then available via a dropdown.
Comment: I don't like this design as it triples the number of products for each good/service, however since it is apparently the only way of doing it in DC I accept your answer. Thanks.


How many elements in a ring can be invertible?

Question:
If $R$ is a finite ring (with identity) but not a field, let $U(R)$ be its group of units. Is $\frac{|U(R)|}{|R|}$ bounded away from $1$ over all such rings?

It's been a while since I cracked an algebra book (well, other than trying to solve this recently), so if someone can answer this, I'd prefer not to stray too far from first principles within reason.
Comment: What do you mean by "bounded away from 1"?
Comment: @user26857:  I don't remember any longer, but it probably had to do with probability in choosing a random element.  (I just now realised you likely aren't the user26857 I intended anymore.)
Answer: $\mathbb{F}_p \times\mathbb{F}_q$ has $(p-1)(q-1)$ invertible elements, so no.
Since $\mathbb{F}_2^n$ has $1$ invertible element, the proportion is also not bounded away from $0$.
Comment: Wow, you guys are good -- I might have hit upon that, but not this fast!
Answer: The bound given by navigetor23 is tight for example in the case $R=\mathcal{O}/\langle p^2\rangle$, where $\mathcal{O}$ is the ring of integers of a finite unramified extension of the $p$-adic numbers of degree $n$: $|R|=p^{2n}$ and there are $p^n$ non-units consisting of the cosets in $p\mathcal{O}$.
Answer: By the way, the number $\# U(R)/ \#R$ equals $\sum_{\mathfrak{m}} \left(1-\frac{1}{\# R/\mathfrak{m}}\right)$, where the sum ranges over all maximal ideals $\mathfrak{m} \subseteq R$.


Error Creating zip file In Memory using Java

Question: Here is the code that I'm using to create a zip file:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream out = new ZipOutputStream(baos);
try {
    for(int i=0; i<docId.length; i++){
        BoxDotComDocumentManager docman = new BoxDotComDocumentManager();
        Document d = docman.get(docId[i]);
        ZipEntry entry = new ZipEntry(d.getFileName());
        entry.setSize(d.getFileBytes().length);
        out.putNextEntry(entry);
        out.write(d.getFileBytes());
        resp.setContentType("application/zip");
        resp.setHeader("Content-Disposition", "attachment; filename="+ "zipdemo.zip");
        out.closeEntry();
 }
 } catch (Exception e) {
      System.out.println("E = " + e);
 }
 try {
       resp.getOutputStream().write(baos.toByteArray());
   resp.flushBuffer();
} catch (IOException e) {
   e.printStackTrace();
    }
 finally {
baos.close();
out.close();
 }

the zip file is being returned to the browser to be downloaded but when I attempt to download the file I'm receiving an error stating that the file cannot be downloaded because the zip file is invalid.
Document is an object which contains all of the information about a file including the actual file.
Any ideas as to what I'm doing wrong?  I've tried a lot of permutations of this and none of them seem to work.  Thank you in advance.
Keith
Comment: But it's making it very easy for you to *miss* exceptions. IMO, it's worth getting the exception handling right *first* so that you can tell when you're really going through the happy path...
Comment: For one thing: when you encounter a fatal error, *don't* just print the stack trace. Make the request fail. Also, don't catch bare Exceptino - it's almost always the wrong approach. Oh, and why are you setting the headers on each iteration of the loop?
Comment: Jon - Just trying to make a happy trail work and then I'll handle all of the exceptions properly, same thing with the headers; having them in the loop or outside doesn't change the error.  They will be moved out of the loop.
Comment: I appreciate your feedback; any idea why this isn't working?  I know that the exception handling isn't correct but that wouldn't effect the proper creating and downloading of this file.
Answer: Try using the out.write method with 3 arguments.
Replace:
out.write(d.getFileBytes());
With:
out.write(d.getFileBytes(),0,d.getFileBytes().length);
Note: According to the java doc the write method with one parameter doesn't get read.

Writes b.length bytes to this output stream.
The write method of FilterOutputStream calls its write method of three
  arguments with the arguments b, 0, and b.length.
Note that this method does not call the one-argument write method of
  its underlying stream with the single argument b.

Making this change in my own code fixed my problem.


How do I map from a source property to the destination?

Question: I swear I've done it before, but I can't seem to get it to work now.  Basically I'm getting an EndUser containing a Site, and I want to map that Site to a SiteInfo object.
Here's my map configuration:
Mapper.CreateMap<Site, SiteInfo>()
    .ForMember(dest => dest.SiteID, opt => opt.MapFrom( src => src.ID))
    .ForMember(dest => dest.CompanyID, opt => opt.MapFrom(src => src.Company.ID));

Mapper.CreateMap<EndUser, SiteInfo>()
    .ForMember( dest => dest, opt => opt.MapFrom(src => src.Site ));

So EndUser.Site should be able to map to SiteInfo. I can do this on the outside by just calling Mapper.Map<SiteInfo>(EndUser.Site). I think it's just cleaner syntax to map from the end user to the location info directly.
So how can I map directly from EndUser to SiteInfo?  Basically this is the code I'd LIKE to write:
var user = mcp.Users.GetEndUser(userAddress.Address);
var siteInfo = Mapper.Map<SiteInfo>(user);

Currently I'm working around the issue by just mapping from EndUser.Site like this:
var user = GetEndUser(emailAddress);
            var siteInfo = user == null
                            ? null as SiteInfo
                            : Mapper.Map<SiteInfo>(user.Site);

Answer: Do you want to map Location to SiteInfo or LocationInfo? What is the dest property you're mapping to in your EndUser -> SiteInfo mapping? Does SiteInfo contain a combination of both Location and EndUser properties?
Without that info I'm only guessing, but are you trying to do something like this?
var rc = Mapper.Map<SiteInfo>(endUser);
rc = Mapper.Map(endUser.Location, rc);

UPDATE
So if I understand correctly, you're after a mapping like this?
Mapper.CreateMap<EndUser, SiteInfo>()
    .ForMember(dest => dest.SiteID, opt => opt.MapFrom( src => src.Site.ID))
    .ForMember(dest => dest.CompanyID, opt => opt.MapFrom(src => src.Site.Company.ID));

Comment: Edited to answer some of your questions and make things more clear (Location should really be Site throughout the example, but I switched names midway through the project. )


Derivative of a function which is defined as a derivative

Question: I'm new to this kind of stuff so maybe this is a stupid question but I don't even know what to search on the internet.
My problem is that: find the derivative of the following function on $\Bbb R^3$
$g(x;y)=D^xf(y)$
Where $D^x$ is the x-th derivative of the function $f(y)$ defined on $\Bbb R^2$ (assuming that is continuos and always differentiable). I know that, using fractional calculus, $D^x$ is well defined for every $x\in \Bbb R$ but I don't know if the function I wrote has any sense or which branch of math studies this kind of relations so I don't even know how to start. Any hint ?
Just to make things clearer I make an example:
Take $f(y)=y^2$ as the function, some values would be:
$g(1;y)=2y$
$g(2;y)=2$
$g(3;y)=0$
Answer: The derivative of a function on $\mathbb R^3$ is not really a good way to put it. You can take the partial derivative (which is the derivative with respect to a specific variable). In addition, if you have a function defined on $\mathbb R^2$ I don't think trying to find derivatives in $\mathbb R^3$ is going to make much sense (fractional calculus aside).
Having said all of that, if you have a function
$$F=f(y)$$
you can use the derivative operator to find z given...
$$(1) \quad z=D^x \cdot f(y)$$
To answer your question, equations like $(1)$ are studied all the time in mathematics. If you have $z$, but would like $f(y)$ you need integrals and possibly the theory of differential equations. If you have $f(y)$, but would like z, you need the theory of differentiation. If your interested in non-integer derivatives then replace the above subjects with the prefix-"fractional".
Here are some links,
Intro to Fractional Calculus,
Intro to Fractional Differential Equations,
Interpretation of Fractional Derivative,
Geometric Interpretation of Fractional Integration. The last link I provided is a bit silly, as it just is a paper about vector projection, it doesn't actually provide physical intuition, it just identifies how one would plot the integral.


How to increment value via $inc in Mongoose

Question: I am trying to increment a field value using $inc without too much success. I have the following schema:
var postSchema = mongoose.Schema({
  title         : { type: String, required: true },
  body          : { type: String, default: '' },
  counter       : counterSchema
});

var counterSchema = mongoose.Schema({
  upvotes       : { type: Number, default: 0, min: 0 },
  downvotes     : { type: Number, default: 0, min: 0 },
  view          : { type: Number, default: 0, min: 0 }
});

I am trying to increment values in counter, and what I have is:
  ...
  let where = `{ '_id': ObjectId("${req.body.pid}") }`:
  let update = req.body.action === 'up' ? "{ '$inc': { 'counter.upvotes': 1 } }"
                                        : "{ '$inc': { 'counter.downvotes': 1 } }";

  Post.findOneAndUpdate(where, update, {'new': true}, (err, post) => {
    if (err) return next(err);
    console.log('post=' + JSON.stringify(post));
  ...

I was able to successfully increment in mongod using the statement,
db.posts.update({_id: ObjectId('56cd78fddfe1372131a04b4d')}, {$inc: {'counter.upvotes': 1}})

so I initially thought it had to do with Mongoose syntax, and tried number of variations including:

Using collection...update().exec(...) format
Enclosing keys and values in single, double, no quote
Omitting ObjectId, ie, { '_id': id) }

But so far no luck. Any help would be greatly appreciated.
PS. The code does execute successfully without error, and I get back a post since I set the option to {'new': true}. It's just that either of post.counter.[upvote | downvote] is incremented in what's returned nor in the mongodb.
Answer: Your where and update variables need to contain objects, not strings.
So it should be like this instead:
let where = { '_id': ObjectId(req.body.pid) };
let update = req.body.action === 'up' ? { '$inc': { 'counter.upvotes': 1 } }
                                      : { '$inc': { 'counter.downvotes': 1 } };


How do I Install an earlier version of Drupal 8 with composer because install fails on server with PHP 5.6?

Question: My server is using PHP version 5, therefore, I need to install Drupal 8 version 8.6.18. But when I try, composer create-project drupal-composer/drupal-project:8.x-dev my_site_name_dir --no-interaction --no-install, I get the following error.
  [InvalidArgumentException]
  Could not find package drupal-composer/drupal-project with version 8.x-dev
  in a version installable using your PHP version 5.6.40.

Is there anyway to install 8.6.18 with composer?
Comment: PHP 5 is no longer getting security fixes, not supported by PHP nor D8, 2 times slower than PHP 7. Thus, upgrade to PHP 7.
Comment: Is there a reason why you are still running PHP 5.6?
Answer: Drupal 8 does not support PHP version 5. It requires a minimum PHP version of 7.0. Please see here for Drupal install requirements
Drupal Installation Requirements - Drupal.org
So you will have to upgrade PHP on your machine. Also PHP 5.0 is no longer supported and is not secure. So you might want to upgrade PHP on your server any way.
PHP Supported Versions - php.net
Comment: Sure. Good luck with your trying out Drupal. The community will be more than happy to help you with issues if you run into any.
Comment: thank you very much!


An AJAX HTTP error occurred using commerce coupon percentage

Question: I'm able to create coupons with no errors. When I enter coupon code into the field and click on the submit button I get the following error.
<code>An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /system/ajax
StatusText: Service unavailable (with message)
ResponseText:
</code>
Drupal version 7.28
Commerce Coupon Percentage 7.x-1.0-beta7
dblog messages
<code>// first error
Rules Warning:
  Unable to get a data value.
Error:
  Unable to get the data property code as the parent data structure is not set.
// second error
Rules Warning:
  Unable to evaluate condition commerce_coupon_discount_coupon_codes_exist_on_order.
// second error
PHP Error:
  EntityMetadataWrapperException:
  Unable to get the data property coupon_id as the parent data structure is not set.
  in EntityStructureWrapper->getPropertyValue()(line 438 of /homepages/
  36/d385915579/htdocs/bbp/sites/all/modules/entity/includes/entity.wrapper.inc).
</code>
Comment: That means a fatal error happen when processing the AJAX petition. Check the dblog entries (/admin/reports/dblog, make sure db log core module is enabled). Also check your PHP log errors (log path depends on your system setup)
Comment: I edited the post to include dblog messages.
Answer: This seems an error in Commerce Coupon Percentage module. Your problem comes from the EntityMetadataWrapperException: when processing the AJAx petition something goes wrong and an Exception is throw. This is fatal, so Apache ends the petition with the status 500.
I think this a bug in the module code, so you may go the issue queue for this module and create a new bug report with your problem.
By the way, the Commerce Coupon Percentage is only comptabible with Commerce Coupon 1.x, check your are using a 1.x release.
Comment: You were right to suggest I look at the version of Commerce Coupon. After some considerable [effort](http://drupal.stackexchange.com/questions/119015/what-is-the-proper-way-to-drop-database-references-for-an-uninstalled-drupal-mod/120766#120766) I was able to reinstall everything which cleared up the EntityMetadataWrapperException: Error for coupon_id however I now get one for currency_code and I still have the ajax error which may or may not be related. I'm going to ask a separate question to deal with the remaining errors and how to find out their causes. Thank you @tunic!


LINQ to select Leads where FirstName.length < 6

Question: Which LINQ will select Leads where FirstName.length < 6?

This query throws "Invalid 'where' Condition. An entity member is invoking an invalid property or method"
var q = from a in serviceC.LeadSet where a.FirstName.Length < 6 select a;

Comment: Maybe related http://weblogs.asp.net/pabloperalta/archive/2012/04/04/notsupportedexception-invalid-where-condition-an-entity-member-is-invoking-an-invalid-property-or-method.aspx
Comment: @TimSchmelter It does list the LINQ to CRM Limitation that Bvrce is violating, but the solution specified is not possible if Brvce does need to get the leads where the first name is less than 6
Answer: The reason this doesn't work is that all Linq to CRM Statements are converted into Query Expressions, and Query Expression don't support a length operator.  This leaves you with a couple options.

Use a direct SQL query to get the data you need.  This is less than desirable for most situations since you're operating outside of the SDK, and not possible if you're using CRM Online
Use Grant's answer to actually look at the length, which unfortunetly does pull all of the records...
Try this totally untested idea I just came up with:  Query Expression do have a GreaterEqual condition so you should be able to compare it to a string of 6 single quotes (since single quotes are the first character when sorted by default.  So theoretically, this should work:

var q = from a in serviceC.LeadSet where a.FirstName <= "''''''" select a;

EDIT
After performing a test I realized that Linq won't accept that Expression, even though SQL will.  So the answer is to create the actual Query Expression:
QueryExpression qe = new QueryExpression("lead");
qe.Criteria.AddCondition("firstname", ConditionOperator.LessEqual, "''''''");

var entities = service.RetrieveMultiple(qe);

Answer: You could use ToList to project the collection to objects, that should do it.
Comment: That would result in the entire database table being transferred to the client and the filter being done on the client. This won't scale.
Comment: @JimWooley I know. Well, actually, not the _entire_ database necessarily, but the point is potential heavy loading.


Coin Flip Statistics Program - undefined method

Question: I'm trying to write a coin flip program where I can analyze the percentage of Heads flipped.  I've gotten coin flip to work, just not the actually analyzing yet.
The problem is when I created a Coin class in order to further break down the object into something like Coin.length afterwards.
Why am I getting an "undefined method 'flip' for Coin:Class (NoMethodError)"   from flip.rb:14:in 'times'
    from flip.rb:14:in
 when I indeed have one?
class Coin

def flip
  flip = 1 + rand(2)
    if flip == 2
        then puts "Heads"
    else
        puts "Tails"
    end
end

end

10.times do
  Coin.flip
end

Here's a die roll example that I am somewhat trying to emulate:
 class Die

     def roll
       1 + rand(6)
     end

  end

    #  Let's make a couple of dice...
    dice = [Die.new, Die.new]

    #  ...and roll them.
    dice.each do |die|
      puts die.roll
    end

Answer: Coin.flip is not a method you defined; this would be a class method, and to define a class method called flip you would write:
class Coin
  def self.flip
    ...
  end
end

What you created is an instance method, and as such it requires that it is called on an instance:
coin = Coin.new
coin.flip
# or
Coin.new.flip

In your second example (with the Dice), you are correctly calling new and creating instances.
Answer: you defined instance method filp, but there is no class method called Coin.flip.


Como inserir tabela excel no mysql usando php

Question: Tenho uma tabela no excel com mais de 300 linhas e gostaria de inserir os dados dessa tabela no mysql no phpmyadmin
uso php atualmente
Agradeço pela atenção!
Answer: Se é um trabalho que vai ser feito apenas uma vez e/ou esta migrando de um excel para o seu banco, você pode baixar o MySQL Installer que tem várias ferramentas em:

https://dev.mysql.com/downloads/installer/

Aqui é demonstrado um preview dele:

https://www.mysql.com/why-mysql/windows/excel/

Agora se a intenção é realmente trabalhar documentos .xls e .xlsx com PHP via upload então recomendo que tenha em mente que boa parte você quem terá que desenvolver:
Primeiro será o upload do documento, usando move_uploaded_file
Depois use o https://github.com/PHPOffice/PhpSpreadsheet para extrair os dados do documento, os formatos suportados pelo PhpSpreadsheet são:

Open Document Format/OASIS (.ods)
Office Open XML (.xlsx) Excel 2007
BIFF 8 (.xls) Excel 97 and above
BIFF 5 (.xls) Excel 95
SpreadsheetML (.xml) Excel 2003
Gnumeric
HTML
SYLK
CSV

Para instalar é preciso usar o composer, se já tiver composer instalado então via CMD ou terminal navegue até a pasta do projeto e rode o comando:
composer require phpoffice/phpspreadsheet

Então no seu documento terá que ter algo como após o upload:
<?php

require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

... upload vai aqui ...

//Arquivo upload
$inputFileName = './upload/example1.xls';

$spreadsheet = IOFactory::load($inputFileName);

Então para acessar as celulas do documento use https://phpspreadsheet.readthedocs.io/en/develop/topics/accessing-cells/
Por exemplo celular B8:
$spreadsheet->getActiveSheet()->getCell('B8');


Bounds on integer solutions to multivariate polynomials

Question: The following problem came up while I was doing a related homework problem.
Imagine we have $f_1,\ldots,f_m$ be multivariate polynomials in variables $x_1,\ldots, x_n$ with rational coefficients. Can we bound the possible size of the smallest integer solution (that is to say find some $M$ such that if an integer solution exists, then there is an integer solution $a_1,\ldots,a_n$ such that $|a_i|<M$). If such a bound exists I imagine it depends on the number of $f_i$, their degree, and the size of their coefficients.
I am asking more about the existence of such a bound than what it is. Also it seems reasonable to me that such a bound would exist, but in my attempts to show this I have been getting hung up on something in each of the directions I have tried to go to prove it.
Thank you for any help or direction
Comment: If we could it would mean a decision procedure for diophantine problems, but this is known not to be the case.
Comment: I'd like to suggest some clarifications of your question, for possible benefit to your readers.  Are the polynomials here _integer coefficient_ polynomials?  Are you asking about an effectively computable bound with general application?  I was going to add a note to my answer about the univariate case, and these clarifications would inform such a note.
Comment: I originally had in mind rational coefficients, but this is equivalent to integer coefficients. I understand the univariate case (the bound can be gotten from Rouché's Theorem of complex analysis), but there is no harm in adding a note
Answer: Building on earlier work of Julia Robinson, Martin Davis, and Hilary Putnam, Yuri Matiyasevich's theorem proved that Hilbert's tenth problem has a negative answer: there is no general procedure for deciding if a diophantine equation has a solution in (rational) integers.
If there were a procedure such as specified in this Question, applying it to a diophantine equation would produce a bound on the smallest integer solution (involving multiple variables), and a procedure of checking all possibilites less than that bound would then decide whether any integer solution exists.
Many specific diophantine problems, however, may be attacked in this way.  Computing effective bounds on integer solutions of elliptic curves is one such research of area.
Added:  Multiplicity of equations is not essential, since a sum of squares of rational polynomials being zero implies each of them is zero (at any real (specifically rational integer) point of evaluation).  However the multivariate aspect of the problem is essential for undecidability (lack of constructive bounds).  A univariate rational polynomial equations can be converted to one with integer coefficients by clearing denominators, and in this form the Rational Root Theorem implies any integer solution would divide the constant term.  In particular the (absolute value of the) constant term gives an upper bound on the smallest integer solution as asked for.


Expressions Web 4 Format Code Shortcut?

Question: Is there a keyboard shortcut for formatting code like Visual Studio has Ctrl+K Ctrl+D?
Answer: Based on @Ryan Anderson's answer:
To reformat the code of an existing page:

Open the web page you want to reformat.
In the Code pane, right-click and select Reformat HTML.
Answer: Found it.... http://expression-web-wiki.com/index.php?title=Format_code
Comment: Where is the shortcut in that document?

Expressions Web 4 Format Code Shortcut?


Is a smooth cubic in $\mathbb P^2(\mathbb C)$ never birational to a line in $\mathbb P^2(\mathbb C)$?

Question: Let $V$ be a smooth cubic in $\mathbb P^2(\mathbb C)$ ; then is it true that $V$ cannot be bi-rationally equivalent to $\mathbb P^1(\mathbb C)$ ?
We know that $V$ is bi-rationally equivalent to the cubic defined by
$Y^2Z=X^3+aX^2Z+bXZ^2+cZ^3$ . But I'm unable to say anything else (I'm not even sure whether this simplification of $V$ is helpful or not).
Please help. thanks in advance .
EDIT : Please don't use the concept of genus. I think it can be done without using genus.
Comment: There are two proofs which boil down to field theory (hence do not use the concept of genus) in Reid's [*Undergraduate algebraic geometry*](https://homepages.warwick.ac.uk/staff/Miles.Reid/MA4A5/UAG.pdf); see (2.2) and Exercise 2.12. Another proof is outlined in Hartshorne, Exercise I.6.2 for the particular cubic curve $y^2=x^3-x$, but as far as I can tell the same argument works for other cubics as well. The basic idea of Hartshorne's proof is that the coordinate ring of a(n affine) cubic curve is not a UFD, while (affine) rational curves have coordinate rings which are UFD's.
Comment: A line has genus $0$ – a smooth cubic, genus $1$.
Comment: @Bernard: Please don't use the concept of genus
Comment: @users : in fact I might have another solution I'll write an answer.
Comment: @NicolasHemelsoet: ok, thanks
Comment: Well, what *have* you learned, then? Do you know that every birational class of curves has a unique smooth projective representative? This reduces it to isomorphism invariance; which isomorphism invariants have you learned?
Answer: Let $f : X \to \Bbb P^1$ be a birational morphism. If $X$ is a smooth curve, you can show that $f$ should extend to a regular morphism.
Now, $f$ has degree $1$ so it should be an isomorphism, since it's injective and surjective.
This is a contradiction because a cubic curve is not isomorphic to $\Bbb P^1$ since even topologically they are different.
Comment: extend where to a regular morphism ? How do you prove it ?
Comment: So $f : X \to \Bbb P^1$ is birational means that there is a Zariski open $U$ and a morphism $f : U \to \Bbb P^1$. Now $U$ is $X$ minus some point, and take $p \in X \backslash U$. There are local coordinates $(z,w)$ around $p$ so that $f = [f_1(z,w):f_2(z,w)]$ where $f_1, f_2$ are homogenous polynomials of the same degree. Now, say $p$ corresponds to $(z_0,w_0)$ : you can do a Taylor expansion of $f_1,f_2$ at $(z_0,w_0)$ and see that necessarly you have either $0,\infty$ or a finite limit. In any case the morphism extends.
Comment: Could you please elaborate on why $\mathbb P^1$ cannot be isomorphic with a cubic ?
Comment: A complex smooth projective cubic is homeomorphic to a torus $S^1 \times S^1$ and $\Bbb P^1$ is topologically $S^2$.


Local alias in /etc/hosts not working anymore without internet connection

Question: I have my developer machine on which I work on web applications running under apache on Debian testing.
Now I like to be able to have myApp as domain name and not to have to use localhost or 127.0.0.1 in my browser address bar. Some CMS software doesn't support changing domains very well anyways... :-(
Now to do this I have a /etc/hosts file looking like this:
127.0.0.1 localhost
127.0.0.1 myApp
127.0.0.1 phpmyadmin
....

In my apache settings I properly configure my virtualhost servernames.
This always worked fine, but today I had to share the internet with someone and when I unplug the cabel, I can't access myApp or other aliases anymore except localhost which now delivers me the document root of 'myApp' which it is not even configured to do in apache config...
I never really knew anything of DNS under Linux, but I think I have used this before without internet and it worked.
I haven't tried rebooting without the ethernet cable plugged in, maybe that would work but I am a bit puzzled and would like to understand and fix this problem
Since recently I do have another server (jetty) listening to localhost but on another port, but that might have nothing to do with it...
Answer: Your line in /etc/hosts must be converted to:
127.0.0.1 localhost localhost.localdomain myApp phpmyadmin

Comment: thanks alot, that did the trick. I used to have it like that, but then at some point I changed it... I don't remember why. I would upvote both answers, but don't have enough rep... will do so later.
Comment: actually, sorry, I must have had a cached page in the browser because the problem persists... I haven't rebooted though (don't know if that is necessary).
Answer: Your /etc/hosts looks scrambled for me.
In man hosts the following syntax is noted: IP_address canonical_hostname [aliases...]
So my advice is to use the following:
127.0.0.1 localhost myApp phpmyadmin

Answer: Make the changes earlier answers have suggested to your /etc/hosts file and make sure that "files" is listed in the "hosts" line in your /etc/nsswitch.conf file.
(/etc/nsswitch.conf controls, among other things, the order in which the resolver library consults various sources to try and resolve host names.  if "files" isn't listed as a source /etc/hosts isn't consulted at all.  In your case it probably makes sense to put "files" before "dns" on the hosts line.)
Comment: Thanks for the tip, 'files' is already the first entry on that line.
Comment: Since you indicated above that you are still having problems..  What *exactly* do you get as the result of:  "ping myApp"?
Comment: ping myApp works fine and shows: `PING localhost (127.0.0.1)...`however firefox says `Server not found`
Comment: ok, after rebooting it works. Thanks for your help


Dúvida sobre o método onCreateOptionsMenu

Question: Alguém poderia me explicar qual a finalidade desse método?
onCreateOptionsMenu
Já pesquisei em vários sites (na documentação do Android também), mas ainda assim não ficou claro qual a finalidade desse método.
Answer: Esse é um dos métodos públicos disponíveis da Activity que podem ser sobrescritos. A finalidade dele é a de simples criação de menus de opções de uma Activity inflando um XML (Menu).
São os menus que geralmente ficam no topo ao lado direito do aplicativo.
Um exemplo de menu de opções do WhatsApp:

Notas:

Esse método é chamado apenas uma vez após o método onStart() no ciclo de vida da Activity. Para tornar dinâmico a alteração de itens do menu com base em eventos durante o ciclo de vida da Activity você pode usar o método onPrepareOptionsMenu()
A exibição do menu pode variar em versões do android

Mas porque usar as APIs de menu do Android?
Apesar de você ter liberdade para criar algo do zero, usar as APIs disponíveis é recomendado pois, além de ser bem mais fácil de criar e dar manutenção, o usuário já está familiarizado com esse tipo de navegação.

Relacionado:
onOptionsItemSelected()
Método "ouvinte de cliques" do menu de opções. Com esse método você pode saber qual item do menu foi clicado e realizar ações específicas.

Mais sobre:

Menus
Métodos públicos de Activitys


Tuning in Teradata (group by)

Question: I am trying to tune a query in Teradata. It's pretty huge, so I am giving below the outline:
<code>SEL column_1, column_2......column_20, sum(column_21), sum(column_22),.....sum(column_30)
from table_a a
inner join table_b b
on conditions...
group by column_1, ...,column_20;
</code>
I am trying to tune this. It's hitting a performance roadblock in the group by. The tables A and B are huge (more than 2 billion records).
I tried the following options, but none of them improved the performance:
1) Collected all necessary stats
2) Created a JI on the columns from table A and B
3) Created an AJI on the columns and the summations from table A and B
4) Created a SI on each of the tables for the columns involved in group by.
Can someone suggest how to proceed further?
Comment: Can you post the EXPLAIN plan? Do you know which step of the EXPLAIN the query is in fact hanging on?
Comment: How do you know the problem is in the GROUP BY and not, say, the JOIN or SUM()?
Answer: It is very hard to say anything ,  without having any details about:

query (is it always they same, or there is always different WHERE )
structure of A and B  (primary indexes/partitioning)
execution plan
log of execution (to see where is the bottleneck)

But if we assume that this single query is exactly the same every time then AJI is created and used during execution, then then only improvement that I can think of would be trying to adjust primary index of JI, so its distribution among amp would be as uniform as possible
(BTW if AJI is used then steps 2 & 4 would be waste of your time and db space)

Tuning in Teradata (group by)


rails 3, 2 check_boxes shouldn't be false at the same time, how?

Question: I have a form like this:

    <%= form_for @user do |f| %>

      <%= render '/shared/error_messages' %>

      <%= f.label :name %>
      <%= f.text_field :name %>

      ........

      <% if current_user.admin? %>

      <%= f.label :admin %>
      <%= f.check_box :admin, {checked: true} %>

      <%= f.label :developer %>
      <%= f.check_box :developer %>

      <% end %>

     ........

      <%= f.submit "Invite new user", class: "btn btn-large btn-primary" %>

    <% end %>

As you see, there are two check_boxs to determine whether the new user admin or developer. Admin is checked by default.
What I want to do is, when somebody click checked admin, it won't be unchecked. When click developer, admin will be unchecked and developer will be checked.
New user must be either admin or developer. Both check_boxes should never false at the same time
Answer: This functionality (only one possible choice) is for radio button, not checkbox
Comment: I know, but both admin and developer are separate attributes. Are radio buttons for separate choices for 1 attribute? If I can use radio buttons in my case, then how?
Comment: @kalahari if a user can't be both an admin and a dev, why having two separate attributes? Why not having a `role` text field in your db (with inclusion validation in `['admin', 'developer']`)? That said, having checkboxes that behave like radio button may be confusing from a user point of view.
Comment: I did this because I am new. I will try it, lets see
Comment: is this a true questioning `current_user.role("admin")?`  ?
Comment: No, `current_user.role == 'admin'`. But if you go this way, you will probably to define an `admin?` method
Answer: use radio buttons. If you still insist on using checkboxes, give both the check boxes a class name, bind the class in a javascript with live and do the validation !
$('.checkboxes').live('change', function(){

    if($(this).is(':checked')){
        dosomething...
    }
});

Comment: I don't know how to bind the class in javascript with live
Comment: something like this

    $('.checkboxes').live('change', function(){

        if($(this).is(':checked')){
            dosomething...
        }
    });
Comment: added an example with the answer
Comment: ok, where should I put this? `assets/javascripts/application.js` or `assets/javascripts/users.js.coffee` or somewhere else?
Comment: you can put it in any js file. The only thing is it should be loaded with your view ! Application js is loaded by default unless configured extensively. So application js should do. To verify use fire bug and check the java scripts loaded when the page is loaded.
Comment: I gave a class name `'yetki'` to both checkboxes. In this function, where should I use it so it can be recognized?
Comment: instead of .checkboxes use .yetki ... Please go through basics of binding javascripts. Just google it and you will understand it.


Can I run multiple chi-square for each conditions?

Question: HI supposed I have these conditions.
<code>    dt = structure(list(sunny = 21:22, shade = 3:2
, tree = c(384L, 807L), hat = c(24L, 43L))
, row.names = c("Control", "Treated" )
, class = "data.frame")

> dt
        sunny shade tree hat
Control    21     3  384  24
Treated    22     2  807  43
</code>
What I'm interested is if there is a difference within each group and not across. So for example I'm interested if there is a difference between control and treated in tree, and hat and so on.
Can I do something like this?
<code>     set.seed(123)
     chisq.test( as.table(as.matrix( dt[, 1]  ))  , simulate.p.value = TRUE)
     chisq.test( as.table(as.matrix( dt[, 2]  ))  , simulate.p.value = TRUE)
     chisq.test( as.table(as.matrix( dt[, 3]  ))  , simulate.p.value = TRUE)
     chisq.test( as.table(as.matrix( dt[, 4]  ))  , simulate.p.value = TRUE)
</code>
so that I will end with 4 p.values and just correct with Bonferroni?
Comment: There were 3 shades in the control and 2 shades (whatever it means) among the treated. What do those 3 and 2 mean, and why may this difference relate to the treatment?  Could "shades" migrate to "trees" as a result of the treatment?
Comment: @Alex subjects collect buried items.
they run around in different areas, sunny, shade,tree, hat.
in each areas are the total gems that were collected.
What I don't need to do is compare between sunny,shade or tree but whether there was a difference
within the tree area, that is did the treament group collected more rocks there than the none treated, and so on for each area.
Comment: The situation that you describe is very complex and statistically unusual. Because there are several subjects (and the numbers in the contingency table aren't them). Those subjects collect the items consecutive. This collection is not independent between the subjects (if the item is found by one treated subject, it cannot be collected by another treated subject or by a control subject). If a subject collects an item now he or she can't collect another item at the same time, because he or she is busy. These are all very relevant factors for modeling. Chi-2 won't work in any case.
Comment: @Alex sorry I was not clear;  all items can be collected by any subjects since they are just replaced and moreover subjects can collect as many items as they can between any of the conditions. May be I need to edit the post to describe this better?
Comment: Ok. Thanks. I added my suggestion.
Answer: I would suggest the following then
<code>chisq.test(x=dt[,1], p=c(0.5, 0.5))
</code>
Comment: You actually can. It will be pretty conservative.
Comment: thanks; follow up question if I run this 4 times, for 1..4 can I just simply multiply by 4 to get the Bonferroni correction?


Javascript function not working in Wordpress post

Question: The following code functions fine on my computer. However, when i paste it into a wordpress post the button shows but doesn't function. What do I need to tweak in Wordpress to get this to work? TIA

 <button onclick="newQuote()">New Quote</button>

Answer:
You should add  ; for quote variable
Try to search for any errors in console


How to get a record from an array result of API in React Native with condition?

Question: This is the result JSON file from API:
{
    "data": [
        {
            "recordid": "8888abc",
            "accountno": "00-00-00000-00007-00",
            "tag": "govid",
            "filename": "gov_id.png",
            "path": "C:\\MOBILEAPP\\governmentid/gov_id.png",
            "ext": ".png",
            "posted_dt": "12/11/2019 10:38:20 AM"
        },
        {
            "recordid": "8888abc",
            "accountno": "00-00-00000-00007-00",
            "tag": "compid",
            "filename": "compid.jpg",
            "path": "C:\\MOBILEAPP\\compid/cid.jpg",",
            "ext": ".jpg",
            "posted_dt": "12/11/2019 10:38:20 AM"
        }
    ],
    "error_message": "Successfully retrieved.",
    "is_success": true,
    "requested_on": "12/18/2019 2:14:27 PM"
}

I need to get the path where tag = 'govid' to be puth in a variable because it is used in the header of another API fetching.
 async getProfilePhotoPath(token) {
     //membid is recordid
    let membid = await AsyncStorage.getItem(MEMBER_ID);
    let resp2 = await fetch("https://api/files",
      {
        method: 'GET',
        headers: {
          "Authorization": "Bearer " + token,
          "MemberID": membid,
          'Content-Type': 'application/json;charset=UTF-8',
        },
      },
    )
      .then(resp2 => {
        let respImg = resp2.json();
        varImagePath = "should contain data.path where tag = 'govid'"
        console.log('This is respImg values',respImg)
        return respImg;
      })
      .catch(error => {
        alert('Error in resp2 imgpath!' + error);
      });
  }

 async getProfilePhoto() {
    let token = await AsyncStorage.getItem(ACCESS_TOKEN);

    this.getProfilePhotoPath(token);

    let resp = await fetch("https://api/filepathtoimage", {
      headers: {
        "Authorization": "Bearer " + token,
        "ImagePath": varImagePath,
      }
    })
    let respBlob = await resp.blob();
    let reader = new FileReader()
    reader.readAsDataURL(respBlob)
    reader.onload = () => {
      this.setState({ imgsrc: reader.result })
    }
  }

console.log('This is respImg values',respImg)  returns:
  This is respImg values
Promise {_40: 0, _65: 0, _55: null, _72: null}
_40: 1
_65: 1
_55:
data: Array(2)
0: {recordid: "8888abc", accountno: "00-00-00000-00007-00", tag: "govid", filename: "gov_id.png", path: "C:\\MOBILEAPP\\governmentid/gov_id.png", …}
1: {recordid: "8888abc", accountno: "00-00-00000-00007-00", tag: "compid", filename: "compid.jpg", path: "C:\\MOBILEAPP\\compid/cid.jpg", …}
length: 2
__proto__: Array(0)
error_message: "Successfully retrieved."
is_success: true
requested_on: "12/18/2019 3:10:32 PM"
__proto__: Object
_72: null
__proto__: Object

How to I put value on varImagePath (in this example should be 'C:\MOBILEAPP\governmentid/gov_id.png')?
Answer: Just use filter:
let filterString = 'govid';
const result = arr.filter(f => f.tag == filterString);

An example:

let arr = [
      {
          "recordid": "8888abc",
          "accountno": "00-00-00000-00007-00",
          "tag": "govid",
          "filename": "gov_id.png",
          "path": "C:\\MOBILEAPP\\governmentid/gov_id.png",
          "ext": ".png",
          "posted_dt": "12/11/2019 10:38:20 AM"
      },
      {
          "recordid": "8888abc",
          "accountno": "00-00-00000-00007-00",
          "tag": "compid",
          "filename": "compid.jpg",
          "path": "C:\\MOBILEAPP\\compid/cid.jpg",
          "ext": ".jpg",
          "posted_dt": "12/11/2019 10:38:20 AM"
      }
  ]

  let filterString = 'govid';
  const result = arr.filter(f => f.tag == filterString);

  console.log(result);

UPDATE:
In your response:
then(resp2 => {
    let respImg = resp2.json();
    let arr = respImg.data;
    let filterString = 'govid';
    const result = arr.filter(f => f.tag == filterString);
    return respImg;
  })

Comment: I replaced it toconst varImagePath = arr.filter(f => f.tag =='govid'); and It alerted Error in resp2 imgpath! ReferenceError: arr is not defined
Answer: resp2.json() return a promise.
.then(resp2 => resp2.json())
.then(jsonObject => {
  const data = jsonObject.data;
  const record = data.find(item => item.tag === 'govid');
  if (record) {
    varImagePath = record.path;
  }
})

Comment: This worked but I can't make varImagePath be read by getProfilePhoto().
Comment: you should await this function `await this.getProfilePhotoPath(token);`


Chamar método no bean caso condição seja true

Question: Criei este confirm:

E chamo no meu commandButton:

A idéia é chamar o método no bean somente se oo meu javascript ser true. O problema é que no onclick fala que não encontra o método. Alguém sabe como posso resolver?
Answer: Você pode usar o componente do PrimeFaces <p:remoteCommand> para fazer isso.
Exemplo:

E no seu botao voce faria:

E voce pode chamar seu remoteCommand com javascript assim:


Solve system for elements of a matrix

Question: I have a system of $n$ equations which follows a particular pattern as follows (showing the case $n=3$):
$$\phi = a_1 + \psi_2 a_2 + \psi_3 a_3 \\
\phi = \psi_1 a_1 + a_2 + \psi_3 a_3\\
\phi = \psi_1 a_1 + \psi_2 a_2 + a_3$$
The scalars $\phi$ and the $a_i$ are known, and I need to solve for the $\psi_i$. All scalars are $\in \mathbb{R}$.
So I am trying to rewrite it into a matrix equation, and getting mixed up with constructing the matrix, and then solving, somewhat similar to this and this previous questions.
So I've got this far:
$$\phi \begin{Bmatrix} 1\\1\\1 \end{Bmatrix} =
\begin{bmatrix}
1 & \psi_2 & \psi_3 \\
\psi_1 & 1 & \psi_3 \\
\psi_1 & \psi_2 & 1
\end{bmatrix}
\begin{Bmatrix} a_1\\a_2\\a_3\ \end{Bmatrix}
$$
which more generally can become:
$$\phi\boldsymbol{\unicode{x1D7D9}}_{n\times 1} = \boldsymbol{\Psi}_{n\times n} \boldsymbol{a}_{n\times 1}$$
so to solve for the vector $\boldsymbol{\psi} = \left[\psi_1, ..., \psi_n\right]^T$ and inspired by this I try to decompose $\boldsymbol{\Psi}$ as follows:
$$ \boldsymbol{\Psi} = \left[ \textrm{diag}(\boldsymbol{\psi} )(\boldsymbol{\unicode{x1D7D9}}_{n\times n}) - \boldsymbol{I}_{n\times n}\right]^T + \boldsymbol{I}_{n\times n} $$
but this both feels messy, and also doesn't seem to make finding $\boldsymbol{\psi}$ any easier. The system might also be overdetermined.
Any ideas appreciated!
Answer: $
\def\o{{\tt1}}
\def\M{\Psi}
\def\LR#1{\left(#1\right)}
\def\BR#1{\Big(#1\Big)}
\def\op#1{\operatorname{#1}}
\def\Diag#1{\op{Diag}\LR{#1}}
\def\a{{\o a^T}}
$Let $x$ denote the unknown vector and $\o$ the all-ones vector, then
$$\eqalign{
\M &= I + \o x^T - \Diag{x} \\
}$$
This decomposition allows your linear system to be algebraically manipulated and solved
$$\eqalign{
\phi\o &= \M a \\
 &= a + \o\LR{x^Ta} - \Diag{x}\,a \\
 &= a + \LR{\a}x - \Diag{a}\,x \\
\LR{\phi\o-a} &= \BR{\a - \Diag{a}}\,x \\
x &= \BR{\a - \Diag{a}}^{\bf+}\LR{\phi\o-a} \\
}$$
where the pseudoinverse is used since the matrix in parentheses can be singular.
Comment: This is neat! and the $\phi 1 - a$ term appears as for the other answer. But why is $(a I - \Diag{a})^{+}$ necessarily diagonal?
Comment: You're right. In my initial post, I transposed ${\tt1}x^T$ on the first line. Propagating that through the rest of the calculation, it turns out that the matrix is **not** diagonal.
Answer: If I understand you correctly, your matrix is
$$ 0 \psi_1 + a_2 \psi_2  + a_3 \psi_3  = \phi -a_1\\
 a_1\psi_1  + 0 \psi_2 + a_3 \psi_3 = \phi -a_2\\
 a_1 \psi_1 + a_2 \psi_2  + 0 \psi_3 = \phi -a_3$$
Using Gaussian Elimination, we arrive at
$$\begin{bmatrix} 1 & 0 & 0 & \dfrac{a_1-a_2-a_3+\phi}{2 a_1}\\0 & 1 & 0 & \dfrac{-a_1+a_2-a_3+\phi}{2 a_2} \\ 0 & 0 & 1 & \dfrac{-a_1-a_2+a_3+\phi}{2 a_3} \end{bmatrix}$$
Note that any $a_i$ equal to zero causes issues.
Comment: Useful link: https://math.stackexchange.com/a/3144635/189703
Comment: Yep - that is what we are effectively doing.

Solve system for elements of a matrix


How to delete a task?

Question: Or more precisely - is there a way to remove a participant from subsequent iterations if it was "deleted" at the first iteration?
What I mean...
For example, there is a some parallel workflow. I choose 10 participants and initiated this business process. Thus, 10 tasks were created, one for each participant. But then I decided to delete a few participants.
As far as I know, I can't remove the task. But I can to complete these tasks by using WebScript. For example, as follows. I know the workflowId and taskId:
...
Map<String, String> templateArgs = req.getServiceMatch().getTemplateVars();

// String workflowId = templateArgs.get("workflowId");
String taskId = templateArgs.get("taskId");

Map<QName, Serializable> updatedProperties = new HashMap<>();
updatedProperties.put(TaskRemoverModel.REVIEW_OUTCOME_PROPERTY, "Approve");
updatedProperties.put(TaskRemoverModel.COMMENT_PROPERTY,
    "The user was excluded from the list of participants.");

workflowService.updateTask(taskId, updatedProperties, null, null);
workflowService.endTask(taskId, null);
...

But the problem is that at the stage of revise, the initiator can send for approval again. Then tasks for excluded participants will be created again.
Is there a way to "mark" these participants, so that no tasks were created for them in the future?
I would be very grateful for the information. Thanks to all.
Comment: You should be able to remove the participants after completing the task from the workflow variable, so that, further tasks will not be creating next revise.
Answer: You can remove the person from the list of assignee.When you complete a task use below code to remove person from the list using javascript, if you are using bpm:assignees for association.
bpm_assignees.remove(person);  // where person is an current logged in person.
You can use nodeService for removing association in java.
Comment: I'm about to type the same.
Comment: that doesn't matter I guess
Answer: The solution can be represented as follows.
In the WebScript it's needed to update the task properties and complete that task. To the task properties add the new property with the reference to the excluded participant (who was the owner):
...
Map<String, String> templateArgs = req.getServiceMatch().getTemplateVars();

String taskId = templateArgs.get("taskId");

Map<QName, Serializable> updatedProperties = new HashMap<>();
updatedProperties.put(TaskRemoverModel.WORKFLOW_CONFIRM_MODEL_CONFIRMOUTCOME_PROPERTY,
    "Approve");
updatedProperties.put(TaskRemoverModel.WORKFLOW_MODEL_LASTCOMMENT_PROPERTY,
    I18NUtil.getMessage("task.comment.excluded"));

WorkflowTask workflowTask = workflowService.getTaskById(taskId);
Iterator taskProperties = workflowTask.getProperties().entrySet().iterator();
while(taskProperties.hasNext()) {
    Map.Entry taskProperty = (Map.Entry)taskProperties.next();
    if(TaskRemoverModel.CONTENT_MODEL_OWNER_PROPERTY.toString().equals(
      taskProperty.getKey().toString())) {
        updatedProperties.put(TaskRemoverModel.TASK_WAS_EXCLUDED_SIGN,
                personService.getPerson(taskProperty.getValue().toString()));
    }

}

workflowService.updateTask(taskId, updatedProperties, null, null);
workflowService.endTask(taskId, null);
...

For the complete event of the task add the listener. This listener will work after this call in the WebScript:
...
workflowService.endTask(taskId, null);
...

In the listener, find this new property, in which the reference to the excluded participant. Then get the list of bpm_assignees and delete the reference for this participant from that list and set variable bpm_assignees again:
public class TaskCompleteListener implements TaskListener {
    private Map<Object, Object> registeredBeans =
        Context.getProcessEngineConfiguration().getBeans();
    private ServiceRegistry registry =
        (ServiceRegistry) registeredBeans.get(
            ActivitiConstants.SERVICE_REGISTRY_BEAN_KEY);
    private WorkflowService workflowService = registry.getWorkflowService();

    @Override
    public void notify(DelegateTask delegateTask) {
        WorkflowTask workflowTask =
            workflowService.getTaskById("activiti$" + delegateTask.getId());
        Map<QName, Serializable> taskProperties = workflowTask.getProperties();

        Iterator iterator = taskProperties.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry taskProperty = (Map.Entry)iterator.next();
            if(taskProperty.getKey().toString().equals(
             ContractsApprovalModel.TASK_WAS_EXCLUDED_SIGN)) {
                ActivitiScriptNodeList assignees =
                    (ActivitiScriptNodeList) delegateTask.getVariable("bpm_assignees");
                for(ActivitiScriptNode personNode : assignees) {
                    if(personNode.getNodeRef().toString().equals(
                      taskProperty.getValue().toString())) {
                        assignees.remove(personNode);
                    }
                }
                delegateTask.setVariable("bpm_assignees", assignees);
            }
        }
    }
}

After that it becomes possible to delete the tasks of the participants in runtime and after the resubmit for these participants tasks are not generated.

How to delete a task?


How to customize user edit page drupal 7?

Question: I need to change the order in which things are on the user edit page in Drupal 7.  I have tried modifying page-user-edit.tpl.php and user-profile-edit.tpl.php, but it doesn't seem to ever get there. What can I do?
Comment: The order of which "things" ?
Comment: I found out if you are logged in as admin you cannot see the effects of page-user-edit.tpl.php
only people who are not admin can see the changes you made.  pretty crazy in my opinion!  I stumbled upon this information by accident.
Answer: It's a little different for Drupal 7... The structure of the file name would be page--user--edit.tpl.php (for D7) as opposed to page-user-edit.tpl.php (for D6).
Also, remember to clear the cache after you make any such changes so that they're recognized.
Hope that helps... :)
Answer: If you just want to change the order of the fields in the user profile as they appear on the user profile edit page in Drupal 7, navigate to "Administration » Configuration » People » Account settings" and then click on the "Manage Fields" tab.  You can the use the slider (or row weights) to rearrange the order of the fields.
If you also want to change the order these fields appear in the profile when it is displayed (as opposed to edited), use the "Manage Display" tab.
Remember to save when you're done.


Hellwig's method of selection of variables

Question: Hellwig's method is a method of selection of variables in linear model. It is widely used in Poland, probably only in Poland because it is really hard to find it in any scientific paper written in English.
Description of method:
$m_{k}$ - set of variables in k'th combination (there are $2^{p}-1$ combinations, where p is number of variables)
$r_{j}$ - correlation between $Y$ and $X_{j}$
$r_{ij}$ - correlation between $X_{i}$ and $X_{j}$
$H_{k}=\sum\limits_{j \in m_{k}}\frac{r_{j}^2}{\sum\limits_{i \in m_{k}}|r_{ij}|}$
Choose the combination of variables with the highest $H_{k}$
Question
Is this method used anywhere outside the Poland?
Does it have any scientific background? It seems that it based only on intuition that variables in a model should by highly correlated with $Y$ and poorly correlated with eachoter.
Answer: After spending too long on web research, I'm pretty sure the source of 'Hellwig's method' is:
Hellwig, Zdzisław. On the optimal choice of predictors. Study VI in Z. Gostkowski (ed.): Toward a system of quantitative indicators of components of human resources development; Paris: UNESCO, 1968; 23 pages. [pdf]
Google Scholar finds 3 papers that have cited it. None of them appear particularly noteworthy. So I think the answer to your first question is 'No'. As for your second question, I'll leave you to study the paper as i've spent far too long on this already. But from a skim, it appears the motivation behind his method was to avoid calculations that were very tedious without an electronic computer:
"... generally speaking one has to compute $2^n-1$ times the inverse matrices, which is of course an extremely dull perspective. The method we are going to present in this paper does not require finding inverse matrices." (p3-4).

Biographical note:
A little further googling reveals Zdzisław Hellwig was born on 26 May 1925 in Dobrzyca, Poland, and was for many years professor of statistics at the Wrocław University of Economics. There was a scientific meeting to honor his 85th birthday in November 2010.
Comment: Thanks for the answer it confirmed my supposition that this method shouldn't be used.
Comment: I know this is an old question, but I've just implemented this method and am frustrated with its performance after around 30 variables.  I was wondering if you could recommend more modern approaches which *are* specifically meant for computers?  Thanks!


Why does $\mathrm{E}[e^{-X}] = 0$ imply $\mathrm{P}(X = \infty)=1$?

Question: Came across the following problem:

with the following solution:

I can follow the whole solution, except for the last statement: $\mathrm{E}[e^{-X}] = 0, $ equivalently, $\mathrm{P}(X = \infty)=1.$
Can someone walk me through the steps of this conclusion?
Comment: For a rigorous solution, note that for any $N \gt 0,$ the zero expectation implies $\Pr(X \le N)=\Pr(e^{-X} \ge e^{-N}) = 0.$ This line of reasoning will not require you to perform potentially suspect operations with infinities.
Comment: Cross-post: https://math.stackexchange.com/q/3212483/321264
Comment: @whuber: A nice approach, but you can pretty easily add infinity as an allowable outcome of the random variable, giving it a mixture distribution on the closed reals.  It requires some elaboration of operations, but here is nothing particularly suspect about that approach in my view.  Indeed, *without* allowing infinity as an outcome, the probability statement is meaningless.
Comment: @Ben I like your approach too, but too many threads here on CV abuse the concept of infinity.  It's a common source of confusion.
Comment: @Ben Yes, that is a well-established approach and I'm not trying to suggest it is suspect.  I am only warning against the possibility of less-principled uses of "infinity" in calculations that might be suggested by this notation.  One needn't create a numerical infinity to make sense of the statement. For instance, it can be taken to mean that for all $N\gt 0$ and $\epsilon\gt 0,$ $\Pr(X\le N)\lt \epsilon.$
Comment: Fair enough - I guess I just prefer to take the problem on its stated terms rather than reinterpreting it without the numerical infinity.  (I've always been a fan of using an explicit infinity element in lieu of limits where possible.  You still end up having to use limit properties implicitly in the operations, but it cleans up the notation a lot.)  Anyway, I think we agree on the dangers of misuse.
Answer: See https://math.stackexchange.com/questions/1191818/why-does-e-raised-to-the-power-of-negative-infinity-equal-0 for explanations why $e^{-X}$=0 only in the limit as $x \rightarrow \infty$.
As for the additional step that $E[e^{-X}]=0$ implies $P(X=\infty)=1$, note that there is no value of X for which $E[e^{-X}] < 0$.  $E[e^{-X}] = P(X=\infty)*0 + (1-P(X=\infty))*E[e^{-X}|X < \infty]$.
$E[e^{-X}|X < \infty]$ is strictly positive, so $(1-P(X=\infty))*E[e^{-X}|X < \infty] = 0$ implies $(1-P(X=\infty))=0$ which implies $1=P(X=\infty)$.


What is the correct way of learning sheet music?

Question: I don't really know what is the correct way of learning new pieces from sheet music and because of this I get distracted really quickly while familiarizing myself with new music. I tend to follow some path like learning single hand, then I start to think that it shouldn't be done like that, so I try to follow with the other hand, in the middle of that all I change my mind multiple times and can't lose the feeling that I'm doing everything wrong. Because of this learning something new has become really "painful" for me.
Should I learn right hand first or try to learn both hands simultaneously? Do you follow any algorithm that helps you with learning new pieces? Do you have any advices for me?
Answer: Part of the problem is that beginners are trying to learn at least three different things at the same time:

How to read sheet music
How to play their instrument
How to play the specific piece that is in front of them.

If you concentrate mostly on #3, then learning #1 and #2 will be slower, and (relatively) unstructured and disorganized. You need to work systematically on all of them, independently of each other.
You can work on "how to read music" anywhere. All you need is some sheet music, and possibly a recording of the piece so you can check what the notation actually means. Your ultimate objective is to be able to look at a piece of sheet music that you have never seen before, and "hear it in your head" accurately just by looking at the printed page.
That might seem impossible to you right now, but don't forget that you have already learned (when you were a young kid) how to read printed text that way. If you can already read a book or a newspaper, there is no reason why you can't learn to read sheet music just as fluently and accurately. But you won't get that fluency just by "picking out the notes one hand at a time" while trying to learn pieces.
You will make progress on "how to play the instrument" much quicker and more reliably by using systematically graded technical exercises, rather than by "learning pieces" and trying to solve the technical problems in the random order that they turn up in those pieces. Otherwise, you will be constantly trying to run before you can walk, which only leads to frustration.
But of course you shouldn't ignore "learning specific pieces" altogether, because, most likely, "wanting to play pieces" is your motivation for spending time and effort learning the first two things I mentioned.
Answer: There really isn't a best way of learning new pieces, at least not one that all piano teachers and pedagogues would agree on.
Some insist that learning hands together is best, and others insist that learning each hand separately is better, so really it tends to boil down to which method works best for you, or which method your teacher advises.
From my own experience, I find the following works best for me:

Never try to learn pieces which are much harder than pieces I can already play. Obviously, they need to be a bit harder, or no progress is made, but if I can play pieces at a certain grade, then I restrict myself to pieces which are just one grade higher (unless my piano teacher recommends anything else).
Learn the right hand until I can play it accurately at a speed faster than the music requires.
Do the same for the left hand.
Start practising hands together at slow speed, and gradually get the piece up to speed.

I also think that sight-reading practice is vital, and have spent hours practising sight-reading, using sources like:

old piano methods available free (legally) on IMSLP,
music for children composed by people like Bartok, Schumann,Tchaikovsky, Kabalevsky, ...
any music I find in second-hand or charity shops which is a couple of grades lower than my current grade,
old hymn books.
Comment: Every answer under my question was helpful but this one is most algorithmic one. I'm writing this comment in case someone is wondering why I accepted this one instead of highest rated answer. I really appreciate it John!
Answer: Are we talking about "piano lesson" playing, or about learning songs?  If the former yes, hands seperately, slowly enough to get it RIGHT (and if it isn't right, sort out why - don't just keep making the same fluffs).
But if you're learning songs (which "sheet music" suggests you might be) it can be more about finding out how it "goes" and working out what best to play.  Is it just you, or are you in a band?  Sheet music for popular songs is rarely played literally.  For instance, you're unlikely to want to play the melody all the time.
Answer: I definitely agree with a lot of what Old John pointed out, but I would also like to add certain additional points that are important in my opinion when it comes to learning new pieces.
First about the question of whether to learn a piece with both hands toghether first or not:
I would say this actually depends on the piece/the section of the piece you are currently practising. If it's something that you already have the technique of playing (when for example the left hand is an easy repeating pattern and you can fully concentrate on the right hand) there is nothing wrong with playing both hands together immediately (at a slow pace of course).
If you, however, at any point feel like you can't keep up with coordinating your hands, you can just switch back to practising each hand independently.
There is nothing wrong with applying different techniques of learning to different sections of the same piece if it's required.
One thing that I find very important when it comes to practising new pieces is that you need to concentrate on your technique. With every new section you should always focus on whether you are playing everything with the correct technique or not - especially because you don't have a teacher (at least I assume so because you've put "self-learning" as a tag).
Correct technique involves things making sure that...

your wrists are high enough (but not too high)
your fingers are bent so that you're playing with the tip of your fingers
your hands are relaxed at all times (especially when playing fast and/or big chords)
you are actually playing everything exactly as is written in the notes - e.g. playing the correct note lengths, staccatos, portatos, legatos...
and a lot more that I can't list here because the list would be too long

One thing I slightly disagree on with Old John is the fact that I think trying to learn pieces that seem to be much harder that the ones you have played until now is not necessarily a bad thing.
My experience with several teachers that I've had is that I've always learned the most with the ones that pushed me to play the very hard pieces (that other teachers would have not given me to play). In the beginning it might seem like it's impossible but in the end it just comes down to how much you practise it.
If you split it up into small parts and pracitse and perfect those at a time you will eventually find yourself able to play something that you wouldn't have ever imagined to be able to play. Also these are the pieces that will improve your technique the most.
Also, as Old John said, sight-reading is not only very important but especially really rewarding in the long run when you have played so many pieces from sight that you can just open up even demanding pieces and play them from sight without needing to think about it.
I wish you the best of luck with your playing!
Comment: Check what you say in your penultimate para. I also think that getting the notes right is more important than playing them staccato, forte, etc in the early stages.
Comment: Oh yes, thanks for the hint. I was missing the "not `only`". Of course it is important and necessary to get the notes right before you start to add dynamics and play faster but in my opinion it's just as important to also concentrate on these other aspects. I mean yes, if he's only been playing for like a couple of months then the pieces he plays probably don't even offer very much in terms of dynamics or ornamentation. My answer is more about the general approach of learning new pieces :)
Answer: There is no 'correct' way to learn a new piece. There are many good ways, but they are quite subjective. They will depend to a degree initially on how good one is at sight-reading. In fact, several of the guys I have played with over the years are so good at sight-reading, they never have to actually 'learn' pieces. If that's not a great indictment to learn to be a good sight-reader, I don't know what is!
Back to the question in hand. Some will get pretty good on each hand separately before putting them together. Some will work, more slowly, on getting it together from the start. It does depend very much on the sort of piece: with a rhythmical left hand accompaniment, the two together will be a good idea, whereas if it's more of a question-answer type, separately works well.
There is also the important factor, missed by so many learners, that it's the tricky bits that need to be practised, not the 10 bars that you play well before and maybe after them. So isolate those nasty bits, and just work on them, otherwise a lot of time is being wasted. Once a section is learned, there is no special reason to keep playing it, but rather wait till the part before or after is as good, then run them together.
Some need to see (and hear!) the harmonic structure and format of the piece, so listening to renditions first is good for them. Some like to do it in little bites, say 2 bars at a time, and again it depends on the way the music goes - if 4 bars makes a sentence, then 4 bars is a good bite. Some like to start at the beginning (a very good place to start, so we're told), but others will take a passage half way through, or even the last part, so when it's nearly learnt, they already know what's comong next.
Some may lock themselves away and repeat as many times as it takes, before letting themselves out,that works for me!, whereas others prefer simply a few minutes on a particular part, and return a couple of hours, whatever, later, and do the same.
Some find they're most receptive at certain times of the day or week, so attempt to put the work in then. It may be first thing in the morning, when they're freshest, or later at night when the worries of the day have subsided somewhat. Some need the high expectations of their teacher to spur them on, others work better without external pressure. Some give themselves a deadline - I'll perform this for my friends at the end of the month - while others plod happily on, knowing it'll be there in the end - if they live long enough...
In amongst all this, you need to find YOUR best way, by trying out some of the suggestions. No one way will be best for each and every piece, but those are some ideas for you. Good luck!
Answer:
Should I learn right hand first or try to learn both hands
  simultaneously? Do you follow any algorithm that helps you with
  learning new pieces?

This really depends on your overall skill level, and what you're trying to achieve in learning a particular piece. If you're advanced enough so that you can read proficiently and have the technique to play standard repertoire (Mozart sonatas, for example), then very slowly learning both hands together works for many people. Some prefer, and may even require, that they learn each hand separately, and then put them together. If preparing for a performance, then many will learn, or at least practice, separately. In all cases, do in very small chunks (as little as one beat or one bar), not entire phrases.
For me, I've always been very methodic, and have always learned hands separately. Many others I know prefer to always play together, even all the way through, enough to become familiar with the piece. Also, a trick that I sometimes use on very difficult passages is to play one hand while fingering the other hand. Going through the physical motions of fingering the other hand, while not actually depressing the keys enough to make a sound, forces your inner ear to hear/sing those silent notes, but frees you up enough to not deal with the technical aspect of actually playing them. (I also do this with both hands for the same purpose.) Doing this is actually more difficult than playing both hands, but it really solidifies my learning and memorization.
Reading between the lines, it may be that you're having difficulty putting the two hands together? If so, no worries. This will get easier with more practice, I promise. At whatever point is giving you the most difficulty, freeze on the note(s) right before that part, and then look, feel, and hear the very next note(s). For example, while holding down the previous note(s), look at the next key(s) you'll need to press, hear the notes in your mind (or better yet, sing them if you can), and maybe even finger them. Sometimes when learning a new piece, it's not always obvious that the difficulty may lie in the parts right before and after what you believe to be the difficult notes, and the connections between all of them. If your difficulty is rhythmic or hand independence (which is really also rhythmic), again, no worries. If you do all of the above, and give it time, this is a skill that will naturally improve on its own. The biggest of these hidden skills that you naturally acquire is the ability to hear and feel multi-line voices at the same time. We're not used to that in the real world, but it's like the tapping your head while rubbing your stomach trick – it's not a trick at all, but an acquired skill.