text:
Q: Get JSON data from multiple files in a unique response There are several files containing JSON data on my server. I want to receive the data contained in those files with a single GET request.
Right now my code looks like this:
app.get('/json', function(req, res){

    fs.readFile(__dirname + '/file01.json', function(err, content){
        var data01 = content;
    });

    fs.readFile(__dirname + '/file02.json', function(err, content){
        var data02 = content;
    });

    res.send({file01: data01, file02: data02});

});

I know this is absolutely not the way to do it, the files are still being read when the response is sent, and i'm not sure if data01 and data02 are globally defined.
But then, what is the way to do it?
Should I use a stream? Should I use multiple res.write() instead? Enlighten me.

A: Perfect fit for async.parallel.
var async = require('async');
app.get('/json', function(req, res) {
  var work = {
    file01: async.apply(fs.readFile, __dirname + '/file01.json'),
    file02: async.apply(fs.readFile, __dirname + '/file02.json')
  };
  async.parallel(work, function (error, results) {
    if (error) {
      res.status(500).send(error);
      return;
    }
    //might need string->Object here
    results['file01'] = JSON.parse(results['file01']);
    results['file02'] = JSON.parse(results['file02']);
    res.send(results);
  });
});

A: Use the callback of each readFile to do the next operation:
fs.readFile(__dirname + '/file01.json', function(err, content){
    var data01 = content;
    //Might be smart to do some err checking here
    //if (err) send error
    //else read the next file
    fs.readFile(__dirname + '/file02.json', function(err, content){
        //if (err) again
        var data02 = content;
        res.send({file01: data01, file02: data02});
    });
});


text:
Q: How to get pointed back button in jquery mobile? Is there anyway to get pointed back button like we have in iphone. Currently I am getting round button.
Also, any one has idea abt navigation bar in jQuery mobile. Whenever we are changing screen using navigation bar css is not getting applied.

A: Back Button:
You can try this:
http://taitems.tumblr.com/post/7240874402/ios-inspired-jquery-mobile-theme-jquery-mobile
But it will use a background picture instead of pure CSS backgrounds.
If you want to do it pure CSS, this will be tricky.
Start from here. I assign this to an empty div, which gives me a CSS only triangle, which I'm using for popup windows. You would have to find a way to turn this by 90 degrees, match border color to button background gradient and fiddle it into any of the JQM button styles.
Nice challenge :-)
.popover_triangle {
    background: none repeat scroll 0 0 red;
    border-color: transparent transparent black;
    border-style: solid;
    border-width: 16px;
    font-size: 0;
    line-height: 0;
    width: 0;
    }

If you manage to get it done, please post. There are a lot of people looking for it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Running two commands at the exact same time in bash Code:
#!/bin/bash
nc ipv4 port echo "hi"

Question:
How do I make it say Hi  automatically right after it connected to the listener?

A: in case you want to keep the connection open after command, a fifo can be used
mkfifo fifo_filename

# start nc reading from fifo in background (jobs,kill can be used to monitor)
nc host port <fifo_filename &

# open file descriptor 3 to write to fifo
exec 3>fifo_filename
echo hi >&3
...
echo bye >&3

# close file descriptor (will close the fifo and background nc will exit)
exec 3>&-


text:
Q: How to delete rows with NaN in a pandas dataframe? I have this pandas dataframe which is actually a excel spreadsheet:
    Unnamed: 0  Date    Num     Company     Link    ID
0   NaN     1990-11-15  131231  apple...    http://www.example.com/201611141492/xellia...   290834
1   NaN     1990-10-22  1231    microsoft http://www.example.com/news/arnsno...     NaN
2   NaN     2011-10-20  123     apple   http://www.example.com/ator...  209384
3   NaN     2013-10-27  123     apple...    http://example.com/sections/th-shots/2016/...   098
4   NaN     1990-10-26  123     google  http://www.example.net/business/Drugmak...  098098
5   NaN     1990-10-18  1231    google...   http://example.com/news/va-rece...  NaN
6   NaN     2011-04-26  546     amazon...   http://www.example.com/news/home/20160425...    9809

I would like to remove all the rows that have NaN in the ID column and reindex the "index imaginary column":
    Unnamed: 0  Date    Num     Company     Link    ID
0   NaN     1990-11-15  131231  apple...    http://www.example.com/201611141492/xellia...   290834
1   NaN     2011-10-20  123     apple   http://www.example.com/ator...  209384
2   NaN     2013-10-27  123     apple...    http://example.com/sections/th-shots/2016/...   098
3   NaN     1990-10-26  123     google  http://www.example.net/business/Drugmak...  098098
4   NaN     2011-04-26  546     amazon...   http://www.example.com/news/home/20160425...    9809

I know that this can be done as follows:
df = df['ID'].dropna()

Or
df[df.ID != np.nan]

Or
df = df[np.isfinite(df['ID'])]

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Or
df[df.ID()]

Or:
df[df.ID != '']

And then:
df.reset_index(drop=True, inplace=True)

However, It didnt removed the NaN in ID. I am getting the former dataframe.
UPDATE
In:
df['ID'].values

Out:
array([ '....A lot of text....',
       nan,
       "A lot of text...",
       "More text",
       'text from the site',
       nan,
       "text from the site"], dtype=object)

A: Try df.dropna(axis = 1).
Or, df.dropna(axis = 0, subset = "ID")See if it helps.

A: try this
df = df[df.ID != 'nan']


text:
Q: Wordpress/IIS/PHP cannot download files with non-ASCII characters I have a Wordpress installation on a Windows IIS with PHP. It is not possible to download files from the website that have been uploaded with non-ASCII characters. Renaming the files with ASCII characters works fine.
Does anyone know how we can solve this?
Upon trying to download the file an error is received: 404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or temporarily unavailable.
Windows Server 2012 R2, IIS 8 and PHP 5.6.8


text:
Q: Solving infinite coupled equations I need to solve symbolically an infinite system of coupled algebraic equations that I tried to do analytically but I could not.
Solutions of these equations, $V_l^m$, define the coefficients of a some function $V$ (that I'm looking for) of the form
$$ V(r,\theta ,\varphi)=\sum _{l=0}^{\infty } \sum _{m=-l}^{+l} Y_l^m (\theta ,\varphi) V_l^m(r)=Y_0^0 V_0^0+Y_1^0 V_1^0+Y_1^1 V_1^1+Y_1^{-1} V_1^{-1}+\cdots $$
where $Y_l^m (\theta ,\varphi)$ denote the spherical harmonics.
These solutions $V_l^m$ obey the general form
$$ A\, V_l^m+\frac{B}{2}\left(-\sqrt{\frac{(l+m-1) (l+m)}{(2 l-1) (2 l+1)}} V_{l-1}^{m-1}+\sqrt{\frac{(l-m) (l-m-1)}{(2 l+1) (2 l-1)}} V_{l-1}^{m+1}+\sqrt{\frac{(l-m+1) (l-m+2)}{(2 l+1) (2 l+3)}} V_{l+1}^{m-1}-\sqrt{\frac{(l+m+2) (l+m+1)}{(2 l+1) (2 l+3)}} V_{l+1}^{m+1}\right)+m R V_l^m+\left(\delta _{l,1} \delta _{m,-1}-\delta _{l,1} \delta _{m,1}\right)D\, \lambda  =0$$
which involves an infinite coupled equations.
Here $ A, B, D, R, \lambda$ are real constants.
In MA input form it gives
eq[l_,m_]:=A Subscript[V,{l,m}]+B/2 (Sqrt[((l-m+1)(l-m+2))/((2l+1)(2l+3))] Subscript[V,{l+1,m-1}]+Sqrt[((l-m)(l-m-1))/((2l+1)(2l-1))] Subscript[V,{l-1,m+1}]-Sqrt[((l+m-1)(l+m))/((2l-1)(2l+1))] Subscript[V,{l-1,m-1}]-Sqrt[((l+m+2)(l+m+1))/((2l+1)(2l+3))] Subscript[V,{l+1,m+1}])+(KroneckerDelta[l,1]KroneckerDelta[m,-1]-KroneckerDelta[l,1]KroneckerDelta[m,1])D \[Lambda]+m R Subscript[V,{l,m}]

Here just for the code I used $V_{\{l,m\}}$ instead of $V_l^m$.
For your information, solution of this problem is to express $V_{\{0,0\}}$ according to the variable $\lambda$ as
$$V_{\{0,0\}}=(f)\lambda$$
where $f$ is a term that includes all other solutions (maybe in the form of an infinite continued fraction).
Any help please on this problem! Can MA do something?

A: first attempt
(apparently this isn't what the OP wanted)
I have edited the equation a bit because D is a reserved symbol and because subscripts are inconvenient:
eq[l_,m_] = d λ (KroneckerDelta[-1, m] KroneckerDelta[1, l] - KroneckerDelta[1, l] KroneckerDelta[1, m]) + a V[l, m] +
            m R V[l, m] +
            1/2 b (-Sqrt[(((-1 + l + m) (l + m))/((-1 + 2 l) (1 + 2 l)))] V[l-1, m-1] +
                   Sqrt[((-1 + l - m) (l - m))/((-1 + 2 l) (1 + 2 l))] V[l-1, m+1] +
                   Sqrt[((1 + l - m) (2 + l - m))/((1 + 2 l) (3 + 2 l))] V[l+1, m-1] -
                   Sqrt[((1 + l + m) (2 + l + m))/((1 + 2 l) (3 + 2 l))] V[l+1, m+1]);

For every value of l, we have 2l+1 equations that can be used to determine {V[l+1,-l-1],...,V[l+1,l+1]}. There are 2l+3 unknowns, so we cannot determine all coefficients. Here I've chosen to solve for the {V[l+1,-l-1],...,V[l+1,l-1]} and leave V[l+1,l] and V[l+1,l+1] as free parameters:
S[l_] := First@Solve[Table[eq[l, m] == 0, {m, -l, l}],
                     Table[V[l+1, m], {m, -l-1, l-1}]]

Try it out:
S[2]
(*    {V[3, -3] -> ...,
       V[3, -2] -> ...,
       V[3, -1] -> ...,
       V[3, 0] -> ...,
       V[3, 1] -> ...}    *)

We can stack these solutions in order to express the coefficients at a given value of l in terms of all smaller l-values:
Expand[S[2] /. S[1] /. S[0]]
(*    complicated expression for V[3,-3]...V[3,1] in terms of
      V[0, 0], V[1, 0], V[1, 1], V[2, 1], V[2, 2], V[3, 2], V[3, 3]}    *)

programmatically:
Clear[F];
F[l_] := Module[{f = S[l]},
  Do[f = f /. S[L], {L, l - 1, 0, -1}];
  Expand[f]]

Now calling F[2] gives the same result as the above Expand[S[2] /. S[1] /. S[0]].
second attempt
If you want to express $V_{0,0}$ in terms of $\{V_{L,-L},V_{L,-L+1},\ldots,V_{L,L}\}$ for a specific $L$, you can solve all the equations for $l<L$ for all the variables with $l<L$. For example, with $L=4$ we express $V_{0,0}$ in terms of $\{V_{4,-4},V_{4,-3},V_{4,-2},V_{4,-1},V_{4,0},V_{4,1},V_{4,2},V_{4,3},V_{4,4}\}$:
With[{L = 4},
  FullSimplify[V[0, 0] /.
    First@Solve[
      Flatten[Table[eq[l, m] == 0, {l, 0, L - 1}, {m, -l, l}]],
      Flatten[Table[V[l, m],       {l, 0, L - 1}, {m, -l, l}]]]]]

-((b (-10290 Sqrt[7] a^7 d λ +
         42 Sqrt[15]
           a^2 b^3 R (35 Sqrt[7] R^2 (-V[4, -2] + V[4, 2]) +
            2 b^2 (7 V[4, -4] - Sqrt[7] V[4, -2] + Sqrt[7] V[4, 2] -
               7 V[4, 4])) -
         294 Sqrt[15]
           a^4 b^3 R (7 V[4, -4] - Sqrt[7] V[4, -2] + Sqrt[7] V[4, 2] -
            7 V[4, 4]) +
         6 Sqrt[15]
           b^3 R (21 Sqrt[7] b^2 R^2 (V[4, -2] - V[4, 2]) +
            49 R^4 (7 V[4, -4] + 4 Sqrt[7] V[4, -2] -
               4 Sqrt[7] V[4, 2] - 7 V[4, 4]) +
            b^4 (-7 V[4, -4] + Sqrt[7] V[4, -2] - Sqrt[7] V[4, 2] +
               7 V[4, 4])) +
         49 a^5 (174 Sqrt[7] b^2 d λ +
            2940 Sqrt[7] d R^2 λ +
            b^3 (-7 Sqrt[15] V[4, -4] + 2 Sqrt[105] V[4, -2] -
               3 Sqrt[42] V[4, 0] + 2 Sqrt[105] V[4, 2] -
               7 Sqrt[15] V[4, 4])) -
         14 a^3 (153 Sqrt[7] b^4 d λ +
            1680 Sqrt[7] b^2 d R^2 λ +
            36015 Sqrt[7] d R^4 λ +
            35 Sqrt[3]
              b^3 R^2 (7 Sqrt[5] V[4, -4] + Sqrt[35] V[4, -2] -
               3 Sqrt[14] V[4, 0] + Sqrt[35] V[4, 2] +
               7 Sqrt[5] V[4, 4]) -
            2 b^5 (7 Sqrt[15] V[4, -4] - 2 Sqrt[105] V[4, -2] +
               3 Sqrt[42] V[4, 0] - 2 Sqrt[105] V[4, 2] +
               7 Sqrt[15] V[4, 4])) +
         a (162 Sqrt[7] b^6 d λ +
            252 Sqrt[7] b^4 d R^2 λ +
            50274 Sqrt[7] b^2 d R^4 λ +
            370440 Sqrt[7] d R^6 λ +
            14 Sqrt[3]
              b^5 R^2 (28 Sqrt[5] V[4, -4] + Sqrt[35] V[4, -2] -
               6 Sqrt[14] V[4, 0] + Sqrt[35] V[4, 2] +
               28 Sqrt[5] V[4, 4]) +
            49 Sqrt[3]
              b^3 R^4 (77 Sqrt[5] V[4, -4] + 8 Sqrt[35] V[4, -2] -
               27 Sqrt[14] V[4, 0] + 8 Sqrt[35] V[4, 2] +
               77 Sqrt[5] V[4, 4]) -
            3 b^7 (7 Sqrt[15] V[4, -4] - 2 Sqrt[105] V[4, -2] +
               3 Sqrt[42] V[4, 0] - 2 Sqrt[105] V[4, 2] +
               7 Sqrt[15] V[4, 4]))))/(3 Sqrt[
       42] (1715 a^9 - 1225 a^7 (2 b^2 + 21 R^2) +
         7 a^5 (156 b^4 + 2380 b^2 R^2 + 15435 R^4) -
         a^3 (174 b^6 + 3045 b^4 R^2 + 31850 b^2 R^4 + 145775 R^6) +
         3 a (3 b^8 + 58 b^6 R^2 + 651 b^4 R^4 + 5880 b^2 R^6 +
            20580 R^8))))

You can do this for larger values of $L$, but it gets more difficult.


text:
Q: Cannot finish a race with timer in RxJS race(
  timer(2000).pipe(mapTo(1)),
  timer(1000).pipe(mapTo(2)),
).toPromise().then(r => console.log(r))

Code above will output 2.
If I have an action that I try to repeat until condition is met but ignore it if it takes too long, then I take an approach in this answer https://stackoverflow.com/a/51644077
The problem is that race never finishes with the shortest function. The longActionObservable repeats until the condition is met and empty() is called.
const o = longActionObservable();
race(
  o.pipe(expand(v => v < 100 ? empty() : o)), // no toArray because I do not need result
  timer(2000),
).toPromise()

This code does not return a promise that will ever resolve. I'm wondering why is this approach so fragile to this kind of behavior? If there's one observable timer(2000) that most surely ends, why doesn't race end?

A: You are missing an important point about race:

The observable to emit first is used

This means that if first emission of longActionObservable occurs before the timer, then timer is not used, regardless of how long the "expand" observable takes to complete.

no toArray because I do not need result

Even though you don't need the result, toArray actually makes this work as you wish because it will not allow any emissions until your "expand" observable completes.  Instead of using toArray, you could use reduce instead:
race(
  o.pipe(
    expand(v => v < 100 ? empty() : o),
    reduce(() => undefined)
  ),
  timer(2000),
)
.toPromise()

If there's one observable timer(2000) that most surely ends, why doesn't race end?

The only reason race will not end is because the chosen source (first observable to emit) does not complete.  Check the emissions of your expand observable to see why it isn't completing:
  o.pipe(
    expand(v => v < 100 ? empty() : o),
    tap(v => console.log('expand: ', v)),
    reduce(() => undefined)
  ),

Here's a StackBlitz you can play around with :-)


text:
Q: Escaping char in regex I ran this example in my bash terminal:
echo "ab" | egrep '\a\b'

Output
ab

then I ran this one:
echo "a" | egrep '\a\b'

Output
a

I was confused. Why did I get output?
But then I input another one:
echo "a" | egrep '\ab'

and didn't get output.
What is the difference between \a\b and \ab for Extended RegEx?
P.S
Regex didn't ignore the first letter:
echo "b" | egrep '\a\b'

Output is empty
Regex acted as I expected, but what is the difference from the first case?
P.P.S
I found out that this example:
echo 'ab' | egrep '\a\b'

also does not output anything. In the first case (echo "ab" | egrep '\a\b'), the output was ab. How can quotes affect regex?

A: The '\a\b' makes \a\b regex where \a is an unknown escape sequence and matches an a and \b is a word boundary.
echo "a" | egrep '\a\b' - correctly outputs a, there is an a not followed with a digit, letter or underscore.
echo "a" | egrep '\ab' - correctly does not output anything, a does not contain ab.
echo "b" | egrep '\a\b' - correctly does not output anything, b does not contain a.
As for echo "ab" | egrep '\a\b', it should not output any result, ab does not contain a at a word boundary, there is b after a.
Other letters that means something else when escaped (GNU grep, POSIX):

*

*\B - a position other than a word boundary position

*\s - whitespace

*\S - non-whitespace

*\w - letters, digits, and underscores

*\W - characters different from letters, digits, and underscores.

Also, there is \< (start of word) and \> (end of word).
If you use -P, PCRE pattern, there are even more escape sequences available (see pcresyntax and pcrepattern).


text:
Q: Messages: show User Name with variable User_ID i have 2 tables, to create messages, conversation and messages. If you create a new message with a new partner, you get a new conversation ID, so if you started the conversation, your user_id is in the messages table and in the conversation table you are user_one your writting partner is user_two. But if somewhere else is started the conversation you are user_two and in the messages table, the user_id ist the other user.
I need the name from your writting partners to show in a list.
Example:

*

*Mario  / Last Message /       -> if i click so i will see the messages

*Maria  / Last Message /       -> if i click so i will see the messages

To save and show the messages is working. I need only to read the name from your conversation partner.
With my solution i get the name of the writting partners, but only if you are User two.
The problem is the join.
I need something like JOINNOTIN
My table:
Conversation
  'id'
  'user_one'
  'user_two'

Messages
  'id'
  'message'
  'userid'
  'conversationid'

My Query:
 $messages = DB::table('conversation')
      ->select('messages.message', 'conversation.user_one', 'conversation.user_two', 'users.name', 'users.firstname', 'messages.id', 'messages.created_at', 'conversation.id')
      ->join('users', 'users.id', '=', 'conversation.user_one')
      ->join('messages', 'messages.conversation_id', '=', 'conversation.id')
      ->where('messages.userid', '!=', Auth::user()->id)
      ->orwhere('conversation.user_one', '=', Auth::user()->id)
      ->orwhere('conversation.user_two', '=', Auth::user()->id)
      ->groupBy('messages.conversation_id')
      ->latest()
      ->get();

A: You need the condition user_one == auth()->user()->id OR user_two == auth()->user()->id in the join() method.
$authId = auth()->user()->id;
$messages = DB::table('conversation')
      ->select('messages.message', 'conversation.user_one', 'conversation.user_two', 'users.name', 'users.firstname', 'messages.id', 'messages.created_at', 'conversation.id')
      ->join('users', function ($join) use ($authId) {
          $join->on('id', '=', 'user_one')->orOn('id', '=', 'user_two')
          ->where('id', '!=', $authId);
      })
      ->join('messages', 'messages.conversation_id', '=', 'conversation.id')
      ->where('messages.userid', '!=', Auth::user()->id)
      ->orwhere('conversation.user_one', '=', Auth::user()->id)
      ->orwhere('conversation.user_two', '=', Auth::user()->id)
      ->groupBy('messages.conversation_id')
      ->latest()
      ->get();


text:
Q: P-value from Chi sq test statistic in Python I have computed a test statistic that is distributed as a chi square with 1 degree of freedom, and want to find out what P-value this corresponds to using python.
I'm a python and maths/stats newbie so I think what I want here is the probability denisty function for the chi2 distribution from SciPy. However, when I use this like so:
from scipy import stats
stats.chi2.pdf(3.84 , 1)
0.029846

However some googling and talking to some colleagues who know maths but not python have said it should be 0.05.
Any ideas?
Cheers,
Davy

A: You meant to do:
>>> 1 - stats.chi2.cdf(3.84, 1)
0.050043521248705147

A: Quick refresher here:
Probability Density Function: think of it as a point value; how dense is the probability at a given point?
Cumulative Distribution Function: this is the mass of probability of the function up to a given point; what percentage of the distribution lies on one side of this point?
In your case, you took the PDF, for which you got the correct answer.  If you try 1 - CDF:
>>> 1 - stats.chi2.cdf(3.84, 1)
0.050043521248705147

PDF
CDF

A: Some of the other solutions are deprecated. Use scipy.stats.chi2 Survival Function. Which is the same as 1 - cdf(chi_statistic, df)
Example:
from scipy.stats import chi2
p_value = chi2.sf(chi_statistic, df)

A: If you want to understand the math, the p-value of a sample, x (fixed), is
P[P(X) <= P(x)] = P[m(X) >= m(x)]  = 1 - G(m(x)^2)
where,

*

*P is the probability of a (say k-variate) normal distribution w/ known covariance (cov) and mean,

*X is a random variable from that normal distribution,

*m(x) is the mahalanobis distance = sqrt( < cov^{-1} (x-mean), x-mean >. Note that in 1-d this is just the absolute value of the z-score.

*G is the CDF of the chi^2 distribution w/ k degrees of freedom.

So if you're computing the p-value of a fixed observation, x, then you compute m(x) (generalized z-score), and 1-G(m(x)^2).
for example, it's well known that if x is sampled from a univariate (k = 1) normal distribution and has z-score = 2 (it's 2 standard deviations from the mean), then the p-value is about .046 (see a z-score table)
In [7]: from scipy.stats import chi2

In [8]: k = 1

In [9]: z = 2

In [10]: 1-chi2.cdf(z**2, k)
Out[10]: 0.045500263896358528

A: To calculate probability of null hypothesis given chisquared sum, and degrees of freedom you can also call chisqprob:
>>> from scipy.stats import chisqprob
>>> chisqprob(3.84, 1)
0.050043521248705189

Notice:

chisqprob is deprecated! stats.chisqprob is deprecated in scipy 0.17.0; use stats.distributions.chi2.sf instead

A: Update: as noted, chisqprob() is deprecated for scipy version 0.17.0 onwards. High accuracy chi-square values can now be obtained via scipy.stats.distributions.chi2.sf(), for example:
>>>from scipy.stats.distributions import chi2
>>>chi2.sf(3.84,1)
0.050043521248705189
>>>chi2.sf(1424,1)
1.2799986253099803e-311

While stats.chisqprob() and 1-stats.chi2.cdf() appear comparable for small chi-square values, for large chi-square values the former is preferable. The latter cannot provide a p-value smaller than machine epsilon,and will give very inaccurate answers close to machine epsilon. As shown by others, comparable values result for small chi-squared values with the two methods:
>>>from scipy.stats import chisqprob, chi2
>>>chisqprob(3.84,1)
0.050043521248705189
>>>1 - chi2.cdf(3.84,1)
0.050043521248705147

Using 1-chi2.cdf() breaks down here:
>>>1 - chi2.cdf(67,1)
2.2204460492503131e-16
>>>1 - chi2.cdf(68,1)
1.1102230246251565e-16
>>>1 - chi2.cdf(69,1)
1.1102230246251565e-16
>>>1 - chi2.cdf(70,1)
0.0

Whereas chisqprob() gives you accurate results for a much larger range of chi-square values, producing p-values nearly as small as the smallest float greater than zero, until it too underflows:
>>>chisqprob(67,1)
2.7150713219425247e-16
>>>chisqprob(68,1)
1.6349553217245471e-16
>>>chisqprob(69,1)
9.8463440314253303e-17
>>>chisqprob(70,1)
5.9304458500824782e-17
>>>chisqprob(500,1)
9.505397766554137e-111
>>>chisqprob(1000,1)
1.7958327848007363e-219
>>>chisqprob(1424,1)
1.2799986253099803e-311
>>>chisqprob(1425,1)
0.0

A: For ultra-high precision, when scipy's chi2.sf() isn't enough, bring out the big guns:
>>> import numpy as np
>>> from rpy2.robjects import r
>>> np.exp(np.longdouble(r.pchisq(19000, 2, lower_tail=False, log_p=True)[0]))
1.5937563168532229629e-4126

Update by another user (WestCoastProjects)  When using the values from the OP we get:
np.exp(np.longdouble(r.pchisq(3.84,1, lower_tail=False, log_p=True)[0]))
Out[5]: 0.050043521248705198928

So there's that 0.05 you were looking for.


text:
Q: How to skip to the next song with shuffle on? REACT-NATIVE im building a music player, and im having a problem with this, cant think a way to solve this, i have the shuffle mode, when the shuffle is on and I press next song, it goes to the next song, and when the track is over, it validates if shuffle is on, if its, repeat the track, if not, next song, the problem here is when i select another track from the queue, because when i do that, the listener will execute, validating again if shuffle is on and next is off, causing a loop, i can only go to the next song pressing next and not from the queue, heres the code:
state = {
  shuffle: true,
  next_song: false,
  repeat_song: "",
}

if (this.state.repeat && !this.state.next_song) { //if user want to repeat a track
                await TrackPlayer.pause();
                await TrackPlayer.skip(this.state.repeat_song);
                TrackPlayer.play();
            }else {
                let {title} = await TrackPlayer.getTrack(current_song);
                let {current_track_id, current_track, cover, artist} = await this.get_info_track(tracks, title);
                await AsyncStorage.setItem("last_song", JSON.stringify(current_track));
                await AsyncStorage.setItem("last_song_duration", JSON.stringify(0));
                this.setState({
                    current_track_id: current_track_id,
                    current_track: current_track,
                    cover: cover,
                    artist: artist,
                    repeat_song_id: current_song,
                    last_song_duration: 0,
                    next_song: false,
                });
            }

update_next_song = () => {    //this will execute when the user press next, once is executed will be passed to false again
    this.setState({next_song: true});
}

then problem is when I select from the queue, next song is already set to false, and the first condition will always be true, so cant think a way to do this

A: Hi you can put array of Songs in
 TrackPlayer.add(Array).

and use
TrackPlayer.skipToNext()
TrackPlayer.skipToPrevious();

it will work according to your requirements thanks :-)
 skipToNext = async () => {
    try {
      await TrackPlayer.skipToNext();
      this.props.SetProgress('pasued')
    } catch (_) {
    }
  }

  skipToPrevious = async () => {
    try {
      await TrackPlayer.skipToPrevious();
      this.props.SetProgress('pasued')
    } catch (_) { }
  }


text:
Q: Start a new git branch with the changes from my last push I have two git branches master and first_puppet. I pushed first puppet up to github and then created a pull request. I have now subsequently started working on a new feature, but mistakenly have been working in the first_puppet branch. I want to move all my changes since I pushed on first_puppet to a new branch. How might I do so? Basically my confusion centers around shouldn't I always be branching from master. And if I don't branch from master will there be any problems. Thank you very much for you your help.
-Tom

A: Assuming you are on the first_puppet branch and origin points to the remote where you pushed to:
git branch new_branch
git reset --hard origin/first_puppet
git checkout new_branch

This creates a new branch from the current HEAD, then resets the current branch back to the same ref as you pushed upstream, then switches to the new branch.
The new branch still contains everything in the first_puppet branch, plus your new changes (which is not necessarily a problem! it depends how you want to use branches, see below).  If you only want it to contain the new changes you could either create another branch, branched off master, and cherry-pick the new changes:
[after running the first steps above]
git checkout -b new2 master
git cherry-pick first_puppet..new_branch

Or you could rebase the new branch onto master and remove the unwanted commits:
[after running the first steps above]
git branch --set-upstream-to=master
git rebase -i
[edit the list of commits to only include the new ones]

Basically my confusion centers around shouldn't I always be branching from master.

Not necessarily. If you want to do another set of changes that are based on the ones in the first_puppet branch then it makes sense to branch off that.
If you want to make some independent changes that might form a separate pull request, starting from master might make more sense.

And if I don't branch from master will there be any problems.

It depends what you consider problems!
You will have a branch that includes two sets of changes. That might be good, or it might be a problem. Fundamentally there is no reason you must always branch from master, but it might make sense for you as a convention or for a particular workflow.


text:
Q: Tensorflow variable_scope: tf.placeholder and tf.get_variable within a function I just tried to get an understanding of the TensorFlow naming behavior and I still need some clarification.
I worked on a project where I went into trouble with the naming of tensor, because they were predefined in a function, which was called later.
So I have the following example here:
import tensorflow as tf

    def foo():

        with tf.variable_scope("foo", reuse=True):

            a = tf.placeholder(tf.float32,name="a")
            b = tf.placeholder(tf.float32,name="b")

        return a,b
    ##

    a,b  = foo()

    print(a)
    print(b)

I get the output:
Tensor("foo/a:0", dtype=float32)
Tensor("foo/b:0", dtype=float32)

When I call it again though, I get the output:
Tensor("foo_1/a:0", dtype=float32)
Tensor("foo_1/b:0", dtype=float32)

Why is this the case? I set reuse on true, so I expect the tensors to be in the same variable_scope "foo" again or that the program throws an error like "tensors already defined".
So, I tried a workaround with tf.get_variable:
    def foo():
    with tf.variable_scope("foo", reuse=True):

        a = tf.get_variable("v", [1])

    return a
##

a1 = foo()
print(a1)

graph = tf.get_default_graph()
#call tensors by name in tensorflow to avoid confusion with the naming
graph.get_tensor_by_name("foo/v:0")

Here, i get always the same output:
<tf.Variable 'foo/v:0' shape=(1,) dtype=float32_ref>

Unfortunately, I cannot work with variables because you cannot define a dynamic shape for them. You need placeholders to define variable shapes.
Can someone explain me why the program continues to create new variable_scopes for placeholders but not when I call tf.get_variable() ?
Thank you!

A: You can force the reuse of a scope by adding a '/' after the name i.e.: tf.variable_scope("foo/", reuse=True):
However that won't solve your problem.
In the case of variables, calling tf.Variable will always create a new variable, whereas calling tf.get_variable will reuse it if it already exists.
But with Placeholders there is no tf.get_placeholder.
What you can do is define your placeholders outside of foo, only once, and get them by name using tf.get_default_graph().get_tensor_by_name(name) or directly using the python variable whenever you need them.
example with get_tensor_by_name:
import tensorflow as tf

with tf.name_scope("scope"):
    tf.placeholder(tf.float32,name="a")
    tf.placeholder(tf.float32,name="b")

def foo():
    a = tf.get_default_graph().get_tensor_by_name("scope/a:0")
    b = tf.get_default_graph().get_tensor_by_name("scope/b:0")

    return a,b

a,b = foo()

print(a)
print(b)

Note that placeholders, unlike variables, do not maintain a state that can be reused or not. They are merely a "pointer" to a tensor which will be fed later. They should not be part of your model, but an input to it, so you should not be creating them several times anyway.

A: Just for the case that you ran the code in a Jupyter notebook twice make sure that the notebook's kernel is not reusing the variables.
If you, instead, call the function foo() multiple times within the scope of the default graph you always get the same result:
def foo():
  with tf.variable_scope("foo", reuse=True):
    a = tf.placeholder(tf.float32,name="a")
    b = tf.placeholder(tf.float32,name="b")
  return a,b

with tf.Graph().as_default():
  a,b  = foo()

  print(a) # gives variable name 'foo/a'
  print(b) # gives variable name 'foo/b'

But that is different from the use case, where the function is called repeatedly to create more placeholders.
c,d = foo()

In this case the answer above of f4 is the recommended solution.


text:
Q: PHP send and receive data curl or json I'm trying to make two file talk to each other.
'output_file.php' to send data from domain 'a' to input_file located on domain 'b'.
Data from output file will later be send to crm via api.
I'm stuck as I don't know what am I doing wrong, what should I change in these files?
Here is output_file.php:
<?php
    //send cURL
    $curl = 'https://domain_name/input.php';
    $fields = array(
        'name' => urlencode($_POST['name']),
        'email' => urlencode($_POST['email']),
        'tel' => urlencode($_POST['tel']),
    );
    //var_dump($fields);
    foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    rtrim($fields_string, '&');
    //var_dump($fields_string);
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL, $curl);
    curl_setopt($ch,CURLOPT_POST, count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    $result = curl_exec($ch);
    //var_dump($result);
    curl_close($ch);*/
?>

Here is input_file.php:
 // main data about the person. person_id is added later dynamically - PERSON DATA
$person = array(
 'name' => 'name from output_file.php',
 'email' => 'email from output_file.php',
 'phone' => 'tel from output_file.php'
);

A: You can use below snippet for this. It should be work.
Ps. Please delete POST functions from your output file, it's uncesseray and useless.
$person = array(
 'name' => $_REQUEST['name'],
 'email' => $_REQUEST['email'],
 'phone' => $_REQUEST['phone'],
);

Best,

A: As you do use POST to send your data, you will need to capture the POST on the target site. As you do use $_POST variables, you may want to have a look into security, to make sure the data recieved can not harm you:
PHP $_GET security, $_POST security best practice
Your Outfile:
<?php

    $curl = 'https://domain_name/input.php';
    $fields = array(
        'name' => urlencode($_POST['name']),
        'email' => urlencode($_POST['email']),
        'tel' => urlencode($_POST['tel']),
    );

    // here you do prepare your POST data
    foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    rtrim($fields_string, '&');
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL, $curl);

    // here you define that your data will be sent via POST
    curl_setopt($ch,CURLOPT_POST, count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    // this curlopt ensures the output of your destination is captured
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    curl_close($ch);
?>

Your Input/Destination file:
<?php
// user $_POST to populate your array
$person = array(
 'name' => $_POST['name'],
 'email' => $_POST['email'],
 'phone' => $_POST['tel']
);
// see the result
var_dump($person);
?>


text:
Q: Height of Virtual Android Keyboard for Untiy3d I try get height of Virtual Android Keyboard for Unity3d
I write android Plugin for Unity3d and try calc height in function Trace() in below code (But always get Height of Screen or 0. I create window and edit field and show it when I need. I need get height of Virtual Keyboard for place some image over virtual keyboard):
public class KeyboardTool
{

    private EditTextEx input;
    public Activity _activity;
    private PopupWindow window;
    public KeyboardTool(Activity activity)
    {
        if (activity == null)
            activity = com.unity3d.player.UnityPlayer.currentActivity;

        _activity = activity;
        _activity.runOnUiThread(new Runnable() {@SuppressLint("NewApi") public void run()
        {

            window = new PopupWindow(_activity);
            input = new EditTextEx(_activity);

            window.setTouchable(false);
            window.setFocusable(true);
            window.setSplitTouchEnabled(false);
            window.setOutsideTouchable(true);
            window.setIgnoreCheekPress();
            window.setClippingEnabled(false);

            window.setContentView(input);
            window.setBackgroundDrawable(new ColorDrawable(0));

            input.setInputType(InputType.TYPE_CLASS_TEXT);
            input.setBackgroundColor(0);
            input.setVisibility(View.VISIBLE);
            input.setFocusable(true);
            input.setFocusableInTouchMode(true);

            window.setInputMethodMode(PopupWindow.INPUT_METHOD_FROM_FOCUSABLE);
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            UnityPlayer.currentActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

            Trace();
        }});
    }

    @SuppressLint("NewApi") private void Trace()
    {
        Window rootWindow = UnityPlayer.currentActivity.getWindow();
        View rootView = rootWindow.getDecorView().findViewById(android.R.id.content);

        Log.i("xxx", "xxx rootView " + rootView);

        rootView.getViewTreeObserver().addOnGlobalLayoutListener
        (
                new ViewTreeObserver.OnGlobalLayoutListener() {
                public void onGlobalLayout(){
                    Rect r = new Rect();
                    View view = UnityPlayer.currentActivity.getWindow().getDecorView();
                    view.getWindowVisibleDisplayFrame(r);
                    Log.i("xxx", "xxx left " + r.left +" " + r.top+ " " +  r.right + " " + r.bottom);
                    // r.left, r.top, r.right, r.bottom

                    Window rootWindow = UnityPlayer.currentActivity.getWindow();
                    View rootView = rootWindow.getDecorView().findViewById(android.R.id.content);
                    int heightDiff = rootView.getHeight()- rootWindow.getDecorView().getHeight();
                    Log.i("", "xxx heightDiff " + heightDiff + "rootView.getHeight() " + rootView.getHeight() + " rootWindow.getDecorView().getHeight() " + rootWindow.getDecorView().getHeight());
                }
                });
    }

    public void Show()
    {
        this.canceled = false;
        this.done = false;
        if (input != null)
        {
            input.done = false;
            input.canceled = false;
        }
        _activity.runOnUiThread(new Runnable() {public void run()
        {
            window.setFocusable(true);
            input.setFocusable(true);
            input.setFocusableInTouchMode(true);

            window.showAtLocation(_activity.getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, 0);
            input.requestFocus();
            input.bringToFront();
            InputMethodManager imm = (InputMethodManager)_activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(input, 0);

            Trace();
        }});
    }

    public void Hide()
    {
        _activity.runOnUiThread(new Runnable() {public void run()
        {
            window.setFocusable(false);
            input.setFocusable(false);
            input.setFocusableInTouchMode(false);
            input.clearFocus();
            window.dismiss();

            InputMethodManager imm = (InputMethodManager)_activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(input.getWindowToken(), 0);

            Trace();
        }});
    }
}


text:
Q: DateTime Parsing "Wed Mar 12 2014 17:50:15 GMT+0000 I got format exception when trying to parse this
// input string "Wed Mar 12 2014 17:50:15 GMT+0000 (UTC)"
DateTime.Parse(response.LastActivityDate);

A first chance exception of type System.FormatException
How can I parse it this input string ?
What culture is this ?
thank you in advance!

A: Here, have some fish:
string value = "Wed Mar 12 2014 17:50:15 GMT+0000 (UTC)";
value = value.Replace("GMT","").Replace("(UTC)","").Trim();
value = value.Insert(value.Length - 2, ":");
DateTime parsed = DateTime.ParseExact(value, "ddd MMM dd yyyy HH:mm:ss zzz",
                                      CultureInfo.InvariantCulture);


text:
Q: hibernate and dates I want to get records between start date and end date using hibernate .Like,
id     startDate                 endDate
15     2011-01-05 05:05:10   2011-05-01 09:05:10
37     2010-03-01 05:06:10   2010-06-01 09:07:10
49     2005-01-05 03:03:03   2005-05-01 08:08:08

I want to retrive 15 when provided startDate=2011-01-05 05:05:10 and endDate=2011-05-01 09:05:10
I want to retrive 37 when provided startDate=2010-03-01 05:06:10 and endDate=2010-06-01 09:07:10
Can anybody tell me  how to do using hibernate ? I tried using between clause but not worked .

A: What Criteria did you try to use?  If both startDate and endDate need to match for the row to be returned, then you can try using the following Restrictions:
Restrictions.and(Restrictions.eq("startDate",startDateValue),Restrictions.eq("endDate", endDateValue))


text:
Q: Android AlarmManager send notification every time app starts instead of only once My app use an AlarmManager that start a BroadcastReceiver.
The BroadcastReceiver generate a reminder notification to the user.
This is the MainActivity that start the Alarm
public class MainActivity extends ActionBarActivity {

    private PendingIntent pendingIntent;
    private AlarmManager alarmManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set the alarm to start at approximately 2:00 p.m.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int curHr = calendar.get(Calendar.HOUR_OF_DAY);

// Checking whether current hour is over 14
        if (curHr >= 14)
        {
            // Since current hour is over 14, setting the date to the next day
            calendar.add(Calendar.DATE, 1);
        }

        calendar.set(Calendar.HOUR_OF_DAY, 14);
// Schedule alarm manager

        Intent myIntent = new Intent(MainActivity.this, MyBroadcastReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);

        alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);

        // With setInexactRepeating(), you have to use one of the AlarmManager interval
        // constants--in this case, AlarmManager.INTERVAL_DAY.
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, pendingIntent);

    }

And this is the BroadcastReceiver that generate the notification
public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent)
    {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "tag");

        //Acquire the lock
        wl.acquire();

        Log.v("ADebugTag", "It work!");

        int mId = 0;
        //Show the notification here.
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_action_edit)
                        .setContentTitle("Diario Scolastico")
                        .setContentText("You have homeworks for tomorrow!")
                        .setAutoCancel(true)
                        .setDefaults(-1);

// Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(context, MainActivity.class);

// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager mNotificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
        mNotificationManager.notify(mId, mBuilder.build());

        //Release the lock
        wl.release();
    }
}

Manifest permissions:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.VIBRATE" />

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />

As you can see the alarm must start at 14 PM, but i receive the notification every time that i start the app.
There is something wrong in my code?
I use the Scheduling Repeating Alarms for setting the alarm every day at same hour, but don't work properly

A: The issue is you are setting the time to current day. So if you are opening your app after 14:00, your alarm manager will immediately fire.
You need to check whether the time is over 14:00 for the current day, if yes you need to change the date to the next day:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int curHr = calendar.get(Calendar.HOUR_OF_DAY);

// Checking whether current hour is over 14
if (curHr >= 14)
{
   // Since current hour is over 14, setting the date to the next day
   calendar.add(Calendar.DATE, 1);
}

calendar.set(Calendar.HOUR_OF_DAY, 14);
// Schedule alarm manager


text:
Q: Java Algoirthm number of Combinations of variables (Similar to Bit String Algoirthm) I have a problem I'm trying to solve in Java and I cannot figure out the algorithm that I'm going to need to follow. This problem is similar to the Bit String problem (how many bit strings are there of length x), but with some added difficulty. I'm not even sure the algorithm for solving the normal bit string problem anyway.
So here's my actual problem:
I have 5 variables. Say Q W X Y Z. Each variable can take one of 3 values (so like bit string can take 1 or 0, but this can take say 0, 1, or 2). I need to generate all possible combinations of this "bit string".
So one combination may be 00000 another may be 10002, another could be 22222, etc. I need to print out all combinations of this "bit string"
I'm really stumped on how to solve this problem or even come up with a decent algorithm.
Thanks for the help! Much appreciated.

A: Try this:
import java.util.Iterator;
import java.util.NoSuchElementException;

public class Generator implements Iterable<String> {

    private int len;
    public Generator(int len) {
        this.len = len;
    }

    public Iterator<String> iterator() {
        return new Itr(len);
    }

    private class Itr implements Iterator<String> {
        private int[] a;
        private boolean done;

        public Itr(int len) {
            a = new int[len];
            done = false;
        }

        @Override
        public String next() {
            if (done) throw new NoSuchElementException();
            String s = getString();
            step(a.length - 1);
            return s;
        }

        @Override
        public boolean hasNext() { return !done; }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }

        private void step(int index) {
            if (a[index] == 2) {
                if (index == 0) {
                    done = true;
                    return;
                }
                a[index] = 0;
                step(index - 1);
            } else
                a[index]++;
        }

        private String getString() {
            StringBuilder s = new StringBuilder();
            for (int i : a)
                s.append(i);
            return s.toString();
        }
    }

}

Then you could do something like this:
Generator g = new Generator(2 /* length of resulting strings */);
for (String s : g)
    System.out.println(s);

Output:

00
  10
  20
  01
  11
  21
  02
  12
  22

Basically, all we're doing here is counting upwards in base-3 until we reach 222...222 (where the number of 2s is specified when instantiating a Generator). Hope this helps!

A: You need to consider the math behind it. It makes things a lot easier when you've understood how to enumerate these strings. This will yield an obvious way not only of generating the strings, but also allow you to "random access" them, i.e. you can also write a get(int num) method that will produce the numth element.
The math is pretty simple, it only involves modulo operations (%) and divisions, and it really pays off when you figure this out yourself.
As a simple first preparation, assume that you have n decimal digits.

*

*Given a number x, how do you get the nth digit?

*Given n digits, how do you get the number x?

After you have figured this out, try to abstract from having 10 digits. Say, practise counting in binary. Then in ternary, which will be your solution for 3 digits.

A: To achieve this, you could just count up to your maximum value (22222 in your example) using a radix of 3. The BigInteger class supports output and instantiation with an arbitrary radix. The BigInteger class, however, does not support zerofill which is why I added this myself. Here is the resulting solution:
public static void main( String[] args ) {
    System.out.println( new BitStrings().generateBitStrings( new BigInteger( "2222", 3 ) ) );
}

public List<String> generateBitStrings( BigInteger maxValue ) {
    final String format = "%0" + maxValue.toString( 3 ).length() + "d";
    BigInteger current = BigInteger.ZERO;
    final List<String> result = new ArrayList<String>( maxValue.intValue() );
    do {
        result.add( String.format( format, Long.valueOf( current.toString( 3 ) ) ) );
        current = current.add( BigInteger.ONE );
    } while(current.compareTo( maxValue ) <= 0);
    return result;
}

Output:
[0000, 0001, 0002, 0010, 0011, 0012, 0020, 0021, 0022, 0100, 0101, 0102, 0110, 0111, 0112, 0120, 0121, 0122, 0200, 0201, 0202, 0210, 0211, 0212, 0220, 0221, 0222, 1000, 1001, 1002, 1010, 1011, 1012, 1020, 1021, 1022, 1100, 1101, 1102, 1110, 1111, 1112, 1120, 1121, 1122, 1200, 1201, 1202, 1210, 1211, 1212, 1220, 1221, 1222, 2000, 2001, 2002, 2010, 2011, 2012, 2020, 2021, 2022, 2100, 2101, 2102, 2110, 2111, 2112, 2120, 2121, 2122, 2200, 2201, 2202, 2210, 2211, 2212, 2220, 2221, 2222]

Hope this answers your question.

A: This should be a relatively easy problem to solve.
Essentially, you're merely computing the set of strings Σ^5 where Σ = { 0, 1, 2 }.
static Iterable<String> strings(final int radix, final int digits) {
  return new Iterable<String>() {

    public Iterator<String> iterator() {
      return new Iterator<String>() {

        private final int hi = (int) Math.pow(radix, digits);
        private int cursor;

        public boolean hasNext() {
          return cursor < hi;
        }

        public String next() {
          int v = cursor++;
          int n = digits;
          final char[] buf = new char[n];
          while (n > 0) {
            buf[--n] = (char) (v % radix + '0');
            v /= radix;
          }
          return new String(buf);
        }

        public void remove() {
          throw new UnsupportedOperationException();
        }
      };
    }
  };
}

... which can be used as follows:
for (final String val : strings(3, 5)) {
  System.out.println(val);
}

Basically, we generate the numbers in the interval [0, 3^5), where 3 is our radix and 5 our desired string length, and then convert the numbers into ternary form. 0 becomes 00000, 3^5 becomes 100000.


text:
Q: Nested filters in Javascript I have the following nested filters in javascript but returning from the inner filter was not returning users satisfying the role I wanted so I used a different approach. Here is what I have
  let admins = [];
  let customers = [];

  if(users.results){
    users.results.filter(user => {
      user.roles.filter(role => {
        if(role.role.name === 'ADMIN'){
          admins.push(user);
        }
      });
    });
    users.results.filter(user => {
      user.roles.filter(role => {
        if (role.role.name === 'CUSTOMER') {
          customers.push(user);
        }
      });
    });
  }

Example of the payload is
{
            "addresses": [],
            "created_at": "2020-04-18 14:21:55",
            "email": "deliverypersonnel4@mail.com",
            "first_name": "Lucas",
            "id": "5c7f9e0d-4727-416c-b0ce-61bc7542aee4",
            "image": null,
            "is_active": false,
            "is_verified": false,
            "last_name": "DeliveryPersonnel",
            "phone": "2547324738723",
            "roles": [
                {
                    "role": {
                        "description": "Can only access the online shop",
                        "name": "CUSTOMER"
                    }
                },
                {
                    "role": {
                        "description": "Can only access orders for delivery",
                        "name": "DELIVERY_PERSONNEL"
                    }
                }
            ],
            "updated_at": "2020-04-18 14:21:55"
        },
        {
        "addresses": [],
        "created_at": "2020-04-18 14:20:57",
        "email": "testadmin@mail.com",
        "first_name": "Admin",
        "id": "40f32c1e-5f53-41c7-8b78-e4918b05472d",
        "image": null,
        "is_active": false,
        "is_verified": false,
        "last_name": "Test",
        "phone": "254711123456",
        "roles": [
            {
                "role": {
                    "description": "Can create, view & update all records",
                    "name": "ADMIN"
                }
            },
            {
                "role": {
                    "description": "Can only access the online shop",
                    "name": "CUSTOMER"
                }
            }
        ],
        "updated_at": "2020-04-18 14:20:57"
    }

How can I have the testadmin@mail.com in both the admins and customers array and have deliverypersonnel4@mail.com in the customers array without using the array push method.

A: Try filter with complex condition:
let customers = users.filter(user => {
  return user.roles.some(role => role.role.name === 'CUSTOMER')});
let admins = users.filter(user => {
  return user.roles.some(role => role.role.name === 'ADMIN')});

A: I am not sure what result you want. But if you don't want to use push method then you can use the given method.
const admins = users.filter(({roles}) => roles.some(({role: {name}}) => name === 'ADMIN'));
const customers = users.filter(({roles}) => roles.some(({role: {name}}) => name === 'CUSTOMER'));


text:
Q: Feasibility of HAML + PHP/CakePHP Is anyone using a HAML implementation for PHP like phpHaml or pHAML? Both projects have seen no activity for about 2 years, and both are < 1.0. Is it feasible/wise to use HAML for a large PHP application, or is it too immature?
Does anybody have experience with Chaml for CakePHP? I played around with it, and it seems to be really picky about whitespace, which I think might cause a few hiccups in a large project with many developers.
I really want to use HAML or something minimalistic like it, but I don't want it to add another layer of debugging problems. Recommendations are welcome.

A: Oh well, so in the meantime, I did start writing a small site using Chaml, which uses the phpHaml parser. First of all: HAML is so much fun! X-D
Second: phpHaml is still a little buggy. I've had instances where a line like
= $html->link('Something', '/somewhere')

yielded
<?php echo $html->link('Something', '/somewhere'); ?><?php echo $html->link('Something', '/somewhere'); ?>

if the following line was left blank. Inserting something on the following line removed the duplicate. This means you're always required to double check you're actually producing the markup you think you are.
The Chaml plugin is working quite well, I haven't had any particular problems with it. The included SASS parser is not really worth talking about though, it's experimental at best.
Overall, HAML on PHP at this stage does add a slight debugging overhead, so I wouldn't recommend using it to just anybody. It may be worth it if you'd have to type loads and loads of markup otherwise.
I'm currently trying to decide whether diving into the phpHaml parser or switching to Rails is the better decision. ;)

A: My expertise is not with HAML but with CakePHP so I can only answer part of your question. CakePHP is a tightly coupled framework so you either work with it or against it. If you wanted to use a different template engine such as HAML you'd be better with a loosely coupled framework such as Code Igniter or Zend.
For more information see this thread on using Smarty in Code Igniter or Zend - the same principle would apply for using HAML.

A: See: http://haml-to-php.com/related%20work.html. It depends on how much of the HAML features you want to use. Most of them get simple HAML right. But if you also want have quoting and maybe advanced features such as %div{:attr=>"foo_#{ php code }"} all but HAML-TO-PHP fail to my knowledge


text:
Q: flex: cant edit item in Datagrid with override set data method I've a custom itemRenderer for my datagrid. To set the actual data I use the following method:
override public function set data(side:Object):void{
   ...
}

As soon as I use this function the cell doesn't show up any item Editor anymore. Why is that? When I remove this function the itemEditor is working but with the wrong initialization data...
What's the proper way to handle this?
Thanks,
Markus

A: Have u called 'Super' on that method ?

A: Make sure that you also have an itemEditor that is correctly working or that you set the rendererIsEditor property to true and use the renderer as the editor.


text:
Q: Is the coordinate ring of a variety a finitely generated algebra? Let $k$ be an algebraically closed field and let $X$ be a (not necessarily affine) variety over $k$. Is the coordinate ring of $X$ ($k[X]$ or $O_{X}(X)$) always a finitely generated $k$-algebra?

A: Feed google with "variety whose ring of global sections is not finitely generated". One gets An example of a nice variety whose ring of global sections is not finitely generated by Ravi Vakil.


text:
Q: php settings for large uploads (413 error) Using Dropzone.js and the Dropbox API, I'm looking to setup a drag-and-drop web interface that can accept files up to 10G. It works perfectly with files up to ~50M, but fails after that with a 413 Request Entity Too Large error. The sample file I've been trying is 1.5G. I've tried what I know to change for large file uploads, but still doesn't seem to be working. I'm hoping someone can point me in the right direction with a look at my PHP settings.
Here's a rendering of the associated phpinfo(): http://codepen.io/jboneca/pen/bNvEwV
Additional information:

*

*No file is ever stored on our server. It is uploaded (successfully, in most cases) directly to Dropbox.

*File size limitation has been disabled on Dropzone.

*The following settings have been changed, to no avail.upload_max_filesize, post_max_size, max_execution_time, max_input_time, memory_limit. Perhaps they need to be still larger?

A: A few things to note:

*

*When you handle a file upload with php, even if your script does not end up saving the file but only to send it to the Dropbox API -- the way it works is php must write it to a temp location on the server, e.g. /tmp/tempfilename. Therefore your server must have enough space to store the file, even though it's just temporary. Your script then uploads the file via Dropbox API and PHP will automatically clean up/remove the file from the temp location.

*The 413 Request Entity Too Large error typically happens when the post_max_size is not large enough to handle your request, but in your case you might have other issues limiting it as well.

*In my experience from running command line php scripts handling large amounts of data, the php memory limit starts breaking around 1700M-2000M. Meaning, even after setting memory_limit to something much higher, php itself could not handle checking memory limit that large, and fails when memory usage exceeds something around 1800M. (maybe it uses a signed 32-bit int for memory limit? Not sure.)

*I have worked with the combo of Dropzone.js + php file uploads as well, and had no problems uploading files of several hundred MBs. I recommend you to try this: set upload_max_filesize to 1100M, set post_max_size to 1200M, and set memory_limit to 1700M. Now, first try files of 100mb, then 500mb, then 1gb. I believe it will work for all of these sizes. Now adjust each setting higher and see how close you can get to 1.5gb. That's probably the limit of the current php version and server that you have.

*Just FYI, max_execution_time is not your issue if your error was 413 Request Entity Too Large. (you're not even there yet) This is only the time it takes to execute all the lines in your php script. (If you were saving the file on server locally, this time would be in milliseconds even if you upload a 1GB file.) However, since you need to send this file to Dropbox API from your server, it is possible that your request will take too long and over the max_execution_time limit. I believe you will run into problems with this after you solve your current issue with the upload. To solve this, I recommend your http request handling php script to simply add the file to a queue somewhere, and have a separate consumer process that reads from the queue and uploads files to Dropbox. (also probably better UX for your users so they don't have to wait 2x as long)


text:
Q: mysql insert malfunction I can't figure out why this isn't working. It says "note added" but it doesn't actually add it to the database.
<?php

    $notetitle = $_POST['title'];
    $notebody = $_POST['body'];

if ($notetitle && $notebody){
mysql_query("insert into notes values
('$user_id', '', '$subject', '$notetitle', '$note_type' '$notebody')");

echo "Note \"" . $notetitle . "\" added.";
}

?>

A: You missed a comma:
('$user_id', '', '$subject', '$notetitle', '$note_type', '$notebody')");

A: You have some mistakes in your code. use the code below and check it. I have added something more to be sure about your data accuracy:
<?php

$notetitle = $_POST['title'];
$notebody = $_POST['body'];

if ($notetitle != '' && $notebody !='') {
    $myQuery = mysql_query("INSERT INTO notes VALUES
                          ('$user_id', '', '$subject', '$notetitle',
                          '$note_type', '$notebody')");

   // verify your database query and then show the message below
   if (mysql_affected_rows()) {
      echo "Note \"" . $notetitle . "\" added.";
   }
}

?>

Pay attention that you forgot a comma before '$notebody' in your MySQL query.

A: Your SQL query is not quite valid - you also have to add to it the column names which you want to set through INSERT:
mysql_query("insert into notes (id, smth, subject, ... etc) values
('$user_id', '', '$subject', '$notetitle', '$note_type', '$notebody')");

A: If you checked if the insert worked and reported errors on failure then you'd know why it wasn't working....
if ($notetitle && $notebody){
      $qry="insert into notes values
           ('$user_id', '', '$subject', '$notetitle', '$note_type' '$notebody')";
      if (mysql_query($qry)) {
           echo "Note \"" . $notetitle . "\" added.";
      } else {
           print "Failed: $qry\n" . mysql_error();
      }
}

Not handling errors and exceptions is very bad programming. Not declaring your columns in an insert statement is very bad practice. Not using an explicit database handle is messy. Not commenting your code is bad practice.

A: You have missed a comma between "'$note_type' '$notebody'",
In better way you should to write like this:=
    $notetitle = $_POST['title'];
    $notebody = $_POST['body'];

if ($notetitle && $notebody){
mysql_query("insert into notes
set userid='$user_id',
subject = '$subject',
notetitle = '$notetitle',
note_type = '$note_type',
notebody = '$notebody' ");

}

Actually it will not conflict your column name and values. :)


text:
Q: Does high-availability VM for Mac OS X exist? I seek rock-stable, production-worthy virtual machines capability with macOS.
I'm relatively a noob when it comes to VMs. High availability clusters are all the rage, and I can see why. I took over as the sysadmin for an SMB and we have 7 Mac Mini's in the machine room; each one running one thing, each obviously underutilized, and each without redundancy.
If I ran Win services, a good strategy would be to deploy up to 7 instances on a pair of servers in a high availability configuration, active/passive failover, etc., correct? And until Apple changes their mind, that's an impossibility in OS X Land?

A: Yes, high-availability for macOS definitely exists.
As on Windows, you cannot just push some magical button and have any computer with whatever generic software suddenly run in a HA system, being it active/passive or active/active.
The way to setup a HA system depends on the services you want the system to offer. Is it a highly available network storage system you require? - is it a highly available build server? is it a highly available rendering system?
In some cases it is not optimal to use virtual machines at all, but rather use software running bare-metal to implement the highly available services.
In other cases, you can use VMs to have an easier way to implement for example an active/passive fail-over style high availability. This usually comes with some draw backs, but they are the same here as in an Windows environment.
One of the simplest setups here is to have the virtual machine disk itself be stored on a storage system shared by a pair of Mac Minis (or more). The storage system itself needs to be highly available as well. You would then replicate the configuration of the virtual machine between the two Mac Minis, implement a heart beat system and have the passive computer automatically take over when the heart beat stops. Typically this is a type of STONITH, which can be implemented in multiple ways.
A well known industry implementation of such a simple system is the VMware vSphere HA system, where you basically run ESXi on the Mac Minis and use vSphere with vSphere HA to do monitoring and automatic failover. The shared storage system can be implemented in many different ways (although most have drawbacks).

A: We run esxi Bare Metal Hypervisor on Intel Macs, ARM, Dell and other consumer and server grade hardware. All are exceptionally stable, documented and supported.
If you are not into owning the hardware or wish to co-locate it, MacStadium  is the long time vendor of choice for virtualization.
These are all a decade old (except Kubernetes and ARM esxi), so you should check it out... also, don't waste any time on HA software or features initially. Sprinkle that on last of and only if you really, really need it.

A: Amazon Web Services launched Mac EC2 instances three weeks ago. It's not something you can host yourself, but it certainly gives you access to rock-stable production-ready Mac virtual machines.


text:
Q: dynamic radio button creation using handlebars in meteor For a game I am creating,I have an array of objects like this (please ignore the silly effects/results) :
issues = [
{
    uid: 1,
    question: "Should Marijuana be legalized?",
    options: [
        {
            statment: "Yes Please, It is better than alcohol",
            result: "Smokes fill up the skies",
            effect: {
                goldBonus: 0.2,
                Spirituality: 1,
                offenseBonus: -0.5,
                counterIntelBonus: -0.2
            }
        },
        {
            statment: "No it is against the civilized society",
            result: "Jails are full of blazed teens",
            effect: {
                goldBonus: -0.2,
                Spirituality: -1,
                counterIntelBonus: +2
            }
        }
    ]
},
{
    uid: 2,
    question: "Should children be banned from playing in the streets?",
    options: [
        {
            statment: "Yes, they are pests",
            result: "clean efficient traffic free roads",
            effect: {
                goldBonus: 1,
                ironBonus: 1,
                populationBonus: -0.2,
                HDI: -0.5
            }
        },
        {
            statment: "No, children should be free to play wherever they want",
            result: "Roads are full of kids running around playing",
            effect: {
                goldBonus: -0.2,
                HDI: 2
            }
        },
        {
            statment: "Drivers get paid to kidnap kids on roads and deliver to army",
            result: "No kids are found outside their house in the fear of being snatched up by the govt.",
            effect: {
                goldBonus: 0.5,
                populationBonus: -2,
                offenseBonus: 3,
                defenseBonus: 3,
                HDI: -5
            }
        }
    ]
},
]

Based on this array, I am trying to create a radio-button form for every issue in the issues array. The helper function is as follows:
Template.HomePrivateIssues.helpers ({

  issues: function () {
    return issues;
  }

});

And the template is:
<template name = "HomePrivateIssues">

        {{#each issues}}
            <form>

{{question}}

                {{#each options}}
                    <input type = "radio" name = "test" value = "{{this.statement}}" > {{this.statment}}

                {{/each}}
                <input type = "submit">
            </form>
        {{/each}}

</template>

I am running into problems while defining name and value for the forms
simple name = {{this.uid}} or name = "{{this.uid}}" does not seem to work.
if I keep the name or value constant (e.g.: name = "test" value = "obama"), I can simply use ..
Template.HomePrivateIssues.events({
  'submit': function(event, template) {
    var element = template.find('input:radio[name=test]:checked');
    console.log($(element).val());
  }
});

I get obama in my console.
I am at a loss on how to generate the value and name dynamically and pass it to event when the form is submitted.

A: OK first lets change the html.

    {{#each issues}}

{{question}}

            {{#each options}}
            <form>
                <input type="radio" name="test" value="{{this.statment}}">{{this.statment}}
            {{/each}}
            <button id="lol"> Click </button>
        </form>
    {{/each}}

Here we add a Form inside the {{#each options}}
Now we need to change a little bit the event function
  Template.HomePrivateIssues.events({
  'click #lol': function(event, template) {
    event.preventDefault();
    var value = $(":radio[name=test]:checked").val();
    console.log(value)
  }
});

here we just add the event.preventDefault(); here, for more information about preventDefault();.
Try it, it should work


text:
Q: radical expression foil which confuses me So straight to example
$\sqrt{x} = 3-\sqrt{x}$
When squared gives us
$x = (3-\sqrt{x})(3-\sqrt{x})$
Now foil
$x = 9 - 3\sqrt{x} - 3\sqrt{x} + ?$
I don't understand the l part of the foil what should be there . I saw some where that  $-\sqrt{x}-\sqrt{x} = x$  but I dont quite get it, so please explain . Thanks in advance.

A: $\sqrt{x} = 3 - \sqrt{x}$.
Adding $\sqrt{x}$ to both sides:
$2\cdot \sqrt{x} = 3$, then square both sides:
$4x = 9$.
So $x = \dfrac{9}{4}$

A: $(-\sqrt{x})(-\sqrt{x}) = (-\sqrt{x})^2 = (\sqrt{x})^2 = x$.
(Note that this is not the same thing as $-\sqrt{x}-\sqrt{x}$, which would be $-2\sqrt{x}$.)


text:
Q: Disable clicking on markers If one click on a marker, information about the spot (e.g the coordinates) is shown. I want to disable this, so the markers aren't clickable. How can I do that?
I've looked around everywhere but haven't been able to find information about how that can be done.

A: Apparently there are two possible ways to achieve this

*

*by  using the property setClickable(flag:boolean);
see http://code.google.com/apis/maps/documentation/v3/reference.html#Marker

*Remove the listener off the marker. It will look something similar
to this
google.maps.event.addListener(marker, "click", function(etc)
Reference
Also, if you work on the map in Collaborate mode, at the upper right of the left frame (with the locations listed), there's an Edit button. Click it.
Then go to the location you want to remove in the list on the  left and click it to open it's information window on the map (expanding from the droplet-shaped marker). Inside that information box is a "delete" link, and that removes the location.


text:
Q: How to implement recursive "using"/extract template parameters So someone asked a question then deleted it, but I found it an interesting challenge.
They had this weird type, and had run into the problem that Concat and Range were castable to Sequences but were not Sequences (for obvious reasons)
template<unsigned... Is> struct Sequence{};

template<typename... Is> struct Concat{};
template<unsigned... Is> struct Concat<Sequence<Is...>> : public Sequence<Is...> {};
template<unsigned... Is, unsigned... Js, typename... Rest>
struct Concat<Sequence<Is...>, Sequence<Js...>, Rest...>
   : Concat<Sequence<Is..., Js...>, Rest...> {};

So I figured it'd be an interesting challenge to do this right, making everything the same type.
So my first pass at Concat ran into unexpected problems...How on earth does one extract the template parameters for the Sequences? I ended up using a function below:
template <unsigned... Is,unsigned... Js>
constexpr auto concat_results(Sequence<Is...>,Sequence<Js...>) -> Sequence<Is...,Js...>
{
  return Sequence<Is...,Js...>();
}

template <typename seq1,typename seq2>
using Concat = decltype(concat_results(seq1(),seq2()));

Bizarrely, I think that's the shortest way to declare it, though it is a little weird. However, the concat_results could be useful (on references of the sequences) and the type can be useful in other places. Anyone have a better way to do that?
Next up was range, which I did with a recursive struct helper:
template <unsigned N>
struct nrange_helper
{
  using Range = Concat<typename nrange_helper<N-1>::Range,Sequence<N>>;
};

template <>
struct nrange_helper<0>
{
  using Range = Sequence<0>;
};

template <unsigned N>
using Range = typename nrange_helper<N>::Range;

Again, its weird, but it works...but I feel like there should be a better way. Anyone got one?

A: Note: please check out std::integer_sequence, its specialization index_sequence and its make_index_sequence and index_sequence_for facilities.
If you want to declare them yourself, you generally would use inner types:
template <typename, typename> struct Concat;

template <unsigned... Is, unsigned... Js>
struct Concat<Sequence<Is...>,Sequence<Js...>> {
    using type = Sequence<Is..., Js...>;
};

template <unsigned N>
struct Range {
    using type = typename Concat<typename Range<N-1>::type, Sequence<N>>::type;
};

template <> struct Range<0> { using type = Sequence<0>; };

Which can of course be combined to template aliases for a shorter final form:
 template <typename, typename> struct ConcatH;

template <unsigned... Is, unsigned... Js>
struct ConcatH<Sequence<Is...>,Sequence<Js...>> {
    using type = Sequence<Is..., Js...>;
};

template <typename L, typename R>
using Concat = typename ConcatH<L, R>::type;

and:
template <unsigned N>
struct RangeH {
    using type = Concat<typename RangeH<N-1>::type, Sequence<N>>;
};

template <> struct RangeH<0> { using type = Sequence<0>; };

template <unsigned N>
using Range = typename RangeH<N>::type;

However, indeed, this is slightly verbose. Still, there is little cruft here:

*

*baseline declaration

*specialization (to end recursion or limit to "interesting" types)

*alias declaration

on the other hand it's only written once.


text:
Q: Unit test stub for google authenticator barcode scanning using PHPUnit in Laravel Please help me to find out the solution.

*

*Does anyone know how to write a unit test stub using PHPUnit for scanning a barcode?
FYI :
In our application, two-factor authentication used(google authenticator). When users enter a valid username and password next screen displayed with barcode, we scan that barcode using the google-authenticator app on mobile then 6 digit code is generated, which we enter in web application then redirects to the home page.

*How to set a cookie while writing unit test stub for login?

A: *

*Create an abstraction for your 2FA

*Make Google Authenticator the default implementation

*Create a fake implementation that suits your needs. This could be a fixed six digit code that is always valid or you make it configurable

*Swap the default implementation with the fake in your tests

*Test the scenarios you need to test in your login process

*Create a manual test to make sure that your Google Authenticator implementation is actually working

I know this answer is rather abstract, but your question was not very concrete either. If you can provide more details, I'd be happy to go into it.

A: For point 2 :
I am able to set cookies (json encoded array) with requests while unit testing in laravel.
$cookie = ['cookiename' => \Crypt::encryptString(json_encode(array('cookieValue' => 1)))];

  $this->call('post', 'login', [
        'username' => user1,
        'password' => 'test',
        '_token' => csrf_token(),
        'remember'  => 'on',
    ], $cookie)