Understanding the meaning of transition rates in a CTMC

Question: I am reading the queueing theory volume 1 by Kleinrock. In the chapter on Continuous Time Markov Chain(CTMC), the author defines the infinitesimal generator, $Q(t)$ as having the following elements:
\begin{align}
q_{ii}(t) &= \lim_{\Delta t \to 0 } \frac{p_{ii}(t, t+ \Delta t) - 1}{\Delta t} \\
q_{ij}(t) &= \lim_{\Delta t \to 0 } \frac{p_{ij}(t, t+ \Delta t)}{\Delta t} & i &\neq j
\end{align}
where $p_{ij}(t, t+ \Delta t)$ is the probability of moving to state j from i in a small interval $\Delta t$.
The author says that - "if the system at time $t$ is in the state $E_i$ then the probability that a transition occurs ( to any state other than $E_i$) during the interval $(t + \Delta t)$ is given by $- q_{ii} \Delta t + o(\Delta t) $. Thus we may say that $-q_{ii}$ is the rate at which the process departs from the state $E_i$ when it in the state."
I am unable to understand how the author arrives at the above interpretation from the limit definition. Can someone please provide clarification or point me to resources where there is an elaborate explanation?
Answer: $P_{ij}(t,t+\Delta t)$ is the probability that the system is on the state $i$ at time $t$ and in the state $j$ at time $t+\Delta t$.
In discrete time MC, it is good enough because the system moves only once at each time step. (including moves to the same state)
However, in continuous time MC, the $P_{ij}(t,t+\Delta t)$ includes that the system moves from $i$ to $k$ and moves to $j$.  Between $t$ and $t+\Delta t$ it can go any state as long as it comes back to the state $j$.
And also it doesn't show how long it will stay the current state. we need another variable to show the staying time which should be exponential random.
Therefore, I believe, the rate comes in.
If you compare the limit with the definition of the derivative, you will get the idea.
I don't know why the author uses $p_{ii}-1$ instead of $1-p_{ii}$, though it is just a matter of sign.
$1-p_{ii}$ can be interpreted as the probability to leave the state $i$.
And as $\Delta t$ goes to $0$, the limit becomes the rate (the slope of the probability curve, or the speed of probability change at time $t$) of leaving the current state $i$.
By limiting $\Delta t$ to $0$ we don't need to care about moving out and coming back.
Not sure I made all the statements mathematically correct. This is how I understand the rate (instead of Probability) in CTMC.
Comment: The sign of the diagonal entries of $q$ is negative for a reason; it is the derivative of $p_i$ when $p_i(t)=1$, so it must decrease as probability flows from $i$ to its neighbors $j$. Eventually it will tend to increase again as probability flows back to it, of course.
Comment: Thank you, Professor
Comment: @Ian, I am sorry I didn't get your comment completely. When you say $p_i(t)$, does it mean the probability of being in state $i$ at time $t$?
Comment: @gaganso Yes. This is because $q_{ij}$ is just $\left. \frac{d}{dt} P(X_t=j \mid X_s=j) \right |_{t=s}$. So the fact that $q_{ii}<0$ is not just convention.
Comment: @Ian, Got it. Thank you!
Comment: (There is an obvious typo in my previous comment...)
Answer: For discrete state space $S$, note that:
$$\sum_{j \in S : j \neq i} q_{ij}$$
is the instantaneous rate that the process departs state $i$, given it is in state $i$.
So for small $\delta>0$ we have
$$P[X(t+\delta) = i|X(t)=i] \approx 1-\sum_{j \in S : j \neq i}q_{ij} \delta$$
So
$$\frac{P[X(t+\delta)=i|X(t)=i] - 1}{\delta} \approx  -\sum_{j \in S : j \neq i}q_{ij}$$
and this approximation becomes exact as $\delta\rightarrow 0$.
Comment: Note that for small $\delta>0$, we can safely assume there is either no transition in a time interval of size $\delta$, or exactly 1 transition.  The probability of 2 or more transitions is negligible.
Comment: Note that you can view $q_{ii}$ as being  _defined_ as $q_{ii} := -\sum_{j \in S : j \neq i} q_{ij}$.
Comment: Thank you, Professor.


Posso abrir o VS2017 com um usuário diferente daquele colocado na instalação?

Question: Posso abrir o VS2017 com um usuário diferente daquele colocado na instalação? Porque estou tentando entrar com um novo usuário que me foi dado na empresa. Esse novo usuário é o meu usuário no AD e com ele eu acesso o TFS já que com o usuário atual(usuário MicroSoft usado na instalação do TFS). O note que trampo é o meu particular e não o dá empresa, por isso dois usuário diferentes.
Answer: Você está utilizando o Visual Studio Pro? Se sim, não existe a necessidade de conectar com a sua conta da Microsoft no Visual Studio, ele permite que você utilize todas as funcionalidades do VS sem a necessidade de autenticação.
Porem caso você necessite realizar a autenticação para utilizar diversas contas da Microsoft, você pode seguir o passo a passo estipulado no site da Microsoft :
https://msdn.microsoft.com/pt-BR/library/dn872465.aspx
Caso você esteja utilizando o Visual Studio Community é necessário a autenticação e você pode utilizar apenas 1 conta de usuário por licença.
Comment: Anderson, consegui. Me desloguei do VS2017 Enterprise. O problema estava exatamente aí. Não me loguei com outro usuário ainda, mas não sei se posso. A questão de logar com outro usuário era poder me conectar ao TFS, já que com o usuário que estava logado estava sem permissão. Mas ao deslogar consegui me conectar ao TFS e por isso nem tentei me logar com outro usuário.


How to get Nokia S30+'s MRE vxp file to run on nokia 225?

Question: The setup
Ok let's me talk a bit about the setup:
I have installed Visual Studio 2008 (the edition that let you try for 90 days), MRE SDK 3.0 from this Github issue, Sourcery Codebench Lite for ARM EABI and also ARM Realview Development suite 3.1 (but it requires license, and I am too lazy to cr@ck it, also I prefer the open source GCC to that commercial software). I set the compiler to Sourcery Codebench's GCC.
I can compile and run vxp file on Mediatek's emulator without any problem.
The problem
After compile for ARM platform, here's the output in [project_dir]\arm:

I tried copying the Default.vxp to my Nokia 255's SD card, then open that file on my phone, but the phone said Can't open this app at the moment.
I also try creating an appmanager folder on my SD card, then my phone's internal storage, then copy the vxp file there, but in the app list, there is still no app other than stock apps, and the vxp file still not run.
Other vxp files
I downloaded some vxp files from http://shifat100.xtgem.com/, put to my SD card and run from it. Some will work, for example the Asphalt 6 Game, but some won't, for example the Gold rush game, they yelt Can't open this app at the moment.
I checked the format of the Asphalt 6 game 's vxp with the file command, and it said data. But I check my Default.vxp, it was ELF. I think this is the problem, but don't know how to convert/pack ELF to vxp.
Using binwalk with the Asphalt 6 game 's vxp, I get 2 zlib compressed files and 2 GIFs, which are icons of the game. The two compressed files, after unpack, one contain many names, for example
splash_320x240.bsprite
splash_menu_320x240_200k.bsprite
splash_menu_split_320x240_200k.bsprite
splash_title.bsprite
hollywood_320x240_200k.bsprite
new.png
font_small.bsprite
font_large.bsprite
interface_font.bsprite
copter.bsprite
car_tourist.bsprite
cars_fx.bsprite
cars_shadow.bsprite

so I think this is the resource file. The other might contain code, I found some exception strings in it, for example
Unknown signal
Invalid Operation
Divide By Zero
Overflow
Underflow
Inexact Result
: Heap memory corrupted
Abnormal termination
Arithmetic exception:
Illegal instruction
Interrupt received
Illegal address
Termination request
Stack overflow
Redirect: can't open:
Out of heap memory
User-defined signal 1
User-defined signal 2
Pure virtual fn called
C++ library exception

and some (maybe) S30+ platform APIs, for example
vm_get_mre_modules
vm_get_mre_total_mem_size
vm_get_mre_version

So what might be the problem? Screen resolution? I changed it but still not work. SDK version? I also tried all 3 version, but no luck. File format? Compiler difference? (Note that I'm using GCC while most tutorial left on the internet suggest using RVCS) I don't know.
Any ideas? Thanks!
If you need to get any files, tell me and I will put it here.
Comment: No solution here but just to tell  you i am also interested in running app in s30+ series.
Comment: It *seems* that the phone will only run the apps in the list of installed apps & downloadable apps in the store. It will not run the others.
Comment: No, I can confirm that Nokia 225 can run ELF. Opera mini's vxp file in ELF format is an example.
Comment: I can confirm that IT WORKED!! The answer will be posted here tomorrow!
Answer: Delivered from my answer at RE.SE

First I want to say thanks to people at 4pda forum. See their thread here.

Can you figure out informations about the MRE VXP format

Well I haven't found yet, need further research

how to get it signed

Short answer:
Step 1: Get your SIM 1's IMSI number (NOT IMEI, they are DIFFERENT!)
You can do this in multiple ways, but the easiest way is to plug the SIM 1 in to an Android phone and read. I personally use ADB to read IMSI (worked on Android 6+ without root):
adb shell service call iphonesubinfo 7

Step 2: Go to https://vxpatch.luxferre.top/ and input the IMSI number you got in step 1. Then select your VXP file, click 'Patch' and you should be able to download a patched version.
or
You can enter the IMSI number in the project setting, but REMEMBER TO ADD 9 BEFORE THE IMSI NUMBER

Step 3: Move the patched version into a SD card and plug it in your phone
Step 4: Find the vxp file and click open, your app should run now!
Long answer:
Some apps doesn't require specify the IMSI, they just work on any devices. That's because they use another way of signing, using RSA key.
If you are interested, read here. The text is in Russian, so use Google Translate if you want to.
I have tested with ADS 1.2 compiler (I cracked myself, if you want it then tell me) and GCC (Smaller size + work very well) and Nokia 225, will continue to test further!
The apps in S30+ platform are written in C (and optionally C++), so you can port many apps to S30+
Again, a great thanks to people at 4pda forum!
An image of the app running after signing:


Mean value theorem with integrals?

Question: Here is the question:

Let $f:[0, 1]\rightarrow \mathbb{R}$ be a continuous function satisfying
  $$\int_0^1 (1-x)f(x) \,dx = 0$$
  Show that there exists $c\in (0, 1)$ such that
  $$\int_0^c xf(x)\,dx = cf(c)$$

I'm pretty sure that the problem wants me to use the mean value theorem of some type. So I tried to consider a function $F(t)$ that would give the form
$$F'(t) = \int_0^t xf(x)\,dx -tf(t)$$
so that I would be able to say $F'(c) = 0$ for some $c\in (0, 1)$, using Rolle's theorem. But this gave me
$$F(t) = \int_0^t ((t-1)x-x^2)f(x)\,dx$$
which didn't really help me proceed any further.
I have also tried setting
$$F(t) = \int_0^t (t-x)f(x)\,dx$$
in hopes of using Rolle's theorem, since $F(0)=F(1)=0$. But $F'(t)$ wasn't really the required form. I've also tried other different forms so that I could apply mean value theorem for integrals, or Cauchy's mean value theorem. But I couldn't derive the correct form to solve the problem.
Maybe I have missed something? Or can someone provide me a different approach to this problem? Thanks in advance.
Answer: Define $F, G : [0,1] \to \mathbb{R}$ as $F(x) = \displaystyle\int_{0}^{x}f(t)dt$ and $G(x) = \displaystyle \int_{0}^{x}tf(t)dt.$ Integrating the second integral by parts, allows us to write:
$G(x) = xF(x) - \displaystyle \int_{0}^{x}F(t)dt.$
Note that $G(0) =0.$ Our aim is to find another zero of $G$, say $b$, and then apply Rolle's theorem to the function $e^{-x}G(x)$ on the interval $[0, b].$
Claim: There exists $b \in (0,1)$ such that $G(b) =0.$
Proof of claim: Suppose not. Then since $G$ is continuous, it cannot change sign on $(0,1]$ so WLOG, assume $G(x) >0 \quad \forall \, x >0.$
Since $F$ is continuous on a closed and bounded interval $[0, 1]$, it attains its bounds. Let $d \in [0,1]$ be a point of minimisation of $F.$ Two cases arise:
1) $d=0$
Then $\forall \, t \in [0,1] \quad F(t) \geq F(0) =0.$ By the mean value theorem for integrals, $\, \exists \, 0< x_{0} < 1$ such that $\displaystyle \int_{0}^{1}F(t)dt = F(x_{0}).$ The given condition can be stated as $\displaystyle \int_{0}^{1}F(t)dt =0$, hence $F(x_{0}) =0.$
By assumption, $G(x_{0})>0$ which implies $\displaystyle \int_{0}^{x_{0}}F(t)dt< 0$ which by the mean value theorem again implies that $x_{0}F(x_{1})< 0$ for some $x_{1} \in (0, x_{0})$ and thus $F(x_{1}) <0, $ a contradiction. Thus $d=0$ is an impossibility and hence $d>0$ which brings us to case 2.
2) $d>0$
For all $t \in [0,1]$ we have $F(t) \geq F(d).$ Integrating over $[0,x]$ we get $\displaystyle \int_{0}^{x}F(t)dt \geq xF(d)$ and rearranging this yields $G(x) \leq x(F(x) - F(d))$ from which we get that $G(d) \leq 0$ for $d>0,$ a contradiction. Hence the claim holds $\blacksquare$.
With the claim in hand, we apply Rolle's theorem to the function $h(x) = e^{-x}G(x)$ on the interval $[0, b]$ to get $c \in (0, b)$ such that $h'(c) =0$ which implies $e^{-c}(G'(c) - G(c))=0$ from which it follows that $\displaystyle \int_{0}^{c}tf(t)dt = cf(c).$
Comment: Thank you very much, for spending your time on this question. I really appreciate it, and I am happy to see it solved. Thanks again!
Comment: No problem! It was an interesting variant of this question: https://math.stackexchange.com/q/3627804/360587 which also linked to. yours in the comments
Answer: The very first integral can be splited in two. Value of one integral is f(c), according to L. M. V. T.  and of other is c. f(c). Comparing c. f(c) =f(c), we get c=1 or f(c) =0.But c cannot be 1. So f(c) =0.
Comment: I don't understand the part where you used LMVT... Can you please elaborate?
Comment: First split very first integral, then apply L. M. V. T.  on the two splited integrals.
Answer: In fact, the conclusion is true for any continuous function $f$ that changes its sign in $[0,1]$.
Let $G(y)=\int_0^{y}xf(x)dx$, and assume that there is no point $y$ such that $G'(y)=G(y).$
I claim that there can't exist a point $b>0$ where $G'(b)<G(b)$ and $G(b)>0$. Indeed, let $b$ be such a point, and let $a:=\inf\{0<x<b:G>0 \text{ on } (x;b) \}$. Then, on $(a,b)$, we have $(\log G(x))'= G'(x)/G(x)<1$, hence $\log G(x)> (x-b)+\log G(b)$ and thus $G(x)> G(b)e^{x-b}\geq G(b)e^{-b}$. On the other hand, $G(a)=0$, regardless of whether $a=0$ or $a>0$, which is a contradiction. Similarly, there can't exist a point $b>0$ with $G(b)<0$ and $G'(b)>G(b)$.
Hence, if $a$ is some point where $G(a)>0$, then we necessarily have $G'(y)>G(y)>0$ in some interval $(a,b)$. If take $b$ to be the supremum of all possibilities, then we still have $G(b)>G(a)>0$, and hence we can only have $b=1$. Similarly, if $a$ is such that $G(a)<0$, then in fact $G'(y)<G(y)<0$ for all $y\in [a;1]$. But these scenarios are mutually exclusive. On the other hand, $\inf\{x:G(x)\neq 0\}=0$, for otherwise $G'\equiv G\equiv 0$ in some neighborhood of $0$.
Therefore, either $xf(x)=G'(x)>G(x)>0$ for all $x\in (0,1]$, or $xf(x)=G'(x)<G(x)<0$ for all $x\in (0,1]$. In each case, $f$ has a constant sign.
Answer: You can use Taylor Lagrange equality between expansion :
I set $$ F(t)\triangleq \int_{0}^t(1-x)f(x)dx$$
So as $F(t)$ is differentiable , by Lagrange there exists $c \in ]0;1[$
So that $$ F(1)=F(0)+F'(c)$$
Which respectively gives :
$$ cf(c)=f(c) $$ so $f(c)=0$ or $c=1$. Yet $c$ isn't equal to $1$ according to the theorem,
So know, you have to proove
$$  \int_0^cxf(x)dx=0$$
Comment: I don't think this is the $c\in (0, 1)$ that the problem wants me to find. I tried letting $f(x) = 1/3 - x$. This satisfies the original condition, and using your argument, $f(c) = 0$ gives $c = 1/3$. But sadly, $\int_0^{1/3} xf(x)dx =1/162$, which is not equal to $0$.
Comment: Is the original condtions on $f$ thoses you gave here ? Because the demonstration shows us that the result wanted isn't the right one.
Comment: Yes the original condition is that $f$ is continuous and $\int_0^1 (1-x)f(x)dx = 0$. That's all I have, unfortunately.

Mean value theorem with integrals?


Update dinâmico em componente Primefaces através do autocomplete

Question: Uma dúvida simples, existe alguma maneira fácil de utilizar o componente autocomplete do primefaces, e assim que ao selecionar alguma opção fazer com que um componente (por exemplo um dataScroller) seja atualizado???
Tentei algo através de um f:ajax adicionando um listener para o evento itemSelect como mostrado no showcase, mas não consigo prosseguir para fazer com que o outro componente seja atualizado dinamicamente, alguma luz?
Answer: Já usei o autocomplete, para atualizar outro componente usei:

Comment: Valeu pela resposta, era só isso mesmo, eu estava tendo problemas pois estava adicionando um listener ao evento ajax tentando criar alguma lógica com o itemSelect, sendo que nem é preciso.


How to loop in sql?

Question: I dont want to use the "loop" related keyword, how can I implement loop with basic sql command in oracle ?
I have two table :
A:
ID, Color
B,
ID, AID, Type

I want to loop all records in B, and if ID = AID, then set the A.Color = B.Type
Thanks in advance !
Comment: Edited `sql` tag to `plsql`, given that this is for Oracle.
Answer: Looping is, by definition, a procedural construct.
SQL is declarative: tell the database what you want done, not how to do it.
If you're absolutely convinced that you need to program such a thing, then write it in PL/SQL, Oracle's procedural language.
Bu I'm sure that it's possible to do what you want in SQL using an UPDATE with a WHERE clause.
Something like this (corrected per NullUserException):
UPDATE A SET A.Color = (SELECT B.Type FROM B WHERE A.ID = B.AID)

Comment: The SQL query has illegal syntax
Comment: You're correct - yours is better.  I voted yours up.  I think mine might be for a particular SQL flavor.  I got it from this reference - http://geekswithblogs.net/faizanahmad/archive/2009/01/05/join-in-sql-update--statement.aspx
Comment: @Joe If you try to run the original query, Oracle will give you `ORA-00933: SQL command not properly ended`
Comment: @Null: interesting, thanks.  The original SQL looked valid for, say, TSQL/SQLServer, and I haven't used Oracle in a while.
Comment: Didn't know if the original was ANSI SQL.  NUE's is better.
Answer: You could just do:
UPDATE tablea a
   SET a.color = (SELECT b.type
                    FROM tableb b
                   WHERE b.aid = a.id)

See this SQL script.
Answer: An alternate method:
MERGE INTO a
USING b
ON (b.aid = a.id)
WHEN MATCHED THEN UPDATE SET a.color = b.type;

Answer: To do that you will have to write a stored procedure using PL/SQL. Here is the oracle page with some info and papers on the topic.
Answer: As others pointed out, you can probably solve your problem with a normal DML statement, without any looping involved.  But to give you some basics on how to accomplish what you asked for in PL/SQL, here's an example...
DECLARE
    CURSOR c IS
        SELECT id, aid, type FROM b;
    statement VARCHAR2(200);
BEGIN
    FOR iterator IN c LOOP
        IF iterator.id = iterator.aid THEN
            statement := 'UPDATE a SET color = ' || iterator.type || 'WHERE id = ' || iterator.id;
            EXECUTE IMMEDIATE statement;
        END IF;
    END LOOP;
END;

This anonymous PL/SQL block will iterate through each record in table b, and if b.id = b.aid, it will update table a and set a.color = b.type where a.id = b.id.
This seems to be what you were asking for.  It's not exactly an efficient way to go about doing things, since you're firing off one DML statement per row in table b that has b.id=b.aid.  But I wanted more to give this as a syntax example.  This is just one way to iterate through a cursor by the way; you can also explicitly open cursors and fetch records, but it's easier this way if you don't need to do anything but iterate over the entire result set.

How to loop in sql?


PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column

Question: I am tring to perform the following sql query to check if the name that was inserted to the form already created as taxonomy name. But I keep getting this error message:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'test' in 'where clause': SELECT COUNT(*) FROM {taxonomy_term_data} WHERE name = test; Array ( ) in get_google_map_api() (line 79 of /Applications/MAMP/htdocs/Drupal/sites/all/modules/toodate/toodate.module).

my function is:
function get_google_map_api($item){
    $city_name = $item;
    $chack_if_is_taxonomy = (db_query("SELECT COUNT(*) FROM {taxonomy_term_data} WHERE name = ".$city_name));
    var_dump($chack_if_is_taxonomy);
    drupal_exit();
}

Comment: you error does not seem to match the code..? test column is not there in the where clause which u might have entered earlier.
Comment: You are right, I've edited my text
Comment: is the error still occuring ? Pls update the error which correlates to the code.
Comment: Yes the error is still occurring. I did update the error
Comment: What is test ? is it a column or a variable ?
Comment: test is the variable that pass through $item
Answer: Quick fix would be adding the missing single quotes around your variable. Forgetting the quotes can throw odd errors from this function, such as mixing a string for a column, like in your case.
There are less error prone ways to make short queries like this. See also Molot's answer.
Comment: Thanks, But it didn't show what I wanted to get... I'll post another question about it.
Answer: Don't use db_query() unless you really have to. Build your queries with db_select(). It's harder to make SQL errors using it. Your query would look like this:
// SELECT COUNT(*) FROM {taxonomy_term_data} WHERE name = $city_name
$chack_if_is_taxonomy = db_query('taxonomy_term_data', 'ttd');
$chack_if_is_taxonomy->addField('ttd', 'COUNT(*)', 'count');
$chack_if_is_taxonomy->condition('name', $city_name, '=');

As you can see, no place to make SQL errors, and PHP bugs should be easier to spot in your favourite IDE.


Ninite with a logoff group policy script

Question: I'm trying to use a batch script to automate the updates of some apps using ninite with a group policy log off script.
Here is my script:
<code>echo Copying ninite
mkdir C:\temp
mkdir C:\temp\ninite
echo STARTING

robocopy /xo /"\filesever01\shared data\IT\SoftwareUpdate\/" \temp\ninite\ NiniteOne.exe

echo installing Chrome and Skype...
c:\temp\ninite\NiniteOne.exe /select Chrome Skype /cachepath "\\fileserver01\shared data\IT\SoftwareUpdate\NiniteCache"

echo Installing Java and Reader without autoupdates...
c:\temp\ninite\NiniteOne.exe /select Java Reader /disableautoupdate /cachepath "\\fileserver01\shared data\IT\SoftwareUpdate\NiniteCache" /silent report.txt
</code>
When the script runs at logoff it fails. I ran it at log on and noticed that it fails because ninite asks for administrator permission and I am assuming that it's failing at logoff for the same reason.
Does anyone have any recommendations on what I should do? Is ninite the right tool for what I am trying to do? Is a batch script the right path or should I try using powershell?
Answer: Logoff scripts run as the user. In any sensible Windows environment users should not have Administrator rights and won't able able to install software.
You'd be better off installing software in a Startup or Shutdown script, which run as the computer (SYSTEM).
I have no familiar with Ninite so I can't say if it will work in a Startup or Shutdown script, but I can say that any issues with needing elevated privileges won't be an issue.
Comment: Thanks Evan! That worked. I run a logoff script to copy ninite over and then a shutdown script to install. I tried to do it all in one script but the network connection was timing out during shutdown.


Replace is not a function

Question: Criei um script pra inserir uma div no carrinho da minha loja, mas a está dando erro na função replace. Alguém saberia o por que ?
var $JQuery = jQuery.noConflict();
$JQuery(function(){
var ValorFreteGratis = 299;
var PrecoTotal = '{{order_total}}';
var QuantoFalta = ValorFreteGratis - PrecoTotal;
var NumeroComVirgula = QuantoFalta.replace(".", ",");
if(PrecoTotal < ValorFreteGratis){
$JQuery('

EI!!: Comprando mais R$' + NumeroComVirgula.toFixed(2) + ' você aproveita o FRETE GRÁTIS nas compras acima de R$' + ValorFreteGratis + '

').insertAfter('form#cart_update_post');}});

Fica dando o erro: "Uncaught TypeError: QuantoFalta.replace is not a function"
Comment: Se QuantoFalta não for `string` tu pode fazer isso: `String(QuantoFalta).replace...`
Comment: Provavelmente `QuantoFalta` não é uma string, talvez `undefined` ou `NaN`. Vefifique assim: `console.log(typeof QuantoFalta)` antes da linha que aplica o `replace`.
Comment: QuantoFalta é `number` pela conta, é necessário converter para `string`
Answer: A função replace é uma função do tipo String. A variável QuantoFalta é produto de uma operação matemática, logo não é uma String. Utilize toString para transformá-la:
 ...
 ... QuantoFalta.toString().replace(...
 ...

String.prototype.replace()
O método replace() retorna uma nova string com algum ou todas as combinações do padrão substituído por um substituto.
Answer: Seu problema é com tipagem (é possível perceber pelo TypeError), como você está fazendo uma subtração, todo o resultado se torna do tipo number, logo, a função replace não existe.

var x = 10 - 5; // deve dar 5
console.log(x) // 5
console.log(typeof x) // number
x.replace(5, 10) // Uncaught TypeError

O que pode ser feito é alterar o tipo da variável, utilizando String(valor):

    var x = 10 - 5; // deve dar 5
    console.log(x) // 5

    x = String(x).replace('5', 'agora foi') // note o uso do String(x)
    console.log(x) // "agora foi"

    // O string pode ser feito na conta também
    // Ex:
    var y = String(10 - 5)
    console.log(y)

Geralmente esses erros causam confusão por o Javascript não ser uma linguagem bem tipada, não é necessário explicitar isso durante o uso.
E outra coisa que também pode gerar problemas é, você pode substrair/multiplicar/dividir strings e elas se tornarão number, mas não pode somá-las, já que é o mesmo caractere utilizado para concatenar, isso
outra coisa que pode criar esse tipo de confusão.

console.log(typeof ('10' - '5')) // number (5)
console.log(typeof (10 + 5)) // number (15)
console.log(typeof ('10' + 5)) // string ('105')
console.log(typeof (10 + '5')) // string ('105')
console.log(typeof ('10' + '5')) // string ('105')
Answer: o replace só pode ser dado com String. Altere para:
var numeroComVirgula = String(QuantoFalta).replace('.',',')

Replace is not a function


What is the difference between a "voice" and a "register" on an accordion?

Question: What is the difference between a "voice" and a "register" on an accordion?
For example the Hohner Bravo III says it has 4 "Standard bass voices" and 3 "Standard bass registers"
Answer: Voice refers to how many different sets of reeds the accordion contains. Each set of reeds produces a different timbre, similar to the way sets of pipes produce different timbres in a pipe organ. So "Four standard bass voices" means there are four different bass timbres available.
Register is combinations of reeds that are producing tones at the same time. Again analogous to a pipe organ in which combinations of different pipes are opened to produce a particular sound, accordions will have preset combinations of reeds that are selected by the push of a button. Thus, "Three standard bass registers" means that there are three different combinations of the bass voices available.
See, for example, http://www.accordionlounge.com/accordiontypes.html.
Answer: A "voice" is a reed set.  When engaging the "master" registration, every reed set is active, and the number of reed sets will indicate how many reeds sound for every key or bass button pressed.  An accordion with LMMH tuning has 4 reed sets or voices: "low" (sometimes written as 16" in analogy to organ pipes), two "M" voices ("medium" or 8", usually the main reed set that is on-pitch and the tremolo reed set that is tuned more or less sharp in order to create a beating sound quality) and an "H" voice ("high" or "piccolo" or 4") that will make the sound more piercing in connection with other reed sets.
When there are 3 M reed sets, they are usually in "musette tunning" with one reed set tuned straight, one somewhat flat, and one quite sharp.  That generates the piercing sound quality known from Parisian Musette music.  Less conspicuous 3-reed tunings are also available, like the still comparatively prominent "Oberkrainer" tuning.
The registers are combinations of reed sets that can be engaged at one time, usually with a combination register switch.  On an LMMH accordion, 11 registers are customary.  From the possible 2⁴=16 combinations, the silent registration is omitted, and all combinations using the tremolo reed set but not the main reed set.
For a standard Stradella bass, bass voices are split into actual bass reed sets (typically two that are an octave apart) with a size of 12 notes each, and chord reed sets also with a size of 12 notes each.  The mechanics assemble chords from 3 notes in each active chord reed set (with the chord inversion predetermined by the chord reed set), and play bass notes by sounding all active bass reed sets and usually all active chord reed sets (very few accordions, like the Hohner Gola, don't do this coupling of basses into the chord reeds, instead having an additional bass reed set).
Just where reed set start on the bass is a black art.  Typical large Hohner accordions have bass reed sets starting at E1 and E2, and chord reed sets on E3, E4, E5.  Italian models can have something like A1, A2 on bass and F♯3, C4, C5 on chord reeds.  Having 3 different octave wraparounds better masks the octave breaks in the various reed sets in the master registration and makes a bass note scale wrap around less conspicuously since there are, after all, only 12 different bass buttons to play.
Just which bass and chord reed sets (= voices) the available bass registers engage again is "voodoo" that everyone does differently.  Apart from a "Master" register, it is common to have one with the lowest bass and chord reeds switched off, and one with the highest one or two chord reeds off.  The more registers there are, the less common ground with other manufacturers or even models will be.
Comment: I think the pipe lengths are usually in feet (4', 8', 16') rather than inches (4", 8", 16")?


Residual diagnostics for negative binomial regression

Question: In the residual diagnostics for OLS, I understand what to look to assess any violations (e.g., normality and homoskedasticity of residuals). I was wondering what should one check for in residuals for a negative binomial regression fitted model. How could I do about getting these residual diagnostics in R?
Comment: The thing with GLMs is usually you employ one family with a theoretical foundation. You pretty much chose a distribution you expect the data to follow _a priori_. Unless you are dealing with very specific choices for the distribution, then I don't expect mild violations of the assumptions to degrade your modelling approach.
Answer: Check out the DHARMa package in R. It uses a simulation based approach with quantile residuals to generate the type of residuals you may be interested in. And it works with glm.nb from MASS.
The essential idea is explained here and goes in three steps:

Simulate plausible responses for each case. You can use the distribution of each regression coefficient (coefficient together with standard error) to generate several sets of coefficients. You can multiply each set of coefficients by the observed predictors for each case to obtain multiple simulated response values for each case.
from the multiple response values for each case, generate the empirical cumulative density function (cdf)
find the value of the empirical cdf that corresponds to the observed response for each case. This is your residual and it ranges from 0 to 1.

If there is no systematic misspecification in your model, all values from the empirical cdf are equally likely. And a histogram of these residuals should be uniformly distributed between 0 and 1.
The package contains additional checks.

Edit:
The steps above are not exactly correct. The biggest difference between my description and what DHARMa does is DHARMa uses the simulate() function in base R, which ignores the variability in the estimated regression coefficients. The Gelman and Hill regression text recommends taking the variability in regression coefficients into account.
A crucial step I forgot to include is: once one has generated the responses, we should place them on the response scale. For example, the predicted variables from logistic regression are logits, so one should place them on the probability scale. Next step would be to randomly generate observed scores using the predicted probabilities. Continuing with the logistic regression example, one can use rbinom() to generate 0-1 outcomes given predicted probabilities.
Additionally, when the responses are integers, such as with binary outcomes or count data models, DHARMa adds random noise to the simulated responses prior to computing the empirical cdf. This step ensures the residuals behave as one would expect in OLS if the model was not misspecified. Without it, you could have a pile up of residuals at 1 if your outcome is binary outcome.
The code for the simulate residuals function in DHARMa is relatively easy to follow for anyone looking to roll their own implementation.


itext 5 TextField using chinese font with bold and italic

Question: I'am trying to using TextField in itext 5.
My font name is "微軟正黑體" in English is "Microsoft JhengHei".
I want to using this font with bold and itatic.
Init Font ( 3 is Font.BOLD | Font.ITALIC and BC is my base color)
Font fontZh = FontFactory.getFont(CurrentFont.getFontName(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED,
                    CurrentFont.getFontSize(), 3, BC);

I have a textField variable and set fontZh to setFont.
field.setFont(fontZh.getBaseFont());

The pdf result only the font style, size and color is correct. But the bold and itatic isn't work.
Answer: You can only set a BaseFont to a field. This in particular means that those properties from your FontFactory.getFont call which merely become part of the returned Font and not of the underlying BaseFont, are not in the base font you retrieve using fontZh.getBaseFont() and, therefore, are not set to the field.
Among the properties that get lost this way are in particular style information like italic or bold (unless the referenced font file already is italic or bold or the referenced font family is registered with a bold or italic font file) and the color.
(You say that in your test the color is correct; if it is, that is not because of it being transported via the font. As you don't show enough code for a good analysis, I can only guess; I would surmise that the color either is the default to start with or you set it using some other instruction.)
Thus, if you want to have a bold or italic font used in a text field, you should use a base font that references a font file which already draws characters in the desired combination of bold and italic, e.g. in case of Century Gothic use GOTHICBI.TTF instead of GOTHIC.TTF. I don't know whether you have such a variant of "微軟正黑體".
If you want to set the color of the font of a field, you can do so by setting it to the field, i.e.
field.setTextColor(BC);

before building the field dictionary using field.getTextField().
Comment: Thanks, I got it. I will search my font bold and italic. If I can't find my font bold and italic, is there a way to convert the normal ttf or ttc font file to bold or italic?
Comment: I don't know but I would assume that there is a tool for that. The results may not be perfect but should be acceptable.


EF Code First: One-to-One One-way Relationship

Question: I regularly have the following structure:
MyClass
public virtual ICollection<Version> Versions { get; set; }
public virtual Version CurrentVersion { get; set; }

That is, there is a list of stuff, and some class both points to that list, and one specific item in that list - either the current version of many versions, the next upcoming event in a list of events, etc.
In my schema what I'd like to end up with is a Foreign Key pointing from Version to MyClass - that much works out properly. But then I'd like a Foreign Key pointing from MyClass to Version representing the CurrentVersion property, with no Foreign Key pointing back - I don't want the extra storage or bother of telling a Version what MyClass it's the CurrentVersion for, if any. Put another way, I'd like this second relationship to be one-way from MyClass to Version, even though it's one-to-one.
What EF Code First gives me instead is the normal one-to-many on the first property, with the FK from Version to MyClass, but then a full one-to-one relationship on the second property with an FK pointing in both directions - so the underlying schema for Version ends up with MyClass_Id and MyClass_Id1.
So, is there a way to get a one-way relationship in EF Code First without resorting to the Fluent API? It looked like maybe System.ComponentModel.DataAnnotations.Schema.InverseProperty had a shot at it, but it didn't seem to offer a way to say "Don't generate one."
Answer: The key is to specify the InverseProperty on the property that points back, so that EF realizes it's to the Many-to-Many, not to the One-to-One.
public class MyClass
{
    public int Id { get; set; }

    public Version CurrentVersion { get; set; }

    public ICollection<Version> Versions { get; set; }
}

public class Version
{
    public int Id { get; set; }

    [InverseProperty("Versions")]
    public Versioned Versioned { get; set; }
}

Comment: would you please tell me how can I do it with fluent api?
Comment: @ahmadalishafiee Probably best as its own question


Como colocar o valor de uma variável Php dentro do Input no html5

Question: Boa tarde preciso fazer que o valor da variável $x seja exibida dentro do input item. abaixo segue o código.
desde já agradeço.

<!DOCTYPE html>

 <title>Teste</title>

<form>

 <fieldset style="width: 650px">
  <legend>Cotação</legend>

Item

Descrição

QTD

Valor Unit

Valor Total

   <?php
   $x = 0;
    while ($x < 7)
    {
      $x ++;

      echo '

         <input style="width: 25px" type="text" name="item" value="<?php echo $x ?>">

         <input style="width: 300px" type="text" name="nome">

         <input style="width: 60px" type="number" name="quantidade">

         <input style="width: 120px" type="number" name="valorUnit">

         <input style="width: 120px" type="number" name="Valor">

 ';
    };

   ?>

  <fieldset style="width: 638px">

   <input type="submit" name="Enviar" <?php echo "
  Respondidos $x </5>" ?>

 </fieldset>

 </fieldset>
</form>

Answer: Dentro do echo não funciona <?php ?>, você pode simplesmente concatenar com o operado . em
<input style="width: 25px" type="text" name="item" value="'.$x.'">

O código completo ficaria:
<!DOCTYPE html>

    <title>Teste</title>

<form>

    <fieldset style="width: 650px">
        <legend>Cotação</legend>

Item

Descrição

QTD

Valor Unit

Valor Total

            <?php
            $x = 0;
                while ($x < 7)
                {
                        $x ++;

                        echo '

                                    <input style="width: 25px" type="text" name="item" value="'.$x.'">

                                    <input style="width: 300px" type="text" name="nome">

                                    <input style="width: 60px" type="number" name="quantidade">

                                    <input style="width: 120px" type="number" name="valorUnit">

                                    <input style="width: 120px" type="number" name="Valor">

 ';
                };

            ?>

        <fieldset style="width: 638px">

            <input type="submit" name="Enviar" <?php echo "
  Respondidos $x </5>" ?>

    </fieldset>

    </fieldset>
</form>


Is it normal for a string to buzz unless my finger that is fretting is almost against the fret?

Question: I just got a stratocaster. I've never played the guitar before this week. When I try to play the D major chord, I get buzzing on the first and third strings.
When my first finger on the third string isn't pressed almost against the fret, it makes a buzzing noise, but it's extremely uncomfortable to have both my first and second finger that close to the fret. I want to move my first finger away a little, but it makes a buzzing noise if I do.
I'm trying to learn from JustinGuitar, but when I see his picture for fretting, his fingers aren't that close to the fret.
Comment: You probably need to put more pressure on.  Look for diagrams/lessons online about good left hand position, as it may be that the way you're positioning your left hand right now isn't the best way to effectively transmit force to the strings.
Comment: If you're still in your first month of guitar, then you should expect a lot of buzz. Your fingers have a lot to learn in terms of muscle memory and placement, etc. If you can't get rid of buzz no matter how you place your fingers (and you might try working on each note one at a time), then you could take your guitar in for a "setup". If it's new, you might take it back where you bought it and say the setup it had when you bought it isn't very good and would they mind doing a free or discounted setup for you.
Comment: don't forget to trim the fingernails on your fretting hand: even a little growth can cause buzzing from incomplete contact, depending on finger angle.
Answer: The closer a finger is to a fretwire, the easier it gets to eliminate buzz, as there's no need to press as hard. Just try that on one string on the lower frets. Move your finger towards the nut, and you'll realise that you need to press harder to produce a clear sound.
However - with that particular D chord, there are twelve different ways your fingers can go. There will be two or three which suit you better, probably, than the version you are playing now. Bear in mind, as a beginner, that lots of chord shapes can and are played in different ways. I'm talking about the exact same strings and frets, not other chord shapes. Experiment !
Answer: My first recommendation would be to have the action on the guitar checked. a properly adjusted action will assure that frets are leveled and the neck isn't out of adjustment. The nut and bridge will be adjusted so that the strings are most easily played. Very few new guitars have had the action set for optimal playing ease. If there is still a problem when you fret a note or chords, then
the problem may be the placement of your fingers in relation to the frets.
Answer: Buzzing usually comes from low pressure or if your fingers are not close enough to a fret.
A good rule of thumb is to try to get your fingers as close to the frets as possible when playing, This becomes pretty difficult later one when you have more complicated chords with complex fingerings.
When I learn new chords I check to make sure that all my fingers are pressed down and close to the frets and play it multiple times with all the strings sounding as clear as I can get them. It may seem challenging at first, but with practice, it will eventually be second nature.


Weakly closed and stable for convex combinations with rational coefficients implies strongly closed

Question: It is a standard result that for a convex subset of a Banach space weak-closure and strong-closure coincide.
Is this result still true for a subset which is convex only for combinations with rational coefficients?
Answer: Let the set $M\subset X$, where $X$ is a Banach space.
1) Let first have that $M$ is convex for rational coefficients and that $M$ is norm-closed. This means that for each $\lambda\in\mathbb Q:\quad \lambda x_1+(1-\lambda) x_2\in M$ for $x_1,x_2\in M$. Let $r\in\mathbb R$ and $\{\lambda_n\}\subset\mathbb Q: \lambda_n\rightarrow r\in \mathbb R$. For each $n$: $\lambda_n x_1+(1-\lambda_n)x_2 \in M$ and after letting $n\rightarrow \infty$ we see $\lambda_n x_1+(1-\lambda_n)x_2\rightarrow rx_1+(1-r)x_2\in M$ because $M$ is norm-closed. Therefore $M$ is convex also with real coefficients.
2) If we have that $M$ is convex with rational coefficients and also $M$ is weakly closed, then it is also norm-closed. Therefore applying the above argument we see that again $M$ is convex for real coefficients.


Postfix lost connection with "server/host" while receiving the initial server greeting

Question: I have postfix on CentOS6.6 on my local server(192.168.1.103), from which I'm unable to send emails to any domains.
The following is the error obtained when sent to our company email.:

Jun  2 11:09:55 server postfix/error[23443]: 3392D5418AC: to=, relay=none, delay=73765, delays=73765/0.03/0/0.09, dsn=4.4.2, status=deferred (delivery temporarily suspended: lost connection with yyy.com[192.254.abc.def] while receiving the initial server greeting)

This is the error when sent to a gmail address:

Jun  2 11:11:26 server postfix/smtp[23507]: connect to gmail-smtp-in.l.google.com[2404:6800:4003:c00::1a]:25: Network is unreachable
Jun  2 11:11:38 server postfix/smtp[23507]: 519B054193B: to=, relay=gmail-smtp-in.l.google.com[18.104.22.168]:25, delay=13, delays=0.11/0/3.4/9.8, dsn=5.7.1, status=bounced (host gmail-smtp-in.l.google.com[18.104.22.168] said: 550-5.7.1 [18.104.22.168] The IP you're using to send mail is not authorized to 550-5.7.1 send email directly to our servers. Please use the SMTP relay at your 550-5.7.1 service provider instead.

This is the command I use to send email from my server:
<code>echo "Test mail from postfix" | mail -s "Test Postfix" firstname.lastname@example.com
</code>
Any suggestions?
Answer: This is happening because your IP is listed on a few popular black lists.  You can check that on mxtoolbox.com.
Also note that your MTA's IP does not have neither a forward (A) or reverse (PTR) DNS records which is a good reason for them to get rejected by other MTAs in the first place.
In this world of spammers, MTAs need to be extremely careful on what other MTAs they deal with.
Managing an MTA is not a simple task and you should therefore leave it to the professionals and use your hosting provider's service.


Block loading behaviour in Drupal 8 in a performance sense through the visibility settings

Question: The following scenario:
- i have for example a standard block region through a pages of a site: "highlights"
- for the frontpage i have an additional region: "highlights_frontpage"
- i put a block into "highlights_frontpage"
- i have to put into the visibility textarea: ""
If i remember correctly for D7, otherwise the block is loaded everywhere even though he is only shown on the frontpage.
Has Drupal 8 the same behaviour in loading blocks?
My page has for each main menu page an own region, but it would be a little bit ugly for the editor if he has to place the block via the administration in one region and also has to set the visibility ...
thanks
Comment: Interesting question. Can you test it yourself? A dpm() call in the block cobtent builder should inform you whether the function was run or not. Make sure you disable block cache.
Answer: The block is loaded (otherwise we could not check if he should be shown or not), but we do not call build() unless the block is visible and the user has access.
I'm pretty sure that was already the case in Drupal 7, it is only Drupal 6 AFAIK where it was building the blocks and then checking visiblity.


Need more fields than 'className' '_objCount' and 'id' when making a find() query against Parse.com

Question: When making a find() request against Parse.com, each of the results I get back only contain the following fields: 'className' '_objCount' and 'id'.
How to get all fields ? (I have more than 3 columns in the database browser)
How to get specific fields ?
UPDATE 1
1) Screenshot of the headers of my class, named "Code"
2) Query:
var Code = Parse.Object.extend('Code');
var query = new Parse.Query(Code);
query.equalTo('codeSet', codeSet);
query.find()
.then(function(codes) {
  console.log(codes);
}

3) Results:
[ { className: 'Code', _objCount: 1, id: '6cMkEQxE6A' },
{ className: 'Code', _objCount: 2, id: 'uOU7osLvOo' },
{ className: 'Code', _objCount: 3, id: 'Vks4QEpBlh' },
{ className: 'Code', _objCount: 4, id: 'dWtukZhsHZ' } ]

UPDATE 2
The code is hosted in a heroku-hosted node.js instance
Comment: You're seeing an abbreviated version of your objects. Use `codes.forEach(code => console.log(code.toJSON()))` to get the complete object.
Comment: The default is all of them.  The only way not to get all of them that I know of is to include a subset in a select qualifier on the query.  To get better help, post the code and a snapshot of the header row in the databrower
Comment: @danh I've updated the post with code and snaphsot or the header row in the databrowser
Comment: The header row indicates string fields "key" and "alias", but the code shown tries to qualify on "codeSet".  The results shown have different fields altogether and do not resemble results from any parse query of any class.
Comment: @adolfosrs It's js cloud code, hosted in a node.js instance at heroku
Comment: @danh I updated the screenshot so the last column appears - "codeSet".
Comment: Still, the results are nonsensical.  Not even parse objects.  Lets see the result of the console log in the then block.
Comment: @danh the array I've already copied in my question is actually what I get from console.log(codes))
Comment: I'm also seeing this with a relatively straightforward query. Can you post any updates you on this thread.... https://github.com/ParsePlatform/Parse-SDK-JS/issues/258#issuecomment-243287965
Comment: @MadsFoliBjerre you're right. Facing the same issue this solved it. Thxs
Answer: Use PFObject get method. like user.get('nickname');
https://parse.com/docs/js/api/classes/Parse.Object.html
Comment: Link is outdated (since parse docs moved to Github) but this still solved my problem. Current link to docs is [https://parseplatform.github.io/Parse-SDK-JS/api/classes/Parse.Object.html#methods_get](https://parseplatform.github.io/Parse-SDK-JS/api/classes/Parse.Object.html#methods_get); In OP case, he should do `codes[i].get('alias');` instead of `codes[i].alias;`, for instance.
Answer: Just incase anyone comes accross this problem, I'm going to post an answer as it took me several hours to find the solution, which is to use toJSON().
Example:
  var Parse = require('parse/node');
  var User = Parse.Object.extend("User");
  const query = new Parse.Query(User);

  await query.get("object-id-here")
  .then((user) => {
    // The object was retrieved successfully.
    console.log("The User Object", user.toJSON())

  }, (error) => {
    // The object was not retrieved successfully.
    console.log("Error:", error)

  });


Why my Iterator in singly linked list always returns same first value

Question: So i have to implement logic to some kind of game where we add units to armies and they can fight. Right now i created new game character named Dragon. Dragon has to do mass damage to every single unit in opposite army every 3 rounds. I can't resolve why my iterator always returns same element so instead of hitting every single unit i hit X times only the first one. There is my code
Hit method in Dragon class implementation:
  @Override
    public void hit(CanReceiveDamage opponent) {
        rounds++;
        if(opponent instanceof ArmyWarrior armyUnit && rounds==3){
                if(armyUnit.hasNext()) {
                    armyUnit.next().receiveDamage(() -> FIRE_BREATH_MASS_DAMAGE);
                }
        }
    }

Interface ArmyWarrior:
public interface ArmyWarrior {
    Warrior getWarriorBehind();
    Warrior next();
    boolean hasNext();

}

getWarriorBehind() method works perfectly fine with this implementation:
@Override
        public Warrior getWarriorBehind() {

            return next == head ? null : next.warrior;
        }

Army class and nested Node class:
public class Army implements Iterable<Warrior> {

 private class Node extends Warrior implements ArmyWarrior, IHealer {
        Warrior warrior;
        Node next;

        public Node(Warrior warrior) {
            this.warrior = warrior;
            this.next = this;
        }

 @Override
        public Warrior next() {
            if(!hasNext()){
                throw new NoSuchElementException();
            }
            return iterator().next();
        }

        @Override
        public boolean hasNext() {
            if(next!=head){
                return true;
            }
            return false;
        }

And my iterator:
public Iterator<Warrior> iterator() {
        return new SimpleIterator();
    }

private class SimpleIterator implements Iterator<Warrior> {

        Node cursor = head;

        @Override
        public boolean hasNext() {
            return cursor.next != head;
        }

        @Override
        public Warrior next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }

            return cursor.next;
        }

    }

No matter how hard i try and how many different approaches i tried, nothing seems to work as it should, need some help
Comment: Is this a homework assignment, or is there a reason you're not using one of the pre-built list types?
Answer: Here you create a new iterator each time the method is invoked:
    public Warrior next() {
        ...
        return iterator().next();
    }

You should either store this iterator somewhere and keep iterating using it. Or implement Linked List differently, e.g. by storing next Warrior right in the current one.
Comment: I tried to extract is somewhere else but i think im doing it wrong. Is there any chance you could show me where could i extract it to work as intended?
Comment: @Fellou98 Note that an iterator (which is basically a bookmark) has separate state (position) independent of the list (the book), and you could have several iterators active on one list at the same time. If your iterator doesn't have some `index` or similar variable, it can't do its job.


Algebra of Random Variables?

Question: I've been looking online (and in teaching journals) for a good introduction to Algebras of Random Variables (on an undergraduate level) and their usage, and have come up short. I know I can find the probability distribution of $h(z)$ where:
\begin{equation*}
z = x + y.
\end{equation*}
If $x$ and $y$ are from known independent probability distributions (the solution is simply a convolution). Two other operations $z=xy$ and $z=y/x$ can be solved for quite easily as well.
Does anyone know of any other, more complicated, uses for treating random variables as objects to be manipulated?
Answer: In the special case that the sample space is the non-negative integers (or a subset thereof), one can think of a probability distribution as a generating function $f(x) = \sum_{n \ge 0} a_n x^n$ where $a_n \ge 0$ and $f(1) = 1$.  Then the sum of random variables corresponds to the product of generating functions, so one can bring generating function techniques (see, for example, Wilf) to bear on such random variables.  For example, it is particularly easy to compute expected values this way: the expected value is $f'(1)$, and the product rule expresses the fact that expected value is additive.  Similarly, the variance is $f''(1) + f'(1) - f'(1)^2$.
I don't really know a place where these issues are discussed in detail, but one spectacular family of examples is the computation of the expected values and variances of certain statistics on permutations.  For example, suppose we want to compute the expected number of fixed points that a permutation of $n$ elements has.  By Burnside's lemma, the answer is $1$.  But another way to do this computation is to construct the family of polynomials
$\displaystyle P_n(x) = \frac{1}{n!} \sum_{\pi \in S_n} x^{c_1(\pi)}$
where $c_1(\pi)$ is the number of fixed points.  Then the number we want is $P_n'(1)$.  It turns out we can compute all these numbers at the same time because the bivariate generating function is
$\displaystyle P(x, y) = \sum_{n \ge 0} P_n(x) y^n = \frac{1}{1 - y} \exp \left( xy - y \right).$
Then the family of numbers we want is $\frac{\partial}{\partial x} P(x, y)$ evaluated at $x = 1$, which (as it is not hard to verify) is $\frac{1}{1 - y}$.  In fact this is true for the second derivative and all higher derivatives as well; in particular, the variance of the number of fixed points is also $1$.
What if we want to know the expected number and variance of, say, the total number of cycles?  Now we want to look at the family of polynomials
$\displaystyle Q_n(x) = \frac{1}{n!} \sum_{\pi \in S_n} x^{c(\pi)}$
where $c(\pi)$ is the total number of cycles.  Then the number we want is $Q_n'(1)$.  Now it turns out that the bivariate generating function is
$\displaystyle Q(x, y) = \sum_{n \ge 0} Q_n(x) y^n = \frac{1}{(1 - y)^x}$
(which should be interpreted as $\exp \left( x \log \frac{1}{1 - y} \right)$).  The partial derivative $\frac{\partial}{\partial x} Q(x, y)$ evaluated at $x = 1$ is now
$\displaystyle \frac{1}{1 - y} \log \frac{1}{1 - y} = \sum_{n \ge 1} H_n y^n$
where $H_n$ is the $n^{th}$ harmonic number.  Thus the expected number of cycles of a permutation of $n$ elements is about $\log n$.  (It actually turns out that the expected number of cycles of length $r$ is $\frac{1}{r}$, from which this result immediately follows.)  The second partial derivative evaluated at $x = 1$ is
$\displaystyle \frac{1}{1 - y} \log^2 \frac{1}{1 - y} = \sum_{n \ge 1} G_n y^n$
where $\displaystyle G_n = \sum_{k=1}^{n-1} \frac{1}{k} H_{n-k}$; I'm not sure of the asymptotic growth of this sequence, though, but whatever it is, the variance of the total number of cycles is $G_n + H_n - H_n^2$.  (In any case $G_n \le H_n^2$, so the variance is less than or equal to $H_n$, and this is probably about right asymptotically.)  One can deduce asymptotics for these kind of sequences using methods such as those in Flajolet and Sedgewick's Analytic Combinatorics, which is my best guess for more examples of using generating functions in this way.  There are probably examples there related to statistics of trees.
All the generating function identities I used above are a consequence of the exponential formula, one version of which is proven and discussed in this blog post.
Comment: Thank you Qiaochu, no matter how many times I've looked through Flajolets book, I'm still surprised on how often it comes up when I'm not expecting it!
Comment: For z = xy instead of z = x+y the analogous thing to do is consider Dirichlet series (http://en.wikipedia.org/wiki/Dirichlet_series).
Answer: There are nice algebraic relationships for special families.  The sum of normal (Cauchy, Levy) random variables is normal (Cauchy, Levy). The product of log-normal random variables is log-normal.  The sum of gamma random variables is gamma if the distributions have a common scale parameter, etc. See more here.
Comment: Thanks John, that table on the 3rd page of "Relationships Among Common Univariate Distributions", American Statistician 40:143-146 made my day!
Comment: "The sum of normal (Cauchy, Levy) random variables is normal (Cauchy, Levy)". I think sum of two normal random variables may not still be normal.

Algebra of Random Variables?


Strange compile errors in equality: (No method 'equals(Any?): Boolean' available)

Question: The following code
fun main(args: Array<String>) {
    val a = listOf('A', Pair('X', 'Y'))

    println(a[0] == 'B')
}

throws compile errors:
Error:(4, 17) Unresolved reference: ==
Error:(4, 17) No method 'equals(Any?): Boolean' available

as in the screenshot:

Why do these compile errors occur?
EDIT 1: It seems it is not related with a when expression.
EDIT 2: Code snippet (Press the "run" button on the top right to compile)
I need to cast manually to avoid the compile error. Using a smart cast also does not work. (Or val a: List<Any> = listOf('A', Pair('X', 'Y')) works)
Comment: How is your project configured? Is the Kotlin standard library correctly attached to it?
Comment: @yole This is done in http://try.kotlinlang.org/ JVM env., Kotlin v.1.2.71
Comment: Kotlin sees your list as `List`
Comment: As @forpas mentioned problem is `Serializable` does not contain `equals` operator. If you create your list explicitly with `listOf( ... )`, or inverse your condition `'B' == a[0]` the problem doesn't happen.
Comment: @Pawel Isn't a `Serializable` a subtype of `Any`?
Comment: @Naetmul `Serializable` is an interface so it has no supertypes.
Comment: @Pawel I think the main curiosity (at least as I see it, but I think this is probably what Naetmul is also wondering about) is why the smart cast doesn't work. Why does `if (a[0] is Char) { println(a[0] == 'A') }` give a compiler error but `println((a[0] as Char) == 'A')` works fine? Isn't the smart cast in the first case meant to make it unnecessary to cast as in the second case?
Comment: @KlitosKyriacou it does seem odd, one issue is querying a[0] twice doesn't let smart cast work, but even when I put local variable `val b = a[0]` and checked it didn't work. I guess smart cast only goes for subtypes, since it's still looking for `Serializable` equals method. You'd need to look at official forums to see if someone knows why it doesn't use `Any` equals operator.
Comment: the strange thing is: listOf('A', Pair('X', 'Y'))  is implicitely cast to List which gives the described error, but if you specifiy it explicitely listOf('A', Pair('X', 'Y')) it works :D. Looks like a bug to me
Comment: @WilliMentzel `listOf('A', Pair('X', 'Y'))` gives `Cannot access 'Serializable': it is internal in 'kotlin.io'`
Answer: This is a tricky case.
The highest common denominator between Char and Pair happen to be the Serializable interface, which doesn't define an equals() method. listOf(...) default type is defined as the highest common denominator of its elements.
Casting the array to List will allow using the equals() function implemented on Any, hence let the code work:
fun main(args: Array<String>) {
  val a = listOf('A', Pair('X', 'Y')) as List<Any>

  println(a[0] == 'B')
  println(a[0] == Pair('X', 'Y'))

  if (a[0] is Char) {
    println(a[0] == 'A')
  }

  println((a[0] as Char) == 'A')
}

A bit more elegant would be to define the Any type specifically:
val a = listOf<Any>('A', Pair('X', 'Y'))
Comment: `Pair` does implement `Serializable`, but `Char`? Also isn't it that *the highest common denominator* should be used?
Comment: In Char, it is implicit, probably for cross-platform needs. See: https://stackoverflow.com/q/53033094/3834036;
Right - will correct to highest common denominator :-)
Answer: As it was pointed out in the comments and by Lior Bar-On's answer, the inferred type for val a = listOf('A', Pair('X', 'Y')) is List<Serializable>.
The strange thing is that if you let Kotlin infer the type, you cannot compile:
val a = listOf('A', Pair('X', 'Y'))
println(a[0] == 'B')

but if you specify the type explicitely:
val a = listOf<Serializable>('A', Pair('X', 'Y'))

it will. This will not work in the Kotlin playground (try.kotlinlang.org) giving:

Error: Cannot access 'Serializable': it is internal in 'kotlin.io'

but if you compile it locally. This should be filed as bug.


In TensorFlow, how to write an if-else statement?

Question: Why both the if-else statements executed? "y" and "n" are printed out when executing the following code:
        if tf.reduce_all(tf.math.pow(s1, 4) == 0):
            print("y")
        else:
            print("n")

Full code:
class MAGOptimizer(keras.optimizers.Optimizer):
    def __init__(self, learning_rate=0.01, name="SGOptimizer", **kwargs):
        """Call super().__init__() and use _set_hyper() to store hyperparameters"""
        super().__init__(name, **kwargs)
        self._set_hyper("learning_rate", kwargs.get("lr", learning_rate)) # handle lr=learning_rate
        self._is_first = True

    def _create_slots(self, var_list):
        for var in var_list:
            self.add_slot(var, "pv") #previous variable i.e. weight or bias
        for var in var_list:
            self.add_slot(var, "pg") #previous gradient

    @tf.function
    def _resource_apply_dense(self, grad, var):
        var_dtype = var.dtype.base_dtype
        lr_t = self._decayed_lr(var_dtype) # handle learning rate decay

        new_var_m = tf.math.subtract(var, tf.multiply(grad, lr_t))

        pv_var = self.get_slot(var, "pv")
        pg_var = self.get_slot(var, "pg")

        if self._is_first:
            self._is_first = False
            new_var = new_var_m

        else:

            new_var = tf.math.subtract(var, tf.multiply(grad, lr_t))

        s1 = tf.math.subtract(var, pv_var)

        if tf.reduce_all(tf.math.pow(s1, 4) == 0):
            print("y")
        else:
            print("n")

        pv_var.assign(var)
        pg_var.assign(grad)
        var.assign(new_var)

    def _resource_apply_sparse(self, grad, var):
        raise NotImplementedError

    def get_config(self):
        base_config = super().get_config()
        return {
            **base_config,
            "learning_rate": self._serialize_hyperparameter("learning_rate"),
        }

    def _resource_apply_sparse(self, grad, var):
        raise NotImplementedError

    def get_config(self):
        base_config = super().get_config()
        return {
            **base_config,
            "learning_rate": self._serialize_hyperparameter("learning_rate"),
            "decay": self._serialize_hyperparameter("decay"),
            "momentum": self._serialize_hyperparameter("momentum"),
        }

model = keras.models.Sequential([keras.layers.Dense(1, input_shape=[8])])
model.add(keras.layers.Dense(2))
model.add(keras.layers.Dense(1))

model.compile(loss="mse", optimizer=MAGOptimizer(learning_rate=0.001))
model.fit(X_train_scaled, y_train, epochs=2)

The output is:
Train on 11610 samples
Epoch 1/2
y
n
y
n
y
n
y
n
y
n
WARNING:tensorflow:5 out of the last 5 calls to <function MAdaGradOptimizer._resource_apply_dense at 0x000001D4D8760828> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings is likely due to passing python objects instead of tensors. Also, tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. Please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for more details.
11610/11610 [==============================] - 3s 235us/sample - loss: 2.9868
Epoch 2/2
11610/11610 [==============================] - 1s 89us/sample - loss: 1.3655
<tensorflow.python.keras.callbacks.History at 0x1d4d8c3f908>

At runtime, does it execute for one branch or both branches?
Comment: If that's really your code, then the function must have been called 10 times.
Answer: This is documented behavior, which occurs when using print instead of tf.print in graph mode. See this for more details:

Side effects, like printing, appending to lists, and mutating globals,
can behave unexpectedly inside a Function, sometimes executing twice
or not all. They only happen the first time you call a Function with a
set of inputs. Afterwards, the traced tf.Graph is reexecuted, without
executing the Python code.

Here is an example:
@tf.function
def test(s1):
  if tf.reduce_all(tf.math.pow(s1, 4) == 0):
      print("y")
  else:
      print("n")
  return s1

test(tf.random.normal((5, 5)))

y
n

@tf.function
def test(s1):
  if tf.reduce_all(tf.math.pow(s1, 4) == 0):
     tf.print("y")
  else:
     tf.print("n")
  return s1

test(tf.random.normal((5, 5)))

n


Show that a triangle is isosceles inside a circle

Question: Let $\Gamma$  be a circle. Suppose $\Gamma '$ is another circle whose center lies on $\Gamma $. Let these two circles intersect at $A$ and $B$. Let $P$ be a point on $\Gamma $, and let $PB$ intersect $\Gamma'$ again at $Q$. Show that $\triangle PQA$ is isosceles.
I know my first step is to show that $\triangle ABP$ is isosceles when $P$ would lie on the midpoint between $AB$ , but I am not sure how.
Comment: Where is point $Q$? You don't seem to have mentioned it.
Comment: I edited it. Sorry.
Comment: There is no good reason why $ABP$ is isosceles (and it is not). Try changing the position of $P$.
Comment: I doubt if $\triangle ABP$ is always isosceles.
Answer: I am writing about one of the cases here, where $P$ is outside circle $\Gamma'$.
$$\begin{align}\angle APQ =& 180^\circ - \angle AOB\\
\angle AQP =& \frac{1}{2} \angle AOB\\
\angle PAQ =& 180^\circ -(180^\circ - \angle AOB) - \frac{1}{2} \angle AOB\\
=& \angle AQP\\
AP=&QP
\end{align}
$$

By swapping $A$ and $B$, we have another case to prove:
$$\begin{align}
\angle QPA =& 180^\circ - \angle AOB\\
\angle PQA =& 180^\circ - \left(180^\circ-\frac{1}{2}\angle AOB\right)\\
=&\frac{1}{2}\angle AOB\\
\angle PAQ =& \angle PQA\\
AP=QP
\end{align}$$
Answer: As pointed out, your first step isn't true, so it will be impossible to show.
This question is easily approached by angle chasing, using the properties that were given. Let $O'$ be the center of $\Gamma'$.
Let $ \angle PQA = \alpha $.
What can you say about $\angle AO' B$?
What can you say about $\angle APB$?
Hence show that $\angle PAQ = \alpha$.
Thus the triangle is isosceles.
Answer: It suffices to show that $\angle QPA=\pi-2\cdot \angle PQA$ which can be accomplished with some angle chasing. In this configuration, $Q$ lies between $P$ and $B$, but angle chasing can be done similarly in other configurations (or with directed angles.)
Let $O$ be the center of $\Gamma'$, so it lies on the circumcircle of $APB$. Then
$$
\angle PQA=\pi-\angle BQA=\pi-(\pi-\frac{1}{2}\angle AOB)=\frac{1}{2}\angle AOB=\frac{1}{2}(\pi-\angle APB)
$$
($\angle BQA=\pi-\frac{1}{2}AOB$ because $O$ is center of $\Gamma'$.) This gives us $\angle APB=\pi-2\cdot \angle APB$ as desired.
If you know about spiral similarity, a more direct method would be to note that $A$ is the spiral similarity center mapping $O_1P$ to $OQ$ (where $O_1$ is the center of $\Gamma$), and thus it also maps $PQ$ to $O_1O$. Thus $\triangle APQ\sim\triangle AO_1O$, which is isosceles because $AO_1=O_1O$ was given.


Symmetric matrices and exponentials

Question: My question is simple, suppose I have a matrix $A$, how do I know that it is an exponential of symmetric matrix $S$, i.e what are the conditions on $A$ such that $A= \exp(S)$ where $S$ is symmetric
Comment: You might want to look at the [Logarithm of a matrix](http://en.wikipedia.org/wiki/Logarithm_of_a_matrix).
Comment: for a start, all the eigenvalues must be positive. i am not sure if that is sufficient.
Answer: We claim that $A = e^S$ for $S$ symmetric if and only if $A$ is symmetric and has positive eigenvalues.
If $A = e^S$, $A$ must be symmetric as well since $(\text{exp(S)})^T = \text{exp}(S^T)$. To show positivity of eigenvalues, let $v$ be an eigenvector of $S$, with eigenvalue $\lambda$. Then $Av = e^S v = e^{\lambda} v$, and $e^{\lambda} > 0.$
Now assume $A$ is symmetric and has positive eigenvalues. Then there exists an orthogonal matrix $O$ such that $O^T A O = D$, where $D$ is diagonal and has positive entries on the diagonal. Then there exists a diagonal matrix $M$ such that $D = e^M$. Thus $A = O e^M O^T = \text{exp}(OMO^T)$ and clearly $OMO^T$ is symmetric.

Symmetric matrices and exponentials


Samba server on CentOS sees shared directories, but no files visible

Question: I have a very basic samba share for a development environment.  There is a directory /var/www/ owned by www:www.  All subdirectories are also owned by www:www.  All users are members of the www group.  The entire smb.conf file is the default except for the share definition.
<code>[www]
  path = /usr/share/nginx/www/
  public = yes
  writable = yes
  create mask = 0775
</code>
I can see the directory structure from windows, but all directories shown as empty.  This config works in FreeBSD perfectly.  Any ideas?
After getting to the office, I ran wireshark and on the QUERY_PATH_INFO request, I get back STATUS_OBJECT_NAME_NOT_FOUND, over and over again.
I moved the webroot back to the nginx default of /usr/share/nginx, and this for whatever reason solved the browsing problem, but my user now doesn't have permission to write to the directory.  If it isn't one thing it's another.
Comment: Try `setenforce 0` and see if it's SELinux-related.
Comment: Check your samba log and audit logs.
Comment: What are the permission of the files (not the directories)? Also, on CentOS, Apache usually works as user/group `apache`, not `www`.
Comment: All of the files and directories are owned by www:www, and the logs don't show anything of consequence, a few errors from the windows machine attempting to reload the directory before it was configured, and some errors regarding printers, which are enabled in the default config, but I'm not using.  I'm on nginx, but it's configured to run as www, it's a holdover from FreeBSDwhere the default user is www.
Comment: That's in /etc/grub.conf, no?
Answer: As told above, try first:
<code># setenforce 0
</code>
if the files appear, then it's a SELinux missing context. Enable SELinux again, then add context to folder:
<code># setenforce 1
# chcon -Rt samba_share_t /usr/share/nginx/www/
</code>
Comment: When something strange goes wrong one has to be vigilant about remembering about SELinux.


composition of a number using 1 and 2

Question: The number of partitions of $n$ in which all parts are $1$ or $2$ is
$$
\Bigl\lfloor \frac{n}{2} + 1 \Bigr\rfloor
$$
Similarly how can I formulate the number of compositions formed using $1$ or $2$?
I could come up with a following series:
If $n = 7$, then the number of compositions using $1$ and $2$ is
$$
\binom{7}{0} + \binom{6}{1} + \binom{5}{2} + \binom{4}{3} = 21.
$$
How can I form a formula to calculate the sum of this series?
Definitions: Partition, Composition
Answer: Let $F(n)$ be the number of compositions of $n$ by $1$ and $2$.  A composition of $n$ can either end in $1$ or $2$.  There are $F(n-1)$ that end in $1$ and $F(n-2)$ that end in $2$, so we have $F(n)=F(n-1)+F(n-2)$.  Does that look familiar?
Comment: fibonacci series right ? And the fastest way to calculate the sum would be fibonacci exponentiation.Please correct me if I am wrong.
Comment: @g4ur4v:  Exactly right.  You need to think a bit about how this $n$ matches up with the indices of the Fibonacci series.

composition of a number using 1 and 2


Posting Object Data from Console App to Web API

Question: I am creating a console app in .Net Core that gets data from a Web API, updates that data and does a Put to update the Web API data. I am running into an issue where I am losing my data at the HttpRequestBuilder when sending it to HttpContent and the Web API is not getting updated but I get a 200 returned. Any ideas what I may be doing wrong?
Controller:
public static async Task<HttpResponseMessage> UpdateTransaction(Transaction transaction)
{
    var requestUri = $"{baseUri}transactions/{transaction.ID}";
    return await HttpRequestFactory.Put(requestUri, transaction);
}

JsonContent:
public JsonContent(object value, string mediaType)
        :base(JsonConvert.SerializeObject(value), Encoding.UTF8, mediaType)
{
}

HttpRequestFactory:
public static async Task<HttpResponseMessage> Put(string requestUri, object value)
{
    var builder = new HttpRequestBuilder()
        .AddMethod(HttpMethod.Put)
        .AddRequestUri(requestUri)
        .AddContent(new JsonContent(value, "application/json"));

    return await builder.SendAsync();
}

HttpRequestBuilder:
 public HttpRequestBuilder AddContent(HttpContent content)
{
    this.content = content;
    return this;
}

public async Task<HttpResponseMessage> SendAsync()
{
    // Check required arguments
    EnsureArguments();

    // Setup request
    var request = new HttpRequestMessage
    {
        Method = this.method,
        RequestUri = new Uri(this.requestUri)
    };

    if (this.content != null)
        request.Content = this.content;

    request.Headers.Accept.Clear();
    if (!string.IsNullOrEmpty(this.acceptHeader))
        request.Headers.Accept.Add(
            new MediaTypeWithQualityHeaderValue(this.acceptHeader));

    // Setup client
    var client = new HttpClient();
    client.Timeout = this.timeout;

    var response = await client.SendAsync(request);

    return response;
}

Comment: Please do not confuse ASP.NET Core with .NET Core. Those are different products.
Answer: I don't think the JsonContent class is doing the correct thing. We are missing the full class definition so I can only guess:
When you call it in the Put method it is returning an object to .AddContent but that is probably not getting serialized as the content string.
Change your Put method to call the JsonConvert method directly.
HttpRequestFactory:
public static async Task<HttpResponseMessage> Put(string requestUri, object value)
{
    var builder = new HttpRequestBuilder()
        .AddMethod(HttpMethod.Put)
        .AddRequestUri(requestUri)
        .AddContent(JsonConvert.SerializeObject(value, Encoding.UTF8, "application/json"));

    return await builder.SendAsync();
}

If you do want to use your JsonContent class then you might be better with a static method to do the conversion rather than a class hierarchy?


Determine the point where function output will go from positive to negative

Question: I have a function that is like:
f(x) = c - x^2 (c = some constant positive integer, x = +ve integer >= 0)

The output of this function, goes from positive to negative as x -> +infinity.

Is there a way to directly figure out the x which produces last of the positive outputs before entering in the negative domain?
Also, if I use an iterative method to locate such a point, how should I find the right increment to go with so that I can reach that value of x as quick as possible? Right now, I am initializing x = floor(sqrt(c) * 0.9) and using dumb +1 increments to x to reach the point where f(x) enters the negative range.
An observation: f(x) seems to behave in a weird way for c > 10e40 (i.e. when we initiate x = floor(sqrt(c) * 0.9) it gives out a value way too far from the desired point) and you can imagine how long the +1 increment takes to get to the desired output with such large values of c.. ;-(.

Please help. thanks.
Comment: $f$ does not behave weirdly for $c>10^{40}$. Are you using floating point math on a computer perhaps?
Comment: I am using standard C/Python interface to do the calculations of sqrt..can this be the reason?
Answer: If we solve the quadratic equation $c-x^2=0$ for a real number $x$, we get $x=\sqrt c$ or $x=-\sqrt c$. Since we are looking at the branch $x\ge 0$, the required solution is the largest integer not exceeding $\sqrt c$. For example, if $c=2$ then $\sqrt c=1.414\ldots$ and the solution would be $1$.
Comment: That is sqrt(c) - 1?
Comment: @khan - No it is not "sqrt(c) - 1". It is "floor(sqrt(c))" where floor() returns the next lower integer value of the argument. In some computer languages you can use "int(sqrt(c))" to achieve the same result but some languages will round up of the fractional part of the argument is greater than or equal to 0.5.
Answer: The mathematical answer is that given by Jasper Loy. The computational solution may be better done the following way in order to avoid the detour via floating point numbers and surprises caused by conversion.
I assume that you have integer operations $+,-,\cdot,/$ available (where $/$ is integer division as usual in programming) that can deal with integers in the range $0,\ldots,c$. The following algorithm corresonds to Heron's method of computing square roots (assuming $c>2$ perhaps)

Let $r\leftarrow 2$
Let $s \leftarrow (r+c/r)/2$
If $s>r+1$ or $s<r-1$, let $r\leftarrow s$ and go back to step 2.
If $s\ge r$, then $r^2<c\le (r+1)^2$, hence we output $r$ and terminate
Now $s=r-1$, $s^2<c<r^2$, hence we output $s$ and terminate
Comment: @khan For questions of performance, a computing group may be better but first consider whether you prefer: the correct answer slowly or the wrong answer quickly.
Comment: Very interesting indeed. A question though: Is this method more expensive than computational square root?
Comment: That is right. I agree.
Comment: @Hagen von Eitzen what do you suggest about figuring out the right increment to `x`, to reach the desired point, if we choose to go with an iterative approach?


Setup a non-CA Puppet Master

Question: I would like to set up an additional puppet master to act as a non-CA server.
I've have installed and am successfully using Passenger.  The servers in question are all running CentOS 6.6 and are all on the same network.  Selinux has been set to permissive.  The test environment consists of three servers as follows:
1.  HOSTNAME=basxtststinfl01, DNS=puppet.xchanginghosting.com,basxtststinfl01.xchanginghosting.com (CA Master)
2.  HOSTNAME=basxtststinfl02, DNS=basxtststinfl02.xchanginghosting.com (non-CA Master)
3.  HOSTANME=basxtststinfl03, DNS=basxtststinfl03.xchanginghosting.com (Agent)

I have configured my second puppet master (non-CA) as follows:
[main]
   dns_alt_names = basxtststinfl02.xchanginghosting.com,basxtststinfl02
   ca_server = basxtststinfl01.xchanginghosting.com

[master]
   ca = false

I removed the original certificate on the non-CA puppet master and regenerated another after the dns_alt_names were added but prior to ca and ca_servers.
+ "basxtststinfl01.xchanginghosting.com" (SHA256) E6:5D:56:39:16:22:A0:FD:8A:C1:AF:83:EB:80:94:2D:74:CE:1F:75:D5:3A:F7:92:EF:36:1A:85:4C:EA:58:F2 (alt names: "DNS:basxtststinfl01", "DNS:basxtststinfl01.xchanginghosting.com", "DNS:puppet", "DNS:puppet.xchanginghosting.com")

Is this the correct approach so far?
My virtual host file looks like this:
LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-4.0.59/buildout/apache2/mod_passenger.so
PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-4.0.59
PassengerDefaultRuby /usr/bin/ruby
PassengerMaxRequests 1000
PassengerMaxPoolSize 12
PassengerPoolIdleTime 1500
PassengerStatThrottleRate 120

Listen 8140

<VirtualHost *:8140>
    SSLProxyEngine On
    ProxyPassMatch ^/([^/]+/certificate.*)$ https://basxtststinfl01.xchanginghosting.com:8140/$1

    SSLEngine on
    SSLProtocol             ALL -SSLv2 -SSLv3
    SSLCipherSuite          EDH+CAMELLIA:EDH+aRSA:EECDH+aRSA+AESGCM:EECDH+aRSA+SHA384:EECDH+aRSA+SHA256:EECDH:+CAMELLIA256:+AES256:+CAMELLIA128:+AES128:+SSLv3:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!IDEA:!ECDSA:kEDH:CAMELLIA256-SHA:AES256-SHA:CAMELLIA128-SHA:AES128-SHA
    SSLHonorCipherOrder     on

    SSLCertificateFile      /var/lib/puppet/ssl/certs/basxtststinfl02.xchanginghosting.com.pem
    SSLCertificateKeyFile   /var/lib/puppet/ssl/private_keys/basxtststinfl02.xchanginghosting.com.pem
    SSLVerifyClient optional
    SSLVerifyDepth  1
    SSLOptions +StdEnvVars +ExportCertData

    RequestHeader unset X-Forwarded-For

    RequestHeader set X-SSL-Subject %{SSL_CLIENT_S_DN}e
    RequestHeader set X-Client-DN %{SSL_CLIENT_S_DN}e
    RequestHeader set X-Client-Verify %{SSL_CLIENT_VERIFY}e

    DocumentRoot /usr/share/puppet/rack/puppetmasterd/public/
    RackBaseURI /
    <Directory /usr/share/puppet/rack/puppetmasterd/>
            Options None
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

NOTE:  I removed SSLCertificateChainFile, SSLCACertificateFile and SSLCARevocationFile assuming I don't them for non-CA purposes.
The agent has been used many times for other test circumstances so I've removed any existing certificates prior to attempting the initial agent run.  I then attempt to request for a certificate via the non-CA master (basxtststinfl02).
# puppet agent --verbose --onetime --no-daemonize --server basxtststinfl02
Info: Creating a new SSL key for basxtststinfl03.xchanginghosting.com
Info: Caching certificate for ca
Info: csr_attributes file loading from /etc/puppet/csr_attributes.yaml
Info: Creating a new SSL certificate request for basxtststinfl03.xchanginghosting.com
Info: Certificate Request fingerprint (SHA256):  85:13:E4:3E:DE:54:24:44:22:07:7E:E9:51:96:CE:88:89:96:82:35:51:97:91:8C:C0:B9:24:42:50:FD:FE:F3
Info: Caching certificate for ca

Looks good so far!
I can then successfully sign the certificate on the CA master (basxtststinfl01).  However, after I've signed the certificate and repeat the puppet agent command on the agent I see the following error:
Error: /File[/var/lib/puppet/lib]: Failed to generate additional resources using 'eval_generate': SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed: [unable to get local issuer certificate for /CN=basxtststinfl02.xchanginghosting.com]
Error: /File[/var/lib/puppet/lib]: Could not evaluate: Could not retrieve file metadata for puppet://basxtststinfl02/plugins: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed: [unable to get local issuer certificate for /CN=basxtststinfl02.xchanginghosting.com]

I've absolutely no clue as to what this error is telling me.  Has anyone else been successful with configuring an second master to act as a non-CA?  Or does the above error make any sense to anyone.
Answer: I think you are presenting the wrong CA certificate. It should be set to the CA puppet master's ca.pem.
Run the second master's agent against the primary one, after that add this to your puppet master vhost config:
SSLCertificateChainFile /var/lib/puppet/ssl/certs/ca.pem
SSLCACertificateFile    /var/lib/puppet/ssl/certs/ca.pem
SSLCARevocationFile     /var/lib/puppet/ssl/crl.pem
SSLCARevocationCheck    chain

In case that I'm mistaken, I've checked my working secondary master's config, here's what's different to yours:
SSLCertificateChainFile /var/lib/puppet/ssl/certs/ca.pem
SSLCACertificateFile    /var/lib/puppet/ssl/certs/ca.pem
SSLCARevocationFile     /var/lib/puppet/ssl/crl.pem
SSLCARevocationCheck    chain

RequestHeader set X-SSL-Subject %{SSL_CLIENT_S_DN}e
RequestHeader set X-Client-DN %{SSL_CLIENT_S_DN}e
RequestHeader set X-Client-Verify %{SSL_CLIENT_VERIFY}e

ProxyPassMatch ^/([^/]+/certificate.*)$ https://ca.puppet.master:8140/$1

<Location ~ "/[^/]+/certificate">
    PassengerHighPerformance Off
</Location>

That gives you something else to try at least.
Comment: Thank you fuero!  Although this wasn't 100% of the answer I was hoping for it certainly provoked further thought on my part and so I've marked it as correct.  Thanks again.

Setup a non-CA Puppet Master


How to know the parent class of the invoked java program?

Question: I am working on a distributed application and getting an exception in the main method of a class. How do I know which java program has invoked it ? I tried debugging the distributed application, but could not figure it out.
Comment: Care to post the stack trace? The only instance I can clearly recall when caller information wasn't available from the stack trace was when the class was running in its own thread (hence, the stack trace would generally end at the thread level with no indication of who started the thread and where).
Comment: what about the stack trace? what do you mean, parent class of invoked program?
Comment: Need more details, is this an RMI application?
Comment: It's not RMI call, just invoking a java application.
Comment: If it's just invoking the application you should see the who calls the method in the stacktrace. Otherwise this is really strange.
Comment: Below is the stack trace. I would like to know who invoked the YarnChild

java.lang.RuntimeException: java.lang.ClassNotFoundException: org.apache.hadoop.examples.RandomWriter$RandomMapper
at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:1179)
..
..
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:143)

Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.examples.RandomWriter$RandomMapper
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
..
..
at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:1177)
... 8 more
Answer:
Let's say Java Class A invokes Java Class B (like "java classB") . I am getting the exception in class B. How do I want to know which class has invoked "java classB"?

You cannot know what invoked the java process from ClassB. The Exception will only go as deep as it's own call stack from it's process. If something else started the process, even if it was java itself, there is no way of know this from ClassB.
You are better off using helpful logging (of both debug/info messages and exception stacktraces) from ClassA. You will have to make sure that ClassB exits appropriately when it fails (exit with a code other than 0) and then ClassA can see this failure in the process it spawned.
Comment: Thanks Gweebz - I had spent some time putting break points, printf in the code and could not figure it out. So, wanted to find if this can be figured out from Class B.
Answer: Try getting the current stacktrace and see who calls your main method.
<code>StackTraceElement[] elements = Thread.currentThread().getStackTrace();
</code>
Comment: I got the stack trace, but it's not showing the parent class. Let's say Java Class A invokes Java Class B (like "java classB") . I am getting the exception in class B. How do I want to know which class has invoked "java classB"?
Answer: Here's the Javadoc for "Exception":
http://download.oracle.com/javase/6/docs/api/java/lang/Exception.html
There are several things you can do with the exception object besides call "getMessage()".  For example, you can "printStackTrace()" (showing you how it was called, and where it was thrown).
Comment: I got the stack trace, but it's not showing the parent class. Let's say Java Class A invokes Java Class B (like "java classB") . I am getting the exception in class B. How do I want to know which class has invoked "java classB"?


Passing Variables Between Two Classes in Flutter

Question: I am making register and login pages in flutter and facing a problem as I want to use the same variables 'email' and  'password' declared inside class _MyHomePage in main.dart file
to another class SignupPage in signup.dart file.
I already imported the files but I can not use the values in both classes
class _MyHomePageState extends State<MyHomePage> {
 int _counter = 0;

String _email = '';
String _password = '';

final formKey = new GlobalKey<FormState>();

FormType _formType = FormType.login;

bool validateAndSave() {
final form = formKey.currentState;
if (form.validate()) {
  form.save();
  return true;
 //      print('Form is Valid  Email: $_email, Password: $_password');
}
return false;
}

Answer: You can pass the data when you navigate your screen in following way.
Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => SignUp(email: emailvariable,pass: passvariable),
                ),

in following way you can receive data
class SignUp extends StatefulWidget {

  final email;
  final pass;
  SignUp({Key key,this.email,this.pass}) : super(key: key);

  @override
  _SignUpState createState() => _SignUpState();
}

now in state widget you can access email and pass variable as
widget.pass and widget.email

Comment: Wrap your sign up widget with scaffold widget because it provides material or you can use material widget as well
Comment: It gives "no material widget found" error. I did exactly what you did, any idea what could be go wrong? In my program when user presses the edit button of a post, I'm trying to get postID of what user clicked, and give it to another class.
Comment: I edited my question just before you answered it.  Sorry, you instantly responded :) Can you check it again? I'm using a StreamBuilder to list some data from CloudFirestore.  I couldn't wrap it with scaffold, but when i wrap it with material it gave the same error. I can post as a question if you want, thank you!
Answer: There are two approaches for that

Pass values through class constructor

If you don't want to go back and forth you can use this
Just in the second page use like this
class Register extends StatefulWidget {
  Register({Key key, this.email, this.pass});

  final String email;
  final String pass;

  @override
  _RegisterState createState() => _RegisterState();
}

class _RegisterState extends State<Register> {

  @override
  Widget build(BuildContext context) {
    print(widget.email);
    print(widget.pass);
    // to use state class values you need to use the widget as the parent class object
    return Container(
    );
  }
}

To pass the values in constructor
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => Register(email: email, pass: pass),
  ),

Store the values in global scope before routing to another page

If you have to route multiple times and even require these values further, you store the values in global file before routing to another page and access there
Make one file
global.dart
library my_project.global;

// set default values for the initial run
String email = '';
String pass = '';

To access the values
import 'global.dart' as global;

main() {
 // import the global.dart file to access the variables across the application
 global.email = 'firstname.lastname@example.com';
 print(global.email);
}

Comment: Setting Global Variables is a not a good practice. You can send them through class constructors or use a form of State Management (ScopedModel, Redux, BLoC, etc). Flutter gives you [InheritedModel](https://api.flutter.dev/flutter/widgets/InheritedModel-class.html) (InheritedWidget) which allows you easily share value throughout your app without much muss.
Comment: variable name should not include _ as it makes the private in dart, try removing underscore @AlexAli
Comment: The first solution is going to make the same problem which is defining the same variables many times so I go with the second solution but I get this error : error: The name '_emailTest' is being referenced through the prefix 'global', but it isn't defined in any of the libraries imported using that prefix. (undefined_prefixed_name at [flutter_app_service] lib/main.dart:136)
Answer: If the other answers do not solve your issue, you can use the InheritedModel widget that's provided by Flutter. It allows you to share data between deeply nested widgets. The documentation is good and there's even a video from the Flutter team explaining how to use it: https://api.flutter.dev/flutter/widgets/InheritedModel-class.html
Comment: I guess those widget are independent, but still If this is the preferred way give it a shot!


Unzip the specific folder in NodeJS

Question: Is there any way I can unzip the specific folder from the zip file via NodeJS.
I tried this
const unzipper = require('unzipper');
const fs = require('fs');

fs.createReadStream('path/to/archive.zip') // Your zip file
  .pipe(unzipper.Parse())
  .on('entry', function (entry) {
    const fileName = entry.path;
    const type = entry.type; // 'Directory' or 'File'
    // file_name1, file_name1 are files which you are looking for
    if (type === 'File' && ['file_name1', 'file_name1'].indexOf(fileName) >= 0) {
      entry.pipe(fs.createWriteStream('output/path/' + fileName)); // Output folder of unzip process
    } else {
      entry.autodrain();
    }
 });

But this work only for files. I want to look for specifc folder and unzip that.
Comment: What does "look for specific folder" mean?  Are you looking on the hard drive for a specific folder?  Are you looking in the zip file for a specific folder?
Comment: I want to exclude root directory inside zip if it contains the root directory otherwise ignore that
Answer: var filename = req.files[0].filenam
var zippath = __dirname + "../../../../../public/uploads/pages/zip/"
var unzippath = __dirname + "../../../../../public/uploads/pages/"
fs.createReadStream(zippath + filename).pipe(unzipper.Extract({ path: unzippath }))

Comment: While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply.

Unzip the specific folder in NodeJS