Optimise complexity of combinatoric algorithm (2)

Question: I'm trying to find a way to optimise the calculation for the following problem:

You are given N boxes indexed from 1 to N. Each box contains 0, 1, or 2 coins.  The number of boxes with 0, 1, or 2 coins are denoted n0, n1, and n2 respectively. You take a random subset of the boxes where each subset has the same same probability to be selected. The empty set and the set itself are considered a subset.
What is the probability that the total number
of coins in a random subset is divisible by 3.
Constraint: N = n0 + n1 + n2 < 100000
EXAMPLES
1

Input: n0 = 0, n1 = 1, n2 = 0
Output: 0.5
Explanation: There are two subsets: [] and 1. Only the sum of [] is a multiple of 3.

2

Input: n0 = 0, n1 = 2, n2 = 0
Output: 0.25
Explanation: There are four subsets: [], 1, 1, and [1, 1]. Only the sum of [] is a multiple of 3.

3

Input: n0 = 1, n1 = 1, n2 = 1
Output: 0.5
Explanation: There are eight subsets and the following four have a sum that is a multiple of 3: [], [0], [1, 2], and [0, 1, 2].

My implementation in Python 3.8:
prob = 0

for j in range(0, n1+1):
    for k in range(0, n2+1):
        if j == k:
            prob += comb(n1, j) * comb(n2, k)

        elif (j % 3 == 0) & (k % 3 == 0):
            prob += comb(n1, j) * comb(n2, k)

total_prob = (2**n0 * prob) / (2 ** (n0+n1+n2))
return total_prob

The result doesn't seem trivial, but after playing with the number, some patterns appear : similar result are given when changing the numbers; eg. n0= 10, n1= 700, n2= 100 gives the same result (0.11111) as n0=11, n1=600, n2= 201; thus there must be some way of simplifying the calculation
This question is related to my previous question.
I tried to implement the solution proposed by Mike, but I must have made something wrong as the result is not correct, and it takes ages to compute:
def p_x_equals_i(n1, n2, i):

    y_n1 = n1 // 2
    y_n2 = n2 // 2
    z_n1 = n1 // 2 + (n1 % 2)
    z_n2 = n2 // 2 + (n2 % 2)

    prob = 0

     ## i equals 0

    if n1 == 1 and n2 ==0 and i == 0:
        return 0.5

    if n1 == 0 and n2 == 0 and i == 0:
        return 1

    if n1 == 0 and n2 ==1 and i == 0:
        return 0.5

    if n1 == 1 and n2 ==1 and i == 0:
        return 0.5

    ## i equals 1

    if n1 == 1 and n2 ==0 and i == 1:
        return 0

    if n1 == 0 and n2 == 0 and i == 1:
        return 0

    if n1 == 0 and n2 ==1 and i == 1:
        return 0.5

    if n1 == 1 and n2 ==1 and i == 1:
        return 0.25

    if i == 0:
        return p_x_equals_i(y_n1, y_n2, 0) * p_x_equals_i(z_n1, z_n2, 0) +\
            p_x_equals_i(y_n1, y_n2, 1) * \
                    ( 1 - (p_x_equals_i(z_n1, z_n2, 0) + p_x_equals_i(z_n1, z_n2, 1))) + \
             ( 1 - (p_x_equals_i(y_n1, y_n2, 0) + p_x_equals_i(y_n1, y_n2, 1))) *\
                p_x_equals_i(z_n1, z_n2, 1)

    if i == 1:
        return  p_x_equals_i(y_n1, y_n2, 0) * p_x_equals_i(z_n1, z_n2, 1) +\
            p_x_equals_i(y_n1, y_n2, 1) *  p_x_equals_i(z_n1, z_n2, 0) +\
            ( 1 - (p_x_equals_i(y_n1, y_n2, 0) + p_x_equals_i(y_n1, y_n2, 1))) *\
                ( 1 - (p_x_equals_i(z_n1, z_n2, 0) + p_x_equals_i(z_n1, z_n2, 1)))

    else:
        print('error')

def recursive(n1, n2):
    y_n1 = n1 // 2
    y_n2 = n2 // 2
    z_n1 = n1 // 2 + (n1 % 2)
    z_n2 = n2 // 2 + (n2 % 2)

    return p_x_equals_i(y_n1, y_n2, 0) * p_x_equals_i(z_n1, z_n2, 0) +\
            p_x_equals_i(y_n1, y_n2, 1) * \
                    ( 1 - (p_x_equals_i(z_n1, z_n2, 0) + p_x_equals_i(z_n1, z_n2, 1))) + \
             ( 1 - (p_x_equals_i(y_n1, y_n2, 0) + p_x_equals_i(y_n1, y_n2, 1))) *\
                p_x_equals_i(z_n1, z_n2, 1)

UPDATE 2 (Solution):
Here is the code I come up with, following the 2nd answer from Mike. Thanks a lot for the help again!
from numpy.linalg import matrix_power
import numpy as np

def p(n):
    A = np.array([[0.5, 0, 0.5], [0.5, 0.5, 0], [0, 0.5, 0.5]])
    p0 = [1, 0, 0]
    return matrix_power(A, n).dot(p0)

def q(n):
    B = np.array([[0.5, 0.5, 0],[0, 0.5, 0.5], [0.5, 0, 0.5]])
    q0 = [1, 0, 0]
    return matrix_power(B, n).dot(q0)

def f(n1, n2):
    pn1 = p(n1)
    qn1 = q(n1)
    qn2 = q(n2)

    return pn1[0] * qn2[0] + pn1[1] * qn2[2] + pn1[2] * qn2[1]

Comment: Good start! Check your base cases for i = 1, that should fix the wrong values. The reason you code is so slow is because you have too many recursive calls. It is the same reason that the program to compute the Fibonacci numbers with the recursive call f(n) = f(n-1) + f(n-2) is so slow.
Comment: hey Mike, thanks for your answer but i dont get it in terms of computing time; if the recursive way of calculating the value is slower than my initial algorithm, is it worth implementing ?!
Comment: It can be done quicker! For example, you do not need a recursive call to compute P(Y = 2), you should instead use one minus the sum of the other two. But it requires more fixes for a true speedup. I'm sorry, this was more difficult than I anticipated.
Comment: However, you may be pleased to know there is an O(1) solution! Not quite, but almost. Try computing with n2 = n0 = 0, and n1 = 1,2,3,... until you see the pattern.
Comment: I should add, it helps to compute $P(X \equiv 1)$ and  $P(X \equiv 2)$ as well to see the pattern. You see a similar pattern when n1 = 0 and n2 grows, and can then combine those two observations into 1.
Answer: Posting a second answer since it is different enough.
Let $p(n,0)$ be the probability that the number of coins is congruent to $0\pmod 3$  when there are $n$ boxes with one coin, and zero boxes with $0$ or $2$ coins. Similarly, let $p(n,1)$ and $p(n,2)$ be the probability that the number of chosen coins is $\equiv 1\pmod 3$ and $\equiv 2\pmod 3$ in this scenario. By considering whether or not box number $n$ is chosen, you get the recursion
$$
p(n,0)=\tfrac12p(n-1,0)+\tfrac12p(n-1,2)\\
p(n,1)=\tfrac12p(n-1,1)+\tfrac12p(n-1,0)\\
p(n,2)=\tfrac12p(n-1,2)+\tfrac12p(n-1,1)\\
$$
Now, let $\vec p(n)$ be the column vector $[p(n,0)\quad p(n,1)\quad p(n,2)]^T$. The above equations can be summarized as a matrix equation
$$
\vec p(n) = \begin{bmatrix}\frac12&0&\frac12\\\frac12&\frac12&0\\0&\frac12&\frac12\end{bmatrix}\vec p(n-1)
$$
Iterating this recursion, and letting $A$ be the matrix of $\frac12$ and $0$ above, you get that
$$
\vec p(n)=A^n\vec p(0)
$$
Therefore, if you can compute the matrix power $A^n$ quickly, then you can find $\vec p(n)$ quickly. You can compute $A^n$ in $O(\log n)$ time using exponentiation by squaring.
So far, we have solve the special case where $n_2=0$. Letting $q(n,0)$ be the probability the number of coins is $\equiv 0\pmod 3$ when there are $n$ boxes with $2$ coins and nothing else, similarly for $q(n,1)$ and $q(n,2)$, a similar scheme allows you to compute the vector $\vec q(n)$ quickly. Finally, letting $f(n_1,n_2)$ be the probability you desire when there are $n_1$ one-coin boxes and $n_2$ two-coin boxes, you get
$$
f(n_1,n_2) = p(n_1,0)q(n_2,0)+p(n_1,1)q(n_2,2)+p(n_1,2)q(n_2,1).
$$
Comment: thanks for your answer mike, i updated my question with an implementation of your solution, but it seems I get results still different with my initial algo.
Also in your last equation, is it

f(n_1,n_2) = p(n_1,0)q(**n_2**,0)+p(n_1,1)q(n_2,2)+p(n_1,2)q(n_2,1) ?
Comment: Yes, that was a typo. OK, my algorithm is correct, and your initial algorithm is wrong. Two problems; there is no need to do the $j=k$ case, since that is counted for by `j%3==0 & k%3==0`. More importantly, you also need to account for `j%3==1 & k%3 == 1` and `j%3==2 & k%3 == 2`. For example, if you select $5$ boxes with one coin and $8$ boxes with two coins, then the number of coins is a multiple of $3$.
Comment: With these extra cases, your result for the original program in the cases you asked about should increase from `0.11111` to `0.33333`, because you were only counting one third of the event. The results are still the same, and this is no coincidence; when the number of boxes is large, the number of coins is approximately equally likely to be any of the three values $\pmod 3$.
Comment: thanks a lot @Mike for all your precious help on this problem! Yeah I figured out also that the solution should converge to 1/3. Really appreciate you help!
Answer: Your solution is roughly linear in $n_1,n_2$. We can do this logarithmically in $n_1,n_2$ as follows.
Let $X_{n_1,n_2}$ be the random variable equal to the remainder $\pmod 3$ of the number of coins when there are $n_1$ boxes with one coin, and $n_2$ with $2$. Note that $n_0$ is not referenced, since it does not affect the probability distribution. The probability distribution of $X_{n_1,n_2}$ is described by three numbers summing to $1$, or more succinctly by two of those numbers $P(X_{n_1,n_2}\equiv 0\pmod 3)$ and $P(X_{n_1,n_2}\equiv 1\pmod 3)$.
We can compute these probabilities recursively as follows. Imagine splitting the one coin boxes into two roughly equal halves, one red and one blue, and same for the two coin boxes. Let $Y$ be the number of blue coins selected, and let $Z$ be the number of red coins selected, so that $X_{n_1,n_2}=Y+Z$. Then using $\equiv$ to mean "congruent modulo $3$", we have
$$
P(X_{n_1,n_2}\equiv 0)=P(Y\equiv 0)P(Z\equiv 0)+P(Y\equiv 1)P(Z\equiv 2)+P(Y\equiv 2)P(Z\equiv 1)\\
P(X_{n_1,n_2}\equiv 1)=P(Y\equiv 0)P(Z\equiv 1)+P(Y\equiv 1)P(Z\equiv 0)+P(Y\equiv 2)P(Z\equiv 2)
$$
This immediately leads to a recursive algorithm, since $Y$ and $Z$ are similar random variables described by parameters which are half the size.
Comment: hey @Mike thanks a lot for your answer. I kinda get a grasp of your solution theoretically, but when it comes to actually implement it, I'm a bit lost...
"splitting the one coin boxes into two roughly equal halves", so i guess i should implement something that halve the n1 and n2, but how to handle the odd numbers? cheers
Comment: also, out of your two final equation, the first one is not enough to calculate the probability that the total number of coins in a random subset is divisible by 3 ?
Comment: @Roger You only need the first equation to answer the question, but you need both equations for the recursion you work. I can add more detail in a couple of days
Comment: thanks for the clarification @mike, I updated the question with a tentative of implementation of your solution


Download file from Skydrive using SkyDrive Live

Question: I'm using SkyDrive Live to upload files, but now I want to download the file I just uploaded.  In the documentation it mentions a file ID but I'm not finding how I can get that ID.
I have a folder that I placed the file into so I would somehow need to pass the folder ID and then get the fileID...
Does anyone know how to do this or know of any tutorials on this?
Comment: can you please help how to upload files from wp7 to skydrive ?
Answer: If you uploaded the file with SkyDrive SDK, then you get the fileId by the UploadCompleted event's e.Result["id"]
If you have the folderId, but not the fileId, then you can query the content of the folder with client.GetAsync(folderId/files). The GetCompleted event's e.Result["data"] returns a IDictionary of file descriptions, each containing the fileId. In this cased you need to identify the required file by dictionaryEntry["name"] or some other magic..


How to name quarter tone chords

Question: Studying the flamenco mode I found that the third note of the scale is tonic when tonic is played, so it would be a major chord, yet minor in all the other cases. Eg. in the key of E the scale would go E F G(#) A B C D
resulting in the following chords: E F G Am Bm75b C Dm
If I wanted to replace the third note with a G+ (that is, G raised by a quarter-tone), I'd get a neutral major seventh chord on the first degree.
Question is: what would be the name of the chord on the 3rd degree (350 cent neutral third, 650 cent quarter-diminished fifth, 950 cent 3-quarter-diminished seventh)?
Answer: Major edit after OP's clarification
I'm pulling nomenclature from a paper written by Myles Skinner, a microtonal community wiki, and Wikipedia. I'll refer to quarter tone intervals as decimals between the semitone intervals.
3.5 is pretty universally called a neutral third. That's from all three of the sources and personal experience. It's a good representation of the just interval 11/9.
6.5 on the other hand, is called a narrow fifth on the microtonal wiki and a minor fifth in the paper and on Wikipedia. Either way, the nomenclature works. Narrow inverts to wide and major inverts to minor. For the sake of using familiar terminology and at the risk of further overloading the words, I'll go with with major and minor. It's a good representation of the 11th subharmonic, 16/11. It's also called a "wolf" fifth, which is a term borrowed from mean temperaments and pythagorean temperaments where the lack of a closed circle of fifths made one "fifth" particularly out of tune.
9.5 isn't even referred to in Skinner's piece, but the microtonal wiki says it can be called an ultra sixth or an infra seventh. They're enharmonic and both represent 26/15 very closely. Wikipedia calls those intervals subminor or supermajor and says they approximate 12/7. For the structure of the chord, we'll go with the seventh and for sticking with major and minor, call it a subminor seventh.
So, you could call this a G+nsub7m5. What a chord and its name is fully Wikipedia-compliant! Regardless of what you call it, here's what it sounds like:
https://soundcloud.com/danbobdavis/stackexchange-how-to-name-quarter-tone-chords/s-PqOhB
In order:

The flamenco scale with the G+ in it
The chord arpeggiated across two octaves and then played across one
The chord used as a V in a V-i progression
The chord used as a V in a V-I progression
A different voicing of the chord in a vii°-i type setting

In my opinion, it sounds much better as a diminished chord. If I had more time, I'd invert it, try to modulate, maybe compose with it a little. A chord in between a diminished seventh and a dominant seventh chord is definitely fascinating, but this is all time permits for this answer. Hope it helps.
Comment: The upload failed. I'll have to reupload when I'm on better internet.
Comment: All uploaded and ready to go.
Comment: I'm trying to imagine (lacking the proper software and the time) how a chord between the dominant seventh and the fully diminished may sound, but I agree it must sound funky. The G+ is the only note in the scale that is raised by a quarter tone.
Comment: Oh, I thought that when you were talking about the quarter-tone intervals that you were talking about intervals relative to the root, not to the G+. I'll edit my answer and upload a clip to reflect that when I get home.
Comment: I'd like to listen to it, but SC says the track does not exist.
Comment: If anyone wants to record these chords and put them up on the web, I'm sure we'd love to hear them!
Answer: quick answer using interval names: G+n5d7db.
The 6th also includes the G+, so that would be C5+

How to name quarter tone chords


Como desativar o Popover do Bootstrap 4 apenas em dispositivos móveis?

Question: Hoje eu uso popover em alguns locais do meu site, mas eu gostaria que eles não aparecessem na versão mobile. Existe algo no script de chamada que eu consiga fazer para que ele só apareça na versão desktop?

Answer: Pesquisando na documentação não vi nenhuma opção que desabilita o popover pela resolução da tela ou por tipo de dispositivo. Uma forma seria aplicar um display: none na classe .popover (classe nativa dos popovers) em um determinado breakpoint via CSS @media.
Supondo que o site entre em modo mobile numa resolução de 768px pra baixo, coloque no final do seu CSS a regra:
@media screen and (max-width: 768px){
   .popover{
      display: none !important;
   }
}

Exemplo:

$(document).ready(function(){
    $('[data-toggle="popover"]').popover();
});
@media screen and (max-width: 768px){
   .popover{
      display: none !important;
   }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

Toggle popover

Ao clicar no link do exemplo, o popover fica oculto. Se você executar
  o snippet acima em tela cheia (que será maior do que 768px) o popover
  irá aparecer normalmente.

Vale notar que resolução de tela não quer dizer "tipo de dispositivo". Muitos dispositivos móveis possuem resoluções altas (tablets, smartphones de tela grande), logo, se a página for aberta em um desses dispositivos e tiver resolução maior que o breakpoint do @media, o popover irá aparecer normalmente.
Existe uma função JavaScript nesta resposta que detecta quando o dispositivo é de fato móvel e não um notebook ou um desktop, independente da resolução de tela. Você pode usá-la para desabilitar o popover via JavaScript, mas como é uma função já de algum tempo atrás, não posso garantir que irá funcionar em 100% dos dispositivos, porém, em todos os dispositivos móveis que testei, funcionou em todos.
Usando a função JavaScript, não precisa inserir a regra no CSS e ficaria assim:

$(document).ready(function(){

   function ehMovel(){
      if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))){
        return true;
    }

    return false;
}

   // só aplica o popover se a função retornar "false"
   if(!ehMovel()) $('[data-toggle="popover"]').popover();
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

Toggle popover
Comment: Excelente saída, Sam. Muito obrigado.


About monitoring a server (and a HTTP status of 200)

Question: This is probably a very silly question, but I'm new to this. I am currently learning about system administration, and was asked to set basic monitoring in place (that checks a website returns HTTP 200). Here's the setup:

Server one runs a web site and backups daily to server two.
Server two stores the backups.

So, if I am tasked to "set basic monitoring in place", so that the website on server one returns an HTTP status of 200, where should I place the monitoring software? On server two? I am thinking it must be that way because if server one's site didn't return an OK HTTP status, then that'd mean the monitoring tool would fail as well?
I am planning to use Nagios for this, but I'm very confused and don't even know where to start. Sorry for the dumb question!
Thanks.
Comment: Do you have an option for a third server where you can set up monitoring separate from the two servers you already have?
Comment: Nope, I only have those two servers at my disposal.
Answer: If your monitoring requirements are simple (just checking one page for a HTTP 200) you could use the free tier of https://www.pingdom.com/ or https://www.statuscake.com/alternative-to-pingdom/
The problem with Server two monitoring Server one, is they are on the same network. If your connection to the outside world goes down your two servers would still be able to talk to one another. A real solution has to be on the same network as your users and if Server one serves the public then the monitor should simulate a user as best it can.
Answer: The answer here, if possible, is to use a third server specifically for the purpose of monitoring Server One (which can then also be expanded to monitor Server Two). Where it's possible to do so, each server should have a single function - and in doing it this way, your monitoring system's health is not tied to the health of the monitored systems.
If it is not possible to add a third server, for whatever reason, then you would monitor Server One from the outside using Server Two as you correctly state in your question, and for the reason you outlined - if Server One is down, and Server One is also running Nagios, Nagios can't tell you that Server One is down!


Krull dimension greater than or equal to small inductive dimension for Noetherian topological spaces

Question: I am trying to prove Krull dimension and the small inductive dimension coincide for any Noetherian topological space $X$. The inequality Krull$(X) \le$ ind$(X)$ holds for all topological spaces. It is the other direction ind$(X)\le$ Krull$(X)$ that troubles me. By Noetherian induction we can take a minimal closed set $A$ violating this (and we can assume $A=X$). If we can show $X$ is irreducible we can easily finish the argument (just take a point $p$ and a neighborhood $U$ whose boundary has small inductive dimension ind$(X)-1$. Then since the boundary is not $X$, we can take a chain of irreducible closed sets of length ind$(X)-1$ in $\partial U$ and add $X$ to this chain.) But how to show $X$ must be irreducible? Can someone give a hint?
Comment: What definition of small inductive dimension are you using, exactly?  The usual definition only makes sense for regular spaces (or rather, it would make every non-regular space have infinite dimension).
Comment: @EricWofsey Sorry, I forget to clarify this. A space has dimension $\le n$ if there is a basis $\mathcal B$ of open sets such that ind$(\partial U)\le n-1$ for all $U\in \mathcal B$.
Answer: For any open $U\subseteq X$, $\partial U$ is a closed subset of $X$ with empty interior, and therefore it cannot contain any irreducible component of $X$ (any irreducble component has nonempty interior, namely the complement of the union of all the other irreducible components).  So, $\partial U$ must have strictly smaller Krull dimension than that of $X$, and therefore also smaller inductive dimension than the Krull dimension of $X$ by the induction hypothesis.


Botão Toogle , com ação em html

Question: Eu estou desenvolvendo um site , e gostaria de criar um botão "Mostrar Mais" quando clicado ira mostrar um texto , mas a lista que estará em baixo ira descer , como exemplificado na imagem , qual o método mas simples e pratico para fazer ?
Comment: Não é para descer o que está abaixo? É para o de cima ficar por cima do que está abaixo?
Answer: Fiz esse modelo só com CSS, é bem simples, mas é só para fins didáticos e para você entender melhor o técnica.
Aqui tem um label com um for para o input checkbox que quando estiver :checked vai mostrar o conteúdo. Só que esse input fica escondido e o label faz o papel do botão. Veja o Snippet pra entender melhor.

.wrapper {
    padding: 8px 24px 24px;
    border: 1px solid black;
    display: inline-block;
    float:left;
    margin: 16px;
}
a, label {
    color: orangered;
    cursor: pointer;
}
.hide {
    display:none;
}
input[type="checkbox"] {
    display: none;
}
input[type="checkbox"]:checked ~ .hide {
    display: block
}
input[type="checkbox"]:not(:checked) ~ .hide {
    display: none
}

Título

    <input type="checkbox" id="btn-a">
    Mostrar Mais

Aqui meu conteúdo.
 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est, asperiores?

Título

    <input type="checkbox" id="btn-b">
    Mostrar Mais

Aqui meu conteúdo.
 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est, asperiores?

Se precisar que seja em JavaScript eu te passo um modelo, mas acho desnecessário...

Botão Toogle , com ação em html


Notes in small font

Question: Is there a name for the notes that appear in smaller size in sheet music? Not grace notes, but rather notes to accompany alternative words in lyrics in different verses that require slight variations in rhythm.
Comment: *Ossia* is used for actual alternatives but I'm not sure if that's the right word here.
Comment: @Duffa: Perhaps you could post a picture of what you mean to make it totally clear?
Answer: Smaller notes are sometimes called "cue notes" but that is only for a specific and different usage: when a melody line from a different musical part is shown in the score for another part to alert the performer as to their next entrance.
I think "small notes" is as good a term as any for the usage you describe.

Notes in small font


If $(\forall x,y\in \Bbb R)(f(x+f(y)) = f(x) +y)$ and $f(0) =1$, then $f(7) = ?$

Question: Problem :
If $(\forall x,y\in \Bbb R)(f(x+f(y)) = f(x) +y)$ and $f(0) =1$, then $f(7) = ?$
Please guide how to handle such problem I have no clue how to proceed ,, thanks..
Comment: In fact none now, @GitGud, since the OP apparently used logic notation and after the quantificator he included all the formula within parentheses...it really confused me. Thanks.
Comment: I see, @GitGud...well, if someone's not expecting that I think that can be confusing.
Answer: This problem is impossible. Applying the formula with $x = y = 0$, you get
$$f(1) = f(0+f(0)) = f(0) + 0 = 1.$$
Similarly, by using this with $x = 1$, $y = 0$, you get
$$f(2) = f(1+f(0)) = f(1) + 0 = 1.$$
On the other hand, we could have used $x = 1$, $y = 1$ and obtained
$$f(2) = f(1+f(1)) = f(1) + 1 = 2,$$
which is a contradiction.
Comment: Nicely done and caught. +1
Comment: but the answer given is 1?????
Comment: @sultan There is no solution. It's like asking what number $x$ is such that $x+1=x$, there is none (in ordinary real arithmetic).
Answer: Let $y=0$ you obtain $f(x+1) = f(x)$ thus $f(7) = f(6) = ... = f(0) = 1$
But you can show that there is no such function f, so every 'solution' is a correct answer to your question.


Are the site rules overly restrictive?

Question: I'm an old hand at StackOverflow, where the site rules make a great deal of sense (even when I egregiously violate them). But I believe they are too restrictive for Econ, where there is an enormous amount of subjectivity and difference of opinion even in relatively narrow, focused questions. We are talking about a social science, after all.
There are exceptions, of course: various well-known equations and assertions, etc. But these are the low-hanging fruit, and when they are exhausted not much will be left unless the rules are relaxed or it is determined that economics is simply not a good fit for a Q&A site such as this one.
My prediction is that a small, banal portion of economics will work in Econ SE as it currently stands, and the rest—unfortunately the most interesting part—will not. But we will see.
Thoughts?
Comment: Could you please clarify with an example or explain a bit more explicitly? I cannot see good questions (with the actual rules) exhausting very quickly.
Comment: @GregoryHigley I actually think the stackexchange rules apply well to research/academic/professional economics well for exactly the same reason that they work well for programming or statistics or mathematics. That is, there is a large body of very well-explored, well-understood, and empirically tested theory and methods These are precisely stated, and questions (and answers) can be stated in precise terms.
Comment: Thats actually the one thing I'm very afraid of. Outsiders to Economics taking the public evidence-resistant discourse they know from blogs as the "top of the notch"/expert level of Economics and asking questions that better be left to the pub.
Comment: Do you mean the site's rules during private beta? Or more generally? Because (as has been said in a few comments/answers), these are very different time periods with very different purposes.
Comment: Unfortunately I haven't done a full econometric analysis of potential questions and answers. :) This is a hunch, nothing more, which is why it's on Meta. Perhaps I'm wrong.
Comment: @CompEcon No. I'm referring to the general Stack Exchange rules, which (except in a few cases), discourage subjective questions and answers. This is mildly stultifying for a social science.
Comment: @CompEcon Good. I hope you're right.
Answer: For one, I think we need to be careful how we interpret opinion/subjectivity.
In my view, economics is as much a methodology as a body of knowledge. Given a question about social behaviour, I can write down a set of assumptions that form an economic model and solve that model to answer the question. Whether the assumptions (be they standard or unorthodox) that are made are good or not is, of course, usually somewhat subjective. I do not think this subjectivity is itself a problem for out site.
The whole point of this mode of working is that the formalism of a model forces you to make your assumptions explicit so that your peers can judge the merits of your work accordingly. I think answers involving this kind of subjectivity should be welcome. That's not to say that a mathematical model should be a necessary for a good question/answer: often, purely non-technical statements also appeal to an economic logic that implies a model—even if the model itself is never written down.
What, I think, should not be welcome are answers predicated on a particular ideological position (i.e. purely normative arguments) or speculation the cannot obviously be grounded in a sound economic mechanism or empirical evidence.
Here's a (stylised for clarity) example of what I think is and is not okay:
Firstly, not okay because purely ideological/normative (not to mention dubious economic reasoning):

A monopoly manufacturer $M$ should not be allowed to merge with monopoly retailer $R$ because the owners of $M$ make enough money already.

Secondly (and a bit more subtly), this is not okay. Although this seems to be a less opinion based answer, the economic basis for the argument is not clear and so it is hard to judge whether there is any merit to this or whether it is pure speculation:

The monopoly manufacturer $M$ should not be allowed to merge with monopoly retailer $R$ because that will make the merged $MR$ very powerful, which is likely to be bad for consumers.

Thirdly, I think this (perhaps in a slightly more developed form) is okay:

Consider a monopoly manufacturer $M$ that sells its good via monopoly retailer $R$. Consumer demand for the final good is given as a decreasing function of the retail price $D(p)$, and the manufacturer's unit cost is $c$. The manufacturer sets a wholesale price, $p_M$, whilst the retailer sets the retail price $p$.
The retailer's profit is $D(p)(p-p_M)$, which is maximised when $D'(p)(p-p_M)+D(p)=0.$ The solution is the optimal retail price, $p^*$. The manufacturer's profit is $D(p^*)(p_M-c)$, which is maximised when $$D'(p^*)\frac{\partial p^*}{\partial p_M}(p_M-c)+D(p^*)=0.$$ In particular, we must have $p_M>c$.
If the two firms merge then the merged entity maximises profits with the standard first-order condition: $D'(p)(p-c)+D(p)=0.$ Since the unmerged $p_M$ is greater than $c$, it is immediate that the merged entity sets a lower price so that consumer surplus increases. Moreover, since the merged entity is now operating at the optimal price with respect to the entire market, its profits must have increased. The merger therefore yields a Pareto improvement. This line of reasoning is likely to lead regulators to look favourably on such mergers.

The important point here is that, even though some of the assumptions in the above might be quite stark and are clearly open to criticism (i.e. the legitimacy of this analysis is somewhat subjective), there is a clear and transparent economic analysis behind the statement. The same analysis could, in principle, be presented without any mathematics provided the economic mechanism is made clear enough. In any case, such an analysis might either stand alone or be paired with empirical evidence on the issue in question.
Comment: In other words, this is the kind of site where a formula-averse Hayekian like myself would not do well at all. :)
Comment: "The same analysis could, in principle, be presented without any mathematics provided the economic mechanism is made clear enough". I agree.

Are the site rules overly restrictive?


Intercept in mixed effects cox regression (coxme in R)

Question: I am using mixed effects Cox models in the R package coxme, with the model
SurvObj ~ Sex*NE + (1|Year)

where Sex is a categorical fixed effect with two levels each (M and F), NE is a continuous predictor of particular interest, and Year the sampling year used as a random effect.
Here's dummy data/script with longer lifespan in Sex = M, and a positive effect of NE on lifespan:
set.seed(1239)
dumDF = data.frame(
    "Sex" = rep(c("M","F"), each = 1000),
    "Year" = sample(c("A","B"), replace = T),
    "NE" = rnorm(2000,0,5),
    "Status" = sample(c(1,2,2,2), 2000, replace = T),
    "Life" = rnorm(2000, 50, 5))

dumDF$Life = ifelse(dumDF$Sex=="M", dumDF$Life -10 + dumDF$NE, dumDF$Life+dumDF$NE)

dumDF$SurvObj = with(dumDF, Surv(Life, Status == 2))
coxdum <- coxme(SurvObj ~ Sex*NE + (1|Year), data = dumDF)

coxdum

I would like to get some guidance on how to interpret the result/output:
> coxdum
Cox mixed-effects model fit by maximum likelihood
  Data: dumDF
  events, n = 1480, 2000
  Iterations= 1 7
                    NULL Integrated    Fitted
Log-likelihood -9793.495  -9068.067 -9068.067

                    Chisq df p     AIC     BIC
Integrated loglik 1450.86  4 0 1442.86 1421.66
 Penalized loglik 1450.86  3 0 1444.86 1428.96

Model:  SurvObj ~ Sex * NE + (1 | Year)
Fixed coefficients
               coef exp(coef)    se(coef)      z       p
SexM     1.92364026 6.8458338 0.063091867  30.49 0.0e+00
NE      -0.17453933 0.8398438 0.009085403 -19.21 0.0e+00
SexM:NE -0.05491849 0.9465623 0.011945520  -4.60 4.3e-06

Random effects
 Group Variable  Std Dev Variance
 Year  Intercept 2e-02   4e-04

What I'd like to do is predict the coefficient for the range of NE, specific to either sex. I have done similarly so previously using a different sort of model, but the problem I have here is that the coxme does not give me an intercept for the group where Sex = F and it is necessary for all predictions. How can I predict the coefficent for either group/how can I get the intercept (b1)?
$ coef_{F} = b_1 + b_3 \times x$
$ coef_{M} = (b_1 + b_2) + (b_3 + b_4) \times x$
where $b_1$ is the F specific intercept, $b_2$ is the M specific intercept ("SexM") relative to $b_1$, $b_3$ is the F specific slope ("NE") and $b_4$ is the M specific slope ("SexM:NE") relative to the F specific slope.
Also how does one interpret the number (coef), given that SurvObj is the response, would a negative coefficient for NE mean that there is negative relationship between NE and survival (higher NE = short lifespan/higher rate of mortality) or negative relationship between NE and mortality (higher NE = long lifespan/lower rate of mortality)? Following from my dummy data, where I know NE is positively associated with lifespan, then I believe the coefficient would represent mortality rate, because NE is negative in the example, thus mortality rate decreases with increasing NE.
Answer: A Cox proportional hazards model does not provide an intercept like the glmm models in the page to which you linked. It is a semi-parametric model, a substantially "different sort of model" from those.
The reference for a Cox model is effectively the empirical hazard function over time, at the covariate values for the baseline class. Conceptually, you could think of that entire empirical hazard function as the "intercept." The coefficient for a predictor variable documents how that predictor affects the overall slope of the log of the hazard function, assuming proportional effects on hazards. Significance tests are properly performed on the coefficients ($\hat\beta$) and their standard errors, but in clinical use at least practical attention is more often on $exp(\hat\beta)$, which represent the hazard ratios relative to the baseline class.
You might find the documentation in the survival package or other introductory explanations to be more helpful for these basic concepts than what is provided in the coxme package.
Comment: thanks, what I am planning on doing is testing for sex differences in the slopes - I can still get these slopes (in this example it's simply comparing b3 with (b3+b4)) and to do this I am using the coefficients, and randomising NE in the data 1000 times, then taking the ratio of randomised slopes which are steeper than the actual slope as a psuedo p value... I'll take a look at the documentation you noted, thanks very much for your answer!
Comment: For sex differences in slopes with `female` as the baseline level of that factor, all you need to do is test the coefficient reported for the `male` level; that already is expressed relative to the value for `female`. In your terminology, b3 is subsumed in the baseline hazard, all you need to test is b4.
Comment: thanks @EdM - you're right, essentially I am testing whether b4 is significant... I have been using the reconstructed slope because in my actual data I have an additional two-level factor fixed effect, thus I have four slopes of interest. Would you agree that if I construct the slopes as I have done in my previous question I can then compare the slopes to one another and test by randomisation?
Comment: If you have two categorical factors each of which has two levels, then there will only be 2 coefficients from them to test in the Cox model, or 3 if you include their interaction. The baseline hazard will be for the reference value of all factors (and at a value of 0 for any continuous predictors in your model). It's not completely clear what you mean by "test by randomisation" but if you mean bootstrap resampling that would be fine. The covariance matrix of the estimated coefficient values also could allow for significance tests.


Null Behavior in Pandas DataFrame Multiplication

Question: I have a DataFrame of values to questions, vals, and a DataFrame of the weights to those questions multiply_vals. Each record in the vals DataFrame corresponds to a single user.
import pandas as pd
vals = pd.DataFrame({'A1':[0,1], 'A2':[1,2], 'A3':[3,3],'A4':[4,2],'B1':[2,1]})
multiply_vals = pd.DataFrame({'Weights':[.5,.25,.75,1,.33]}, index=['A1','A2','A3','A4','B1'])

#vals
   A1  A2  A3  A4  B1
0   0   1   3   4   2
1   1   2   3   2   1

#Multiply Vals
    Weights
A1     0.50
A2     0.25
A3     0.75
A4     1.00
B1     0.33

I want to multiply each row in vals by the correct weight multiply_vals, but there seems to be some unexpected results with nulls.
Expected result:
    A1    A2    A3  A4    B1
0  0.0  0.25  2.25   4  0.66
1  0.5  0.50  2.25   2  0.33

What I tried:
I tried using mul/multiply as well as combining it with transpose/T but it returns nulls.
vals.mul(multiply_vals.T, axis=1)

         A1  A2  A3  A4  B1
0       NaN NaN NaN NaN NaN
1       NaN NaN NaN NaN NaN
Weights NaN NaN NaN NaN NaN

Unexpected Behavior:
if I take the exact same but use .values it works.
vals.mul(multiply_vals.T.values, axis=1)

    A1    A2    A3   A4    B1
0  0.0  0.25  2.25  4.0  0.66
1  0.5  0.50  2.25  2.0  0.33

Why does .values work?
Using pandas version '0.25.0'
Answer: Define the second one as a Series as it is only one column, then multiply by its transpose:
import pandas as pd
vals = pd.DataFrame({'A1':[0,1], 'A2':[1,2], 'A3':[3,3],'A4':[4,2],'B1':[2,1]})
multiply_vals = pd.Series([.5,.25,.75,1,.33], index=['A1','A2','A3','A4','B1'])
vals*multiply_vals.T
    A1    A2    A3   A4    B1
0  0.0  0.25  2.25  4.0  0.66
1  0.5  0.50  2.25  2.0  0.33

Comment: Ah - the *why* might have something to do with `Series` versus `DataFrame`. Very interesting!
Answer: You just need the values from multiply vals
vals * multiply_vals.values.T
    A1    A2    A3   A4    B1
0  0.0  0.25  2.25  4.0  0.66
1  0.5  0.50  2.25  2.0  0.33

Comment: using `.values` returns a `np.array` which will cause `*` to do element-wise multiplication
Comment: This is a good alternative as well! It still goes NULL when we don't use `.values` though. very strange!
Answer: Try this code:
import pandas as pd
vals = pd.DataFrame({'A1':[0,1], 'A2':[1,2], 'A3':[3,3],'A4':[4,2],'B1':[2,1]})
multiply_vals = pd.DataFrame({'Weights':[.5,.25,.75,1,.33]}, index=['A1','A2','A3','A4','B1'])
vals2 = vals.transpose()
vals2.columns =['0', '1']
df_join = pd.merge(vals2, multiply_vals, left_index=True, right_index=True)
df_join['0 weighted'] = df_join['0']*df_join['Weights']
df_join['1 weighted'] = df_join['1']*df_join['Weights']
df_final = df_join[['0 weighted', '1 weighted']]
df_final = df_final.transpose()
df_final.head()

Answer: The reason DataFrame.mul and DataFrame.multiply don't work as expected is that they are referencing the names of the columns and rows to do elementwise operations. This is very useful for other purposes.
Converting to a Series with vals.mul(multiply_vals.T.values, axis=1)
or vals * multiply_vals.values.T solves the original problem.
However, if you want to make DataFrame.mul to work, you could do this:
Starting with the same DataFrames...
vals = pd.DataFrame({'A1':[0,1], 'A2':[1,2], 'A3':[3,3],'A4':[4,2],'B1':[2,1]})
multiply_vals = pd.DataFrame({'Weights':[.5,.25,.75,1,.33]}, index=['A1','A2','A3','A4','B1'])

We need to reshape multiply_vals to match the expected shape.
# copying the rows, in a somewhat silly exercise
multiply_vals_reshaped = pd.concat([multiply_vals.T, multiply_vals.T], axis=0)

# matching the index of vals
multiply_vals_reshaped.reset_index(drop=True, inplace=True)

#multiply_vals_reshaped

     A1   A2    A3    A4   B1
  0  0.5  0.25  0.75  1.0  0.33
  1  0.5  0.25  0.75  1.0  0.33

vals.mul(multiply_vals_reshaped) now behaves as expected:
     A1    A2   A3    A4   B1
  0  0.0  0.25  2.25  4.0  0.66
  1  0.5  0.50  2.25  2.0  0.33


How to implement real time application pure

Question: I am actually developing application for bank cash management.. It must be real-time... Once there is a change in db it must be sent to the client... I don't want to use long polling or ajax etc... (Because It puts load on the server by repeating requests)...
Cant use nodejs or other server related technology... (Not installed in server)... Question is that I want to develop server pure in php... Can anyone post code and give the details about it... Searched internet a lot but nothing there... Suggestions will be appreciated
[Edit]
I am putting my angularjs code for long polling here:
<code>function dataCtrl($scope, $timeout, Data) {
                $scope.data = [];

                (function tick() {
                    $scope.data = Data.query(function(){
                        $timeout(tick, 1000);
                    });
                })();
            };
</code>
and I call tick function in the following code
<code>$http.get('url').success(function(data, status, headers, config) {
                  data.response = data;
                  $('.serverStatus').text(data.response.message);
                  data.calls++;
                  $timeout(poller, 1000);
                });
              };
</code>
Comment: What exactly do you mean by "real time application" or "realtime" here? I have the impression you actually mean something else here than what is usually referred to as "realtime constraint".. Apart from that: why should ajax long calls put load on a server? They are idle until a reply is sent. You can take a look at web sockets for push notifications, but that does not really change the basic architecture underneath.
Comment: I mean just like facebook... when there is a comment/like by one user, update sent to other user at that time
Comment: You can't find anything because you can't do it in php without javascript.
Comment: I have used javascript comet/ajax.. but it sends request from my browser to server every second(or time interval).. but i only want that browser will get data when there is a change received from server
Comment: Sorry, but this is impossible to do, since the technology does not offer such thing. A browser is _not_ a server, so it cannot be contacted from outside. Also this would violate the network topology in most cases.
Comment: then how did other applications work? What thing they have implemented?
Comment: Ajax long polls are the right choice here, or mentioned web sockets. Same basic principle, and no, they do _not_ send a request every second. They hold open a channel for as long as the server allows, then reopen it. That does not add much load to a server, since those channels are inactive, except when used. There is no way around that without modifying a browser by means of a plugin.
Comment: Doesn't it put a lot of load on server... I will be requesting alot even if there is no activity on the server...  Suppose we have one million users each of them will be sending request from their browser
Answer: You must use sockets in your application... You can find Php socket library named Rachet over here
http://socketo.me/
There must be socket connection between users. So socket will listen until the data comes


OpenLdap TLS authentication setup

Question: I am trying to setup openldap on ubuntu 12.04 by following this guide
https://help.ubuntu.com/12.04/serverguide/openldap-server.html
When I tried to enable TLS on the server by creating a self signed crtificate as decribed in the guide above, I got the following error
command that I ran
ldapmodify -Y EXTERNAL -H ldapi:/// -f /etc/ssl/certinfo.ldif

Content of ldif file
dn: cn=config
add: olcTLSCACertificateFile
olcTLSCACertificateFile: /etc/ssl/certs/cacert.pem
-
add: olcTLSCertificateFile
olcTLSCertificateFile: /etc/ssl/certs/ldap01_slapd_cert.pem
-
add: olcTLSCertificateKeyFile
olcTLSCertificateKeyFile: /etc/ssl/private/ldap01_slapd_key.pem

Error Message
ldap_modify: Inappropriate matching (18)
        additional info: modify/add: olcTLSCertificateFile: no equality matching rule

After hours of searching on google, I have not found anything that tells much about this error.
Does anyone have any more information on this?
Comment: Not an answer to your question, but once you have it fixed, you may want to [force the use of SSL](http://serverfault.com/questions/459718/configure-openldap-with-tls-required).
Answer: These are SINGLE-VALUE. Use replace instead of add.
Also note, changes in the attributes may require a restart of slapd. (Not everything is a run-time configurable as we'd like.)
Your schema is probably:
attributeTypes: ( 188.8.131.52.4.1.4184.108.40.206.3.0.70 NAME 'olcTLSCertificateFile' SYNTAX 188.8.131.52.4.1.1422.214.171.124.15 SINGLE-VALUE )
attributeTypes: ( 126.96.36.199.4.1.418.104.22.168.3.0.71 NAME 'olcTLSCertificateKeyFile' SYNTAX 22.214.171.124.4.1.14188.8.131.52.15 SINGLE-VALUE )

A little explaination: ldapmodify add causes slapd to make sure you aren't putting in the attribute valie pair twice by doing an equality match. From what I can tell it should be using 22.214.171.124 NAME 'caseExactOrderingMatch', but I've not sure I've ever tried an add for these attributes. This behavior might be completely normal.

OpenLdap TLS authentication setup


How to style text as bold in facebook feed

Question: I am developing an app where the user can share some text on his facebook account. I tried to bold some sentence using html () and using **. But nothing worked. Any ideas?
Answer: That Kind of features still not provided By FaceBook API Integration Team.
Alternatively  you can create custom url pass through link in  url
<code> ShareLinkContent content = new ShareLinkContent.Builder()
    .setContentUrl(Uri.parse("your url"))
    .build();
</code>
Read more for more details Sharing on Android
Comment: Thanks. It's a shame


BOTO ResourceRecordSets object convert to string

Question: How to convert an ResourceRecordSets  to string ? I need to get like the blabla.lt, A, and 188.8.131.52 separately in strings.
It is on BOTO Route53.
Running on Ubuntu, Python 2.6.
Answer: The Boto documentation doesn't give a lot of detail about the structure of the Route53 classes. You can easily work it out however by using dir() on returned objects, for example dir(conn.get_zone("your zone."))
Eventually, you'll find that you can access all the attributes of each record object, including type, name and resource_records (In your case, the IP address).
You should end up with something like:
conn = boto.route53.connection.Route53Connection(aws_access_key_id = aws_access_key_id, aws_secret_access_key = aws_secret_access_key)

zone = conn.get_zone("your.zone.")

for record in zone.get_records():
  print "Type: %s, name: %s, values: %s" % (record.type, record.name, ",".join(record.resource_records))


How to render user posts with links but no other html?

Question: I'm building a website similar to twitter. A user can make a post and mention another user using the @username notation.
At first I was going to parse each post server side and add html tags around the @mentions, then render the post as a template.HTML (I'm using Go server side), but then I realized that users would be able to add any html they want, and I don't want that. Is there a way to render the posts as html while ignoring any html that the user tries to upload? Any code/markup that they upload should be shown in plain text.
Or will it be better to add the markup around the @mentions client side using javascript?
Comment: what is `template.HTML`?
Comment: It's a `type` in `go`. https://stackoverflow.com/questions/18175630/go-template-executetemplate-include-html
Answer: Great worry! This type of HTML injection from user input is a real problem, fortunately, there's an easy fix, you can escape HTML characters so the browser understands that there's a literal "<" character in the text, not the start of a HTML element.
In Go, there's  the html.EscapeString, which you pass the user input and then can safely use inside HTML. So you would sanitize the input and after that parse it and link the @mentions.


AngularJS $promise executes only once

Question: Is any way that $promise can execute multiple times or any alternate in angular.
Refer below code.
Sample Code:-
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}

...

if () {
     resolve('Hello, ' + name + '!');
} else {
     reject('Greeting ' + name + ' is not allowed.');
}

Answer: Yup, it will only execute only once, might be in angularJS you will not get alternative. You can try jQuery or some thing else. :)
Comment: yes, but I want this to complete only using angularJS
Answer: You could probably use the notify callback

notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected.

The following (untested) code should notify ten times with the numbers 1-10 and then resolve with the message "Done counting".
function countToTen() {
    return $q(function(resolve, reject, notify) {
        for (var counter=1; counter <= 10; counter++) {
            setTimeout(function() {
                notify(counter);
            }, 1000 * counter);
        }
        setTimeout(function() { resolve("Done counting"); }, 10001);
    });
}

Edit : as ARedHerring notices, notify isn't part of any promise standard and should be considered bad practice.
Comment: please get me any idea or sample code, by using that I can understand concept more :)
Comment: @ChetanSharma I've never used it so I'm not too sure but it is meant to track progress of the resolution of a promise. For example if you are downloading a file it will eventually succeed (resolve) or fail (reject). In the meantime, the progress can be updated by the mean of notify, which can be called multiple times to update the progress. I'll try to put up some code. However as other said, I'm not too sure it is a good idea to use your promise multiple times. Could you maybe add some context to your question?
Comment: @ChetanSharma added an example
Comment: The only problem with this is that OP will have to manually implement the notify functionality into his promise, and that the notify mechanic is non-standard behaviour. I think OP is trying to use the wrong tool for the job and should instead look into a library like highlandjs which is perfect for streams (which appears to be what he is trying to create).
Comment: @ARedHerring can you elaborate on how the notify mechanic isn't standard? While I agree OP might not be looking for the right tool, notify is well defined on both angular's deferred API and promise API.
Comment: Angular's Deferred/Promise API is [not part of the A+ promise spec](https://promisesaplus.com/), which is what I am referring to. Deferred is [considered an anti pattern](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern) for one, and having A+ compliant promise behaviour makes your application easier to reason about and interop with other libraries without any extra magic. I would avoid using `notify` for the same reason I avoid using `success`/`error` on http promises.
Comment: TLDR my point is if you're going to use something that looks and walks like a duck, it would be wise to make sure it quacks like a duck instead of barks like a dog.
Comment: @ARedHerring thank you for the answer, I'm only doing web development in my spare time and did not know of the A+ promise spec. I'll make sure to check it out !
Comment: Thanks for sharing idea on it, let me try it :)
Answer: The contract of a promise is that it will only ever resolve once, and honestly I can't really imagine any scenarios where it makes sense for it to execute more than once. After a promise has resolved, any subsequent calls to then will be invoked upon the next event loop tick as the value of the promise has already been resolved and will be cached.
This seems like an XY problem. Could you explain what you are trying to do in more detail?
Answer: You can go through this forum where Thomas has told how you can resolving a promise multiple times.
$rootScope.$apply( function() {
  deferred.resolve( incremented );
});

AngularJS $promise executes only once


How to Modify Views output on every 10th item?

Question: I have a drupal based project that uses views to output some images and markup in a loop. Each content chunk is similar so pretty standard set up. However I now have a request to uniquely modify every 10th ( or so ) content block that gets output to have a different style and markup.  I am not sure how to handle this in drupal views. Can somebody please point me in the right direction?
I don't know how many items in total would be output.
Comment: What version of Drupal and Views are you using? I'd suggest creating a template file for the row, from there you'll be able to detect the row index and make the necessary changes. Google has tons of info on it. Here is an article of interest: http://spencerhedger.com/?q=node/19
Answer: Views by default wraps each View in a div with a class based on the View's name, eg,

and each row in a div with a views-row-# class, eg,

So, quick and dirty, you could change the first 5 of these with css along the lines of
.view-NAME .views-row-10,
.view-NAME .views-row-20,
.view-NAME .views-row-30,
.view-NAME .views-row-40,
.view-NAME .views-row-50 {

   /* different CSS here */

}

You can cascade down from there if you need or want to change the CSS of any of the fields in the row as well.
If you want to get fancier, you can also add classes to each row based upon modulo arithmetic inside of the Views theme templates or via a pre_process hook and then base your css off that class.
ADDITION BASED ON COMMENTARY:
Can you do something like this with the first/last classes?  Immediately out of the box it sort of does what you want, eg:

creates output like this:

and where last-tenth in this quick and dirty copy and paste is every 10th row?
Comment: Thanks for the suggestion however on this particular site I am using sematic views and stripping out all extra drupal markup. The site files are loaded via ajax and can't have the extra drupal markup wrappers so unfortunately this approach will not work. I am looking for a way to completely do this within the views 3 interface. Is this even possible?
Comment: Added more information to answer based on your comment above.
Comment: Awsome this is exactly what I was looking for thank you so much for your help!
Comment: Jimajamma do you have any experiance with drupal panels? I am having another issue that I could use some assistance with I would be happy to pay you for your time at your going rate. I think it should be a fairly simple fix. If your interested please contact me at firstname.lastname@example.com


Concept of Probability distribution

Question: Sorry for a silly question, but it seems like only you can answer this question.
What's is the concept of Probability distribution, what's the meanining behind this term. Why we need probability function if we already have pdf (probability density function) and pmf (probability mass function). What's the new new information PD provide us with. Why we use it's definition $P(X<a)$ with less sign?
Sorry for the lack of the information.
Thanks!
Comment: It's also called a cumulative probability distribution to signify that it is actually a cumulated sum of a pdf.
Comment: Actually, the usual definition is $P(X \le x)$, so "less than or equal," not "less."
Answer: If $X$ is a random variable, then the (cumulative) distribution function $F_X(x)$ of $X$ is ordinarily defined by
$$F_X(x)=P(X\le x).$$
In the discrete case, if you know the probability mass function, you can compute the cumulative distribution function by adding.  In the continuous case, if you know the density function, you can get the cumulative distribution function by integrating.
In more advanced work, generalizations of the cumulative distribution function are more natural than generalizations of probability mass function or density function. Indeed, in some situations, suitable generalization of these is impossible. But I will try to give a partial answer to your question in more or less familiar terms, without dragging in advanced matters.
Suppose, for example, that we are trying to make a probability model of the distribution of weights of people, or of the waiting time between consecutive buses.  It is common and natural to use a continuous distribution as a model.
We are essentially never interested in the probability that the weight of a person is exactly $p$ pounds, where $p$ is a real number, like $50\pi$. For one thing, according to the model, this probability is $0$!
What we are typically interested in is the probability that the weight $W$ lies in a certain range, say greater than $200$ pounds, or between $140$ and $160$ pounds. That is information that can be easily obtained from the cumulative distribution function.
Even in the discrete case, we are often not all that interested, at the practical level, in the probability mass function. For instance, we are seldom interested in the probability that out of a population of $1000$, exactly $339$ are in favour of a certain candidate. We are more typically interested in the probability that a random variable lies in a certain range. The cumulative distribution function enables us to calculate this easily.
In later calculations, you will be interested, for example, in the distribution of a sum of two or more random variables. The cumulative distribution function will be very useful in this work.
Finally, let's make an analogy from basic physics.  If we know the acceleration at all times, and the initial velocity, we can in principle compute the velocity at all times.  So, one might ask, what's the point of having the concept of velocity?  The analogy
is actually fairly close, since if we know the density function, then in principle we know the cumulative distribution function, and part of your question kind of asks what's the point of having the concept of cumulative distribution function.
One answer, for velocity and also for cumulative distribution function, goes as follows. These notions are important,  both conceptually and at the practical level.
Answer: For a real-valued random variable $X$, let $P_X$ denote the probability distribution of $X$, meaning that $P_X (B) = P(X \in B)$, for any Borel set $B$ of $\mathbb{R}$. Particularly important is the case when $B$ is of the form $B = (-\infty, x]$, $x \in \mathbb{R}$; then $P_X (B) = P(X \in (-\infty,x]) = P(X \leq x)$. The function $F_X$ defined by $F_X (x) = P(X \leq x)$, $x \in \mathbb{R}$, is called the distribution function of $X$. Regarding your last question, it is important to note that the distribution function of $X$ is sometimes defined as the probability of $X < x$, but this is less common.
Elementary properties of a distribution function: 1) $F_X$ is monotone increasing, that is $F_X (x) \leq F_X (y)$ when $x < y$; 2) $F_X$ is right-continuous at every $x \in \mathbb{R}$, that is $F_X (y)$ approaches $F_X (x)$ as $y$ approaches $x$ from the right; 3) $F_X (x) \to 0$ as $x \to -\infty$, and $F_X (x) \to 1$ as $x \to \infty$. Further note that, for any $a,b \in \mathbb{R}$ with $a < b$, $P( a < X \leq b) = P_X ((a,b]) = F_X (b) - F_X (a)$.
It is clear from the definitions that any random variable has a probability distribution and a distribution function. A random variable $X$ has a probability density function (pdf) if and only if $X$ is absolutely continuous; $X$ has a probability mass function (pmf) if and only if $X$ is discrete. However, there are random variables which are neither absolutely continuous nor discrete. As a simple example, let $X$ be defined as follows: $X=U$ with probability $1/2$, where $U$ is a uniform$(0,1)$ random variable, and $X=1$ with probability $1/2$. Moreover, there are even continuous random variables which are not absolutely continuous (continuous singular random variables). For $X$ which is neither absolutely continuous nor discrete, the probability distribution and distribution function of $X$ are clearly essential. For example, the expectation of such $X$ can be written in terms of $P_X$ by ${\rm E}(X) = \int_\mathbb{R} {xP_X (dx)}$ and in terms of $F$ by ${\rm E}(X) = \int_{ - \infty }^\infty  {x\,dF(x)} $ (provided that the integrals converge; these formulas hold for any random variable $X$). The formula ${\rm E}(X) = \int_{ - \infty }^\infty  {x f_X (x)}\,dx$, where $f_X$ is the pdf of $X$, can be applied only to absolutely continuous random variables, and the formula ${\rm E}(X) = \sum\nolimits_k {x_k p_k } $, where $p_k = P(X=x_k)$, can be applied only to discrete random variables.
Remark: When $X$ is absolutely continuous, $F_X (x) = \int_{ - \infty }^x {f(t)\,dt}$; when $X$ is discrete, $F_X (x) = \sum\nolimits_{x{}_k \le x} {p_k } $.
Comment: The function $F_X$ is monotone *nondecreasing*.
Answer: There are probability distributions that have neither a p.d.f. nor a p.m.f. The easiest example of this would be a random variable that has both discrete and continuous behaviour simultaneously, such as a random variable with the rectified Gaussian distribution.  However, every probability distribution on $\mathbb{R}$ does have a c.d.f., and every c.d.f. uniquely determines a probability distribution.
Let's make this precise. First, we should establish some properties common to all cumulative distribution functions. Let $X$ be a real-valued random variable. Its c.d.f. is the function $F : \mathbb{R} \to [0, 1]$ given by
$$F(x) = \mathbb{P}[X \le x]$$
By the axioms for a probability measure, it is immediate that $F$ is an non-decreasing function with
$$\begin{align} \lim_{x \searrow -\infty} F(x) & = 0 & \lim_{x \nearrow +\infty} F(x) & = 1 \end{align}$$
It is also straightforward to show that $\mathbb{P}[a < X \le b] = F(b) - F(a)$. It is clear that $\lim_{b \searrow a} \mathbb{P}[a < X \le b] = 0$ while $\lim_{a \nearrow b} \mathbb{P}[a < X \le b] = \mathbb{P}[X = b]$, so we conclude that
$$\begin{align} \lim_{x \searrow a} F(x) & = F(a) & \lim_{x \nearrow b} F(x) & \text{exists} \end{align}$$
In other words, $F$ is right-continuous with all left-limits. Such a function is called càdlàg (which, despite appearances, is French, and short for continue à droite, limite à gauche).
Proposition. Every non-decreasing càdlàg function $F : \mathbb{R} \to [0, 1]$ with $F(x) \searrow 0$ as $x \searrow -\infty$ and $F(x) \nearrow 1$ as $x \nearrow +\infty$ is the c.d.f. of some real-valued random variable.
Proof. For convenience, let us extend $F$ to be a function $\mathbb{R} \cup \{ -\infty \} \to [0, 1]$, with $F(-\infty) = 0$. Then, by the adjoint functor theorem, there is a function $G : [0, 1] \to \mathbb{R} \cup \{ -\infty \}$ which is left adjoint to $F$, that is, for all $z \in [0, 1]$ and $x \in \mathbb{R} \cup \{ -\infty \}$,
$$G(z) \le x \text{ if and only if } z \le F(x)$$
and $G$ is a non-decreasing left-continuous function. [Exercise: Prove this directly without using a sledgehammer.]
Now let $Z$ be a random variable uniformly distributed on $[0, 1]$, and set $X = G(Z)$. This well-defined since $G$ is measurable. We then have
$$\begin{align*} \mathbb{P}[X \le x] & = \mathbb{P}[G(Z) \le x] \\
& = \mathbb{P}[Z \le F(x)] = F(x) \end{align*}$$
In other words, the c.d.f. of $X$ is precisely $F$, as required. (Note that $\mathbb{P}[X = -\infty] = 0$, so $X$ really is a real-valued random variable.)
Comment: Sledhehammer indeed. One can also simply *define* $G$ by $G(z)=\inf\{x\mid z\le F(x)\}$.

Concept of Probability distribution


RuntimeWarning: invalid value encountered in reduce

Question: After updating numpy to version 1.14.1 I get the following warning message after executing any command (e.g. typing 1+1):
/home/username/anaconda3/lib/python3.6/site-packages/numpy
/core/_methods.py:26: RuntimeWarning: invalid value encountered in reduce
return umr_maximum(a, axis, None, out, keepdims)

Does anyone now what the problem is and how I can fix it?
Answer: I know I'm about five months late, but my answer might be helpful to some other people.
First, the warning indicates that the matrix, that you are running reduce over or any other function that runs reduce internally, has some invalid values. These invalid values are mostly NaN or inf. I created a small snippet to explain what I mean!!
In the following snippet, I will create a variable x that has some invalid values in it, then run a function that uses reduce internally like numpy.amax().
>>> import numpy as np
>>>
>>> x = np.array([[0.2, 0.7], [np.nan, np.nan]])
>>> print(np.amax(x, axis=0))
RuntimeWarning: invalid value encountered in reduce
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
[nan nan]

So, my advice is to double check the matrix that's causing this problem.. I don't know if this is the same case with you, but it worked for me!!
In the next time, when you encounter any problem with your code... it's always a good idea to provide the code that causing the problem.
Comment: Thanks for your answers! The things is that I don't use any matrix at all. I just typed `1+1` and that's it...
Answer: because some values in your array has the value of inf or NaN. Check your array before applying further actions.
Answer: Sometimes this error has nothing to do with your original matrix. You can check and remove all nan and inf values. But if you use something like scipy.stats.kstest() and depending upon the distribution list that you give it, you can get this exact error. For example if you test the argus distribution you can get:

/site-packages/scipy/stats/_continuous_distns.py:719: RuntimeWarning:
invalid value encountered in sqrt   sk = 2*(b-a)np.sqrt(a + b + 1) /
(a + b + 2) / np.sqrt(ab)

If you test for the logistic distribution you can get:

/site-packages/scipy/stats/_continuous_distns.py:6111: RuntimeWarning:
invalid value encountered in log   lndata = np.log(data - loc)

or, also testing logistic distribution:

/site-packages/numpy/core/fromnumeric.py:86: RuntimeWarning: overflow
encountered in reduce   return ufunc.reduce(obj, axis, dtype, out,
**passkwargs)

...and many more.


What percentage of positive integers, written in base 10, are composite regardless of what base they are interpreted in?

Question: There is a sequence of numbers (OEIS A121719) with the following defenition:
If the string of base-$10$ digits corresponding to the positive integer $k$ is composite when interpreted in any possible base $b$, then $k$ is in the sequence.
After writing a program to find values of the sequence, I was curious whether the percentage of numbers $k<n$ in the sequence approaches a certain value as $n$ increases. I will now formally define my question:
$A$ is the set of all positive integers in the sequence defined above.
$$C(n)=1\:\text{if}\:n\in A,\:\text{otherwise}\:0$$
$$L=\lim_{n\to\infty}\frac{1}{n}\sum^n_{i=1} C(i)$$
I would like to know:

Does the limit $L$ exist?
Is $L>0$?
Is there some method to find $L$ or the first $n$ digits of $L$?
Comment: @Ravi, why isn't $L > \frac{3}{10} = \frac{1}{10} + \frac{4}{10}\cdot\frac{1}{2}$ (numbers ending in zero and half of numbers ending in $2,4,6,$ or $8$)?
Comment: This sequence contains all proper multiples of 10, and also all even numbers $> 2$ with even digit sum (by condition 3 from the link).  Those account for $\frac{1}{10}$ and $\frac{1}{4}$ of numbers respectively, with intersection $\frac{1}{20}$, so together that makes at least $32.5\%$ of all numbers.  So $L \geq 0.325$ if it exists (and the same is true of the lower density regardless).
Comment: By the way, the Bunyakovsky conjecture (or the stronger Bateman-Horn conjecture) would imply that conditions 1-3 are the only "reasons" that a number can be in the sequence; in fact, any number not satisfying any of those conditions should produce infinitely many primes.  But of course these conjectures are currently out of reach.
Comment: I'm sure that lower bound can be improved by applying condition 3 with more small primes.  Finding upper bounds sounds much harder.
Comment: @DavidDiaz You're right--thanks for the correction.  (I confused $\frac{1}{20}$ with $\frac{1}{40}$ in my mental calculation.)  Unfortunately I can't edit my comment anymore.
Comment: @RaviFernando You can delete and rewrite a comment :) Bunyakovsky came into my mind as well immediately
Answer: I claim that assuming the Bunyakovsky conjecture and the extended Riemann hypothesis (i.e. RH for all Dedekind zeta functions), the limit $L$ exists and equals
$$ L = \frac{59/18 + 1/5^4 + 1/7^6}{10} = \frac{4340435807}{13235512500} \approx 0.32793862776. $$
(Both of these hypotheses seem like really big hammers, but I'm pretty sure there is no easy way around either of them.)
Proof:  Identify nonnegative integers $k$ with the polynomials $f_k(x)$ whose coefficients are their base-10 expansions.  The Bunyakovsky conjecture predicts that any $f_k(x)$ not satisfying condition 2 or 3 will produce infinitely many prime values at positive integer inputs.  In particular, it will produce some primes at inputs $b$ which are large enough (say, $b \geq 10$) for $k$ to be interpreted in base $b$.  This implies, conditional on Bunyakovsky, that every term of the sequence must satisfy condition 2 or 3 from the comment on OEIS.
Let's consider condition 3.  Any common divisor of the values of $f_k(x)$ is in particular a divisor of $f_k(0)$, namely the last digit of $k$.  This implies that if the last digit of $k$ is nonzero, $k$ can never satisfy condition 3 for any prime $p > 7$.  Of course, if the last digit of $k$ is zero (and $k > 10$), then $k$ automatically satisfies condition 2.  So it suffices to consider condition 3 with $p = 2, 3, 5$, and $7$, along with condition 2.
Now consider condition 2.  It's relatively uncommon for a polynomial with small integer coefficients to be reducible.  In fact, assuming the extended Riemann hypothesis, Corollary 3 of this recent paper of Breuillard and Varjú implies that as $d \to \infty$, the proportion of degree-$d$ polynomials with $\{0, \dots, 9\}$ coefficients that are reducible is $\frac{1}{10} + O(d^{-1/2})$.  (Take $\mu$ to be the uniform distribution on $\{0, \dots, 9\}$ and $N = 1$.  The $\frac{1}{10}$ comes from polynomials vanishing at 0; i.e. integers $k$ that are divisible by 10.)  So as $k \to \infty$, we can ignore condition 2 except as it pertains to multiples of 10.
At this point, it's just a matter of going through the casework of condition 3 for $p = 2, 3, 5, 7$.  You can check that $f_k(x) = \sum_i a_i x^i$ satisfies condition 3 for a given $p$ if and only if the following two hypotheses hold:  (a) $p$ divides $a_0$, and (b) for all $0 \leq t < p-1$, $p$ divides
$$ \sum_{i > 0, i \equiv t \pmod{p-1}} a_i. $$
(Equivalently, $f_k(x)$ lies in the ideal $(p, x^p - x) \subset \mathbb Z[x]$.)  As $k \to \infty$, (b) happens with probability $1/p^{p-1}$, independently of $a_0$.  So the probability that $n$ is in the sequence given each possible last digit is as follows:

$P = 1$ (condition 2)
$P = 0$
$P = 1/2$ ($p = 2$)
$P = 1/9$ ($p = 3$)
$P = 1/2$ ($p = 2$)
$P = 1/5^4$ ($p = 5$)
$P = 5/9$ ($p = 2$ or $3$)
$P = 1/7^6$ ($p = 7$)
$P = 1/2$ ($p = 2$)
$P = 1/9$ ($p = 3$)

(Note that for $a_0 = 6$, the conditions coming from $p = 2$ and $p = 3$ are independent as $k \to \infty$.)  Averaging these ten probabilities gives the final answer.
Comment: Well, I was not expecting an exact value for the limit, so I am still delightfully surprised.
Comment: Sorry, I should have explained that.  The results in the Breuillard-Varjú paper are conditional on ERH.  I'll edit my answer.
Comment: This is an amazing answer. I am not highly knowledgeable about the extended Riemann hypothesis, though. Which part of this proof requires it to be true?
Comment: To be clear, the Breuillard-Varjú paper does all the hard work in this answer.  And my understanding of it goes no further than their results section and the Quanta article:  https://www.quantamagazine.org/in-the-universe-of-equations-virtually-all-are-prime-20181210.


File upload change name gives error

Question: <code>    $ref_id = mysql_insert_id();

$locatie = 'iso_photo/afwijkingen';

    if($_FILES['uploaded']['type'] != 'application/octet-stream')  // Geen php files
    {
        $folder = $locatie.basename($_FILES['uploaded'][$ref_id.'.jpg']) ;
        move_uploaded_file($_FILES['uploaded']['tmp_name'], $folder);
    }
</code>
Gives:
Warning: move_uploaded_file(iso_photo/afwijkingen) [function.move-uploaded-file]: failed to open stream: Is a directory
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/php6LQCqY' to 'iso_photo/afwijkingen'
What might be wrong?
Answer: edited 4th line, should work now
<code>$locatie = 'iso_photo/afwijkingen';

if($_FILES['uploaded']['type'] != 'application/octet-stream')  // Geen php files
{
    $folder = $locatie . "/" . basename($_FILES['uploaded'][$ref_id]) ;
    move_uploaded_file($_FILES['uploaded']['tmp_name'], $folder);
}
</code>
but can't properly say, as i don't know content of <code>$ref_id</code> variable

File upload change name gives error


Como criar lista simples a partir de lista composta?

Question: O que está errado aqui? Gostaria que o output fosse [123, 456, 789]:
a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
b = []

for num in a:
    x = ''
    for num2 in num:
        x.join(num2)
    b.append(x)

print(b)

Answer: Cada elemento de a é uma tupla com 3 números. Para juntá-los, você pode transformá-los em string, juntar tudo com join e converter o resultado de volta para número:
a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
b = [int(''.join(str(n) for n in numeros)) for numeros in a]
print(b)

Mas se quiser, pode também usar um pouco de matemática para transformar (1, 2, 3) em 123:
def juntar_numeros(numeros):
    return sum(n * 10 ** (len(numeros) - 1 - i) for i, n in enumerate(numeros))

a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
b = [juntar_numeros(numeros) for numeros in a]
print(b)

A ideia é usar o índice de cada elemento para saber a potência de 10 correspondente. Para isso uso enumerate, que permite obter o elemento e o respectivo índice ao mesmo tempo.
O resultado de ambos é a lista [123, 456, 789].

Nos códigos acima usei a sintaxe de list comprehension, bem mais sucinta e pythônica.
Para quem não está acostumado, pode parecer meio difícil de entender. Outro modo de fazer seria:
# transformar em string, join e converter para número depois
a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
b = []

for numeros in a:
    # map converte os números para strings, para poderem serem unidos no join
    b.append(int(''.join(map(str, numeros))))

print(b)

# solução matemática
a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

def juntar_numeros(numeros):
    result = 0
    for i, n in enumerate(numeros):
        result += n * 10 ** (len(numeros) - 1 - i)
    return result

b = []
for numeros in a:
    b.append(juntar_numeros(numeros))

print(b)


How to set the number of replicas properly when I try to start a TDengine cluster?

Question: I was wondering how to set the replica parameter properly when start a TDengine cluster to balance the storage and high availability? According to documentation of TDengine, default value of replica is 1 which means no copies for each vnode (vGroup size should be 1 as well), and the replica  can be dynamically changed to maintain a high avilability of the cluster. However, the extra vnode copies have to be generated physically when starting up multi-replica. So the problem rise up, how should a real company determine the value of replica to increase availability without taking up too much overhead(storage and performance) when using TDengine cluster?
Answer: replica means keeping a copy of the same data on multiple machines that are connected via a network. There are reasons you want to replicate data:

To keep data geographically close to your users (and thus reduce latency)
To allow the system to continue working even if some of its parts have failed (and thus increase availability)
To scale out the number of machines that can serve read queries (and thus increase read throughput)

referred from DDIA


How to calculate size of directory on FTP?

Question: How to calculate size of FTP folder? Do you know any tool or programmatic way in C#?
Answer: If you have FileZilla, you can use this trick:

click on the folder(s) whose size you want to calculate
click on Add files to queue

This will scan all folders and files and add them to the queue. Then look at the queue pane and below it (on the status bar) you should see a message indicating the queue size.
Comment: Very good solution. This way, you can get the total number of files and the total size without Downloading any file. The [FTP command](http://en.wikipedia.org/wiki/List_of_FTP_commands) used by Filezilla is MLSD (recursively) if anybody is curious about it.
Comment: Note that you need to have a valid destination selected in the local directory tree pane (otherwise _Add files to queue_ will be greyed out).
Comment: To sort the queue by size, click the "Size" column heading
Answer: You can use the du command in lftp for this purpose, like this:
echo "du -hs ." | lftp example.com 2>&1

This will print the current directory's disk size incl. all subdirectories, in human-readable format (-h) and omitting output lines for subdirectories (-s). stderr output is rerouted to stdout with 2>&1 so that it is included in the output.
However, lftp is a Linux-only software, so to use it from C# under Windows you would need to install it in the integrated Windows Subsystem for Linux (WSL) or using Cygwin or MSYS2. (Thanks to the commenters for the hints!)
The lftp du command documentation is missing from its manpage, but available within the lftp shell with the help du command. For reference, I copy its output here:
lftp :~> help du
Usage: du [options] <dirs>
Summarize disk usage.
 -a, --all             write counts for all files, not just directories
     --block-size=SIZ  use SIZ-byte blocks
 -b, --bytes           print size in bytes
 -c, --total           produce a grand total
 -d, --max-depth=N     print the total for a directory (or file, with --all)
                       only if it is N or fewer levels below the command
                       line argument;  --max-depth=0 is the same as
                       --summarize
 -F, --files           print number of files instead of sizes
 -h, --human-readable  print sizes in human readable format (e.g., 1K 234M 2G)
 -H, --si              likewise, but use powers of 1000 not 1024
 -k, --kilobytes       like --block-size=1024
 -m, --megabytes       like --block-size=1048576
 -S, --separate-dirs   do not include size of subdirectories
 -s, --summarize       display only a total for each argument
     --exclude=PAT     exclude files that match PAT

Comment: For authentication
echo "du -hs ." | lftp -u user,password hostname  2>&1
Comment: You can now use Windows Subsystem for Linux (WSL) if you are using Windows 10
Comment: alternative to cygwin is msys2
Answer: WinSCP (free GUI on Microsoft Windows):
Answer: If you just need the work done, then SmartFTP might help you, it also has a PHP and ASP script to get the total folder size by recursively going through all the files.
Comment: WinSCP does this as well
Answer: You could send the LIST command which should give you a list of files in the directory and some info about them (fairly certain the size is included), which you could then parse out and add up.
Depends on how you connect to the server, but if you're useing the WebRequest.Ftp class there's the ListDirectoryDetails method to do this. See here for details and here for some sample code.
Just be aware, if you want to have the total size including all subdirectories, I think you'll have to enter each subdirectory and call it recursively so it could be quite slow. It can be quite slow thought so normally I'd recommended, if possible, to have a script on the server calculate the size and return the result in some way (possibly storing it in a file you could download and read).
Edit: Or if you just mean that you'd be happy with a tool that does it for you, I think FlashFXP does it and probably other advanced FTP clients will as well. Or if it's a unix server I have a vague memory that you could just login and type ls -laR or something to get a recursive directory listing.
Answer: I use the FTPS library from Alex Pilotti with C# to execute some FTP commands in a few production environments. The library works well, but you have to recursively get a list of files in the directory and add their sizes together to get the result. This can be a bit time consuming on some of our larger servers (sometimes 1-2 min) with complex file structures.
Anyway, this is the method I use with his library:
///
/// <para>This will get the size for a directory</para>
/// <para>Can be lengthy to complete on complex folder structures</para>
///
/// <param name="pathToDirectory">The path to the remote directory</param>
public ulong GetDirectorySize(string pathToDirectory)
{
    try
    {
        var client = Settings.Variables.FtpClient;
        ulong size = 0;

        if (!IsConnected)
            return 0;

        var dirList = client.GetDirectoryList(pathToDirectory);
        foreach (var item in dirList)
        {
            if (item.IsDirectory)
                size += GetDirectorySize(string.Format("{0}/{1}", pathToDirectory, item.Name));
            else
                size += item.Size;
        }
        return size;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return 0;
}

Answer: Simplest and Efficient way to Get FTP Directory Size with it's all Contents recursively.

var size = FtpHelper.GetFtpDirectorySize("ftpURL", "userName",
  "password");

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

public static class FtpHelper
{
    public static long GetFtpDirectorySize(Uri requestUri, NetworkCredential networkCredential, bool recursive = true)
    {
        //Get files/directories contained in CURRENT directory.
        var directoryContents = GetFtpDirectoryContents(requestUri, networkCredential);

        long ftpDirectorySize = default(long); //Set initial value of the size to default: 0
        var subDirectoriesList = new List<Uri>(); //Create empty list to fill it later with new founded directories.

        //Loop on every file/directory founded in CURRENT directory.
        foreach (var item in directoryContents)
        {
            //Combine item path with CURRENT directory path.
            var itemUri = new Uri(Path.Combine(requestUri.AbsoluteUri + "\\", item));
            var fileSize = GetFtpFileSize(itemUri, networkCredential); //Get item file size.

            if (fileSize == default(long)) //This means it has no size so it's a directory and NOT a file.
                subDirectoriesList.Add(itemUri); //Add this item Uri to subDirectories to get it's size later.
            else //This means it has size so it's a file.
                Interlocked.Add(ref ftpDirectorySize, fileSize); //Add file size to overall directory size.
        }

        if (recursive) //If recursive true: it'll get size of subDirectories files.
            //Get size of selected directory and add it to overall directory size.
            Parallel.ForEach(subDirectoriesList, (subDirectory) => //Loop on every directory
        Interlocked.Add(ref ftpDirectorySize, GetFtpDirectorySize(subDirectory, networkCredential, recursive)));

        return ftpDirectorySize; //returns overall directory size.
    }
    public static long GetFtpDirectorySize(string requestUriString, string userName, string password, bool recursive = true)
    {
        //Initialize Uri/NetworkCredential objects and call the other method to centralize the code
        return GetFtpDirectorySize(new Uri(requestUriString), GetNetworkCredential(userName, password), recursive);
    }

    public static long GetFtpFileSize(Uri requestUri, NetworkCredential networkCredential)
    {
        //Create ftpWebRequest object with given options to get the File Size.
        var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.GetFileSize);

        try { return ((FtpWebResponse)ftpWebRequest.GetResponse()).ContentLength; } //Incase of success it'll return the File Size.
        catch (Exception) { return default(long); } //Incase of fail it'll return default value to check it later.
    }
    public static List<string> GetFtpDirectoryContents(Uri requestUri, NetworkCredential networkCredential)
    {
        var directoryContents = new List<string>(); //Create empty list to fill it later.
        //Create ftpWebRequest object with given options to get the Directory Contents.
        var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.ListDirectory);
        try
        {
            using (var ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse()) //Excute the ftpWebRequest and Get It's Response.
            using (var streamReader = new StreamReader(ftpWebResponse.GetResponseStream())) //Get list of the Directory Contentss as Stream.
            {
                var line = string.Empty; //Initial default value for line
                while (!string.IsNullOrEmpty(line = streamReader.ReadLine())) //Read current line of Stream.
                    directoryContents.Add(line); //Add current line to Directory Contentss List.
            }
        }
        catch (Exception) { throw; } //Do nothing incase of Exception occurred.
        return directoryContents; //Return all list of Directory Contentss: Files/Sub Directories.
    }
    public static FtpWebRequest GetFtpWebRequest(Uri requestUri, NetworkCredential networkCredential, string method = null)
    {
        var ftpWebRequest = (FtpWebRequest)WebRequest.Create(requestUri); //Create FtpWebRequest with given Request Uri.
        ftpWebRequest.Credentials = networkCredential; //Set the Credentials of current FtpWebRequest.

        if (!string.IsNullOrEmpty(method))
            ftpWebRequest.Method = method; //Set the Method of FtpWebRequest incase it has a value.
        return ftpWebRequest; //Return the configured FtpWebRequest.
    }
    public static NetworkCredential GetNetworkCredential(string userName, string password)
    {
        //Create and Return NetworkCredential object with given UserName and Password.
        return new NetworkCredential(userName, password);
    }
}

Answer: As the answer by @FranckDernoncourt shows, if you want a GUI tool, you can use WinSCP GUI. Particularly its folder properties dialog.

If you need a code, you can use WinSCP too. Particularly with WinSCP .NET assembly and its Session.EnumerateRemoteFiles method it is easy to implement in many languages, including C#.
It is also doable with .NET built-in FtpWebRequest, but that's lot more work.
Both are covered in How to get a directories file size from an FTP protocol in a .NET application.
Answer: You can use The FileZilla client. Download here: https://filezilla-project.org/download.php?type=client
If you want more readable size go to:
Edit -> Settings -> Interface -> filesize format -> size formatting -> select binary prefixes using SI symbols.
When you select a directory you can see its size.
Answer: Just use FTP "SIZE" command...


Best way to encode information for input to neural network?

Question: If I have a 20x20 grid of cells, each cell can take on one of four values (Red, Green, Black, Blue)
What is the best way to encode this information?
My first guess would be that one hot encoding is a good idea in this case.
Answer: There's no single "best" method, but probably the most straightforward would be to use one-hot encoding resulting with 20x20x4 tensor, where the encodings would be at the third dimension of it. Basically, this would be same as if you had images in four color scale but with the values rounded up to the extremes.
Comment: Thanks for the reply. What do you mean by 'the encodings would be at the third dimension of it'?
Comment: Also would there be any advantage/disadvantage to scaling the max values from 255 to 1?
Comment: For the case of a neural net, scaling likely wont matter but, by convention, you should to between 0 and 1. Some models are sensitive to scaling.  As explained, an easy and good method would be to one hot encode the results.  The encoding being in the third dimension just means that your color encoding is after your x (1st) and y (2nd) dimension in your grid.
Comment: @KaneM your data is categorical (?), so there's no scaling. As about third dimension, I mean 20x20 $\to$ 20x20x4, with four layers per each one-hot code.


How to add a   in a map-function in Javascript?

Question: Working in React I stumbled across this problem:
 <Grid item>
    {
        rolePriorities.map((rp, index) => (
                <Chip key={index} label={rp} color="primary" sx={{ color: "whitesmoke" }} />    //error happens here
        ))
    }
</Grid>

This doesn't work as it doesn't compile (Parsing error: Unexpected token, expected ",")
I've also tried with a +, putting it in parentheses, using the String code String.fromCharCode(160), but none of them have worked so far. It compiles with a
 around it, but I want the chips to be in the same line and not stacked on each other.
Anybody know how I could put a whitespace between the Array-items without making them stack?
Answer: You need to wrap it into a Fragment because in this way technically you are trying to return 2 children in one jsx which is not allowed.
 <Grid item>
    {
        rolePriorities.map((rp, index) => (
               <>
                <Chip key={index} label={rp} color="primary" sx={{ color: "whitesmoke" }} />

               </>
        ))
    }
</Grid>

Comment: Oh wow, I didn't know you could just do that.


Divergence of a vector field?

Question: For some vector field $F = f(x)i + g(y)j$, the divergence in $\mathbb{R}^2$ is defined by: $\frac{\partial {f}}{\partial {x}} + \frac{\partial {g}}{\partial {y}}$.
What happens if $f$ or $g$ is not differentiable anywhere? Is the divergence (or curl for that matter) defined? If it's not defined why is it still possible to still calculate the flux? Shouldn't it be impossible to calculate the flux since the flux is the sum of the infinitesimal divergences (intuitively) which are not defined?
Comment: You can define derivatives in a `weak' sense.
Comment: @user_of_math What do you mean by "weak sense"?
Comment: See http://en.wikipedia.org/wiki/Weak_derivative
Answer: Divergence can be defined for less then differentiable functions, using integration by parts against $C_c^\infty$ functions (i.e. $\int f div \phi = -\int \phi \nabla f$, where $f\in C_c^\infty$ is test function).

Divergence of a vector field?


O HTML não esta sendo exibido

Question: Tenho um campo na minha tabela que grava textos formatados em HTML corretamente. Quando estou tentando exibi-lo na tela, via TWIG usando o filtro RAW, ele continua sendo exibido como texto e não como HTML.
Notei que o TWIG está colocando uma aspas no início e no final do texto.
Como faço para exibir o HTML original?
Estou usando assim: {{ texto|raw }}.
E a saída é mais ou menos assim:

teste

Se eu peço para ver o código HTML da página, está assim:
"
teste
"

Answer: Resolvi usando o htmlspecialchars_decode(); antes de enviar para o TWIG.

O HTML não esta sendo exibido


Create Android Wear application with Xamarin

Question: I would like to start a new Android Wear project with Xamarin, but when I try to create a new project with Visual Studio for Mac I can't find the Android Wear template.
Am I Missing something?
This is my wizard:

Thanks a lot
Answer: On what version and update channel are you?
I have a template available with the current version on stable channel.
Comment: I'm also on the stable channel.
I'm using MacOs High Sierra
Comment: I am on Sierra but that shouldn't be the cause.
Answer: I found out a way to create Android Wear application on Visual Studio for Mac on macOS High Sierra:

create a blank solution (new project -> miscellanous -> blacn solution)
then right click on the solution -> add project -> Android -> Wear


WPF (or WinForm) WebView doesn't opens local URL (NotFound 404 error)

Question: Introduction
Microsoft recently released the WebView control (Microsoft.Toolkit.Win32.UI.Controls package), that allows developer to include a Webbrowser which uses Microsoft Edge to render website in WPF/WinForm application. This new control is intended to replace the old WebBrowser control which is using IE engine.
More info here
My problem
The browser doesn't seems to work with local network website urls. Even if I use ip address, I always get the NotFound (404) on my WebErrorStatus (but no exception), but in the stand-alone Edge browser it works well. However, external urls (google...) are working fine.
I've tried to check if the embeded browser uses proper proxy settings, but i've got no luck.
Answer: For security purpose, the WebView control disables private network capabilities by default. You must enable it explicitly.
wvc.IsPrivateNetworkClientServerCapabilityEnabled = true;


BPMN XOR Gateway within parallel gateway allowed?

Question: Does someone know if the following BPMN model is correct?
I'm not sure here because of XOR gateway within the parallel gateway.
Answer: After some research I found the solution.
The example above is not correct.
Instead of the normal end event, a termination event must be used. This event terminates the whole process immediately and removes all other tokens.
This would be the correct solution:


2checkout custom plugin not working with woocommerce

Question: i have added a new WooCommerce Custom Payment Gateway plugin, this plugin show me the 2checkout features in woocommerce setting page like this
![enter image description here][1]
but how can I send my product value in 2co site when user check the 2checkout option and click the place order button then what action perform in front of site
Ive attached an image of my woocommerce custom payment gateway plugin, file name is class-wc-custom_payment_gateway_1 so in this file i have use the below code
<form action='https://www.2checkout.com/checkout/purchase' method='post'>
<input type='hidden' name='sid' value='5456777' >
<input type='hidden' name='product_id' value='10' >
<input type='hidden' name='quantity' value='1' >
<input name='submit' type='submit' value='Add to Cart' >
</form>

how can i get get form value in this form which i have set in payment gateway 2checkout page
and how to redirect form value on click the place order button on site
this is my product detail and i sent the product detail on click the place order button
Thank you for your reply
Answer: When using a third party cart like WooCommerce, you do not want to create products in your 2Checkout account. You can pass your lineitem details in dynamically using the Pass Through Products parameter set or Third Party Cart parameter set.
In your custom WooCommerce module, under the generate_*your_gateway_name*_form method, you need to generate your 2Checkout form or link from the order object and output the HTML to initiate the redirect. Your custom configuration inputs would be set as properties on your custom Gateway class so they can be set and accessed like below:
```
<code>// Set Value
$this->my_property_name = $this->get_option('my_property_name');

// Get Value
$this->my_property_name;
</code>
```
You can see an example in this custom 2Checkout module I did for 2Checkout's PayPal Direct method. Feel free to use this module as a template for your own custom module.
You can also contact 2Checkout tech support directly for help at any time at email@example.com.
Answer: You need to add all the parameters which need to be send to 2co in the form with a for loop
foreach ($this->params as $name => $value) {
   echo "<input type=\"hidden\" name=\"$name\" value=\"$value\"/>\n";
}

And submit the form , I found this on 2CO Dynamic payment gateway plugin