Colocar um nome dependendo do numero do array

Question: Imaginemos que tenho 4 variavéis:

 - Porto = 1
 - Benfica = 2
 - Sporting = 3
 - Braga = 4

Tenho este código que me faz um shuffle de números de um array denominado por "arr".
Integer[] arr = {1,2,3,4};
    Collections.shuffle(Arrays.asList(arr));

     for (int i = 0; i < arr.length; i++) {

        }
        Collections.shuffle(Arrays.asList(arr));

Ao executar o programa imaginemos que obtive o resultado : [1, 3, 2, 4];
Agora que tenho este resultado tenho 4 labels (equipa1, equipa2, equipa3, equipa4);
Quero colocar na label "equipa1" o 1 resultado do array e colocar o nome da equipa correspondente a esse numero neste caso PORTO.
Outro exemplo..
Quero colocar na label "equipa2" o 2 resultado do array, que é 3, então quero colocar nessa label a equipa corresponde ao numero 3, neste caso Sporting..
Podem me explicar como posso fazer isto ?
Para executar o programa tem o código aqui abaixo:
public class J2 extends JFrame {
    private JPanel contentPane;
    JLabel equipa1 = new JLabel("");
    JLabel equipa2 = new JLabel("");
    JLabel equipa3 = new JLabel("");
    JLabel equipa4 = new JLabel("");

    public void func(){

        int Porto = 1;
        int Benfica = 2;
        int Sporting = 3;
        int SCVitoria = 4;

        Integer[] arr = {1,2,3,4};
        Collections.shuffle(Arrays.asList(arr));

         for (int i = 0; i < arr.length; i++) {

            }
            Collections.shuffle(Arrays.asList(arr));

            System.out.println(Arrays.toString(arr));

    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    J2 frame = new J2();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public J2() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 553, 405);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblJornada = new JLabel("Jornada 1");
        lblJornada.setBounds(61, 11, 80, 14);
        contentPane.add(lblJornada);

        JButton btnNewButton = new JButton("Gerar Jornada");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

             func();
            }
        });
        btnNewButton.setBounds(125, 139, 139, 23);
        contentPane.add(btnNewButton);

        equipa1.setHorizontalAlignment(SwingConstants.CENTER);
        equipa1.setBounds(20, 36, 139, 14);
        contentPane.add(equipa1);

        equipa2.setHorizontalAlignment(SwingConstants.CENTER);
        equipa2.setBounds(169, 36, 139, 14);
        contentPane.add(equipa2);

        equipa3.setHorizontalAlignment(SwingConstants.CENTER);
        equipa3.setBounds(20, 86, 139, 14);
        contentPane.add(equipa3);

        equipa4.setHorizontalAlignment(SwingConstants.CENTER);
        equipa4.setBounds(169, 86, 139, 14);
        contentPane.add(equipa4);

    }

}

Comment: Label? É interface gráfica? Se sim, você precisa fornecer um **[mcve]** da sua interface para que seja possivel executar o código.
Comment: `Quero colocar na label "equipa2" o 2 resultado do array, que é 3, então quero colocar nessa label a equipa corresponde ao numero 3, neste caso Sporting..` - isso divergiu completamente do resto da pergunta. Se Sporting é 3 , porque ele deveria estar em equipa2?
Comment: Já forneci o código completo. Ele deveria estar na equipa2 porque o sorteio do array é aleatório.
Answer: Uma solução seria você fazer um array com o nome das equipes;
String [] nomes_equipes = {"Porto","Benfica","Sporting","Braga"};

então, basta acessar a posição (equipe)  do array de nomes ex:
se vc acessar a label "equipa2" o 2 resultado do array, que é 3 e por o nome basta fazer:
nomes_equipes[arr[2]]

Ele vai acessar a posição 2 do array (que o valor é 3) e a posissão 3 do nomes_equipes (Sporting)
Answer: Para facilitar a distribuição, crie um array de JLabel com o mesmo número de índices do seu array de times, e distribua os times após o shuffle conforme abaixo:
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Collections;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

public class J2 extends JFrame {

    private JPanel contentPane;
    private JLabel[] equipas = new JLabel[4];

    public void func() {

        int Porto = 1;
        int Benfica = 2;
        int Sporting = 3;
        int SCVitoria = 4;

        Integer[] arr = { 1, 2, 3, 4 };

        Collections.shuffle(Arrays.asList(arr));

        for (int i = 0; i < arr.length; i++) {
            equipas[i].setText(String.valueOf(arr[i]));
        }

        System.out.println(Arrays.toString(arr));
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new J2().setVisible(true));
    }

    public J2() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 553, 405);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblJornada = new JLabel("Jornada 1");
        lblJornada.setBounds(61, 11, 80, 14);
        contentPane.add(lblJornada);

        JButton btnNewButton = new JButton("Gerar Jornada");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                func();
            }
        });
        btnNewButton.setBounds(125, 139, 139, 23);
        contentPane.add(btnNewButton);

        JPanel equipaPanel = new JPanel(new GridLayout(2,2));

        for(int i = 0; i < equipas.length; i++) {
            equipas[i] =  new JLabel();
            equipas[i].setHorizontalAlignment(SwingConstants.CENTER);
            equipaPanel.add(equipas[i]);
        }

        equipaPanel.setBounds(20, 36, 149, 50);
        contentPane.add(equipaPanel);

    }
}

Veja funcionando:

Vale ressaltar a recomendação abaixo:

Evite usar layout absoluto, a não ser que seja de extrema necessidade e que saiba as consequências disso, pois layout absoluto dificulta manutenção da tela e faz com que sua aplicação fique com aparência diferente dependendo do monitor e resolução que estiver sendo executada.
Existem vários gerenciadores de layouts para que você não tenha que se preocupar com posicionamento ou organização manual de componentes. Sem contar que o uso de layouts faz com que seu código fique mais fácil de dar manutenção do que ficar inserindo um monte de setbounds, e caso precise alterar a posição de algum componente, no layout absoluto, vai ter que reposicionar todos manualmente.

Para distribuir os pontos do resultado, eu utilizei GridLayout, que te dá liberdade de organizar itens em um layout de grids(parecido com o excel), e como se trata de 4 JLabels em forma quadrática, ele foi a melhor e mais simples opção para o caso.
Quanto ao layout absoluto do painel principal, eu não removi pois teria que reescrever sua tela. Mas fica a recomendação acima.
Comment: Sim sei que vai estourar mas pode exemplificar essa parte de definir a JLabel ?
Comment: @RicardoLopes `labels[indice] = new JLabel();` você pode fazer isso dentro de um laço, e ir posicionando ele na sua tela.
Comment: Peço desculpa mas continuo não entendendo como fazer..
Comment: Pode exemplificar melhor ?
Comment: @RicardoLopes veja a edição.
Comment: Entendo sua recomendação, meu professor só me ensinou na escola como funcionar com layout absoluto e já tentei usar outros e penso que seja demasiado difícil recomenda algum tutorial ?
Comment: @RicardoLopes executou o código da minha resposta? Ele já está funcional. E sobre links, veja a recomendação na resposta, há links da documentação oficial ensinando a mexer em cada um.
Comment: Sim executei o código e está funcional perfeitamente com o que era pretendido.


Exclude Debit Transactions

Question: I have a need to select records from transactions table excluding certain transactions.
Bellow is a sample output of my tables.
TB_ACCOUNTS
CUSTCD  ACCTNO  PRDCD
100     10001   SATF
100     10002   SATF
200     10003   CUS

TB_TRANSACTIONS
TXNNO   TXDATE      ACCTNO  CUSTOMER_NO TXAMT   CASHFLOWTYPE
TX1     18-Jul-16   10001   100         5000    CR
TX2     18-Jul-16   10002   100         5000    DR
TX3     18-Jul-16   10003   200         3000    DR
TX4     18-Jul-16   10001   100         3000    CR

I want to select credit transactions where PRDCD is 'SATF' and exclude transfers between own accounts. For example customer 100 PRDCD is SATF and has two accounts. I want my select query to exclude credit transaction of amount 5000 because the debit account also belongs to the same customer. But include credit transaction of 3000 amount because the debit account is of different customer and type is not SATF.
So far I got bellow query but the output I'm getting is completely wrong.
select * from TB_TRANSACTIONS AB inner join TB_ACCOUNTS AC
on AB.ACCTNO=AC.ACCTNO
where AB.CASHFLOWTYPE='CR'
and AC.PRDCD='SATF'
and AB.TXNNO=
(select TXNNO from TB_TRANSACTIONS A, TB_ACCOUNTS B
where A.ACCTNO=B.ACCTNO
and A.TXAMT=AB.TXAMT
and A.CASHFLOWTYPE='DR'
and B.PRDCD=AC.PRDCD)

How to achieve the desired result?
Comment: It would be simple if in your example transactions were numbered TX1, TX1, TX2, TX2. Otherwise how do we know that the first two lines belong to the same transaction and next two to second transaction? Using `txamt` to join rows seems to be suspicious.
Comment: is there a way to relate a given CR trx with its correspondent DR trx?
Comment: @ Ponder Stibbons: TXNNO is not duplicated, it has a unique number, this is where I'm also stuck at
Comment: @ Ricardo Arnold: The only possible way I found was through the amount, otherwise it's not straight forward to relate the DR & CR
Answer: You could use something like here:
select txnno, txdate, acctno, customer_no, txamt, cashflowtype, prdcd
  from (
    select t.*, a.prdcd,
           count(distinct customer_no) over (partition by txdate, txamt) cnt
      from tb_transactions t join tb_accounts a on t.acctno = a.acctno )
  where cnt = 2 and cashflowtype = 'CR' and prdcd = 'SATF'

Here I assumed that txamt is unique for each date. I strongly suspect that this may be wrong assuption so be warned.
But there is nothing except this column that tells us that two rows belongs to the same operation.
In first query I used count() in analytic version. There are also possible other solutions, for instance (not) exists:
select *
  from tb_transactions t join tb_accounts a on t.acctno = a.acctno
  where
    not exists (
      select 1 from tb_transactions tt join tb_accounts ta on tt.acctno = ta.acctno
        where tt.txdate = t.txdate and tt.txamt = t.txamt
          and tt.cashflowtype = 'DR' and tt.customer_no = t.customer_no)
    and cashflowtype = 'CR' and prdcd = 'SATF'

(sorry for any language mistakes)

Exclude Debit Transactions


Real Analysis Limit of a Sequence Question

Question: I'm working on this question (from an introductory Real Analysis textbook):

Define a sequence $(a_n)^{\infty}_{n=1}$ such that $\lim_{n \to \infty} a_{n^2}$ exists but $\lim_{n \to \infty} a_n$ does not exist.

I've come up with a sequence for which this holds.
Define
$$
a_n =
\left\{\begin{matrix}
0 \; \; \;  \text{if} \; \;  \sqrt{n} \in \mathbb{I}\\
1 \; \; \;  \text{if} \; \;  \sqrt{n} \notin \mathbb{I}
\end{matrix}\right.
$$
where $n \geq 1$ and $n \in \mathbb{I}$. This sequence does not converge, as $(a_n)$ flips between $0$ and $1$, depending on whether or not $\sqrt{n}$ is an integer. However, for $(a_{n^2})$, we have,
$$
a_{n^2} =
\left\{\begin{matrix}
0 \; \; \;  \text{if} \; \;  \sqrt{n^2} \in \mathbb{I}\\
1 \; \; \;  \text{if} \; \;  \sqrt{n^2} \notin \mathbb{I}
\end{matrix}\right.
$$
$$
 =
\left\{\begin{matrix}
0 \; \; \;  \text{if} \; \;  n \in \mathbb{I}\\
1 \; \; \;  \text{if} \; \;  n \notin \mathbb{I}
\end{matrix}\right.
$$
which of course is simply a sequence of zeros and as such "converges" to zero. Have I taken the right approach? Or should I be using the limit definition to define a more general sequence for which the given conditions hold. Thanks for any input.
Comment: Looks good to me. The question asks for a sequence and you've found one. If you want to improve your answer, you can rigorously show that $a_n$ diverges.
Comment: Too many symbols. Before typing all those symbols, you had an informal idea and knew that it worked: $f(k)=1$ if $k$ is a perfect square, and $fk)=0$ otherwise. Say it that way.
Answer: Yeah it works but you could express it simplier with
$$a_n = \left\{ \begin{array}{rl}
1 & \exists k \in \mathbb{N} : k^2=n \\
0 & \text{else} \end{array}\right.$$
Answer: Your answer is correct and convincing: you needed only to "find" such a sequence, and indeed you did.  I'd simply add that to make the argument fully convincing (or, perhaps more rigorous, as it seems pretty convincing to me), it might be a good idea to demonstrate that it is, indeed, an example of such a sequence (i.e., explicitly prove that indeed, $\;\large a_{n^2}\;$ converges to 0).


Given $\epsilon > 0$, show that the unit disc contains finitely many dyadic squares whose total area exceeds $\pi - \epsilon$

Question: I found this question here. The answer here is obviously not the answer I need. The question is:

Given $\epsilon > 0$, show that the unit disc contains finitely many dyadic squares whose total area exceeds $\pi - \epsilon$, and which intersect each other only along their boundaries.

I tried to solve it but a misunderstanding still remains.
My solution:
First I put the center of disc at the origin of Cartesian coordinates. Then I tile the number plane with dyadic squares each of side length $2^{-n}$. Now I need to come up with a formula that gives "an upper bound for the total area inside the disc that is not covered by a square and lies entirely within the disc". I came up with the formula by chatting with a friend online:

His key insight: The greatest possible distance between any two points in small square is its hypotenuse which is $\dfrac{\sqrt{2}}{2^n}$
Therefore draw a concentric circle of radius $1-\dfrac{\sqrt{2}}{2^n}$ inside the unit disc. Then any point on any square that "lies both inside and outside the disc" will always be outside the inner concentric circle.

Then it can be easily shown that the area between two concentric circles is:
$$\dfrac{2 \sqrt{2}}{2^n}- \dfrac{2 \pi}{2^{2n}}$$
This is "an upper bound for the total area inside the disc that is not covered by a square and lies entirely within the disc". This also is a decreasing function of $n$ whose limit goes to zero when $n \rightarrow \infty$.
Thus the total area "inside the disc that is not covered by a square and lies entirely within the disc" goes to zero when $n \rightarrow \infty$.
Thus the result of theorem follows.
My confusion:
Why is the bold sentence in "His key insight" true?
Comment: You can write out everything in a set theoretic fashion; I guess that should help; you can write $B(0,1):= \{(x,y): x^2 + y^2 \leq 1\}$ to denote the ball with the interior with radius $1$, maybe that will convince you
Answer: Let $S$ be a square with side length $2^{-n}$ that "lies both inside and outside the disc." Then there is a point $a \in S$ with $\Vert a\Vert > 1$.
For all $b \in S$ is (using the triangle inequality)
$$
 \Vert b \Vert  = \Vert a - (a-b)\Vert
\ge \underbrace{\Vert a \Vert}_{> 1}
- \underbrace{\Vert a-b\Vert}_{\le \sqrt 2/2^n}
 > 1 - \frac{\sqrt{2}}{2^n}
$$
and that proves that $S$ is outside the inner circle.


Relation between SVD and affine transformations (2D)

Question: I am trying to decompose affine transformations in elementary operations (rotation, scaling, shear), leaving translation aside for the moment, and in particular, to understand the relation of affine transformations with the singular value decomposition (SVD). I am focusing on the two dimensional case.
$$M = U \Sigma V^t$$
There are already a number of questions asking about this, none of them with a general, definitive answer:

Decomposing an Affine transformation (non-general answer, only specific chain of operations)
extracting rotation, scale values from 2d transformation matrix (non-definitive answer, see discussion)
Given this transformation matrix, how do I decompose it into translation, rotation and scale matrices? (does not explain how to pad the problem to 4 dimensions, incorrect in the presence of shear, see discussion)
Why can any affine transformaton be constructed from a sequence of rotations, translations, and scalings? (accepted answer omits the explanation about singular value decomposition, second answer mentions "trivial" details that have to be polished but does not address them)

In particular, I observed, but could not prove, that

The singular values of an affine transformation matrix are the absolute values of the scaling parameters.
The SVD of a transformation consisting in a uniform scaling and a proper rotation didn't reconstruct the original matrices, but introduced two improper rotations (i.e., determinant = -1).
Nonetheless, the multiplication of these two improper rotations yielded the original rotation. Perhaps because the transformation is conformal?

In Python code:
<code>In [66]: rot
Out[66]:
array([[ 0.8660254, -0.5      ],
       [ 0.5      ,  0.8660254]])

In [67]: sc
Out[67]:
array([[ 2.,  0.],
       [ 0.,  2.]])

In [68]: svd(rot @ sc)
Out[68]:
(array([[-0.8660254, -0.5      ],
        [-0.5      ,  0.8660254]]), array([ 2.,  2.]), array([[-1., -0.],
        [ 0.,  1.]]))

In [69]: det(_68[0])
Out[69]: -1.0000000000000002

In [70]: _68[0] @ _68[2]
Out[70]:
array([[ 0.8660254, -0.5      ],
       [ 0.5      ,  0.8660254]])
</code>
Under which assumptions can we perform this decomposition or does it make sense? Is there any proof that the singular values are the sorted absolute scaling factors? Is there a decomposition that is robust against reflection (i.e. improper transformations)?
Comment: Can you define precisely what you mean by "the scaling parameters"/"scaling factors"?
Answer: What do you mean by "improper rotations"? An orthogonal transformation with a reflection (i.e. determinant -1)? This would appear to be a non-uniqueness problem and could be fixed by flipping the sign of an arbitrary (but same index) column of $U$ and $V$, which would still be a valid SVD.
Comment: Thanks for your comment, but the "obviously" part is precisely what I am trying to address.
Comment: Yes, I mean determinant -1. I clarified that in the question.
Comment: @astrojuanlu: Ok, then just multiply the first (say) column of U and V by -1 each. Since $\det \Sigma>0$ by definition, and provided that $\det M>0$, $\det U$ and $\det V$ will always either be both +1 or -1, so you can "fix" your SVD such that U and V are proper rotations. Diagonal elements of $\Sigma$ are obviously scaling factors, with one rotation applied before and one after the scaling.


Magento - Need to bypass built-in custom options system and populate custom options from an external PHTML file

Question: The company I work for is currently in the process of moving over our site from a full HTML site with no CMS to Magento. Our products are very customizable and a lot of the options that are available are dependent on each other. I also have our menu system (and how it appears) dependent on the currently-selected product options. This being said, Magento's custom options system does not (out of the box) allow for the customization I need to make the product's options menu work the way I need. Instead of trying to re-invent the Magento wheel, I figured the easiest way to do this would be to have the item pull the custom options from a PHTML file. This way I can specify which options to pull based on the product type (an attribute). I was able to get that part working fine. The issues I am having are as follows:

price will not update when options are selected
options are not sent to cart when i add to cart

How can I bypass Magento's built-in custom options system and still have my custom options (from the phtml file) send to the cart when you add along with changing the price? Hope I was clear. Let me know if I need to clarify anything. Thanks in advance.
Answer: You need to copy the data from the app/design/frontend/base/default/template/catalog/product/view/options.phtml file so that Magento dynamically pulls the pricing and custom option data that will be present on the product page.
You will include all scripting (between the script tags), and be sure the custom options are between the dl tags unless you're using completely custom CSS work.
Exclude all PHP language from the options.phtml file if you're going to dump the options directly into a phtml file.
This allows the pricing to dynamically update with the selections made and allows the custom options to be added to the cart.


Hausdorff measure of unit ball is bounded

Question: In my course we defined the Hausdorff meaure as follows:
$$
\begin{align*}
    \mathcal{H}_\delta^d(A)=\inf \left\{\sum_{k = 1}^{\infty } r_k^d\ \middle|\  A \subseteq \bigcup_{k \in I} B\!\left(x_k, r_k\right), 0<r_k<\delta\right\}, \quad
    \mathcal{H}_{ }^{ d}\!\left( A\right)
    = \lim_{\delta  \to 0} \mathcal{H}_{ \delta }^{ d}\!\left( A\right) .
\end{align*}
$$
Now I want to show that $\mathcal{H}_{ }^{ n}\!\left( [ 0, 1] ^{n}\right) < + \infty $ and came up with the following:
Fix any $\delta > 0$. We can cover $[ 0, 1] ^{n}$ by means of rectangles with side lengths $\sqrt{ 2} \delta  $.
Writing $m:= \left\lceil ( \sqrt{ 2} \delta ) ^{-1}\right\rceil $ we obtain
$$
\begin{align*}
[ 0, 1] ^{n} \subset \bigcup_{k _{ 1} = 0}^{m -1} \cdots \bigcup_{k _{ m} = 0}^{m - 1} [k _{ 1}\sqrt{2}\delta , ( k _{ 1} + 1) \sqrt{2}\delta ] \times \cdots \times [ k _{ m}\sqrt{2}\delta ,
( k _{ m } + 1) \sqrt{2}\delta ]
.\end{align*}
$$
Now, each of these rectangles can in turn be covered by balls of radius $\delta $ (for every rectangle we take one of these balls). This gives us
$$
\begin{align*}
\mathcal{H}_{ \delta }^{ d}\!\left( A\right) \le  m ^{n} \delta ^{n} \le 2^{n / 2}< +\infty
\implies \mathcal{H}_{ }^{ d}\!\left( A\right) < +\infty
.\end{align*}
$$
My question: Is there a simpler way to show this?
Comment: I would say this is as simple as it can get, but I may have seen too much of that kind of stuff to have an unbiased opinion.
Answer: Your argument just boils down to subdividing $[0,1]^n$ into sufficiently small boxes and covering each with a small ball, which in my opinion is probably the most straightforward and intuitive way to approach the problem, and your argument is still very short and simple.
The only "simpler" proof I can think of is to simply use the fact that $\mathcal{H}^n=\omega_n\mathcal{L}_n$ for some $\omega_n>0$, where $\mathcal{L}_n$ is the Lebesgue measure on $\mathbb{R}^n$. Then it is as simple as noting that
$$\mathcal{H}^n([0,1]^n)=\omega_n\mathcal{L}_n([0,1]^n)=\omega_n<\infty.$$
This does, however, require a bit more work in that you need to prove the above equality first, and so you don't get a short and simple proof from just the definition using this approach.


Searching a string inside an array of two Hashes

Question: I wrote the following:
Tab = [{"quiche"=>{"pepper"=>"10gr","cheeze"=>"50gr"}},{"pizza"=>{"tomato"=>"80gr","cheese"=>"100gr"}}]

which is an array of two hashes, each of which contains a hash. I want to know if there is a pizza recipe in the array. The only thing I found was to do so:
Tab.each {|meal| meal.each{|key,val| puts key}}
quiche
pizza

Then I can make a test to know if the key is the value I'm looking for. But I'm pretty sure this is a dirty way of doing it.
I tried to apply some methods like: Tab.include?("pizza"), but it returns false every time because it is looking into the two elements inside Tab:
{"quiche"=>{"pepper"=>"10gr", "cheeze"=>"50gr"}}
{"pizza"=>{"tomato"=>"80gr", "cheese"=>"100gr"}}

and {"quiche"=>{"pepper"=>"10gr", "cheeze"=>"50gr"}} is not "quiche". Someone help me, please. I can't find any solution.
Answer: In the ruby docs the very useful things for this problem are listed in the Enumerable class.  Depending on how strict you want to be about finding it you have a few options, but
Tab.any?{|recipe| recipe.keys.include?("pizza")}

should work.
Comment: Hi James, thank you for your quick answer. I'm going to check this right now.

Ps: I don't know why, I can't add any hello all! at the begining of my topic.. it disappears everytime I edit! ..
Comment: Yes it perfectly does what I am looking for... I'm so ashamed it is so simple.. I tried so many things much more complicated... Well thanks a lot and sorry for this dumb question! :) Have a nice evening.
Comment: @Oulanos Greetings are automatically removed.  http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts/93989#93989
Comment: Nice; there are so many ways to do things in Ruby!  I used Tab.select{|recipe| recipe.include? "pizza"}  This returns all of the matches as a new array.  If you just want a found/not found answer though James' answer is simpler.
Comment: Yes that was the purpose of my tests. But I also take your answer for some other purposes :) thanks @bigtunacan
Comment: @ShawnBalestracci How is mine? :)
Answer: You can take a look at the methods - Hash#assoc or Hash#has_key?
Tab = [{"quiche"=>{"pepper"=>"10gr","cheeze"=>"50gr"}},{"pizza"=>{"tomato"=>"80gr","cheese"=>"100gr"}}]

Tab.any? {|h| h.assoc("pizza") } #=> true
Tab.any? {|h| h.has_key?("pizza") } #=> true

Comment: `has_key?` is nice.  I often find myself using `keys.include?` and should switch.   Since you're just throwing away the key and value assoc doesn't make sense here.  `Tab.any? {|h| h["pizza"]}` seems better, but I suppose it depends on how one wants to handle nil or false values.


How to get absolute path to website

Question: My website is on a shared server. Having DNS issues, this seems to be the only way. I need to get the real and absolute path to my website like 126.96.36.199/~mywebscom without asking the support is this possible?  With the IP address and path.
Comment: That IP address you've provided looks like a home machine. The answers on this question are generic because you do not specify the server software. What details do you already have (a domain name?) If your shared host frequently changes IP addresses, you should consider moving to a more reliable host.
Comment: Its apache. The IP address above is just a sample.
Comment: Operating System? If possible, mention the hoster name.
Comment: Can you clarify a bit more. WHat are you trying to achieve. If you are looking for hostname to ip traslation for the url, then nslookup in windows would tell you the name it could find for the ip. The ~ specifies the userdir. See the httpd.conf or one of included .conf for userdir directive is included.
Comment: This depends on how the actual server is configured. It sounds like you want to access your site via IP. If your using a hosting company the is very unlikely. Unless you have a dedicated IP, there is probably only a 404 or a redirect site waiting. What's the actual problem your trying to fix? if it's code, then it may be a 'relative' problem, maybe hard coded variables that don't work as expected. Or your 'environment' hasn't been made 100% clear to you. Add a comment and let us help.
Answer: If your server has PHP installed (usually all apachie servers now are php enabled) this simple PHP script will return the absolute path wherever you will place it:
<?php
echo getcwd(); // Short for `Get Current Working Directory`
?>

Just save this on a file curdir.php and run it via URL for example www.example.com/curdir.php
There are also options to retrive the IP Address, Server Name etc... with $_SERVER variable
<?php
echo $_SERVER['SERVER_ADDR']; // The IP address of the server under which the current script is executing.
echo $_SERVER['SERVER_NAME']; //Gets the server name
?>

You can see full listing of this variable and find almost everything about the server where your website is here:
http://php.net/manual/en/reserved.variables.server.php
Answer: Define "absolute path". Absolute file path on the webserver? Likely /home/mywebscom/public_html.
If you meant URL, there is no definite URL for all servers, but if userdirs are enabled, you can access the website using http://ip.ad.dr.ess/~username. To retrieve the IP address, you should look in the documentation of your webhost. The IP is unlikely to change, but in the event of an IP change of the server your website is put on, you can get the IP by running:
host the-server-on-which-your-site-is-hosted.example.com

Answer: For the time being you can add an entry to your hosts file but you should really be working on the DNS. I don't understand how you think the path to your website is related to your DNS not resolving or how knowing it is going to help.
Comment: Your local hosts file. Add an entry for mydomain.com with your IP and it will work the same as if DNS was working correctly. But only on that machine.
Comment: I assume he means that he can't access it by going to the IP, which makes perfect sense if it's a Virtual Host redirecting based on URL. If he gets the absolute path he can just browse to it using that.
Comment: I don't own the server. I'm a client of a webhosting agency. I have no rights to the host files.
Answer: Web servers use "Host" header of requests to detect virtualhosts. So probably there isn't any path like http://ip.ad.dr.ss/~yoursite.
You can add your ip address and domain to hosts file of your system and connect server using your domain. So web server will serve your virtualhost instead of default virtualhost.
You can add a newline to hosts file contains ip address and domain as space seperated.
e.g
18.104.22.168 mydomain.com www.mydomain.com
Answer: Copy and paste this into a .php file (path.php or something) and upload it to your server. Call it in a browser; such as http://www.yourdomainname.com/path.php et voila, your absolute path:
<?php
$path = getcwd();
echo "This Is Your Absolute Path: ";
echo $path;
?>

Comment: I don't think that he asked for this kind of "absolute path"

How to get absolute path to website


"Twig_Error_Loader: Template "file.html.twig" is not defined" for new twig template file

Question: After creating a new paragraph type and its template file in the correct folder location, I am receiving the following error every time I view the page with that houses the new paragraph type.
Twig_Error_Loader: Template "file.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "file.html.twig" in the Drupal theme registry.)
I have followed the steps here to disable the cache. However I don't believe it worked because I still have to clear my cache through config>performance for changes to twig files to appear.
Similarly, I tried to enable twig debugging (and turn off caching) here and can not confirm that it has been enabled either.
I found an article: blog.wturrell.co.uk/troubleshooting-drupalcoretemplateloaderthemeregistryloader-unable-to-find-template/ discussing potentially clearing the theme-registry, but I do not have access to drush to run any commands.
I have already tried clearing all the cache from within drupal itself.
Answer: Cache is a pretty broad concept, and sometimes mean content caching and sometimes they mean broader things like config settings and the theme registry.  Disabling content caching is still a bit confusing to me so I can't help with that part of the question.
But the theme registry has some pretty simple rules.  If you add new template file (or change it's name or move it to a different folder) or if you add a new theme callback (in hook_theme) or override to a theme callback (hook_preprocess...) then you MUST clear the theme registry before they will be active.  To do that, the simplest method (without additional modules or drush) is to 'Clear all caches' under admin->config->development->performance.
Of note, sometimes the theme registry is referred to as the theme cache.  While I know it's probably possible, I don't think that disabling the theme registry from caching is a standard practice in development.


Twilio Call back user when their next in queue

Question: I'm familiar with Twilio's enqueue and queue functionality where we put a caller into a queue and when they are the next person in line we connect them to an agent. Pretty straight forward.
I'd like to have an option where the system can call the caller back when they are next in line. So if there are 20 people ahead of them they don't have to sit in queue listening to horrible hold music.
If I put a user in a queue and disconnect them they are removed from the queue. Any suggestions on how to do this?
Answer: Twilio developer evangelist here.
The Twilio Queue is for people who remain on the line, so that's not going to work for you in this case.
What you'd want to do is maintain your own queue of callbacks to be made within a database in your application. You can store the time added to the queue with the number to call. Then when you have an available agent, sort the queue by time added, pick the oldest call and generate a call to the agent and then to the waiting user using the REST API.
Does that help at all?


How to load past comments properly?

Question: I am currently trying to do a load previous comments function. I am using ajax and i have problems trying to make the onClick event to work. Any ideas?
Html Code:

    Load older chats...

Loading...

Scripts:
function getMessages(){
    $("#workroom_boxes_chatpast").html('  Loading...');

    $.ajax({
        url: "/recent/messages/{{ chat.key.id }}",
        cache: false,
        success: function(html){
            $("#chatcontent").html(html);
            $("#workroom_boxes_chatpast").hide();
        }
    });

    setTimeout('getMessages()', 4000);
});

Comment: http://jsfiddle.net/LekisS/WX4VG/1/ :)
Comment: you should use the jQuery click trigger rather than inline javascript.
Comment: @Lekis can you give me an example on jsfiddle.net?
Comment: @lekis is there a explanation why my method does not work and using your click trigger is better way of using? i realise i cannot do a setTimeout now using your method because i need to give this function a name in order to execute
Comment: Where is loaded your "getMessages" function ? It shouldn't be wrapped by any $(function()) or anything similar :). Otherwise it should be working
Answer: Just a shot in the dark, but change the $("#chatcontent").html(html); to  $("#chatcontent").html(html.d);
Comment: MS returns a response in a `d` property: http://www.codeproject.com/KB/aspnet/Parsing-ClientScript-JSON.aspx
Comment: As Jakub said... Your question didn't give too many details as to what problems you're having (specifically), so it's really a guess as to what might be wrong.
Comment: @Farlig i am pretty sure my backend servers are working. When i Click the ahref, nothing happens- the page stays as it is..so i guess the loading is not working
Comment: @Farlig i managed to get it work using Lekis' solution which choose a click trigger instead of triggering through my current method. Is there a reason why people would want to choose my method to execute instead of using click function?
Comment: The way LekisS' solution works is by unobtrusively adding behavior to the page, which is the preferred way of adding behavior to page elements. Adding the behavior is dependent on JavaScript being enabled on the page, which it should be, considering the event handler it self IS JavaScript... Read up a bit on it.
Answer: getMessages function doesn't return anything so do not write return getMessages() in onclick. You might want to write:
onclick="getMessages(); return false;"

to prevent jumping in some browsers.
Answer: var status="notloaded";

function getMessages(){

    $('#loading').hide();

    if(status == "notloaded")
    {
        var myurl = "/recent/messages/id/10/status/notloaded"
        /**
        load older message
        **/
        status = "loaded"
    }
    else{
        var myurl = "/recent/messages/id/10/status/loaded"
        /**
        do not load older message
        **/
    }

    $.ajax({
        url: myurl,
        /**
        Load new message
        **/
        cache: false,
        success: function(html){

            $('#loading').hide();
            $("#workroom_boxes_chatpast").hide();

        }
    });

    setTimeout('getMessages()', 4000);
});

How to load past comments properly?


Build a born-again tree from XGboost set of trees

Question: I am wondering whether an approach like what is described here: https://github.com/vidalt/BA-Trees for building a single tree from a Random Forest can be applied to an XGBoost model? Is there a library that already does this?
Answer: I'm not very familiar with the paper in question, but a skimming suggests that it isn't particularly different for gradient boosted trees or random forests.  What matters is that the tree ensemble is constant on what the paper calls cells, the partition of space by the tree splitting hyperplanes (fully extended, so a refinement of the partition of space into the constant-prediction regions).  Those are the same for random forests and gradient boosted trees, the only difference is that the predicted value is aggregated differently in each of those cells.
I have no idea if this is implemented anywhere; I would guess the repository you've linked could be modified very slightly to make it work.  You'd need to be able to export the xgboost model into the specific format they use, and then the actual scripts.  E.g., in their RandomForest.cpp, the hyperplane getting and leaf regions will be the same, but instead of majorityClass you'll need the predicted values in a leaf.


Inequality with integral

Question: Assume that F is a strictly increasing and continuous function , differentiable if needed,  over [0,a] such that F(0)=0 and F(a)=1, a>0. Prove or disprove :
$\int_0^a (F(x)-4F^2(x)+3F^3(x))\, dx\leqslant 0$
I proved this for concave functions and also it is true for many non concave functions, like $x^k, k>1$ but I don't have a general proof nor a counter example.
Any other sufficient conditions for F for this to be true would be appreciated.
Answer: To construct a counterexample, think about the map $y \mapsto y(1-4y+3y^2)$. This possesses roots at $y = 0,1/3,1$, and is positive on $(0,1/3)$ and negative on $(1/3,1)$. The problem can arise when $F$ spends time in $(0,1/3)$, contributing positive mass, or in $(1-\delta,1)$, contributing little negative mass. With this in mind, how about any function $F$ defined in such a way that $F(x) = 1/6 + x/1000$ for $x \in (\delta, 1-\delta)$, for $\delta > 0$ small (taking $a = 1$ for simplicity).
I checked this recipe for $\delta = 1/100$ and got that $$\int_{\delta}^{1-\delta} F(x) (1 - 4 F(x) + 3 F(x)^2) dx = 0.0680139$$, which means that no matter what values $F$ takes on the remainder of $[0,1]$, you'll still have an overall positive integral.
EDIT (Addendum): A sufficient condition for the inequality to hold:
Write $G(y) = y(1-4y+3y^2)$. Then $G$ has a maximum value $z^* > 0$ at some point in $(0,1/3)$. The condition will be of the form $F|_{(\delta, a-\delta)} \in (1/3 + \epsilon, 1 - \epsilon)$, where $\epsilon, \delta$ will be determined in terms of $z^*$. We have,
$$\int_0^a G \circ F(x) dx \leq z^* \delta + (a - 2 \delta) \max\{G(1/3 + \epsilon), G(1 - \epsilon)\}
$$
You can now specify $\epsilon, \delta$ so that the right hand side is dominated by zero.
Comment: To clarify, I'm saying that any $F$ satisfying the parameters of the problem which takes on the above form on the interval $(1/100, 99/100)$ will break the inequality. You can fill in $[0,1/100]$ and $[99/100]$ however you want to.
Comment: Good idea but it is not clear to me why (1/100,99/100) has to dominate (99/100,1). Derivative may be too high at 1. Will check your example by filling in (99\100,1).
Comment: The global minimum of $y(1-4y+3y^2)$ is about -.3 and so the contribution from the endpoints can be no worse than $-.3 * 2/100 = -.006$.
Comment: Moreover, this problem doesn't have anything to do with the derivative of $F$. Which derivative are you talking about?
Comment: Now, I see. If the calculation is correct, this shpuld be okay. Thank you for your work. Any idea on possible sufficient condition for F for the inequality to be true?
Comment: Well, roughly speaking, you'd want a condition that prevents the construction above from working. What I have in mind is some condition that says $F$'s values leave the interval $[0,1/3]$ 'quickly', and that the values of $F$ spend 'enough' time in $(1/3,1)$ in such a way that they don't linger at the endpoints of this interval for too long (so that the contribution would be near zero). You could turn this into some kind of sufficient condition given by an inequality.
Comment: Thank you for your response.  I completed the example you made and inequality fails. So, this is a valid example. The worrying thing for me about the sufficient condition argument you were thinking is that this inequality holds $F(x)=x^{k}$, for all $k$. Hence, for large $k$, $F$ values are almost always below $1/3$. For example, for $k=1000$, $F$ is below $1/3$ when $x<0.9989$. So, there seems to be additional reason for the inequality to hold.
Comment: @EmrePer Yeah, that makes sense; the 'sufficient' condition I mentioned is very much 'nonnecessary'. I'm sorry to say however that it's not likely you'll find a nice 'necessary' condition aside from the integral inequality itself...
Answer: This doesn't have to be true. If $1>c-4c^2+3c^3>0$ for $0<c<1$, for example $c=1/4$, the integral of the constant function $F(x)=c-4c^2+3c^3$  from $0$ to $1$ is greater than $0$. Now just approximate $f(x)=c$ by a differentiable function that satisfies your criteria. One example (hope I didn't make a mistake !)
$$
f(x)=
\begin{cases}
c\sin(\pi/2\cdot x/\epsilon),\quad 0\leq x <\epsilon\\
c,\quad \epsilon\leq x\leq 1-\epsilon\\
1-(1-c)\cos(\pi/2\cdot (x-(1-\epsilon))/\epsilon),\quad 1-\epsilon<x\leq 1
\end{cases}
$$
You can choose $\epsilon$ as small as you want, so the integral is as close to $c-4c^2+3c^3$ as you want.

Inequality with integral


Solving a rational inequality with an unknown using cases

Question: So the question is,

For what values of x is $\dfrac{1}{1 + x}> -1 $ ?

Now, one way to do it is write the inequality relative to zero, and then find the behavior of the graph relative to the zeroes of the numerator and denominator:
$\dfrac{1}{1 + x}> -1 \implies \dfrac{1}{1+x} + 1> 0 \implies \dfrac{1}{1+x} + \dfrac{1+x}{1+x} > 0 $
$\implies \dfrac{2+x}{1+x} > 0$, and we simply find what happens when $x < -2, -2 < x < -1$, and $x > -1$.
What I don't understand is why I can't answer this by multiplying through by $1 +x$ if I consider both a) $1 +x >0$ and b) $1+x < 0$.
Here's the attempt:
Case a):
$1 + x > 0 \implies x > -1$, so
$\dfrac{1}{1+x} > -1$
$\implies (1+x) \dfrac{1}{1+x} > -1 (1+x) $ (we can multiply both sides by 1+x because we assume 1+x is positive)
$\implies x > -2 $.
Hence, the inequality is true when $x > -2$ and $x > -1$--so $x > -1$.
Case b): $1+x < 0 \implies x < -1$, so
$\dfrac{1}{1+x} > -1$
$\implies (1+x) \dfrac{1}{1+x} < -1 (1+x) $ (we assume $1+x$ is negative, so we reverse the sign)
$\implies 1 < 1 + x$
$\implies x > 0$.
Hence, the inequality is true when $x < -1$ and $x > 0$--this is never true.
So the real answer is $x > -1$ or $x <-2$, and I think the reason my attempt at multiplying through by an unknown doesn't work is that, in my assumption $x\in (-1, \infty)$ clearly includes both negative and positive values, and that leads the answer to be wrong.
But I'm not 100 percent certain it's impossible, and would like some help!
Comment: If $1+x<0$ then the inequality is equivalent to $$(1+x)\frac{1}{1+x}<-1\cdot (1+x)\implies 1<-1-x\implies 2<-x\implies x<-2$$
Comment: Oy, such a silly error. Thank you!
Comment: You're welcome :) Anyway your idea is correct. ;)
Answer: Shortly $${ \frac { 1 }{ 1+x }  }>-1\\ \frac { 1 }{ 1+x } +1>0\\ \frac { x+2 }{ x+1 } >0\\ \frac { \left( x+1 \right) \left( x+2 \right)  }{ { \left( x+1 \right)  }^{ 2 } } >0\\ \left( x+1 \right) \left( x+2 \right) >0\\ x\in \left( -\infty ;-2 \right) \cup \left( -1;+\infty  \right) \\ $$
Answer: I think the question has been well-answered, but in case you were looking for a way to multiply through and not have to worry about these cases, try this:
$$\frac{1}{1+x} > -1$$ Multiplying through by the positive quantity $(1+x)^2$ gives, $$ (1+x)^2 \frac{1}{1+x} > -(1+x)^2$$ $$ 1+ x > -(1+x)^2$$ $$(1+x) + (1+x)^2 > 0 $$$$ (1+x) [1+ (1+x)]>0$$ $$(1+x) (2+x)>0$$ which has solutions of $x<-2$ or $x>-1$.
Answer: The following specifically answers this part of OP's question:

What I don't understand is why I can't answer this by multiplying through by $1 +x$ if I consider both a) $1 +x >0$ and b) $1+x < 0$.

This does in fact work, and the posted attempt failed only because of a simple mistake in case b).

Case b): $1+x < 0 \implies x < -1$, so
  $\dfrac{1}{1+x} > -1$
  $\implies (1+x) \dfrac{1}{1+x} < -1 (1+x) $ (we assume $1+x$ is negative, so we reverse the sign)
  $\color{red}{\implies 1 < 1 + x}\;\;\cdots$

The part in red is wrong. After multiplication, the inequality is $\,1 \lt \color{red}{-1 -x} \iff x \lt -2\,$, instead. Once this is corrected, the rest of the proof works, and gives the correct end result.
The problem appears to be with this comment "we assume $1+x$ is negative, so we reverse the sign" which I am not sure what means. When multiplying $-1 \cdot (1+x)$ the result is always $-1 \cdot (1+x)$ regardless of the sign of $1+x\,$. What does change when $1+x$ is negative is that the direction of the inequality gets reversed from $\,\gt\,$ to $\,\lt\,$ (which part was done correctly in the post).


How do I compile my main Java program on the command line when it includes an external java package?

Question: I'm a relative Java newbie so apologies if the question appears somewhat basic. I've googled high and low for an answer here and I'm not finding anything that's helping.
Problem:
Whilst I'm able to integrate external packages into my Java programs from an IDE environment, I am trying to do run a very basic program from the command line that calls on a separate, basic package file that I have written - and am simply doing all this as I want to have a bottom-up understanding of how package files are related to a main program by Java.
I have a program that sits on my desktop named MyProgram.java:
import org.somepackage;

public class MyProgram {

    public static void main(String arguments[]) {

    System.out.println("Programme up and running...");
    Human myHuman = new Human();
    myHuman.scream();

  }

Still on the Desktop, I then have another folder which I've named src, inside of which I have created the necessary subfolders corresponding to the package name, i.e. ./src/org/somepackage - and in this location, I have the Human.java file which defines the Human class with the following contents:
package org.somepackage;

public class Human {

    public void scream() {

    System.out.println("I exist!!");

  }

}

I then created a classes folder, again on the Desktop, and ran the following compile command on the command line:
javac -d ./classes/ ./src/org/packagename/Human.java

This ran fine and created - as expected - the Human.class file within the ./classes/org/packagename/ location.
However, where I fall down is when I then try to compile MyProgram.java on the command line, i.e.
javac -cp ".:./classes/" MyProgram.java

As you'll see, my class path contains a reference to the current location (".") for the MyProgram.java file, and it contains a reference to the classes folder ("./classes/") which is the base location for the org.somepackage package inside whose subfolders (./classes/org/somepackage/) on can find the Human.class file.
At this stage, I was simply expecting the java engine to compile MyProgram.java into the program MyProgram.class - but, instead, I get an error:
MyProgram.java:1: error: package org does not exist
I've been following the instructions listed here:
https://www3.ntu.edu.sg/home/ehchua/programming/java/J9c_PackageClasspath.html
and I don't appear to be deviating from the instructions - yet I'm unable to locate an explanation on Stackoverflow or anywhere else as to a  possible reason for this compile failure. If anyone has an idea, your help would be very much appreciated.
Thanks,
Answer: Your mistake is here
import org.somepackage; <--

public class MyProgram {

    public static void main(String arguments[]) {

    System.out.println("Programme up and running...");
    Human myHuman = new Human();
    myHuman.scream();

  }

you forgot to import class actually, you need to write this name
import org.somepackage.Human; import all package content import org.somepackage.*; or write full qualified name of class in your code
org.somepackage.Human myHuman = new org.somepackage.Human();
myHuman.scream();

correct mistake:
import org.somepackage.Human;

public class MyProgram {

    public static void main(String arguments[]) {

    System.out.println("Programme up and running...");
    Human myHuman = new Human();
    myHuman.scream();

  }

after that compile your Human.java by this command:
javac -d classes Human.java

and MyProgram.java
javac -d classes -cp "classes" MyProgram.java

and run MyProgram by
java -cp "classes" MyProgram

Comment: My first post on stackoverflow, and barely a few minutes after submitting the question, I get the solution to my problem - thank you so much! Code is working a treat now....
Comment: @GoingMush Good question contains half of the answer. When all your code works, mark answer as accepted according to site rules.


Coordinate descent for the lasso or elastic net

Question: Are there any good papers or books dealing with the use of coordinate descent for L1 (lasso) and/or elastic net regularization for linear regression problems?
Answer: I earlier suggested the recent paper by Friedman and coll., Regularization Paths for Generalized Linear Models via Coordinate Descent, published in the Journal of Statistical Software (2010). Here are some other references that might be useful:

Pathwise coordinate optimization, by Friedman and coll.
Fast Regularization Paths via Coordinate Descent, by Hastie (UseR! 2009)
Coordinate descent algorithms for lasso penalized regression, by Wu and Lange (Ann. Appl. Stat. 2(1): 224-244, 2008; also on available on arXiv.org)
Coordinate Descent for Sparse Solutions of Underdetermined Linear Systems of Equations, by Yagle (a bit too complex for me)
Comment: "A brief history of coordinate descent for the lasso" on pp15-17 of the UseR! talk is a gem :-)
Comment: Thanks for the references. Incidentally, the paper by Friedman et al partially answers a related question I've just posted, about the relative performance of coordinate descent vs LARS.
Answer: I've just come across this lecture by Hastie and thought that others might find it interesting.
Comment: Sorry but I am not able to open the video. I am very interested to Watch it
Comment: @Christina It seems to be working at the moment. However you need to have Flash enabled. I cannot find a download link, so there seems no choice but to enable Flash and watch it streaming.


Subpatterns within CAGED guitar patterns

Question: I've been looking at the CAGED system to learn to play movable scales on the guitar.
As part of this I've tried to draw the patterns myself, and in the process I noticed that if you look at two consecutive strings as a pair, there are five sub-patterns within the five CAGED scale diagrams. So each scale diagram can be described with three sub-patterns. See attached picture below. I've marked the two string patterns I, II, III, IV, and V. In some cases the patterns have to be shifted one fret up the neck, and I've marked these with '>'. The solfege note names are the same for all the subpatterns, which is a good help for remembering their relation the the scale.
I've not read anything about this before, but do these patterns within the CAGED system have any name, or is there some literature on this?
Answer: The're just the first 5-6 notes of some of the mode of a major scale which isn't a surprise since the patterns for the modes themselves come from shifting where you start the major scale pattern.

I is the first 6 notes of the Phyghian mode
II is the first 5 notes of the Mixolydian mode
III is the first 6 notes of the Aeoleian mode (or minor scale)
IV is the first 6 notes of the Locrian mode
V is the first 5 notes of the Dorian mode

Also in general, try not to use Roman Numerals to denote ideas in music as   they are already use widely in Roman Numeral Analysis and to mark positions in classical guitar music.


Wordpress Woocommerce sort products differently per category

Question: I am working with wordpress and woocommerce. What I have been trying and search for the last days is a way to sort products per productcategory. Products in category 'cars' for instance must be sorted by price ASC. I have about 10 different categories with different sorting. I thought this code below would solve my problem, but it doest. I have tried multiple ways, but can't find the right one. My PHP knowledge is very limited, but learning everyday. Shoud I use case ? How would I accomplish this ? Or maybe it's just a other way of writing ? I hope someone can assist me. Thanks in advance.
Bas
add_filter('woocommerce_get_catalog_ordering_args','tk_woocommerce_catalog_orderbyb');
function tk_woocommerce_catalog_orderbyb( $args ) {
   $cat = get_the_terms( $product->ID, 'product_cat' );
   foreach ($cat as $categoria) {
      if($categoria->parent == 0) {
         $main_parent = $categoria->name;
      }
   }
   if($main_parent == 'Cars') {
      $args['orderby']  = 'meta_value_num';
      $args['order']    = 'ASC';
      $args['meta_key'] = '_price';
   }
   return $args;
}

Answer: I know this is not a very clean solution, but it works. And with an 'else if' statement ( or with case ) I can use different sorting per product category.
add_filter('woocommerce_get_catalog_ordering_args', 'tk_woocommerce_catalog_orderbyb');
function tk_woocommerce_catalog_orderbyb($args) {
$urlb = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($urlb,'cars')) {
    $args['orderby']  = 'meta_value_num';
    $args['order']    = 'ASC';
    $args['meta_key'] = '_price';
    }
return $args;
}


How to pass the output from a Web Activity into a Copy activity for storage

Question: I am new to Azure Data Factory and wonder if you can please help me in acheiving with the following scenario:

I want to get data from a REST Endpoint using API. The REST Endpoint is stored in a SQL Database table and therefore I fetch the URL using a Lookup activity

Further on, I am storing the URL value in a variable using a "Set Variables" activity

Post that I am fetching the data from the Endpoint using REST API in a Web activity.

Now , I want to store the output data from the Web activity into a Blob storage. For this, i am using Copy activity , but I am not able to get this working at all. Meaning , I am unable to collect the output from the Web Activity into my Copy activity.

In case any of you have come across this situation then it will be of very good help for me indeed.
Comment: Further to clarify, I am getting the following error:
{
    "errorCode": "2200",
    "message": "ErrorCode=InvalidParameter,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=The value of the property 'value' is invalid: 'The required property is not specified.\r\nParameter name: value'.,Source=,''Type=System.ArgumentException,Message=The required property is not specified.\r\nParameter name: value,Source=Microsoft.DataTransfer.Common,'",
    "failureType": "UserError",
    "target": "Copy data1",
    "details": []
}
Answer: Seems you are not using correct output from web activity in copy activity. To check what is the output from web activity follow this GIF and pass those values appropriately to copy activity


The definition and the role of cliques in Markov random fields

Question: I'm freshing up on machine learning (specifically image analysis) and of course looked into Markov random fields.
I really cannot wrap my head around the concept of cliques and their application in MRFs. The definition of a clique is, to my knowledge from graph theory, that every vertex in a clique is adjacent to every other vertex. However, I have no idea how this concept of cliques relates to the concept of neighbourhoods in MRFs and the Markov properties. Could someone explain to me the concept / definition / role of cliques in MRFs?
Comment: https://en.wikipedia.org/wiki/Clique_(graph_theory)
Answer: A clique is a complete subgraph. For the role of cliques, because the local conditional probability distribution and topological ordering do not apply to undirected models, we need to express the relations between variables and the clique is the method for us to represent the relations or connections or affinities. I think we can just use unary factors but that would be not as compact depending on the scenarios.
For instance in this example:

To encourage variables take the same value it is better to make the above three cliques. If we use the unary factor it is very hard to represent the requirement but if we use the cliques above we can make the weights big if the values are the same and very small if values are different.
And a clique can be just treated as a unary factor and hence its neighbors are just the Markov blanket because the same principle for a single variable also applies to a clique: given the Markov blanket the clique is independent of the rest of the nodes in the graph.


Printing only the first returned value to the view in Angular2 App

Question: In my Angular 2 app I am using string interpolation to print to the view some data. I am using an *ngFor to iterate over an array of objects, looking for a certain value in each of those objects, and if found, printing that value to the screen. This is working as expected.
However, on occasion, more than one value is returned - when more than one of the three objects checked has a value for that particular property. This throws off the layout. In these instances I'm wondering if there's a way I can add some logic (to the view specifically) so that ONLY the first value found gets printed.
This is what I have:
        <ng-container *ngFor="let status of record.status">

                {{status?.step}}

                {{'N/A'}}

        </ng-container>

Is there something I can add to this view code to accomplish handling this logic?
Comment: Why are you doing this in the template? Do it in the class instead.
Comment: Jon, when someone asks a question, rather than telling them how they should do it, perhaps stick to the question at hand. I realize this is usually done in the component, but in this particular case (this one time), I want to handle it in the template, if possible. And according to the answer below, it looks like this is possible.
Comment: what does when more than one of the three objects checked has a value for that particular property means
Comment: `let status of record.status; #first=first` instead of `let status of record.status, #first=first`
Comment: Right. I caught that and made the change to the semi-colon -- still erroring out with the same error, though.
Answer: You can get the first element as below
<ng-container *ngFor="let status of status;  #first=first">

And the use it as you want.
Result :
<ng-container *ngFor="let status of record.status; #first = first">

                        {{status?.step}}

                        {{'N/A'}}

    </ng-container>

OR for ng2
<ng-container *ngFor="let status of record.status;  let i = index">

                        {{status?.step}}

                        {{'N/A'}}

    </ng-container>

Comment: Do I need to reference #first elsewhere as well? Right now this is causing a compilation error for me.
Comment: You don't have to reference it.  Try changing it to  or would you please give us the thrown error ?
Comment: Parser Error: Unexpected token #, expected identifier, keyword, or string at column 46 in [let status of record.status, #first=first] in DisplayComponent@83:28 ("g-container *ngFor="let status of record.status, #first=first">
Comment: You declaration is okay. Which angular version are you using. Note that `first` is a boolean. So the content of your ng-container must be wrapped inside it.

Please use ; instead of  ,
Comment: After matching to what you have above, I'm still getting the error. Is this syntax perhaps something that only works in Angular4 on?
Comment: Maybe it's a version problem. Check with index. I edited my answer.


How do I properly define a library so that JS will execute after a certain condition is met?

Question: I'm creating a custom module to execute some JS AFTER the cache is cleared. Here is the structure of the module:
Module -> flush.info.yml
name: Flush
type: module
description: A very important module.
package: Custom
version: 1.0
core_version_requirement: ^8 || ^9

Module -> flush.libraries.yml
flush:
  version: 1.x
  js:
    js/flush.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

Module -> flush.module
<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implementation of hook_cache_flush()
 */

  function flush_cache_flush() {
    \Drupal::state()->set('flush_cache_cleared', TRUE);
  }

  function flush_page_attachments(array &$attachments) {
    if (\Drupal::state()->get('flush_cache_cleared')) {
      $attachments['#attached']['library'][] = 'flush/flush';
     \Drupal::state()->set('flush_cache_cleared', FALSE);
    }
  }

Module -> JS -> flush.js
(function ($, Drupal, drupalSettings) {
    'use strict';

    Drupal.behaviors.flush = {
      /**
       * Drupal attach behavior.
       */
      attach: function (context, settings) {
        this.settings = this.getSettings(settings);
        alert("flush!");
        console.log ("Hello World");
      },
    };
  })(jQuery, Drupal, drupalSettings);

Both functions in flush.module work properly, however the JS that is #attached which is simply supposed to use an alert() never runs. I believe the issue is related to this line specifically : $attachments['#attached']['library'][] = 'flush/flush';
Is there something obvious I'm doing wrong? I used page_attachments as the method to attach the JS because it does not necessarily have to be associated with a specific part of the page, or a render array, etc. Please let me know if you have any potential ideas as to what the issue could be, thanks!
Comment: It is perfectly valid to attach a library inside hook_page_attachments() like you are trying to do - I have working code that does that. I don't see anything wrong with your hook_page_attachments(). BUT if you have added or changed flush.libraries.yml after you enabled your flush module, then the new libraries file might not be picked up. Try uninstalling and re-installing your module.
Comment: What happens if you run it without the if statement in hook_page_attachments?
Comment: @sonfd The JS still doesn't work. I know the if statement triggers as intended because if I echo the JS alert() command inside of it, it triggers. It's only when I try to attach the JS via the library that nothing happens.
Comment: Did you clear the cache after adding that code?
Comment: @Jaypan Yeah, clearing the cache works and if I add JS into the function flush_page_attachments() it will work as intended (i.e. an alert when the cache is cleared) however using a library which is the correct way of doing it doesn't work.
Comment: That was my point.
Comment: Clearing the cache doesn't make my library work, nor does uninstalling and reinstalling the custom module. When I add JS to hook_page_attachments() (like an alert) it seems to pop up after the cache clears but before the page reloads. Could this be why attached JS via the library isn't appearing? I feel like it should still trigger an alert like it does when it's added directly into hook_page_attachments(). Not sure though.
Comment: Are you sure you are editing the correct file? Did you check the module isn't copied in two different directories?
Comment: Attaching JavaScript code as library is what Drupal core does. It even uses the same hook you are using. If there is anything wrong, that is not the used hook. See [`contextual_page_attachments()`](https://api.drupal.org/api/drupal/core%21modules%21contextual%21contextual.module/function/contextual_page_attachments/9.3.x) as example of what Drupal core does. IMO, if the correct way to add JavaScript code were adding a block, Drupal core would do that.
Comment: See also the content of [contextual.libraries.yml](https://api.drupal.org/api/drupal/core%21modules%21contextual%21contextual.libraries.yml/9.3.x), from which it's clear that the *drupal.contextual-links* library contains JavaScript code.
Comment: I think you just need a more complete definition of what "after the cache was cleared" means. Is that an absolute truth for the universe at the moment the cache was cleared? Does a user need to be on the site before the cache was cleared for it to be significant? Is it a period of time that lasts X seconds after a cache clear?
Comment: The way you are trying to use state will not work. Your js will only be attached for literally a single page request from a single person in the universe after a cache clear.
Comment: @sonfd The code can be changed to add the library to the first X page requests done after the cache is cleared. I don't understand why it has be added after the cache is cleared, though. Probably, seeing which JavaScript code is attached and why would help in giving a better answer.
Answer: I wouldn't use Drupal::state() or hook_page_attachments(), those are too static. Better use a session value and a block, see my comment in the previous question.
Set the session value in the hook when the cache is cleared and only if not running from the command line:
function flush_cache_flush() {
  if (PHP_SAPI !== 'cli') {
    \Drupal::request()->getSession()->set('run_flush_js', TRUE);
  }
}

In the block check the session value and remove it so that it doesn't persist after the redirect.
src/Plugin/Block/FlushBlock.php
<?php

namespace Drupal\flush\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a flush block.
 *
 * @Block(
 *   id = "flush_flush",
 *   admin_label = @Translation("Flush"),
 *   category = @Translation("Custom")
 * )
 */
class FlushBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $session = \Drupal::request()->getSession();
    $build = [];
    if ($session->get('run_flush_js')) {
      $session->remove('run_flush_js');
      $build['content'] = [
        '#markup' => '

',
        '#attached' => ['library' => ['flush/flush']],
      ];
    }
    $build['#cache']['max-age'] = 0;
    return $build;
  }
}

js/flush.js
(function ($, Drupal, once) {
  'use strict';

  Drupal.behaviors.flush = {
    /**
     * Drupal attach behavior.
     */
    attach: function (context, settings) {
      if (once('flush', '.run-flush-js', context).length) {
        alert("flush!");
      }
    }
  };
})(jQuery, Drupal, once);

flush.libraries.yml
flush:
  js:
    js/flush.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/once

Edit: Update js code, see How can I make this JavaScript code get executed when the BigPipe module is enabled?
Comment: I think you need a session, without you run the javascript on a random client, whoever is requesting the first page after the cache is cleared. There are other ways than a block, but it's probably the quickest way because you can use the system how Drupal renders pages, This works even with BipPipe. I've tested it with and without and you can see how this effects the page loading.
Comment: The OP didn't say he wanted to run the JavaScript code for the same user who caused the cache to be cleared; if that were the case, though, using a session value isn't necessary, as the user who caused the cache to be cleared would be visiting at least two different pages or the same page twice. Even supposing the OP wanted to be sure to add the JavaScript code to the page requested by the user who caused the cache to be cleared (which doesn't make sense, since the cache is cleared for every user), it would be sufficient to store the user ID using the state API.
Comment: `hook_page_attachments()` is used to conditionally add attachments to a page before it's rendered, and the state API is used to store site state values. The OP isn't doing anything wrong in using them. The suggested alternative has its cons: A session value is per user and a block needs to be added to a theme region (which also means that changing theme could cause the library not to be added).
Comment: Then, using a block and a session value won't resolve the issue the OP is noticing. It could be the OP edited the .libraries.yml file after installing the module, or the OP is editing the wrong .libraries.yml file (which could also happen because there are two copies of the same module); in both the cases, changing the way the library is added to the page doesn't fix the real issue.
Comment: That's make sense because the user who was logged in when the cache was cleared is a state value for the site, not a session value.
Answer: I think you should approach this differently. Here's what I would do:
First, implement hook_cache_flush() and use it to store the last cache flush time to Drupal state.
function flush_cache_flush() {
  \Drupal::state()->set('flush_cache_cleared', time());
}

Next, use hook_page_attachments() to always attach your javascript on every page, but pass the the cache cleared timestamp to your javascript.
function flush_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'flush/flush';
  $attachments['#attached']['drupalSettings']['flush_cache_cleared'] = \Drupal::state()->get('flush_cache_cleared');
}

Last, in your javascript, check if the new cache cleared time is more recent than the previous (you'll need to store this on the client side via local storage or something).
If the times are different, you know the cache was cleared.
(function ($, Drupal, drupalSettings) {
  'use strict';

  Drupal.behaviors.flush = {
    attach: function (context, settings) {

      let cacheFlushedTime = drupalSettings['flush_cache_cleared'];
      // Do stuff with the cache_flushed_time here, like
      // compare it to a previously known cache flushed time...

    },
  };
})(jQuery, Drupal, drupalSettings);


How to extract common words of a bunch of strings

Question: Let's say we have strings like this:
Tommy is a very good child
Tommy has a very wonderful child
Tommy loves his very child

I want to extract the common words of above 3 strings as:
Tommy*very*child

How am I supposed to do that? Thanks.
Comment: By "part" do you mean, "whole word"? Or can it be a single character or group of characters? **EDIT** Thanks for clarifying
Comment: @JonathanLam, I mean in word units. Thanks.
Answer: EDIT I just realized @Joce's comment, and I put my answer in JavaScript. But it can easily be adapted to other languages. If it's not JavaScript, treat this as pseudocode.
EDIT 2 Whoa! It worked beautifully on my first try! See working example at JSFiddle.net.
This might be a very bulky scripting answer, but here goes:
Given the original sentences as string arrays:
var sentences = [
    "Tommy is a very good child",
    "Tommy has a very wonderful child",
    "Tommy loves his very child"
];

You can try to create an array of words from each array, storing it in a multidimensional array.
var split = [];
for(var i = 0; i < sentences.length; i++) {
    split[i] = sentences[i].split(" ");
}

You could also remove word duplicates here, but I don't know how to on the spot, but you could probably get some simple algorithm to do it. Unless you'll allow duplicate word phrases, of course.
Then, you could create another array with words that are the same, and fill it like so:
var same = [];
for(var i = 0; i < split.length; i++) {             // loop through sentences
    for(var j = 0; j < split[i].length; j++) {      // go through each sentence for new words
        if(same.indexOf(split[i][j]) <= -1) {       // if not already found
            var inAll = true;
            for(var k = 0; k < split.length; k++) { // check if in every sentence
                if(k == i) continue;
                if(split[k].indexOf(split[i][j]) <= -1) inAll = false; // if not found, make `inAll` false
            }
            if(inAll) same.push(split[i][j]);       // if found in all other sentences, add to array `same`
        }
    }
}

Sorry this is such a convoluted answer, but it should show the logic behind the algorithm. If you want to, try changing around the strings on JSFiddle.
Comment: I know it's pretty old but I came across to your answer because I needed it in JS. It worked beautifully indeed! Thank you!
Answer: To keep it simple, I'll use lodash here:
var a = 'Hello world'.split(' ');
var b = 'Hello again world!'.split(' ');
var c = 'Hello tomorrow'.split(' ');

var commonWords = _.union(a, b, c);
// => ['Hello']

I used lodash simply because it provides a succint method for what, in reality, you're trying to do, which is a union, based on (for example) delimiters and transforms.
A union is language-independent: the algorithm you use to implement the union will differ somewhat based on the language you choose.
You can use that within a function, where you define delimiters (for example, do I separate at a space?) and transforms (for example, do the words have to be uppercase to match?)
Comment: [`lodash`](https://lodash.com/) is "A JavaScript utility library delivering consistency, modularity, performance, & extras." I wasn't sure what it was, so I'm hoping this will clarify for anyone else.
Answer: You can use the data structure called inverted index
First you assign an unique integer to each of your input strings. Then, the idea is that for each word in the input strings, you want to compute a list of integers denoting the strings in which the word occurs. Notice that you can easily do that just processing all the input strings. In your case, in order to get words occurring in all strings, you can output words which list of occurrences has the same number of entries as the number of strings in the input.
For more details, please refer here:
https://en.wikipedia.org/wiki/Inverted_index


Why are rational singletons nowhere dense on the real line?

Question: I'm trying to understand this using the definition that the interior of the closure must be non-empty for a nowhere dense set.
Thanks
Answer: Every singleton subset of $\Bbb R$ is nowhere dense in $\Bbb R$. Let $x\in\Bbb R$ be arbitrary. Then $\{x\}$ is a closed set, so $\operatorname{cl}\{x\}=\{x\}$. Clearly $\{x\}$ does not contain any non-empty open interval, so $\operatorname{int}\{x\}=\varnothing$, and $\{x\}$ is therefore nowhere dense in $\Bbb R$.


I can't return the image of a record located in the storage folder

Question: I'm trying to display an image of a record in the table using storage, the code I made is not returning the image, and when I put its path in the browser it is possible to see the image.

Column to show image at table

 url($cli->image_client)) }}" class="w-16 h-auto">

Path from file

/opt/lampp/htdocs/client/storage/app/avatars/yTYkibyZFb9oYaF4uPfgHTg25Pa599PYiVI7btMC.jpg

filsystems.php

    'links' => [
        public_path('storage') => storage_path('app/public'),
        public_path('avatars') => storage_path('app/avatars'),
    ],

dd($validations['image_client'])

"avatars/yTYkibyZFb9oYaF4uPfgHTg25Pa599PYiVI7btMC.jpg" // app/Http/Controllers/ClientController.php:49

Comment: Did you link your storage folder to the public folder as described in the docs? https://laravel.com/docs/9.x/filesystem#the-public-disk
Comment: 'links' => [
        public_path('storage') => storage_path('app/public'),
        public_path('avatars') => storage_path('app/avatars'),
    ],
Comment: Did you run `php artisan storage:link` after that?
Comment: If you look at the generated HTML, what is the value of `src`?
Answer: To access the file in the avatars folder:
image_client)}}" class="w-16 h-auto">

Or, from the storage directory:
image_client)}}" class="w-16 h-auto">

Comment: ```image_client)}}" class="w-16 h-auto">```don't working.
Comment: Value of ```src=""```return ```src="/opt/lampp/htdocs/client/storage/app/avatars/yTYkibyZFb9oYaF4uPfgHTg25Pa599PYiVI7btMC.jpg"```
Comment: what `storage_path("app/" . $cli->image_client)` returns?
Does it return this: `/opt/lampp/htdocs/client/storage/app/avatars/yTYkibyZFb9oYaF4uPfgHTg25Pa599PYiVI7btMC.jpg` ?
Comment: But in the column of the table the image is not shown.
Comment: if you have linked the storage path to the public, you can try this: ``.
Answer:  image_client) }}" height=100 width=100>


Adjusting the browser zoom size

Question: Now I have read a couple SO answers about this question, but I have tried them all with no luck. I have found that that website I have been developing on I have had my browser zoom set differently than the default zoom size. I want to accommodate for people that may still have the default zoom size. Being the curious guy that I am, I wondered if I can change the browser size for that window. If the user wants to zoom in or out after they load page that's up to them, but I wanted to see if there was a way to have a default zoom so that it looks how it should.
Some things that I have tried
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Tried this and literally nothing changed on my browser. I set it to default just to check as well, and even after changing all the numbers it never made a difference.
So I came across a different way to do this, in CSS and same thing nothing happens at all.
@-viewport
{
zoom: .5;
}

So now I am on SO. I'm not even 100% positive that what I am trying to do is the right way to do it. I could be doing something completely off track, so that's why I am asking this question.
Basically, how do I achieve a default zoom size for the size on load, and what is the syntax for it?
Answer: Try: user-scalable=no
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />

And:
@-webkit-viewport   { zoom:100%; }
@-moz-viewport      { zoom:100%; }
@-ms-viewport       { zoom:100%; }
@-o-viewport        { zoom:100%; }
@viewport           { zoom:100%; }

Comment: yeah i just tried it, still nothing. Might just redesign everything smaller =[
Comment: Updated my answer. Try =no rather than =0, and add the CSS.

Adjusting the browser zoom size


BulkInsert entities with ComplexType

Question: How to insert many entities with a ComplexType in a timely fashion?
Consider the following:
public class Entity {
  public Address Address { get; set; }
}

[ComplexType]
public class Address {
  [ColumnName("Street")]
  public string Street { get; set; }
}

I tried SqlBulkTools which ignores nested properties. Both .CustomColumnMapping(x => x.Address.Street, "Street") and .AddColumn(x => x.Address.Street) didn't crash but didn't actually do anything either.
I also tried EntityFramework.BulkInsert-ef6 which is confused by the ComplexTypes and crashes.
Doing the inserts one by one takes a very long time, even with ValidateOnSaveEnabled and AutoDetectChangesEnabled turned off. Creating new contexts and playing with the amount of DbContext.SaveChanges() didn't help either.
Comment: Just my opinion: I don't like any of the BulkInsert Tools coming around EF6. There's no much support and nobody guarantee that they will work with further versions of EF. (And Data components are just too core to take that risk). so whenever I want to Bulk things. I use old good plain ADO.NET SqlBulkCopy even if it's lead to a more unelegant solution.
Comment: The most efficent way to run SQL in .Net is ADO.Net. **Nothing** will beat this for performance. So if you want performance use ADO.Net SqlBulkCopy (as mentioned)
Answer: You can easily do that using Entity Framework Extended Library.
Just an example:
//update all Entities with Street of MyStreet to Street of YourStreet
context.Entities
    .Where(t => t.Address.Street == "MyStreet")
    .Update(t => new Entity { t.Address.Street = "YourStreet" });

Here is the Link : Entity Framework Extended Library
Comment: He is asking for bulk inserting. This library does not offer this feature.
Answer: Disclaimer: I'm the owner of the project Entity Framework Extensions
This library allows Bulk Inserting (With Complex Type) but also all other bulk operations.

BulkSaveChanges
BulkInsert
BulkUpdate
BulkDelete
BulkMerge

Example
// Bulk Insert
context.BulkInsert(complexTypeEntities);

// Easy to use
context.BulkSaveChanges();

// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);

The library support all kind of inheritance and association, however, the library is not free.

BulkInsert entities with ComplexType


How do I find tablespace names

Question: I'm trying to upgrade APEX from oracle XE 11.2 to APEX 5.1.2
I'm an absolute newbie on databases. I know almost nothing, and I'm doing this to learn.
I had just installed OracleXE112_Win64, and I don't know how to find the data to do the upgrade.
To do the upgrade, I need this data:
-tablespace_apex is the name of the tablespace for the Oracle Application Express application user.
-tablespace_files is the name of the tablespace for the Oracle Application Express files user.
-tablespace_temp is the name of the temporary tablespace or tablespace group.
-images is the virtual directory for Oracle Application Express images. To support future Oracle Application Express upgrades, define the virtual image directory as /i/.
How do I find what is tablespace_apex, tablespace_files, tablespace_temp, and images directory?
Answer: Officially there APEX 5.1 is not supported in Oracle XE but here you can find a guide to help you with that
https://mikesmithers.wordpress.com/2015/05/25/upgrading-to-apex-5-on-oracle-xe-11g/
In general to look at the tablespace names you can use
<code>SELECT TABLESPACE_NAME FROM DBA_TABLESPACES;
</code>
I strongly suggest to create new tablespaces for the new installation of Apex and to use TEMP as tablespace_temp.
The virtual image directory is the URL for your images, so if you don't have any specific requirements just use the default /i/

How do I find tablespace names


Analogue Expedited App Review for WP-application

Question: As far as I know the certification process in the Windows Phone Store lasts from 5 to 9 days (mean 7). My application is confined to a specific date of the company, and there is a suspicion that the application does not have time to appear in the store by that date. But I would like to make it. In AppStore there is such thing as a Request for an Expedited app Review. You must fill out a form, submit your app, specify the reason for the request and a description (Time-Sensitive Event in this case), and in most cases, Apple makes a decision on the application within 2 days (or so). Of course there are restrictions on the use of this possibility (1 per year for an account.)
Actually the question. Is it possible to speed up the certification process for Windows Phone applications? Or at least reduce to a minimum the time of certification.
I would be grateful for related links, or any other information.
Answer: There is no provision of publishing app immediately as per users request. Windows phone marketplace does not allow user to publish there app without going through certification process and no one can manually publish app even you contact microsoft support.


Block web browsing by older browsers

Question: Given the vulnerabilities in older versions of IE, I want to enforce a rule that only the latest IE or Firefox is used to browse the web.
I can't ensure that everyone's PC is up to date, so is there a firewall that will let me write a rule to restrict the version of the  browser that can make requests through the firewall?
Our current firewall is from Watchguard
Comment: Squid can do it.. but I'm not sure if you mean outbound user traffic, or inbound foreign traffic.. either way, it doesn't sound like the best way to deal with the problem.
Comment: Talk to your Watchguard vendor or Watchguard themselves.  The only reason for buying (and ongoing licensing of) Watchguard firewalls is that availability of somebody to talk to.
Answer: As far as I know it not possible for IE to determine exact version of browser and I never seen watchguard, but the main idea is to monitor HTTP requests for User-Agent field and analyse it. But it is always better to monitor your network health and update status with tools like WSUS or NAP
Comment: It is indeed better to monitor your network health centrally, but blocking old user-agents (and the ability to block user-agents of known malware) is pretty useful.  You'll get flack from managers who are suddenly unable to browse the web when you do this, so you'll want to warn people before implementing this in order to cover yourself.
Comment: agreed, I would prefer to use WSUS, but not all the PCs are on the domain

Block web browsing by older browsers


Windows XP PC cannot resolve external domain names without dialup connection

Question: I'm trying to connect a Windows XP machine to the Internet via my router / ADSL modem at home. When I set up a dialup connection, the machine is able to resolve external domain names. When I just plug it in without dialling up, it will not resolve the names. It can resolve names of other machines internal to the network, and other machines can ping it. It can ping the router and external IPs without needing to dial up.
The router and network are absolutely fine for 4 other machines on the network - Windows 7 and Linux boxes, as well as my Android phone, none of which require dial-up connections.
The same behaviour occurs regardless of whether the firewall is on or off.
EDIT: Everything works when I hardcode in the correct default gateway and DNS server. When I leave all the stuff blank, it breaks again.
Answer: You could check your IP settings to make sure that you've got DHCP set up for your DNS server, not something hardcoded in there.
Comment: Does this config live somewhere other than the usual Connection Properties -> TCP/IP settings? There's nothing there that is hardcoded. When I do hardcode in the correct default gateway / DNS server, it does work.
Comment: No, it should live in the usual place. With them not hardcoded if you do ipconfig/all at a command prompt you can see if the gateway/dns server are being correctly given out by your router.
Answer: Check if the default gateway in working machine is same as windows xp. I think it will be not. Then adjust your default gateway to be that same as working machine if possible. To print the routing table in windows xp., Open cmd prompt and type
<code>route print
</code>
look for default section in near end of the list. I think this cmd requires admin privileges. Please check. For linux
<code>#route -n
</code>
HTH
Comment: To be honest, I'm not 100% certain how to read this, but it does look similar for the two.


Given a UMP test, why does NP lemma deliver the same critical region for all $\theta_1\in\Omega_1? $

Question: I'm unsure why, given a uniformly most powerful test exists, that the Neyman-Pearson lemma delivers the same critical region for all $\theta_1\in \Omega_1.$ Is it because this is the smallest critical region?
Answer:
why ... the same critical region for all theta_1

The test is a single critical region by definition.
It is dependent on the alternative hypothesis $\Omega_1$ (which is a single instance) but independent of whichever value for $\theta_1$ (which can have different values as long as $\theta_1 \in \Omega_1$).
Example: With a one-sided t-test (testing the alternative $\theta > 0$) the rejection criteria is to reject any hypothesis for which the statistic surpasses some critical value $t>t_c$. This critical value/region remains the same no matter what the (unknown) value is for $\theta$.
If a test is uniformly most powerful, then this single region is the best (most powerful) critical region for whatever the value of $\theta_1 \in \Omega_1$. Given some conditions, this region must be unique, and there can not be for some alternative region.


Proper method and code in R to complete PCA to determine if I can reduce variables prior to doing k-means cluster

Question: I apologize in advance for the question here as it is rather vague.   What I have been searching for is the proper way to complete PCA on a data set with 300k records and 30+ variables.   My ultimate goal is to do cluster analysis.  I have done this with relatively good outcome.   I would like to complete PCA to determine if I can reduced the number of variables.   I've been searching the internet for some time now and not finding 100% of the answer - some great information but not getting me there.   What I would like to do is use PCA to determine the most important variables to use to support streamlining my cluster analysis.  I would also like to determine if there is any multicollinearity in the variables I could avoid.   I completed PCA but struggling to tie this back to the actual variables in the data.  Any help or suggestions on a resource by link would be awesome!!  Thank you!!
Comment: I think the general issue you're having is that PCA isn't generally used for the purpose of variable selection. What kind of modeling techniques are you looking to use after you select your variables?
Answer: Yes, this can be done quite simply:

Perform PCA, decide on the number of components you want to keep. Save weights.

For each observation, calculate component scores (linear combination of weighted sum of variable values - Note, that it is best to first re-scale all variables, preferably before step 1).

Perform cluster analysis on the component scores.

END.

You have done step 1, so now you just need to do step 2 and 3.
To answer the other question: multicollinearity is rarely an issue for PCA unless you have correlations like 0.98, 0.99.


CloudFront Distribution with ELB origin HTTP 502 (Bad Gateway)

Question: I have a CloudFront Distribution connected with a custom origin ELB (with EC2 instance). When executing  a request curl https://xxx.cloudfront.net/atlassian-connect.json a HTTP/1.1 502 Bad Gateway response is returned.
HTTP/1.1 502 Bad Gateway
Content-Type: text/html
Content-Length: 587
Connection: keep-alive
Server: CloudFront
Date: Sun, 29 May 2016 14:32:18 GMT
Age: 23
X-Cache: Error from cloudfront
Via: 1.1 fb7ff691963d3e3600808dccbe4422d2.cloudfront.net (CloudFront)
X-Amz-Cf-Id: HymCU2TweM0e6O4bDhluvDOj0gd2BoAqCnDtVyTOZBz2wOIYHN-Qhg==

When sending a request (bypassing the CloudFront distribution) straight to the ELB I'm able to get the response that is expected:
curl  -kv https://xxx.eu-central-1.elb.amazonaws.com/atlassian-connect.json

After trying to tweak some of the cloudfront distribution options I'm not able to get it to work.
Comment: The `-k` in your cURL command is concerning. Does it work without that? If your SSL isn't valid, CloudFront isn't going to connect.
Comment: You nailed it, as usual, @ceejayoz.
Comment: For me issue was that certificate for ELB was incorrect (was custom certificate, but the Origin URL for CloudFront was AWS own DNS: something124124.eu-west-1.elb.amazonaws.com
Answer: In case the problem is not with the certificates (like in my case), it can be related to the headers not being passed to the origin. After setting AllViewer for the Origin request policy option in the CloudFront behavior setting (see picture), the 502 Bad Gateway error was gone.

Origin request policy values are further explained here: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-origin-request-policies.html
Answer: The SSL certificate on your server is not usable in this configuration.
You're bypassing validation with curl, but CloudFront (sensibly enough) provides no such bypass mechanism.
Your cert must match either the origin hostname or the Host: header in the original request, if you have the Host: header whitelisted for forwarding to the origin.

If your certificate doesn't contain any domain names that match either Origin Domain Name or the domain name in the Host header, CloudFront returns an HTTP status code 502 (Bad Gateway) to the viewer.

...and, it has to be current, valid, not self-signed, with a properly constructed trust chain:

If the origin server returns an expired certificate, an invalid certificate or a self-signed certificate, or if the origin server returns the certificate chain in the wrong order, CloudFront drops the TCP connection, returns HTTP error code 502, and sets the X-Cache header to Error from cloudfront.

Citations are from http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html.
Comment: Headers have not been forwarded with the request. So the `Host:` header was missing in the request and the request failed.
Comment: I can't believe it took me too long to find out the certificate was the issue. I'm upvoting this, hopefully it will making to the first results of Google.


Determining a derivation on the unit sphere of the $\mathbb{R}^3$

Question: Let $S^2 \subseteq \mathbb{R}^3$ be the unit sphere in $\mathbb{R}^3$ (which is a smooth manifold of dimension $2$). Let $\phi = (x_1, x_2): S^2 \backslash \{N\} \to \mathbb{R}^2 $ be the stereographic projection of the $S^n$, where $N = e_3 = \pmatrix{0 \\ 0 \\1}$ is the north pole, i.e. $\phi$ is given by
$$\phi(u) = \phi(u_1, u_2, u_3) = \left( \frac{u_1}{1 - u_3}, \frac{u_2}{1 - u_3} \right) $$
Now let $f: \mathbb{R}^3 \to \mathbb{R}$ be given by $f(u) = u_3$, i.e. $f$ is the third coordinate projection.
For any $p \in S^2$, I now want to determine the derivation $\frac{\partial}{\partial x_i} \mid_p (\overline{f})$ (where $\overline{f}$ denotes the function germ of $f$).
I must admit that I haven't yet fully understood how to determine a derivation like this. So do I simply need to determine the partial derivatives of $f$, and then determine $\phi(p)$ and sum up the partial derivatives of $f$ correctly to get the derivative of $f$ in the "direction" $\phi(p)$? I'm not really sure if that's the right approach, though.
Answer: Here is how you determine
$$
\frac{\partial}{\partial x_i}|_p f
$$
in general for a smooth function $f$ defined on some neighborhood of $p$ in $S^2$. (The vector fields ${\partial}/{\partial x_i}$ are only defined on $S^2\setminus\{N\}$, so we have to assume $p\neq N$ for all this to make sense.) We may assume that $f=f(x,y,z)$ is a smooth function defined on a neighborhood of $p$ in $\mathbf R^3$. Note that the inverse $\phi^{-1}$ of the stereographic projection $\phi$ is defined by
$$
\phi^{-1}(x_1,x_2)=\left(\frac{2x_1}{||x||^2+1},\frac{2x_2}{||x||^2+1},\frac{||x||^2-1}{||x||^2+1}\right),
$$
where $||x||^2=x_1^2+x_2^2$. Then
$$
\frac{\partial}{\partial x_i}|_p f=\frac{\partial (f\circ\phi^{-1})}{\partial x_i}(\phi(p)).
$$
We compute the partial derivative using the chain rule. For example for $i=1$ this gives:
$$
\begin{multline*}
\frac{\partial (f\circ\phi^{-1})}{\partial x_1}=
\frac{\partial f}{\partial x}\cdot \frac{\partial \phi_1^{-1}}{\partial x_1}+
\frac{\partial f}{\partial y}\cdot \frac{\partial \phi_2^{-1}}{\partial x_1}+
\frac{\partial f}{\partial z}\cdot \frac{\partial \phi_3^{-1}}{\partial x_1}=\\
\frac{\partial f}{\partial x}\cdot \frac{2(||x||^2+1)-4x_1^2}{(||x||^2+1)^2}+
\frac{\partial f}{\partial y}\cdot \frac{-4x_1x_2}{(||x||^2+1)^2}+
\frac{\partial f}{\partial z}\cdot \frac{2x_1(||x||^2+1)-(||x||^2-1)2x_1}{(||x||^2+1)^2}=\\
\frac{\partial f}{\partial x}\cdot \frac{2-2x_1^2+2x_2^2}{(||x||^2+1)^2}+
\frac{\partial f}{\partial y}\cdot \frac{-4x_1x_2}{(||x||^2+1)^2}+
\frac{\partial f}{\partial z}\cdot \frac{4x_1}{(||x||^2+1)^2},
\end{multline*}$$
the first factor of each term being evaluated at $p$, the second at $\phi(p)$.
Doing the latter evaluation gives an expression in terms
of the coordinate functions $x,y,z$ on $S^2$ only:
$$
\begin{multline*}
\frac{\partial}{\partial x_1}|_p f=
\frac{\partial f}{\partial x}\cdot \frac{2-2x^2/(1-z)^2+2y^2/(1-z)^2}{(x^2/(1-z)^2+y^2/(1-z)^2 +1)^2}+
\frac{\partial f}{\partial y}\cdot \frac{-4xy/(1-z)^2}{(x^2/(1-z)^2+y^2/(1-z)^2 +1)^2}+
\frac{\partial f}{\partial z}\cdot \frac{4x/(1-z)}{(x^2/(1-z)^2+y^2/(1-z)^2 +1)^2}=\\
\frac{\partial f}{\partial x}\cdot \frac{(1-z)^2(2(1-z)^2-2x^2+2y^2)}{(x^2+y^2+(1-z)^2)^2}+
\frac{\partial f}{\partial y}\cdot \frac{-4xy(1-z)^2}{(x^2+y^2+(1-z)^2)^2}+
\frac{\partial f}{\partial z}\cdot \frac{4x(1-z)^3}{(x^2+y^2+(1-z)^2)^2}=\\
\frac{\partial f}{\partial x}\cdot \frac{4(1-z)^2(1-z-x^2)}{4(1-z)^2}+
\frac{\partial f}{\partial y}\cdot \frac{-4xy(1-z)^2}{4(1-z)^2}+
\frac{\partial f}{\partial z}\cdot \frac{4x(1-z)^3}{4(1-z)^2}=\\
(1-z-x^2)\cdot\frac{\partial f}{\partial x}-
xy\cdot\frac{\partial f}{\partial y}+
x(1-z)\cdot\frac{\partial f}{\partial z},
\end{multline*}$$
which is the formula we where after.
It is interesting to note that it follows that the vector field $\partial/\partial x_1$ has smooth continuation over the whole sphere $S^2$, and that it vanishes at $N$.
Anyway, for your function $f(x,y,x)=z$, one now obtains
$$
\frac{\partial}{\partial x_1}|_p f=x(1-z).
$$
By symmetry, one has
$$
\frac{\partial}{\partial x_2}|_p f=y(1-z).
$$