If $d|n$, then $\phi(d)|\phi(n)$

Question: Where $\phi(n)$ denotes Euler's Totient Function. My proof follows, I was hoping someone could verify it, and give critique.
Let $d,n\in\mathbb{Z}^+$ so that $d|n$. By the Fundamental Theorem of Arithmetic, $n$ can be written in the following way:
$$n = p_1^{\beta_1}\cdots p_n^{\beta_n}$$
where $p_j,\ j=1,...,n$ are all distinct primes. As $d$ divides $n$, $d$ can be written as:
$$d=p_1^{\alpha_1}\cdots p_n^{\alpha_n}$$
where $0\leq\alpha_j\leq\beta_j$, and $\ j=1,...,n$.
Then, using the multiplicative property of $\phi(n)$ and the fact that $\phi(p^k)=p^{k-1}(p-1)$ for some $k\in\mathbb{Z}^+$:
\begin{align}
\notag \phi(n) &= \phi(p_1^{\beta_1}\cdots p_n^{\beta_n})\\
\notag &= \phi(p_1^{\beta_1})\cdots\phi(p_n^{\beta_n})\\
\notag &= p_1^{\beta_1-1}(p_1-1)\cdots p_n^{\beta_n-1}(p_n-1)
\end{align}
\begin{align}
\notag \phi(d) &= \phi(p_1^{\alpha_1}\cdots p_n^{\alpha_n})\\
\notag &= \phi(p_1^{\alpha_1})\cdots\phi(p_n^{\alpha_n})\\
\notag &= p_1^{\alpha_1-1}(p_1-1)\cdots p_n^{\alpha_n-1}(p_n-1)
\end{align}
As $\alpha_j\leq\beta_j$ for all $j$, we must also have $\alpha_j-1\leq\beta_j-1$ for all $j$, and:
$$p_j^{\beta_j-1}(p_j-1) = p_j^{\beta_j-\alpha_j}p^{\alpha_j-1}(p_j-1),\ \forall j\in\{1,...,n\}$$
So $\phi(n)$ can be written as:
\begin{align}
\notag \phi(n) &= p_1^{\beta_1-1}(p_1-1)\cdots p_n^{\beta_n-1}(p_n-1)\\
\notag &= p_1^{\beta_1-\alpha_1}p_1^{\alpha_1-1}(p_1-1)\cdots p_n^{\beta_n-\alpha_n}p_n^{\alpha_n-1}(p_n-1)\\
\notag &= (p_1^{\beta_1-\alpha_1}\cdots p_n^{\beta_n-\alpha_n})p_1^{\alpha_1-1}(p_1-1)\cdots p_n^{\alpha_n-1}(p_n-1)\\
\notag &= (p_1^{\beta_1-\alpha_1}\cdots p_n^{\beta_n-\alpha_n})\phi(d).
\end{align}
and $\phi(d)|\phi(n)$.
Comment: A simple argument: the onto ring map $\Bbb Z/n\Bbb Z\to\Bbb Z/d\Bbb Z$ induces an onto homomorphism of unit groups. (This requires basics of abstract algebra.)
Comment: Ha, I agree, I'll review your approach. Thanks!
Comment: It looks fine...a little long, perhaps.
Comment: @seaturtles I'm not that familiar with rings yet, but I will definitely keep that in mind when I get there. Thanks!
Comment: It looks correct!! I think everything is right!!
Comment: @chs21259: When you have deduced the expressions for $\phi(d)$ and $\phi(n)$ you could easily claim that $\phi(d)$ $|$ $\phi(n)$ because $\beta_i \geq \alpha_i$ for all $i \in \mathbb N$.
Comment: @WilliamHilbert That shortens it up quite a bit, I didn't want to jump too many steps ahead, but I guess it is pretty obvious. Thanks for the comment!
Comment: First, you say $n = p_1^{\alpha_1}\dots p_n^{\alpha_n}$. This should rather be

$$n = p_1^{\alpha_1}\dots p_m^{\alpha_m}$$

as there is no reason to believe that the prime decomposition contains precisely $n$ primes.
Comment: Not that you care anymore after 5 years, but just posting this comment for future readers...
Answer: Hints for a shorter and simpler, imo, approach:
Use that
$$n=\prod_{i=1}^k p_i^{a_i}\;,\;\;p_i\;\;\text{primes}\;\;,\;\;a_i\in\Bbb N\implies \phi(n)=n\prod_{i=1}^k\left(1-\frac1{p_i}\right)$$
so now
$$d\mid n\implies n= xd\;,\;\;x\in\Bbb N\implies\;\ldots$$

If $d|n$, then $\phi(d)|\phi(n)$


Trying to organize toJson data in Laravel

Question: I'm trying to create a website using Laravel. I have a 'annonces' table in my database and I want to show all of it's content into my website.
Here is my Controller function
public function annonceAffiche() {
    $data = Annonce::all()->toJson();
    return $data;
}

And my Annonce class
    class Annonce extends Model
{
    public function user() {
        return $this->belongsTo('App\User');
    }
}

However, it only shows a string of all the data, I can't organize it. Something like that :
[{"user_id":32,"created_at":"2020-04-16T18:13:13.000000Z","updated_at":"2020-04-16T18:13:13.000000Z","description":"A description","titre":"A title","prix":1}]

What can I do ?
Comment: You can add a `select()` statement, and change `all()` to `get()`. You can see all of the functions you can use at https://laravel.com/docs/master/queries
Comment: What do you mean, organize it? If you want your results in a certain order, you can add `orderBy` to your `Annonce::all()` call
Comment: @aynber I mean that I only want to show 'title', 'description' and 'price' into my website
Comment: @aynber This works perfectly, thanks ! One last thing, how can I delete the [{...}] surrounding my data ?
Comment: If you're getting all the results, you can't, as that denotes an array of items. Removing it will invalidate your json. If you want just 1 result and remove the brackets, then you can use `first()` to get the very first result.
Comment: @aynber Okay, thank you !
Answer: From the docs here:
Set the $appends and add a getter for the attribute:
class Annonce extends Model {
    protected $appends = ['user'];

    public function getUser() {
         return $this->belongsTo('App\User');
    }
}


Do I need to run yum update in fresh centos 7

Question: Him guys.
Im used to run yum update when begin working on fresh centos servers.
Im working on a dedicated machine for cacti.
Should I install cacti and then run yum update ? or before install cacti or anything ?
Regards.
Leandro.
Answer: Yum package managers pulls latest packages during installs. So, no just start installation of Cacti. Unlike apt package manager that recommended running updates before installation.


How to match alphabetical chars without numeric chars with Python regexp?

Question: Using Python module re, how to get the equivalent of the "\w" (which matches alphanumeric chars) WITHOUT matching the numeric characters (those which can be matched by "[0-9]")?
Notice that the basic need is to match any character (including all unicode variation) without numerical chars (which are matched by "[0-9]").
As a final note, I really need a regexp as it is part of a greater regexp.
Underscores should not be matched.
EDIT:

I hadn't thought about underscores state, so thanks for warnings about this being matched by "\w" and for the elected solution that addresses this issue.
Answer: You want [^\W\d]: the group of characters that is not (either a digit or not an alphanumeric). Add an underscore in that negated set if you don't want them either.
A bit twisted, if you ask me, but it works. Should be faster than the lookahead alternative.
Comment: Nice, +1 from me. Didn't think of that one.
Comment: great idea, that can be re-used with other patterns and other regex implementation.
Answer: (?!\d)\w

A position that is not followed by a digit, and then \w. Effectively cancels out digits but allows the \w range by using a negative look-ahead.
The same could be expressed as a positive look-ahead and \D:
(?=\D)\w

To match multiple of these, enclose in parens:
(?:(?!\d)\w)+

Comment: Don't forget that \w also contains the underscore.
Comment: Just in case the OP doesn't expect it. I like your solution.
Comment: The OP did say nothing about the underscore. How is that relevant?


Learn to play to piano notes

Question: I am playing piano for almost 4 years. But I never played with notes. Now I want to play to notes. I can read them, but I have no idea how I can learn to play to them so fast, that I don't need to look at the sheet so long. What's the best way to learn it?
Answer: Try to get hold of some easy piano tutors, even very simple ones for children, perhaps. There are also some very easy pieces by serious composers you might look at. When I started, as a mature learner, one of the things I used at the start was book 1 of Bartok's Mikrokosmos. The first pieces are very simple with both hands playing in parallel one or two octaves apart, and gradually move on to more difficult pieces - and more musically interesting pieces.
You might also do a search for some old piano methods which can be freely downloaded from IMSLP.
Some examples:

Czerny Method for beginners
Bartok: First Term at the Piano
Kohler's piano method

Speed, and being able to find the notes without looking at your hands will come with (lots!) of practice. Be patient!
I would also recommend practicing scales and arpeggios as well as learning some theory, as it really helps with the skill of being able to recognize chord shapes quickly, so that you can more quickly take in whole chords and musical phrases with a very quick glance at the sheet music.

Learn to play to piano notes


Expectations operator doubt

Question: The question is mathematical with underpinnings of economics so I will try to explain so that the question can be understood without any knowledge of economics.
I need to maximize dividends in two periods with respect to investment (I):
max D2
D2 = f(I) + (1-a)I
The caveat is that "a" is a random variable which takes on values 1 with probability p and 0 with probability (1-p)
I substitute in the value of D2 and differentiate with respect to Investment.
I wrote D2 = p*(f(I))* + (1-p){f(I)) + (1-a)I}
as a is 1 if probability is p so it drops out in the first part
When I differentiate with respect to I, I get the answer as: (f'(I)) + 1 - p
Is this correct? The reason I ask is economically it doesn't make much sense.
Answer: When you set the derivative to zero, you are finding a stationary point, not necessarily a maximum. Is $f(I)$ a concave function? If not you might be hitting a saddle point or a minimum
Also, when you plug-in the outcomes of the random variable, it shouldn't appear in the expectation expression. You should have $\mathbb{E}[D_2] = pf(I) + (1-p)(f(I) + I)$

Expectations operator doubt


What properties can be derived for these recursively defined Nimbers (or Grundy numbers)?

Question: We let $a_0 = 0, a_1 = 0, a_n=\text{mex}(\{a_i+a_{n-i-2},i=0\ldots n-2\}),n\geq2$. Now suppose we need to calculate $a_n$ for large $n$ and fast. There have got to be certain shortcuts for that - like being able to move from $a_n$ to $a_{2n}$ in one step or having a closed form for some of these numbers for some $n$s. That's what I'm interested in. Thanks.
EDIT: For those who are new to this whole Nimber thing, as I am, $\text{mex}$ stands for "minimally excluded" and returns minimal non-negative number that is not in the given set. For example, $\text{mex}(\{1,2,4\})=0$ and $\text{mex}(\{0,2,5\})=1$. Also, nimber-addition is just bitwise-xor, so plus-sign in the formula can be changed for $\oplus$. Now if we go back to my sequence, we would have
$$
a_2=\text{mex}(\{0\oplus0\})=1,
$$
$$
a_3=\text{mex}(\{0\oplus0,0\oplus0\})=1,
$$
$$
a_4=\text{mex}(\{0\oplus1,0\oplus0,1\oplus0\})=2.
$$
Similarly, $a_5=0,a_6=3,a_7=1$, and so on.
Comment: No, it's $\text{mex}$. Short for "minimum excluded". These are not ordinary numbers, but Nimbers. See wiki for that.
Comment: in this case all your values will just be $0$, as the two start conditions are $0$
Comment: I assume you mean max? There might be a typo in your formula.
Comment: Interesting. May be good to note that in the question. Most people in my area would probably just assume it was a type because that also parses.
Comment: MJD, $i$ varies from 0 to $n-2$, so you can't have $i=1$ when $n=2$.
Answer: This sequence is naturally identical to the sequence of nimbers for a heap game in which, on your turn, you can remove $2$ items from a heap and then optionally split the remainder into two separate heaps of arbitrary sizes. That heap game is extremely famous, and is known as Dawson's Kayles, or "the heap game with Octal code 0.07". Equivalently, you can imagine this game as placing dominoes on a line of boxes, as in this other MSE question.
Very briefly, nimber sequences like this often become periodic after a while, and there is a theorem that says they definitely become periodic if they look like they do. This makes it very easy to calculate your sequence for large $n$ quickly. For some more information, see this community wiki collection of tutorials about nimbers and octal games.
As mentioned in my answer to that other question, a nearly identical sequence is at OEIS entry A002187, except the sequence there is missing the $a_0=0$ term. For completeness, here is the beginning of your sequence, with $8$ exceptional terms underlined. There are no more exceptions; it continues on with period $34$:
\begin{array}{r|cccc}
 n & \text{0+} & \text{34+} & \text{68+} & \text{102+} \\
\hline
 0 & \underline{0} & 4 & 4 & 4 \\
 1 & \underline{0} & \underline{0} & 8 & 8 \\
 2 & 1 & 1 & 1 & 1 \\
 3 & 1 & 1 & 1 & 1 \\
 4 & 2 & 2 & 2 & 2 \\
 5 & 0 & 0 & 0 & 0 \\
 6 & 3 & 3 & 3 & 3 \\
 7 & 1 & 1 & 1 & 1 \\
 8 & 1 & 1 & 1 & 1 \\
 9 & 0 & 0 & 0 & 0 \\
 10 & 3 & 3 & 3 & 3 \\
 11 & 3 & 3 & 3 & 3 \\
 12 & 2 & 2 & 2 & 2 \\
 13 & 2 & 2 & 2 & 2 \\
 14 & 4 & 4 & 4 & 4 \\
 15 & \underline{0} & 4 & 4 & 4 \\
 16 & 5 & 5 & 5 & 5 \\
 17 & \underline{2} & 5 & 5 & 5 \\
 18 & \underline{2} & \underline{2} & 9 & 9 \\
 19 & 3 & 3 & 3 & 3 \\
 20 & 3 & 3 & 3 & 3 \\
 21 & 0 & 0 & 0 & 0 \\
 22 & 1 & 1 & 1 & 1 \\
 23 & 1 & 1 & 1 & 1 \\
 24 & 3 & 3 & 3 & 3 \\
 25 & 0 & 0 & 0 & 0 \\
 26 & 2 & 2 & 2 & 2 \\
 27 & 1 & 1 & 1 & 1 \\
 28 & 1 & 1 & 1 & 1 \\
 29 & 0 & 0 & 0 & 0 \\
 30 & 4 & 4 & 4 & 4 \\
 31 & 5 & 5 & 5 & 5 \\
 32 & \underline{2} & 3 & 3 & 3 \\
 33 & 7 & 7 & 7 & 7  \end{array}


Hangman GUI receiving a null pointer exception and cannot find where

Question: I am currently working on a Hangman GUI as a HW assignment and I have all the code done (I think) but, I am getting a nullpointerexception and cannot figure out for the life of me where it is originating and it's making me rather furious. I need a second set of eyes to help me figure out where I made a mistake and what I need to do to correct it. Thanks in advance!
The NPE is occuring at:
alphabet = "abcdefghijklmnopqrxtuvwxyz";
            numLetters = 26;
            for (int count = 0; count < numLetters; count++) {
                letterChoice[count] = new JButton(Character.toString(alphabet
                        .charAt(count)));
                letterChoice[count].addActionListener(new CharacterListener(
                        alphabet.charAt(count)));
                letterChoice[count].setMnemonic(65 + count);
                add(letterChoice[count]);
            }

And here is all my code.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;

public class HangmanPanel extends JPanel {
    private JLabel imageLabel, numberLetters, gameOver, youWin;
    private JLabel[] spaces;
    private ImageIcon[] images;
    private JButton exitProgram, newGame, nextImage;
    private JButton[] letterChoice;
    private int imageNumber, letterNumber, numLetters, guesses;
    private WordList wordRand;
    private String word, alphabet;

    public HangmanPanel() {

        newGame = new JButton("New Game");
        newGame.setEnabled(true);
        newGame.setToolTipText("Press to restart game.");
        newGame.addActionListener(new NewGame());

        exitProgram = new JButton("Exit");
        exitProgram.setEnabled(true);
        exitProgram.setToolTipText("Press to close the program.");
        exitProgram.addActionListener(new ExitGame());

        wordRand = new WordList();
        word = wordRand.getWord();

        images = new ImageIcon[8];
        // Populating the array
        {
            images[0] = new ImageIcon("hangman0.png");
            images[1] = new ImageIcon("hangman1.png");
            images[2] = new ImageIcon("hangman2.png");
            images[3] = new ImageIcon("hangman3.png");
            images[4] = new ImageIcon("hangman4.png");
            images[5] = new ImageIcon("hangman5.png");
            images[6] = new ImageIcon("hangman6.png");
            images[7] = new ImageIcon("hangman7.png");
        }

        setBackground(Color.white);
        imageLabel = new JLabel(images[imageNumber]);
        imageNumber++;
        add(imageLabel);

        alphabet = "abcdefghijklmnopqrxtuvwxyz";
        numLetters = 26;
        for (int count = 0; count < numLetters; count++) {
            letterChoice[count] = new JButton(Character.toString(alphabet
                    .charAt(count)));
            letterChoice[count].addActionListener(new CharacterListener(
                    alphabet.charAt(count)));
            letterChoice[count].setMnemonic(65 + count);
            add(letterChoice[count]);
        }

        spaces = new JLabel[word.length()];
        while (letterNumber < spaces.length) {
            numberLetters = new JLabel("___");
            add(numberLetters);
            letterNumber++;
        }

        add(nextImage);
        add(newGame);
        add(exitProgram);

    }

    private class NewGame implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            imageLabel.setIcon(images[0]);
            imageNumber = 0;
            imageNumber++;
            imageLabel.repaint();
        }
    }

    private class ExitGame implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }

    private class CharacterListener implements ActionListener {
        public CharacterListener(char charAt) {

        }

        public void actionPerformed(ActionEvent e) {
            while (guesses < images.length) {
                int count = 0;
                while (count < word.charAt(count)) {
                    if (letterChoice[count].equals(word.charAt(count))) {
                        spaces[count] = new JLabel("" + letterChoice[count]
                                + "");
                        count++;
                    } else
                        imageLabel.setIcon(images[imageNumber]);
                    imageNumber++;
                    imageLabel.repaint();
                    guesses++;

                }

                if (guesses == 7) {
                    gameOver = new JLabel(
                            "You lose! Press New Game to try again!");
                    add(gameOver);
                } else
                    youWin = new JLabel(
                            "You win! Press New Game to play again or press Exit to remain Victorious!");
                add(youWin);
            }

        }

    }

}

Comment: Please do some legwork on your own. Where is the NPE originating? What did you learn while debugging?
Comment: I believe it is originating here

alphabet = "abcdefghijklmnopqrxtuvwxyz";
        numLetters = 26;
        for (int count = 0; count < numLetters; count++) {
            letterChoice[count] = new JButton(Character.toString(alphabet
                    .charAt(count)));
            letterChoice[count].addActionListener(new CharacterListener(
                    alphabet.charAt(count)));
            letterChoice[count].setMnemonic(65 + count);
            add(letterChoice[count]);
        }
Comment: Add that to your question, please.
Comment: letterChoice[count] = new JButton(Character.toString(alphabet
                    .charAt(count)));
Answer: The NullPointerException should tell you which line is causing the problem. Could you please post the exception and we'll try to help you figure out why its occurring at the particular line.
Without this information, there are a few possible errors..
1st possible error...
You're not creating the letterChoice array - ie you're missing the following somewhere before the alphabet...
letterChoice = new JButton[26];

2nd possible error...
You're not creating the nextImage - ie you're missing the following...
newImage = new JButton("Blah");

3rd possible error...
    public void actionPerformed(ActionEvent e) {
        while (guesses < images.length) {
            int count = 0;
            while (count < word.charAt(count)) { // probably here
                if (letterChoice[count].equals(word.charAt(count))) { // maybe here too
                    spaces[count] = new JLabel("" + letterChoice[count]
                            + "");
                    count++;
                } else
                    imageLabel.setIcon(images[imageNumber]);
                imageNumber++;
                imageLabel.repaint();
                guesses++;

            }

The reason: if you're doing a command like word.charAt(count), you should make sure that count is less than the length of the word first. Change the line to...
while (count < word.length && count < word.charAt(count)) {

4th possible error...
Your list of letters doesn't have an 's' in it, but rather it has 2 's' characters.
Comment: Exception in thread "main" java.lang.NullPointerException
 at HangmanPanel.(HangmanPanel.java:59)
 at Hangman.main(Hangman.java:16)

Is the NPE I have been getting
Comment: Is

letterChoice[count] = new JButton(Character.toString(alphabet
                    .charAt(count)));

Not creating anything?
Comment: Before the alphabet, you need `letterChoice = new JButton[26];` - you need to say that there's 26 buttons in the array before you can create them.
Comment: Awesome that worked =D! But, now I have an endless loop somewhere X( haha at least no more NPE.
Comment: The endless loop is probably in the 3rd error I listed above. Also, if the answer is correct, could you please tick it so that people know you've chosen a correct answer for your question. Thanks.
Comment: And I added the

while (count < word.length && count < word.charAt(count)) {

and it didn't fix the endless loop... Do I have to do something similar to that below in the if statement?
Comment: I think there is something not quite right in your logic of the `while (guesses < images.length) {` loop - maybe guesses is never getting to be large enough?


What is the 'Drupal way' to create a menu callback and display a rendered page of JSON?

Question: I have created a new menu item and a callback function.
<code>  ...
  $items['user/%user/enquiries'] = array(
    'title' => t('Enquiries'),
    'page callback' => '_client_enquiries',
    'access callback' => 'user_access',
    'access arguments' => array('view enquiries'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1
  );
 ...
 function _client_enquiries() {
   return t('Enquiries');
 }
</code>
I am now going to CURL some json from a published google spreadsheet, and cherrypick, and then print some of it out in a table. My question.. what is the drupal way to do this? I think it would be to create a custom theme function which makes my processed json data available to a template, which I can somehow load onto my menu callback and output. If that is the case, could anyone give me some pointers/examples or a point in the right direction.
Answer: Much simpler:
<code>function _client_enquiries() {

  $var_to_output = caculate_value_to_return();

  drupal_json_output($var_to_output);
  drupal_exit();
}
</code>
Comment: Ops, so I totally misunderstood your question. Then your aproach is right: use a custom theme function and call it in your hook menu callback. You don't have to load anything, it must be available. You can return the rendered HTML or a renderable array.
Comment: Answered for simplicity, for more info see the above answer that may be a duplicate of this one.
Comment: I'm not actually outputting any json. I will take some json from a feed, convert it with drupal_json_decode, extract the data I require and then theme that data into a table. I like your simple approach, but I want to keep the presentation layer separate from the business logic, which is why I thought the theme/template approach would be better?
Comment: No worries, my question isn't very clear! As per usual.. Thanks


Websocket can't connect when deploy on server IIS 7

Question: <code>I have issue when Deploy Websocket on my server on local it working fine,
</code>
when i deploy on Server, Response from server :
 "failed: Error during WebSocket handshake: Unexpected response code: 200", the different between Local and Server it on Server I used UrlRewrite on IIS
Comment: WebSocket is only supported on IIS 8 and above, https://learn.microsoft.com/en-us/iis/get-started/whats-new-in-iis-8/iis-80-websocket-protocol-support
Answer: According to your description, it seems that your server doesn't install web socker or your IIS doesn't support web socket.
I suggest you could try to check the windows features to make sure you have installed the websoket protocol.


Executing custom sql including complex select joins using entity framework 4

Question: My application currently uses ado.net to access the database.
It allows users to configure dashboards by passing custom sql. The custom sql includes joins on multiple tables and the columns of every table are included in the result.
We are migrating from ado.net to entity framework 4.
How do I execute the same queries using entity framework?
Also other code in the application requires firing custom complex join queries on the database. This is done by developers.
Answer: Yes you can use inline queries and even stored procedue in entityframework
see example for query http://msdn.microsoft.com/en-us/library/bb738451
see example for stored procedure http://msdn.microsoft.com/en-us/library/bb896334.aspx
Comment: My end user has entered database queries that i need to fire. The first link provided requires passing linq sql queries. The moment i pass a database join query it gives me scope or context error.
Comment: My Database tables are USER(primary table) and USER_DETAILS(child table) related by USER_ID.
Comment: The initial database query : "SELECT u.USER_ID, u.LOGIN_ID, u.FIRST_NAME, u.LAST_NAME, u.GENDER, ud.USER_ITEM_ID, ud.ITEM_VALUE from [USER] u LEFT JOIN USER_DETAILS ud ON u.USER_ID = ud.USER_ID ".
The entity framework query to which I had to change to : "SELECT u.USER_ID, u.LOGIN_ID, u.FIRST_NAME, u.LAST_NAME, u.GENDER, ud.USER_ITEM_ID, ud.ITEM_VALUE from USERs as u LEFT JOIN USER_DETAILS as ud ON u.USER_ID = ud.USER_ID ".
I need to be able to fire my database queries using Entity Framework. I have no ides how many columns these queries would return or the datatype of these columns.
Comment: I'm sorry for the untidy look of the reply. I had formatted the reply, but I don't know how the formatting dissappeared.
Comment: @ChrisSerrao: Don't pass code to comments. If your question doesn't provide necessary details, update the question directly.
Answer: If you have dynamic queries you cannot execute them through EF. EF works in strongly typed manner so it expects that you created the type with correct properties (with correct types) at design time (you can create the type at runtime as well but it requires you to create dynamic assembly, emit IL, etc.).
Use your old approach for this type of queries.


Sequence Diagram(termination of object)

Question: I prepared a university assignment where they asked me to create sequence diagram. Here is the diagram.

The teacher rejected the diagram and asked me to mention termination symbol in the diagram. I don't know what is the termination symbol in sequence diagram. The only thing I could find is a cross like symbol which destroys the object but I don't think thats what they are asking. Please help me.
Comment: Is there anything in the narrative that says that a lifeline is supposed to terminate? I hope nobody will terminate the user. The form could perfectly not be terminated and stay with a hidden/inactive state.  Same for the database validator. Last but not least, the sequence is about opening a page so the page should not be terminated either. And we're not in an activity diagram where activities are supposed to have an end.
Comment: Moreover, the diagram shows a scenario with 2 cases: what if the pwd is wrong? wouldn't the other lifelines stay or would the login just stop and the system destroy itself?
Answer: You were just right: that's simply a diagonal cross at the end of the object's lifetime.
From UML 2.5 p. 713:

Basically you just put that centered on the dashed life line below the execution. Then of course it means that at that point in time the object is no longer existent and will neither accept nor send any message. For your picture it might be (I have to guess without knowing details!) be the Login form to terminate when Correct part is executed and the Home page comes into existence. As a side note I would use a createMessage

to actually create the Home page instance right at that point.
As a second side note: don't try to use SD as graphical programming tool. Best stay away from fragments as long as possible. Better you create several diagrams that show a distinct flow of events in a fixed context. That would be one diagram for the positive login and one for the negative attempt. Of course both are trivial cases and you would not need them - they are for academic purpose only. SDs are useful to bring light into complex collaborations. With a stress on complex.
Comment: While I fully agree with the answer regarding what the termination symbol is, I cannot consent to the last sentence. The termination symbol isn't to be just placed anywhere because we need to have it by teachers request. Instead we need to have a valid reason. Example can be a creation of temporary data (e.g. session token) that is destroyed once certain condition is met.
Comment: Yes, much clearer now and my upvote goes to it ;-)
Comment: @Ister I have made it a bit more wordy. Hope that would be more exaplantory now...

Sequence Diagram(termination of object)


Correlating Likert data to nominal data

Question: I have three different versions of a web page design which I have evaluated using a set of Likert usability scales. How do I (can I??) use SPSS to correlate the usability scales to the different versions to see which web page (if any) is perceived to be most useful? (I'm a stats novice so please explain gently :))
Answer: While I am not overly familiar with SPSS, the transformation of Likert to nominal data depends on the scale that you have used in the first instance.
For instance, suppose that you have a usability scale from 1 (least useful) to 10 (most useful).
You decide that a ranking of 7 or above is deemed useful, with your nominal variable being 1 = useful, 0 = not useful.
Therefore, any value of 7 or above is being replaced with a 1, while that below 7 is being replaced with 0.
While I don't have much information on the structure of your data, I would be inclined to convert the data manually in order to ensure that your nominal variable remains consistent across the three different versions.

Correlating Likert data to nominal data


db_delete rows older than 5 minutes

Question: I have a table with a date column and I'd like to delete rows that are older than 5 minutes than "now".
I tried with db_delete conditions but it doesn't work.
I tried this query:
$deleteOldRows = db_delete('reserves')
    ->condition('entityId', -1)
    ->condition('dataReg + 5 MINUTES', 'NOW()')
    ->execute();

Comment: Could you post the code that you have tried here so we can review it?
Comment: I tried this query:
$deleteOldRows = db_delete('reserves')
     ->condition('entityId', -1)
     ->condition('dataReg + 5 MINUTES', 'NOW()')
     ->execute();
Comment: Could you edit the question and include that?
Comment: Done it, sorry!
Comment: No problem, now we have a proper question :)
Answer: The problem is with the condition syntax; it looks like below and performs a binary comparison:
$query->condition($field, $value = NULL, $operator = '=')

There are several issues, there is no field dataReg + 5 MINUTES and it likely won't have the literal value NOW() either. Besides, since you omitted the operator, the query would (if it had worked) only select items that are exactly 5 minutes old.
You are looking for a way to execute SQL in the query instead, which is provided by the where clause:
$query->where($snippet, $args = array())

In your case, it would probably look like this:
$deleteOldRows = db_delete('reserves')
  ->condition('entityId', -1)
  ->where('`dataReg` + 5 MINUTES < :time', array(':time' => 'NOW()'))
  ->execute();

You can find some good information on conditional clauses here: https://www.drupal.org/docs/7/api/database-api/dynamic-queries/conditional-clauses
UPDATE
It appears I was wrong and this can be done with conditions after all, you should just reverse the logic. Rather than adding 5 minutes to the date, subtract 5 minutes from now.
$query->condition('dataReg', $adjusted_date, '<=')

Where $adjusted_date for timestamps would be time() - (5*60). And for DATE types something like date('Y-m-t H:i:s', time() - (5*60)).
Comment: Damn, I didn't think to reverse the logic, you're right! Thank you!!!
Comment: Thank you for your reply, I tried the code you posted but it returns a syntax error, I looked for the documentation but I can't understand how to correctly write the condition 'dataReg + 5 MINUTES'
Comment: Please see my updated answer

db_delete rows older than 5 minutes


Trigger smart speaker announcement via HTTP request

Question: I have a smart speaker with buit-in Google Assistant which I want to automatically make announcements at specific times. The times are determined by a program I wrote running in the cloud which can send HTTP POST requests at those times (e.g. to trigger a Telegram bot or anything else with a usable API).
Is there a way to send POST requests directly to my smart speaker with a message to announce? Or would I need some intermediary app/service to integrate with Google Assistant?
Comment: I am looking for the same answer. I want to tell the speaker saying "bed time, kids" at 20:30 for example. @J-J, have you figured this out?
Comment: I have not. However, your requirement seems simple: if it's a regular bed time then just set up a routine on your phone which broadcasts to your specified home device(s). My difficulty is the times of my broadcasts are determined in code each day.
Answer: You can make use of the Google Assistant SDK to send POST requests directly to your smart speaker with a message to announce. The Google Assistant SDK lets you add voice control, natural language understanding and Google's smarts to your ideas. Your project captures an utterance (a spoken audio request, such as What's on my calendar?), sends it to the Google Assistant, and receives a spoken audio response in addition to the raw text of the utterance.
You can also refer to the Google Broadcast and Routines feature using which you can make announcements at specific times .


How to notate a phrase than goes up and down several octaves

Question: I have several bars of sixteenth notes that span quite a large range on the keyboard, and also go up and down the length of four octaves on the keyboard quite rapidly. I am not sure about how best to notate this on my score for maximum clarity.
The beginning of the particular phrase starts in the bass clef, and the first note is F3; then the notes ascend up to B flat 4, before coming down again to F3, then up to C5, and back down again, and so on, for several bars. There are some quite large jumps between notes, for example there are two notes in the fourth octave, followed by three notes in the second, and so on.
I have tried using ottava alta lines, but this looks messy because sometimes there are only two notes that would require it. I ended up with too many very short 8va lines above the staff, and it became confusing to read.
I have tried changing the clef throughout the phrase, but again it looked messy, as I would need to change the clefs very frequently within the same bar.
I have tried moving the lower notes of the phrase down onto the bottom staff (with a bass clef) and keeping the higher notes on the top staff (with a treble clef in the top staff) - in other words, using cross-staff beaming. But again this looked more confusing, as I already have two rather complex voices in the bottom staff. Also, some notes of the phrase have accents and slurs that were obscured when I did this.
I have tried keeping the whole phrase in either the bass clef or the treble clef, but that left short sections with many ledger lines (up to six ledger lines). Because the top staff is already in a bass clef, it looks inelegant to the use six ledger lines above the staff, when it could just be in treble.
I want to avoid using three staffs if at all possible.
Any advice would be much appreciated. Thank you.
Comment: Welcome! You can probably get more targeted answers if you post some images of the attempts so we know the actual pitches/ranges in question.
Comment: 8va and 15va are the way most of us would read and understand.
Comment: Another question that can be most authoritatively answered by the book *Behind Bars* by Elaine Gould. (I have no affiliation with the book or the author - it is a comprehensive text on best practices for music notation.)
Comment: I agree with @AndyBonner: Please post an image of your score. You've enumerated and rejected all of the methods for notating this kind of phrase, but getting fresh eyes on it might help find a good-enough compromise.
Comment: Ottava lines don't have to span only those notes that definitely require them. If you need an ottava line *at all*, make it a decent size, even if it ends up transposing a lot of notes that wouldn't in themselves call for it.
Answer: A few real-world examples to supplement @user1079505's answer. Shown below are examples of:

cross-staff notation
clef changes
ottava indications
multiple staves

Chopin's Etudes, Op. 10 (IMSLP) and Op. 25 (IMSLP), are a rich source of these kinds of sweeping phrases.1 The below example comes from his Etude in Ab Major, Op. 25, No. 1. The final six bars contain arpeggios spanning six octaves between the two hands. In the second measure of the excerpt — the first of the "big arpeggio", we can see the uses (1) cross-staff notation, (2) clef changes (in the left hand), and (3) ottava indication. This single measure covers the gamut of options.

A similar example is found in Op. 25, No. 12, mm. 15–16. Note that the clef changes in the left hand correspond exactly with the ottava indications in the right hand. This helps make reading easier.

Another option is to use multiple staves for one or both hands. This is used more often when the musical roles are distinct. In Rachmaninoff's Prelude in C# Minor (IMSLP), the final section of the piece includes both the left and right hands playing large, sustained "accompaniment" chords, then both jumping into higher octaves to play the melody. Two staves are used for each hand in order to clarify the distinct musical roles. Shown below are measures 46–48 from the Augner edition.

1 All Chopin examples come from the Mikuli editions on IMSLP, linked above.
Answer: I'm not sure if you mean F3 in scientific notation on the third line added below the staff with violin clef, or f''',or three-lined which is above the third line added above the staff with the violin clef?
In the first case the phrase would fit well in violin clef:

Or if you really want you could notate it with cross-staff notation:

In the latter case I would use 8va or even 15ma (double octave shift) for the whole phrase, not only the notes that strictly require it.
Comment: OP specifies F3 in bass clef.
Comment: @Aaron yes, I saw it, but then I don't really understand the issue. Just three added lines are not so bad to read? Maybe I'm just biased because they are used normally in guitar scores.
Comment: Got it, and I agree: piano scores routinely use three ledger lines both above and below the staves. The question will benefit from clarification.


Conformal Mapping of Semi-infinite strip

Question:

Problem

I'm looking to investigate how the exponential map acts on the semi inifite strip
$$U:=\{z \in \mathbb{C} : Re(z)<0, 0<Im(z)<\pi \} $$
My understanding is that for the infinite strip, the region will be mapped to the UHP, but I'm not sure how the semi infinite condition affects the mapping.
Ultimately I'm looking for a conformal map from $U$ to the UHP.
Thanks in advance.
Comment: It maps to the uppar half of the unit disc.
Comment: $e^{x + i y} = e^x(\cos(y) + i \sin(y))$.
Comment: @WimC: Thanks, are you able to briefly explain why?
Comment: @WimC: Thanks! Should've seen that!
Answer: Apologies.. you were asking for the exponential mapping. Should have seen that! answer left for reference though. :)
Clearly a semi-infinite strip is still infinite, but only on say X>X0 or Y>Y0 with the "non-infinite" dimension bounded. The mapping for a semi-infinite strip still maps to an upper half plane, it is just slightly different mathematically. The mapping is really quite simple if one is but to apply a Schwarz-Christoffel mapping as the limiting form of a triangle (to quote the wikipedia page on Schwarz-Christoffel transformations).
I know it has been a year since your post, but I stumbled upon this unanswered question in my hunt for my own answers!


Definition of a certain matrix

Question: I remember I came across matrix of the form
$$\begin{bmatrix}
1 & 0 & 0 & 0\\
1 & 1 & 0 & 0\\
0 & 1 & 1 & 0\\
0 & 0 & 1 & 1\\
\end{bmatrix}$$
There is a name for it but I can't remember. Does anyone know the name of the matrix of this form?
Comment: Search on Jordan.
Comment: May be [Jordan block](https://en.wikipedia.org/wiki/Jordan_matrix) (though usually the ones are on upper diagonal), lower [triangular](https://en.wikipedia.org/wiki/Triangular_matrix), upper [Hessenberg](https://en.wikipedia.org/wiki/Hessenberg_matrix) (with imagination!), [tridiagonal](https://en.wikipedia.org/wiki/Tridiagonal_matrix) (with a zero upper diagonal) or [bidiagonal](https://en.wikipedia.org/wiki/Bidiagonal_matrix). Also a [nonnegative matrix](https://en.wikipedia.org/wiki/Nonnegative_matrix), or simply a [square matrix](https://en.wikipedia.org/wiki/Square_matrix) :-)
Comment: Yup, that is the one. Thanks.
Answer: It is called the Jordan Block .
$$\left(\begin{matrix}
\lambda & 1 & 0 & \cdots & 0 \\
0 & \lambda & 1  & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots\\
0 & 0 & 0 & \lambda & 1\\
0 & 0 &  0 & 0 & \lambda
\end{matrix}\right)$$
Comment: You lazy man! ;-)
Comment: Actually i dont know how to use this Mathjax =P

Definition of a certain matrix


Proving $rank(\wp(x)) = rank(x)^+$

Question: Enderton defines the rank of a set $A$ to be the least ordinal $\alpha$ such that $A \subseteq V_{\alpha}$ (equivalently, $A \in V_{\alpha^+}$). He the derives the following identity: $rank(A) = \bigcup \{ (rank(x))^+ : x \in A \}$ for all sets $A$.
In Exercise 30 of Chapter 7, the reader is asked to prove several identities involving rank. For instance, that $rank\{a,b\} = max(rank(a),rank(b))^+$. I am having trouble proving the second identity, that $rank(\wp(x)) = rank(x)^+$ for all sets $x$. I am not sure whether I am missing some elementary identity that would let me prove the identity, or whether I am misunderstanding the definition of rank.
Clearly, $z \in rank(\wp(x)) \Leftrightarrow (\exists y)(y \subseteq x \wedge (z \in rank(y) \vee z = rank(y))$. On the other hand $z \in (rank(x))^+ \Leftrightarrow (\exists y)(y \in x \wedge z \in (rank(y))^+) \vee z = rank(x)$. I'm not sure why the first statement should imply the second, and conversely, however.
Answer: I assume $\alpha^+$ just means $\alpha+1$, the immediate successor of $\alpha$. (Typically, we use $\alpha^+$ for a different notion.)
The point is this: Suppose that $x\subseteq y$. Then $rank(x)\le rank(y)$. This is immediate from the identity at the end of your first paragraph. It follows that all subsets of $x$ have rank at most $rank(x)$. Say $\beta$ is least such that $x\in V_\beta$. Then ${\mathcal P}(x)\subseteq V_\beta$ (since all subsets of $x$ are also elements of $V_\beta$) and therefore ${\mathcal P}(x)\in V_{\beta+1}$. This shows that $rank({\mathcal P}(x))\le rank(x)^+$.
For the converse: If $rank({\mathcal P}(x))< rank(x)^+$ then $rank({\mathcal P}(x))\le rank(x)$. Use the identity at the end of your first paragraph to conclude that all elements of ${\mathcal P}(x)$ have rank strictly less than $rank(x)$. But then $x$ itself would have rank strictly less than $rank(x)$. This is a contradiction, and we are done.
Comment: Thank you, Andres. I was certainly approaching this problem incorrectly. Your explanation is very clear, and the method helpful.
Comment: Out of curiosity, what *does* $\alpha^+$ mean? My lecturer used $\alpha^+$ for the successor of $\alpha$ as well...
Comment: The standard notation is that if $\kappa$ is an *infinite cardinal* (i.e., an infinite ordinal that is not in bijection with any smaller ordinal; sometimes one says: $\kappa$ is an infinite *initial ordinal*), then $\kappa^+$ is the successor *cardinal* of $\kappa$, which is an ordinal much much larger than $\kappa+1$. If $\alpha$ is an ordinal then $|\alpha|$ is its cardinality (the initial ordinal in bijection with $\alpha$), and $\alpha^+$ means $|\alpha|^+$. For $\alpha$ finite sometimes people mean $\alpha^+=\alpha+1$ and sometimes they mean $\alpha^+=\omega$.

Proving $rank(\wp(x)) = rank(x)^+$


Twig doesn't throw exceptions

Question: I am using symfony 2.3 with twig 1.0.* Twig doesn't throw any errors when undeclared variables are displayed. All errors are ignored.
For example, I have any undefined variable 'test' I can do the following and no errors are displayed just blank text.
{{ test }}
{{ test.do() }}
{{ test.test2 }}

Is there a setting to turn this back on?
Answer: Yes, the strict_variables option of twig. In a symfony standard installation the twig configuration defaults to
# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"

which means it depends on the debug option of the kernel. In prod environment this should be false of course, but in the dev environment it should default to true and twig should throw a exception. If the kernel debug is not true in dev, check your web/app_dev.php file. It should initialize the AppKernel with the following line.
$kernel = new AppKernel('dev', true);

Comment: "In prod environment this should be false of course" - I don't understand this part. Doesn't this mean that a bug would be silently hidden? I understand this should be true in dev environment to catch the bug there first. But if it slips through, there is no chance to catch it in the production logs. Or am I missing a point?

Twig doesn't throw exceptions


Why does my content type need to be reviewed before it can be saved?

Question: I created a new content type and when I want to create new content of this content type, on the bottom I only get the Preview button, the Save button does not show up and I can not find in the content type settigns how I disable this "must preview before save"-feature...
Answer: In Drupal 7, you can manage this via admin/structure/types/manage/CONTENT_TYPE in the Submission form settings:

In Drupal 6, you manage this via admin/content/node-settings:


Create a method like current_user for devise's current resources

Question: I want to create a method like current_user for devise's current resources.
Suppose I have two resources like User and Admin and devise is associated with both. So as usual it dynamically creates it's default methods like current_user and current_admin.
It creates it by defining like this in file lib/devise/controllers/helpers.rb:
def current_#{mapping}

How can I add a new method like this to it's dynamic methods.
I want to implement it with devise methods, so that when devise initializes then my method is also initialize with same mapping name.
Comment: User and Admin different model and table?
Comment: Yes they are different tables
Comment: if your `Devise` model is called `Member` instead of `User`, for example, then the helpers available are: `current_member` or `member_session`.
Comment: Yes I know that but I just wanted to add my own method with devise methods which will generate methods like user_policies, present_policies.
Answer: Copy this code into your application controller. and your problem will solved.
Devise.mappings.each do |mapping, obj|
  define_method "current_#{mapping}_email" do
    eval("current_#{mapping}.email if current_#{mapping}")
end
helper_method "current_#{mapping}_email"

On view page/controller used according to your resource name
like if you have resource_name as user then its 'current_user_email'
or if have admin then 'current_admin_email'
Answer: This works!
I added a custom method current_user_email as follows!
Add a file devise_ext.rb in config/initializers:
And in that file, add your custom methods in this way:
module Devise
      module Controllers
        # Those helpers are convenience methods added to ApplicationController.
        module Helpers
      def self.define_helpers(mapping) #:nodoc:
        mapping = mapping.name

        class_eval <<-METHODS, __FILE__, __LINE__ + 1
          def authenticate_#{mapping}!(opts={})
            opts[:scope] = :#{mapping}
            warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
          end

          def #{mapping}_signed_in?
            !!current_#{mapping}
          end

          def current_#{mapping}
            @current_#{mapping} ||= warden.authenticate(scope: :#{mapping})
          end

          def #{mapping}_session
            current_#{mapping} && warden.session(:#{mapping})
          end

          def current_#{mapping}_email
            @current_#{mapping}.email if @current_#{mapping}
          end
        METHODS

        ActiveSupport.on_load(:action_controller) do
          helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session", "current_#{mapping}_email"
        end
      end
    end
  end
end

P.S. I don't think this is the best way to do this. But it works. I tried this in one of my applications! You can use this code till I find a better way to do this :)
Comment: Yes that's what the devise does but the question is not how we create a dynamic method. It's how we can add our method with the methods of devise.
Comment: You can do that by overriding the devise classes.
Comment: Are you trying to achieve this without overriding devise methods


Gini impurity greedily optimises a loss function in decision trees

Question: I am trying to understand how the Gini criterion for decision decision tree construction actually greedily optimises a loss function.
The Gini impurity, sometimes also called Gini index, for a region (think: set) $R_{j}$ is defined as  $\sum_{i=1}^K p_{i}^j (1-p_{i}^j)$ where $p_{i}^j$ is the probability of drawing an example of class $i$ from region $R_{j}$ and $K$ is the number of classes.
I have two references which suggest this but I am not able to fully understand either of them so I would appreciate some help.
Yang2019 write:

Given some node, the objective function after splitting on this node can be written as
$$
L\left(s, f_L, f_R\right)=\sum_{i: s\left(x_i\right)=0} l\left(f_L\left(x_i\right), y_i\right)+\sum_{i: s\left(x_i\right)=1} l\left(f_R\left(x_i\right), y_i\right) \text {, }
$$
where $s(\cdot)$ denotes a binary split function which decides whether an input instance that reaches this node should progress through the left or right branch emanating from the node; and $f_L(\cdot), f_R(\cdot)$ denote the output function w.r.t the left and right child, respectively.

Given a specific split function $s(\cdot)$, we have the reduction of objective function
$$
\begin{aligned}
t(s)=\min _w \sum_{i=1}^n l\left(w, y_i\right)-\min _{w^L} & \sum_{i: s\left(x_i\right)=0} l\left(w^L, y_i\right)
& -\min _{w^R} \sum_{i: s\left(x_i\right)=1} l\left(w^R, y_i\right),
\end{aligned}
$$
where $w, w^L, w^R$ denote the output values of the node and left and right child node, since instances in one node have the same output values. --- Based on this equation, we can directly prove that the essence of various splitting criteria is to optimize some loss functions greedily. For instance, the frequently-used criteria gini impurity and information gain are essentially equivalent to optimizing the square loss and softmax loss [23], respectively.

I understand the equations above but I do not see how a split $s$ that minimises the Gini index reduces the squared error loss function $l(w_{L}, y_{i}) = (w_{L} - y_{i})^2$ (resp. for $R$).
Let's try something else then.
Leistner2009 consider margin losses instead and argue that the Gini index greedily optimises a loss function "related to the Hinge loss"

We can write the empirical loss at a node $R_j$ as
$$
\mathcal{L}\left(\mathcal{R}_j\right)=\frac{1}{\left|\mathcal{R}_j\right|} \sum_{(\mathbf{x}, y) \in \mathcal{R}_j} \ell\left(g_y(\mathbf{x})\right) .
$$
where $g_{y}(x)$ is the "true margin vector of $x$" i.e. Let $\mathbf{g}(\mathbf{x})=\left[g_1(\mathbf{x}), \cdots, g_K(\mathbf{x})\right]^T$ be a multivalued functio, then. $\mathbf{g}(\mathbf{x})$ is called a margin vector, if
$$
\forall \mathbf{x}: \sum_{i=1}^K g_i(\mathbf{x})=0 .
$$
Defining the margin vector as $\mathbf{g}^j(\mathbf{x})=\left[p_1^j-\right.$ $\left.\frac{1}{K}, \cdots, p_K^j-\frac{1}{K}\right]^T$, we can develop the empirical loss as
$$
\begin{aligned}
\mathcal{L}\left(\mathcal{R}_j\right) & =\frac{1}{\left|\mathcal{R}_j\right|} \sum_{(\mathbf{x}, y) \in \mathcal{R}_j} \sum_{i=1}^K \mathbb{I}(y=i) \ell\left(p_i^j-\frac{1}{K}\right) \\
& =\frac{1}{\left|\mathcal{R}_j\right|} \sum_{i=1}^K \ell\left(p_i^j-\frac{1}{K}\right) \sum_{(\mathbf{x}, y) \in \mathcal{R}_j} \mathbb{I}(y=i) \\
& =\sum_{i=1}^K p_i^j \ell\left(p_i^j-\frac{1}{K}\right) .
\end{aligned}
$$
Using (these) results, we can see that (...) the Gini index is related to the hinge loss function.

Again, I understand the derivation but I am unable to see how the Gini index $\sum_{i=1}^K p_{i}^j (1-p_{i}^j)$ can be related to the equation above and via what $\ell$.
Comment: The name Gini is attached, with some historical justification, to quite different measures. This measure based on squared probabilities is not the same as that covered in the book by Yitzhaki and Schechtman.
Comment: To make the distinction concrete, note that for the measure here it is necessary and sufficient to know or estimate probabilities of $K$ classes, $p_k$ (I've changed the OP's notation slightly).  At the simplest we might have just categories $A$ and $B$ and two probabilities. Then $\sum_{k=1}^K p_k^2$ is a measure of homogeneity, quaintly sometimes called purity, maximised at $1$ if one $p_k$ is $1$ and the others all $0$. Similarly $1 - \sum_{k=1}^K p_i^2$ is a measure of heterogeneity (impurity).
Comment: This is nothing to do with any Gini index based on pairwise differences $x_i - x_j$ for pairs of values $x_i, x_j$ for a counted or measured variable $x$ (income is a common example in economics). It's unfortunate that the same name is persistently used for different measures, but confusion should not survive a look at the algebra or the results of calculations.
Comment: I don't have an answer to the question!
Comment: Thank you for your comments. Indeed, I am referring to the quantity that @NickCox describes. The better term is probably "Gini impurity". Also described on [this wikipedia page](https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity). Since opening this question I thought about it some more, see my answer below.
Comment: See also: [What is the relationship between the GINI score and the log-likelihood ratio](https://stats.stackexchange.com/a/95459/178468) for relating Gini impurity to entropy and information gain.
Answer: I got a somewhat mathematical explanation for this. The idea is to argue that the negative Gini index is a generator function for a Bregman divergence that corresponds to classification margins.
I hope it makes sense. Let me know if there's anything wrong with it.
One may suggest a measure of purity as the probability of drawing two different outcomes from the examples in the current cell.

Def: Let $p_{k} = \mathbb{P}_P(k|X)$ be the probability of drawing an example orepf class $k$ from node $P$. The probability of drawing
one example of class $k$ and one of a different class is
$p_{k}(1-p_{k})$. The probability of drawing two examples of any two
different classes then is the Gini index $$ G := \sum_{k}p_{k}(1-p_{k}) = 1 - \sum_k p_k^2 $$

We will now argue that a reduction in the Gini index in fact pushes values $p_{k}$ to the extremes of the probability simplex.
We perform a slight shift in perspective and consider the classification margin instead of the estimated probabilites.

Def: The classifier margin for class $k$ of an example $X$ is the difference between the model's confidence that $X$ is of class $k$ and
the next-best class: $$ m_{k}(X) := \mathbb{P}(k|X) - \max_{j\not=k}
> \mathbb{P}(j|X) $$

For a pair $(X,y)$ of example and true outcome, the model's prediction is correct iff $m_y(X) > 0$
The vector $m(x) = [m_{1}(x), \dots, m_{K}(x)]^\top$, where $K$ is the total number of classes, is called a margin vector iff its components sum to zero.
We will argue that the Gini index split criterion, which finds a split such that the Gini index is reduced, in fact maximises the classification margins.

Lemma: Let $p$ be a probability distribution and $u$ an arbitrary vector.
Let $G =\sum_{k} p_{k}(1-p_{k})$ be the Gini index. Then $-G$ is the generator for the Bregman divergence $$ B_{-G}(p,u) =\sum_{k}(p_{k}-u_{k})^2 $$

Proof: Let $\phi(q) := (-1) \sum_{k} p_{k}(1-p_{k})$. Then, the first equality follows by definition of a Bregman divergence and the second equality by arithmetic.
\begin{align*}
B_{-G}(p,u) &=
\underbrace{(-1) \sum_{k} p_{k}(1-p_{k})}_{\phi(p)}
 ~ ~ - ~ ~
\underbrace{(-1) \sum_{k} u_{k}(1-u_{k})}_{\phi(u)}
~ ~ - ~ ~
\underbrace{\sum_{k} (2u_{k}-1)(p_{k}-u_{k})}_{\langle \nabla \phi(u), p-u \rangle} \\
 &= \sum_{k} (p_{k}-u_{k})^2
\end{align*}
Note further that maximising the value of the generator function $\phi$ with respect to $p$ while leaving the the other parameter $u$ fixed also maximises the divergence $B(p,u)$.
The sign of the generator value and the sign of the divergence are related in that  $B_{-\phi}(p,u) = - B(p,u)$.
This means that minimising the Gini index during splitting maximises component-wise sum of squared errors between $p$ and $u$.
$$
\min G \rightarrow \min B_{-G}(p,u) \rightarrow \max B_{-G}(p,u) = \sum_{k}\left( p_{k} - u_k \right)^2
$$
If $p$ is a probability distribution and $u := [\frac{1}{k}, \dots, \frac{1}{k}]^\top$, then $p-u$ is a margin vector and the optimisation corresponds to maximising the classification margins as measured by the squared error.
A common approach in training classification models
is margin maximisation [2]
in which we aim to maximise the margin of the true label $m_{y}(X)$.
A margin loss function $\ell : \mathbb{R} \to \mathbb{R}$ is a margin-maximising loss if $\ell'(m_{y}(X)) \leq 0$ for all values of $m_{y}$ [3].
An example for a margin-maximising loss function is the hinge loss defined as
$\ell(m_{y}(x)) :=  \max \{ 0, 1-p \}$. Its subderivative is
$$
\frac{\partial\ell}{\partial p} = \begin{cases}
-1 & p \leq 1 \\
0 & \text{else}
\end{cases}
$$ and hence it is a margin-maximising loss.
A decision tree can also be evaluated based on a margin loss.
The empirical error of a decision tree node $P$ with respect to a margin loss $\ell$ can be written as $L(P) = \frac{1}{|P|} \sum_{i \in P} \ell\left(m_{y}(x_{i})\right)$ where $m_{y}(x_{i})$ is the value of the true margin. Then the following holds [3].
\begin{align*}
L(P) &= \frac{1}{|P|}\sum_{i \in P} \sum_{k} \mathbb{1}(y_{i}=k) ~ ~ \cdot ~ ~  \ell   \left( m_y(x_i) \right)  \\
&= \sum_{k}
\frac{1}{|P|} \sum_{i \in P} \mathbb{1}(y_{i}=k)
~ ~ \cdot ~ ~
\ell(m_{k}(x_{i})) \\
&= \sum_k p_k(x_i) \ell(m_k(x_i))
\end{align*}
Hence we see that the Gini index splitting criterion greedily optimises classification margins and thus margin-maximising losses.
Side note: Another commonly used splitting criterion is the information gain corresponding to the Shannon entropy. The entropy is the Bregman generator for the KL-divergence. So, a very similar argument could be applied to argue that the information gain optimises the KL-divergence.
[2] schapire_BoostingFoundationsAlgorithms_2012
[3] leistner_SemiSupervisedRandomForests_2009


Replace character on multiple elements

Question: Given this piece of HTML

            Cantidad

            <fieldset>

                <input type="radio" value="3-rosas" id="cantidad" name="attribute_cantidad">3_rosas

                <input type="radio" value="12-rosas" checked='checked' id="cantidad" name="attribute_cantidad">12_rosas

                <input type="radio" value="18-rosas" id="cantidad" name="attribute_cantidad">18_rosas

                <input type="radio" value="24-rosas" id="cantidad" name="attribute_cantidad">24_rosas

            </fieldset>

I would like to replace the "_" character on the option text with a white space using  javascript or jQuery.
I have tried with no success.
Thanks.
Comment: option text? where is that?
Comment: Where is your jquery code you tried?
Comment: I don't think it is good to have multiple id with same name.
Answer: It is difficult to get each text after radio button and then replace _ with space. You need to wrap the text in some html element like label, span etc and then use .replace('_',' ');).
See below code -
HTML - I have wrapped text into label

         Cantidad

         <fieldset>

            <input type="radio" value="3-rosas" id="cantidad"
                    name="attribute_cantidad">
            3_rosas

            <input type="radio" value="12-rosas" checked='checked'
                   id="cantidad" name="attribute_cantidad">
            12_rosas

            <input type="radio" value="18-rosas" id="cantidad"
                   name="attribute_cantidad">
            18_rosas

            <input type="radio" value="24-rosas" id="cantidad"
            name="attribute_cantidad">
            24_rosas

         </fieldset>

jQuery :
$(function(){
    $('table td.value fieldset label').each(function(){
     $(this).text($(this).text().replace('_',' '));
    });
});

DEMO
Comment: Thanks, I was banging my head on the wall with this. I wasn't wrapping the element with a tag.
Answer: Please check below code.
$('.value').find('input:radio').each(function(){
    var val = $(this).val().replace(/-/g, ' ');
    $(this).next('span').html(val);
});

Please check below fiddle.
Fiddle
Answer: You can use the .contents() method, then replace any _ in each text node as follows:
$('.value > fieldset').contents().each(function() {
    this.nodeType !== 3 || ( this.textContent = this.textContent.replace(/_/g,' ') );
});

$('.value > fieldset').contents().each(function() {
    this.nodeType !== 3 || ( this.textContent = this.textContent.replace(/_/g,' ') );
});

            Cantidad

            <fieldset>

                <input type="radio" value="3-rosas" id="cantidad" name="attribute_cantidad">3_rosas

                <input type="radio" value="12-rosas" checked='checked' id="cantidad" name="attribute_cantidad">12_rosas

                <input type="radio" value="18-rosas" id="cantidad" name="attribute_cantidad">18_rosas

                <input type="radio" value="24-rosas" id="cantidad" name="attribute_cantidad">24_rosas

            </fieldset>

Replace character on multiple elements


Swift serial queue that only retains one pending task

Question: I need a serial queue that instead of building up a backlog of tasks, only performs the task it's doing and the latest one queued since that started. Any job waiting in the queue for execution should be discarded if a new one comes in before it starts. Been trying to make it work using actor, async and await as follows but it's a bit advanced considering I only learned this stuff today. Is this close?
actor Worker {
    var task: Task <Void, Never>? = nil
    var next: Item? = nil
    var latestResult = false

    func analyseItem(_ item: Item) async -> Bool {
        // make our item next (but could be overwritten)
        next = item
        // let anything that's running complete
        await task?.value
        // start a task for the latest request
        task = Task {
            latestResult = next?.processItem()
            task = nil
        }
        return latestResult
    }
}

Comment: What problem are you having with the above code?
Comment: I think if a few items are queued while one is ongoing, the `task = Task` line will fire multiple times leading to the same item being processed repeatedly.
Answer: I made a small project in Playgrounds
import Combine
import Foundation
import _Concurrency

actor Analyzer {
    var timestamp = Date()
    var flag = false

    func analyzeData(timestamp: Date) async throws {
        if flag { return }

        flag = true

        print("analyzing @\(timestamp)...")

        try await Task.sleep(nanoseconds: 3_000_000_000)

        print("analyzing @\(timestamp) complete.")

        flag = false
    }
}

let analyzer = Analyzer()
var cancellable: AnyCancellable

cancellable = Timer.publish(every: 2, on: .main, in: .default)
        .autoconnect()
        .receive(on: DispatchQueue.main)
        .map({ output -> Date in
            Task {
                try? await analyzer.analyzeData(timestamp: output)
            }

            return output
        })
        .sink(receiveValue: { date in
            // print(date)
        })

Since flag is isolated, tasks will be analyzed every 4 seconds, because the timers fired every 2 and tasks last 3 seconds.
Comment: Thanks, this would be a good no-nonsense way of approximating it.
Comment: This will discard anything that comes in while a previous task is still running. But he wanted a solution that "only performs the task it's doing and the latest one queued since that started."


How can I show modal , after button [action] is clicked?

Question: Well, I have modal-window where I have 2 buttons - pay and close.
Once pay is clicked, I need to show another modal-window
I have 2 modals as DIV's

and here is Pay button
<button type="button"
onclick="event.preventDefault();
$('#checkaccept-tid{MKT_ID} input[name=accept]').val(1);
$('#checkaccept-tid{MKT_ID}').submit();"
class="submit">Pay
</button>

and other DIV/Modal

Both divs/modals are working fine, tested using Demo Button , just changing ID's.
So, when user is working with 1 DIV (modal) there is a button, which he is clicking - Pay.
After this button is clicked, I need to show 2 DIV success_order_popup_content
really tired or brain totally do not work, cannot understand, how to display ..
was trying to call modal window when condition of other logic is true, but this is I guess bad idea.
Comment: `$('#confirm_inprogress_done_popup_content').show();` maybe??
Answer: I'm an idiot.
I was calling

And it was not working, but it was NOT working because of my PHP Condition was written incorrect. Now all is good


Subtração de valores na mesma tabela e mesma coluna

Question: Eu tenho uma tabela no phpMyAdmin chamada fluxo, nessa tabela se encontra o fluxo de um caixa

(A descrição serviria para sabermos para que serve cada registro)

Eu preciso ter um jeito de conseguir o lucro liquido de cada mês em um período de 1 ano de forma que o primeiro registro seja o mais antigo e o ultimo o mais novo.
Eu tentei somar o lucro agrupando por mês, fazer a mesma coisa com os gastos e subtrair uma coluna da outra e só filtrar as colunas desejadas no final com SELECT:
SELECT
    Valor,
    DataN
FROM
    (
    SELECT
        COALESCE((L.Valor - G.Valor),
        L.valor) AS Valor,
        MONTHNAME(L.Data) AS DataN,
        L.Data AS DATA
    FROM
        (
        SELECT
            `ID`,
            SUM(`Valor`) AS Valor,
            `Data` AS DATA
        FROM
            `fluxo`
        WHERE
            `Tipo` = 'Lucro'
        GROUP BY
            YEAR(`Data`),
            MONTH(`Data`)
        ORDER BY
            YEAR(`Data`),
            MONTH(`Data`)
        DESC
    ) AS L
LEFT JOIN(
    SELECT `ID`,
        SUM(`Valor`) AS Valor,
        `Data` AS DATA
    FROM
        `fluxo`
    WHERE
        `Tipo` = 'Gasto'
    GROUP BY
        YEAR(`Data`),
        MONTH(`Data`)
    ORDER BY
        YEAR(`Data`),
        MONTH(`Data`)
    DESC
) AS G
ON
    L.Data = G.Data
ORDER BY
    YEAR(L.`Data`)
DESC
    ,
    MONTH(L.`Data`)
DESC
LIMIT 12
) F
ORDER BY
    YEAR(F.`Data`) ASC,
    MONTH(F.`Data`) ASC

Mas algo está dando errado e não sei o que possa ser.
Answer: Segue um exemplo de utilização
Select month(data) as mes, year(data) as ano, coalesce(flucro.total, 0) as lucro, coalesce(fgasto.total, 0) as gasto, (coalesce(flucro.total, 0) - coalesce(fgasto.total, 0)) as saldo from fluxo
  left join (Select Sum(valor) as total, month(data) as mes, year(data) as ano from fluxo as flucro where tipo = 'Lucro' group by 2, 3)
as flucro on month(data) = flucro.mes and year(data) = flucro.ano
  left join (Select Sum(valor) as total, month(data) as mes, year(data) as ano from fluxo as fgasto where tipo = 'Gasto' group by 2, 3)
as fgasto on month(data) = fgasto.mes and year(data) = fgasto.ano
group by 1,2 order by 1,2
Comment: Apareceu o seguinte erro: ```#1055 - Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'flucro.total' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by```


How to write the code for the back button?

Question: I have a php code here and I would like to create a "back" href to get me back to where I was before. Here's what I have:
<input type="submit" "Back"

     <?php
     // get form selection
     $day = $_GET['day'];
     // check value and select appropriate item
      if ($day == 1) {
      $special = 'Chicken in oyster sauce';
         }
      elseif ($day == 2) {
      $special = 'French onion soup';
       }
      elseif ($day == 3) {
       $special = 'Pork chops with mashed potatoes and green salad';
        }
      else {
      $special = 'Fish and chips';
      }
      ?>

Today's special is:

       <?php echo $special; ?>
       <input type="submit" "Back"

Comment: And your problem is what, exactly?
Comment: Probably the nested  inside the  tag. (Which should be type button, not type submit). But Dave already posted an answer.
Answer: <button onclick="history.go(-1);">Back </button>

Comment: Caution: `history.go(-1);` will always take you one step back in history, even if that page is some other website you had opened earlier in the same tab of the browser.
Comment: @tintin yes, you can.  and the -1 is telling it where to go in the history, in this example back one.
Comment: this one works perfect... can i adjust the space of the back button?
Comment: i see how can you adjust the width of the button and also the spacing?
Comment: don't forget `type="button"` attribute
Answer: If you want to do it (what I think you are trying right now) then replace this line
<input type="submit" "Back"

with this
<button type="button" onclick="history.back();">Back</button>

If you don't want to rely on JavaScript then you could get the HTTP_REFERER variable an then provide it in a link like this:
<a href="<?php echo $_SERVER['HTTP_REFERER'] ?>">Back

Comment: Nice options - You may want to include `type="button"` to your button code so it validates :)
Comment: @Basiclife: how could you do that?
Comment: Is `type` really a mandatory attribute? http://www.w3schools.com/tags/tag_button.asp
Comment: @Dave - I was just about to link to that :) I believe "button" should be the default type but I've had instances of browsers using submit as the default - which can cause issues if you're not expecting a submit. I've since made myself define it explicitly - That said, you're right, it's not required to validate.
Comment: @Basiclife - But it would surely not be amiss, so I edited my answer and added the type attribute :-)
Comment: @davehauser see w3fools for recommending w3schools.com
Comment: I am adding +1 because the second solution (using $_SERVER['HTTP_REFERER'])  is the only one that works for me.  I am embedding a google slide presentation.  Each time the user moves forward it updates the history, so using history is useless.  Thanks!
Comment: Note: Starting with 5.4, one can rely on `` `">Back`.
Comment: ... however, clicking a link to the URL supplied by HTTP_REFERER is not quite the same as `history.back()`. Specifically, the server recreates the page and sends it to the browser again. So there is a cost in server cpu, network bandwidth, and delay before user sees page, versus javascript telling browser to go back in history.
Answer: Back

this one (by Eiko) is perfect, use css to make a button of ...
eg you can use this css class in  as `
Back`

.back_button {
display:block;
width:100px;
height:30px;
text-align:center;
background-color:yellow;
border:1px solid #000000;
}

Answer: You need to tell the browser you are using javascript:
Back

Also, your input element seems out of place in your code.
Comment: You asked for a "back href". And *button* can be anything you click on - if you need form elements, specifically ask for them. Maybe put a single question in your text anyway... If you downvoted, then sorry I bothered to answer.
Comment: @no problem it's ok. opps my bad. yes i asked only for the back href. I was already imagining that it will be automatically inside the button. sorry
Comment: No worries. See the other answers in that case.
Answer: <input type="submit" "Back"

Is invalid HTML due to  the unclosed input element.
"Back"

is enough
Comment: I believe he meant `history.go(-1)` :)
Answer: In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.
  function redirection()
        {
           <?php $send=$_SERVER['HTTP_REFERER'];?>
            var redirect_to="<?php echo $send;?>";
            window.location = redirect_to;

        }

Comment: `$_SERVER['HTTP_REFERER'];` is highly unreliable.
Comment: in my case window.history was not working,I tried this in codeigniter,and it gives me correct redirection
Comment: Be aware that this sends a URL to your web server. The page will be slower to load than simply doing javascript in browser to go back one page. So only use when cannot use the javascript solution for some reason.
Comment: @ToolmakerSteve Absolutely correct, In my case I was having multiple views which were called through AJAX. These views were called based on the workflow that is why normal javascript was not working for me
Answer: Basically my code sends data to the next page like so:
**Referring Page**
$this = $_SERVER['PHP_SELF'];
echo "Next Page";

**Page with button**
$prev = $_GET['prev'];
echo "<button id='back'>Back</button>";

Comment: Please explain under what circumstances this is preferable to using the standard, built-in ways of going back a page, seen in other answers.
Comment: When I wrote that answer, I wasn't too big on JS... but I won't say it's all wrong, because it's easier to implement. All you have to do is place it in the href attribute, versus adding event listeners


Problems rendering radio buttons after an ajax call

Question: I'm going to be linking this D.O issue.
I found that when changing an attribute other radio buttons would not update properly. Specifically that when there was two possible options for these buttons but each were only available if another option in the form was set, changing the first attribute resulted in the second one not being rendered as checked. If you went to add that item to the cart the proper variation would be added so this  seems to be just visual.
I was able to use xdebug to find that the default value of the buttons is set correctly.
I've been digging through the rendering trace of this element but am getting quite lost.
Does anyone know why after an ajax call a radio button would be rendered incorrectly and not be marked as checked?
Comment: could you please post your AJAX callback code? Also, is the default value for the Style input already set when the form is initially loaded? Or is this set entirely based on the Color selection?
Answer: A common mistake with AJAX is presuming that an AJAX callback is "aware" of the form's state. In reality, the form definition that AJAX works with is the original form instance. You will have to set the form values accordingly in your AJAX callback prior to returning the re-rendered markup. The $form argument that you receive in your callback function is always a cached copy of the original form.
So, to track what is going on in your form across AJAX callbacks, need to stash data server-side (e.g. in \Drupal::state()) or use the values stored in the $form_state argument. A good explanation of Drupal's form handling can be found here (thanks Jaypan!): https://www.drupal.org/forum/support/module-development-and-code-questions/2012-02-24/update-form-state-in-ajax-callback#comment-5648474
Comment: I do think that makes sense, but is that my problem? ~~I am only changing things within the commerce entity~~ Wrong issue, I don't get any errors about the state being wrong
Comment: Just to make sure I understand: you have radio elements that should be rendered with updated values? And the value isn't being applied to the returned markup?
Comment: Yes. I suggest you take a look at the screenshots on the D.O issue linked, it shows the problem.
Comment: Thanks. I took a look, and I think it still might be the situation I've described. I've asked for some clarification.


Cálculo sempre ativo em JQuery

Question: Preciso do seguinte:
Tenho 3 campos de entrada para valores/moeda.
Esses valores não são preenchidos em sequência, outros campos, com outros valores são preenchidos entre esse 3 campos.
Preciso saber, como eu faço para que o resultado apareça, do cálculo desses 3 campos, somente quando os 3 valores forem preenchidos, ou seja, deixar a fórmula sempre "ativa", "ligada", para que a qualquer momento o resultado seja exibido, como uma célula do Excel.
Espero que a pergunta esteja clara.
Comment: Posta seu codigo ai
Answer: Você pode utilizar o .change para verificar quando estes campos estão sofrendo alrteração e apenas exibir o resultado em uma div ou um span quando os 3 possuirem algum valor.
Exemplo:

$(function() {
  $("#one, #two, #three").change(function() {
    if ($("#one").val() != "" && $("#two").val() != "" && $("#three").val() != "") {
        total = parseInt($("#one").val()) + parseInt($("#two").val()) + parseInt($("#three").val());
      $("#resultado").text(total);
    }
  });
});
#resultado {
  border: 1px solid;
  padding: 10px;
}

<input id="one" placeholder="Campo 1" type="number">

<input id="two" placeholder="Campo 2" type="number">

<input id="three" placeholder="Campo 3" type="number">

Comment: Beleza @Erlon Charles, vou tentar
Comment: Em partes deu certo, porém, o resultado apareceu "0", zero. Será que não é por estar convertendo os valores em int, parseInt, sendo que os valores estão em 0,00
Comment: eu não posso criar mais de uma function, como você me sugeriu para calcular outros valores em outras fórmulas?
Comment: Pra pegar casa decimais vc usa parseFloat()
Comment: Dentro do `If` que verifica se há conteúdo nos 3 inputs você pode colocar o que quizer, qualquer cálculo ou função
Answer: Assim:
HTML:
<input type="text" class="data_value">
<input type="text" class="data_value">
<input type="text" class="data_value">

jQuery:
$('.data_value').keyup(function() {
    calc()
});

function calc() {
   var sum = 0;
   $('.data_value').each(function() {
      if ($(this).val() != '') {
        $("#result").text(sum += +$(this).val())
      }
   });
}

EXEMPLO JSFIDDLE
Comment: Ele quer que atualiuze APENAS quando os 3 campos estiverem preenchidos
Comment: @Jefferson Alison, é que cada input que tenho, tem um id e no seu exemplo todos são a mesma class.
Como posso ajustar o seu código com os meus ids?
Comment: @GustavoSevero, fiz dessa forma pra ficar dinâmico. Você pode adicionar quantos input quiser. Se está usar o id, pode add o atributo normalmente no input ou você quer que realmente seja com ID?
Comment: @JeffersonAlison, eu costumo usar só id, mas posso usar os dois, juntos, em um input?
Comment: Outra coisa @JeffersonAlison, eu preciso que a entrada dos valores seja com "," e não ".", entende? É pra ser 1,11, por exemplo e não 1.11. E no seu exemplo só funciona se for 1.11. Sim, eu entendo que "," e JS é reconhecido como string, mas  então, preciso converter de "," para ".". Já tentei fazer isso, mas não deu certo.

Cálculo sempre ativo em JQuery


Repeaded measures for id, but id can never be in different subtypes, how to analyse difference between subtypes?

Question: In this example data I want to test if the variable "w" is different between subtypes. There are repeated measures for ids for each subtype, but the same id can never be found in different subtypes. How should it be analysed correctly? Does id have to be nested in subtype as a random factor, somehow? But can subtype also be a fixed factor? Highly appreciate guidance!
id <- c(1,1,1,2,3,4,5,5,5,6,7,8,8,8,9,9)
subtype <- c("A","A","A","C","B","A","C","C","C","B","A", "B", "B", "B", "A","A")
w<- sample(100,16)
df <- data.frame(id,subtype,w)
df
library(lme4)
library(car)
lm <- lmer(w~subtype+ (1|id), data=df)
Anova(lm, type=3)
summary(lm)
l <-emmeans(lm, "subtype")
pairs(l)

Comment: From the way the data are structured, id is implicitly nested in subtype because given id, there is only one subtype. The code you have produces a reasonable analysis.
Answer: All the alternatives that you mention are possible (except for the nesting one, see below). It all depends on your data. If you have some domain knowledge (i.e. some insight into the nature of the data) then you can use it to choose the right model, otherwise, you just have to try all the models and then compare them using some model selection method (lme4 provides e.g. AIC, BIC, ... for each fitted model).
Here is some intuition as to how to use domain knowledge:
Subtype as fixed or random effects? If you know that the subtypes are completely dissimilar from each other, and the $w$ values of one subtype give you absolutely no indication as to what the $w$ values of the other subtypes might be, then you would use subtypes as fixed effects, thus each subtype gets its own independent intercept. But if you would say that the subtypes do have some similarity and the $w$ values of one subtype do give you some indication as to what the $w$ values of the other subtypes might be, you should use random effects. Random effects models usually lead to the effects being similar to each other (at least when using the defaults as in lme4).
Ids as fixed or random effects? Here, the same applies as to subtypes.
Nesting id in subtype? Nesting would be useful if an id in one subtype would lead to different $w$ values than the same id in another subtype. But since each of your ids is always only appearing in a unique subtype, nesting is not appropriate.
In your example, subtype is a fixed effect, and id a random effect. Presuming that $w$-values for the same id are similar and that subtypes are also similar, I would suggest modelling both as random effects:
lm <- lmer(w ~ -1 + (1|subtype) + (1:id), data = df)

But, as mentioned above, trying alternative models and applying some model selection might be useful.
Comment: the subtypes should not have similarities, they are different. Then the model I have written seem to be correct, great!, thanks!!


Como interagir vários menu dropdown?

Question: Tenho dois menus, qual função fazer e como fazer, para quando abrir um, fechar o outro? E ao clicar fora do menu fechar também? Obrigado!
Meu código

function menu1() {
    document.getElementById('dropdown').classList.toggle('visivel')

  }

  function menu2() {
    document.getElementById('dropdown2').classList.toggle('visivel')

  }
.submenu {
    display: none;
}

.visivel {
    display: flex;
}
<!doctype html>

    <title>Title</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" type="text/css" href="estilo.css">

          <button onclick="menu1()">BOTAO</button>

conteudo1

conteudo2

conteudo3

conteudo4

conteudo5

          <button onclick="menu2()">BOTAO2</button>

conteudo1

conteudo2

conteudo3

conteudo4

conteudo5

Comment: Tentou? `function menu1() {
    document.getElementById('dropdown').classList.toggle('visivel'); document.getElementById('dropdown2').classList.toggle("submenu");

  }

  function menu2() {
    document.getElementById('dropdown2').classList.toggle('visivel'); document.getElementById("dropdown").classList.toggle("submenu");

  }`
Answer: Você poderia fazer uma query para selecionar todos os outros submenus e então remover a class visivel
// busca todos os elementos com a classe submenu, exceto o com ID dropdown2
for (var outroSubmenu of document.querySelectorAll('.submenu:not(#dropdown2)')) {
    outroSubmenu.classList.remove('visivel')
}

document.getElementById('dropdown2').classList.toggle('visivel')

Outra melhoria seria criar uma única função para manipular todos os submenus, e receber como parâmetro o id do elemento clicado:

function toggleMenu(id) {
    for (var outroSubmenu of document.querySelectorAll(`.submenu:not(#${id})`)) {
        outroSubmenu.classList.remove('visivel')
    }
    document.getElementById(id).classList.toggle('visivel')
}
.submenu {
    display: none;
}

.visivel {
    display: block;
}

button {
    display: block;
    margin-top: 10px
}
<!doctype html>

    <title>Title</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" type="text/css" href="estilo.css">

          <button onclick="toggleMenu('dropdown')">BOTAO</button>

conteudo1

conteudo2

conteudo3

conteudo4

conteudo5

          <button onclick="toggleMenu('dropdown2')">BOTAO2</button>

conteudo6

conteudo7

conteudo8

conteudo9

conteudo10

Comment: Amigo, e se fosse com 4 menus? a ideia eh a mesma?
Comment: Sim, como `querySelectorAll` busca todos os submenus, não importa que você tenha 2 ou 100 deles, contanto que eles tenham a classe `submenu`, todos eles serão "fechados".
Comment: Muito Obrigado pela sua explicação!
Answer: Há uma forma mais genérica de se fazer isso sem ter que criar uma função para cada botão e usar id's. Basta colocar uma classe nos botões a adicionar events handlers a todos. Ao clicar no botão irá buscar o elemento adjacente (que vem após) com .nextElementSibling.
Criar também um event handler para o document que irá ocultar todos os menus quando você clicar fora dele ou dos botões.
Veja abaixo como fica com comentários explicativos do que o código faz:

// pega todos os botões pela classe
const botoes = document.querySelectorAll(".botaomenu");

// cria um evento para o document
document.onclick = function(){
   // percorre todos os menus e remove a classe
   for(let menu of botoes){
      menu.nextElementSibling.classList.remove("visivel");
   }
}

// percorre todos os botões e cria os eventos
for(let menu of botoes){
   menu.onclick = function(e){
      e.stopPropagation(); // impede que o clique atinja o document
      let visivel = document.querySelector(".visivel"); // busca um menu visível
      // se houver um menu visivel, oculta ele desde que não seja o referente ao botão clicado
      if(visivel && visivel != e.target.nextElementSibling) visivel.classList.remove("visivel");
      // altera a classe
      this.nextElementSibling.classList.toggle('visivel');
   }
   // impede que o document seja atinjido ao clica dentro do menu
   menu.nextElementSibling.onclick = function(e){
      e.stopPropagation();
   }
}
.submenu {
    display: none;
}

.visivel {
    display: flex;
}
<button class="botaomenu">BOTAO</button>

conteudo1

conteudo2

conteudo3

conteudo4

conteudo5

<button class="botaomenu">BOTAO2</button>

conteudo122

conteudo2

conteudo32

conteudo42

conteudo52

Comment: Muito Obrigado professor pela sua explicação! Funcionou perfeito.

Como interagir vários menu dropdown?


Mixed model interaction (covariate+factor): How to interpret posthoc table output in R package phia?

Question: In R, using package lme4, I have used the following 2 mixed models to determine I have a signifacnt interaction between a covariate (continous, normally distributed) and a factor (three levels: herbivores, plants, predators):
test1 <- lmer( mode ~ sr * func.group + (1|community), data=nr.test, REML="FALSE")
test2 < -lmer( mode ~ sr + func.group + (1|community), data=nr.test, REML="FALSE")
anova(test1, test2)

Data: nr.test
Models:
test2: mode ~ sr + func.group + (1 | community)
test1: mode ~ sr * func.group + (1 | community)
     Df    AIC    BIC  logLik  Chisq Chi Df Pr(>Chisq)
nr.test2  6 77.458 82.093 -32.729
nr.test1  8 62.570 68.751 -23.285 18.887      2  7.919e-05 ***

I have obviously plotted the interaction for each level of factor, and all three levels are positive relationships which cross over each other (i.e. different levels of slope steepness).
However, I would like to be able to identify which level of the factor are significantly different from one another, and which are also significantly different from a slope value of zero (i.e. which slopes are significant).
I have installed the R package phia, and used the command
testInteractions(test1, pairwise="func.group", slope="sr")

and recieved the following output:
Adjusted slope for sr
Chisq Test:
P-value adjustment method: holm
                     Value Df   Chisq Pr(> Chisq)
    herbivore-plant 0.11878  1  4.3061     0.03798 *
 herbivore-predator 0.40567  1 65.3283   1.902e-15 ***
     plant-predator 0.28689  1 30.3474   7.224e-08 ***

It would appear for each level of factor the slopes are significantly different from one another, but how can I know which ones are significantly different from zero, and how would I report this?
Comment: As regards this code below which works well, may I ask you to exlain how it works? i.e. Does this compare one factor level (coded as "1") against the the other two factor levels (grouped by coding as "0")....  or does it instead run a signifcance test only on the slope classed as a "1" (and the "0" are ignored), so that in effect this code tests each slope independently (hence three slopes = 3 tests)?        Also, are the levels of factor organised alphabetically, so that the "1" in (1,0,0) refers to herbivore, while "1" in (0,0,1) refers to predator?
Answer:
how can I know which ones are significantly different from zero, and
  how would I report this?

To obtain the slope estimate and its statistical significance for each level of a factor, you can perform the following tests:
testInteractions(test1, custom=list(func.group=c(1,0,0)), slope="sr", adjustment="none")
testInteractions(test1, custom=list(func.group=c(0,1,0)), slope="sr", adjustment="none")
testInteractions(test1, custom=list(func.group=c(0,0,1)), slope="sr", adjustment="none")

You may report the results of the individual slopes the same way as the pairwise comparisons of slopes (e.g., tables).


Crash when open containing app from today extension

Question: I created today extension and add a button to open containing app. Inside extension view controller:
@IBAction func pressed() {
    extensionContext?.openURL(NSURL(string:"myApp://")!, completionHandler: nil)
}

So, I also add URL Scheme to containing app plist:
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>myApp</string>
        </array>
    </dict>
</array>

Widget works fine, but when I try to press widget my app crashes inside containing app AppDelegate.swift. Breakpoint inside application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) can't be reached.
Backtrace:
* thread #1: tid = 0x27fb0, 0x00000001861bd698 CoreFoundation`CFStringCreateCopy + 36, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x00000001861bd698 CoreFoundation`CFStringCreateCopy + 36
    frame #1: 0x00000001019f7954 libswiftFoundation.dylib`Foundation._convertNSStringToString (ObjectiveC.NSString) -> Swift.String + 152
    frame #2: 0x000000010030172c myApp`@objc myApp.AppDelegate.application (myApp.AppDelegate)(ObjectiveC.UIApplication, openURL : ObjectiveC.NSURL, sourceApplication : Swift.String, annotation : Swift.Optional<Swift.AnyObject>) -> Swift.Bool + 104 at AppDelegate.swift:0
    frame #3: 0x000000018ad172f0 UIKit`-[UIApplication _applicationOpenURL:payload:] + 216
    frame #4: 0x000000018ad1b4c8 UIKit`-[UIApplication _handleNonLaunchSpecificActions:forScene:withTransitionContext:] + 2420
    frame #5: 0x000000018ad1f810 UIKit`-[UIApplication _handleApplicationActivationWithScene:transitionContext:completion:] + 2220
    frame #6: 0x000000018ad1ecec UIKit`__88-[UIApplication _handleApplicationLifecycleEventWithScene:transitionContext:completion:]_block_invoke + 140
    frame #7: 0x000000018ad1ec44 UIKit`-[UIApplication _handleApplicationLifecycleEventWithScene:transitionContext:completion:] + 380
    frame #8: 0x000000018ad12578 UIKit`-[UIApplication scene:didUpdateWithDiff:transitionContext:completion:] + 512
    frame #9: 0x000000018e54562c FrontBoardServices`__31-[FBSSerialQueue performAsync:]_block_invoke + 28
    frame #10: 0x000000018628ea28 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 20
    frame #11: 0x000000018628db30 CoreFoundation`__CFRunLoopDoBlocks + 312
    frame #12: 0x000000018628c154 CoreFoundation`__CFRunLoopRun + 1756
    frame #13: 0x00000001861b90a4 CoreFoundation`CFRunLoopRunSpecific + 396
    frame #14: 0x000000018f35b5a4 GraphicsServices`GSEventRunModal + 168
    frame #15: 0x000000018aaee3c0 UIKit`UIApplicationMain + 1488
  * frame #16: 0x0000000100307df4 myApp`top_level_code + 76 at AppDelegate.swift:15
    frame #17: 0x0000000100307f0c myApp`main + 48 at AppDelegate.swift:0
    frame #18: 0x000000019709aa08 libdyld.dylib`start + 4

If I open myApp:// in Safari, app open correctly w/o crash.
Comment: Did you ever resolve this? I'm hitting a very similar problem.
Comment: I even open radar for Apple
Comment: Did you resolve this?
Answer: I ran into a very similar issue. I'd implemented application:openURL:sourceApplication:annotation: with this Swift code:
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {

But it turns out that sourceApplication should actually be optional:
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {

No idea how I got that wrong (I'm assuming Xcode autocomplete, but it seems to be doing the right thing now), but changing that fixed it for me.


Weird parameter in VB param ( , ) converting to C#

Question: I am trying to re-write some very old VB codes into C#.
There is a function as follows:
Function function1 (ByVal sp As String, Optional ByVal param(,) As Object = Nothing) As DataSet

And there is a comment:
//<param name="param">Parameters to pass to stored procedure</param>.

Can anyone let me know how to re-write param(,) into C#? Thanks!
Comment: when I see documentation it should be `Optional ByVal ParamArray param() As Object = Nothing` which its equivalent in c# is `params object[] param = null`
Comment: Thanks for the reply. But when I am looking at the legacy system, there is a comma ',' in the middle of the bracket - param(,). The codes is copied and pasted here directly from the system which is still fully functioning.
Comment: Do not use `ParamArray` - method expect 2-dimensional array as optional parameter
Answer: Function function1 (ByVal sp As String, Optional ByVal param(,) As Object = Nothing) As DataSet
End Function

converts to:
public DataSet function1(string sp, object[,] param = null)
{
}

http://converter.telerik.com/
Comment: Thanks! That's useful!
Answer: In vb.net you can use param as name for variable. Because vb.net use ParamArray as keyword for optional array of parameters - which equivalent to params in C#.
So in your case method just expect 2-dimensional optional argument.
Which can be converted in C# as
public DataSet function1(string sp, object[,] param = null)

Comment: Thanks Fabio!  Good to know the difference.


C# delegate Invalidcast Exception

Question: I am stuck with an InvalidCast Exception. I am calling a delegate to run some function. In the callback method of the delegate I am trying to get the return value of the function as shown below.
<code>     public delegate SyncHelper.SyncPlan RunJobDelegate();

     public static void SyncJobCallback(IAsyncResult result)
    {

        RunJobDelegate runSyncJob = (RunJobDelegate)result.AsyncState;
        SyncHelper.SyncPlan obj_Plan = runSyncJob.EndInvoke(result);
</code>
When RunJobDelegate runSyncJob = (RunJobDelegate)result.AsyncState; is called I am hitting an exception saying "Unable to cast object of type 'RunJobDelegate' to type 'RunJobDelegate'. "
Please help me with the solution if anyone has seen this before.
Divya.
Comment: Could you post the `BeginInvoke` code too?
Comment: Can you show more of the code? Specifically, how is the RunJobDelegate being initialized and started?
Comment: Possible duplicate to http://stackoverflow.com/questions/3895163/invalidcastexception-casting-object-to-its-own-type/3895578#3895578
Answer: This sort of thing should only ocurr if you have two different RunJobDelegate types defined in your code.  Make sure it isn't defined twice.
If that isn't the problem, please most more of the code (including the calling function) for us to examine.
Comment: Yes, You are right. I have declared the same type of delegate but in a different namespace in a different class. I have removed that and used the already existing one and my issue got resolved. But can you please tell me why that is an issue?
Comment: System.Data.Whatever is a totally different type than Your.Own.Namespace.Whatever.  Having the same "last name" doesn't make them the same type.  So, if you used the first type and tried to cast it to the second type, it would fail without a way to convert one to the other.
Answer: Did you check the type of result.AsyncState in the debugger?
also are you sure you want to use AsyncState and not AsyncDelegate?
Reference: http://msdn.microsoft.com/en-us/library/system.iasyncresult.asyncstate.aspx

C# delegate Invalidcast Exception


How to hide My results tab for the User using Quiz module in Drupal 7

Question: It looks so silly to ask these questions but I'm beginner in drupal. I need a help on implementing the modules. I'm trying to build a portal using Quiz Module wherein I need to hide a tab for the user but should be visible to administrator.
Is it possible to hide the My results tab in drupal 7? If so how?
Answer: You can use Tab Tamer module.
Project page says:

Tab Tamer is an administration utility that provides easy re-ordering,
hiding, and deactivation of tabs and subtabs.

For more information go through the module documentation.
Answer: Just go to modules->quiz core module and in configuration/permission uncheck view own result. That is it. If you want to re-enable it, just check it