Duplicate a Random Number function from JS to C#

Question: I got this function in JS
var number = Math.random() + "";
var r = number * 10000000000000;

I need the 100% same function in C# as I'm new to C# I'm having hard time getting a function for this in C# for people who are familer or not with JS Math.random() will generate a number between 0 to 1 similar to this (0.7740926130209118, 0.6105941028799862) and then I would like to multiply by 10000000000000 and we get something like "2647182801738.3813 <---This is what I need.
I thought about creating a 13 digits random number and another 4 digit random number and just add it like 13 digit + . + 4 digits. This of course is not ideal but I'm having issues with it as well.
Random random = new Random(); int randomNumber = random.Next(1000000000000, 9999999999999);

will give me errors about int, What I understand is I should use long? but when I change int to long it still looks like random function itself is INT? Well I'm already confused of what I have found online, So It will be great if you can help with this one and explain how  does it work.
Comment: Whatever approach you take, make sure you keep the same instance of Random rather than creating a new Random object every time as that won't generate a series of very random numbers for you.
Answer: Haven't tested but sounds like you need:
 Random random = new Random();

 long r = (long)(random.NextDouble() * 10000000000000);

Answer: If you want an exact port, go for something like:
var number = (new Random()).NextDouble() * 10000000000000;

Answer: C# also has a var :)
using System;

public class Test
{
        public static void Main()
        {
           Random randObj = new Random();
           var number = randObj.NextDouble( ) * 10000000000000;
           Console.WriteLine( number );
        }
}

...
input: no
output:
6426401076105.61


UE4 - Can't connect Unreal Live link with iPhone X Live Link Face app?

Question: I try to connect the iPhone X app - Live Link Face with UE4 but I have a problem. I connect everything from the tutorial and from Epic docs but still have a problem. Live link subject name doesn't recognize my iPhone device. I put the IP address from my pc in-app but noting.
I'm using Windows 10, Face AR SAMPLE - default project from Epic Games - Learn category for Live Link Face app.
Answer: I was encountered the same problem in windows 10 until I changed my network profile from "Public" -> "Private" and then live link recognized my iPhone all in sudden!
Answer: I just got it to work after trying for like 5 hours, haha
Here are some things that helped:
-Windows 10 turning Firewalls off
-Public connection --> Private
-the IP address on my phone was slightly different than the one on my computer, even though both were on the same Wifi connection. On my phone/Livelink app, I entered in the IP address of my computer.
-on my computer /Unreal, go into  Edit>Project Settings>UDP Messaging and then enter in the same IP address under "Unicast Endpoint" with :0 at the end
I also tried adding in :11111, i cant remember which worked haha
good luck!
Answer: I turned off the firewall on the private network


You don't have permission to access [ Apache + CentOS 6.3 ]

Question: If I paste the code from a file into index.html and try to access it from browser is working BUT if I try to transfer the file with WinSCP into /var/www/html directory I get "403 Forbidden; You don't have permission to access". I also tried to copy the file with root login or a user made without root access + chown the /var/www/html directory to root, apache, nothing worked. What could be the problem?
Comment: In general on CentOS: SELinux security contexts. Try for instance [`restorecon -R /var/www/html/`](https://linux.die.net/man/8/restorecon)
Comment: It worked! thanks, can u please reply as an answer so I can mark as the solution for this problem.
Answer: Frequently such problems find their origin in SELinux security context violations.
Try for instance restorecon -R /var/www/html/
Answer: Edit /etc/httpd/conf/httpd.conf file. Add the below code.
<Directory "path">
  #Options FollowSymLinks
  Options Indexes FollowSymLinks Includes ExecCGI
  AllowOverride None
  Allow from all
</Directory>

Then, restart httpd.


Is there any other way to prove this fact? (non-existence of slowest diverging series)

Question: Let $a_n>0$ and $S_n=\sum_{k=1}^{n}a_n$. If $\lim_{n \rightarrow \infty}S_n = +\infty$, then $\sum_{n=1}^{\infty}\frac{a_n}{S_n}=+\infty$. I think this is an important example because it tells us that there exists no series which diverge slowest. So I want to verify this fact in different aspect.
I know a method which uses Cauchy's Theorem. For any $n \in \bf N$ , choose a sufficiently large $p \in \bf{N}$. we have $$\sum_{k=n+1}^{n+p}\frac{a_k}{S_k}\geq \frac{S_{n+p}-S_{n}}{S_{n+p}}\geq \frac{1}{2}$$

Is there any other approach to it? Thanks very much.
Comment: If you just want to prove that there is no slowest diverging series, you can see that you can actually choose the increasing sequence $S_n$, and define $a_n=S_n-S_{n-1}$. Then, for any sequence $S_n$ you can get the slower diverging sequence $\sqrt{S_n}$.
Comment: That's probably the simplist way. See [this](http://math.stackexchange.com/questions/388898/divergent-series-of-positive-numbers/388902) also (I assume this is the argument you're using).
Comment: Is [that](http://math.stackexchange.com/questions/808964/divergence-of-sum-k-1n-fraca-ns-n-where-s-n-sum-k-1n-a-k-to/808995#808995) answer your question?
Answer: First : $a_n= S_n - S_{n-1}$
Let $U_n$ be : $U_n = \frac{S_n- S_{n-1}}{S_n} = 1 - \frac{S_{n-1}}{S_n}$
Then : $\ln(S_n) -\ln(S_{n-1}) = -\ln(1-U_n)$
Suppose the series of general term $(U_n)$ converges:
$\implies (U_n) \rightarrow 0$
$\implies$ $\ln(S_n) - \ln(S_{n-1}) = U_n + o(U_n) $
It means that $( \ln(S_n) - \ln(S_{n-1}) )$ is the term of a convergent series, thus implying that $(S_n)$ is a converging sequence, which is absurd.
Hence the series of general term $(U_n)$ diverges, always.
Now one interesting question is:
 what c does make $U_n(c) = \frac{a_n}{S_n^c}$ converge? You know that $c \geq 1$ , but is it the inf?
Comment: Insulting everyone for an opinion of one person is neither productive, nor helpful, nor it stimulates upvotes. If you suspect that foul play is involved, you can always flag your answer for moderator attention.
Comment: Downvotes and no comments, classic math.exchange. Deontology still not a thing here, shameful really . The guy who pointed to the proof of op's very result got 4 upvotes for his comment, I give another solution and a generalization of his example and I get 2 downvotes. You guys actually achieve to turn maths into mediocrity, I have to say I'm baffled but not positively
Comment: And what's the point of downvoting an answer if there is not one single information about why. Just what's the point.. And you don't even seem to find it the most troubling thing altogether, that comforts me about the seriousness of this community. If this site is not about pedagogy and emulation, then it's useless just like downvoting an answer with not a single explanation. I did not believe it was possible to disgust me of mathematical material, but this community actually achieved that. That's not how I 'exchange' about math with someone, I leave that to all of you
Comment: Note that upvotes on *comments* are very different from upvotes on *answers*. Also, I think the reason that comment was upvoted was to indicate agreement with the claim "that's probably the simplest way".


Find the exact value of $\cot(202.5^\circ)$

Question: As the title states.
I've hardly touched trig before, and finally wrapped my head around how to find $\displaystyle\cos(225^\circ), \tan(405^\circ),$ etc, but I don't get how to find $\displaystyle\cot(202.5^\circ)$.
Please help explain very clearly.
Please help explain very clearly.
Comment: Degrees or radians?
Answer: $$\cot(202.5^0) = \cot(180^0+22.5^0) = \cot (22.5^0)$$
Now Calculate value of $\displaystyle \tan (22.5^0)$
Using $$\displaystyle \tan(2A) = \frac{2\tan A}{1-\tan^2 A}\;,$$ Put $A=22.5^0$
We get $$\displaystyle \tan (45^0) = \frac{2\tan (22.5^0)}{1-\tan^2(22.5^0)}\Rightarrow 2\tan(22.5^0)=1-\tan^2(22.5^0)$$
So we get $$\tan^2(22.5^0)+2\tan(22.5^0)+1 = 2\Rightarrow \left[1+\tan(22.5^0)\right]^2=(\sqrt{2})^2$$
So we get $$\displaystyle 1+\tan(22.5^0) = \pm \sqrt{2}$$
So we get $$\displaystyle \tan(22.5^0) = \sqrt{2}-1$$ bcz $\tan(22.5^0)>0$
So we get $$\displaystyle \cot(22.5^0) = \frac{1}{\tan(22.5^0)} = \frac{1}{\sqrt{2}-1}\times \frac{\sqrt{2}+1}{\sqrt{2}+1} = \sqrt{2}+1$$
Comment: Just what I needed, thanks. Sorry: Can you explain the 2tan(22.50)=1−tan2(22.50) part for me?
Comment: Here I have Used Double angle formula.
Comment: I see that. I mean how you transitioned to that step. Give me a moment, let me look at it again...
Comment: Here I have Used the formula $a^2+b^2+2ab = (a+b)^2\;,$ Like for $\tan^2(22.5^0)+1+2\tan^2(22.5^0) = (\tan(22.5^0)+1)^2$
Comment: I mean the step before that. How you got from  tan(45)=2tan(22.5)/1−tan2(22.5)
⇒2tan(22.5)=1−tan2(22.5)
Comment: Actually Here I have used double angle formula $\displaystyle \tan(2A) = \frac{2\tan A}{1-\tan^2 A}\;,$ Then put $A=22.5^0$ and then cross multiply.
Comment: SORRY! I just remembered tan 45 = 1, that's how. I was confused where the tan 45 had gone, not about the formulas and stuff. Thank you for this explanation!
Answer: HINT:
$$\cot A=\dfrac{2\cos^2A}{2\sin A\cos A}=\dfrac{1+\cos2A}{\sin2A}$$
Now set $A=202.5^\circ$
$2A=405^\circ=360^\circ+45^\circ\implies\cos2A=\cdots=\cos45^\circ\dfrac1{\sqrt2}$
Can you find $\sin2A?$
Comment: @mathflair, How about this?
Answer: If you want to compute it by hand you could use the $\cot z$ series,
$$\sum_{n=0}^\infty\frac{(-1)^n 2^{2n} B_{2n} z^{2n-1}}{(2n!)}$$
Where $B_{2n}$ are Bernoulli numbers. This only works in radians so convert $202.5$ degrees to radians and do a numerical approximation.
It will be pretty accurate (not exact though). Bernoulli numbers are also hard to compute so you can compute a very accurate cosine (using the series) of $202.5$ degrees and divide it by a computation of a very accurate sine of $202.5$ degrees using the series to get a better answer.
Remember convert your degrees to radians.
Answer: $\cot 202.5^0 = \cot 22.5 $, in third quadrant. Recognizing half of $45^0$ you are going to need tan of half angle formula.
Denoting tan full angle by caps, $ T = \dfrac{2 t }{1-t^2} \implies t = (\sqrt{ 1+T}-1 ) , \tan 22.5^0 = \sqrt 2 -1$ where we chose positive value from  $\pm$ in third quadrant...and the required cot is its reciprocal:
$$ \cot 22.5^0 = \sqrt 2 +1.$$


Problem with conditional Probability with multiple conditions

Question: I have classification setup with $r$ classes and three random variables:

$T$: true category
$F^A$: category assigned by the (fallible) classifier "A"
$F^B$: category assigned by the (fallible) classifier "B"

For these, I have the following information:

$p_i := P(T = i) \quad (i \in \{1, \ldots, r\})$
$c^A_{ik} := P(F^A = k|T = i) \quad (i \in \{1, \ldots, r\}, \ k \in \{1, \ldots, r\})$
$c^{B|A}_{kj} := P(F^B = j|F^A = k) \quad (j \in \{1, \ldots, r\}, \ k \in \{1, \ldots, r\})$

As a result, I have
$$
\pi^A_k := P(F^A = k) = \sum_{i = 1}^{r}{P(T = i) \, P(F^A = k|T = i)} = \sum_{i = 1}^{r}{p_i \ c^A_{ik}}
$$
and
$$
\pi^B_j := P(F^B = j) = \sum_{k = 1}^{r}{P(F^A = k) \, P(F^B = j|F^A = k)} = \sum_{k = 1}^{r}{\pi^A_k \ c^{B|A}_{kj}}\\ = \sum_{k = 1}^{r}{\sum_{i = 1}^{r}{p_i \ c^A_{ik}} \ c^{B|A}_{kj}} = \sum_{i = 1}^{r}{p_i \ \sum_{k = 1}^{r}{c^A_{ik}} \ c^{B|A}_{kj}}\\[30pt]
$$
With vectors $p = (p_1, ..., p_r)^T$, $\pi^A = (\pi^A_1, ..., \pi^A_r)^T$, $\pi^B = (\pi^B_1, ..., \pi^B_r)^T$, and matrices $C^A = (c^A_{ik})_{1 \leq i, k \leq r}$ and $C^{B|A} = (c^{B|A}_{kj})_{1 \leq k, j \leq r}$, the above expressions are equivalent to
$$
(\pi^A)^T = p^T \, C^A \quad \text{and} \quad (\pi^B)^T = (\pi^A)^T \, C^{B|A} \, = p^T \, C^A \, C^{B|A}
$$
So far, so good. Quite simple stuff. Now, I want to compute $c^B_{ij} := P(F^B = j|T = i)$. Using the law of total probability and the definition of conditional probabilities, I get
$$
P(F^B = j | T = i) = \sum_{k = 1}^{r}{P(F^B = j | F^A = k \wedge T = i) \, P(F^A = k|T = i)}.
$$
From simulations (and intuition, because of the last matrix product of $(\pi^B)^T$), I concluded something slightly different:
$$
P(F^B = j | T = i) = \sum_{k = 1}^{r}{P(F^B = j | F^A = k) \, P(F^A = k|T = i)}.
$$
The big question here: why is $P(F^B = j | F^A = k \wedge T = i) = P(F^B = j | F^A = k)$? The most simple answer would be that $T$ is independent of $F^A$ and $F^B$, but this is usually not true. What other reasons could there be? And how can I prove it? The sum expression of $\pi^B_j$ (and the matrix expression of $\pi^B$) is not sufficient (, right?).
Maybe you could provide me with links to some publications that already dealt with that problem.
Answer: The problem here is that your information is insufficient to solve the problem, since you have not specified the statistical relationship between $F^B$ and $T$, conditional on $F^A$.  If you are willing to assume conditional independence then you have:
$$F^B \bot \text{ } T | F_A \quad \quad \iff \quad \quad \mathbb{P}(F^B=b |F^A=a) = \mathbb{P}(F^B=b|F^A=a, T=t)$$
In other words, making the probability equation you are using in your analysis  is equivalent to assuming that the random variables $F^B$ and $T$ are conditionally independent given $F^A$.  This means that once you already know $F^A$, your knowledge of the behaviour of $F^B$ is not affected by the true state $T$.  If this is a reasonable assumption in your analysis then the use of that equation is acceptable.


KeyError when trying to search through list of dictionaries in JSON

Question: Im trying to search for a dict key in a JSON file which looks like this:
[{"1.0": {"name": "Name", "message": "Message"}},
 {"69.0": {"name": "F.Z", "message": "Dggl"}}
]

I am using :
def main(id:float):
   for i in output_json:
     if(i["id"]==id):
         return(i["message"],i["name"])

to search through the JSON file but it gives me a key error over 'id'.
I want the output to be the contents of the dictionary whose key I have inputted.
Comment: Where is the `id` key in your dictionaries?
Answer: There's no id key in your dictionaries. The numbers are the keys of the first level of dictionaries, so you need to test if it exists as a key, which you can do with in.
You need to convert id to a string, since the keys of your dictionaries are strings, not floats.
def main(id: float):
    key = str(id)
    for d in output_json:
        if key in d:
            return d[key]['message'], d[key]['name']


combining multiple .js files into one in a build process

Question: Any tips on combining multiple .js files into 1 (for a build process).
Will yuicompressor do this?
Comment: Follow-up question: any tips on re-writing multiple script tags into one?
Answer: YUI Compressor can do this very easily, just send in the file names into YUI as arguments and it will output them as one file.
For example

> yuicompressor-2.4.2 file1.js file2.js file3.js -o combined.min.js
Comment: Doesn't work here with YUI compressor 2.4.8, only the last file is taken into account.
Comment: Nice.  I didn't know YUI could handle more than one file at once.
Comment: this works : `cat *.js | yuicompressor-2.4.2 --type js -o combined.min.js`  and to choose the proper order
`cat file1.js file2.js file3.js | yuicompressor-2.4.2 --type js -o combined.min.js`
Answer: There's always the old standby (without compression like YUI compressor) cat file1.js file2.js > newfile.js
Comment: Doing this as the first command and then the yuicompressor-2.4.2 file1.js file2.js file3.js -o combined.min.js seems to be a winning combination.
Answer: This worked for me
cat file1.js file2.js file3.js | yuicompressor-2.4.2 --type js -o combined.min.js

And if order is not important
cat *.js | yuicompressor-2.4.2 --type js -o combined.min.js

Answer: If doesn't work
yui-compressor file1.js file2.js file3.js -o combined.min.js

try this:
for file in file1.js file2.js file3.js
do
  yui-compressor $file >> combined.min.js
done


Flutter - Take a photo

Question: When I tap on a GestureDetector it opens a dialog where I am able to select, if I want to take the picture from the gallery or to make a photo on my own (the plugin). But my problem is when I click on one of the buttons on the dialog, the dialog pops up again and only after that, it's possible to take a picture from the camera or the gallery.
It would be great, if someone could help me with this problem.
This is the GestureDetector:
GestureDetector(
              child: Container(
                child: (_image == null
                  ? CircleAvatar(child: Icon(Icons.photo))
                  : FileImage(_image)
                )
              ),
              onTap: () async{
                switch(await dialogs.takePhoto(context)){
                  case "take":
                    getImage(ImageSource.camera);
                    break;
                  case "pick":
                    getImage(ImageSource.gallery);
                    break;
                }
              },
            )

The call dialogs.takePhoto(context) ends here:
takePhoto(BuildContext context){
  return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext ctxt){
        return AlertDialog(
          title: Text("Change Photo"),
          content: Container(
            child: Column(
              children: <Widget>[
                InkWell(
                  child: Text("Take photo"),
                  onTap: ()=> Navigator.pop(ctxt, "take"),
                ),
                InkWell(
                  child: Text("Pick photo"),
                  onTap: ()=> Navigator.pop(ctxt, "pick"),
                ),

              ],
            ),
          ),
          actions: <Widget>[
            FlatButton(
                child: Text(
                  "Abort"
                ),
                onPressed: ()=>Navigator.pop(ctxt),
            )
          ],
        );
      }
  );
}

This is an example:
Thanks in advance !
SOLUTION
Found the solution exactly the moment where I clicked on the submit button. The problem was that I called the function to pick the image twice XD.
Comment: You can answer it by separately tapping `answer this question`
Answer: Found the solution exactly the moment where I clicked on the submit button. The problem was that I called the function to pick the image twice XD.

Flutter - Take a photo


Ajuste do button bootstrap css

Question: Estou tentando acertar a altura de um button no formulário, mas ele aparece muito alto em relação aos campos:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<form>

  Categoria:
    <input class="form-control" type="text" name="cat">

  Valor:
    <input class="form-control" type="text" name="valor">

  <button class="btn btn-primary form-control" type="submit">
      Gravar</button>

</form>
Comment: tente postar o código todo
Answer: Primeiro, você está não está usando Bootstrap corretamente.
As classes de coluna, class="col-{xs, sm, md, lg}-{1-12}, em princípio deveriam ser usadas dentro de linhas, class="row", mas esse isso é o de menos.
A ideia do Bootstrap é criar um framework responsivo com foco na ideia de mobile first, ou seja, a ideia central é que você pense em aparelhos móveis primeiro, desta forma, a classe col-xs-* quer dizer eXtra Small (extra pequeno), se referindo à tela. col-sm-* quer dizer small (pequeno). col-md-*, medium (médio). col-lg-*, large (grande). Bem, mas isso se você não estiver pensando somente em dar suporte aos desktop.
Outra coisa é, os botões, incluindo os input tipo button e submit, têm suas próprias classes e form-control não é uma delas.

        Categoria: <input class="form-control" type="text" name="cat">

        Valor: <input class="form-control input-md" type="text" name="valor">

        <button class="btn btn-primary btn-md" type="submit"> Gravar</button>

Exemplo no JSFiddle
Answer: Isso está acontecendo porque o botão está sem label, coloque alguma que já vai resolver o problema:
Clique em Executar e depois em Página Toda para ver como vai ficar na visualização que você postou na imagem.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<form>

  Categoria:
    <input class="form-control" type="text" name="cat">

  Valor:
    <input class="form-control" type="text" name="valor">

  Gravar
    <button class="btn btn-primary form-control" type="submit"> Gravar</button>

</form>
Comment: Sua resposta não está correta. Botões não precisam de *label*, se precisassem seriam *self-closing tags* como os *input*. O que acontece é que ele colocou a classe `form-control`, usada em `input` no `button`.
Comment: Obrigado, Tony Montana. O form-control no button, foi uma tentativa estúpida para acertar o alinhamento do objeto. Colocar o label no button, também não resolve. Eu desenvolvo aplicativos para web, claro que a questão de ser responsivo é importante, mas a principio os forms serão utiiizados em pcs.

Ajuste do button bootstrap css


Angular shows random image order but it should't

Question: I try to show some images on  a single page in a strict order. The images comes from a NodeJs web server as ArrayBuffer.
This is the recommended version but isn't working. The order of images is random at every page refresh:
categories = ['hero-nature', 'hero-portrait', 'hero-commercial', 'hero-panorama'];
heroesArray: any = [];
for (let category of this.categories) {
    this.fileService.getPhotos(category).subscribe((res: any) => {
        const blob = res as Blob;
        const reader = new FileReader();
        reader.onload = () => {
            this.heroesArray.push(reader.result);
        };
        reader.readAsDataURL(blob);
    });
}

Finally I figured out a working solution:
categories = ['hero-nature', 'hero-portrait', 'hero-commercial', 'hero-panorama'];
heroesArray: any = [];
const images$: Observable<ArrayBuffer>[] = [];
for (let category of this.categories) {
    images$.push(this.fileService.getPhotos(category));
}
concat(...images$).subscribe((res: any) => {
    const blob = res as Blob;
    const reader = new FileReader();
    reader.onload = () => {
        this.heroesArray.push(reader.result);
    };
    reader.readAsDataURL(blob);
});

However the second approach has impact on webpage downloading speed.
Can anyone explain what is going on in the first example?
And what will be a better solution?
Answer: In your first example you're pushing only when the image is loaded but there is no order on when the each image is loaded. (A bigger image will take longer to load for example).
A better solution would be to have a preallocated array.
categories = ['hero-nature', 'hero-portrait', 'hero-commercial', 'hero-panorama'];
heroesArray: any = new Array(this.categories.length);
for (let [i,category] of this.categories.entries()) {
    this.fileService.getPhotos(category).subscribe((res: any) => {
        const blob = res as Blob;
        const reader = new FileReader();
        reader.onload = () => {
            this.heroesArray[i] = reader.result;
        };
        reader.readAsDataURL(blob);
    });
}

Here, you see that the index is determined by the initial order, not the order by which each image has been loaded.


guard in angular how can I get value from auth.service.ts (user login or not)

Question: I use canActivate in history.guard and how can I check if the user login or not!
the value which I console always return false!
Do I need to create a new function in auth.service or just edit in history.guard ? Is there any way instead of using subscribe ??
auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs/Subject';
import { ApiService, VERSION, ENDPOINT } from '../api/api.service';
import { Observable, BehaviorSubject } from 'rxjs';

@Injectable()
export class AuthService {

  logger = new BehaviorSubject<Object>(false);
  referralRoute: string;

  constructor(
    private router: Router,
    private api: ApiService
  ) {
  }

  logout() {
    localStorage.removeItem('access-token');
    localStorage.removeItem('uid');
    localStorage.removeItem('client');
    this.redirectToLogin();
    this.logger.next(false);
  }

  postLogin(body: any) {
    this.api.get(['token.json'], {}).subscribe(
      (res: any) => {
        localStorage.setItem('access-token', res['access-token']);
        localStorage.setItem('uid', res['uid']);
        localStorage.setItem('client', res['client']);
        this.logger.next(true);
        this.redirectToPrevStep();
      },
      (err) => {
        this.logger.next(err);
      });
  }

  checkLogin(body: any) {
    this.api.get([VERSION, ENDPOINT.checkLogin], {}).subscribe(
      (res: any) => {
        this.logger.next(true);
      },
      (err) => {
        this.logger.next(err);
      });
  }

  checkUserLogin() {
    const isLogin = !!localStorage.getItem('JWT_TOKEN');
    if (isLogin) {
      this.logger.next(true);
    } else {
      this.logger.next(false);
    }
  }

  subscribeLogger(): Observable<Object> {
    return this.logger.asObservable();
  }

  isAuthenticated() {
    const token = localStorage.getItem('access-token');
    let isAuthenticated: boolean;
    if (this.isTokenInvalid()) {
      localStorage.removeItem('access-token');
      isAuthenticated = false;
    } else {
      isAuthenticated = true;
    }
    return isAuthenticated;
  }

  getUserInfo() {
    const token = localStorage.getItem('access-token');
    // let userInfo = this.jwtHelper.decodeToken(token);
    return  {};
    //   this.jwtHelper.decodeToken(token),
    //   this.jwtHelper.getTokenExpirationDate(token),
    //   this.jwtHelper.isTokenExpired(token)
    // );
  }

  isTokenInvalid() {
    const token = localStorage.getItem('access-token');
    if (!token) {
      return true
    } else {
      // this.api.setHeaders(token);
      return false;
    }
  }

  /**
   * Helper method for set up referral route, enable useful redirect after login
   * @method setRoute
   * @param  {string} route Route as defined in app.routes, eg. /user/1
   */
  setRoute(route: string): void {
    this.referralRoute = route;
  }

  redirectToPrevStep() {
    const route = this.referralRoute ? this.referralRoute : '/';
    this.router.navigateByUrl(route);
  }

  redirectToLogin(current: string = '/') {
    // Store current url as referral and use latter for login redirection
    this.setRoute(current);
    window.scroll(0, 0);
    this.router.navigate(['/auth/login']);
  }

}

history.guard.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../../core/service/auth/auth.service';

@Injectable({ providedIn: 'root' })
export class HistoryGuard implements CanActivate {
  checkUserLogin: boolean;
    constructor(
        private router: Router,
        private auth: AuthService
    ) {}
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const checkUserLogin = this.auth.subscribeLogger().subscribe(
          (data: any) => {
            this.checkUserLogin = data;
          }
        );
        if (!this.checkUserLogin) {
          return this.router.navigate(['mypage']);
        }
        else {
          return this.checkUserLogin;
        }
    }
}

history.module.ts
import { NgModule } from '@angular/core';
import { HistoryComponent } from './history.component';
import { HistoryItemComponent } from './history-item/history-item.component';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';
import { HistoryGuard } from  './history.guard';

const routes: Routes = [
  {
    path: '',
    component: HistoryComponent,
    canActivate: [HistoryGuard]
  },
  {
    path: ':id',
    component: HistoryItemComponent,
    canActivate: [HistoryGuard]
  }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [HistoryComponent, HistoryItemComponent]
})
export class HistoryModule { }

Comment: You can just return Observable to your canActivate guard instead of a boolean.
Comment: can you show the replacement ??
Comment: Sure, in a minute.
Comment: I test on localhost with stiffness JWT_TOKEN inject into application (dev mode)
Answer: This is how your canActivate should look like:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  return this.auth.subscribeLogger().pipe(
    tap(login => {
      if(!login) {
        this.router.navigate(['mypage']); // If user is not logged in, just navigate away
      }
    })
  );
 }

Comment: what is tap mean ?? can not find it!
Comment: It's an `rxjs` operator. `import { tap } from 'rxjs/operators'`. https://rxjs-dev.firebaseapp.com/api/operators/tap
Answer: Hi this how I implemented AuthGuard, you can check just if in local storage is a JWT token or not, because on logout you should delete jwt token from localStorage and that's it
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

// Auth service

isLoggedIn() {
    return Boolean(this.getToken());
}

getToken() {
    return this.localStorage$.retrieve('authenticationToken');
}

logout() {
    this.localStorage$.clear('authenticationtoken');
}

Comment: if in localStorage there is no jwt token you should navigate to /mypage and then return false
`this.router.navigate(['/mypage']);
return false;
`
Comment: can I use it instead ?`canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.token === localStorage.getItem('JWT_TOKEN')) {
      if (this.auth.isAuthenticated()) {
       console.log("tokenba",this.token)
        return true;
      } else {
        return this.router.navigate(['mypage']);
      }
    }
  }`
Comment: I get token buy localstorage.getitem('JWT_TOKEN')


Showing sparkine in tree jqgrid

Question: I need to show a line graph inside a jqgrid. So, I come across this question
Here in this question, it is shown how easily we can show sparkline graph in jqgrid cell. I used the same thing and it worked but
the problem is mine is a tree grid. So, here only parent node are populating not the child nodes.
This is my code
 loadComplete: function () {
                var ts = this;
                if (ts.p.reccount === 0) {
                    $(this).hide();
                    emptyMsgDiv.show();
                } else {
                    $(this).show();
                    emptyMsgDiv.hide();
                }
                var index = getColumnIndexByName('col_chart');
                $('tr.jqgrow td:nth-child('+(index+1)+')').each(function(index, value) {
                var ar;
                    try {
                        var chartData = [];
                        var height;
                        height = $(this.innerHTML.split(','));
                        for(i=0;i<height.length;i++){
                            chartData.push(height[i]);

                        }

                        ar = chartData;
                        var largest = Math.max.apply(Math, ar);
                        if (ar && ar.length>0) {
                            console.log(ar);
                        $(this).sparkline(ar,{
                        type: 'line',

                        tooltipFormat: "{{y:value}}",});
                        }
                    } catch(e) { alert (true);}
                });
            }

I checked by using console everything is working fine as expected only chart is not shown.
Can anyone please tell me what is wrong here?
Answer: I suppose that sparkline don't work on hidden nodes. I'd suggest you to call sparkline inside of treeGridAfterExpandRow callback or jqGridTreeGridAfterExpandNode event handler. Another possible problem could exist if you loads the nodes dynamically from the server. In the case you should include call of sparkline inside of loadComplete callback or jqGridLoadComplete event.
UPDATED: The modification of your demo http://jsfiddle.net/adishri22/98yxbjgc/ could be the following: https://jsfiddle.net/OlegKi/98yxbjgc/3/
I used the following code of treeGridAfterExpandRow:
treeGridAfterExpandRow: function (options) {
    var $self = $(this), p = $self.jqGrid("getGridParam"),
        iCol = p.iColByName.sl, item, i, tr, $td, rowid,
        idName = p.localReader.id,
        children = $self.jqGrid("getNodeChildren", options.item);
    for (i = 0; i < children.length; i++) {
        item = children[i];
        rowid = item[idName];
        tr = $self.jqGrid("getGridRowById", rowid);
        $td = $.jgrid.getDataFieldOfCell.call(this, tr, iCol);
        try {
            $td.sparkline($.parseJSON(item.sl));
        } catch(e) {}
    }
}

Comment: sorry for not adding the whole code at once. I am calling it inside loadComplete only. I added the new code as well. I will check on the other solution you provide
Comment: @shv22: The problem can't be analysed based on the code fragment. It's unclear, whether the same problem exist with TreeGrid and local data or you load nodes on demand. It's unclear which version of jqGrid you use, which jQuery, jQuery UI/Bootstrap, sparkline, ... It's better you prepare the demo, which reproduces the problem. One could see the problem, debug and analyse it.
Comment: Hi I created a demo http://jsfiddle.net/adishri22/98yxbjgc/ here with same problem I am having
Comment: @shv22: Small remark. I suppose that you don't know, that the searching engine (even Google) uses voting counter in ordering of searching results. It means that it's difficult to find the information by searching if the answer/question has low voting. You have right to vote about 30 answers **per day** (see [here](https://meta.stackexchange.com/a/5213/147495)), but during 1 year and 9 months you voted only 27 times. Please use your right and **vote any information on stackoverflow, which you find helpful**, if you want help other people to find the information.
Comment: from now onwards I will follow this

Showing sparkine in tree jqgrid


jQuery Time mouse is over element (Hover)

Question: i have a hover event attached to a few links and when you go over it a box appears.
Is there a way that i can make the hover event only trigger if the mouse has been over the link for more then 500 ms? So currently as soon as the mouse goes over the link the box appears but i want it to only appear if the mouse has been over the box for 500 ms or longer.
Answer: <code>var myTimeout;
$('#mylink').mouseenter(function() {
    myTimeout = setTimeout(function() {
        //do stuff
    }, 500);
}).mouseleave(function() {
    clearTimeout(myTimeout);
});
</code>
Answer: Here's a great jQuery plugin that helps you decide if the mouse movement is appropriate for initiating an action.
It is called hoverIntent


With logistic regression, how does one choose a number of predictors when preregistering a study?

Question: Harrell's Regression Modelling Strategies suggests that the number of predictors should not exceed $m/10$, $m/15$ or $m/20$.* For logistic regression $m$ is $\textrm{min}(n_1, n_2)$, where $n_1$ and $n_2$ are the numbers in the two categories you are predicting. (E.g. number of deaths, number of survivals.)
If you are preregistering a study, so that you do not actually know $n_1$ and $n_2$, how should you proceed? Should you use domain knowledge to take a guess? What about cases where the study is the first of its kind, so that all previous knowledge is anecdotal?
*Presumably 10, 15 or 20 depending on how careful you want to be to avoid overfitting, although it's not spelled out.
Edit: actually, how is it even legitimate to look at $n_1$ and $n_2$? Surely this contributes to the forking paths problem?
Comment: Your precision for most estimates from this study will depend on $\min(n1,n2)$ more than anything else.  Is it possible to design your study to continue until you have a certain number of each event?
Comment: Thank you for pointing out the article on the forking paths problem.  Very good.
Answer: The forking paths problem is one whereby we exaggerate the statistical significance of a result when it entailed one among multiple possible analyses.  Attending to this problem certainly matters.  But so, often times, does statistical power.  Examining n1 and n2 (learning how narrow is the outcome distribution) and finding that the min(n1,n2) is rather large may lead you to inclusion of more predictors and conduct of more analyses than if you had assumed min(n1,n2) to be very small.  You have the ability to do something to correct for those multiple comparisons that you find that data enable.  You can adjust alpha according to the methods of Bonferroni, Benjamini, Hochberg, and so on.  Or you can simply reduce alpha to a level you and colleagues find reasonable.  In this way you can hopefully strike a balance between control of Type I and Type II error.
Comment: Could you expand on how you would adjust alpha in this specific case?
Comment: There is no single correct way.  Some excellent commentary:  https://stats.stackexchange.com/questions/630316/how-many-p-value-observations-do-you-think-are-required-before-doing-fdr-correct/630324#630324 .  I also recommend Geoffrey Keppel's commentary in Design and Analysis:  A Researcher's Handbook (Prentice Hall).


Como comparar 2 HashMaps diferentes em Java

Question: Eu tenho 2 Strings que converto para HashMaps, a primeira é uma entrada que o usuário dá ao aplicativo. A segunda é um Array que contém um monte de palavras.
Eu preciso comparar ambos os HashMaps para verificar se a entrada pode ser reorganizada para corresponder a uma das palavras do Array. Não há necessidade de usar cada char da entrada do usuário para o sistema, pode haver alguma sobra de char do primeiro HashMap, mas eu preciso ter certeza de que eles podem combinar uma das palavras do Array (o segundo HashMap).
Esse é o código para criar o primeiro HashMap:
String normalizedInputWord = normalizeString(inputWord);

Map<Character, Integer> countDuplicateMapInput = new HashMap<>();

char[] charInputArray = normalizedInputWord.toCharArray();

for (char c: charInputArray) {
    if (countDuplicateMapInput.containsKey(c)) {
        countDuplicateMapInput.put(c, countDuplicateMapInput.get(c) + 1);
    } else {
        countDuplicateMapInput.put(c, 1);
    }
}

Esse é o segundo HashMap:
Map<Character, Integer> countDuplicateMapArray = new HashMap<>();

for (int i = 0; i < 1; i++) {
    // Chama uma função para normalizar cada String do Array wordArray
    String normalizedWordArray = normalizeString(wordArray[i]);

    char[] charWordArray = normalizedWordArray.toCharArray();

    for (char c : charWordArray) {
        if (countDuplicateMapArray.containsKey(c)) {
            countDuplicateMapArray.put(c, countDuplicateMapArray.get(c) + 1);
        } else {
            countDuplicateMapArray.put(c, 1);
        }
    }
}

Como posso comparar essas 2 estruturas e obter uma resposta "true" ao exemplo abaixo?
Exemplo:
O input é "unstoppable" e o HashMap countDuplicateMapInput vai receber:
{
key: "p", value: 2;
key: "a", value: 1;
key: "b", value: 1;
key: "s", value: 1;
key: "t", value: 1;
key: "u", value: 1;
key: "e", value: 1;
key: "l", value: 1;
key: "n", value: 1;
key: "o", value: 1;
}

e tem a palavra "stop" no meu Array que vai popular o HashMap countDuplicateMapArray da seguinte forma:
{
key: "p", value: 1;
key: "t", value: 1;
key: "s", value: 1;
key: "o", value: 1;
}

Answer: Encontrei uma resposta que resolveu o meu problema e vou deixar ela registrada aqui caso alguém esteja com o mesmo problema.
countDuplicateMapArray.entrySet().stream()
     .allMatch(e -> countDuplicateMapInput.getOrDefault(e.getKey(), 0) >= e.getValue());


PCA Dimension Reduction for Cox Proportional Hazard Model

Question: I am trying to figure out if it is possible and appropriate to use PCA to reduce the dimensions of my dataset? A little background - I have survival data with 8 covariates. I have run a Pearson's correlation test and found that the data was highly colinear.

This is what I have so far, but I am stuck on how to transform the PC axis into useable covariates for the model
otraits <- read.csv("C:/Users/bacon/Documents/Box Sync/YLR IDE Restoration Experiment/YLRmeantraitsonly.csv")
rownames(otraits) <- otraits[,1]
otraits[1:1] <- list(NULL)

MTVpca <- prcomp(otraits, center=TRUE, scale = TRUE)

pc.use <- 2 # explains 93% of variance
trunc <- MTVpca$x[,1:pc.use] %*% t(MTVpca$rotation[,1:pc.use])

#and add the center (and re-scale) back to data
if(MTVpca$scale != FALSE){
  trunc <- scale(trunc, center = FALSE , scale=1/MTVpca$scale)
}
if(MTVpca$center != FALSE){
  trunc <- scale(trunc, center = -1 * MTVpca$center, scale=FALSE)
}
dim(trunc); dim(Xt)

Specifically I want to truncate it for a cox proportional hazard model (here is an example with the original data)
cox <- coxph(Surv(Time, Event, type = c('right')) ~
               Treatment+SLA+Growth_Rate+SLAVar+AreaVar+Thickness+VLA+VLAVar+PD10+CPD,  data = YLRMeans)

ggforest(cox, data=YLRMeans)

Here is the Covariate/Trait dataset that need to PCA:
    Growth_Rate Area    AreaVar SLA SLAVar  VLA VLAVar  Thickness   ThicknessVar    logThickness    logThicknessVar LV  LVVar   PD0 PD10    PD50    CPD
ARCA    0.035049437 14.56355219 11.78670881 180.1322546 99.50427931 9.364236482 1.414207935 0.268703703 0.074128238 -1.352780779    0.298806173 43.22157529 13.35296757 12.61566    29.016  250 0.721921544
ESCA    0.029380702 1.245833333 1.076820745 262.1630059 60.49033956 4.392284625 0.596306575 0.16357684  0.038660691 -1.835819399    0.223972815 39.80718218 11.25985865 294 294 294 0.577356321
MIAU    0.00652489  0.00652489  0.011364841 3.412857143 2.976064883 151.5001201 79.68333552 2.370279914 0.731201273 0.285257143 0.120154396 37.54090305 16.93270863 183.7778    209.3333    250 0.622318052
SIBE    0.01441308  5.477777778 5.117901992 181.6818246 42.91299583 2.954769874 0.448780843 0.176855556 0.018545802 -1.735344864    0.107673785 31.80493389 4.311588188 225.2889    225.2889    315.3334    0.594958509
SIMA    0.020075948 4.974358974 4.901863202 142.4036892 39.11274955 1.651824981 0.295753475 0.148082051 0.045211395 -1.953346759    0.300665842 20.91557187 8.108682659 163.3333    193 250 0.625836637
STPU    0.01546666  5.28968254  6.055307558 122.3827137 32.67582669 7.352684101 3.027753522 0.149629537 0.031130015 -1.943799376    0.210327301 17.91978995 5.823172424 24  24  315.3334    0.611910294

Here is the head of the survival data set used for the cox model: The datafile has too many characters but I can create a cloud link with it if desired
Plot.ID Subplot Treatment   Species Time    Event   st.Growth_Rate  st.Area st.AreaVar  st.SLA  st.SLAVar   st.VLA  st.VLAVar   st.LV   st.Thickness    st.ThicknessVar st.logThickness st.logThicknessVar  st.PD0  st.PD10 st.PD50 st.CPD
PC1 1   control ACMI    829 0   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC1 2   control ACMI    829 1   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC1 3   control ACMI    829 0   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC1 4   control ACMI    829 0   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC1 5   control ACMI    829 0   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC1 6   control ACMI    829 0   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC1 7   control ACMI    829 0   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC1 8   control ACMI    829 0   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC2 1   control ACMI    829 0   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC2 2   control ACMI    829 1   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC2 3   control ACMI    535 1   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC2 4   control ACMI    535 1   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC2 5   control ACMI    535 1   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345
PC2 6   control ACMI    829 0   2.803030572 1.085246545 1.062513537 NA  NA  NA  NA  NA  -0.21732483 -0.016144437    -0.391346353    -0.351950426    -0.735633202    -0.870395351    -0.665279262    1.429445345

Answer: Note that by calculating the principal components based on the original variables, using these principal components in your Cox model you lose in interpretability. That is, the coefficients you obtain are log hazard ratios for the principal components and not for your original variables.
Now, if this is a problem will depend on what exactly is your purpose with this analysis, i.e., do you want to be able to interpret the coefficients or not.
Another solution to account for multicollinearity is to use ridge regression, which is available in the survival package in R using the ridge() function.
Comment: Dimitris thanks that makes sense, but when I use the `ridge` function it also seems to lose the original variables e.g. `ridge(SLA+Growth_Rate+SLAVar+Thickness+ThicknessVar+VLA+VLAVar)` turns all of those covariates into a single covariate for the cox model  - if it is significant does that just mean those are all significant for survival in the same directionality? (yes I want to interpret the original variables)
Comment: You have to use `ridge(SLA, Growth_Rate, ...)`, and you will also need to set the `theta` argument.


Cannot conect to azure Database

Question: I already tried many things:

Firewall Exception
Named Pipes enables
TCP/IP Enabled and 1443 port open.

And I still got this error all the time

Cannot connect to ip.database.windows.net.
  ERROR : (provider: Named Pipes Provider, error: 40 – Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 53 )

This is driving me crazy, because I need this connection to do some reports about that data.
Thanks.
Comment: So, what is the programming problem? Stackoverflow is sort of dedicated to PROGRMAMING - system administration has sister sites, you know.
Comment: What is the Connection String you are using and with which language?
Comment: SQL Server default port is 1433.
Comment: maybe duplicate of: http://stackoverflow.com/questions/33775810/refused-my-local-machine-sql-connection-for-1433-port/33775937#33775937
Comment: @MatiasQuaranta I turned off the firewall and it worked. Now I'm using SQL Server Data Tools and the error still pop ups.
Answer: Maybe the firewall rules don't include the proper client IP that you think it does. Use SQL Server Management Studio to attempt to access to your database on Azure.
Look at the error message that pops up. It should have an IP address in it. Now look at the list of IP addresses that you have in your firewall settings and make sure that the proper IP is in there.
I'm suggesting this because I had the same problem, while I was connected in an office network through a VPN, and the wrong IP was showing up. Once I added the IP that it actually resolved for my client connection, I was able to get access to the SQL Server database without any issues.

Cannot conect to azure Database


Build DAHDI for Beablebone Black

Question: I'm planning to build DAHDI for Beagleboneblack
Firstly, I built the kernel for BBB completely by following this tutorial
http://elinux.org/Building_BBB_Kernel,

make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- beaglebone_defconfig
  make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- uImage dtbs
  make ARCH=arm CROSS_COMPILE=arm-linux-gnu- uImage-dtb.am335x-boneblack modules

I used linaro toolchain for armhf (CROSS_COMPILE=arm-linux-gnueabihf-) instead of the instructed one.
And then I start building the DAHDI :

cd dahdi-linux-complete-2.10.1-rc2+2.10.1-rc2
  cd linux/              # I build the dahdi only, not their tools
  make KSRC=PATH_TO_MY_ABOVE_KERNEL

Unfortunately, process ends with the following error when compiling the dahdi-base.c :

/home/working/dl/dahdi-linux-complete-2.10.1-rc2+2.10.1-rc2/linux/drivers/dahdi/dahdi-base.c:1: error: code model kernel not supported in the 32 bit mode
  /home/working/dl/dahdi-linux-complete-2.10.1-rc2+2.10.1-rc2/linux/drivers/dahdi/dahdi-base.c:1: sorry, unimplemented: 64-bit mode not compiled in

I have no idea why, because my linaro toolchain is 32-bit

/home/working/dl/gcc-linaro-arm-linux-gnueabihf-4.7-2012.10-20121022_linux/bin/arm-linux-gnueabihf-gcc-4.7.3:
  ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped

and my gnu gcc toolchain is 32-bit as well.

/usr/bin/gcc: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, stripped

If anybody gets an idea, your help would be appreciated.
Best Regard.
Loi Dang Thanh
Comment: how is your `--host` configured for your `arm-linux-gnueabihf-gcc`. Run `arm-linux-gnueabihf-gcc`and look for `--host`
Comment: And try `make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- KSRC=PATH_TO_MY_ABOVE_KERNEL`
Comment: Why do you need DAHDI? ...Are you connecting a Digium card to the beagle bone black? Otherwise, you shouldn't need DAHDI to run asterisk.
Comment: BBB have no HPET. so yes, he need dahdi or other  timer. Unfortanly it is not granted dahdi can be compiled for other platform except x86. Developer must change it to support new platform. DAHDI just say you you have no x86 on this box. I recommend you use thread on openwrt forum for ideas.
Comment: Thank you guys, I was confusing of building it. I thought only KSRC argument is needed when building dahdi only, not dahdi's tools. So I didn't input CROSS_COMPILE or ARCH.
Following Miline's instruction solves the issue pretty well.
Best regards
Answer: I'm making this answer to make sure everyone else who get into my issue can search and solve the problem in the future.
Just add 2 more ARGS to the make command when building DAHDI, and the problem solved pretty well.

make KSRC=PATH_TO_MY_ABOVE_KERNEL ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-

A big thanks to Miline who get me out of the stuck.
Best Regards
Loi Dang.

Build DAHDI for Beablebone Black


Multivariate distribution from drawing balls with elimination of previously picked colors from urn at each step

Question: Consider an urn with n balls of k colors ( labelled 1 through k ) where n >= k. You get to draw j times (j <= k) with the following action between draws. Each time you draw a ball belonging to a color, you remove all balls in the urn having that color. How can we characterize the multivariate distribution (an ordered set of j random numbers) resulting from this experiment?
To clarify a consequence of the rules of the experiment, the resulting multivariate whose properties I am seeking to understand will be of the form $X = \{ X_1, X_2 , ... X_j\}$ and will have the following obvious characters:

$X_i$ is an integer for all $1 \leq i \leq j$
$X_i \in [1,k]  $
$X_i \neq X_j$ when $i \neq j$.

I am trying to understand if this falls under some known multivariate distribution families.
Comment: This is a special case of "weighted sampling without replacement." A solution is described, with references, at http://math.stackexchange.com/questions/316175.
Answer: Whuber already answered your question in the comment by referring to this math.stackexchange.com thread, but for completeness let me expand his comment.
Probability of drawing first ball of $i$-th color is $p_i = n_i / n$ where $n_i$ is the number of balls of $i$-th color. In the next draw you have $n - n_i$ balls in the urn, so probability of drawing $j$-th ball is $\tfrac{p_j}{\sum_{m \notin \{i\}} p_m} = \tfrac{p_j}{1 - p_i} = \tfrac{n_j}{n-n_i}$, etc. The procedure is continued until you draw expected number of balls. The probability of drawing sequence $i,j,k$ is
$$
\begin{align}
\Pr(X_1 = i, X_2 = j, X_3 = k) & = p_i \cdot \frac{p_j}{1 - p_i} \cdot \frac{p_k}{1 - p_i - p_j} \\
& = \frac{n_i}{n} \cdot \frac{n_j}{n-n_i} \cdot \frac{n_k}{n-n_i-n_j}
\end{align}
$$
If you need formula for obtaining sample $i,j,k$ in any order, then you simply need to sum over probabilities of all the possible permutations of those items (this may not be managable for larger number of items).
If you are looking for a general, named, distribution, then the closest thing I recall is multivariate Wallenius' noncentral hypergeometric distribution with numbers of balls equal to $m_1 = m_2 = \dots = m_k = 1$ and weights equal to a priori probabilities of drawing each ball, i.e. $n_i/n$ for $i$-th ball.


loop transformation for nonlinear sector functions

Question: Please see attached pages from Nonlinear Systems by Hassan K Khalil,
It is claimed that the loop in the upper H1 can "nullify" the transformations in the down H2. Does it mean that the transfer function of the system remains the same?
I try to derive but I can hardly tell that the transfer functions of the subfigures are the same. Specifically, I can tell Fig 6.13 (a) = Fig 6.13 (b), But the rests are not the same.
Answer: They are the same in the sense that the input (and output) signals for $H_1$ and $H_2$ are the same. Thus, they are the same in the sense of stability and boundedness (convergence) of the circulating signals. They are not necessarily the same in the sense of input-output transformation, but it is up to the choice of the output.
The idea is that what we want to study is the stability of the system. What does it mean? It means that (in the absence of the reference input, the most left arrow on Fig. (a)) the circulating signals are bounded, or converge to zero, it is up to your definition of stability. What are the circulating signals? From Fig. (a) we see that these signals are the outputs of $H_1$, namely $y_1$, and the output of $H_2$, namely $y_2$. Then the input of $H_1$ is $u_1=-y_2$, and the input of $H_2$ is $u_2=y_1$. So the claim is as follows: if the signals $y_1$ and $y_2$ are bounded (converge), then the system is stable.
Now, the figures (a) and (d) are equivalent in the sense that the input of $H_2$ in (d) is still equal to the output of $H_1$, that is $y_1$, and the input of $H_1$ is still equal to the negative output of $H_2$, that is $-y_2$. It also means that if you simulate the systems (a) and (d) with the same initial conditions, then the signals $y_1$ and $y_2$ will be the same. Thus, if the system (d) is stable, then the system (a) is stable as well.
Comment: That is exactly what I don't understand, could you provide me with more explanation or some standard reference about this? Because I don't quite get the meaning of "they are the same in the sense that the input (and output) signals for H1 and H2 are the same." I think the total input and output of the transformed system are not the same as the original one, since they don't have the same transfer function right?
Comment: I do not know a more standard reference, than the book you are reading. :) See the updated version, I hope it will help.


Do there exist non-maximal Isometry groups on $\mathbb R^3$ induced by a homogeneous metric?

Question: Let $g$ be some homogeneous Riemannian metric on $\mathbb R^3$ (i.e, a metric such that $(\mathbb R^3,g)$ is a homogeneous space). Consider its isometry group $G = Isom(\mathbb R^3,g)$.
A covering subgroup $H \subset G$ is a group acting freely and properly discontiously on $\mathbb R^3$, in other words, the natural projection $\pi: \mathbb R^3 \to \mathbb R^3/H$ is a covering map. Note that trivial group $H = \{e\}$ is always a covering subgroup of $G$.
Question 1: Does there exist a cocompact covering group $H \subseteq G$, i.e a covering group such that $\mathbb R^3/H$ is compact ?
Suppose $G$ contains a cocompact covering group. Then it is a classic result by Thurston that, up to conjugation by some diffeomorphism $\phi: \mathbb R^3 \to \mathbb R^3$, there are six Riemannian metrics $\{g_i\}_{i=1}^6$ on $\mathbb R^3$ (independent of the choice of $g$), so that $G$ is contained in precisely one of $Isom(\mathbb R^3,g_i)$.
Question 2: Is there some $G$ as above, such that (a conjugate of) $G$ is properly contained in one $Isom(\mathbb R^3,g_i)$, i.e $G \subsetneq Isom(\mathbb R^3,g_i)$.
If we consider $\mathbb R^2$ instead of $\mathbb R^3$, such a homogeneous metric cannot be found. For if $g$ is any homogeneous metric on $\mathbb R^2$, then as $\mathbb R^2$ is two dimesional, this means that $(\mathbb R^2,g)$ is also an isotropic space, i.e, $G$ acts transitively on the set of all tangent planes in $T\mathbb R^2$. It follows that $(\mathbb R^2,g)$ has constant curvature, implying that $G$ is either conjugate to $Isom(\mathbb R^2,g_{eukl})$ or $Isom(\mathbb R^2,g_{hyp})$, both of which are maximal.
EDIT: In an earlier version, I mistakenly assumed that every metric $g$ on $\mathbb R^3$ would induce a homogeneous structure, simply because every translation is always an isometry, regardless of the specific choice of $g$. This is, of course, blatantly false, as Professor Lee was so nice to remind me of, it's because the inner product induced by $g$ may very well vary from point to point (as it's the usual case when picking a random metric on a manifold).
Comment: If $g$ is an arbitrary metric on $\mathbb R^3$, the translations are almost certainly not isometries.
Comment: The fact that the Jacobian is the identity in standard coordinates is irrelevant, unless the metric has the same matrix at different points.
Comment: That is true, for some obscure reason, this simple observation went past me. I will edit accordingly
Comment: There is a 1-parameter family of solvable 3-dimensional Lie groups $L_t$; for generic value of the parameter $t$, $Isom(L_t)$ contains no discrete subgroups acting cocompactly. Here $L_t$ is equipped with a left-invariant Riemannian metric.
Answer: Question 1: No. For instance, take the Riemannian metric on $R^3$
$$
dt^2 + e^{at}dx^2 + e^{bt}dy^2
$$
for generic values of $a, b>0$. This geometry is homogeneous (with a 3-dimensional solvable Lie group acting transitively) but has no discrete cocompact subgroups of the isometry group.
Question 2: Yes. For instance, start with the 3-dimensional real Heisenberg group $H_3$ and equip it with a suitable left-invariant Riemannian metric which is also invariant under $SO(2)$ (this is known as the Nil-geometry, see Thurston's book that you are reading). Then $H_3$ contains a discrete cocompact subgroup, while $H_3$ is strictly smaller than $Isom(H_3)$.
Comment: @BerniWaterman: The group $H_3$ will be the isometry group of a randomly chosen left-invariant Riemannian metric on $H_3$; the Nil-metric on $H_3$  will have strictly larger isometry group. This is what your 2nd question is about.
Comment: Thanks for answering my first question. I believe your second answer doesn't really answer my second question, as the $G$ in my question should always be the isometry group of some Riemannian metric (I think that you chose $G = H_3$, but $H_3$ is not the full isometry group of the left-invariant metric you chose).
Comment: Just to clear things up: By $Isom(H_3)$, you mean the isometry group of $H_3$ with respect the Nil-metric (not with respect to the randomly chosen left-invariant one)?
Comment: @BerniWaterman: Right.


How to stop OS X compiling/converting .plist files

Question: I'm currently setting up a few OS X clients and servers and frequently need to open/edit .plist files.  Annoyingly OS X compiles these plist files into a binary format, presumably to speed up reading them for performance reasons, which is great except I need to convert them back to xml every time I need to open them which is more important to me than a insignificant performance boost.
So I have to either:

Use Plist editor - I don't like it and it requires Xcode to be installed - not always feasible on a client machine.
Convert them using plutil: plutil -convert xml1 file.plist - which is a PITA.

Is there a way of stopping OS X from converting the nice XML plists to the Devils' binary format?
Answer: I think the format of a property list file is completely determined by the program that creates/updates the file. The Cocoa property list serialization methods and those of Core Foundation all take a format option that lets the program specify either "XML" or "binary"; there is no value like "use some externally specified default". Programs could conceivably do their own defaulting based on some centralized setting, but I am not aware of any such setting (of course it could just be undocumented; the point is that it would still be limited to only the applications that adopted such a "manual defaulting" convention).

PlistBuddy is a flexible and mostly scriptable property list editor (e.g. defaults will only access/modify values at the "top level" of the property list, but PlistBuddy can access/modify values at any arbitrary depth). It is available at /usr/libexec/PlistBuddy on 10.5 and later. It was not bundled with the system on 10.4, but you can usually find it as one of /Library/Receipts/*/Contents/Resources/PlistBuddy (e.g. /Library/Receipts/iTunesX.pkg/Contents/Resources/PlistBuddy).
E.g.

inspect a property list file
PlistBuddy -c print /path/to/some/plist/file

clear out (or create) a plist file and set CFBundleIdentifier to com.apple.plistbuddy
PlistBuddy -c 'clear dict' \
           -c 'add :CFBundleIdentifier string' \
           -c 'set :CFBundleIdentifier com.apple.plistbuddy' \
    /path/to/some/plist/file

You could also use osascript to run commands from System Events' "Property List Suite". It is certainly not as convenient to run from a shell command line, but would be fine for more automated inspections and modifications (i.e. done by a script). The commands from this suite offer write access on 10.5 and later (10.4 was read-only).


How to fetch the value of all XML tags inside a parent XML Tag using Regular Expression?

Question: I have an XML like this:
<Machines>
<Machine>
<Machine_Name>Mac Book Pro</Machine_Name>
<Machine_Type>Laptop</Machine_Type>
<Outputs>
<Output>
<Hour>1</Hour>
<Speed>Very Quick</Speed>
</Output>
<Output>
<Hour>2</Hour>
<Speed>Quick</Speed>
</Output>
</Outputs>
<Capacities>
<Capacity>
<Hour>1</Hour>
<Speed>50%</Speed>
</Capacity>
<Capacity>
<Hour>2</Hour>
<Speed>30%</Speed>
</Capacity>
</Capacities>
</Machine>
<Machine>
<Machine_Name>LG Desktops</Machine_Name>
<Machine_Type>Personal computers</Machine_Type>
<Outputs>
<Output>
<Hour>1</Hour>
<Speed>Fast</Speed>
</Output>
<Output>
<Hour>2</Hour>
<Speed>Moderate</Speed>
</Output>
</Outputs>
<Capacities>
<Capacity>
<Hour>1</Hour>
<Speed>30%</Speed>
</Capacity>
<Capacity>
<Hour>2</Hour>
<Speed>10%</Speed>
</Capacity>
</Capacities>
</Machine>
</Machines>

This is the regex i tried "<Capacity>(?<Value>[\d\w\s\W\D]*)<\/Capacity>"

but what i get is all tags that lie between the first occurence of  to last occurrence of  that is i get all tag: output,hour,speed,machine_name(i get hour and speed for both output and capacity).From this i want to fetch the value of tag (Speed) that falls under (Capacities). that is I need to measure the speed capacity of machine every hour for particular machine type and compare it with previous hour's speed and find out the increase or decrease in the speed and generate report accordingly.
Can anyone please tell an accurate regex to fetch such data and I m strictly instructed to use regex to get these data I am not suppose to use XMLDocument so please kindly suggest me a regex i badly need it.

Comment: Try parsing the XML instead.
Comment: If this is school assignment, you should say so. It's an unusual requirement not to use proper XML utility classes.
Answer: Once again, consider to parse XML using anything else but regexp, but check if that can help you:
string reg = @"<(?'tag'\w+?).*>" +
             @"(?'value'.*?)"    +
             @"</\k'tag'>";
string xml = "<test>this is the inner text</test>";
Match mMatch = Regex.Match (xml, reg);

Then you can use the property "Groups" to fetch data.
Source: 10 secs of google
Comment: It produces an error saying "Unrecognized Grouping Construct". I used while(mMatch.Success){ string matchfound+=mMaalue; mMatch = mMatch.NextMatch();}. what things do I need to replace?
Comment: I replaced it like this string reg = @"<(?Capacity\w+?).*>" +
                 @"(?]*?>(?.*?).*?)" +
                 @"";
Comment: mMatch.Groups["value"] should return "this is the inner text"
Comment: but will it return any value if the string is like this:1st test2nd test then will this regex work and will mMatch.Groups[value] return "1st test2nd test?
Answer: Instead of Regex, use a real xml parser. For example, using Linq To Xml
var speeds = XDocument.Load(fname)
             .XPathSelectElements("//Capacity/Speed")
             .Select(x => (string)x)
             .ToList();

Comment: yes i know its the most easiest way but i am helpless because i am very strictly instructed to use regular expression only. I am firmly warned to accomplish this task only by using regex. Please help me out
Comment: @user2786794 Show them this link http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags who instructed to use regular expression
Comment: I know its obvious to get frustrated but its matter of my job so i cant just argue got to do as instructed. Hope i get an answer or they change their mind


send https post request with authentication in ruby

Question: I got a curl here:
curl https://test-api.pin.net.au/1/charges -u your-secret-api-key: \
 -d "amount=400" \ -d "currency=USD" \

how can I use net/http to post this request? It include the ssl and authentication.
Comment: Did you read the documentation for [POST](http://ruby-doc.org/stdlib-2.2.1/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-POST) and [Basic Authentication](http://ruby-doc.org/stdlib-2.2.1/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-Basic+Authentication)?
Answer: HTTP#post_form will execute directly
require 'net/http'
require 'uri'

url = URI.parse('https://test-api.pin.net.au/1/charges')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'user', 'pass'
req.use_ssl = true
req.form_data({'your-secret-api-key' => 'val1', 'amount' => 'val2', 'currency' => "USD"})

resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
puts resp

Comment: It is very helpful ,thanks mate. but i make a little change. I already post my answer under the question. Thank you!
Answer: I solved this question now. here is the answer
uri = URI.parse('https://test-api.pin.net.au/1/charges')
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http
req = Net::HTTP::Post.new(uri.path)
req.basic_auth 'user', 'pass'
req.set_form_data({ 'amount' => 'val2', 'currency' => "USD"}
http.request(req))
end


Migrate-d2d UI - Where does sites/default/files source content go?

Question: I am setting up a dedicated development environment on my home LAN where I can work on a Drupal 6 to Drupal 7 migration. So far, I have a clean Centos 7, LAMP stack, and Drupal 7 install and have configured periodic file and image backups to my local NAS. The D6 drupal database has been imported and connected in settings.php and appears to be recognized by the migrate_D2D UI.
What I am unclear about is how to migrate the D6 site's downloadable file content and images under sites/default/files.  Although the D6 site is live and remote, I was thinking about copying relevant portions of the sites/default/files path over to the development system, but I don't know where to put it or how to reference it as a data source in the migration process.
I would assume that the format or field mapping conventions for content in sites/default/files is different between Drupal 6 and 7 and source and destination content must remain separate, but I am not sure about this.  So can anyone advise me as to the best approach for incorporating this D6 content into D7?  I would be happy to either copy the content over or read it remotely from the live site if this is supported.  Thanks.
19 hours later:
I haven't resolved this yet so let me ask my question again with a couple of visual aids.  Here is the file tree of the sites/default/files section from my legacy Drupal 6 website:

Here is the file tree of the sites/default/files section from the clean install of the Drupal 7 website I am trying to migrate into:

My question is where migrate_d2d wants me to put the legacy (source) Drupal 6 files.  Do I put it inside the new sites/default/files tree or somewhere separate from where the post-migration Drupal 7 files will be?
Thanks again.
Answer: I'll post this as a preliminary answer, but please feel free to comment with better suggestions.
Step 4 (Files) of the migrate_d2d UI asks for path where the source files can be found.  I took the conservative approach and uploaded the legacy sites/default/files file system to a separate source directory on the development server, but I don't see why you couldn't directly import the legacy file content into the sites/default/files directory on the destination server.
At least this seems to work so far.


Imagem de fundo, usando css

Question: Como que faço para colocar uma imagem de fundo na div, usando css?
Tentei utilizando aspas simples porém nada aconteceu:
background: url('images/html.jpg');

Estou fazendo assim no:
#tudo { width: 100%; height: 992px; background: url('images/html.jpg');}

Comment: Dê uma olhada aqui: __http://jsfiddle.net/XmTVT/__ - tem a certeza que o ficheiro `images/html.jpg` existe na directoria que indicou?
Comment: Ainda estou querendo entender qual o problema e como foi solucionado se a resposta do usuário abaixo está igual ao código que você apresentou.
Comment: Oi Paulo eu não estava conseguindo linkar o background com html e css, por algum motivo não estava funcionando porém utilizei a opção chamando o stylo dentro da DIV conforme foi informado acima, com isso eu consegui fazer o que desejava. Por isso foi solucionado a minha dúvida. Obrigado a todos.
Comment: @TheMax colocar estilo dentro da div não é uma prática recomendada, o CSS deve estar sempre separado do HTML.
Answer: Tenta assim:

Conteúdo da div

ou
#tudo{
 background-image:url(images/html.jpg);
 width:100%;
 height:992px;
}

Conteúdo da div

Comment: Obrigado ajudou muito!! Valeu sou novo aqui e vou participar varias vezes!!
Comment: Já que a resposta dele funcionou você deve dá-la como certa clicando na símbolo de correto logo abaixo da pontuação.
Comment: Junior como eu posso da como certa não encontrei o que você falou sobre o símbolo!
Comment: @TheMax Do lado esquerdo << Em baixo da seta ▼
Answer: Para isso existem 2 prováveis motivos:

A imagem informada (images/html.jpg) não existe
Você não incluiu o CSS no arquivo.

A 1° pode ser resolvido acessando a imagem se existir então você não incluiu o CSS no arquivo tente substituir o código do arquivo pelo seguinte:

Como pode ver através deste link o código funciona.

Imagem de fundo, usando css


Codeigniter how to load all js files from folder

Question: Codeigniter how to load all js files from folder, without mentioning name of file.
Example- I want to get all js file from one folder. I know the path up to folder but js files are created dynamically when build is created so do not know exact name of files to load tradional way.
Comment: @cartalot, technically yes... blindly include every file that happens to be in a directory.  Does not seem very smart.
Comment: Regardless of CodeIgniter, you can't include files when you don't know the file's name.
Comment: @sparky - couldn't you read the directory and then load them?
Comment: @sparky - with respect -  please delete your first response since its not correct.
Comment: Seema this should get you started - try coding something and if it doesn't work post again with the code you tried http://www.codeigniter.com/user_guide/helpers/file_helper.html#get_filenames
Comment: I got the solution. Posted in Answers section. Thanks All!
Answer: Maybe this solution will going to work
<code>$js_path = rtrim(FCPATH . 'assets/js', '/'); // FCPATH = root folder of your codeigniter project

$js_files = glob("{" . $js_path . "/*.js}", GLOB_BRACE);

for($i = 0; $i < count($js_files); $i++){
    echo read_file($js_files[$i]);
}
</code>
code not tested but I hope this will solve the problem
Answer: I tried following that worked for me
<code>        $folderpath = $_SERVER['DOCUMENT_ROOT'].'/resources/common/js/';
        $fileName = array();
        $fileName = get_filenames($folderpath);
        $jsFiles = array();
        foreach($fileName as $file){
            $url = 'resources/common/js/'.$file;
            $jsFiles[]['js'] = base_url($url);
        }
        $this->load->vars($jsFiles);
</code>


Expectation Inequality with indicator function

Question: When I read proof of Chebyshev's inequality, I came across the problem.
At first, the proof is :
\begin{align*}
P(|X-r|\geq k\sigma) &= E(\chi_{|X-\mu| \geq k\sigma})   \\
&= E(\chi_{\left( \frac{X-\mu}{k\sigma} \right)^2  \geq 1}) **from\_here**  \\
&\leq   E\left(   \left( \frac{X-\mu}{k\sigma} \right)^2   \right)  **to\_ here**  \\
&= \frac{1}{k^2} \frac{E((X-\mu)^2)}{\sigma^2}   \\
&= \frac{1}{k^2}
\end{align*}
As I make a point above, I cannot understand why the inequality holds.
Could you explain it? Thank you in advance.
Comment: This question has a purely visual answer posted under "Chebyshev's Theorem" at  http://www.quantdec.com/envstats/notes/class_06/properties.htm.
Comment: This is a little difficult for me... But Thank you very much. I will read it until I understand.
Answer: The inequality depends on the fact that for any $y \in \mathbb{R}$,
$$
\chi_{y^2 \geq 1} \leq y^2.
$$
The proof is by cases. Suppose $y^2 < 1$. Then
$$
\chi_{y^2 \geq 1} = 0 \leq y^2.
$$
Now suppose $y^2 \geq 1$. Then
$$
\chi_{y^2 \geq 1} = 1 \leq y^2.
$$
To obtain the inequality in your question, simply substitute $y = \frac{X - \mu}{k\sigma}$. Since this inequality holds for all values of $X$, it certainly holds in expectation.
Answer: To simplify slightly the good answer above (+1 by the way), it's because, for any nonnegative random variable $Y$,
$$
Y \ge Y \mathbb{1}(Y > 1) \ge \mathbb{1}(Y > 1).
$$
Then just take expectations on both sides of both inequalities.
Sorry to change your notation. I don't like the $\chi$ thing.


Campo tipo data em formulário Codegniter

Question: Estou desenvolvendo um formulário com campo tipo data.
Como eu uso o recurso do form presente do Codeigniter para um campo data?
No exemplo abaixo estou usando text area. Existe uma função form_ para datas?
 echo "
    ";
            $atributos = array(
                "class" =>  "col-sm-2 control-label"
            );
            echo form_label("Data de início:","DATA_INICIO",$atributos);
            echo "
";
            $atributos = array(
                "name"  =>  "DATA_INICIO",
                "id"    =>  "DATA_INICIO",
                "placeholder" => "Descreva o diagnóstico por dia realizado",
                "class" => "form-control",
                "value" =>  set_value('DATA_INICIO')
            );
            $formdate
            echo form_textarea($atributos);
            echo "
";
        echo "
";

Answer: No CodeIgniter, mediante a documentação para a sua última versão 2.2.0, não existe nenhum helper para formulários que permita gerar campos para os novos tipos introduzidos com o HTML5.
Documentação para Form Helper (Inglês)
Contudo, visto ser algo muito necessário nos dias actuais, já outros passaram por esse problema e criaram soluções.
Um exemplo pode ser encontrado no fórum do CodeIgniter com o nome Extended form helper to support HTML5 form elements (Inglês) cujo mesmo segue em baixo:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Common Input Field
 *
 * @access    public
 * @param    string
 * @param    mixed
 * @param    string
 * @param    string
 * @return    string
 */
if ( ! function_exists('form_common'))
{
    function form_common($type = 'text', $data = '', $value = '', $extra = '')
    {
        $defaults = array('type' => $type, 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value);

        return "<input "._parse_form_attributes($data, $defaults).$extra." />";
    }
}

/**
 * Email Input Field
 *
 * @access    public
 * @param    mixed
 * @param    string
 * @param    string
 * @return    string
 */
if ( ! function_exists('form_email'))
{
    function form_email($data = '', $value = '', $extra = '')
    {
        return form_common($type = 'email', $data = '', $value = '', $extra = '');
    }
}

/**
 * Url Input Field
 *
 * @access    public
 * @param    mixed
 * @param    string
 * @param    string
 * @return    string
 */
if ( ! function_exists('form_url'))
{
    function form_url($data = '', $value = '', $extra = '')
    {
        return form_common($type = 'url', $data = '', $value = '', $extra = '');
    }
}

/**
 * Number Input Field
 *
 * @access    public
 * @param    mixed
 * @param    string
 * @param    string
 * @return    string
 */
if ( ! function_exists('form_number'))
{
    function form_number($data = '', $value = '', $extra = '')
    {
        return form_common($type = 'number', $data = '', $value = '', $extra = '');
    }
}

/**
 * Number Input Field
 *
 * @access    public
 * @param    mixed
 * @param    string
 * @param    string
 * @return    string
 */
if ( ! function_exists('form_range'))
{
    function form_range($data = '', $value = '', $extra = '')
    {
        return form_common($type = 'range', $data = '', $value = '', $extra = '');
    }
}

/* End of file MY_form_helper.php */
/* Location: ./application/helpers/MY_form_helper.php */

Para o teu caso em particular de forma a criares um input[type=data] deverás adicionar ao ficheiro em cima referênciado:
/**
 * Date Input Field
 *
 * @access    public
 * @param    mixed
 * @param    string
 * @param    string
 * @return    string
 */
if ( ! function_exists('form_date'))
{
    function form_date($data = '', $value = '', $extra = '')
    {
        return form_common($type = 'date', $data = '', $value = '', $extra = '');
    }
}

Comment: Grato pelo retorno! Valeu!


Trabalhando com Rotas no Laravel

Question: Essa é a estrutura do meu projeto onde fica minha pagina;

Esse é meu controller;
  public function create()
    {
        return view(imoveis.create);
    }

Está configurado assim minha rota, está no meu arquivo web.php;
Route::resource('imoveis', 'ImovelController');

E está me retornado essa mensagem de erro na URL:  http://localhost:8000/imoveis/create

Onde será que errei?
Comment: A mensagem de erro explica o problema, como constante não definida, ou seja, imoveis.create não existe deve ter uma apas simples ou dupla acredito que resolva tipo `view("imoveis.create");`
Comment: @VirgilioNovic, você está certo, é falta das *Aspas*.
Comment: @VirgilioNovic pode postar a resposta, pois você está certo, funcionou!
Answer: A mensagem de erro explica o significado do erro, dizendo que essa constante não existe, o que se espera no seu código é entre aspas, exemplo:
public function create()
{
   return view('imoveis.create');
}

Comment: Valeu pela diga, é porque ainda estou começando  :)

Trabalhando com Rotas no Laravel


Hierarchy between terms from different vocabularies in Drupal 7?

Question: Is there a way to have a hierarchy of terms by reusing the same terms that reside in different vocabularies? There seem to be so many different options for dealing with taxonomies in Drupal 7 that it feels very daunting to figure out...
For example, let's say I want to make a directory of athletes for different sports. I've created 3 vocabularies, each with several terms:
Vocabulary: Sports
* Soccer
* Basketball
* Baseball
Vocabulary: Divisions
* Division 1
* Division 2
Vocabulary: Teams
* Team 1
* Team 2
Each type of sport will be divided into Divisions and then into different teams per Division.
The hierarchy looks like:
Soccer
* Division 1
    --Team 1
    --Team 2
*Division 2
    --Team 1
    --Team 2
Basketball
*Division 1
    --Team 1
    --Team 2
*Division 2
    --Team 1
... and so on for each sport.
Since the terms for vocabularies Divisions and Teams are always the same, I'm thinking it would make more sense to be able to reuse the same terms under those two vocabularies instead of creating the same terms over and over again for each sport, each division...etc.?
Is that even possible and if so, what would be the best way to go about implementing it?
Comment: your vocabulary structure is correct. I am not getting what you are trying to achieve.
Comment: I was just confused about how to define or at least just display a hierarchical relationship between different vocabularies. So for example, at the top of the hierarchy there would be the Sports vocabulary and below that, the Divisions and then Teams.
Answer: You can make a term reference field on a vocabulary.
So on a the team vocab one of the fields would be "division".
So when you create a new team you would enter the team name and "tag" the division it is in using auto complete or a dropdown.
Answer: The only problem with free-tagging it (by that I don't mean allowing all users to tag the content), which is really the only solution except to create everything in one vocabulary, is that when users search or click on tags for the generic labels like "Division 1", it will not be focused enough in the outcome to be useful.
Since these items have a hierarchy, I think the only solution is to fully duplicate that hierarchy to make results relevant. Someone clicking a linked tag "Division 1" is going to get results for all sports, even when the page in question that is displaying the tags is only about 1 sport. And it won't sort your results based on the previous page unless you set some variable.
I see how the shortcut saves some time but in the long run it completely separates things and in search results only the first result with all terms will be relelvant, the rest will be listings of everything else. Just a thought.
Unless you're going to have separate term reference fields, I'd think it would be a better user experience to simply have the hierarchy in one vocab where pulling the dropdown down would make clear and concise sense.
I guess a good question would be: will you ever have a reason to pull a listing of all Division 1 teams across different sports?
Another question would be: are there so many teams and divisions that one dropdown is simply too long to be user friendly?
Answer: It is also possible to assign multiple parents to a term.  The easiest way to do this that I have found is with the Taxonomy Manager module.


Is a whole note always one bar long, regardless of the time signature?

Question: I found conflicting information about this online.
I am only familiar with 4/4, nothing else.
So, I was wondering if a whole note always one bar long, regardless of the time signature?
Or is it longer in other time singatures? For example, in 3/4 is it 1 bar + 1 quarter note?
Comment: In a given time signature, you never use a single note that spans multiple bars.  So a whole note would never be used in 3/4 time.  If you want to indicate a note that is held over multiple bars, you use ties to denote this.
Comment: The drawback of fractional names is that terms like "whole" can become ambiguous (if you consider them in terms of fractions of a bar). In reality, those fractions are abstract values *derived* from the concept of "whole as in four fourths", where the "fourth" is fundamentally a unit. Considering this, imagine a bar as it were a box: a 3/4 "box" can only hold 3 "fourth units"; since a "whole note" is a 4-fourths value, you cannot fit it in that box: you need to "split" it in two boxes, with a *tie* that clarifies that the two parts belong to the same note, even if they are in different boxes.
Comment: Out of interest where was this misinformation?
Comment: _"I don't always use the Internet, but when I do, I believe everything I see."_ - OP
Answer: Whole notes are always equal to four quarter notes, so are not used in 3/4 time. Whole rests, however, are used for whole measures regardless of time signature.
Comment: Also: It's an unusual situation since it reflects older practice, but there can be an exception to "a whole rest is an entire measure": In 4/2 it's only half a measure, and you'd need a breve rest for the entire measure. That's not really something to worry about at first, though.
Comment: @MusicQuestions7 To expand: A whole note might be used in a time signature that has *more* beats, like 6/4, and it would be less than the entire measure.
Answer: No.  A whole note rest symbol can be used as a "whole bar rest" with the respective length when it is written in the center of the bar as opposed to its normal placement left in a column with other first notes.
There is a very rare case of a "bordun note" with plenty of syllables without prescribed rhythm used in baroque, typically liturgical music (like Monteverdi's Vespers) used in a similar manner in the center of a bar.  However, the symbol being used in that function is not a whole note but a full brevis (length of two whole notes).
In contrast to whole bar rests (which are ubiquitous also in modern music), many will never encounter this special case of a whole bar note.
Comment: @ElementsInSpace Actually, I agree. So much so that I've closed as a duplicate. I think both the questions and answers are fundamentally the same.
Comment: "… normal placement left in a column with other first notes" —is this describing a chord? The meaning here isn't clear to me. Also, note the question is about whole notes and doesn't actually mention rest.
Comment: @AndyBonner "No" addressed the main question and then proceeds to explain about whole rests. It's also explaining that when used for a whole measure, the rest is placed at the center of the bar. When placed at left, in line with the first notes of other staves/voices, it's counted like a normal whole rest (such as in a bar of 3/2 with two beats rest and one beat played).
Comment: Reminds me of this answer: https://music.stackexchange.com/a/131863/53709


Is there better way than this to find and remove additional space in string in JS?

Question: I have the following function which detects if there is 2 space and removes one:
filterText(text) {

        if (text.indexOf('  ') >= 0) {
          return text.replace('  ', ' ')
        }
        return text
      }

is there a better way to achieve the same result?
Comment: You'll have to define "better," but you might just do `return text.replace("  ", " ");` without the `if`. Harmless if it doesn't change anything, very unlikely to cost anything performance wise (since strings are immutable in JavaScript and your code can't tell whether a string primitive has been reused; if it were costly, it would be optimized by JavaScript engines, so either they do or it isn't necessary).
Comment: That only replaces the first occurrence
Answer: String.prototype.replace()

If pattern is a string, only the first occurrence will be replaced.

You can either use String.prototype.replaceAll() or try using RegEx with global flag.
The following example will remove 2 or more spaces with single space:

text = `some  text,  more      text`;
text = text.replace(/\ +/g, ' ');
console.log(text);

If you want match exactly 2 space then:
text = text.replace(/\ {2}/g, ' ');

Comment: ...and tabs and vertical tabs and... It also does lots of pointless replacements (`" "` with `" "`). `/ {2,}/g` would make more sense. But whether this is "better" by the OP's definition...
Comment: Thanks for answer. can I chain lit like this?

text.replace(somePattern, '').replace(/\ +/g, ' ')
Comment: @Dave, yes you can but probably you can achieve that in a single regex pattern.
Answer: No need if statement. Enough replaceAll

function filterText(text) {
  return text.replaceAll('  ', ' ')
}

console.log(filterText('a  df sf s  fsf'))
Answer: You probably don't need a function. You could write your code directly like this, assuming text is the variable in question:
text.replace( /\s{2}/g, ' ' )

The g stands for group and will find all matching occurrences in the String for you.


Combining datetime column in to a mean count by date column

Question: I have a dataset that is formatted in the below manner, and I'm trying to reformat it in a way that instead of DateTime column, id get the mean order count for each day (Monday,Tuesday, etc.)

TIMESTAMP
TEMPERATURE
WINDSPEED

2020-08-01
13.2
4.9

2020-08-01
15
5

2020-08-02
16
2.4

2020-08-02
14.2
6.3

2020-09-10
17.5
2

2020-09-10
9
8.3

Heres my code so far, everything seems to work fine and I can print the mean order count by day, by itself, but when trying to import it into the data set the ordercount is Nan
df = pd.read_csv('orders_autumn_2020.csv')

df['TIMESTAMP']= pd.to_datetime(df['TIMESTAMP'])

df_mod = df.groupby(df['TIMESTAMP'].dt.weekday).mean()
datecount = df.resample('D', on='TIMESTAMP').count()
ORDCOUNT = (datecount['WINDSPEED'])
df_mod["ORDCOUNT"] = ORDCOUNT
df_mod = df_mod[["TEMPERATURE","WIND_SPEED","ORDCOUNT"]]

print(df_mod)

TIMESTAMP
TEMPERATURE
WINDSPEED
ORDCOUNT

0
17.055038
4.027295
NaN

1
15.961699
2.951472
NaN

2
16.305026
3.600513
NaN

3
16.142084
4.051359
NaN

4
16.864189
3.131984
NaN

5
17.364454
4.230898
NaN

6
18.321807
4.310171
NaN
Answer: In your solution aggregate by 2 different values - by weekday and by D for days, so indices are different so if assign column get NaNs.
Possible solution if need count per weekday with omit NaNs if exist in WINDSPEED column with GroupBy.count:
df1 = (df.groupby(df['TIMESTAMP'].dt.weekday)
         .agg(TEMPERATURE = ('TEMPERATURE','mean'),
              WINDSPEED = ('WINDSPEED','mean'),
              ORDCOUNT = ('WINDSPEED','count')))

Or if need count per days use Grouper:
df2 = (df.groupby(pd.Grouper(freq='d', key='TIMESTAMP'))
         .agg(TEMPERATURE = ('TEMPERATURE','mean'),
              WINDSPEED = ('WINDSPEED','mean'),
              ORDCOUNT = ('WINDSPEED','count')))

Your solution:
df_mod = df.groupby(df['TIMESTAMP'].dt.weekday).mean()
datecount = df.resample('D', on='TIMESTAMP')['WINDSPEED'].count()

df_mod["ORDCOUNT"] = datecount.groupby(datecount.index.weekday).sum()

Comment: I'm new to pandas so a follow-up question would be: In df1, how would I get the mean of ordcount instead of the total count? I tried doing ORDCOUNT = ('WINDSPEED','count').mean(). But that's invalid syntax.
Comment: @Kodtld - Can you be more specific? Do you need `df_mod["ORDCOUNT"] = datecount.groupby(datecount.index.weekday).mean()` instead `df_mod["ORDCOUNT"] = datecount.groupby(datecount.index.weekday).sum()` ?


Use Apache HttpService in Android SDK 22

Question: I want to use HttpService in Android for hosting a simple Web Server. When I set the target SDK as 23, and follow instructions here: https://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client, I am able to use HttpService class without any problems.
But I want to do this with target SDK 22. When I try to do that, the code compiles but AndroidStudio keeps giving "deprecated" warnings. Is there any way to avoid that? If its possible to do with SDK 23, then why not with SDK 22?
Answer:
I want to use HttpClient in Android for hosting a simple Web Server.

HttpClient is for implementing the client side of an HTTP connection. I am not aware that it is particularly useful for implementing an HTTP server.

Is there any way to avoid that?

No, other than to stop using Android's long-since-discontinued fork of HttpClient and use the official library from Apache. Google has been telling developers to stop using the built-in HttpClient fork for quite some time. It was only with API Level 22 and up that they started enforcing it more.
Comment: Apologies, I meant HttpService instead of HttpClient. Can you take a look at the question again? Thanks for the prompt response.
Comment: @Bonton255: It doesn't really change my answer. If you want to use `HttpService`, use Apache's official up-to-date implementation.
Comment: I had already tried what you suggest (adding compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '188.8.131.52' to dependency), but that doesn't change anything. HttpService still points to < Android API 22 Platform > and still shows it as deprecated.
Comment: @Bonton255: Yeah, `HttpService` appears to be part of Apache's HttpComponents, not strictly HttpClient. Their project is a bit confusing. I do not know if there is an Android-friendly HttpComponents, though [this looks promising](https://hc.apache.org/httpcomponents-client-4.3.x/android-port.html).
Comment: @mark: that link is essentially saying the same thing as the earlier link you shared.
Comment: @Bonton255: I though that the artifact name was different, but it's not -- my apologies. I have no idea if there is an Android-friendly `HttpService` implementation from Apache. That being said, *please* don't use the built-in one, as heaven only knows what bugs are floating around in it that Google will never fix. If you're implementing a server, it is crucial to use one that is being maintained, particularly for security fixes.
Comment: Figured out the solution. The link you gave above also points to the copy of HttpComponents with a changed namespace cz.msebera.android.I used that and all works fine now! For anyone else facing this problem, the only solution as of today is to use https://github.com/smarek/httpclient-android/wiki/Project-Introduction


Passing more than two arguments in reduce function

Question: I am aware that Python reduce only accepts a function with two arguments. However, is there a way to make more than two arguments available to the function? I don't want to make it a global variable because that would be visible for all other imports. The following snippet might help describing the problem (Please read the comments in the snippets):
# The reduce function
def apply_something(something, config):
    # Consrtuct a class object based on the truth value of some other variable.
    # some_var can be changed and is being accessed in different threads so its
    # not safe to make it global. The reduce function is being called from
    # inside some other function so It would be better to make
    # some_var only accessible in the function context.

    if some_var:
        obj = Klass(some_var)
    else:
        obj = Klass()

def callee():
    # This is how I apply the reduce operation.
    reduce(apply_something, [1, 2, 3], something_initializer)

    # I want something like this:
    some_var = True  # So this can be accessed in apply_something

Please provide some insight into this kind of problem.
Comment: It is not clear to me how this is a reduce function. Can you give an example input, and show how it would reduce that input?
Comment: @Thanatos I have modified the question. Can you please review it?
Answer: I think what you're looking for is partial function application, which you can do using functools.
def apply_something(something, config, some_var):
    pass  # ...

import functools

functools.reduce(functools.partial(apply_something, some_var=True),
       [1, 2, 3], something_initializer)

Example:
>>> def foo(a, b, c):
...     return a + b if c else a * b

>>> functools.reduce(functools.partial(foo, c=True), [1,2,3,4,5], 0)
15

>>> functools.reduce(functools.partial(foo, c=False), [1,2,3,4,5], 1)
120

Answer: Strictly speaking, the function passed to reduce will always be called with two arguments. However, these types of functions will often access variables in an outer scope. Since I'm unclear on your exact problem, let's implement join in terms of reduce:
def join(joining_string, strings_to_join):
    # i.e., join('-', ['a', 'b', 'c']) -> 'a-b-c'
    # Here, we need an extra piece of data in our reduce function:
    #   joining_string.

    def do_reduce(a, b):
        # Joining string comes from the outer scope:
        return a + joining_string + b

    return reduce(do_reduce, strings_to_join)

Also, Chris Martin's solution involving partial is perfectly correct as well. Applying it to the above would look like this:
# This didn't *need* to move out of join, but it can. Before, it needed
# to be in join to be able to "capture" the local variable joining_string.
def do_reduce(a, b, joiner):
    # Joining string comes from the outer scope:
    return a + joiner + b

def join(joining_string, strings_to_join):
    # i.e., join('-', ['a', 'b', 'c']) -> 'a-b-c'
    # Here, we need an extra piece of data in our reduce function:
    #   joining_string.

    return reduce(
        functools.partial(do_reduce, joiner=joining_string),
        strings_to_join)

Answer: You could as well just use a lambda:
def foo(total, cur, some_var=False):
    pass  # ...

reduce(lambda total, cur: foo(total, cur, some_var=True), [1, 2, 3], init)