is it possible to make use of data stored using the user.data service ifor filtering views?

Question: Allowing a user to bookmark a node i have created
<code> public function bookmark($nid,$uid) {
    $user_data = \Drupal::service('user.data');
    $bookmarked_nodes = $user_data->get('my_module', $uid, 'bookmark');
    $bookmarked_nodes[$nid] = $nid;
    $user_data->set('my_module', $uid, 'bookmark', $bookmarked_nodes);
    \Drupal::messenger()->addStatus(t('node bookmarked.'));
  }
</code>
i would like then to create a view listing only nodes that has been bookmarked by the current user.
Is it possible ?
Answer: Better use the Flag module for a more robust bookmarking solution. Allows you to record a "flag" made by user (in this case, a bookmark) and has a ready-to-use Views integration to filter flags and relate the both user and the flagged entity.
Comment: The module is not stable yet
Comment: @Matoeil Unless you have a company policy against unstable modules or modules not covered by Drupal security, it's stable enough for use. I would use Flag than reinvent the same thing myself (and have something even more unstable). Besides, if you find any flaws, you can always patch the module yourself with [`cweagans/composer-patches`](https://github.com/cweagans/composer-patches).


unable to use android Speech to text

Question: I want to use android's speech to text. following is my MainActivity.java
public class MainActivity extends AppCompatActivity {

private TextView txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 1;

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

    txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
    btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

    // hide the action bar
    //getActionBar().hide();

    btnSpeak.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.i("OnClickListener CALLED:", "");
            promptSpeechInput();
        }
    });

}

private void promptSpeechInput() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            getString(R.string.speech_prompt));
    try {
        startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
    } catch (ActivityNotFoundException a) {
        Toast.makeText(getApplicationContext(),
                getString(R.string.speech_not_supported),
                Toast.LENGTH_SHORT).show();
    }
    Log.i("promptSpeechInput :", "Prompt speech CALLED");
}

/**
 * Receiving speech input
 * */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.i("OnActivity CALLED1:","one");
    switch (requestCode) {
        case REQ_CODE_SPEECH_INPUT: {
            if (resultCode == RESULT_OK && null != data) {

                ArrayList<String> result = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                txtSpeechInput.setText(result.get(0));
                Log.i("OnActivity CALLED2:", result.get(0));
            }
            break;
        }

    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}
Here is my Log:
   02-26 16:23:05.047 13636-13636/com.example.vishal.speechtotext I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@39ca1da6 time:158833044
   02-26 16:23:09.637 13636-13636/com.example.vishal.speechtotext I/Timeline: Timeline: Activity_launch_request time:158837632
02-26 16:23:09.707 13636-13636/com.example.vishal.speechtotext I/promptSpeechInput :: Prompt speech CALLED
02-26 16:23:42.797 13636-13636/com.example.vishal.speechtotext I/OnActivity CALLED1:: one
02-26 16:23:42.837 13636-13636/com.example.vishal.speechtotext I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@39ca1da6 time:158870837

code just runs, doesn't show any error. i am unable to find what the
error is.

I am testing on Lollipop

Do i need net connection?
any help will be appreciated.
Answer: Yes you'll be needing Internet for this. Paste Following permissions inside your manifest file:
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Right now all the devices are not supporting offline speech input. To enable offline speech input for supported devices follow below steps:

On your device go to Settings -> Language and Input. Click on icon on Google voice input.
Under ALL tab select the language you want to download.
3. Once the language package downloaded, you can see it under INSTALLED tab.

I have downloaded speech input packages on my Nexus 5 and offline speech is working fine.

For further reference checkout the below link:
https://web.archive.org/web/20160218040751/http://www.androidhive.info/2014/07/android-speech-to-text-tutorial/
Comment: I tried with internet connection on. It seems to be working fine. but why it isn't working offline? I have English(US) voice by default.(See added screenshot of device)
Comment: Checkout the link I mentioned at the  end of my answer, that's what they have stated that offline support doesn't seems to be working fine on all devices.
Comment: After digging out for some time i found that they have some macros on their side which are needed for its functionality. so even if you have downloaded language in speech to text you still need internet connection

unable to use android Speech to text


JQuery 2 Data Table use one page

Question: I have two table in my page i got this data using Ajax. Now i want to add default contain like add button. When i click the button it will go with a id. But when i do that normally for one table its work. But when i use two table with different id its not work it id is not show accurately.
$(function () {
        var table = $('#example6').DataTable({
            'paging': true,
            "serverSide": true,
            ajax: {
                url: "{{ url('/manage-order/data') }}",
                type: 'post'
            },

            "columns": [

                {"data": "vn_name"},
                {"data": "vn_id"},
                {"data": "total_payment_amount"},
                {"data": "total_due_ammont"},

                {
                    "data": null,
                    "defaultContent": "\n" +
                    "\n" +
                    "\n"
                }
            ]
        });

        var table = $('#example5').DataTable({
            'paging': true,
            "serverSide": true,
            ajax: {
                url: "{{ url('/manage-general-sales/data') }}",
                type: 'post'
            },
            "columns": [

                {"data": "vendor_name"},
                {"data": "total_payment_amount"},
                {"data": "total_due_amount"},
                {
                    "data": null,
                    "defaultContent": "\n" +
                    "\n" +
                    "\n"
                }
            ]
        });
        $('#example6 tbody').on('click', '#addBtn', function () {
            var data = table.row($(this).parents('tr')).data();
            var vn_id = data['vn_id'];
            var url = "{{url('/create-order/')}}/" + vn_id;
            window.location.href = url;
        });

        $('#example5 tbody').on('click', '#addBtnGneral', function () {
            var data = table.row($(this).parents('tr')).data();
            var id = data['id'];
            var url = "{{url('/create-general-sales/')}}/" + id;
            window.location.href = url;
        });

    })

Some one please help me.
Answer: You used same table variable, you should make them different to do some actions with them.
$(function () {
        var table1 = $('#example6').DataTable({
            'paging': true,
            "serverSide": true,
            ajax: {
                url: "{{ url('/manage-order/data') }}",
                type: 'post'
            },

            "columns": [

                {"data": "vn_name"},
                {"data": "vn_id"},
                {"data": "total_payment_amount"},
                {"data": "total_due_ammont"},

                {
                    "data": null,
                    "defaultContent": "\n" +
                    "\n" +
                    "\n"
                }
            ]
        });

        var table2 = $('#example5').DataTable({
            'paging': true,
            "serverSide": true,
            ajax: {
                url: "{{ url('/manage-general-sales/data') }}",
                type: 'post'
            },
            "columns": [

                {"data": "vendor_name"},
                {"data": "total_payment_amount"},
                {"data": "total_due_amount"},
                {
                    "data": null,
                    "defaultContent": "\n" +
                    "\n" +
                    "\n"
                }
            ]
        });
        $('#example6 tbody').on('click', '#addBtn', function () {
            var data = table1.row($(this).parents('tr')).data();
            var vn_id = data['vn_id'];
            var url = "{{url('/create-order/')}}/" + vn_id;
            window.location.href = url;
        });

        $('#example5 tbody').on('click', '#addBtnGneral', function () {
            var data = table2.row($(this).parents('tr')).data();
            var id = data['id'];
            var url = "{{url('/create-general-sales/')}}/" + id;
            window.location.href = url;
        });

    })

Comment: Thanks a lot @DennisFrea

JQuery 2 Data Table use one page


The normalizer of a torus is a closed subgroup of the Lie group

Question: Let $G$ be a Lie group and $T \subset G$ a torus, show that $N(T)$ is a closed subgroup of $G$.  Could somebody give a sketch of the proof?
Answer: Say $n_i\in N(T)$ converges to $n$, and let $t\in T$.
Then $$n_itn_i^{-1}\rightarrow ntn^{-1}.$$
Since $n_itn_i^{-1}\in T$ we have $ntn^{-1}\in T$ since $T$ is closed.
Comment: thanks for the answer!  So the key is $T$ is closed, which is true because of its monogenicity, right?
Comment: Yeah, it seem to hold for any closed subgroup. Sorry, I cant remember what monogenicity means at the moment.


Can I use KernelPCA after using TruncatedSVD before clustering?

Question: I am working on a project at a company where I have to make clustering/unsupervised model. The data I am working on is very sparse with high dimensions and after some research, I found out TruncatedSVD is good for sparse data.
So I applied TruncatedSVD on my data and ran a few clustering(k-means and GMM) algorithms on it and then I used top2 and top3 featured from truncatedSVD transformation to visualize the data in 2d and 3d space but the clusters are not distinctively separated.
So I did some more research I found out that kernel PCA is good at finding the separation between the data but it might not be good for sparse data. So my question is Can I use kernel PCA after transforming the data with truncatedSVD?
Will this be a correct approach that I can try? or are there are any other suggestion on how to tackle this problem?
To give you an idea about the dataset
My data includes user_ids(unique) and their corresponding click frequency on multiple webpages and the click frequency on topics also there are some more variables related to time like time different between session and number of distinct days the user has visited the website etc.
Answer: It's one of her many combinations that does not make a lot of sense when you bother to try to understand the methods.
SVD tried to generate a projection where there is some kind of linearity in the factors. KernelPCA is used when you know non-linear relationships exist in your data.
It's generally a bad idea to just stack method on method that you don't know well. It is, unfortunately, easier to get a good looking but wrong result than an okay looking sound result. You should rather spend that time to better understand your data, your problem, and the theory of the methods, to identify how to align these three. In the end, don't aim for a result, but for an explanation.


Error from central difference seems large

Question: for a function $f(x)=e^{2x}-\cos(2x)$,
at grid points $x \in {-0.3,-0.2,-0.1,0}$
I perform a central difference for the derivative at $x=-0.2$
$$\frac{df}{dx}=\frac{f(-0.1)-f(-0.3)}{2*(-0.1--0.3)}=0.28795$$
The derivative of this function (per mathematica) is $0.561803$
So the error is $$Abs[0.561803-0.28795]=0.273853$$
I have a formula for the upper bound of the error, and that formula is $$\frac{M^*\Delta x^2}{3!}=\frac{8*(-0.1--0.3)}{6}=0.0533333\\\text{Where }M^*=\text{Max}(f''(x)|x\in[-0.3,0])=f(0)=8$$
The issue is the error, $0.27$, is greater than the supposid error bound, $0.05$. When I graph this function with its central difference though, it looks correct.

Any idea why my derivatives are higher than the upper bound? The error does seem pretty high.
Answer: The problem lies in your definition of $\Delta x$, remember that
$$
f'_{FD}(x) \approx \frac{f(x + \Delta x) - f(x - \Delta x)}{2\Delta x}
$$
Taking $x = -0.2$ and $\Delta x = 0.1$ we get
$$
f'_{FD}(-0.2) \approx \frac{f(-0.1) - f(-0.3)}{2 \cdot 0.1} = 0.575941 \tag{1}
$$
So the actual error is
$$
\epsilon = |f'_{FD}(-0.2) - f'(-0.2)|= 0.0141374 \tag{2}
$$
Now, the prediction for the error is
$$
\epsilon_{\max} = \frac{|f^{(3)}(c)|\Delta^2 x}{6} \stackrel{c=-0.3}{=} 0.0148461 \tag{3}
$$
You can indeed see that
$$
\epsilon < \epsilon_\max
$$
Comment: Thanks so much! But is the formula for the error bound really supposed to be the third derivative of $f$ or the second?

I got the formula from someone else's notes! I couldn't find it with a google search hahaha.
Comment: @Frank It is the third derivative


How can I find the rank of this linear transformation

Question: Suppose $Q \in  M_{3 \times 3}\mathbb(R)$ is a matrix of rank $2$.
Let $T : M_{3 \times 3}\mathbb(R) \to M_{3 \times 3}\mathbb(R)$ be the linear transformation defined by $T(P) = PQ$. Then rank of T is:
I have searched the site and found that Find Rank of given Linear transformation. is very similar to my question.
The only difference is that role of matrices are  reversed.
But i cannot see how to correctly use the answer given in the original question to solve mine.
Here is what I came up with
since Rank($AB$) $\le$ min(Rank$A$, Rank$B$)
so Rank T = Rank($PQ$) $\le$ min(RankP,Rank $Q$)  < Rank(Q)
so we can simply consider the dimension of all linear transformations from $R^3$ to Q
that will give us the rank of T.
hence rank of T = 6
Is this correct ? if not can anyone give me the correct solution please.
Comment: The last part '*so we can simply consider the dimension of all linear transformations from $\Bbb R^3$ to $Q$*' is not clear. First, I guess you mean all linear maps to the *image* of $Q$.
Answer: Actually, as your linear transformation is $\operatorname T(\operatorname P) = \operatorname{PQ}$ where $\operatorname Q$ is a matrix of $\operatorname {rank} 2$, and hence if you do consider the standard basis of $\operatorname M_3(\mathbb R)$ as $\beta = \{ \operatorname E_{ij} : i,j \in \{1,2,3\} \}$ where
 $\operatorname E_{11} = $$
             \begin{bmatrix}
              1 & 0 & 0 \\
              0 & 0 & 0 \\
              0 & 0 & 0 \\
             \end{bmatrix}
             $$  \ etc ....$, then you can easily check that $$\operatorname T(\operatorname E_{ij}) = \sum_{k=1}^3 q_{jk}\operatorname E_{ik}$$ for all $i \in \{1,2,3\}$ where $\operatorname Q = (q_{ij})_{3×3} .$
Hence, it turns out that the matrix of transformation of $[\operatorname T]_{st}^{st}$  is a $9×9$ matrix and as $\operatorname {rank}
(\operatorname Q) =2$ , hence writing the $9×9$ matrix, there are exactly $3$ linearly dependent columns, hence
$\operatorname {rank} (\operatorname T) = (9-3) =6$
Answer: Assume w.l.o.g. that $q_1,q_2$ are linearly independent columns of $Q$ and $q_3=\alpha q_1+\beta q_2$.
Then $PQ=\big[Pq_1\,\mid\, Pq_2 \,\mid\, \alpha Pq_1+\beta Pq_2\big]$.
Now, for any vectors $a, b\in\Bbb R^3$, one can find a matrix $P$ such that $Pq_1=a$ and $Pq_2=b$ (think about e.g. basis extensions and basis transformations).
It means that exactly the $3\times 3$ matrices of the form $\big[a\mid b\mid\alpha a+\beta b\big]$ will be in the image of the mapping $P\mapsto PQ$.
And these matrices depend on $6$ scalar values (the coordinates of $a$ and $b$), so indeed, its rank is $6$.


Dúvida sobre Null Byte no Bcrypt PHP

Question: Bom, fiquei sabendo que o Bcrypt do PHP é vulnerável à Null Byte.
Quais são testes que eu tenho que fazer para ver essa vulnerabilidade, e quais são as consêquencias disso??
Comment: Bem até onde eu sei, ninguém vai inserir um caractere nulo em uma senha, então há muito com o que se preocupar. Se a pessoa usar um caractere nulo na senha, ela estará vulnerável a um "dictionary attack".
Answer: Várias funções do PHP são (ou já foram) vulneráveis a bytes nulos, um dos maiores problemas era do include(), que o PHP parava ao encontrar o nulo, o que permitia ignorar a extensão do arquivo.

No caso do BCrypt (não sei como anda o Argon2i no PHP), ele irá usar a string até encontrar um nulo.
Então:
$hash = '$2y$10$/nX1tLiwOsGWL4MhUjfEIOBKLV.Oa/uVy7rxqxih2SeNIkCk8doEW';

echo (int)password_verify("a", $hash);
echo PHP_EOL;

echo (int)password_verify("a\0bcde", $hash);
echo PHP_EOL;

echo (int)password_verify("a\0zzzzz", $hash);
echo PHP_EOL;

Todos eles retornam 1, mesmo que sejam diferente.

Isso ocorre porque a hash em questão foi criada com um nulo, de tal forma que:
password_hash("a\0 Qualquer Coisa Aqui Será Ignorada", PASSWORD_DEFAULT)

Este é o problema do null-byte. Em geral ele não é um grande problema, uma vez que senha deve ser definida usando nulos, até onde eu saiba. Entretanto isso irá burlar o número de caracteres mínimos para uma senha. Porque a\0 Qualquer Coisa Aqui Será Ignorada será mais de 10 bytes, por exemplo, mas sua senha terá apenas 1 byte (a).

A solução disso é fazer um pre-hashing, mas deverá codificar para um formato seguro, afinal o resultado de um SHA-2, por exemplo, pode conter um nulo.
A outra opção talvez seja abandonar o BCrypt, você tem o LibSodium no PHP, creio que estas funções (especificamente o sodium_crypto_pwhash_str) não tenha problemas.

Dúvida sobre Null Byte no Bcrypt PHP


Convert double number to float number

Question: I need to do some elaborations on MATLAB data in Python.
The data is stored as an array of doubles in Matlab. When I retrieve it, despite being stated here that double data types from Matlab are converted in float data types when handled by Python, I get this error:

TypeError: unorderable types: double() < float()

What I'm trying to do is this
import matlab.engine

eng=matlab.engine.connect_matlab()

x = eng.workspace['MyData']
x = x[len(x)-1]
if x < 0.01:
    #do stuff

How can I convert the double number stored in the array to a float so that I can use it alongside my other Python variables?
Comment: then try doing `np.array(x)` after your `x = eng.workspace` (np is for `import numpy as np`)
Comment: Have you tried float(x) < 0.01?
Comment: @DavidLeon yes, it only accepts int or strings as arguments, so no luck
Comment: what returns `type(x)`?
Comment: it returns mlarray.double
Answer: Converting doubles into floats in Matlab is as simple as calling the single function:
A = rand(10);
whos A;

B = single(A);
whos B;

As per console output:
  Name       Size            Bytes  Class     Attributes

  A         10x10              800  double

  Name       Size            Bytes  Class     Attributes

  B         10x10              400  single

Be careful about the loss of precision, since you are converting 64 bit numeric values into 32 bit numeric values.
EDIT
Since you can't manipulate your Matlab data, in order to accomplish this I suggest you to use either Numpy (refer to this function in case: https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.ndarray.astype.html) or struct for a straight conversion (refer to this answer in case: convert double to float in Python).
Comment: For sure it can be helpful (https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.ndarray.astype.html) but you have to change some logics into your Python code and learn to use that framework. Alternatively, if you want a quick and dirty solution, you can use `struct` for straight conversions (refer to this answer https://stackoverflow.com/questions/13291539/convert-double-to-float-in-python).
Comment: Hi, thanks for your reply. Unfortunately, I cannot do any preelaboration on the data in Matlab, since it's coming from the simulation of a real plant implemented in simulink, and is practically untouchable. I need to do as much as possible in Python, if there is a way.
Comment: Are you using Numpy?
Comment: Actually no, is it helpful in this context?
Comment: I will take a look at the documentation. By the way, the solution you proposed in your answer still doesn't seem to work, it results in the same error only with 'single' instead of 'double'...
Comment: I eventually solved it using the numpy documentation you linked in the previous comment. If would like to edit your answer with that information, I can mark it as solved. Thanks!
Comment: Good to know! Thanks for the feedback!

Convert double number to float number


Find articles or modules in remote server

Question: I have my website done in Joomla in local and it work fine.
I moved my website to a remote server and now I have links and other things that do not work.
I connect by ssh to my server but I cannot find my custom articles (without category) or my personalize HTML modules.
Where can I find this on my server?
Comment: Your articles should be in the database (table #__content), and if you mean 'custom HTML' module, then the information is in the db too (table #__modules).
Comment: I hope you copied the database as well !
Answer: Chances are you didn't move the site over properly. The easiest way to move a site is to use Akeeba - https://www.akeebabackup.com/.


Find all the relative extrema of $f(x)=x^4-4x^3$

Question: Find all the relative extrema of $f(x)=x^4-4x^3$

$Solution:$
Step 1: Solve $f'(x)=0$.
$f'(x)=4x^3-12x^2=0$
$\rightarrow$ $4x^2(x-3)=0$
$\rightarrow$ $x=0$ and $x=3$
Step 2: Draw a number line and evaluate the sign of the derivative on each section (I don't know how to draw a number line on the computer but I'll do what I can).
Lets pick a number in the region $(-\infty,0)$, how about $x=-1$:
$f'(-1)=4(-1)^2(-4)=-16<0$
Now lets pick a number in the region $(0,3)$, how about $x=2$:
$f'(2)=4(2)^2(2-3)=-1<0$
Now lets pick a number in the region $(3,\infty)$, how about $x=4$:
$f'(4)=4(4)^2(4-3)=64>0$
So our function is decreasing as $x$ increases towards $0$, then our function decreases as $x$ increases towards $3$, then our function increases as $x$ increases towards $\infty$. Therefore we have a relative minimum when $x=3$ and no relative maximum. Lets solve for the corresponding $y$ value:
$f(3)=3^4-4(3)^3 = 81-4(27)=-27$
So we have a relative minimum at $(3,-27)$ and our relative maximum DNE
Comment: Looks OK. I would just mention that $(0,0)$ is a critical point, but not a maximum or minimum.
Comment: I think it's okay except when you say, "So our function is increasing as $x$ increases towards $0$," you mean "So our function is decreasing as $x$ increases towards $0$."
Comment: "Draw a number line" I don't that drawing the line is important.  As the derivative is (presumably) continuous, it cant change sign mid-segment it's fine to pick a sample point.  Which is what you did.  Also you can take the second derivative. If $f''(x)<0$ then $x$ is a local maximum (the derivative was getting less steep will it hit zero and the function plateaued, then the derivatie will  become negatie and the function goes down).  If $f''(x)>0$ then $x$ is a local minimum. If $f''(x)=0$ it inconclusive. As $f''(0)=0$ both deriv and function "flat line". In this case x is saddle point.
Comment: As Saulspatz pointed out, you correctly showed $f'(x)<0$ on $(-\infty,0)$ but incorrectly stated that $f$ was *increasing*. But presumably this was a typo since it didn't affect your conclusion. Other than that, I think your solution and proof are good.
Comment: You cannot say that there is not a relative maximum with your methode.
Answer: Once you have identified $x_0=0$ and $x_0=3$ you can also evaluate the sign of $f(x)-f(x_0)$.

$x_0=0$ where $f(0)=0$

$$f(x)=x^3\underbrace{(x-4)}_{<0}$$
Thus the sign of $f(x)$ is determined by the sign of $x^3$ around $0$ which is not constant so $x_0=0$ is an inflexion point.

$x_0=3$ where $f(3)=-27$

Let set $u=x-3$ then $$f(x)-f(3)=(u+3)^3(u-1)+27=18u^2+8u^3+u^4=\underbrace{u^2}_{\ge 0}\underbrace{(u^2+8u+18)}_{\Delta=-8\implies >0}\ge 0$$
Thus $f(3)$ is a global minimum.
Answer: Solution without derivative.
By AM-GM $$x^4-4x^3=3\cdot\frac{x^4}{3}+27-4x^3-27\geq4\sqrt[4]{\left(\frac{x^4}{3}\right)^3\cdot27}-4x^3-27=$$
$$=4|x^3|-4x^3-27\geq-27.$$
The equality occurs for $x=3,$ which says that we got a minimal value.
The maximum does not exist because $$\lim\limits_{x\rightarrow+\infty}(x^4-4x^3)=\lim_{x\rightarrow+\infty}x^4\left(1-\frac{4}{x}\right)=+\infty.$$
Comment: Alternate proofs are appreciated, thanks mon!!
Comment: I'm not the downvoter but I think the OP was asking for a proof *verification*, not an alternative proof.
Answer: More sophisticated is to take a second derivative which indicates the rate of change of the derivative when the derivative is zero.  (Assuming the second derivative exists)
A derivative $f(x)=0$ means to function has "flatlined" as $x$. Four things can/will occur. [For purpose of analogy, I was consider the graphs moving in time. And values $x'< 0$ I will use past tense.  $x' = x$ is "now" and I'll use present tense. And $x' > 0$ I'll use future tense.
1) The function could have been climbing, is now reaching a peak, and then will decline.  (In which case this is a local maximum.)
That means that the derivative was positive, hits zero, and will then be negative.
The will be the case if $f''(x) < 0$.  That would mean the derivative represented a positive steepness in the function but the steepness was decreasing, it decreases to $0$ steepness at which point the function plateaus, and then will become negatively step and and function will begin to go down.
However this could also be the case if $f''(x)=0$.  The function could have been raises, the steepness (derivative) decreasing but decreasing less and less, the function then plateaus while the rate of change in steepness sloughs to zero, then the rate of change in steepness becomes active again and the steepness becomes negative and the function will begin to drop.
So $f'(x)=0$ and $f'''(x) < 0$ means $x$ is a local maximum.  $f'(x)=0$ and $f''(x)=0$ means it could be, but isn't necessarily, a maximum.  If $f'(x)= f''(x)=0$ and $x$ is a local maximum  that is called an undulation point.
2) The function could have been dropping, is now flatlining, and will then raise.
This is the exact opposite as above for the same reasons.  And is a local minimum.
The will always by the case if $f''(x) > 0$.  If $f''(x)=0$ this could, but isn't nescessarily  the case.  If $f'(x)=f''(x) = 0$ and $f(x)$ is a local minimum this is another example of an undulation point.
3) The function was raising/dropping, is now flatling, but will then continue to raise and drop.
In this case the steepness (derivative) of the function was positive/negative, has leveled to zero, but rather than continuing to become negative/positive and will return to be positive/negative.  This would be a local min/max for the derivative.
IF the second derivative exist it will have to be that $f''(x) =0$ and this point.  (But it need not exist.  $f'$ could be making a "sharp turn" while $f$ is still differentiable).
But $f''(x) = 0$ will not assure this must be the case.
In this case this is called a  saddle point.
4) $f(x)$ have been, or will be, a constant for an interval.
If which case $f', f'', f'''$ etc so long as they actually are defined will be $0$.
====
$f''(x) = 12x^2-24x$.  $f''(3)=12*9-24*3 > 0$ so $x = 3; f(3)= -27$ is a local minimum.
$f''(0) = 0$ so it isn't clear what type of critical point $(0,0)$ is.  Taking point sample of $x=-1,2$ show you it is a saddle point.
If we have the patience and clear head  we could note that:
$f'''(x)=12x^2 - 24$ and $f'''(0)=-24 < 0$  So that means that $f'(0)=0$ was a local maximum for $f'$.  So the derivative had been less than $0$, so the function had been decreasing, the derivative is $0$ and $x=0$ and the function is flatlining, but the will drop down to being negative again, so the function will start to decrease againd.  SO $x=0; f(x)= 0$ is a saddle point.


entityQuery filter by content moderation state

Question: I need to filter a node by moderation state. I am using the Drupal 8 content moderation module.
I basically want to get NIDs of all nodes in draft state. Something similar to this.
$nids = \Drupal::entityQuery('node')
      ->condition('moderation_state', 'draft')
      ->execute();

Answer: An additional workaround to this is you can add a tag to the entity query and then alter it in a separate hook_query_TAG_alter hook. It's an extra step but it gets the job done and gives you direct access to the SQL query for you to modify. So you can generate the entity query like you normally would, and any extra SQL that it does not support you can modify as needed.
Entity query:
/** @var \Drupal\node\NodeStorage $storage */
$storage = \Drupal::entityTypeManager()->getStorage('node');
$query = $storage->getQuery()
  ->addTag('archive_press_releases')
  ->currentRevision()
  ->condition('type', ['post_page', 'story_page'], 'IN')
  ->condition('field_date', $formatted, '<=')
  ->sort('field_date');
$result = $query->execute();

hook_query_TAG_alter example:
/**
 * Implements hook_query_TAG_alter().
 */
function bax_archiving_query_archive_press_releases_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->addJoin('LEFT', 'content_moderation_state_field_data', 'md', 'md.content_entity_revision_id = base_table.vid');
  $query->condition('md.moderation_state', 'archived', '<>');
}

Comment: Thanks for the example, it almost worked for me. It lacks the eventual control on the node language (if translation is also enabled) and it may give unwanted result in the case nodes are moved from `archived` to another not-default state, e.g. `draft`. This latter case is problematic is one want to exclude only `archived` nodes in the latest revision. I've add an example for a case with those two condition.
Answer: You try the code :
$query = \Drupal::database()->select('content_moderation_state_field_data', 'ms');
    $query->join('node_field_revision', 'nf', 'nf.nid=ms.content_entity_id AND nf.vid=ms.content_entity_revision_id AND nf.langcode=ms.langcode');
    $query->fields('ms');
    $query->condition('ms.moderation_state','draft');
    $results = $query->execute()->fetchAllAssoc('content_entity_id');

Because entityQuery not filter content moderation
Comment: Just to add more information about this entityQuery limitation. https://www.drupal.org/project/drupal/issues/3025164
Answer: Posting a link to the d.o issue queue where as of this week a potential patch to core to allow EntityQuery to recognize Workflow moderation state that @Santiago cited above:
https://www.drupal.org/project/drupal/issues/3025164#comment-13221005
Without this patch or a similar core hack, EntityQuery can not query Drupal 8 Workflow moderation state.
Answer: The answer by Lester Peabody almost worked for me.
However, it could gives unwanted results, depending the logic you expect.

archived state by default settings is a default revision state, therefore querying for currentRevision() nodes will count also the ones which have another not-default moderation state.
E.g.:a node has been archived and later moved again in draft With that query that node will be counted. In the case this is not wanted, it's better to query against nodes' latest revision.
It doesn't consider the case the eventual translation.

If 1. and 2. are legit cases then the coode is:
function example() {
    $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();

    return $query->addTag('example_tag')
      ->latestRevision()
      ->condition('type', 'node_type')
      ->condition('langcode', 'en')
      ->execute();
}

/**
 * Implements hook_query_TAG_alter().
 */
function hook_query_example_tag_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->addJoin('LEFT', 'content_moderation_state_field_revision', 'md', 'md.content_entity_revision_id = base_table.vid AND md.langcode = base_table.langcode');
  $query->condition('md.moderation_state', 'archived', '<>');
}


Selenium - Geckodriver (Firefox) load unpacked extension

Question: I coded my own extension and I want to add it to geckodriver.
The important thing is I need to add it unpacked as I did for chromedriver.
options.addArguments("--load-extension=" + System.getProperty("user.dir") + "/base/chrome-extension");

Is it possible?
If unpacked is not possible, then, can I install it with creating an archive for that?
Comment: I found your question trying to find out how to do this with the `selenium-webdriver` JavaScript API. The easiest way seems to be using Mozilla's tool https://github.com/mozilla/web-ext. You can also use that tool to sign your extension when you're ready to publish. Good luck, and please let us know if you found a solution!
Comment: What about https://stackoverflow.com/a/57612283/5097027
Comment: No, man, I am looking for "unpacked"
Comment: We were happily using `web-ext sign` to create XPI files for use with wdio until a Mozilla reviewer wanted to review one.

This is now their policy as they can't tell whether you're signing it to test or to supply to real users.

We can't risk having to go through the review rigmarole every time we make a test build so I too want to load our extension unsigned.

`{ services: [['firefox-profile', { extensions: ['./dist/qa/firefox'] }]] }`

doesn't throw any errors but doesn't load the extension.
Answer: For (local) firefox webdrivers, simply use driver.installExtension as mentioned in the docs.
As for remote firefox webdrivers (or Selenium Grid), use Augmenter as mentioned in this issue.
The following is an example of Augmenter provided in this webpage with MIT license:
driver.setFileDetector(new LocalFileDetector());
WebDriver augmentedDriver = new Augmenter().augment(driver);
String id = ((HasExtensions) augmentedDriver).installExtension(Paths.get("src/test/resources/ninja_saucebot-1.0-an+fx.xpi"));

driver.get("https://www.saucedemo.com");
Assertions.assertTrue(driver.findElements(By.className("bot_column2")).size() > 0);
((HasExtensions) augmentedDriver).uninstallExtension(id);

driver.navigate().refresh();
Assertions.assertEquals(0, driver.findElements(By.className("bot_column2")).size());


Php retorna JSON nulo quando tem acento no MySQL

Question: Olá, tenho o seguinte código em php:
<?php
   $con=mysqli_connect("localhost","user","senha","banco");
   $parametro = $_GET["parametro"];
   if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " .mysqli_connect_error(); }
   $sql = "SELECT * FROM " . $parametro;

   if ($result = mysqli_query($con, $sql))
   {
        $resultArray = array();
        $tempArray = array();

    while($row = $result->fetch_object())
    {
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }
    echo json_encode($resultArray);
}
mysqli_close($con);
?>

Ele retorna um JSON com uma tabela do servidor MySQL  cujo o nome foi passada pelo parametro, mas quando tem um acento ou um "ç" por exemplo ele retorna null
O MySQL esta aceitando a acentuação, posso checar isso pelo phpmyadmin, o problema mesmo esta no php.
Para uma tabela cidades ele retorna isso:
[{"id":"1","nome":"Porto Alegre","estado":"RS"},{"id":"2","nome":"Rio de janeiro","estado":"RJ"},{"id":"3","nome":null,"estado":"SP"}]
Onde deveria ser São Paulo ele retorna null
já tentei utiliza o json_encode com a constante JSON_UNESCAPED_UNICODE para codificar literalmente os caracteres em vez de escapa-los.
echo json_encode($resultArray, JSON_UNESCAPED_UNICODE);
mas aparece esse erro: Warning: json_encode() expects exactly 1 parameter, 2 given in /home/diretorio/public_html/busca.php on line 24
como resolver isso?
Answer: Experimenta algo assim:
<?php
       $con=mysqli_connect("localhost","user","senha","banco");
       $parametro = $_GET["parametro"];
       if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " .mysqli_connect_error(); }
       $sql = "SELECT * FROM " . $parametro;

       if ($result = mysqli_query($con, $sql))
       {

        while($row = $result->fetch_object())
        {
            foreach($row as $key => $col){
               $col_array[$key] = utf8_encode($col);
            }
            $row_array[] =  $col_array;

        }
        echo json_encode($row_array);
    }
    mysqli_close($con);
    ?>

Answer: Solução mais simples encontrada é adicionar essas duas linhas:
$str = str_replace('\u','u',$decoded);
$strJSON = preg_replace('/u([\da-fA-F]{4})/', '&#x\1;', $str);

Fique atento à sua versão PHP, pois uso 5.5 e nos testes não tive este problema! Meus testes deram assim:
echo json_encode($json, JSON_UNESCAPED_UNICODE);

[{"id":"1","nome":"Porto Alegre","estado":"RS"},{"id":"2","nome":"Rio
  de janeiro","estado":"RJ"},{"id":"3","nome":"São
  Paulo","estado":"SP"}]

echo json_encode($json);

[{"id":"1","nome":"Porto Alegre","estado":"RS"},{"id":"2","nome":"Rio
  de janeiro","estado":"RJ"},{"id":"3","nome":"S\u00e3o
  Paulo","estado":"SP"}]
Comment: Cara, o melhor seria atualizar seu php para pelo menos 5.4.0, que assim ele aceitará o parâmetro JSON_UNESCAPED_UNICODE, ou você deverá achar alguma função que decodifique de utf8, mas as convencionais não deram certo aqui.
Comment: Mas como transformo o "S\u00e3o Paulo" em "São Paulo"? coloquei `

` mas mesmo assim não deu @Jhonnyjks
Comment: Essas duas linhas resolveram agora:

$str     = str_replace('\u','u',$decoded);
$strJSON = preg_replace('/u([\da-fA-F]{4})/', '&#x\1;', $str);

Encontrei em: http://stackoverflow.com/a/20181671/5664531
Answer: Amigo, você pode usar a função mb_convert_encoding para converter o encoding
//Neste caso, assumindo que o padrão esteja em ISO-8859-1 e você quer UTF-8
mb_convert_encoding($utf8, 'UTF-8', 'ISO-8859-1');
Comment: Eu preciso implementar essa função em algum lugar especifico? pq fiz uns testes aqui e ainda resultou em `null` @Duque
Comment: Essa é uma função interna do PHP, ela parte do principio que você sabe a codificação que está a string.
Qual o padrão de codificação que está os dados da tabela ?
Você pode testar também com mb_strtolower( $row, 'UTF-8');  para teste.
Faz ai e posta aqui de novo.
Answer: Uma linha antes do echo json_encode($resultArray), coloca isso:
$resultArray = array_map('utf8_encode', $resultArray);

Answer: Antes de retornar você chama uma função para converter o array em utf-8
$result = converteArrayParaUtf8($result); //chama a função
return json_encode($result); //retorna

função:
function converteArrayParaUtf8($result){
    array_walk_recursive($result, function(&$item,$key){
         if (!mb_detect_encoding($item, 'utf-8', true)) {
                $item = utf8_encode($item);
            }
    });
    return $result;
}


Pearson residues applied to the binary model

Question: My question would be about Pearson residuals applied to the binary model.
When we build confidence intervals for a proportion, p: we have a sample, and we count the number of individuals who have a certain characteristic in n (sample size), and therefore, p ^ = x / n, where x is the number of individuals with this characteristic. In this case, X is a binomial (n, p), that is, X is the sum of n random variables with Bernoulli distribution. When n is large, we apply the Central Limit theorem and say that X converges to Normal because the sum of many independent random variables converges to Normal.
But if Y has bernoulli distribution (1 or 0), then E(Y)=p and Var(Y)=1-p, so can we say that Z=(Y - E(Y))/sqrt(Var(Y) converges to a standard Normal distribution? Can I apply the Central Limit theorem?
In my study, each individual follows a Bernoulli distribution, that is, a Binomial(1, p). How do we bring together a group of individuals to add several Bernoulli in such a way that we can apply the Central Limit theorem? Or would you have another theory?
Thanks
Answer: Random thoughts:
In the following I'm assuming that your logistic regression provides as good enough fit that $\hat{p}$ from the logistic regression is a good approximation of the true success probability $p$.
(1)  Definitely $Z = (Y-p)/\sqrt{np(1-p)}$ won't converge in distribution to a normal distribution, because $Y$ is a single, Bernoulli random variable and does not represent a sequence of random variables.  Central Limit Theorem does not apply at all in this case.  ($Z$ has a shifted and scaled Bernoulli distribution with only two possible values, it's very much not normally distributed).
(2)  As you mentioned, if your data values $Y$ represent a collection of $n$ observations averaged together all with the same (under the logistic model) success probability $\hat{p}$, then, yes, if $n$ is fairly large (usual rule of thumb is that $np > 7$ and $n(1-p) > 7$, though this varies), $Y$ will be approximately normally distributed and $(Y-\hat{p})/\sqrt{n\hat{p}(1-\hat{p})}$ will be roughly $N(0,1)$.  However, this won't be very satisfying, because (i) you might not have any two observations with the same predicted success probability, so you would have to pool observations with similar success probabilities and (ii) this rather ruins the idea of looking for outliers, because pooling an outlier with a bunch of non-outliers will probably result in an innocent-looking residual.  This works if the original experiment was based on groups with the same regressor values and you want do detect which groups are anomalous, but not helpful in determining which individual observations are anomalous.
(3)  You actually can use Pearson residuals such as $Z=(Y-\hat{p})/\sqrt{\hat{p}(1-\hat{p})}$.  They won't have a normal distribution, but you can still get a concept of outliers by using bounds based on the Chebyshef Inequality, so, for instance, $|Z| > 5$ would be flagged as an outlier (not adjusting for multiple comparisons).
Comment: Thank you very much, your answer will be very useful.


Como passo corretamente o tipo de dados por PDO

Question: No trecho php abaixo, qual é o tipo de PDO::PARAM devo usar  ?
<code>$cnx = new PostgreSQL(); //Classe de conexão do banco
$data = '2015-02-13';
$select = 'SELECT * FROM eventos WHERE "data" = :data';
$query -> prepare($select);
$query -> bindParam(":data" , $data , ?)/
$result = $query -> execute();
$result = $query -> fetch(PDO::FETCH_ASSOC);
print_r($result);
</code>
Answer: A respota da questão é mesmo PDO::PARAM_STR, que conforme foi dito no link que deixo a baixo serve para string , datas e horas.

– PDO::PARAM_STR – para valores strings, datas, horas…
– PDO::PARAM_INT – para valores inteiros
– PDO::PARAM_BOOL – para valor booleano (true ou false)
– PDO::PARAM_NULL – valor nulo (null)
– PDO::PARAM_LOB – representa valores de grande quantidade de dados
– PDO::PARAM_STMT – representa um conjunto de registros, atualmente não é suportado por nenhum driver
– PDO::PARAM_INPUT_OUTPUT – especifica que é um parâmetro de entrada e saída para "stored procedures"

Fonte:  http://fazer-site.net/pdo-php-data-object/


Como colocar setas no grafico de uma curva paramétrica - Python - Plotly

Question: Eu postei essa mesma questão anteriormente no stack overflow (em inglês).
Sou novo em python e estou aprendendo a plotar funções paramétricas usando o plotpy.
Portanto, eu me "desafiei" a escrever um código que gera o gráfico paramétrico da curva γ:[-2π,2π] → R^2, γ(t)= (sin(t),t^2). Sendo assim, escrevi o seguinte código:
<code>import plotly as py
import plotly.graph_objs as go
import numpy as np

py.offline.init_notebook_mode(connected=True)

x = np.linspace(-2*np.pi, 2*np.pi, 3000)

layout = go.Layout(
    title='$\gamma(t) = (\sin(t),t^2),\ t\in[-2\pi,2\pi]$',
    )

trace1= go.Scatter(
            x=np.sin(x),
            y=x**2,
            mode='lines',
            line=dict(
                shape='spline'
            )
        )

fig = go.Figure(data=[trace1],layout=layout)
py.offline.iplot(fig)

</code>

Agora, gostaria de adicionar algumas setas neste gráfico, a fim de representar a direção do caminho que a curva γ está tomando. Ou seja, estou querendo gerar uma imagem semalhante a essa qui:

Procurei online sobre como fazer isso, mas até agora não encontrei nada.
Alguém sabe como fazer isso?
Comment: Dá pra fazer sem problemas com o Plotly utilizando [multiple-annotations](https://plotly.com/python/text-and-annotations/#multiple-annotations), mas não é um código simples se você quiser que as setas apontem na direção da curva, pois será necessário calcular o ângulo para onde elas apontam.
Comment: Vou tentar fazer, obrigado pelo comentario
Answer: Respondendo e não respondendo à sua pergunta: tens que trabalhar com as ferramentas que o plotly te dá. Infelizmente esta biblioteca não tem suporte para seu requisito. Sugiro que dê uma boa olhada na documentação do Plotly e veja se algum outro gráfico consegue suprir suas necessidades.
Espero ter ajudado!
Comment: matplotlib.pyblot da suporte, da uma olhada
Comment: no matplotlib.pyplot eu sei fazer, eu queria fazer usando o ploply pq ele é mais "bonito". Obrigado pela resposta


settings.bundle ios configure iOS8

Question: I have a problema with iOS8 and the bundle settings, I have a textField where is insert a URL in the settings and use it in my app, but in iOS 8 do not save the text of textField, when I go out of setting and return the textField is in default.
Somebody may be know if in iOS 8 something change about bundle settings.
Another strange change about it, is in iOS8, it have something like this (image), but in iOS 7, the settings do not have IPHONE SETTINGS part.
Comment: Did you ever resolve this issue?
Comment: No I am waiting for the beta 4 because in apple forum a lot of people have the same problem.
Comment: I can confirm this still happens with the latest betas.  Hopefully the GM clears it up.
Comment: The GM has the same problem for me.
Comment: And this looks like the same question: http://stackoverflow.com/questions/25134171/ios-setting-bundle-issue-with-ios-8-at-simulator
Comment: Las answer in apple forum.
Answer: Last answer apple forum.
View or Reply online: https://devforums.apple.com/message/1038479#1038479
--- Fibonacci
I observed the same problem on the GM simulator, both with my app and the AppPrefs sample. When I installed the iOS 8 GM on a iPad 2 physical device, however, the problem went away.
So there is at least some hope that the bug is in the simulator only, and not in the system that will be landing on all our customers' devices in a week! If anyone else watching this thread can test on other physical devices with the GM system, please post your results here.
Comment: On physical devices with IOS 8 exist this part IPHONE SETTINGS. I don't think this is a bug at all.

settings.bundle ios configure iOS8


gulp-eslint Environment key "es2021" is unknown

Question: I have a project with the following dependencies;
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "browser-sync": "^2.26.13",
    "del": "^6.0.0",
    "eslint": "^7.16.0",
    "eslint-config-standard": "^16.0.2",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "gulp": "^4.0.2",
    "gulp-cssmin": "^0.2.0",
    "gulp-eslint": "^6.0.0",
    "gulp-htmllint": "0.0.19",
    "gulp-htmlmin": "^5.0.1",
    "gulp-imagemin": "^7.1.0",
    "gulp-jsmin": "^0.1.5"

When I try to run a gulp task that lints javascript, using eslint/gulp-eslint;
function javascript() {
    return src('private/script/**')
        //.pipe(jsmin())
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError())
        .pipe(dest('public/script'));
}

I get the following error;
Error: .eslintrc.json » eslint-config-standard:
        Environment key "es2021" is unknown

I used npx eslint --init to generate the following configuration file;
{
    "env": {
        "browser": true,
        "commonjs": true,
        "es6": true
    },
    "extends": [
        "standard"
    ],
    "globals": {
        "Atomics": "readonly",
        "SharedArrayBuffer": "readonly"
    },
    "parserOptions": {
        "ecmaVersion": 2018
    },
    "rules": {
    }
}

i have done an npm install, to make sure I have the latest version of the dependencies. I have also read on guthub that the error might have something to do with gulp-eslint as it is an old version and might not be using the current version of eslint, however, in I have changed gulp-eslint package.json to use the latest version of eslint and no luck. I also updated node/npm to their latest lts versions.
Answer: I fixed this by deleting the eslint folder in the node_modules folder for gulp-eslint. this forces node to use the version you have as a dependency rather than the version the project maintainer wants to use.
it appears this is a known issue.
Answer: The problem is that gulp-eslint works with ESLint 6 under the hub, and ESLint 6 does not support the es2021 environment (see the supported environments of ESLint 6).
I'm going to show three options to handle this. The best solution will depend on your setup and requirements.
Method 1: Replace es2021 with an equivalent definition
The es2021 environment is the same as es2020 with the addition of the globals AggregateError, FinalizationRegistry and WeakRef (see the definition of es2021), so you could enter these settings in your .eslintrc configuration file instead to obtain the same result.
{
  ...
  "env": {
    ...
    "es2020": true
  },
  ...
  "globals": {
    ...
    "AggregateError": "readonly",
    "FinalizationRegistry": "readonly",
    "WeakRef": "readonly"
  },
  ...
}

Method 2: Force gulp-eslint to use ESLint 7
If you are using npm >= 8.3 < 9.0 (check this with npm -v), you can override the version of ESLint used by gulp-eslint.
To do so, first add an override entry to your package.json file like this:
{
  ...
  "overrides": {
    "gulp-eslint": {
      "eslint": "7"
    }
  },
  ...
}

then run:
npm install

Now, gulp-eslint will work with the latest version of ESLint 7 which does recognize the es2021 environment (it exists in ESLint >= 7.8).
Note that gulp-eslint does still not support ESLint 7, so some things may not work as expected. Particularly, some plugins may fail to load or produce runtime errors.
Method 3: Use gulp-eslint-new
gulp-eslint-new works with ESLint 8 and can be used in most situations as a drop-in replacement for gulp-eslint, provided that the configuration is compatible with both versions.

Uninstall gulp-eslint with
npm uninstall gulp-eslint

Install gulp-eslint-new with
npm install -D gulp-eslint-new

In your gulpfile, replace the import of gulp-eslint with gulp-eslint-new.

DISCLAIMER: I am currently the only maintainer of gulp-eslint-new.
Answer: I solve it by upgrading eslint version to version 7
This is what my package json looks like
Comment: Random: Nice Webstorm theme. care to share?
Comment: that was material ui themen @LuisRodriguez


Is using a questionnaire score (EuroQol's EQ-5D) with a bimodal distribution as outcome in linear regression a problem?

Question: There is currently a debate whether the EQ-5D score that has a ceiling problem and a bimodal distribution can be used in a linear regression model or not.
Background
The score is very simple and frequently used to assess patient's health related quality of life and consists out of five questions where each has 3 possible answers (there is a newer with 5 answers but it's less used).
The score is commonly used in national registries as a patient reported outcome measure (PROM) and is very convenient because the questions are easy to answer and the completeness is therefore good.
Continuous score
The score is created by using a "tariff" where unique combinations of the 5 variables translate into a continuous-like variable but with the above mentioned limitations. I'm not sure how they decide on the tariff score but the different combinations of the answers combine into a unique value, for instance if you have answered best health on all five categories you get a code of 11111 that gives the maximum of 1.000. If you've answered best on the first 2 question and worst on the last 3 you have a code of 11333 and get a score of -0.066. The score is country-adjusted and ranges between -0.594 to 1.000 in my Swedish tariff.
The Paretian calculation
In most orthopaedic studies we have a preoperative score and a postoperative score. By comparing the two models as the Paretian Classification of Health Change suggests we get four possible outcomes; no change, worse, improved, or mixed change. Mixed meaning that one category became improved while another one deteriorated. As I understand the Paretian outcome is best analyzed using a multinomial logistic model.
My questions

When having large datasets of > 10 000 patients does it matter that the score is not normally distributed and is the Paretian way of analyzing the score better?
Scores like this are very frequently used today - what are the limitations?

Update
After taking all these wise arguments and discussing them closer with our statistician I got some interesting input:

In large sample the central limit theorem will kick in as long as the sample isn't heavily skewed
If the score itself has a flaw (as the EQ-5D score) it might not be right to expect a normal distribution because the bimodality is not due to a subgroup but due to a score feature (I think this is a different way of putting what @whuber wrote: "... The residuals will closely reflect that error distribution"
The normality of the sample helps in calculating the p-value/confidence interval and this could be circumvented by using bootstrapping
Using ordinal regression and leaving out the mixed group we can validate the results from the linear regression - i.e. show that the predictors behave similarly when used "non-parametric"
Comment: Hi Max, how is the score from the test use?. Assuming the possible total score ranges from 5 to 15, are the incremental changes in score important?
Comment: Hi Michelle, I've added what I know of how the score is calculated and tried to clarify the question some. I think the main discussion is if it's OK to have a non-normal variable in a regression as the outcome or if this breaks some fundamental assumption. I'm not that familiar with multinomial regression so I'm also a little curious of how this impacts the interpretation, it's much easier to have a score being ".2 better in females" than "20% more improved in females and 30% more mixed results in females"
Comment: I'm not familiar with this usage of the word "tariff"; I've tried googling it but all I can find are references to taxation :) I think you just mean the rules/weights by which the score is produced, but if I'm wrong, let me know.
Comment: Sorry if that's unclear - I guess it's more commonly used in Swedish where it's like a taxtable - depending on your answers you're taxed differently. What I mean is simply the way the answers are translated into a "continuous variable". I've changed the question to clarify.
Answer: One question that you ought to ask first is whether or not using a weighted score is correct for the kind of analysis that you want to do.  There is a discussion of that in Parkin, D., Rice, N. and Devlin, N. (2010) Statistical analysis of EQ-5D profiles: Does the use of value sets bias inference? Medical Decision Making. 30(5), 556-565 doi: 10.1177/0272989X09357473 The Paretian classification is described and discussed in Devlin, N., Parkin, D. and Browne, J. (2010) Patient-reported outcomes in the NHS: New methods for analysing and reporting EQ-5D data. Health Economics. 19(8), 886-905.DOI: 10.1002/hec.1608
If using the score is OK, what really matters is the distribution of the regression residuals, not the score. If you are using the Paretian classification, you are correct that an ordered model can't be used.
'Tariff' is a slightly silly label, but for historical reasons has been used in this context. Just means a set of scores attached to categorical EQ-5D health states.
Comment: +1 This kind of well-researched, authoritative, and clear answer is what we aim for in all threads.
Comment: +1 for an interesteing, as whuber wrote, well-researched answer.
Answer: First, categorizing continuous variables is generally a bad idea; Royston, Altman and Saurbrei wrote a good article on why dichotomizing is bad, and the same arguments apply to more categories. Altman wrote an article on categorizing variables, but only the abstract is freely available, and I have not read the whole article.
Second, the assumptions of linear regression are not that the dependent variable is normally distributed, but that the residuals from the model are. So, before you can see if your model violates the assumptions, you need to run it and look at the results.
Third, if the residuals are not normally distributed, you have several choices:

Multinomial logistic regression with the four categories you list
Ordinal logistic regression with "mixed" excluded.
Looking at each category separately
Some sort of robust regression

Before doing any of these, my impulse would be to look at the variables graphically, with density plots and possibly quantile normal plots.
Comment: Thank you very much for your answer, I'll check how it behaves with a [qqplot](http://www.statmethods.net/stats/rdiagnostics.html) or is there a better method that you suggest? Part of my question is in regard to *very large* series, when looking at the central limit theorem almost the underlying distribution quickly disappears when n is large. In registry studies the n is > 30 000 and therefore even if the qqplot would suggest some non-normal distribution I wonder if this really matters?
Comment: Max, the CLT is not relevant.  As the amount of data go up, you collect more and more draws from the error distribution.  The residuals will closely reflect that error distribution.  Thus, their empirical density (think: histogram) should be converging towards their theoretical ("population") density, *whatever shape it may have.*  The CLT would apply to statistics like *averages* of the errors, but such statistics are just not germane to the question.
Comment: @whuber: Thank you for your input. So if I know that this population has a bimodal distribution, should I then expect the residual histogram to have a bimodal distribution?
Comment: The hope, Max, is that the independent variables give you so much information about the dependent variable--including which mode it is near--that the residuals wind up being centered at zero, unimodal, and symmetric (all approximately, of course).  (Bimodal residuals usually suggest some factor has not been accounted for in the regression.)
Comment: I'm not sure if I understand what you're referring to in your comment on categorical variables; if you're referring to the design of the survey itself, I would just add that the ease of answering a categorical question is typically much higher than a continuous question, and can make for higher-quality responses (lower respondent fatigue) and higher response rates, which can be beneficial for overall sample quality and also for operational purposes.
Answer: if you have some predictor variables (which I'm assuming you have as you mention regression in your question), I'm wondering if an ordinal logistic regression, using the Paretian measure as the dependent variable (which appears to be ordered categories of pre- versus post- differences), is the best way forward. I love the UCLA websites for the clarity of their explanations of various methods, here is their outline of ordinal logistic regression using SPSS and  here is their example for Stata. As you can see from these sites, you will need to verify that the proportional odds assumption is met with your data.
Ordinal logistic regression is an accepted statistical method, and Professor Agresti has written about it in his books on categorical data analysis. I recommend buying any of his books if your work is taking you down categorical data analysis paths.
Comment: My initial thought was an ordinal logistic regression but then I noticed the annoying "mixed" outcome that is hard to order in comparison to the "no change". I'm also very interested to know exactly why assumptions of linear regression are broken in this case as some say it is.
Comment: Can you do any investigations with the patients in the mixed category. Are there any clinical hallmarks of this group, e.g. on one particular measure of the test?
Comment: Thank you for your suggestions. What I'm mostly interested in is trying to figure out exactly when I need to fall back to a categorical methods.
Comment: The mixed category will present a challenge for any method where you're looking at ordered outcomes. So even in the case of using the score as a continuous measure, rather than a category, it sounds like the mixed scores will be an issue because they don't "fit" with an increasing score representing better functioning.


How to remove all re.findall matches from the inputed text, in Python?

Question: I think it should be like that, but it's not working.
import re

RNA = input("")
regex = r"gu(?:\w{0,}?)ag"
introns = re.findall(regex, RNA)
exons = re.sub(introns, '', RNA)
print(exons)

But it should delete all matches that were found by the re.findall, or replace it with an empty space or other texts.
Comment: Can you give an example of the input you have and the output you want?
Comment: input = aaatguttttttagtaaaaa
output = aaattaaaaa
Answer: You don't need the call to re.findall(), you can call re.sub with a regex and all occurrences will be replaced
import re

RNA = input("")
regex = r"gu(?:\w{0,}?)ag"
exons = re.sub(regex, '', RNA)
print(exons)

Comment: Exactly. `re.findall` returns a list with all occurrences of what you want to replace.
Comment: @Iain Shelvington, many thanks.
I'm just beginning to using a regular expression in python. If you know, can you please give links to some good guides about it?
https://docs.python.org/3.2/library/re.html - for me it`s a little bit kinky.
But the other documentations and guides seem incomplete or had not enough examples for understanding.
Comment: @OrkBiotechnologist The how-to guide in the python docs is okay... https://docs.python.org/3/howto/regex.html. Regular expressions and their use is a bit of a dark art in almost all languages, I don't know of another guide that I would recommend. Sorry!


SKLabelNode delays app start

Question: at the moment I'm coding a little app with SpriteKit, which works perfectly fine, but the only problem is an SKLabelNode, which I initialize with the following normal piece of code:
self.scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"Futura"];
self.scoreLabel.fontSize = 190.0f;
self.scoreLabel.color = [SKColor whiteColor];
self.scoreLabel.alpha = .2;
self.scoreLabel.text = @"00";
self.scoreLabel.position = CGPointMake(screenWidth/2,self.scoreLabel.frame.size.height/2);
[self addChild:self.scoreLabel];

There a many more things to initialize, but they doesn't affect anything. If I comment out the code above, the app loads in the usual time. With the SKLabelNode it delays the loading by few seconds...
Hope anyone can help me.
Comment: Does it lag on simulator, actual device, or both? In general with sprite kit I've found that using the simulator isn't reliable.
Comment: More precisely: In general Simulator isn't reliable as in "not an accurate representation of device behavior, performance and visuals". Where in doubt (that's basically every inexplicable issue) always verify on a device.
Comment: Does the behavior change if you use other fonts like Arial, Helvetica or Courier?
Comment: 1. It lags on the actual device. It's fluently in the simulator (or a bit more fast). 2. Other Fonts doesn't change the behavior...
Answer: Actually, you don't need to preload the font for an SKLabelNode.  The delay is caused by the fact that you're using the wrong font name.  There's no "Futura" font on iOS - what you probably mean is "Futura-Medium".  Replace "Futura" with "Futura-Medium", and you should see the load time drastically fall.
(You can still preload your fonts, but it's not necessary; lazy loading is pretty fast provided you use a correct font name.)
Comment: Amazing. You have no idea how much time I'd put into profiling and looking into possible resource-intensive culprits. And in the end it was one misplaced hyphen in the font name that was freezing my app for 2 seconds!
Comment: Yours is the correct answer - I've added another answer that distinguishes from loading the entire font family - which will appear to 'work' but be really really slow.
Comment: Glad to help.  I had spent a long time trying to figure it out, too.
Comment: I've got the same problem, and have used (supposedly) installed fonts http://support.apple.com/en-gb/HT202771  and I still get the delay. Preloading just moves the delay sooner.. Is there a way to preload in a thread?
Answer: Be careful you aren't loading the entire font family.
If I load "Chalkboard SE" it will take 4-6 seconds, and appear to work.
But if I load ChalkboardSE-Regular , it's virtually instantaneous ~100ms or less.
If you want to know more, I've got various links and timings on my humble blog. https://gilesey.wordpress.com/2015/01/14/ios-spritekit-font-loading-times-of-sklabelnodes/
Comment: This is the correct answer. Problem with delay happens only when loading entire family fonts. If a font name is properly set, loading times are instant.
Answer: You need to preload the font so that when you first call your SKScene sprite kit already has the font ready in memory. The best way to do this is to either use the app delegate or a singleton as soon as you can in your games life cycle.
self.scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"Futura"];
self.scoreLabel.text = @"preload";

You don't need to make the label global, just make sure you keep a strong reference to let the compiler know you want it to keep the font in memory. Also make sure you set the text property (the font is only loaded when you set this).
EDIT:
This is what I am using:
- (void)setupFonts {
    SKLabelNode *preloadFontLabel = [SKLabelNode labelNodeWithFontNamed:@"HelveticaNeue-UltraLight"];
    [preloadFontLabel setText:@"Preload"];
}

This is called from a game assets singleton right when the game starts, I also have a call-back that stops the "PLAY" button appearing before the assets have loaded so the user can't jump the gun until everything is up and loaded. My game assets only take 1.03secs to load so its not an issue, but you could also hide a longer load behind a splash/startup screen if needed.
If your still seeing a problem I would check you don't have any other fonts in your SKScene that your not preloading. Also it could be an issue with loading a custom font, try changing the font to "HelveticaNeue-UltraLight" and see if you get the same issue.
Comment: I actually put my code in the AppDelegate and it delays the start of the app as mentioned. First I had it in the SKScene, so it delayed the start of the game from the Menu.
Comment: Thank you so much !!! The problem was indeed the font... With AvenirNextCondensed e.g. there are no issues.
Comment: No problem at all, glad you got it sorted.
Comment: Note that preloading fonts is not typically necessary unless you're doing a lot of different fonts; this problem usually stems from using an incorrect font name.  When you use the correct font name ("Futura-Medium" instead of "Futura", for instance), the SKLabelNode loads almost instantaneously.

SKLabelNode delays app start


Big-O Notation and Algebra

Question: This is my first question here. Trying to simplify the following.
$$f = O\left(\frac{5}{x}\right) + O\left(\frac{\ln(x^2)}{4x}\right)$$
I give it a try as follows.
$$\begin{align}
f &= O\left(\frac{5}{x}\right) + O\left(\frac{2\ln(x)}{4x}\right), \\
f &= O\left(\frac{5}{x}\right) + O\left(\frac{\ln(x)}{2x}\right), \\
f &= O\left(\frac{10}{2x}\right) + O\left(\frac{\ln(x)}{2x}\right), \\
f &= O\left(\frac{10 + \ln(x)}{2x}\right), \\
f &= O\left(\frac{\ln(x)}{2x}\right).
\end{align}$$
Is this OK?
Comment: Short answer: Yes, that's ok. But note that $O(f) = O(cf)$ for constants $c \neq 0$, so you can omit the $2$ in the denominator in the last expression.
Comment: In not a single one of your expressions (apart from the original one), all open parentheses are closed.
Answer: Yes, that's ok.
Note that you can always omit non-zero multiplicative constants in $O(\cdot)$-terms. For instance, $O(4x) = O(x)$ and $O(2/x) = O(1/x)$. So you could get rid of those constants right away, and get a somewhat shorter version of the proof:
$$f = O\left(\frac{5}{x}\right) + O\left(\frac{\ln(x^2)}{4x}\right) = O\left(\frac{1}{x}\right) + O\left(\frac{\ln x}{x}\right) = O\left(\frac{\ln x}{x}\right).$$
But nothing is wrong with your derivation either.

Big-O Notation and Algebra


Cheap PSTN Card with caller Id for Asterisk Linux server

Question: For my house I just wanted to setup a caller Id system that would auto-reply on certain callers to avoid harements. Any sugestion for this?
I'm thinking on a Linux + Asterisk + PSTN Card with caller Id and configure asterisk to handle these calls, I need to be able to answer some of the calls on the normal phone so this would just be work a bit like an IDS.
http://en.wikipedia.org/wiki/Intrusion_detection_system
Answer: Not sure this belongs to SF but you could get most modems using Intel 537P (AKA Ambient MD3200 ) chipset to be recognized as Digium Wildcard X100P clone by Asterisk. Do not confuse it with Intel 537EP (newer but unsupported chip).

537P is rectangular chip

537EP is square 64-pin TQFP

Also pay attention to which version G(global) or U(USA) you get.
Comment: Cool, just found out that in Brasil the Caller Id is paid monthly to a operator...


Anaconda - Display table output from CSV

Question: I am trying to produce output from .csv file as a table with column headers. I am trying to display as table with frequencies calculated. so far i can calculate frequencies with this code:
import pandas
d = pandas.read_csv('gapminder.csv', low_memory=False)
d['urbanrate'] = d['urbanrate'].convert_objects(convert_numeric=True)

print ('Count Urban rate')
c = d.groupby('urbanrate').size()
print (c)

print ('Urban rate percentage')
f = d.groupby('urbanrate').size() * 100/len(d)
print (f)

and the output is like:
Count Urban rate
urban rate
10.40     1
12.54     1
12.98     1

But i would like to have have columns like:
 Rate   Count
 10.40      1
 ..         ..

Thanks
Answer: You can set the column names:
f.columns = ['Rate', 'Count']
print(f)

prints:
 Rate  Count
0  10.40      1
1  12.54      1
2  12.98      1

If you don't like to see the index:
print(f.to_string(index=False))

prints:
Rate  Count
 10.40      1
 12.54      1
 12.98      1

Comment: Thanks. This is what i wanted.


Can this be proved using Combinatorics or generating functions?

Question: What is the proof for this identity?
$\displaystyle\sum_{r=0}^{n}\binom{n}{r}\binom{m+r}{n}\ = \displaystyle\sum_{r=0}^{n}\binom{n}{r}\binom{m}{r}2^{r}$
I thought of changing $r$ to $n-r$ on left and right both. Then, I thought of building a set with atleast $n$ elements and atmost $2n$ elements with atmost $n$ elements from $m$ element set, and we can do this on LHS by choosing $n-r$ elements from n and out of remaining $r+m$ elements we can choose n more elements. On RHS, we can again choose $n-r$ elements from $n$ and $r$ elements from $m$, then remaining $r$ elements from n element set have 2 choices each. But I think it has a flaw. Can someone please help? If my proof is not correct, please suggest a combinatorial or a generating function proof.
Answer: The story would be like(any resemblance to reality is pure coincidence) :
Suppose you want to build a committee of $n$ mathematicians. You have a pool of $n$ graduate students and $m$ full professors. The rule is that you have to double vote the graduate students. That means, first you choose the graduate students(first filter) and then you choose from the pool of professors and selected graduate students(second filter).
The LHS is you choose $r$ graduate students and then you choose from $m+r$ candidates, the $n$ mathematicians.
The right hand side is you choose the amount of professors that are going to be in the final committee, say $r,$ in $\binom{m}{r}$ and so there should be $n-r$ graduate students. You choose them in $\binom{n}{n-r}$ but notice that the remaining $r$ graduate students, perhaps, pass the first filter so you are going to mark the ones that pass the first filter, you can do that in $2^r$ ways.
This should be reminescent of the proof of $\binom{a}{b}\binom{b}{c}=\binom{a}{c}\binom{a-c}{b-c}.$
Comment: Can u elaborate RHS please?@Phicar
Comment: Can u please explain how u used $2^{r}$ please??
Comment: There are $r$ students that failed to be in the committee. There are 2 ways to fail for students: did not get the vote at all, or only get 1 vote (recall that students need to be selected twice). Hence $2^{r}$
Comment: Thanks @RezhaAdrianTanuharja , that is precisely it. I see you prefer chess to graduate school.(+1)
Comment: @CombatMiners Check Rezha's comment. Let me know if you want me to elaborate further.
Comment: @nmnsharma_007 I see that you fully understand now. If not, which part do you think needs elaboration? Thanks for your feedback.
Answer: Using coefficient extractors we get for the LHS
$$\sum_{r=0}^n {n\choose r} {m+r\choose n}
= [z^n] (1+z)^m \sum_{r=0}^n {n\choose r} (1+z)^r
= [z^n] (1+z)^m (2+z)^n.$$
We get for the RHS
$$\sum_{r=0}^n {n\choose r} {m\choose r} 2^r
= \sum_{r=0}^n {n\choose r} {m\choose m-r} 2^r
\\ = [z^m] (1+z)^m \sum_{r=0}^n {n\choose r} 2^r z^r
= [z^m] (1+z)^m (1+2z)^n.$$
This last term is
$$\mathrm{Res}_{z=0} \frac{1}{z^{m+1}} (1+z)^m (1+2z)^n.$$
There is no pole other than the one at zero and residues sum to zero so
this is
$$-\mathrm{Res}_{z=\infty} \frac{1}{z^{m+1}} (1+z)^m (1+2z)^n
\\ = \mathrm{Res}_{z=0} \frac{1}{z^2}
z^{m+1} \frac{(1+z)^m}{z^m} \frac{(2+z)^n}{z^n}
\\ = \mathrm{Res}_{z=0} \frac{1}{z^{n+1}} (1+z)^m (2+z)^n
= [z^n] (1+z)^m (2+z)^n.$$
This is the claim.
Comment: Is this proof using generating functions or algebraic or both?
Comment: I would say both and formal power series as well.
Answer: This is another version of Phicar's solution.
There are $n$ students and $m$ professionals. All professionals are member of chess club while students can be in the club or not. Suppose that we want to choose $n$ people from the club's members to join a competition.
In the LHS, $r$ students are in chess club, $\binom{n}{r}$. Therefore, there are $m+r$ chess club members to choose from, $\binom{m+r}{n}$. Hence $\sum_{r=0}^{n}{\binom{n}{r}\binom{m+r}{n}}$
In the RHS, $r$ professionals join the competition, $\binom{m}{r}$. Therefore, $n-r$ students must be members of the club and join the competition, $\binom{n}{n-r}=\binom{n}{r}$. The remaining $r$ students can be in the club or not, $2^{r}$. Hence $\sum_{r=0}^{n}{\binom{n}{r}\binom{m}{r}2^{r}}$
Comment: Thank you. I couldn't completely understand Phicar's solution. Your solution made it clear:)
Answer: $$
\eqalign{
  & \sum\limits_{\left( {0\, \le } \right)\,r\,\left( { \le \,n} \right)} {\left( \matrix{
  n \cr
  r \cr}  \right)\left( \matrix{
  m + r \cr
  n \cr}  \right)}  = \sum\limits_{\left( {0\, \le } \right)\,r\,\left( { \le \,n} \right)} {\left( \matrix{
  n \cr
  r \cr}  \right)\sum\limits_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( \matrix{
  r \cr
  k \cr}  \right)\left( \matrix{
  m \cr
  n - k \cr}  \right)} }  =   \cr
  &  = \sum\limits_k {\sum\limits_r {\left( \matrix{
  m \cr
  n - k \cr}  \right)\left( \matrix{
  n \cr
  r \cr}  \right)\left( \matrix{
  r \cr
  k \cr}  \right)} }  = \sum\limits_k {\sum\limits_r {\left( \matrix{
  m \cr
  n - k \cr}  \right)\left( \matrix{
  n \cr
  k \cr}  \right)\left( \matrix{
  n - k \cr
  r - k \cr}  \right)} }  =   \cr
  &  = \sum\limits_k {\sum\limits_r {\left( \matrix{
  m \cr
  n - k \cr}  \right)\left( \matrix{
  n \cr
  k \cr}  \right)\left( \matrix{
  n - k \cr
  n - r \cr}  \right)} }  = \sum\limits_k {\left( \matrix{
  m \cr
  n - k \cr}  \right)\left( \matrix{
  n \cr
  k \cr}  \right)2^{n - k} }  =   \cr
  &  = \sum\limits_k {\left( \matrix{
  m \cr
  k \cr}  \right)\left( \matrix{
  n \cr
  k \cr}  \right)2^k }  \cr}
$$
Note that the sum bounds put in parenthesis is to indicate that they can be omitted since they are implicit in the binomial(s), i.e. the binomials are null outside of the bounds.
Then the steps are:

expand 2nd b. as Vandermonde's Convolution;
group and invert the summation indices;
apply the "trinomial revision" identity on last two b.
$$
\eqalign{
  & \left( \matrix{
  n \cr
  r \cr}  \right)\left( \matrix{
  r \cr
  k \cr}  \right) = {{n!} \over {r!\left( {n - r} \right)!}}{{r!} \over {k!\left( {r - k} \right)!}} = {{n!} \over {\left( {n - r} \right)!k!\left( {r - k} \right)!}} =   \cr
  & {{n!} \over {\left( {n - k} \right)!k!}}{{\left( {n - k} \right)!} \over {\left( {n - r} \right)!\left( {r - k} \right)!}} = \left( \matrix{
  n \cr
  k \cr}  \right)\left( \matrix{
  n - k \cr
  r - k \cr}  \right) \cr}
$$
sum on r, and change $n-k$ with $k$
Comment: what identities are u using in between? I want to know ;_;
Comment: @nmnsharma_007: I have explained the steps involved
Comment: Thanks a lot!!!!. I really love this platform. U learn a lot of things other than getting your doubt clarified ^_^
Comment: Can u explain the identities used here? I mean just write them please:)
Comment: @CombatMiners: I have explained the steps involved


The difference between desktop-series HDD drives and server-series

Question: What are the main differences between desktop-series hard disks and server-series?
The obvious things I can see are: durability (server hardware mostly more qualitative and have more warranty) and power consumption (server hardware more focused on performance, than on power economy). Also server disks are usually a little faster, but it seems, that it is not always the case.
May be there are some other reasons, that make you choose server-oriented series (Seagate ES drives, for example) over desktop-oriented ones (Seagate Barracuda series)? What are they?
Answer: One very important difference is the Time-Limited Error Recovery (aka Command Completion Time Limit)

Time-Limited Error Recovery (TLER) is a name used by Western Digital for a hard drive feature that allows improved error handling in a RAID environment. In some cases, there is a conflict as to whether error handling should be undertaken by the hard drive or by the RAID controller, which leads to drives being marked as unusable and significant performance degradation, when this could otherwise have been avoided. Similar technologies are called Error Recovery Control (ERC), used by competitor Seagate, and Command Completion Time Limit (CCTL), used by Samsung and Hitachi.

This is very important in RAID arrays where one drive can lock up or degrade the array.
Comment: it is a good idea to look for "RAID-compatible" drives, since most consumer drives will never be used this way.
Comment: A late response, but I have to reply. I had three `WDC WD2002FYPS-02W3` disks (with TLER) fail on me in a couple of weeks and they didn't limit their error recovery time at all. The Linux MD driver never knew the drives were broken. **I** knew because the server's load was getting high and dmesg was full of errors.
Answer: According to Intel's Enterprise-class versus Desktop-class Hard Drives, enterprise-class drives are often faster and more reliable due to better hardware and different firmware.
Better hardware specs:

better mechanics for faster and more reliable data access (stronger actuator magnets, more servos)
more cache memory
more components for error detection and correction
vibration compensation or reduction to reduce likelihood of data corruption induced by moving parts in the server, e.g. rotating fans and spinning disks

Behavior:

Time-limited error recovery (TLER) for more reliable and lower-latency error recovery and fail-over
End-to-end error detection
Usually fixed rotation speed
Energy-saving mechanisms that shorten overall life of consumer-grade disks, such as Western Digital's WD Green series' IntelliPark which parks the hard disk after 8 seconds (!) idle time (however, there are tools from the manufacturers and third parties that modify the default settings so that you could use such disks in server or NAS/SAN systems, e.g. idle3-tools).

Testing:

It's just a guess, but it may be that manufacturers test their enterprise-class disks more thoroughly than their desktop disks, however, independent testing by external parties is not entirely conclusive and might even show that desktop drives may be as reliable as server-grade drives, at least in the initial years of operation (Backblaze study).
The point here is though that there are more and older desktop drives out in the wild and in active use than enterprise disks, so one could say that we have more and better data about desktop drive reliability than we have for server disks (Google).

Warranty:

Enterprise-class disks often come with longer warranty than desktop disks. However, this will probably not matter very much to you if you have sensitive data stored unencrypted on your failing disk and do not want to send in your disk to claim the warranty.

Nonetheless, the issue about TLER might be the main reason for choosing server-grade storage solutions over consumer products, especially when operating RAID systems and servers with time-critical workloads like web or database servers.
Other than that, yes, there is probably some FUD by the manufacturers to make you feel uneasy about using desktop products for a server, so using enterprise products will also give you some peace of mind.
Comment: Wondering what the manufacturers' policies about planned obsolescence are regarding their enterprise and consumer products. Might go either way - businesses are more willing to replace hardware and tend to design for redundancy anyways, so why not have enterprise hardware fail more often ?
Answer: THE most important difference is the level of Vendor Support.
If you don't use "hardware compatible" equipment (i.e. OEM) then you may find yourself SOL when the kit dies and you need to get it fixed quick.
Comment: @fractal not really, but the vendors tend to be jerks about this if they can.. if you put in a "non-authorized" drive they'll refuse to service the machine.
Comment: How vendor can support hard drive other than exchange it on warranty? Do HDDs require any support from vendor after they are purchased?
Answer: Enterprise hard disks also tend to have a longer MTBF (Mean Time Between Failures), i.e. longer life span, than consumer grade ones.
Answer: The heat-pad under a smooth chip (motor controller) is missing in the most of the consumer drives (seagate, WD), but is usually present in the most of the enterprise class disks. (so the tiny smooth chip is much more likely to die under the load from overheat in the desktop model).
Also enterprise drives usually have a couple of the vibration sensors.
Rubber anti vibration dumpers and rigid cases are strongly recommended for all modern high density disks/fan mounts. (Esp ones over with density 500GB+ per platter, since their heads are really fragile from my experience).
Answer: Two things:

Cache size
Marketing

Reliability is not a distinguishing factor.
Comment: agree, it's 95% marketing. There might be longer warranties if you pay more for the "enterprise" stuff, but economies of scale dictate that the drives will be basically identical.
Comment: Some desktop models also have 32-64Mb cache size: http://www.seagate.com/www/en-us/products/internal-storage/


Construct a blocking set in a chessboard barring rectangles from it

Question: Suppose we have a chessboard with m*n unit squares. Consider the rectangular polyominoes of the shape a*b within it, where a is less than or equals to m and b is less than or equals to n. A subset of unit squares S of the board is called a blocking set of type (a,b) if any such polyomino(and its rotation) intersects with at least one unit square in S. Now I want to find an algorithm to construct a blocking set that has the least number of unit squares.
I've asked the same problem for a closed formula of the size of the smallest blocking set in MSE and hopefully this time the solution would be easier.

Although there have been some answers now, I think I have the obiligation to make the question more clear. Let me give a concrete example. Suppose our chessboard is of size 6*6. At this momemt let's consider the case a=2,b=3. For example, the yellow blocks in the following picture are two 2*3 rectanglular polyonimoes on it.

Now think about the set S of red unit squares below

It is easy to check that any 2*3 rectangular polyomino on the board must intersect with the S, and by the pigeonhole principle any blocking set must include at least 6 unit squares, so S is also a smallest one. Of course S is not unique in the sense that one can find another smallest blocking set that is not identical to it. To be precise, what I am looking for is an algorithm to construct one smallest blocking set on the board just like the red set S above, but to a general quadruple (m,n,a,b). I hope this explanation works.
Comment: I just dont fully understand the question. Can you be more descriptive? Can you give an example of input/output?
Comment: PS: I do however fully understand the question in MSE, is it exactly same one but with polyomino?
Comment: @libik Sorry about that. I've added an example now.
Answer: A standard dynamic programming solution is to keep a set of "minimum cost by profile sticking up past this row."  Unfortunately there are max(a, b)^m such profiles possible so it won't scale well to large rectangles.
However as one simplification, we can slide each rectangle as far over and down as possible.  This does reduce the number of profiles some.
With that said, here is running Python code for this problem.  Note, though, that even something as simple as finding out that blocking(11,10, 4,3) is 120 will take some time to run.  That's both because of how much data it has to track, and how much temporary garbage it creates.
def blocking (m, n, a, b):
    # Small optimization.
    if (m < n):
        (m, n) = (n, m)
    # We start before with a row with nothing sticking up, of cost 0 to get here.
    last_solutions = {
        tuple([0 for i in range(m)]): 0
        }
    # Now advance one row, n times.
    for i in range(n):
        next_solutions = {}
        for (profile, cost) in last_solutions.items():
            carried_profile = tuple([i-1 for i in profile])
            for (new_profile, incremental_cost) in advance_row(carried_profile, a, b):
                if tuple(reversed(new_profile)) < new_profile:
                    # By symmetry we only need to look at one of these.  Look at the other!
                    pass
                elif new_profile in next_solutions:
                    next_solutions[new_profile] = min(next_solutions[new_profile], cost + incremental_cost)
                else:
                    next_solutions[new_profile] = cost + incremental_cost
        last_solutions = next_solutions
    return min(last_solutions.values())

def advance_row(profile, a, b, p=0):
    if len(profile) <= p:
        # We reached the end.  Yield it.
        yield (profile, 0)
    else:
        if 0 < profile[p]:
            # It is OK to put no block here.
            for (next_profile, cost) in advance_row(profile, a, b, p+1):
                yield (next_profile, cost)
        area = a * b
        if profile[p] < b:
            # We might place a block a x b here
            new_profile = add_in_rectangle(profile, a, b, p)
            for (next_profile, cost) in advance_row(new_profile, a, b, p+1):
                yield (next_profile, cost+area)
        if profile[b] < b:
            # We might place a block b x a here
            new_profile = add_in_rectangle(profile, b, a, p)
            for (next_profile, cost) in advance_row(new_profile, a, b, p+1):
                yield (next_profile, cost+area)

# Creates a copy of the profile with a block of length a, height b
# filled in starting at position p
def add_in_rectangle(profile, a, b, p):
    # Make a copy
    new_profile = [x for x in profile]
    for i in range(p, min(p + b, len(profile))):
        new_profile[i] = max(profile[i], a)
    return tuple(new_profile)

Comment: What is blocking(m,n,a,b) stand for? I am afraid either I totally missed your point in the answer, or you may have some misunderstandings about the question. Since someone told me that the problem description was not quite clear in the first edition, I'll apology for that if that did mislead you.
Comment: @Phil.Z I was thinking blocking off and covering everything.  So I did misunderstand what you wanted.  The math version of your question talking about tilings helped send me on that course.
Answer: Here is a second approach that is likely a lot faster, but I won't take the time to code it.  However because it is unrelated to my other solution, I'll make it a separate answer.
Consider the set of outlines of partial tilings as the nodes of a graph.  From each one you can construct a set of edges which is the result of adding a rectangle whose bottom edge covers the left-most empty square on the bottom row that is not completely filled in.  (This will give a + b edges to each node.)
Now construct an A* search from the node which is nothing there to the node that is completely filled.  From any node the estimated cost is the smallest multiple of a*b that is greater than the number of empty squares.
If, as seems to be often the case, an optimal tiling can be produced by a greedy search, this search will quickly discover that and give you an answer.  It only needs to backtrack if this is not true.
Even if it does backtrack, the fact that you keep track of which nodes you've been to will give you the benefits of a DP solution, likely with better pruning of the possibilities that you have to analyze.


How to submit a user profile form through ajax?

Question: I want to submit the user profile form through ajax.
I see the ajax_register module but it does not support the user profile form. Is there any contrib module which I can use?
Or this can done custom. But with custom approach I have to look for the form validation also?
Answer: Below module will help you
Modal forms (with ctools)

Modal forms make use of the modal feature in the ctools module to open
  some common forms in a modal window.
<code>Log in (modal_forms/nojs/login)
Request new password (modal_forms/nojs/password)
Create new account (modal_forms/nojs/register)
Contact (modal_forms/nojs/contact)
Comment (modal_forms/nojs/comment/reply/%node)
Webform (modal_forms/nojs/webform/%node)
</code>
Function that rewrite normal links to modal forms links (except for
  webforms) can be activated on the modules configuration page
Comment: I think it does not support the user profile form.