Ganglia doesnt update graph

Question: I started to notice my web interface hasn't updated the graph in hours. Each time I restart the gmond process on my clients, I see that the graphs does work. I come back an hour or so later and my graph is blank, just a white graph and nothing has been updated. if I started it again, it works just fine. I'm not sure what it is.
My setup is as follows.
Client -> gmond collector -> gmeta/web host
gmetad.conf
data_source "ENG1" 10.199.1.110
data_source "ENG2" 10.199.19.100
data_source "QA" 10.199.10.200

gmond.conf from 10.199.10.200
globals {
    daemonize = yes
    setuid = yes
    user = nobody
    debug_level = 0
    max_udp_msg_len = 1472
    mute = no
    deaf = no
    allow_extra_data = yes
    host_dmax = 0 /*secs */
    cleanup_threshold = 300 /*secs */
    gexec = no
    send_metadata_interval = 0 /*secs */
}

cluster {
    name = "QA"
}

udp_send_channel {
    host = 10.199.10.200
    port = 8649
    ttl = 1
}

udp_recv_channel {
    port = 8649
}

**gmond.conf no my client files are the same as above except it doesn't have the udp_recv_channel block defined. I forwarded the states from my client to a collector (such as 10.199.10.200), which then gets pulled by the gmeta server (10.199.1.110). This server also collects data from a group of servers defined as "ENG1."
Comment: Please post the /etc/gmond.conf and /etc/gmetad.conf files for client and server.  Also, take a look at the iptables rules on client and server.
Comment: Updated, and no fw between clients and server.
Comment: Looks like you are not using multicast at all?  In any event, the gmetad communication from the server to the store needs a tcp listener on port 8649.  Try adding: tcp_accept_channel {
  port = 8649
}
Comment: what do you mean by you modify the config to use multicast? What changes did you make to your gmond.conf and gmetad.conf so that it works?
Answer: I've been facing with this problem when Ganglia is installed on Ubuntu. According to the document, it sounds like gmond lost metadata and doesn't know what to do with the metric data. Since you're setting up Ganglia in unicast mode, you need to instruct gmond to periodically send metadata by changing send_metadata_interval to a non-zero value:
globals {
  daemonize = yes
  setuid = yes
  user = ganglia
  debug_level = 0
  max_udp_msg_len = 1472
  mute = no
  deaf = no
  allow_extra_data = yes
  host_dmax = 0 /*secs */
  cleanup_threshold = 300 /*secs */
  gexec = no
  send_metadata_interval = 30 /*secs */
}

Give it a try!
Read more:
http://sourceforge.net/apps/trac/ganglia/wiki/ganglia_release_notes

3.1 collectors will request a gmond to resend its metric description information if needed and if using multicast, if you are using unicast
  there is no way to do that yet and so if you restart your collector
  will be left with partial or no data from the cluster that is being
  collected through it untill all gmond in that cluster are restarted.
  To workaround this problem if using unicast setup
  send_metadata_interval to a reasonable value so that all gmond resent
  their metadata periodically to the collector in case it gets lost.

http://sourceforge.net/apps/trac/ganglia/wiki/FAQ

In recent versions of gmond (3.1.x), a new global variable was added
  in gmond.conf called send_metadata_interval, with a default setting
  of 0. Purpose was to reduce network traffic. In 3.1 metric data is
  sent separately from metadata e.g. metadata contains detailed
  description, grouping, other possible setting. A value of zero means
  that the gmond will send metadata when it starts, and no other time
  (which is consistent with older versions of ganglia).
If you plan on using unicast mode, please set send_metadata_interval
  to something other than 0. 30-60 seconds has been found to work
  reliably in most cases. Setting this variable to a non-zero value will
  make the gmond processes periodically announce their metrics and the
  graphs will reappear on the host-view page.
Answer: Try adding: tcp_accept_channel { port = 8649 }
Comment: on the `gmeta` server or the collector - `10.199.10.200` Apologies, I looked at my datastore (10.199.10.200) and I do see the `tcp_accept_channel` block.
Answer: I modified by config to use multi cast and it's working now!

Ganglia doesnt update graph


Is there a fixed-point theorem that can be applied to a ring endomorphism of $k[x,y]$?

Question: Let $k$ be a field of characteristic zero (I do not mind to assume that $k \in \{\mathbb{R},\mathbb{C}\}$), and let $R=k[x,y]$ be the $k$-algebra of polynomials in two variables $x,y$.
Let $f$ be a $k$-algebra endomorphism of $R$.

(I) Is there a fixed-point theorem that can be applied to $f$? (II) If so, then is it possible to obtain a fixed point $\in R-k$? (the elements of $k$ are always fixed points for a $k$-algebra endomorphism $f$).

Remarks:
(1) I have tried to consider $k[x,y]$ as a complete metric space,
see this question, but I guess that $f$ is not a contraction in that metric. So, is there another metric that makes $f$ a contraction? (probably yes? But it may be difficult to guarantee that $f$ has a fixed point $\in R-k$).
(2) The answer probably depends on the given $f$, since, for example,
it seems that $f:(x,y) \mapsto (x^2,y^2)$ does not have fixed points other than the elements of $k$.
(3) Here is a list of fixed point theorems.
(4) The following questions seem relevant: a and b (what if we consider our given endomorphism as a multiplicative group morphism?).
(5) A similar question of mine is this (the fourth remark there says that the existence of such a fixed point implies the two-dimensional Jacobian Conjecture).
Thank you very much!
Comment: I don't think it is possible in any nice way, because you cannot keep the $k$-vectorspace structure compatible with a complete metric (Since $k[x,y]$ is a countable union of nested finite-dimensional subspaces contradicting Baire).
Comment: Thank you very much. Can you please elaborate (in an answer)?
Comment: (If I am not wrong, if we work in the formal power series $k[[x,y]]$, then the 'natural' metric is complete, but $f$ is not a contraction).
Answer: I very much doubt you can approach it in this fashion.
If there is a fixed point, then the fixed set would have to be a subalgebra, so in particular, a vector subspace, and this endomorphism of course respects this structure so you probably want a metric that also respects this.
In particular, you want proper vector subspaces to be closed and nowhere dense.  But this yields a contradiction when you demand the metric to be complete, because we can write $k[x,y]$ as a countable union of proper (hence closed nowhere dense) subspaces
$$
k[x,y]=\bigcup_{d=0}^\infty \operatorname{span}_k\{x^iy^j\mid i+j\leq d\}
$$
but Baire category theorem says a complete metric space is not meagre.
A few words about the formal power series ring
If you decide to work with the formal power series ring $k[[x,y]]$ instead, then obviously your endomorphism $f$ must send the nilpotent $x,y$ to some nilpotent elements.  This means in particular that we can reduce to looking at fixed elements of each $(x,y)/(x,y)^m$ and patching each graded piece together, like in Hansel's lemma.
Comment: Thank you for the answer! Please, do you think that other fixed-point theorems are relevant? (Here is a list of 20 fixed-point theorems: https://en.wikipedia.org/wiki/Fixed-point_theorem).


What are some quick ways to setup Product Displays in Drupal Commerce?

Question: What is a fast way to create product displays in drupal commerce? Say I created 50 different unique products and now they are all over the place on the product list, how can I intuitively add these 50 products to a product display?
Comment: http://drupal.org/project/inline_entity_form
Comment: http://drupal.org/project/commerce_auto_product_display
Comment: "Fast way" is rather subjective; it is like asking for the best way of doing something. Furthermore, since nobody is probably going to measure which is effectively the faster way, there would not be any objective parameter to judge the answers.
Answer: If you are adding product manually then you can use Auto Product Display module to set display of the product at the same time when you create product. But if you are using commerce feed along with feed then you will have to set two separate importer for each of them.


Why is Brazil's top football stadium (Maracana) in Rio de Janeiro rather than São Paulo?

Question: Maracana stadium "was opened in 1950 to host the FIFA World Cup", at which time it was the largest stadium in the world. I have heard the stadium referred to as "the spiritual home of Brazilian football" a few times, and this year it will once again host the World Cup Final. Why is Brazil's top stadium in Rio, rather than in São Paulo, when the latter is a far larger city (not that Rio is small)?
Comment: In 1950 Rio was (slightly) bigger than São Paulo according to the historical figures on wikipedia which may explain why the 1950 final was held there. Obviously once you have somewhere like the Maracana established it's hard to displace.
Comment: the fact that a city has more people does not imply that football culture is bigger there, does it?
Answer: In 1950 - when the stadium was built - Rio de Janeiro was the Brazilian capital city. That explain why the stadium was not built in Sao Paulo
Comment: Not to dispute this answer, but the capital city does not necessarily mean the largest city or the city with the most fans.. Actually in many countries, the capital might not coincide with the city that has most (successful) clubs, e.g. England (London only recently have title challengers), Italy (Milano and Turin) , Germany (Berlin and Bonn have never really had strong teams), Turkey (biggest teams are from Istanbul)
Comment: I'm 100% agree with you but frequently the capital city is the one where the main event happens.


Convergence of a sequence in $\mathbb{C}$

Question: So, in my complex analysis notes my prof typed the following
$$f(z) = \frac{1}{z - z_0} = \frac{-1}{1 - \frac{z}{z_0}} = \frac{-1}{z_0}\sum_{n = 0}^{ \infty} (\frac{z}{z_0})^n$$
How did we figure out that step why do we know that will have that following power series representation can someone explain that step ?
Comment: $z$ should be inside (not even on) the unit circle around $z_0$ for this to make sense. To see that in this case it works think in terms of absolute convergence.
Comment: The numerator in the middle term should not be $-1$. It should be $-1/z_0$. If that is what the  prof wrote, then it's a typo of his.
Answer: It comes from the standard fact
$$
\sum_{n=0}^Nz^n=\frac{1-z^{N+1}}{1-z},\qquad z\neq1. \tag1
$$ If $|z|<1$, then letting $N \to \infty$ in $(1)$ gives
$$
\sum_{n=0}^{\infty}z^n=\frac{1}{1-z},\qquad |z|<1. \tag2
$$ Applying $(2)$ with $z \to\dfrac{z}{z_0}$ gives what your prof wrote, since
$$
\frac{1}{z-z_0}=-\frac{1}{z_0}\frac{1}{1-\frac{z}{z_0}}.
$$
Comment: alright thank you I understand...
Comment: I see I know this is true in the real case I didn't know it is also true for complex numbers.
Comment: why is this true for complex numbers as well can you explain ?
Comment: This is true also for complex numbers: we have used the same mathematical operations, valid in the complex field. Thanks!
Comment: Hi could you help me with the following problem http://math.stackexchange.com/questions/1555577/analytic-function-on-a-certain-domain


Consistent but inefficient GMM

Question: Consider the following linear model
$$y_t = x_t' \beta +u_t$$
where $t =1,...,T$ and $x_t = (x_{1t} x_{2t} ... x_{kt})'$ , $ \beta$ is $k \times 1$ vector of unknown coefficients, $u_t$ is an iid disturbance term with the variance $\sigma^2$ and $E(x_tu_t)=0$ for all t.
Find the consistent but inefficient GMM estimator.

My solution:
I know that $E(x_tu_t)= \frac{1}{T} \sum^T_{t=1} [x_t(y_t-x_t'\beta)]=0$
Define the Jacobian matrix
$$J(B)= g(B)' W g(B)$$
where $g(B)=\frac{1}{T} \sum^T_{t=1} [x_t(y_t-x_t'\beta)]$ and $W=I_k$
Here, I define W as an identity matrix, because efficiency depends on W matrix and when W=I, I guess that this estimator become inefficient. (Maybe wrong, I don't know exactly)
Then, the Jacobean matrix $J(B)$ in the matrix form is written as
$$J(B)=[\frac{1}{T} X'(y-X\beta)]' I_k [\frac{1}{T} X'(y-X\beta)]$$
Let's minimize J(B) w.r.t $\beta$
That's, $\partial J(B) / \partial \beta =0 $
Then, $$\hat{\beta} = (X'XX'X)^{-1} X'XX'y$$
As it is seen in the answer, I obtained OLS estimator $\hat{\beta} = (X'X)^{-1} X'y $. But OLS estimator is efficient, not inefficient. Thus my answer is wrong.
What should I make an extra assumption to obtain inefficient but consistent estimator? Assuming Weight matrix as I is wrong.
How do you solve for this question ? Where I'm wrong? Please share your ideas with me.
Note: the question is as follows. I am asking the part a.

New Update
The efficient GMM estimator depends on the weight matrix.
I firstly define the population moment condition as $g(B)=\frac{1}{T} \sum^T_{t=1} [x_t(y_t-x_t'\beta)]$
Based on the Central limit theorem,$\sqrt{T} g(\beta) \to N(0, P)$ where $P=var(\sqrt{T}g(\beta)=\frac{\sigma^2}{T^2}(X'X)$
Also, Based on Central limit theorem,
$\sqrt{T} (\hat{\beta}_{GMM} - \beta) \to N(0, V)$
where $V=(D'WD)^{-1}D'WPW'D(D'WD)^{-1}$ for the expected value of the matrix go the first derivates of the moment $D$.
I I choose the weight matrix $W=P^{-1}= (\frac{\sigma^2}{T^2}(X'X))^{-1}$ instead of choosing any other positive definite matrix $S$ for $W$, then I can obtain the minimum variance convince matrix.
Well, what is this positive definite matrix $S$ which makes the GMM estimator is inefficient.
Can you give me an example for $S$ matrix?
Answer: You basically, and correctly, rederived OLS, as these are the moment conditions exploited by your GMM estimator (namely, that regressors and errors are orthogonal, so that no external instruments are needed (equivalently, that regressors serve as their own instruments).
Notice that, assuming no multicollinearity, $X'X$ has full rank and hence is invertible. Hence,
$$(X'XX'X)^{-1}= (X'X)^{-1}(X'X)^{-1}$$
so that
$$\hat{\beta} = (X'X)^{-1}\underbrace{(X'X)^{-1}X'X}_{=I}X'y=(X'X)^{-1}X'y.$$
I am not sure if that is the actual answer to your question, as we seek an inefficient estimator, but OLS is, under the present assumptions, efficient, by the Gauß-Markov theorem.
P.S. Not that it is not correct to equate expected values and sample averages. Rather, the sample moment condition is the analogon exploited by the population moment condition.

Consistent but inefficient GMM


vector scalar multiplication

Question: When one define a special vector scalar multiplication, does this normally supposed to have an effect on a multiplication between the scalars themselves?
For example, $\alpha,\beta\in\mathbb{F}$, ${\bf v}\in\mathbb{V}$ , $f:\mathbb{F}\to \mathbb{F}$
$$\alpha \odot {\bf v} \equiv f(\alpha) {\bf v}$$
Now I want to verify associativity of this scalar multiplication, shall I check
$$\alpha \odot(\beta\odot {\bf v}) = (\alpha\odot\beta)\odot{\bf v}$$
where $\alpha\odot\beta$ needs to be explicitly defined, e.g. $\alpha\odot\beta=f(\alpha)f(\beta)$
or, alternatively I have to check
$$\alpha \odot(\beta\odot {\bf v}) = (\alpha\beta)\odot{\bf v}$$
where $\alpha\beta$ is a regular multiplication in this field?
The question is rises from the claim that $\mathbb{C}^n$ is a vector space over complex numbers with regular addition and a $\alpha\odot{\bf v}=Re(\alpha){\bf v}$ which may work with the first definition and won't work with the second, since $Re(z_1 z_2)\ne Re(z_1)Re(z_2)$. So I guess either, the claim isn't correct or I missing something:)
Finally
See own answer below, also the claim above which I've intialy assumed true fails apart as false.
Comment: $\alpha\odot\beta$ is not defined for $V\neq F$. But $\alpha\cdot \beta$ is defined in $F$.
Comment: please see the edit
Comment: Why doesn't $f(\alpha)=\Re(\alpha)$ work with the first definition? $\alpha\odot(\beta\odot\mathbf v)=\Re(\alpha)(\Re(\beta)\mathbf v)=\Re(\Re(\alpha)\Re(\beta))\mathbf v=(\alpha\odot\beta)\mathbf v$, or am I missing something?
Comment: I messed it a little, it won't work with the second - going to fix it
Comment: Seems like you've got an answer, then—it's the first one.
Comment: well, this would make the associativity, however this doesn't mean this is a normal thing.  Although the non uniqueness of unit scalar under this multiplication fails the definition of the field and make the claim invalid, doesn't it?
Answer: Let $\mathbf w=\beta\odot\mathbf v$. Then you must have $\alpha\odot(\beta\odot\mathbf v)=\alpha\odot\mathbf w=f(\alpha)\mathbf w=f(\alpha)(\beta\odot\mathbf v)=f(\alpha)f(\beta)\mathbf v$. So, you must have $\alpha\odot\beta=f(\alpha)f(\beta)$. I hope that with this definition of scalar multiplication, you still have a field.
On the other hand (per Bye_World's comment), if this is the case, then $(\alpha\odot\beta)\mathbf v = f(\alpha\odot\beta)\mathbf v = f(f(\alpha)f(\beta))\mathbf v$, which constrains the functions that can be used for this type of scalar multiplication.
Comment: Except if $\alpha\odot\beta=f(\alpha)f(\beta)$ then $(\alpha\odot\beta)\odot \mathbf v=f(f(\alpha)f(\beta))\mathbf v$ not $f(\alpha)f(\beta)\mathbf v$.
Comment: yes this is what I was thinking about if you see the edit...
Comment: yes, since associativity is needed for removing the brackets, look like this requires $f^2=f$, i.e.  a projection
Answer: Finally,
The definition of a vector $\mathbb{V}$ space over a  field $\mathbb{F}$ talking about a vector multiplication to a scalar $\alpha in\mathbb{F}$. From the definition of the field it is supposes the scalar addition and multiplication with given (Abelian group) properties. Therefore associativity should be checked versus the regular field's multiplication, i.e.
$$\alpha \odot(\beta\odot {\bf v}) = (\alpha\beta)\odot{\bf v}.$$
Otherwise, the definition of vector space should have defined additional operator between the scalars which is not the case.

vector scalar multiplication


General formula for the numerators?

Question: Suppose that $a$ is a natural number. The numerator of $\dfrac {1}{a}$ is $1$. The numerator of $\dfrac {1}{a} + \dfrac {1}{a+1}$ is $2a+1$ [Note: Here for our purpose we don't cancel common factors of the numerator and denominator]. The numerator of $\dfrac {1}{a} + \dfrac {1}{a+1} + \dfrac {1}{a+2}$ is $3a^2+6a+2$. And so on. I tried a lot to come up with a general formula for the numerator of the sum of $n$ consecutive terms but I couldn't. I think there should exist some formula for it same as we have a formula for the coefficients of a binomial expansion. Any idea?
Saying in a more mathematical language:
The numerator of $\dfrac {1}{a} + \dfrac {1}{a+1} + \dots + \dfrac {1}{a+n}$ is $b_1+b_2a+ \dots + b_na^n$. What are the $b_i$'s?
Comment: Perhaps a more intuitive way to write the numerator (adding up to $\frac1{a+n}$) could be
$$
a(a+1)\cdots(a+n-1) + a(a+1)\cdots(a+n-2)(a+n) + \cdots\\ + a(a+2)\cdots (a+n-1)(a+n) + (a+1)(a+2)\cdots(a+n)
$$where each term has one of the factors missing. I don't know if it can be sorted out any nicer.
Comment: @Arthur - Yes of course. That's the definition! But what's this summation in polynomial form, is my question? What's the point of getting the coefficients of (a+b)^n as c(n,k) when we know we can write the sum as (a+b)^n?!
Comment: If $N_n$ designates the nth numerator, then we have immediately the recurrence relationship $N_{n}=(a+n)N_{n-1}+1$. from which for example one can deduce that the constant term is $n!$.
Comment: @JeanMarie it's not exactly n!, it's $\frac{(a+n)!}{(a-1)!}$
Answer: The expression is:
$\frac{1}{a} + \frac{1}{a+1} + \frac{1}{a+2} ... $
The numerator is going to be sum of the product of all the denominators with one term missing.
$(a+1) * (a+2) *.... (a+n)$ [a missing]
$+ a*(a+2)... (a+n)... $ [a+1 missing]
.
.
$+ a*(a+1)... (a+n-1)$ [a+n missing]
Each term can be expressed in terms of factorials.
$= \sum_{i = a}^{a+n} \frac{(a+n)!}{(a-1)!i}$
$ = \frac{(a+n)!}{(a-1)!} \sum_{i = a}^{a+n} \frac{1}{i}$
I don't think there is a closed form for the numerator though.
EDIT: Thanks to Rick Decker's useful comment, I remembered the forgotten Harmonic numbers, so the sum of 1/i becomes H(a+n) - H(a - 1)
Where H(n) is the $n^{th}$ Harmonic number = $\sum_{i=1}^{n} \frac{1}{i}$
Comment: It's not very pretty, but the sum term is $H(a+n)-H(a-1)$ where $H(m)$ is the $m$-th harmonic number.
Comment: @RickDecker YES! I was blanking out on that. Thank you very much!
Comment: And it's easy to show that this sum is never an integer. [the book *Gamma* by J. Havil, for example.]
Answer: The $b_i$ are simple multiples of unsigned Stirling numbers of the first kind.  In a common notation, the coefficient of $x^k$ in the combined sum of $n$ terms is $(k+1)\left[{n \atop k+1}\right]$
Take the triangle of values in Wikipedia
which starts
<code>n \ k    0    1    2    3    4

0        1
1        0    1
2        0    1    1
3        0    2    3    1
4        0    6   11    6    1
</code>
multiply the values in the triangle by the index at the top and drop the initial column and the indices to get a revised triangle
<code>              1
              1    2
              2    6    3
              6   22   18    4
</code>
This new triangle corresponds to the coefficients in

$\dfrac{1}{a} = \dfrac{1}{a}$
$\dfrac {1}{a} + \dfrac {1}{a+1} =\dfrac {1+2a}{a(a+1)}$
$\dfrac {1}{a} + \dfrac {1}{a+1} + \dfrac {1}{a+2}=\dfrac {2+6a+3a^2}{a(a+1)(a+2)}$
$\dfrac {1}{a} + \dfrac {1}{a+1} + \dfrac {1}{a+2}+ \dfrac {1}{a+3}=\dfrac {6+22a+18a^2+4a^3}{a(a+1)(a+2)(a+3)}$

and so on
Comment: There is also a recurrence, so for example the values in the bottom row can be found from the previous row with $6=0+3 \times 2$, while $22=\frac21 \times 2+3\times 6$,  and $18=\frac32 \times 6+3\times 3$ and $4=\frac43 \times 3+3 \times 0$

General formula for the numerators?


Json Provider fails with Illegal characters in path

Question: I am using the FSharp Json Provider.
I am deploying to an Azure Web App.
When I deploy to Dev, it works fine.
When I deploy to TEST, it fails with the following message:

{"Message":"An error has occurred.","ExceptionMessage":"Illegal
  characters in path.",
  "ExceptionType":"System.ArgumentException","StackTrace":"    at
  System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String
  fullPath)\r\n    at System.IO.FileStream.Init(String path, FileMode
  mode, FileAccess access, Int32 rights, Boolean useRights, FileShare
  share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES
  secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath,
  Boolean checkHost)\r\n    at System.IO.FileStream..ctor(String path,
  FileMode mode, FileAccess access, FileShare share)\r\n    at
  email@example.com(Unit unitVar) in
  C:\Git\FSharp.Data\src\CommonRuntime\IO.fs:line 237\r\n

The type is genertated by
type Entities = JsonProvider<"./someDir/Sample.json">

and the error is generated here
let response = Entities.Load(currentUri)

I tried removing the file and in-line the sample json when I generate the type, but that also fails with the same error code.
Anyone have any ideas?  Is it the currentUri?  It is the same across all environments
Comment: Very mysterious... Well, okay, what's the difference between environments? Can you try yet another, the third environment? Can you insert in your code `let a = currentUri`, `let b = currentUri.Trim(Path.GetInvalidFileNameChars())`, `let c = currentUri.Trim(Path.GetInvalidPathChars())` and print `a, b, c` somewhere, e.g. to App Insights?
Comment: I gave up and instead of the TP, used a web client and the newtonsoft deserizalizer
Answer: I let it go and went with web client and newtonsoft.


Mac Terminal: How to view a microsoft word file? (It says it is binary)

Question: So I was writing a paper on Microsoft Word and the file is corrupt now. I'm trying to see if I can open the file using vim, but it says it is binary. Is there any command or any way to convert it into text so that I can just vim myfile.doc and copy the text contents? I tried doing a cp myfile.doc myfile.txt to change the extension but it still says it's binary.
Answer: A doc file is a proprietary format by Microsoft. Docx formats are xml based but neither can be read directly using a text editor. If your file is corrupt you're probably going to have a lot more luck try to find the autosave location or try and recover the document using the tool office provides. In future remember to back up your work ;)
Answer: /usr/bin/strings may be helpful -- built-in to OS X. Hope you can recover your paper.
Comment: `man strings` will tell you more detail, but in short, it lets you see whatever characters are ASCII in a binary file.
Comment: nice to know. but it didn't print out anything useful
Comment: I'm not God, Edmund, just another StackOverflow user trying to be helpful.
Answer: You might try using Antiword to convert to .txt if it can still access the file properly.
http://en.wikipedia.org/wiki/Antiword
Answer: .doc or .docx is not a plane txt file. It has several formatting and a bit of binary and in .docx xml factor included.
You can go for OpenOffice which is Free.
Answer: Word itself has an option to "Recover Text From Any File" which is worth trying if you haven't done so already. When you open the file in Word, if it doesn't recognise the format, you should see a conversion dialog and the option is in there. You might have to check the "Confirm conversion at open" option (e.g. "Word Preferences->General->Confirm conversion at open" on Mac Word 2011, "File->Options->Advanced->General->Confirm file format conversion on open" on Windows Word 2010.


The existence of an inverse to a differentiable function

Question: Let $f:\mathbb{R}^2\to\mathbb{R}^3$ be differentiable. Can there exist a $g:\mathbb{R}^3\to\mathbb{R}^2$ such that $gf=\text{id}_{\mathbb{R}^2}$? What about such that $fg=\text{id}_{\mathbb{R}^3}$?
How does one approach such a problem? Chain rule, I suppose, but I can't manage to make it work.
Edited: Made clear that the question is asking if it is possible that $f$ has such a left or right inverse.
Comment: If $gf = Id_{\mathbb{R}^2}$, then the derivative $(gf)'(p)$ would be the identity at every point $p$. Using the chain rule, how big is the kernel of $(gf)'(p)$? Similarly, if $fg = Id_{\mathbb{R}^3}$, then $(fg)'(p)$ is the identity. But how big is the rank of $(fg)'(p)$?
Answer: For the first question, consider the inclusion $(x,y) \mapsto (x,y,0)$ and in the other direction $(x,y,z) \mapsto (x,y)$.
For the second, the hint of froggie totally works!


Can we dynamically load routes in NextJS based on a API request result?

Question: I have an app built on create react app which loads the route information (Allowed list of routes for the logged in user) from the server and generate the routes based on that. For example,

The user logs in
The app makes a get request to fetch the routes array
The app goes through the fetched results and returns a route:

routes.map((route) => <Route path={route} />)

My question is, can we do something similar in NextJS?
Answer: Sounds like you could use router.push.
api.login()
  .then(() => router.push('/some-route')

NextJS even has this example project that could help you
Now, to expand further, if you mean to say that your API will be returning the URI that you have to redirect to, then you just need to read from it:
api.login()
  .then(responseBody => router.push(responseBody.uri)


Can I have multiple favicons in D7

Question: This favicon generator (recommended here) generates multiple favicon png files and code for the  section of your HTML pages. This is said to be better than a single favicon file which might not display correctly in some devices.

But I think "Path to custom icon" in D7's /admin/appearance/settings only accepts a single favicon file.

If so is there a way to use multiple favicon png files?
If I can only use a single image what is the best practice for the format of the file?
Answer: You're looking for the Head Module:

This module provides a range of metatags that can be added to the
  document head of each available theme.
In an attempt to keep themes clear of anything that could be
  considered optional, i have aggregated all the frontend related
  metatags you could ever need into one advanced theme settings page
  which can be found at admin/appearance/advanced
Answer: An alternative to the Head Module, if you'd like to avoid the overhead of a module, would be to use hook_page_alter() in your theme's template.php. This is a code sample in one of my themes (replace mytheme):
function mytheme_page_alter($page) {
  $path = '/' . drupal_get_path('theme', 'mytheme');
  $apple = array(
    array(
      'rel' => 'apple-touch-icon',
      'href' => $path . '/images/apple-touch-icon-60x60.png',
    ),
    array(
      'rel' => 'apple-touch-icon',
      'sizes' => '76x76',
      'href' => $path . '/images/apple-touch-icon-76x76.png',
    ),
    array(
      'rel' => 'apple-touch-icon',
      'sizes' => '120x120',
      'href' => $path . '/images/apple-touch-icon-120x120.png',
    ),
    array(
      'rel' => 'apple-touch-icon',
      'sizes' => '152x152',
      'href' => $path . '/images/apple-touch-icon-152x152.png',
    ),
    // etc.
  );
  foreach ($apple as $link) {
    drupal_add_html_head_link($link);
  }
}

Comment: Please correct me if I'm wrong, I'm a newbie, but the PHP code itself doesn't go to the client, does it? Only the generated header lines will get sent over the wire, so no matter how verbose the PHP is, it doesn't directly contribute to bandwidth usage. This is independent of the page generation time, which would be affected by CPU time, if the code is inefficient.
Comment: If you'd like to avoid overhead of a hook, you can directly put this in your theme's html.tpl.php file. I wouldn't however, use such hooks or anything just for a favicon (your snippet from the screenshot alone looks like to be 2kb, which can result in GBs with decent traffic).
Comment: @AyeshK that is only if you already use a html.tpl.php. If not, then the overhead of the file itself might be bigger than that of a hook. Besides, the need to use an Apple favicon or not comes presumably from the site's spec and it's not something a developer just decides, unless it's a personal matter. In this question's case, this is an entirely different matter altogether.
Comment: I disagree using a custom tpl.php file is a more overhead. Even of you don't specify a template file, Drupal will use the default one anyway, so it's just a matter of that file vs this file.
Comment: Maybe you're right on this one. I am not convinced at all for your previous strong but confusing statement about GB's in traffic. Mentioning GBs suggests HTML overhead (which seems important and inevitable for the question anyway) and nothing about the CPU overhead to parse the hook. Still, there is no performance measurements of one against the other so this is not a constructive debate anymore but only speculation. Feel free to post a separate answer if you have something better to suggest.
Comment: Sorry if my comments didn't really sound any positive. That GB count was not about your reply in particular. Just that this giant snippet can calculate towards many GBs in server traffic.
Comment: Pity for the downvote. Perfectly legit answer, solves the question's problem alternatively, effort in writing, but gets downvoted by someone and the only comment is by Ayesh K for unclear performance considerations. *When in fact what is recommended is better in performance than using a module as recommended by the top answer (which I do like tbh).
Comment: Sorry if you think I down voted this (it would be great if a mod could confirm this). I didn't downvote and I don't know why would anyone - this method is perfectly valid and to be honest, I would go for this instead of the Head module.
Answer: There is a new module just for that! Here you go: Responsive Favicons

Can I have multiple favicons in D7


Is Slice Sampling a special case of Gibbs Sampling?

Question: I read on this thread the following:

If you can use both the gibbs sampler and slice sampling to sample
  from a posterior I would use the Gibbs sampler as the slice sampler
  seems unnecessary to me <...> If you cannot use the gibbs but you can use the slice then your question seems irrelevant.

But then, when on these slides from M. Jordan's lecture he says that:

Slice sampling is a special case of Gibbs sampling (in a product
  space).

What does he mean by that?
Also, when would one not be able to do Gibbs sampling but still do slice sampling?
Answer: Slice sampling is a special case of Gibbs sampling, where one introduces a latent uniform random variable and then applies Gibbs to the extended set of rvs - this is what Jordan means by in a product space. Slice sampling can also be used within an existing Gibbs scheme, again by augmenting the parameter space (although one does not need to store the uniform parameters during sampling) so I guess what the answer in the other thread means is that it makes no sense to augment an existing Gibbs sampler with slice-within-Gibbs (EDIT: unless you can't run the existing Gibbs in the first place, of course).
It's worth pointing out that there are generalizations of univariate slice sampling (e.g. reflective or elliptical) that can perform much better than Gibbs sampling, so I don't agree with the other answerer about never preferring slicing over Gibbs.
Comment: @landau Yes, there is theory to support it. It is easy to show that any transition kernel which leaves a given full conditional invariant will also leave the joint distribution invariant. The only other condition required for MCMC to work is that the chain is irreducible, which means that the chain can get to any state (plus some other technicalities). This idea is what is powering JAGS, which uses slice sampling to sample the conditionals almost exclusively. I don't have an explicit source for this idea, though, because it is so well known.
Comment: @user023472 Suppose we have parameters $(\theta_1, \theta_2)$ and data $Y$. Gibbs sampling iterates between $p(\theta_1 \mid \theta_2, y)$ and $p(\theta_2 \mid \theta_1, y)$; if one cannot sample exactly from either of these two distributions, Gibbs sampling will not be feasible. But we can always apply the slice sampler, so we can replace the draws from the intractable distributions with draws from slice samplers which target to intractable distributions.
Comment: Thanks. Would you mind clarifying when would one not be able to run Gibbs in first place, but still be able to run slice-sampling?
Comment: @guy I really want to use slice sampling that way, but I can't find a reference to justify it. Do you know of one?
Comment: @landau you want to use it in what way?
Comment: I want to use one univariate slice sampler to sample from $p(\theta_1 | \theta_2, y)$, and then a separate univariate slice sampler to sample $p(\theta_2 | \theta_1, y)$. Each of the two slice samplers would have its own auxiliary variable, as in http://stats.stackexchange.com/questions/192640/slice-sampling-within-a-gibbs-sampler . Is there any theory to support it?
Answer: I disagree that slice sampling is strictly a special case of Gibbs sampling. It's almost Gibbs sampling, but not quite. Look at Neal (2003) section 3, which talks about sampling from $f(x)$ using an auxiliary variable $y$. A Gibbs sampler would

Sample $y$ from $p(y | x)$ = Uniform(0, $f(x)$).
Sample $x$ from $p(x | y)$ = Uniform($S$), where $S = \{x: y < f(x)\}$.

Step 1 is an exact Gibbs step, and if we knew the slice $S$ exactly, step 2 could be as well. However, we don't know $S$ in practice, so slice sampling uses successive approximations of $S$ instead of $S$ itself. Different ways to do this included the stepping-out slice sampler and the doubling slice sampler, both suggested by Neal. But in any case, step 2 is not an exact, true Gibbs step.
I've read that slice sampling is a special case of a general auxiliary variable method, which relies on the same data augmentation idea: i.e., introducing an extra variable like $y$ and using it similarly to make sampling $x$ easier.
Comment: Slice sampling predates the 2003 paper by Neal. The original algorithm, which is precisely the one you gave here, was given the name "slice sampling" by Neal in 1997, although the idea goes back to the late 80s. The step-out algorithm is really an attempt at mimicking the original slice sampler you gave. So, when someone says that slice sampling is just Gibbs, they mean the original algorithm, not the step-out algorithm Neal came up with as an attempt to mimic the original slice sampler.
Comment: Incidentally, there is an entire chapter of Robert and Casella titled "Slice Sampling" that consists entirely of methods which implement steps 1 and 2 exactly; Neal's step-out algorithm is referred to in the bibliographic material, although it is probably more important than the material in the chapter itself. But this should drive home the point that slice sampling is not synonymous with the step-out algorithm.
Comment: After correcting the terminology, is my original answer still wrong? Is Neal's step-out algorithm a special case of Gibbs sampling too? If so, the connection is not obvious to me.
Comment: I didn't know slice sampling could also refer to the exact Gibbs sampler.


Reversing a modulo with an exponent

Question: So I am doing a challenge to break an encryption and have been stuck on one of the equations.
$$c = K^e\mod n$$
I know $c,e$ and $n$ all of which are very very large numbers. I know I have to get $K$ as it is the only way to reverse the next set of equations but I cannot figure out how to get $K$ from this.
Answer: Use Euclidean Algorithm to find the gcd of $e$ and $\varphi(n)$ as their linear combination (which is hopefully $1$ otherwise we don't have a solution guaranteed for all $c$). Suppose $ae\equiv 1 \operatorname{mod} n$. Then take $c$ to the power of $a$ gives you $K$.
Fermat's Little Theorem is the reason behind the mathematics. The difficulty here should be finding $\varphi(n)$, but that's why the encryption works. It is meant to be difficult; but knowing the factorization of $n$ would make it easy. That's why those who know the factorization would be able to decode, and those who don't won't.
Also you might wish to look up RSA algorithm for more information.
Comment: So I know of RSA but maybe why this has me a little stumped is that e is made up of the modular inverse of a prime number and φ(n) which on RSA looks more like the decryption algorithm not the encryption one. While n is pretty similar except that it is made up of 3 primes not 2
Comment: @Miki0099 I don't do CS but I thought the fact that one is able to decrypt should be part of RSA as well? Anyways this is the explanation why (and how).

Reversing a modulo with an exponent


Advice needed to understand an example in Characters and representation theory

Question: I am reading Representations and characters of groups by James Gordon and Martin Liebeck.
I would like to clarify on some concepts in an example given on pg 47. Here is an excerpt:

Let $C_3=\left<a:a^3=1\right>$. Then there is a representation $\rho$ of $C_3$ given by $\rho(a)=  \begin{pmatrix} 0 & 1 \\ -1 & -1 \end{pmatrix}.$ Let $V$ be a $2$ dimensional vector space over $\mathbb{C},$ with basis $\mathcal{B}=\{v_1,v_2\},$ then we turn $V$ into $\mathbb{C}C_3$ module, in particular, by defining $v_1a=v_2$ and $ v_2a=-v_1-v_2$.
  Hence, $[a]_\mathbb{\mathcal{B}}= \begin{pmatrix} 0 & 1 \\ -1 & -1 \end{pmatrix}.$ If $\mathbb{\mathcal{B'}}=\{u_1(=v_1),  u_2(=v_1+v_2)\}$ is another basis, then $[a]_\mathcal{B'}= \begin{pmatrix} -1 & 1 \\ -1 & 0 \end{pmatrix}.$

May I know if $[a]_\mathcal{B'}$ is defined as $ \begin{pmatrix} [(u_1a)]_{\mathcal{B'}}   \\ [(u_1a)]_{\mathcal{B'}} \end{pmatrix},$ where $[(u_ia)]_{\mathcal{B'}}$ is the coordinate vector of $u_ia$ relative to $\mathcal{B'} \ ?$
The authors go on to claim that:

If $T=\begin{pmatrix} 1 & 0   \\ 1 & 1  \end{pmatrix},$ then $[g]_{\mathcal{B}}=T^{-1}[g]_{\mathcal{B'}}T, \forall g \in C_3.$

May I know how is $\begin{pmatrix} 1 & 0   \\ 1 & 1  \end{pmatrix}$ obtained?
Based on my understanding, if we let $I:V \to V$ be the identity map, then $T = \begin{pmatrix} [I(v_1)]_{\mathcal{B'}}    \\ [I(v_2)]_{\mathcal{B'}}  \end{pmatrix}=\begin{pmatrix} 1 & 0   \\ -1 & 1  \end{pmatrix}$ since $I(v_1)=1\cdot u_1+0 \cdot u_2$ and $I(v_2)=-1\cdot u_1 + 1 \cdot u_2$ and similarly, $T^{-1}= \begin{pmatrix} [I(u_1)]_{\mathcal{B}}    \\ [I(u_2)]_{\mathcal{B}}  \end{pmatrix}=\begin{pmatrix} 1 & 0   \\ 1 & 1  \end{pmatrix}.$
May I know if my understanding is correct?
Please advise, thank you.
Answer: This is just what is known as "change of basis" in linear algebra - you can look this up in wikipedia or any linear algebra text for more details.
Note that James and Liebeck use in their book the convention that the matrix of a linear map is written on the rows instead of columns. So here the first row of $T$ is $u_1$ written in basis $\mathcal{B}$ and second row is $u_2$ is written in basis $\mathcal{B}$. Since $u_1 = v_1$ and $u_2 = v_1 + v_2$, you get $(1,0)$ and $(1,1)$ as the rows.
Comment: Noted, thank you. Is the $T$ that I have written correct as well?


Find anagrams in pyspark

Question: Type of variable origin is pyspark.rdd.PipelinedRDD, and origin contains something like:
[u'masquerade',
 u'squaremade',
 u'dianas',
 u'naiads',
 u'antagonist',
 u'stagnation',
 u'bates',
 u'beast',
 u'beats',
 u'thanks']

I want the key and all the anagrams sorted by the key:
[(u'aadeemqrsu', {u'masquerade', u'squaremade'}),
(u'aadins', {u'dianas', u'naiads'}),
(u'aaginnostt', {u'antagonist', u'stagnation'}), ...
(u'abest', {u'bates', u'beast', u'beats'}), ...]

I know it may need map or reducebykey function, but I really have no idea how to do it.
Answer: First you need to define an RDD:
origin =  [u'masquerade',
    u'squaremade',
    u'dianas',
    u'naiads',
    u'antagonist',
    u'stagnation',
    u'bates',
    u'beast',
    u'beats',
    u'thanks']

origin_rdd = sc.parallelize(origin)

you can print it to see the result:
print origin_rdd.take(10)

Now convert it to key-value pairs:
origin_kv = origin_rdd.map(lambda word: ("".join(sorted([letter for letter in word])),[word]))

do the reduce:
res = origin_kv.reduceByKey(lambda word1,word2: word1 + word2)

You can print the result:
print res.take(10)

If you need also the keys to be sorted, and you have enough space in the driver for all the data, you can sort the result:
print sorted(res.take(10))

Answer: Read the anagram  data like
'PSALM  MEALS  MESAL LEAMS SPALE  PELAS PEALS  SEPAL  MELAS SAMEL PALES  SALEP MALES AMPLE  LEAPS  Pelas'
rdd = spark.sparkContext.textFile("/data/anagram.txt")

Create a flat map by removing duplicates words
flatMap=rdd.flatMap(lambda s : s.split(" ")).distinct()

Create paired rdd with sorted words as key and word as value
pairedMap=flatMap.map(lambda word : ("".join(sorted(word.lower())), word))

Create dataframe to perform grouping
df=pairedMap.toDF()

df=df.groupBy(col("_1").alias("anagram_char")).agg(collect_list(col("_2")).alias("anagram_words"))

Checking words pattern that repeats more than one
df=df.withColumn("word_count", size((col("anagram_words"))))
df=df.filter(col("word_count") > lit(1))
df.show(truncate=False)

output will be like
|anagram_Pattern|anagram_word                                            |word_count|
+---------------+--------------------------------------------------------+----------+
|aelps          |[SPALE, PALES, SALEP, PELAS, PEALS, SEPAL, LEAPS, Pelas]|8         |
|aelms          |[MEALS, MESAL, MELAS, MALES, LEAMS, SAMEL]              |6         |
+---------------+--------------------------------------------------------+----------+

Find anagrams in pyspark


xcode 6 remains stationary while compiling the last source file

Question: I have problems when I try to do a Build or Archive  with Xcode 6. I'm not getting any error, Xcode is not freezed; if I do a build on the simulator goes all right (just slow 5 / 6min) and the same when I try on an iPhone 5 goes all right.
Instead  in iPhone 5s remains locked as when I try to Archive.
Thanks to all
Answer: This may happen when there are very large files to compile.
If you are using tools for managing graphics that generate classes check if the resulting file is huge!
Comment: Solved! The graphics have been generated with PaintCode, the StyleKit generated was 40,000 lines; This blocks the compilation and slowed Xcode! Thanks!


How to check which IAM performed an object modification of an s3 bucket

Question: Is there a way to see which IAM did a modification on a aws s3 bucket object (with versioning enabled)?
I know that there is the aws s3api list-object-versions, but it only shows the owner's DisplayName and ID (owner of aws organisation), not the underlying IAM that performed the modification.
"Owner": {
    "DisplayName": "my-username",
    "ID": "7009a8971cd660687538875e7c86c5b672fe116bd438f46db45460ddcd036c32"

Thanks in advance for the help.
Answer: You want to configure CloudTrail. This service monitors calls to the AWS platform and can also monitor S3 API calls, logging the user information you require.
More details here:
Logging Amazon S3 API Calls by Using AWS CloudTrail


Distinct Count Different Columns and Display Result into Multiple Columns in access 2010

Question: I am pretty new to SQL and Ms Access Database.
Had searched through some posts online but still confused on DISTINCT COUNT function.
May I know if the below can be done in a simple way without creating multiple queries or VBA code (due to performance issue)? Or can use sub-query and if yes how can it be done please?
Truly appreciate your advices please.
Many Thanks and Cheers
Pele
Table: Material

Result as below:
Answer: MS Access doesn't support COUNT(DISTINCT), so this is tricky.  One method uses subqueries.  I think this will work:
select c.col0,
       (select count(*)
        from (select distinct m2.col1
              from material as m2
              where m2.col0 = c.col0
             ) as m2
       ) as dcol1,
       (select count(*)
        from (select distinct m2.col2
              from material as m2
              where m2.col0 = c.col0
             ) as m2
       ) as dcol2,
       (select count(*)
        from (select distinct m2.col3
              from material as m2
              where m2.col0 = c.col0
             ) as m2
       ) as dcol3
from (select distinct col0 from material) as c;

I'm not 100% sure if MS Access supports the correlation clause two levels deep.  If not, you can write this as:
select c.col0,
       (select count(*)
        from (select distinct m2.col0, m2.col1
              from material as m2
             ) as m2
        where m2.col0 = c.col0
       ) as dcol1,

But the first better would have better performance.
EDIT:
For these queries, you want an index on (col0, col1).
Comment: Hi @Gordon Linoff, thanks for your advices! And yes performance is my main concern too as I may need to run more than 50K lines of records in Ms Access.  The first one seems working fine but may I know how can I avoid to input the value of Col0 each time when I execute the query please?  The second one seems shorter codes but I am unable to execute it. Can I define AS DCol1, DCol2, DCol3 after SELECT DISTINCT m2.Col0, m2.Col1, M2.Col3?  Please find attached TestDB.accdb  https://www.dropbox.com/s/u28lvc3ew7nt0vv/TestDB.accdb?dl=0
Comment: Hi @Gordon Linoff, do you have any clue on this please?
Answer: This suggests me simple GROUP BY with COUNT(DISTINCT) :
SELECT Col0, COUNT(DISTINCT Col1) AS DCol1,
       COUNT(DISTINCT Col2) AS DCol2, COUNT(DISTINCT Col3) AS DCol3
FROM table t
GROUP BY Col0;

DISTINCT COUNT is not a FUNCTION, there is two things one is FUNCTION which is COUNT() & other is DISTINCT which can be used for uniqueness.
You can also use it with SELECT statement to make entire row to unique.
EDIT : If the DISTINCT inside COUNT() function doesn't work, then you use correlation approach :
select distinct c.col0,
       (select count(*)
        from (select distinct m1.col1
              from material as m1
              where m1.col0 = m.col0
             ) as m1
       ) as dcol1,
       (select count(*)
        from (select distinct m2.col2
              from material as m2
              where m2.col0 = m.col0
             ) as m2
       ) as dcol2,
       (select count(*)
        from (select distinct m3.col3
              from material as m3
              where m3.col0 = m.col0
             ) as m3
       ) as dcol3
from material as m;

Comment: Thank you so much @Yogesh Sharman!! yes you are right that I have tried COUNT(DISTINCT) in Ms Access but unfortunately it didn't work. So I modified a bit of your codes as attached, also a good advices shared from Gordon Linoff in this thread.  https://www.dropbox.com/s/u28lvc3ew7nt0vv/TestDB.accdb?dl=0  Just had a question how can I avoid to input value of Col0 each time I execute the query.


Square Root of a matrix without diagonalization

Question: It's well known (wikipedia: Square root of a matrix) that we can calculate a square root of a matrix by diagonalization or Jordan decomposition (if it's possible). But I saw a different method which seems to work, although it isn't obvious for me why it works.
The method for a diagonalizable matrix $A$:
First calculate the minimal polynomial $\mu_A$ of the matrix. Then chose a polynomial $p$ with $p(\lambda)=\sqrt{\lambda}$ for every eigenvalue $\lambda$.
Now we get $\sqrt{A}=p(A)$.
But does it always work and why? It seems to be possible to use the method in a similar way, if the matrix isn't diagonalisable e.g. if the multiplicity $\lambda$ as a zero of $\mu$  is greater than one. In this case we have to add conditions to the derivates of $p$, like $p'(\lambda)=\frac{1}{2\sqrt{\lambda}}$. Is this also correct?
Answer: I think I have an answer to my own question:
We have $p^2(\lambda)=\lambda$ for all eigenvalues of $A$. So by euclidean division we get $p^2=q\cdot \mu_A+r$ where the remainder have the properties $r(\lambda)=\lambda$ and $\deg(r)<\deg(\mu_A)$. So we get $r(t)=t$, because we have $\deg(\mu_A)$ non trivial conditions on $r$.
So we conclude that $(p(A)^2)=p^2(A)=r(A)=A$ and so $p(A)$ is a square root of $A$.
With similar arguments we get the case where $A$ isn't diagonalizable.
But I still wonder why the method is so unknown, when it's a efficient method to calculate square roots of non diagonalizable matrices...
EDIT: I've found some other results now:
Why does calculating matrix inverses, roots, etc. using the spectrum of a matrix work?; Wikipedia: Sylvester's formula
Comment: This method is a nice theoretical result, but highly impractical. The Schur factorization method is much faster.
Comment: Can you tell a little bit more? I thought Schur factorization isn't always possible. How do you calculate the square root of the upper triangular matrix?
Comment: The Schur factorization can be computed for any square matrix. The square root $T_{1/2}$ of an upper triangular matrix $T$ is easy. $T_{1/2}$ is upper triangular, and after expressing elements of $T$ in terms of elements of $T_{1/2}$ we obtain a simple recursive formula for elements of $T_{1/2}$. Thus, $T_{1/2}$ can be found very fast. This algorithm is explained for example in Björck, Åke, and Sven Hammarling. "A Schur method for the square root of a matrix." Linear algebra and its applications 52 (1983): 127-140.


SimpleDateFormat parse(string str) doesn't throw an exception when str = 2011/12/12aaaaaaaaa?

Question: Here is an example:
public MyDate() throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
    sdf.setLenient(false);
    String t1 = "2011/12/12aaa";
    System.out.println(sdf.parse(t1));
}

2011/12/12aaa is not a valid date string. However the function prints "Mon Dec 12 00:00:00 PST 2011" and ParseException isn't thrown.
Can anyone tell me how to let SimpleDateFormat treat "2011/12/12aaa" as an invalid date string and throw an exception?
Answer: The JavaDoc on parse(...) states the following:

parsing does not necessarily use all characters up to the end of the string

It seems like you can't make SimpleDateFormat throw an exception, but you can do the following:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
sdf.setLenient(false);
ParsePosition p = new ParsePosition( 0 );
String t1 = "2011/12/12aaa";
System.out.println(sdf.parse(t1,p));

if(p.getIndex() < t1.length()) {
  throw new ParseException( t1, p.getIndex() );
}

Basically, you check whether the parse consumed the entire string and if not you have invalid input.
Answer: To chack whether a date is valid
The following method returns if the date is in valid otherwise it will return false.
public boolean isValidDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }
        catch (ParseException e) {
            return false;
        }
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }
        return true;

    }

Have a look on the following class which can check whether the date is valid or not
** Sample Example**
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateValidCheck {

    public static void main(String[] args) {

        if(new DateValidCheck().isValidDate("2011/12/12aaa")){
            System.out.println("...date is valid");
        }else{
            System.out.println("...date is invalid...");
        }

    }

    public boolean isValidDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }
        catch (ParseException e) {
            return false;
        }
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }
        return true;

    }

}

Answer: Java 8 LocalDate may be used:
public static boolean isDate(String date) {
    try {
        LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return true;
    } catch (DateTimeParseException e) {
        return false;
    }
}

If input argument is "2011/12/12aaaaaaaaa", output is false;
If input argument is "2011/12/12", output is true
Answer: After it successfully parsed the entire pattern string SimpleDateFormat stops evaluating the data it was given to parse.
Answer: You can use the ParsePosition class or the sdf.setLenient(false) function
Docs:
http://docs.oracle.com/javase/7/docs/api/java/text/ParsePosition.html
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient(boolean)
Comment: I think parse method only care about the start pos, not the end pos. isLenient doesn't work
Comment: When linking JavaDocs, please try to link the current version (which is 7, not 1.4.2).
Comment: @TerminalUser mm I tried it myself with an example but setLeniet() doesn't seems to work and ParsePosition only works when there is actually a exception thrown. You can check if both Strings have the same length after parseing without an Exception and then throw an exception manual. Not fully what you request but...
Answer: Take a look on the method documentation which says: ParseException if the beginning of the specified string cannot be parsed.
Method source code with javadoc:
/**
 * Parses text from the beginning of the given string to produce a date.
 * The method may not use the entire text of the given string.
 *

 * See the {@link #parse(String, ParsePosition)} method for more information
 * on date parsing.
 *
 * @param source A String whose beginning should be parsed.
 * @return A Date parsed from the string.
 * @exception ParseException if the beginning of the specified string
 *            cannot be parsed.
 */
public Date parse(String source) throws ParseException
{
    ParsePosition pos = new ParsePosition(0);
    Date result = parse(source, pos);
    if (pos.index == 0)
        throw new ParseException("Unparseable date: \"" + source + "\"" ,
            pos.errorIndex);
    return result;
}

Answer: Simply setting sdf.setLenient(false) will do the trick..


How to change text when hover is registered

Question: So I'm trying to make a text change whenever the user hovers such as the following below:

When the user hovers, I would like the word "HI" to change to something else, in which in this case "BYE". However, what I tried is not working:

.word_box span{
    text-transform: uppercase;
    font-weight: bold;
}

.word_box:hover span {
    content: "Bye";
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>

    The text beside will change when hovered
    Hi

Answer: You cannot use content on span but you can use it on pseudo elements like :after
For more info see here CSS content and go to Formal definition applies to:
Also, i would suggest you don't use label element outside a form or if it doesn't represent a caption for another element. label element has a lot of advantages when used with inputs but if you don't need it, use
 or  instead. You can even leave it as plain text inside the div if you don't have other elements.

.word_box:after{
    text-transform: uppercase;
    font-weight: bold;
    content: "HI";
}

.word_box:hover:after {
   content: "BYE";
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>

      The text beside will change when hovered

Comment: is it possible to not add a transition delay to it then?
Comment: 'content' property can't be animated. It's changing the content entirely. Not a color or a position. But you can use 2 different pseudo elements and position them absolute on top of eachother and animate them from opacity 0 to 1 BUT that was not in the scope of your original question. So if my answer solved your original problem, please don't forget to rate is as accepted so other users can use it.
Answer: .hi:after{
    text-transform: uppercase;
    font-weight: bold;
    content: "HI";
}

.hi:hover:after {
   content: "BYE";
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>

  The text beside will change when hovered


Place the footer AND the copyright blocks at the bottom of the page responsive

Question: I installed Industrial Theme from Zymphonies and I am struggling to place the footer and the copyright (2 block layouts) at the bottom of the page.

So, on my website it looks like that.
I tried a lot of methods but I do not know how to deal with 2 containers simultaneously.
Comment: It's called [sticky footer](https://css-tricks.com/couple-takes-sticky-footer/). Use the wrapper div that wraps both of those, if not add one.
Answer: If you are indeed looking to create a sticky footer, not sure what option this particular theme gives you but the idea is the same with any drupal theme

Add both blocks to a region that you will dedicate for this purpose
if no available region exists you can just create a new one
using custom css on your theme you can make this specific region position: fixed but there are other ways as mentioned by No Sssweat


Can I kill apt.system.daily to fix the apt install command?

Question: When I try to install anything (Ubuntu 16.04) with apt or apt-get I get this:
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?

This is the output of ps aux | grep apt:
root     23906  0.0  0.0   4504   784 ?        Ss   Feb20   0:00 /bin/sh /usr/lib/apt/apt.systemd.daily install
root     23912  0.0  0.0   4504  1640 ?        S    Feb20   0:00 /bin/sh /usr/lib/apt/apt.systemd.daily lock_is_held install

But these are the sub processes:
root     23906  0.0  0.0   4504   784 ?        Ss   Feb20   0:00 /bin/sh /usr/lib/apt/apt.systemd.daily install
root     23912  0.0  0.0   4504  1640 ?        S    Feb20   0:00  \_ /bin/sh /usr/lib/apt/apt.systemd.daily lock_is_held install
root     23943  0.1  3.7 140052 77424 ?        S    Feb20  56:54      \_ /usr/bin/python3 /usr/bin/unattended-upgrade
root     23948  0.0  0.0      0     0 ?        Z    Feb20   0:00          \_ [dpkg-deb] <defunct>
root     23965  0.0  2.9 140632 59508 ?        S    Feb20  31:44          \_ /usr/bin/python3 /usr/bin/unattended-upgrade
root     24051  0.0  0.2  19196  4632 pts/0    Ss+  Feb20   0:00              \_ /usr/bin/dpkg --status-fd 10 --configure redis-server:amd64 linux-modules-4.4.0-1102-aws:amd64 linux-image-4.4.0-1102-aws:amd64 linux-image-aws:amd64 linux-a
root     24052  0.0  0.0   4504  1660 pts/0    S+   Feb20   0:00                  \_ /bin/sh /var/lib/dpkg/info/redis-server.postinst configure
root     24094  0.0  0.0   4504  1696 pts/0    S+   Feb20   0:00                      \_ /bin/sh /usr/sbin/invoke-rc.d redis-server start
root     24138  0.0  0.0  24888  1340 pts/0    S+   Feb20   0:11                          \_ systemctl start redis-server.service

I believe that the PIDs from ps aux | grep apt are holding my apt install command but I don't want to kill the redis-server PID in the subprocesses and all the other PIDs eventhough systemctl status says that both redis and redis server state is deactivating (stop-post). And last time someone tried to install anything was redis-server
Comment: shorzly yes, i do ot some times
Comment: Thisi is a production server, what would happen to the redis-server and why is it connected with the daily install?
Comment: `root     23948  0.0  0.0      0     0 ?        Z    Feb20   0:00          \_ [dpkg-deb] ` dpkg is broken sofat kill the processes and restart via `apt install -f` or `dpkg-reconfigure -a`
Answer: Those are unattended upgrades, which acquire a different lock than the usual apt-get.
The simple way to install after the unattended upgrades pass is by waiting its lock to finish with flock. flock will wait until the lock is released and then it will execute sequentially update, upgrade and install.
 flock /var/lib/apt/daily_lock \
  apt-get -y update \
  && apt-get -y upgrade \
  && apt-get -y install \
    zip \
    unzip

References:

Debian
flock
Another's man take
Answer: 1:
Check apt services installed with:
systemctl list-units | grep apt
Disable the running apt services:
systemctl disable apt*.
e.g.
sudo systemctl disable apt-daily.service
Refer a very clean process at:
https://askubuntu.com/questions/1038923/do-i-really-need-apt-daily-service-and-apt-daily-upgrade-service
2:
You might also want to set to zero or false some of the config values of apt.conf files at
/etc/apt/apt.conf.d/10periodic
Refer:
https://askubuntu.com/questions/1167314/disable-automatic-updates-ubuntu-18-04
You most likely will be good with #1 above.
Hope this helps
Thanks


How to move from a physical server to an online server?

Question: My father has a small company: 10 PCs running Windows, 1 running Windows Server 2000 and 1 Fax/Printer.
I want to remove the server and make the network based on an Online server. Can I do that? If yes, how? By using a Windows VPS? Linux VPS with VMWaRE? I'm not sure if that's a viable option, if there's other, please tell me.
Answer: If you're using the server as a local network server (File shares, Exchange, SQL Server, Domain Controller, etc), you should not move it to the cloud.
These servers should be as close as possible to the clients in the network to optimize response time, so moving it to the cloud will make things much slower.
In addition, these servers should usually not be internet-facing (except a mail server)
Comment: +1, Accounting software counts as a file server (probably, or has financial info that you probably don't want the hosting company to have custody of). Hosted e-mail services are good, but a local server is faster.
Comment: +1 I don't think it can be uderstated how really really dangerous  and potentially expensive this idea is.
Comment: +1 - anoter case of incompetent advice "bettering" a business, potentially into oblivion ;)
Answer: Edit: The server is only used for Email, Backups, Fax and an Accounting software. Just that, very simple. If it wasn't for the Accounting software, I would move to a Linux VPS.
What I want to understand is: Can I still use the online server/VPS to do the same thing as the physical server? If yes, what should I learn first?
BR
Comment: I need to answer here, I'm sorry.
What if I don't have any other option? What if I need to go for the online server?
Comment: You should associate your accounts.
Comment: Yes, you can, but you shouldn't.
Comment: What do you recommend? I was thinking about Rackspace Cloud Windows? Thanks for your honesty.
Comment: Any help in how to do it? Something to read? Thanks
Comment: Out of curiosity why would you want to do this?
Comment: plus - how would you smartly replace the fax server? Ignoring reality. Not a good start.
Answer: Looks like you are determined to move to the cloud. I hate to advertise, but here is what happened. I moved one of our backup servers to the Amazon EC2 and it was pretty much easy as setting up a local server. It just took some time to understand the instances, images and elastic IP. But once done, everything worked like charm. I have not used rackspace, so don't know what advantages you get over the other.
Comment: the big difference is that rackspace can guarantee availablity and resource performance


quero clicar numa carinha e deixar apenas ela, caso clico em outra desmarcar a atual e deixar a nova marcada

Question: quero clicar numa carinha e deixar apenas ela, caso clico em outra desmarcar a atual e deixar a nova marcada

                                Muito Insatisfeito

                                <input type="radio" name="satisfacao" value="1" id="icone_minsastifeito"/>
                                1

                        Pouco Insatisfeito

                        <input type="radio" name="satisfacao" value="2" id="icone-pinsatisfeito">
                        2

                        Neutro

                        <input type="radio" name="satisfacao" value="3" id="neutro">
                        3

                            Pouco Satisfeito

                        <input type="radio" name="satisfacao" value="4" id="psatisfeito">
                        4

                        Muito Satisfeito

                        <input type="radio" name="satisfacao" value="5" id="msatisfeito">
                        5

Comment: segue link da aplicação de como a mesma esta http://enquete.provisorio.ws/lcf-teste/enquete/33
Comment: segue link das carinhas marcadas, porem queria que apenas uma ficasse https://i.stack.imgur.com/1sSmy.png
Comment: Outra duplicada https://pt.stackoverflow.com/questions/293657/duvidas-para-estilizar-um-link-ativo e mais outra https://pt.stackoverflow.com/questions/363232/adicionar-class-e-remover
Answer: A logica seria mais ou menos essa, antes de marcar o que foi clicado, desmarca todos, simples e rápido.

function uncheckItems (item) {
  item.forEach(element => {
    element.style.color = "#000000"
  })
}

document.querySelectorAll('li').forEach(element => {
  element.addEventListener('click', () => {
    uncheckItems(document.querySelectorAll('li'))
    element.style.color = "#FF0000"
  })
})
ul {
  display: flex;
}

li {
  list-style: none;
  border: 1px solid;
  border-radius: 5px;
  cursor: pointer;
  margin: 0 5px;
  width: 20%;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

1

2

3

4

5


Condição (WHERE) com IF

Question: Tenho duas tabelas (posts e posts_promovidos). Ambas se relacionam e a busca "normal" funciona sem problemas. Porém, preciso fazer uma busca que me retorne todos os posts e, caso o post pertença à posts_promovidos, me traga somente os posts_promovidos com status = "N".
Tentei algo do tipo
SELECT * FROM posts AS POST [...] WHERE [..] AND IF((SELECT COUNT(*) FROM posts_promovidos WHERE posts_promovidos.post_id = post.id) > 0,posts_promovidos.ativo = "N","")

Porém não funcionou como queria pois está trazendo apenas os posts promovidos e ignorando os posts "não promovidos" (que não constam da tabela posts_promovidos).
Qual seria a forma mais correta de fazer essa busca?
EDIT - SOLUÇÃO
Resolvi da seguinte maneira (compartilhando para ajudar quem tenha algo parecido):
SELECT * FROM posts AS POST [...] WHERE [..] AND posts.id NOT IN(select post_id from posts_promovidos) OR posts_promovidos.ativo = "N"

Answer: LEFT JOIN resolve seu problema:
SELECT
   p.*
FROM posts p
LEFT JOIN posts_promovidos pp
    ON p.id = pp.id
    AND pp.status = 'N'

Comment: Já tenho o JOIN devidamente configurado e funcionando. Só tenho essa questão de, em alguns casos, verificar se o post está em posts_promovidos e, se estiver, que não esteja ativo (ativo = "N"). O JOIN é incondicional, ou seja, sempre vai acontecer.
Answer: select * from posts_promovidos where posts_promovidos.status = "N"
inner join (select * from posts where posts.id not in posts_promovidos) p on p.id = posts_promovidos.id

Comment: Luis, bem vindo ao StackOverflow! Seria interessante se você juntasse ao código uma pequena explicação de como ele reponde à pergunta

Condição (WHERE) com IF


Memory Management of C code in iPhone application

Question: I am developing an iPhone application which has a module written in C and Objective C.
I am using pthread_create for creating new thread.
For memory allocation, i have used malloc().

Will NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]
handle this memory? Or should i explicitly use free() to release this memory?
The thread is running continuously and it is allocating lot of memory. So after one point, it gives memory warning.
Will it create problem if i explicitly free the memory as well as i use NSAutoreleasePool?
Is there any way to check the memory leaks in this thread. Xcode's profile tool is used to check memory leaks in objective C code. will it help to manage C type memory allocation?

Please help me out.
Answer: Anything you don't send an autorelease message to will not be a target for the autorelease pool.  Since you can't send messages to plain c-objects, they will never be affected.  C objects always need to be managed manually (even with ARC).
Answer:
Will NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init] handle this memory? Or should i explicitly use free() to release this memory?

you should use free for all memory allocated through malloc

Will it create problem if i explicitly free the memory as well as i use NSAutoreleasePool?

none. you have to do that as well.

Is there any way to check the memory leaks in this thread. Xcode's profile tool is used to check memory leaks in objective C code. will it help to manage C type memory allocation?

as far as I understand, Instruments Leaks is tightly related to the ObjC runtime system, so it does not work for memory directly (meaning, not via the ObjC runtime) allocated through malloc. For MacOSX, Apple provides a couple of tools to detect memory leaks (MallocDebug and leaks, see here), but they do not work for iOS apps. You might try to run them against the simulator, but I suspect they would not give you reliable results.
On the other hand, if you are using a plain-C library, then you might build around it a plain-C testbed derived from your overall code (by removing the iOS specific parts) to be able to check it under MacOSX. The testbed would emulate the kind of workflow of your app with the C-only module. This would be a significant effort, though, and I would go for it only if you are really worried about it.
Another approach you have is building and ObjC wrapper around your C module, so that you have one or more classes that use the C module and allocate/release memory for it through malloc/free in the init/dealloc methods; you could check that your ObjC wrapper objects are not leaked by using Instruments and if you have correctly implemented the wrapper objects you could be pretty sure that you are not leaking malloc memory.
Comment: Can I check these memory leaks by using instruments of XCode? It shows me memory allocation by malloc. but not showing me leaks.


Question about Brownian motion

Question: Let $\{B(t), t \in \mathbb{R} \}$ be a two sided brownian motion defined as
$$
B(t) = \begin{cases} B_1(t),\quad t >0 \\
0, \quad t = 0 \\
B_2(-t), \quad t < 0 \end{cases}
$$
where $B_1$ and $B_2$ are independent standard Brownian motions on $\mathbb{R}^+$.
Fix $x_0 > 0$ and let $x_k = B(x_{k-1})$ for $k=1,2,\dots$.  What can we say about $\lim_{k\rightarrow \infty} x_k$?
If it converges, then I imagine the limit would have to be to $0$ a.s., since the limit $y$ would satisfy $B(y) = y$ a.s..  But I don't know how to show this sequence converges.  Any ideas? (this isn't homework, just a problem my friend and I thought up)
Comment: Maybe you can start looking at $\mathbb{E}[x_k | x_{k-1}]$  and use $\mathbb{E}\left[\mathbb{E}[X|Y]\right] = \mathbb{E}[X]$ which would then at least give you a recurrence relation for the expectation values. A similar argument could be tried for the variances. Combining, you might deduce a limit for the actual sequence of random variables.
Comment: I'd like to say I really like this question.  There are a lot of things going on here which make things complicated.  I hope this link for the wiki article on [iterated functions](http://en.wikipedia.org/wiki/Iterated_function) is helpful.
Answer: For any fixed $x_0$, there is positive probability that the sequence starting from $x_0$ fails to converge.   To see why, take, say, $x_0 = 15$.  There is positive probability that $50 < B_t < 60$ for $10 < t < 15$ and $10 < B_t < 20$ for $50 < t < 60$.  On this event the sequence oscillates between the intervals $(10,20)$ and $(50,60)$.
On the other hand, almost surely there exist infinitely many $t$ in any interval $(0,\epsilon)$ with $B_t = t$, so even when the sequence does converge the limit need not be 0.  For a proof, note that $P(B_t > t) = P(N > \sqrt{t}) \ge 1/4$ for sufficiently small $t$ (here $N$ is a standard normal random variable).  So for any sequence $t_n$ decreasing to $0$, we have $P(B_{t_n} > t_n \text{ i.o.}) \ge 1/4$; by the Blumenthal 0-1 law, $P(B_{t_n} > t_n \text{ i.o.}) =1$.  However, we also have $P(B_{t_n} < t_n) \ge P(B_{t_n} < 0) = 1/2$ so by a similar argument $P(B_{t_n} < t_n \text{ i.o.}) =1$.  The result follows by continuity.
One could ask some other questions:

For a fixed $x_0$, what is the probability that the sequence starting from $x_0$ converges?  My guess is $0$ but I don't see a proof offhand.
Consider the (random) set $C$ of $x$ such that the sequence starting from $x$ converges.  What is the Lebesgue measure of $C$?  My guess is that $m(C) = 0$ a.s. but again no proof.

Edit: Another interesting fact is that almost surely, for every starting point $x_0$, the sequence $x_k$ is bounded, and hence has a convergent subsequence.  Let $M_r = \sup_{t \in [-r,r]} |B_t|$.  By the strong law of large numbers, $B_t/t \to 0$ a.s. as $t \to \pm \infty$, and it follows that $M_r / r \to 0$ a.s. as $r \to \infty$. In particular, a.s. there exists $r > x_0$ with $M_r < r$, and then $|x_k| \le M_r$ for all $k \ge 1$.
Comment: very good questions!  another way to see $B(t) = t$ i.o. is to notice the set of zero crossings of $X(t) = B(t) - t$ is a perfect set by the strong Markov property, and the last crossing time of $0$ for $X(t)$ has an exponential distribution.

Question about Brownian motion


Would adding a new function to the existing COM interface break its binary compatibility?

Question: I want to add a new method to a COM interface with all the existing one unchanged, will this break its compatibility for the consumer before this update?
Answer: It depends: if this is an internal unpublished interface, you are free to change it at will so long as you control all the code that interacts with that interface.
Once published, however, the rules are strict: every interface has its own IID. You change that interface in any way - by modifying, adding or removing methods - it's a whole new interface, and requires a new IID.
However: COM does doesn't care how that new interface is implemented: so you can have your class implement it as a derivation of the old interface that just adds a new method, and have your implementation class implement the derivation, so long as QI returns a suitable interface when asked for either the old or new interface.
For example:
<code>class IInterfaceOriginal: public IUnknown
{
public:
    ...
    // lots of methods
    ...
};

class IInterfaceUpdated: public IInterfaceOriginal
{
public:
    // Add just one additional method
    STDMETHOD(AdditionalMethod)(...) = 0;
};

class CImplementation: IInterfaceNew // this was IInterfaceOld
{
    // Also add implemention of AdditionalMethod somewhere here...

    HRESULT STDMETHODCALLETYPE QueryInterface( REFIID riid, void **ppvObject )
    {
        *ppvObject = NULL;
        if(riid == __uuidof(IUnknown)
        || riid == __uuidof(IInterfaceOriginal)
        || riid == __uuidof(IInterfaceUpdated)) // This is added
        {
            // Return a IInterfaceUpdated in response to a QI for either of IUnknown,
            // or the old or new interface. This works because in C++, any IInterfaceUpdaed
            // is also both of those two other interfaces.
            *ppvObject = static_cast<IInterfaceUpdated*>(this);
        }
        else
            return E_UNKNOWN;
        return ((IUnknown*)*ppvObject)->AddRef();
    }

    ...
}
</code>
So, while you are technically "adding another interface", you're actually adding little code here: just defining a new interface that derived from the old one, changing the interface your class implements to the new one (and adding the implementation for the new method), and finally updating QI to support both the old and new methods - returning the same interface for both (and for IUnknown too).
Answer: It would certainly break derived interfaces, so it should not be done even if it appears to work.
Instead, derive a new interface containing the additional method(s), and have clients that require the additional functionality QI for the new IID.
Comment: Well, this is the way to allow implementors of derived interfaces to remain binary compatible. :)
Comment: This sounds good, there are many functions in the existing interface and I only add one. Add a new interface seems to be a big change.
Answer: As long as new method is appended, COM interface should be backward compatible. If client application wants to use new COM interface, they have to update header file (C++) or re-add reference(.NET) to the new COM interface. Also, you may need to restart the OS if COM interface is changed without updating IID. In conclusion, it would work without changing IID, but it may be more "correct" to change IID.
Comment: COM interfaces are immutable. http://msdn.microsoft.com/en-us/library/windows/desktop/ms688484(v=vs.85).aspx
Comment: @TownCube So, what exactly would break if I do change it?


DotNetCore 2.2 App with IIS not working - HTTP Error 500.0 - ANCM In-Process Handler Load Failure

Question: I have a DotNet Core 2.2 application that I am trying to get running through IIS. However, I get the following error: HTTP Error 500.0 - ANCM In-Process Handler Load Failure when I try to load the app in my browser.
Upon checking the logs it says the following:
<code>Error:

  An assembly specified in the application dependencies manifest (blablabla.deps.json) was not found:
    package: 'AutoMapper.Extensions.Microsoft.DependencyInjection', version: '7.0.0'
    path: 'lib/netstandard2.0/AutoMapper.Extensions.Microsoft.DependencyInjection.dll'
</code>
But I think that's a bit of a red herring.
The following is the output from dotnet --info:
<code>.NET Core SDK (reflecting any global.json):
 Version:   2.2.401
 Commit:    729b316c13

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.17134
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\2.2.401\

Host (useful for support):
  Version: 2.2.6
  Commit:  7dac9b1b51

.NET Core SDKs installed:
  2.2.401 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.2.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.2.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.2.6 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download
</code>
I have tried all of the following:

Changed "AspNetCoreModuleV2" to "AspNetCoreModule" in the
Web.config.
Tried switching AspNetCoreHostingModel=InProcess to
    RuntimeFrameworkName=Microsoft.AspNetCore.App in my Web.csproj file.
Cleaning and manually deleting the bin, obj, and .vs folders

My application pool is set to 'No Managed Code' (as the guides all say). At a bit of a loss regarding what to do as I've been through every forum post and github issue on the matter. Also, it is running on my colleagues machine whom has the exact same configuration as me.
One thing to note though, if he creates a copy of his application pool (same settings, basic and advanced, just a different name), and tries to run it on that, it doesn't work either and he gets the same error as me. It only works on the application pool called 'Core AppPool' which was automatically added to IIS upon installation of windows server hosting or the SDK (not sure which).
Comment: I suggest you could also check your application pool identity to have the enough permission to access the core dll folder and your package dll's folder.
Comment: What if you use self-contained deployment?
Comment: @BrandoZhang That turned out to be the issue. The App Pool didn't have permission to read the Packages folder. No idea why it didn't automatically apply the permissions like it did on the other machine. Not sure what the etiquette is here but if you want to make that a main comment I'll mark it as the answer. Thanks.
Comment: I had this exact problem. I had already given permission in file explorer. However, when I did the same thing with the "Edit Permissions" menu from inside the IIS control panel, it then worked. odd.
Comment: This did the trick for me too, Here's a link to the relevant documentation FYI https://learn.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities
Answer: It seems your application pool identity don't have the enough permission to access your package folder.
I suggest you could try to set the package folder with enough permission by setting the folder's security.


How do I ping a webpage in php to make sure it's alive?

Question: I have a list of urls for some webpages and I want to make sure that this url ( webpage ) exists and not deleted or it doesn't exist. I want to do it in PHP.
How do I ping a webpage to make sure it's alive?
Comment: Try this SO post, there is a nice example in it: http://stackoverflow.com/questions/1239068/ping-site-and-return-result-in-php
Comment: Do you want to do this on command or have it as a scheduled task?
Answer: $urls = array(...);

foreach($urls as $url) {
    $headers = get_headers($url);

    if ( ! $headers OR strpos($headers[0], '200 OK') === FALSE) {
       // Site is down.
    }
}

Alternatively you could use ping.
$response = shell_exec('ping ' . escapeshellarg($url));

// Parse $response.

Update
You mention you want this to be scheduled. Have a look into cron jobs.
Answer: Create a PHP script that fires off an HTTP Request to each URL that you want to be kept-alive.
PHP HTTP Request
I suggest setting up a Task in your operating system that accesses this script every 15 minutes in order to keep these applications alive. Here's some info on running PHP from the command line in Windows.
Answer: See http://www.planet-source-code.com/vb/scripts/ShowCode.asp?lngWId=8&txtCodeId=1786 for a thorough implementation.


Quadratic equations in $\mathbb{C}$

Question: How to solve $x^2-4=0$ but results should be written in form $a+bi$.
$z=\pm 2$ that means that results are $2+i0$ and $2-i0$ or what?
Comment: rather $2+0i$ and $-2+0i$ but yes
Comment: Oh, $\mathbb C$, not the C programming language :-)
Comment: The results $2, -2$ are already complex numbers for $\mathbb{R}\subset\mathbb{C}$ and $0i = 0$ on top of that $a+0=a$ in every field.
Answer: When we write:$$z=a+ib$$$a$ represents the real component and $b$ represents the imaginary component.
In your case, both answers are real so they can be written as:$$z=\pm2+0i$$
But, as @alvin pointed out in the comments above, $0i=0$ and therefore it is valid to write the answer as:$$z=\pm2$$
Compare this to some ficticious problem where the result was $\pm2i$, this could be written as:$$z=0\pm2i$$But is usually written as:$$z=\pm2i$$

Quadratic equations in $\mathbb{C}$


Can TIME_WAIT port be reused for different remote server?

Question: On a machine, I found there are many TIME_WAIT connections(to different remote server) using same local port by netstat:
tcp        0      0 10.32.198.120:10240         10.32.92.81:4000            TIME_WAIT
tcp        0      0 10.32.198.120:10240         10.66.32.192:80             TIME_WAIT
tcp        0      0 10.32.198.120:10242         10.32.92.81:4000            TIME_WAIT
tcp        0      0 10.32.198.120:10242         10.66.32.192:80             TIME_WAIT
tcp        0      0 10.32.198.120:10243         10.32.92.81:4000            TIME_WAIT
tcp        0      0 10.32.198.120:10243         10.66.32.192:80             TIME_WAIT
tcp        0      0 10.32.198.120:10244         10.32.92.81:4000            TIME_WAIT
tcp        0      0 10.32.198.120:10244         10.66.32.192:80             TIME_WAIT
tcp        0      0 10.32.198.120:10245         10.66.32.192:80             TIME_WAIT

I knew TIME_WAIT is designed for preventing old packets from a previous connection from being accepted into a new connection. But since a new connection to a different remote server will not be mistaken as the old connection, so I think it's clearly safe to use a TIME_WAIT port for a different remote server.
So, is what I saw (same local ports in different connections) an evidence that TIME_WAIT port is reused?
I am on CentOS 6.5 (tcp_tw_reuse is set as 0) and these connections are created by python2.7.6/requests2.12.1.
Answer: The fact that your sockets are in TIME_WAIT doesn't really matter here, they could be in ESTABLISHED state and your question would still stand - why am I seeing the same source port for multiple connections?
TLDR: As long as the TCP 4-tuple (Source IP, Source Port, Destination IP, Destination Port) is not the same, it is permitted to use the same source port for multiple connections.
TIME-WAIT is used to prevent old packets from being accepted in a new connection using the exact same TCP 4-tuple as an old connection.

In most cases, Linux automatically assigns the source port from the Ephemeral port range which defaults to 32768 to 61000:
# cat /proc/sys/net/ipv4/ip_local_port_range
32768   60999

When deciding on which source port to use, the Kernel will first of all check if there is any source port which is unused from the ephemeral port range. With ~28k possible source ports, the Kernel is normally able to find an available port and stop there. If all 28k ports are in use however, it will next check if any of the ports pass the check_established source function which will allow an already allocated source port to be re-used as long as the new connection is for a different TCP 4-tuple.
Also, rather than letting the Kernel automatically assign a source port, it is also possible to programatically tell the Kernel exactly which source IP and port you would like to use for a specific connection.


I would like to get ratings and destructure it when I console the props.ratings I get Array(1) but I get (found: object with keys {star, ,...}

Question:
ERROR Objects are not valid as a React child (found: object with keys
{star, review, reviewDate, name, userID}). If you meant to render a
collection of children, use an array instead.

and my console.log(props.ratings) I get [{…}]  0
<>
  {props?.ratings.map((item, index) => {
    const { star, review, reviewDate, name, userID } = item;
    return (

        <StarRating
          starDimension="20px"
          starSpacing="2px"
          starRatedColor="#F6B01E"
          rating={star}
          editing={false}
        />

{review}

          {reviewDate}

          by: {name}

    );
  })}
</>

ERROR Objects are not valid as a React child (found: object with keys
{star, review, reviewDate, name, userID}). If you meant to render a
collection of children, use an array instead.

And my console.log(props.ratings) I get [{…}]  0 :  {star: 2, review: 'not satisfied', reviewDate: 'Tue Feb 27 2024', name: 'Feisal', userID: '65d5d891dc5ae55627c99ebd'} length :  1 [[Prototype]] :  Array(0).
Comment: Looks like you are trying to render some `item` object directly somewhere in your code. Are you sure *this* is the problematic code? *What* console log are you referring to? There's none in your example code. See [mcve].
Comment: it seems the problem is review props, the problem can be for several reasons: passing an Object/ Non-Serializable Data/ Array as a child,
What is the value of the review?
Answer: possibly your error is not coming from your provided piece of code
<>
    {props?.ratings.map((item, index) => {
        const { star, review, reviewDate, name, userID } = item;
        return (

                <StarRating
                    starDimension='20px'
                    starSpacing='2px'
                    starRatedColor='#F6B01E'
                    rating={star}
                    editing={false}
                />

{review}

                    {reviewDate}

                    by: {name}

        );
    })}
</>

However, the error you're encountering usually occurs when props.ratings is not an array during some render cycles. To avoid this, you can add a conditional check before calling map to ensure that props.ratings is indeed an array.
<>
    {Array.isArray(props?.ratings) &&
        props?.ratings.map((item, index) => {
            const { star, review, reviewDate, name, userID } = item;
            return (

                    <StarRating
                        starDimension='20px'
                        starSpacing='2px'
                        starRatedColor='#F6B01E'
                        rating={star}
                        editing={false}
                    />

{review}

                        {reviewDate}

                        by: {name}

            );
        })
    }
</>

this error actually comes when you try to render item directly in you jsx code like below
<>
    {props?.ratings.map((item, index) => {

        return (

                {item}

        );
    })}
</>


How can I replace a column of values by another with different number of rows?

Question: I have the following df:
df=
               A     B    C
2016-04-16     3     2    2
2016-04-17     4     4    1
2016-04-18     7     3    1
2016-04-19     5     1    3
2016-04-20     5     1    7

On the other hand I have a recalculated column (with 4 rows instead of 5):
df1=
                C
2016-04-16     3.2
2016-04-17     4.7
2016-04-18     7.1
2016-04-19     3.3

how could I replace the recalculated column into the original df to obtain the following output?
df=
               A     B    C
2016-04-16     3     2    3.2
2016-04-17     4     4    4.7
2016-04-18     7     3    7.1
2016-04-19     5     1    3.3
2016-04-20     5     1    7

Answer: Here's one way using combine_first
In [1327]: df.assign(C=df1.C.combine_first(df.C))
Out[1327]:
            A  B    C
2016-04-16  3  2  3.2
2016-04-17  4  4  4.7
2016-04-18  7  3  7.1
2016-04-19  5  1  3.3
2016-04-20  5  1  7.0

Or,
In [1331]: df1.combine_first(df)
Out[1331]:
              A    B    C
2016-04-16  3.0  2.0  3.2
2016-04-17  4.0  4.0  4.7
2016-04-18  7.0  3.0  7.1
2016-04-19  5.0  1.0  3.3
2016-04-20  5.0  1.0  7.0


Calcular média, desvio padrão e coeficiente de variação em série histórica no R

Question: Bom dia,
Preciso gerar a média, o desvio padrão e o coeficiente de variação do data frame abaixo, das colunas mat13 a mat16, conforme abaixo:
library(plyr)
co_entidade<-c(23, 40, 58, 82, 104, 171,    198, 201, 202,244)
depend<-c(2,3,4,4,4,4,4,2,3,4)
mat13<-c(42,    218,    1397,   245,    393,    283, 1053,  529,    NA, 664)
mat14<-c(44,    222,    1300,   218,    428,    246,    994,    521,    NA, 678)
mat15<-c(40,    215,    1345,   199,    411,    226,    1069,   566,    NA, 598)
mat16<-c(10,    208,    1442,   154,    425,    229,    1033,    NA,    521,552)

df<-data.frame(co_entidade, depend, mat13, mat14, mat15, mat16)
df

co_entidade   depend  mat13 mat14 mat15 mat16
1           23      2    42    44    40    10
2           40      3   218   222   215   208
3           58      4  1397  1300  1345  1442
4           82      4   245   218   199   154
5          104      4   393   428   411   425
6          171      4   283   246   226   229
7          198      4  1053   994  1069  1033
8          201      2   529   521   566    NA
9          202      3    NA    NA    NA   521
10         244      4   664   678   598   552
E quando eu aplico a função ddply, nenhuma das estatísticas (média, des padrão e coeficiente de variação não são calculados para cada linha (co_entidade), pegando os valores das colunas mencionada, conforme abaixo.
cv<-function(x){coef<-sd(x)/mean(x)*100
return(coef)}

descrit<-ddply(df, .(co_entidade,depend, mat13, mat14, mat15, mat16),
summarize,
         media = mean(3:6,na.rm=T),
         desvpad = sd(3:6,na.rm=T),
         coefi= cv(3:6)
)
descrit

Entretanto, a função que apliquei não retorna os valores corretamente por linha, conforme imagem.
Quem puder favor ajudar.
Answer: Estou escrevendo como resposta, já que não tenho reputação para comentar ^_^.
Eu não estou entendendo a sua pergunta. Você quer agrupar o df por co_entidade, e pegar as estatísticas de mat13:mat16, correto?
Se for isso, julgo que mat13:mat16 são uma mesma variável, que vou chamar de mat_tipo com um mat_valor.
library(dplyr)
library(tidyr)
df %>%
    gather(mat_tipo, mat_valor, mat13:mat16) %>%
    group_by(co_entidade) %>%
    summarise(
        média_mat = mean(mat_valor, na.rm = T),
        desv_mat = sd(mat_valor, na.rm = T),
        cv_mat = (desv_mat/média_mat)*100
        )

# A tibble: 10 x 4
co_entidade média_mat  desv_mat    cv_mat
<dbl>     <dbl>     <dbl>     <dbl>
1          23   34.0000 16.083117 47.303287
2          40  215.7500  5.909033  2.738833
3          58 1371.0000 61.735997  4.502990
4          82  204.0000 38.305787 18.777347
5         104  414.2500 15.986974  3.859257
6         171  246.0000 26.191602 10.646993
7         198 1037.2500 32.376689  3.121397
8         201  538.6667 24.006943  4.456735
9         202  521.0000        NA        NA
10         244  623.0000 58.799093  9.43805

Note a ultima variável que crio na função summarise, o coeficiente de variação. Posso referenciar variáveis recém criadas na criação de outras.
Comment: Mas viu, recomendo transicionar do mundo do `plyr` para o mundo do `dplyr` + `tidyr` já que o `plyr` não é mais mantido/desenvolvido. Sem falar que eu acho a API do `dplyr` + `tidyr` bem mais tranquila de se entender e ler.
Comment: Guilherme, é isso mesmo que preciso, vou testar os seus comandos, se puder veja o coeficiente de variação também.
Comment: @Tadeu, eu não havia lido a definição da sua função cv, então não estava entendendo. Segue a solução! Pelo menos é assim que eu faria :D


Python -Is there a way to sort a list of strings which contain a date and time within

Question: Say this is my list of values:
my_list = ['Version1 2016,03,12 22:30', 'Version2 2016,03,29 23:00', 'Version3 2016,04,07 16:00', 'Version4 2016,02,24 15:00']
Is there a way to sort the list by the earliest date and time but by keeping the the Version at the front of the string.
Answer: You'd have to parse the datetime substring when sorting:
from datetime import datetime

sorted(my_list, key=lambda x: datetime.strptime(x.split(maxsplit=1)[1], '%Y,%m,%d %H:%M'))

['Version4 2016,02,24 15:00',
 'Version1 2016,03,12 22:30',
 'Version2 2016,03,29 23:00',
 'Version3 2016,04,07 16:00']

Answer: You can use sorted with a custom key:
list(sorted(my_list, key=lambda x: x.split(" ", maxsplit=1)[1])
['Version4 2016,02,24 15:00',
 'Version1 2016,03,12 22:30',
 'Version2 2016,03,29 23:00',
 'Version3 2016,04,07 16:00']

If the date is in the format you give, you do not need to parse it as a datetime, lexicographical order is enough
Comment: Also, why two identical answers?
Comment: I edited the answer on the mobile app and it created another answer that I cannot delete...
Answer: You can use sorted with a custom key:
list(sorted(my, key=lambda x: x.split(" ", maxsplit=1)[1]))

Comment: sorted already returns a list. And you're not parsing the date, you're sorting that string lexicograpically, which won't at all sort the date...
Comment: I thought sorted would give an iterator, you're right it is not needed. If the date format is year, month, day, time, lexicographical order is correct
Comment: Yes it returns list, actually I think it should without casting to datetime yes. But potentially more prone to errors, such as if the month field can be `9` and `11`
Answer: import re
from datetime import datetime

sorted(my_list, key=lambda x: datetime.strptime(re.sub(r"Version.", "", x).strip(), "%Y,%m,%d %H:%M"))

Output:
['Version4 2016,02,24 15:00',
 'Version1 2016,03,12 22:30',
 'Version2 2016,03,29 23:00',
 'Version3 2016,04,07 16:00']

Answer: THis could work as well:
print sorted(l, key=lambda x: int("".join([i for i in x if i.isdigit()])))

Answer: using pandas
import pandas as pd
data = ['Version1 2016,03,12 22:30', 'Version2 2016,03,29 23:00', 'Version3 2016,04,07 16:00', 'Version4 2016,02,24 15:00']
df = pd.DataFrame(data)
df = pd.concat([df, df[0].str.split(" ", n=1, expand=True)], axis=1)
df.columns = ["text","version","timestamp"]
df.timestamp = pd.to_datetime(df.timestamp, format="%Y,%m,%d %H:%M")
df.sort_values("timestamp")["text"].tolist()

output
['Version4 2016,02,24 15:00',
 'Version1 2016,03,12 22:30',
 'Version2 2016,03,29 23:00',
 'Version3 2016,04,07 16:00']