Duvida de como raspar dados como Python usando BeautifulSoup

Question: Sou iniciante e estou tentando pegar uma tabela do site do portal da transparência, mais não estou conseguindo vem só a tag sem dado nenhum. Quando abro a ferramenta do desenvolvedor eu visualizo os dados que eu quero que são os estados e o valor de repasse, mais quando dou um ctrl+u pra o cogido o dado não aparece apedas a tag,pode estar confuso mais tem as imagens abaixo.
quando eu busco a tag no python ela aparece sem nada dentro como quando olho o código da pagina dando um ctrl+u, o que estou fazendo de errado ?

import requests
from bs4 import BeautifulSoup

page = requests.get("http://www.portaltransparencia.gov.br/funcoes/12-
educacao?ano=2018")
soup = BeautifulSoup(page.content, 'html.parser')
p = soup.find('table', class_='tabelaPrimeiroNivel')
forecast_items = p.find_all('tbody')
print(forecast_items)

Answer: O seu problema é que os dados não estão na página. Ao acessar a página, é carregada um esqueleto em branco de onde os dados devem ficar, e em seguida a página roda código javascript que faz uma solicitação separada ao servidor e então cria esses elementos dinamicamente, depois que a página foi carregada.
Como o BeautifulSoup não executa javascript, você só tem acesso à página ainda vazia, logo, não é possível pegar esses dados com ele.
Você pode verificar o que eu falei, abrindo a ferramenta de desenvolvedor e carregando a página com a aba "Network" (rede) selecionada - vai ver que a página faz várias solicitações de onde vem os outros dados dinâmicos.
Existem duas soluções possíveis:

Usar o Selenium - é uma biblioteca python que permite você controlar um navegador de verdade, como o firefox ou o chrome. Como navegadores de verdade executam javascript, você vai conseguir pegar os dados dessa forma, porém, essa solução é bem menos eficiente, pois precisa carregar um navegador pesado e vários elementos da página que não interessam.
Ler a página, examinar o código e as solicitações que ela faz via javascript, e em seguida escrever código python manualmente que imite essas solicitações. Esse método costuma dar mais trabalho, porém, o resultado é mais eficiente, uma vez que terá um código capaz de fazer somente o que é necessário para buscar os dados que você quer.

Por sorte sua, o portal da transparência possui uma API - Uma interface para programadores resgatarem os dados, sem precisar parsear as páginas. A explicação de uso está neste link http://www.portaltransparencia.gov.br/api-de-dados
Um exemplo:
r = requests.get('http://www.portaltransparencia.gov.br/funcoes/12/mapa',
    params={'ano': '2018'})
print(r.json())

Resultado:
[{'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'ACRE',
  'siglaUF': 'AC',
  'valor': 271382820.59},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'ALAGOAS',
  'siglaUF': 'AL',
  'valor': 762900876.36},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'AMAPÁ',
  'siglaUF': 'AP',
  'valor': 202949699.19},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'AMAZONAS',
  'siglaUF': 'AM',
  'valor': 704229532.02},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'BAHIA',
  'siglaUF': 'BA',
  'valor': 1800232448.53},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'CEARÁ',
  'siglaUF': 'CE',
  'valor': 1317203323.08},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'DISTRITO FEDERAL',
  'siglaUF': 'DF',
  'valor': 1702869722.04},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'ESPÍRITO SANTO',
  'siglaUF': 'ES',
  'valor': 1005278642.49},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'GOIÁS',
  'siglaUF': 'GO',
  'valor': 1300024908.65},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'MARANHÃO',
  'siglaUF': 'MA',
  'valor': 904528606.79},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'MATO GROSSO',
  'siglaUF': 'MT',
  'valor': 848977509.3},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'MATO GROSSO DO SUL',
  'siglaUF': 'MS',
  'valor': 812220959.61},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'MINAS GERAIS',
  'siglaUF': 'MG',
  'valor': 5612411096.05},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'PARANÁ',
  'siglaUF': 'PR',
  'valor': 1913617246.26},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'PARAÍBA',
  'siglaUF': 'PB',
  'valor': 1626800821.69},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'PARÁ',
  'siglaUF': 'PA',
  'valor': 1502290653.09},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'PERNAMBUCO',
  'siglaUF': 'PE',
  'valor': 1793890169.14},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'PIAUÍ',
  'siglaUF': 'PI',
  'valor': 752510959.88},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'RIO DE JANEIRO',
  'siglaUF': 'RJ',
  'valor': 5077770452.72},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'RIO GRANDE DO NORTE',
  'siglaUF': 'RN',
  'valor': 1417979764.75},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'RIO GRANDE DO SUL',
  'siglaUF': 'RS',
  'valor': 4444340585.5},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'RONDÔNIA',
  'siglaUF': 'RO',
  'valor': 334773348.77},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'RORAIMA',
  'siglaUF': 'RR',
  'valor': 226714164.22},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'SANTA CATARINA',
  'siglaUF': 'SC',
  'valor': 1531789135.42},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'SERGIPE',
  'siglaUF': 'SE',
  'valor': 622536740.58},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'SÃO PAULO',
  'siglaUF': 'SP',
  'valor': 1981995537.81},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': 'TOCANTINS',
  'siglaUF': 'TO',
  'valor': 424378306.98},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': '',
  'siglaUF': 'Nacional',
  'valor': 36308921677.23},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': '',
  'siglaUF': 'Centro-Oeste',
  'valor': 0.0},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': '',
  'siglaUF': 'Sul',
  'valor': 175660334.04},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': '',
  'siglaUF': 'Nordeste',
  'valor': 248671827.99},
 {'codigoIBGE': '',
  'nomeMunicipio': '',
  'nomeUF': '',
  'siglaUF': 'Sudeste',
  'valor': 0.0}]

Comment: obrigado pela resposta


converting coordinates given in list of tuples to complex number

Question: I have written the following code for calculating the closest pair in a plane. The code works fine but I have two questions. First, is there a shorter/better way to convert the representation of points from tuples to complex in the first function? and second, is the way I have passed the first function to the second function correct?
import sys

x = [1, 4]
y = [1, 5]

def to_complex(hor, ver):
    list_of_points = list(zip(hor, ver))
    list_of_points.sort(key=lambda el: (el[0], el[1]))
    complex_points = [complex(item[0], item[1]) for item in list_of_points]
    return complex_points

# Brute force algorithm.

def brute_force(points=to_complex(x, y)):
    n = len(points)
    if n < 2:
        return sys.maxsize
    else:
        min_distance = sys.maxsize
        for i in range(n):
            for j in range(i + 1, n):
                if abs(points[i] - points[j]) < min_distance:
                    min_distance = abs(points[i] - points[j])
                    closest_pair = (points[i], points[j])

return min_distance, closest_pair

print(brute_force())

Comment: If the code is already working, [codereview.se] may be a better site to post it.
Comment: But note that [cross-posting is not allowed](https://meta.stackexchange.com/questions/64068/is-cross-posting-a-question-on-multiple-stack-exchange-sites-permitted-if-the-qu).
Comment: As a side note: if your elements are all 2-tuples, `(el[0], el[1])` is just the same value as `el`, so why write a key function that just turns `el` into the same tuple?
Comment: Also, it's a bit confusing to call the elements of a list `el` in one line, and then call the elements of the same list `item` in the next. It forces the reader to stop and verify that they really are iterating the same thing, rather than seeing what your code is actually doing.
Answer: A shorter version of complex(item[0], item[1]) is complex(*item), which splats a sequence into separate arguments. And I think this is a little better because it will explicitly fail on tuples longer than 2 items.
But it might be even clearer to just write item[0] + item[1] * 1j. Besides looking like the way you write a complex number, this also avoids the implicit conversion to float that allows complex(…) to silently work on things like Decimal objects or sympy constant-valued expressions—you'll get an error in the first case, and a sympy complex constant-valued expression in the second. (Of course if you want to coerce things to complex values, that's a negative rather than a positive.)
Answer: You can write your algorithm as follows
# Brute force algorithm.
def brute_force(hor, ver):
    # Convert points to complex
    points = [complex(x, y) for x, y in zip(hor, ver)]
    n = len(points)

    min_distance = sys.maxsize
    closest_pair = None
    if n < 2: return min_distance
    else:
        for i in range(n):
            for j in range(i+1, n):
                temp = abs(points[i] - points[j])
                if temp < min_distance:
                    min_distance = temp
                    closest_pair = (points[i], points[j])
    return min_distance, closest_pair

x = [1, 4, 3, 1]
y = [1, 5, 1, 5]

brute_force(x,y)


Possible options for single language site other than English?

Question: What are the possible options for having a single language non-English site? I am thinking of performance mostly.
I don't want prefix or suffix in urls. I don't preferably want entity language (Language neutral possible in Drupal 8)
Adding a second language, deleting English? Will this have implications?
Answer: For a Single Language non English site, When you install Drupal 7, it gives you option of selecting the Language. Plus you will need to download the language PO files for your language.
But if you are using Drupal 8 the only requirement is selecting correct language when you install your Drupal. Drupal 8 will automatically download all the language files for you.
Comment: No, that is not true, there isn't a query per string or at least only the first requests. This is cached in a single entry. There is no other way, this is the recommend and more or less only way.
Comment: Thanks, but performance-wise this is no different than adding a second language, and setting it as default. I am searching for a better way if possible.
Comment: May I know what performance considerations you have for this?
Comment: Basically, for every translated string to be rendered, there is a query from the database to get that string translation. I wonder if there is an easy way to overcome this. There is a discussion about the subject here: https://groups.drupal.org/node/149984


Design a DFA to check whether the Given Number is Even

Question: I have the following question

I have designed the following

A Binary String is even if it is ending with 0 and odd if its ending with 1.I have applied this.Im i right ?
UPDATE:
Comment: First, this isn't a DFA: there's no $0$ transition from $q_2$. Secondly, it accepts the input $1$, which is odd.
Comment: @BrianM.Scott Okay.So for a DFA there should be a transition from every state for each input symbol.
Comment: Yes, that's correct.
Comment: @BrianM.Scott well i made a blunder.I thought it should end with a 1 to be even when creating the DFA in that case is the diagram partially correct.
Comment: But if you're testing for even numbers, you want to accept the inputs that end in $0$, not $1$.
Comment: Looks better with the update
Comment: @BrianM.Scott I know.. i wrote so.. but did not think so while creating the DFA.Please see the update.
Comment: @techno: Yes, the revised version is fine.
Comment: @BrianM.Scott alright.Thanks
Comment: @techno: You're welcome.
Answer: Your answer is incorrect. It rejects strings that are even and therefore should be accepted, like $1100$, and accepts strings that are odd and therefore should be rejected, like $1$.
The correct automaton needs to remember whether the last character read was $1$ or $0$, so we need two states: the initial state and an accepting state. When a $0$ is read, transfer to the accepting state or remain there if we were in the accepting state already. When a $1$ is read, transfer to the initial state or remain there if we were in the initial state already.
When the entire string has been read, if the last character was $0$, we'll be in the accepting state and we'll accept the string as even. If the last character was $1$, we'll be in the initial state and reject the string as odd.
UPDATE: apart from the missing initial state annotation, it looks correct after your update. Well done!
Comment: Please see the updated question.


Slopegraph with too many observations

Question: Currently, I am studying the book "storytelling with data - Cole Nussbaumer Knaflic" to learn about data visualization. Now I am learning why the slope graph can be very helpful. If you have too many observations it could become a mess. The book says the following:

If many of the lines are overlapping, a slopegraph may not work,
though in some cases you can still emphasize a single series at a time
with success.

I can imagine that with 100 observations, a slopegraph can become a little bit of a mess. Unfortunately, the book doesn't tell a good alternative for that problem. Here is a reproducible example:
<code>set.seed(7)
df <- data.frame(status = rep(c('pre', 'post'), each = 100),
                 value = runif(200, 0, 1),
                 group = rep(c(1:100), n = 2))

library(ggplot2)
ggplot(df, aes(x = factor(status), y = value, group = group)) +
  geom_point() +
  geom_line() +
  labs(x = 'Status') +
  theme_classic()
</code>

Created on 2022-12-14 with reprex v2.0.2
So I was wondering what could be a good alternative to a slopegraph to show many observations while keeping the same information as a slopegraph offers?
Comment: Have you considered a standard scatterplot of (pre, post) observations?
Comment: @Quinten Note that the plot is simply showing a set of differences as slopes (taking pre-post distance on the x-axis as 1). That visual comparison of slopes may be better done as their raw values (post-value-pre-value). Beyond that, but in a similar vein, a Tukey mean/difference  plot may be relevant (medical people tend to call it a Bland-Altman plot)
Comment: What do you want to show ultimately with your graph?
Comment: The term "slope graph" is from Edward Tufte, but the idea is much older under names like profile plot or parallel coordinates, and indeed tacit in any plot of two or more time series. But slope graphs have point largely to the extent that (1) each object is named so that you can follow changes using subject-matter knowledge  (2) there is an intelligible pattern or at least some interesting details. If (1) is absent, (2) must be true for such a plot to be useful, The example is random noise, but they key question is then what holds for anyone's real data.
Comment: Hi @JJJ, I would like to show the change from pre to post, so what the changes are.
Answer: Answered in comments:

Have you considered a standard scatterplot of (pre, post)
observations?
– whuber

Note that the plot is simply showing a set of differences as slopes
(taking pre-post distance on the x-axis as 1). That visual comparison
of slopes may be better done as their raw values
(post-value-pre-value). Beyond that, but in a similar vein, a Tukey
mean/difference plot may be relevant (medical people tend to call it a
Bland-Altman plot)
– Glen_b

Slopegraph with too many observations


An equality involving the Wiener process

Question: The equality below appears as a step in a proof in a chapter titled "Itô Stochastic Calculus" in Brzeźniak and Zatawniak's textbook "Basic Stochastic Processes", Springer 2005 (in a solution to exercise 7.10 on p. 216). I don't understand why the equality holds and would appreciate an explanation.
Let $W$ be a one dimensional Wiener process, let $T > 0$ be a strictly positive real number and for some natural number $n \in \{1, 2, \dots\}$ let $0 = t^n_0 < t^n_1 < \cdots < t^n_{n - 1} < t^n_n = T$ be a partition of the real interval $[0,T]$ into $n$ sub-intervals $[t^n_i, t^n_{i + 1}]$, each of length $T/n$. Then
$$
E\left(\left|\sum_{i=0}^{n-1}\int_{t^n_i}^{t^n_{i+1}}\left(W(t^n_i) - W(t)\right) dt\right|^2\right) = \sum_{i = 0}^{n - 1} \int_{t^n_i}^{t^n_{i+1}}E\left(\left|W(t^n_i)-W(t)\right|^2\right) dt
$$

EDIT
I'm not really interested in this equality per se. The ultimate purpose of the chain of equalities, of which this equality is one link, is to show that
$$
E\left(\left|\sum_{i=0}^{n-1}\int_{t^n_i}^{t^n_{i+1}}\left(W(t^n_i) - W(t)\right) dt\right|^2\right) \underset{n \rightarrow \infty}{\rightarrow} 0
$$
Answer: Edit: This answer shows the identity
$$\mathbb{E} \left( \left| \sum_{i=0}^{n-1} \int_{t_i^n}^{t_{i+1}^n} (W(t_i^n)-W(t)) \, dt \right|^2 \right) = \mathbb{E} \left( \sum_{i=0}^{n-1} \left[\int_{t_i^n}^{t_{i+1}^n} (W(t_i^n)-W(t)) \, dt\right]^2 \right). \tag{1}$$

Fix $i<j$. Then, by the tower property,
$$\begin{align*} &\mathbb{E}((W(t_i^n)-W(t))(W(t_j^n)-W(s))) \\ &= \mathbb{E} \bigg[ (W(t_i^n)-W(t)) \cdot \mathbb{E}(W(t_j^n)-W(s) \mid \mathcal{F}_{t_{i+1}^n}) \bigg] \tag{2}\end{align*}$$
for any $s \in [t_j^n,t_{j+1}^n]$ and $t \in [t_i^n,t_{i+1}^n]$. Since $(W_t)_{t \geq 0}$ is a martingale, we have
$$\mathbb{E}(W(t_j^n)-W(s) \mid \mathcal{F}_{t_{i+1}^n})=0.$$
Consequently, $(2)$ yields
$$ \mathbb{E}((W(t_i^n)-W(t))(W(t_j^n)-W(s)))=0. \tag{3}$$
Using the identity
$$\left( \sum_{i=1}^n a_i \right)^2 = 2 \sum_{j=1}^n \sum_{i<j} a_i a_j + \sum_{i=1}^n a_i^2$$
and Fubini's theorem, we conclude
$$\begin{align*} &\mathbb{E} \left( \left| \sum_{i=0}^{n-1} \int_{t_i^n}^{t_{i+1}^n} (W(t_i^n)-W(t)) \, dt \right|^2 \right) \\ &=2 \mathbb{E} \left( \sum_{j=0}^{n-1} \sum_{i=0}^{j-1} \int_{t_i^n}^{t_{i+1}^n} \int_{t_j^n}^{t_{j+1}^n} (W(t_i^n)-W(t))(W(t_j^n)-W(s)) \, ds \, dt \right) \\ &\quad + \mathbb{E} \left( \sum_{i=0}^{n-1} \left[ \int_{t_i^n}^{t_{i+1}^n} (W(t_i^n)-W(t)) \, dt \right]^2 \right) \\ &\stackrel{(3)}{=} \mathbb{E} \left( \sum_{i=0}^{n-1} \left[\int_{t_i^n}^{t_{i+1}^n} (W(t_i^n)-W(t)) \, dt\right]^2 \right). \end{align*}$$

Remark: Since
$$\left| \int_{t_i^n}^{t_{i+1}^n} (W(t_i^n)-W(t)) \, dt \right| \leq 2\sup_{t \in [0,T]} |W(t)| \cdot \frac{1}{n},$$
$(1)$ shows in particular
$$\begin{align*} \mathbb{E} \left( \left| \sum_{i=0}^{n-1} \int_{t_i^n}^{t_{i+1}^n} (W(t_i^n)-W(t)) \, dt \right|^2 \right) &\leq 4  \mathbb{E} \left( \sup_{t \in [0,T]} |W(t)|^2 \right) \frac{n}{n^2} \\ &\stackrel{n \to \infty}{\to} 0. \end{align*}$$
Comment: @EvanAad By Fubini's theorem, we have $$\mathbb{E} \left( \sum_j \sum_{i<j} \int \int \ldots \right) = \sum_j \sum_{i<j} \int \int \mathbb{E}(\ldots).$$ By $(2)$, we know that $\mathbb{E}(\ldots)=0$ for any $i<j$.
Comment: @EvanAad Argh, sorry... obviously, I really should go to sleep. Better now? (If not, I'll have a look at it tomorrow... sorry again.)
Comment: Thank you. I understand almost all of your answer except how equation (2) is used to justify the very last step.
Comment: Thanks, I get it. But now that I think about it, there's one more thing I don't understand in your answer, namely, where did the summand $\mathbb{E} \left( \sum_{i=0}^{n-1} \int_{t_i^n}^{t_{i+1}^n} (W(t_i^n)-W(t))^2\right)$ come from?
Comment: @EvanAad Note that $$\left( \sum_{i=1}^n a_i \right)^2 = 2 \sum_{j=1}^n \sum_{i<j} a_i a_j + \sum_{j=1}^n a_j^2.$$
Comment: But this formula only accounts for a term of the form $\mathbb{E} \left( \sum_{i=0}^{n-1} \left(\int_{t_i^n}^{t_{i+1}^n} W(t_i^n)-W(t) \, dt\right)^2 \right)$, not one of the form $\mathbb{E} \left( \sum_{i=0}^{n-1} \int_{t_i^n}^{t_{i+1}^n} (W(t_i^n)-W(t))^2 \, dt \right)$.
Comment: @EvanAad You are right, there is something off; sorry. How does the proof continue? Do you really need this equality? (Or is it enough to have some estimate?)
Comment: Actually, I have an idea. I think the two forms I mentioned in my previous comment are equal due to [Itō's isometry](http://en.wikipedia.org/wiki/It%C5%8D_isometry), are they not?
Comment: @EvanAad In order to apply Itô's isometry, we need a stochastic integral, i.e. $$\int_{t_i^n}^{t_{i+1}^n} (W(t_i^n)-W(t)) \, d\color{red}{W_t}$$
Comment: Oh, I see. Anyhow to answer your question, no, I don't really need this equality. The ultimate purpose of the chain of equalities, of which the equality I presented in my original post is one link, is to show that $E\left(\left|\sum_{i=0}^{n-1}\int_{t^n_i}^{t^n_{i+1}}\left(W(t^n_i) - W(t)\right) dt\right|^2\right) \rightarrow 0$ as $n \rightarrow \infty$.
Comment: @EvanAad I see. Have a look at my edited answer.
Comment: Thanks. But doesn't your remark only show that almost surely $\left| \sum_{i=0}^{n-1} \int_{t_i^n}^{t_{i+1}^n} (W(t_i^n)-W(t)) \, dt \right|^2 \rightarrow 0$?
Comment: Yes, now it works, thanks to [Doob's Maximal Inequality](https://fabricebaudoin.wordpress.com/2012/04/10/lecture-11-doobs-martingale-maximal-inequalities/). Thank you so much. Good night!


It's true that policy file in drush prevents sql-sync from local to prod?

Question: I know in the policies file in drush there was/is a way to prevent sql-sync'ing from local to prod.
Is this still true? If so how do you go about this?
Answer: Yes this is still true you can find the relevant snippet in the drush source code:
<code>/**
 * Implement of drush_hook_COMMAND_validate().
 *
 * Prevent catastrophic braino. Note that this file has to be local to the machine
 * that intitiates sql-sync command.
 */
function drush_policy_sql_sync_validate($source = NULL, $destination = NULL) {
  if ($destination == '@prod') {
    return drush_set_error(dt('Per examples/policy.drush.inc, you may never overwrite the production database.'));
  }
}
</code>
You should include the policy.drush.inc in your .drush folder usually located in the users home folder.
Comment: Can you add this to the server to enforce the policy?
Comment: No, as per the comment this has to go on the machine that executes the command.
Comment: Can this be added to a module in the drupal site?
Answer: The first thing you must decide is where would you like to keep the policy file, and this really depends on your purpose for creating the policy file in the first place. If you are just wanting to prevent yourself from doing something crazy by accident, or if there is special functionality for you, you can add the policy to the .drush directory inside your home directory.
If you are wanting to have a different policy for different sites or Drupal installs, you might think about adding the policy file to the /sites/all/drush directory; this also makes it handy for versioning the file. To have a global policy file that will work for all sites and users on a server, your best bet is to put the policy file in the /usr/share/drush/command directory.
Each of these directories is valid though they aren't inclusive, meaning that if you have a file in your /sites/all/drush directory, the settings here will overwrite the settings you may have in your ~/.drush directory. Likewise, the policy file in the /usr/share/drush/command directory will overwrite any other policy file, which is what we want, so someone can't circumvent restrictions by creating their own policy.drush.inc file and adding it to their home directory.
Example of policy.drush.inc file:
<code><?php
/**
 * Implementation of drush_hook_COMMAND_validate().
 */
function drush_policy_sql_sync_validate($source = NULL, $destination = NULL) {
  if ($destination == '@prod') {
    return drush_set_error(dt('Permission denied! You almost overwrote the production database you moron!'));
  }
}
</code>
See also:

examples at policy.drush.inc API page,
Limiting Drush access with a policy configuration


How can I raise the maximum upload file size?

Question: I set up private file directory at /var/www/private to keep upload files from webform and setup permission on directory and files (664 for files, 775 for directories). When I click on upload button and select file, it throw an exception -

 "An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (32 MB) that this server supports."
Solution is running on Drupal 8.3 on VM (Vagrant). Below is screen capture of error message

Appreciate if you have an answer of this bug
Answer: This is not particular to the Drupal site but is caused by the hosting (local Vagrant) environment's PHP configuration.
Try increasing these values in php.ini:
<code>upload_max_filesize = 64M
post_max_size = 64M
memory_limit = 64M
</code>
NOTE: If you are using Webform for anonymous file upload to your site and you are setting high limits on file size like this you are quickly going to fill up a lot of disk space (most likely with spam).
NOTE: After modifying php.ini file(s), you need to restart your HTTP server to use new configuration
See answer on Stackoverflow.
Comment: After resize post_max_size = 64M, its throw same exception. The values in php.ini: memory_limit = 192M, upload_max_filesize = 64M, and post_max_size = 64. Any suggestion ?
Comment: Now I got this error "An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (64 MB) that this server supports." I select few kilobyte size of file but showing exceeded 64 MB. There must be a bug on webform. When I navigate private directory 'var/www/private' I saw there are subfolders created by application 'var/www/private/webform/formname/_sid_/. I wonder whats made  exceeded 64 MB when the file size is just few kilobytes. Appreciate if you share your experience. Thank you
Comment: @Bhagi have you resolved this problem? I'm in the same situation
Comment: Same issue with me
Comment: If you have restarted your webserver the new values should load, but some hosts limit access to changing these settings. Try confirming that your changes have "taken" by getting the output of `ini_get ('upload_max_filesize')` and the others.


OCSP validation without issuer certificate

Question: I am currently developing an application that validates signature certificates (like in a pdf) with OCSP or CRL. These will most likely be leaf certificates, without the entire chain. Getting the url to either validation services proved simple enough.
To my understanding, both OCSP and CRL require the issuer of the certificate to validate it. So now I'm stuck because that is not included in the input. The AIA extension might include a URL to a CA certificate, but unfortunately this is the CA of the issuing certificate and not the certificate itself.
Is there any other way to get the issuer's certificate given only the leaf? Or are there some cases in which OCSP/CRL can validate without it?
Comment: did you happen to figure out a workaround to this? I'm in the exact same position and was wondering if there are any alternatives
Answer: Have a look at https://www.ietf.org/rfc/rfc2560.txt  which details the requirements for an OCSP response to be considered valid:

The key
    used to sign the response MUST belong to one of the following:
-- the CA who issued the certificate in question
-- a Trusted Responder whose public key is trusted by the requester
-- a CA Designated Responder (Authorized Responder) who holds a
       specially marked certificate issued directly by the CA, indicating
       that the responder may issue OCSP responses for that CA

The first and third option both require the issuer cert. The second option does not. However I dont think that option is applicable to you situation. The link https://wiki.mozilla.org/CA:OCSP-TrustedResponder has details on what a trusted responder is and when it can actually be used.


Image is loaded much too big

Question: I have a nexus 7 tablet with 1900 x 1200 resolution. I try to create an ImageButton with wrap_content but the created ImageButton is much too big and i dont know why.
This is the layout i use:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/gradient" >

    <ImageButton
        android:id="@+id/main_button_fog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/custom_button_fog"
        android:contentDescription="@string/imageview_description"
        android:scaleType="centerInside" />

</RelativeLayout>

When i start my Application it looks like that:

As a reminder: the width of nexus 7 tablet is 1200 px. The with of my image is 397 px so it should be much smaller. Why is the Image loaded here so big?
Comment: you probably want to use `android:src` instead of `android:background` (scaleType works on `src`, not on `background`)
Answer: I didn't try this, but i think that it can work. But if i can say a thing, put the value of width and height as wrap_content if you want that image will have the maximum dimensions is not useful. If you want to scale the image as the size of the screen you have to use also Java part. Tell me if this doesn't  work by the way.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient" >

<ImageButton
    android:id="@+id/main_button_fog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="android:color/transparent"
    android:src="@drawable/custom_button_fog"
    android:contentDescription="@string/imageview_description"
    android:scaleType="fitCenter" />
</RelativeLayout>

Comment: its this + the answer of @user1194268. so i also had to place the views in xhdpi folder

Image is loaded much too big


What are the photo gallery/album module choices?

Question: I am looking to make a Flickr like site that user can create albums, upload photos.
With Drupal 6, this can be easily done by CCK, Node Reference, Views.
For Drupal 7, it seems difficult since Node Reference is not available yet. (There is a module called Reference, but it only has a development snapshot release.)
So are there any modules that can achieve the ugc photo albums functionality?
Thanks.
Comment: I'm voting to close this question because it's asking for recommendations or suggestions on hosting, tools, modules, themes, distributions, books, tutorials, documentation, or other off-site resources.
Answer: An album essentially is a grouping of like nodes.
In drupal this grouping can be done a number of ways. I would suggest using a fixed taxonomy (not free tagging) for the album. This way views can list list all photos (nodes) from a particular tag and you can create thumbnails for instance for display.
You could also group by author for another group of nodes (e.g. 'my photos')
Answer: There's the Media Gallery module. Haven't used it so I'm not sure how good its Views integration is. Here is an excerpt about it from the module's project page:

Uses the Media module to provide a rich media gallery. It currently supports images and YouTube videos well. Other file types may or may not work as well, but the facility is there to add them.
Comment: I tried media_gallery, but it requires some modules that I can't find:  File_styles, Multiplatform.
Answer: Field Permissions should be able to do it.
I am using the 7.x version; I have not used it to set View Own content, but to block others from viewing it. It should be viable, though.  Use this with a content type and an image field module of your choice and it might do what you want it to do.


How to manage JSON data in javascript pass form django model?

Question: I need to dynamically display my audio on my website. The audio is a file path stored in the Django model.
Djanog Model:
class audio(models.Model):
instrumentId = models.OneToOneField(instrument, on_delete=models.CASCADE, primary_key=True)
location = models.FileField()

I pass the data through view.py into json data so my script can read the data.
view.py, PostJsonListView fetch data form the model and generate json data, testView connect to the html displaying audios
class PostJsonListView(View):
def get(self, *args, **kwargs):
    print(kwargs)
    #upper is to get the number from the js file to set a upper boundry
    upper = kwargs.get('num_aduios') #intial state be 3
    lower = upper - 3
    #pass in the audio in to the list [lower:upper] use to set boundry
    audios = list(audio.objects.values()[lower:upper])

    #comfirmation of no more audi to load
    audio_size = len(audio.objects.values())
    size = True if upper >= audio_size else False
    return JsonResponse({'data':audios, 'max': size}, safe=False)

class testView(TemplateView):
    template_name = 'frontend/testView.html'

JSON data in browser
Javascript that hand the data, after a button click, it would display three more data
    console.log('HELLO')
const aduiosBox = document.getElementById('audio-box') //get the div audio-box
const nextBtn = document.getElementById('next-btn')

let visible = 3
const handleGetData = () =>{
    $.ajax({
    type: 'GET',
    url: `/json/${visible}/`,
    success: function(response)
    {
        max_size = response.max
        //getting all the data and display in the console
        const data = response.data
        data.map(post=>{
            console.log(post)
            aduiosBox.innerHTML +=
            //how to get the location right?
            `

                <audio controls>
                <source src= ${post.location} type="audio/wav">
                </audio>

            `

        })
        //check if the display size reach maxium
        if(max_size){
            console.log('done')
        }
    },
    error:function(error){
        console.log(error)
    }
    })

}

handleGetData()
//event listenrs
nextBtn.addEventListener('click', ()=>{
    visible += 3
    handleGetData()

})
Console on the browser
Here, the audio path was from home/sound1.wav. From my another exmaple, where I also path audio object, has the path of /sounds/sounds1.wav
view.py for the working example
def survey(request):
if request.method == 'POST': #if something is post to the server, reference to HTML form method == post
    form = rateForm(request.POST)
    if form.is_valid():
        form.save()

form = rateForm()
wavFile = audio.objects.all()
return render(request, "frontend/audio.html",{
    'wavFile': wavFile,
    'form': form,
})

Working example
File path of my Django app
In conclusion, I belive the website cannot get to the file path correctly. home/sound1.wav VS sounds/sound1.wav. How can I manage it so the Javascript code can get to the correct path to get the audio to display in the website?
Answer: I solved it by correcting the directory of my audio file. For anyone that is wondering the something, you should look at what have done to your setting.py for the directory of storing data you wanted to access


Pandas IF statement referencing other column value

Question: I can't for the life of me find an example of this operation in pandas.... I am trying to write an IF statement saying IF my Check column is true then pull the value from my Proficiency_Value column, and if it's False, then default to 1000.
report_skills['Check'] = report_skills.apply(lambda x: x.Skill_Specialization in x.Specialization, axis=1)
report_skills = report_skills.loc[report_skills['Check'] == True, 'Proficiency_Value'] = 1000

Any ideas why this is not working? I'm sure this is an easy fix
Comment: `np.where(report_skills['Check'] == True,report_skills['Proficiency_Value'],1000)`?
Comment: for future, you can reference this link ... https://datatofish.com/if-condition-in-pandas-dataframe/
Answer: Let`s create a small example DataFrame like this:
import pandas as pd
import numpy as np

df = pd.DataFrame({'Check':[True,False, False ,True],
                   'Proficiency_Value':range(4)
                  })

>>> df
   Check  Proficiency_Value
0   True                  0
1  False                  1
2  False                  2
3   True                  3

If you use now the np.where() functione, you can get the result you are asking for.
df['Proficiency_Value'] = np.where(df['Check']==True, df['Proficiency_Value'], 1000)

>>> df
   Check  Proficiency_Value
0   True                  0
1  False               1000
2  False               1000
3   True                  3


Bartik's code - manage logo and favicon

Question: I want upload an image for my theme, like the logo or favicon with bartik (or other theme).
Where's the code for doing that with bartik ? (it's not in bartik/theme-settings)
In fact, i want this features : The user choose his background like the logo
Thanks.
Answer: If you just want to show the logo or the screenshot of the theme in your drupal site, just replace your own images with the logo.png or screenshot.png in yoursite/themes/bartik/, remember you have to name them 'logo.png' or 'screenshot.png' exactly.
Not sure if this is what you want. Good luck.
Comment: Thanks for your answer, but it's not that.

Where is the code that allow you to create a new input form like logo or favicon : like background or banner for example.

The user choose his background like the logo.

Thanks

Bartik's code - manage logo and favicon


C: Heap Buffer Overflow when Storing Elements Using Dynamic Memory Allocation

Question: I am writing a C program to store and then print out all strings given through stdin using dynamic memory allocation.
It prompts the user for input until it reads "end of file" (EOF, ctrl + d).
I am assuming that no line is longer than 255 characters.
I am relatively new to coding in C, and also new to using the malloc() function, so please bear with me if I am making some obvious, rookie mistake. Please offer advice and help me fix my program. :)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER 255

int main(void)
{

    char line[BUFFER];
    int item = 0;
    char** data = malloc(sizeof(char*));

    for(;;)
    {
        printf("Enter string %d: ", item + 1);

        if (fgets(line, BUFFER, stdin) == NULL)
        {
            break;
        }

        else
        {
            fgets(line, BUFFER, stdin);
        }

        data = realloc(data, sizeof(void *) * (item + 1));
        data[item] = malloc(sizeof(char) * strlen(line));
        memcpy(data[item], line, strlen(line));

        item++;

    }

    printf("\n\nElements:\n");

    for(int j = 0; j < item; j++)
    {
        printf("%s",data[j]);

        free(data[j]);
    }

    free(data);

    return 0;
}

The first concern I have is that my program prompts the user twice to enter a string input per item increment. This is not supposed to happen, and should continually ask the user while updating item's count.
Also, my program does not store the strings entered correctly; it returns a buffer overflow message when attempting to access and print my stored strings. I have never seen an error quite like it before:
==20==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000052 at pc 0x55a8453c7865 bp 0x7ffd578edac0 sp 0x7ffd578ed280
READ of size 3 at 0x602000000052 thread T0
#0 0x55a8453c7864 in printf_common(void*, char const*, __va_list_tag*) asan_interceptors.cpp.o
#1 0x55a8453c819a in __interceptor_vprintf (/home/run+0xb119a) (BuildId: abfaad925a09237bc199a1c2ac9a7d328268e42f)
#2 0x55a8453c8277 in printf (/home/run+0xb1277) (BuildId: abfaad925a09237bc199a1c2ac9a7d328268e42f)
#3 0x55a84543014d in main /home/main.c:39:9
#4 0x7f08c84fe28f in __libc_start_call_main /usr/src/debug/glibc/csu/../sysdeps/nptl/libc_start_call_main.h:58:16
#5 0x7f08c84fe349 in __libc_start_main /usr/src/debug/glibc/csu/../csu/libc-start.c:381:3
#6 0x55a845337084 in _start /build/glibc/src/glibc/csu/../sysdeps/x86_64/start.S:115
Comment: @user3121023 I have changed this line and the problem persists. Thank-you for pointing it out, though!
Comment: @Akiyuu You *also* need to terminate the string.  `data[item] = malloc(sizeof(char) * ( strlen(line) + 1));` is insufficient.  Replace `memcpy()` with `strcpy()`.
Comment: @user3121023 these two changes actually fixed my code altogether! Thank-you so much :D
Answer: getline is useful when the length of the longest line is unknown. It will allocate memory as needed. It also returns the number of characters processed.
It is good to reallocate to a temporary pointer. If realloc fails, the original pointer is still valid.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ( void) {

    char *line;
    size_t size = 0;
    ssize_t length = 0;
    int item = 0;
    char** data = NULL;

    for ( ; ; ) {
        printf ( "Enter string %d: ", item + 1);
        fflush ( stdout);

        if ( 0 > ( length = getline ( &line, &size, stdin))) {
            break;
        }

        char **temp = NULL;
        if ( NULL == ( temp = realloc ( data, sizeof *data * (item + 1)))) {
            fprintf ( stderr, "realloc problem\n");
            break;
        }
        data = temp;
        if ( NULL == ( data[item] = malloc ( sizeof **data * ( length + 1)))) {
            fprintf ( stderr, "malloc problem\n");
            break;
        }

        strcpy ( data[item], line);

        item++;
    }

    free ( line);

    printf("\n\nElements:\n");

    for(int j = 0; j < item; j++) {
        if ( data[j] && data[j][0]) { // not NULL and not zero
            printf ( "%s", data[j]);
        }
        free(data[j]);
    }
    free(data);

    return 0;
}


Pair computer and phone with USB cable once, and then always use ADB over WiFi, even after reboot

Question: I'm using scrcpy to mirror the phone screen to computer, which uses adb.
I've followed the steps and it works:
# connect via USB
adb devices
adb tcpip 5555
# now unplug USB, and the following will work over WiFi
adb connect 192.168.1.14:5555
scrcpy

But when you reboot the phone or computer, doing adb connect 192.168.1.14:5555 and scrcpy doesn't work anymore (NB: the phone IP hasn't changed, it's fixed).
Reading the answers from Run/install/debug Android applications over Wi-Fi?, I see 3 options:

plug the USB cable each time before doing a wireless connection, but this is annoying, and somehow reduces the interest of wireless...
Use "ADB over network" (main answer's screenshot), but as noted by many people in comments: "i do not have the "ADB over network" option in debugging option"; so this option doesn't work for me
other techniques that need root (not possible for me)

Question: how to pair the phone and computer with a USB cable only once, and then be able to use adb between them without having to use a USB connection first, after each reboot?
Note: I don't use Android Studio, but only scrcpy.
Answer: It's not possible without root the phone. If your phone has rooted. You can use this app. https://play.google.com/store/apps/details?id=com.ttxapps.wifiadb&hl=en. With this app you can easily debugs android apps with only wifi. Don't want USB cable even only first time.
Answer: Based on all the information I have the next conclusion. Just for reference, how a low-level setup with changing add routes works inside, described here. It comes up, there is a pretty straight thing inside changing navigation with adb tcpip <port>.

The first thing we need to do, it's setup system property with tcp port with name setprop service.adb.tcp.port (and values with a port number) By default, there is not such property.
And then just restart adb with few commands. stop adbd and start adbd on a device in order to debug bridge listen new port. What is the trick here, that you don't have access to this service and stop/start it without root. But it could be easily done, via Developer setting with stop/start debugging.

This few simple action hidden inside adb tcpip <port>. And the problem, that you cannot change system properties (point 1). That is why all application requires root access, it's just to change the single option. That is why, we need to connect with USB to debug bridge, which can change properties with his sepolicy.
So answering your question. I don't understand either, what is the problem or enabling this small setup in Developer options. But right now, it's possible to do so on some Roms, or devices with root access.
Comment: @Basj It's not possible. You need to have root, or custom rom for that.
Comment: Thank you for your answer but I don't really understand it. What is your conclusion: is it possible or not without root?


Monitoring a ZFS Raid Pool on Ubuntu for Integrity and Performance

Question: I set up ZFS on Ubuntu (via fuse) for a storage array at home and it has worked great for almost a year now, despite its 'beta' status. I log in and check the array every once in a while using:
zpool status

Which results in:
NAME        STATE     READ WRITE CKSUM
media       ONLINE       0     0     0
  raidz1    ONLINE       0     0     0
    sda     ONLINE       0     0     0
    sdb     ONLINE       0     0     0
    sdc     ONLINE       0     0     0
errors: No known data errors

This is all fine, but I'd like to automate a way to check every once in a while to make sure my pool is error-free.
I have cacti, and zabbix available at my disposal. I suppose I could also write a program that greps that output and if it doesn't find the phrase "No known data errors", send me an email.
However, is there any package already made that does this, or specifications on how I can get some performance metrics from this array?
Answer: zpool status -x is the preferred way to check the pools status via a script.  Its output is "all pools are healthy" unless there are issues making it a bit easier to use as a test.  Otherwise as you get more than one pool your check script and greps will get more complex.  So you can setup a cron job to run a script and make sure the status of that is "all pools are healthy" and send out an alert email of the output otherwise.
You could even setup a nagios plugin to do this for you.  I'm assuming that zabbix should be extendable in the same ways.
Also make sure you're running zpool scrub  regularly....I would set this up in a cron job as well.  This will detect and correct any issues it finds in the pool in areas of the file system that is not accessed often and can catch and correct issues before they result in any data corruption.
To get performance metrics you can use zpool iostat [seconds between updates]  I'm not sure how to tie that into cacti though but I'm sure it's possible.
Answer: assuming zabbix and gnu tools... add to zabbix agent daemon config file the following :
UserParameter=zpool.status,zpool status | grep -q "No known data errors" && echo 1 || echo 0
now, in zabbix add an item with key "zpool.status", create a trigger against it (using a function like ".last(0)=0") and you're done - trigger will fire whenever that string is missing from the zpool status output.
this also assumes that 'zpool' will be in the path of the zabbix user, and that this user will be allowed to run zpool. if not, specify full path and use sudo. another catch might be a default shell that doesn't support used syntax, in which case you can either rewrite the userparameter, or force it to use bash.
Answer: if possible, also do a iostat -xCzn and grep for any HW or Transport errors on the disks or controller.


RxJS: debounceTime on Rx.Observable.interval is not working as expected

Question: In the following line of code I am expecting the printing of here every 2 seconds. But nothing is being printed:
Rx.Observable.interval(1000).debounceTime(2000).subscribe(x => console.log('here'))
However in the following line of code, here is printed every 2 seconds, as expected:
Rx.Observable.interval(2000).debounceTime(1000).subscribe(x => console.log('here'))
In the first case I am expecting an event stream of 1 second period to be debounced to 2 seconds period. This does not seem to work.
And in the second case I am expecting an event stream of 2 seconds period to be debounced to 1 second period. This seems to work.
Why is the first case not working as expected? Is there something wrong in my expectation?
Answer: You may confuse debounce with throttle.
debounceTime
For every item, wait X ms until no other item is emitted, and only then emits the item.
Rx.Observable.interval(1000).debounceTime(2000).subscribe(x => console.log('here'))

All items are dropped since an item will always be emitted within 2000 ms.
throttleTime
Emits an item if no other items were emitted during the last X ms. Otherwise, the item is dropped.
Rx.Observable.interval(1000).throttleTime(2000).subscribe(x => console.log('here'))

Prints an item every 2000 ms.
Comment: Thanks! Yes I did misunderstand debounceTime.
Answer: The problem with your first case is that you are creating a new interval every second, but telling the observable to wait until 2 seconds have passed in order to pass the object through to the subscription. Since the interval value is less than the debounceTime value, your subscription will never "resolve".


Redefining a table with a user-defined type using DBMS_REDEFINITION

Question: The application which we developed has one schema, USER1, which has tables, types, packages etc.
I have to move some of the user-defined types to a different schema, USER2. USER1 has few tables which have a dependency on these user-defined types. We recreated the types in USER2, but before I drop the types in USER1, we have to remove the table's dependency on them. To do this, I am thinking of using DBMS_REDEFINITION by creating an intermediate table using the user defined type in USER2 (instead of USER1)
I'm using the following to cast the user defined type in USER1 and to the new one created in USER2, where EMP_LIST is an array of EMP_TYPE.
<code>BEGIN
   DBMS_REDEFINITION.START_REDEF_TABLE( 'user1', 'department', 'department_in'
         , 'dept_id dept_id, dept_name dept_name
         , cast(emp_list as user2.emp_type) emp_list'
         , dbms_redefinition.cons_use_rowid);
END;
</code>
But, I'm getting the following error:

Error : ORA-22907: invalid CAST to a type that is not a nested table or VARRAY

I tried using the MULTISET operator but it looks as though it's not allowed. How could we achieve this?
Answer: You probably need to write PL/SQL function or object method (constructor) which will convert one type to another by assigning each element from one collection to another. Performance will be not good.


how to remove/change/replace text after input field using jquery

Question:
  <input type="hidden" value="3">Service Tax

How do i change 'Service Tax' string from jquery. 'Service Tax' string might get change in future so string can be anything which i want to replace.
Please note: We can't change the HTML structure.
Comment: How do you want it to change?? On `click`, `change` or `keyup`? Please be a bit more specific, and what should the `Service Tax` "change" to
Comment: Possible duplicate of [Changing text after an input field](https://stackoverflow.com/questions/11411937/changing-text-after-an-input-field)
Comment: @Mohammad .. Thanks to you as well
Comment: Likely on load.
Comment: Check out https://stackoverflow.com/questions/11411937/changing-text-after-an-input-field
Comment: Change span from duplicate to td>input
Comment: @CarstenLøvboAndersen i simply want to change the text. Like On dropdown value change i want to change the 'Service Tax' value.
Comment: What dropdown. Please create a [mcve] - this looks ore and more like an X/Y problem
Comment: @mplungjan simply need to change the text. Doesn't matter it's going to change on dropdown change or click event or keyup event. It's straight forward question. Need jquery to change the 'Service Tax' string without changing the html structure. We are having  class and id if we need to catch the child item.
Comment: @Mohammad better duplicate than https://stackoverflow.com/questions/6925088/get-the-text-after-span-element-using-jquery - which I repopened after marking as dupe. I cannot reclose because of that
Comment: @PalashAgrawal The duplicate suggested by Mohammad is an exact duplicate, easily found when [searching for the title of your question](https://www.google.nl/search?q=jquery+replace+text+after+input+field+site:stackoverflow.com)
Comment: @CarstenLøvboAndersen. shared link helped me. And now i have used below code to achieve the same.
    var inputTaxCol = $("#" + newtaxColId + " :input");
                        text = inputTaxCol[0].nextSibling.nodeValue,
                        newText = text.replace(text, 'here');
Answer: Thank you all for your guidelines.
Link(Changing text after an input field)  shared in comment helped me. It's slightly different but resolved my problem. Below is the code to resolve it.
var inputTaxCol = $("#" + newtaxColId + " :input");
                  text = inputTaxCol[0].nextSibling.nodeValue,
                  newText = text.replace(text, 'my new text here');


JS - Escrever uma função que retorna a maior STRING

Question:
Escrever uma função que retorna a maior string dada.

exemplo:
entrada:
"StackOverflow" "Sem resposta" "Tags"
saída:
"StackOverflow" // string com o maior numero de caracters.
Comment: o que vc já fez para tentar chegar á isso? Mostre seu código se possível
Comment: As vezes uma simples busca no google retorna a resposta.
Answer: Você não precisa escrever uma função que já existe, use Array.prototype.reduce()

var strings = ["StackOverflow", "Sem resposta", "Tags"];
var retorno = strings.reduce(function (atual, proximo) {
  return atual.length > proximo.length ? atual : proximo;
});
alert(retorno);


Is it possible to calculate median value and interquatile range for a set of numbers containing a range or inequalities?

Question: I am trying to make simple median and IQR calculations that involve numbers (in  percentages) appearing in a range and inequalities in addition to whole numbers. My sample dataset looks like this:
5, 10, < 1, 10 - 20, 25, > 90
Any suggestions on how I can perform these two calculations on such a dataset?
Comment: @Tim: this is a *dataset.*  It has six values, of which three are intervals.  Interval arithmetic permits computing quantiles, which generally would themselves be intervals.
Comment: Do you have counts or probabilities accompanying those values?
Comment: @AgnesianOperator I describe and illustrate the interval arithmetic solution at https://stats.stackexchange.com/a/86120/919.
Comment: @whuber I would upvote your answer there, but I have already done that! We have a shared interest in interval arithmetic. Definitely relevant to share here though. I would recommend it to others. Hopefully the OP here checks it out (hint, hint).
Comment: Do you mean $>90$ for the last one?
Comment: sorry, yes its supposed to be > 90.
Comment: I also suggest [interval arithmetic](https://en.wikipedia.org/wiki/Interval_arithmetic) (IA) as it (1) allows the desired calculations, and (2) assumes very little. While other complications can arise with IA, like having to solve optimization problems, you will find perhaps at worst here that IA is going to give conservative (i.e. wider than you might get with a well-chosen probability model) bounds.
Comment: What do these numbers mean? 5, 10, < 1, 10 - 20, 25, > 90 Are they each single observations in which some observations are expressed as numbers and some observations are expressed as ranges? Or do these numbers indicate that you have observations that fall inside these ranges (e.g. you know the 5th percentile, the 10th percentile etc.)
Comment: Can the inequalities be refined into bounded intervals? For example if $x < 1$ then $x \in (-\infty, 1)$, but often things cannot be unbounded in physically realistic scenarios. Can you make a reasonable inference for a finite value for the lower bound? Same goes for the $> 90$ upper bound.
Answer: In this case you can make a non-parametric estimate, although without important things like confidence intervals. You have a combination of left-censored (<1), right-censored (>90) and interval-censored (10-20) values.
Although you might not think of what you have as a survival problem, a survival function $S(t)$ is just 1 minus the corresponding (cumulative) distribution function $F(t)$ (i.e., $S(t)=1-F(t)$), so the median of $F(t)$ is the value corresponding to a "survival" fraction of 0.5, the first quartile that for a survival fraction of 0.75, etc. So you can use a survival modeling method designed to handle arbitrarily censored data to get estimates of quantiles.
The R icenReg package can calculate the Turnbull nonparametric maximum-likelihood estimate of a survival curve based on such data (a generalization of the Kaplan-Meier method for interval-censored data). That should be more generally useful than a method that requires you to pre-rank the exact and interval values.
To get a single non-parametric survival curve this way, provide a 2-column matrix with the lower and upper limits for each data point. For a known data point, those two values are identical. With your example percentage data (lower limit, 0; upper limit, 100):
library(icenReg)
datMat <- matrix(c(0,1,5,5,10,10,10,20,25,25,90,100),ncol=2,byrow=TRUE)
datMat
##     [,1] [,2]
## [1,]    0    1
## [2,]    5    5
## [3,]   10   10
## [4,]   10   20
## [5,]   25   25
## [6,]   90  100
icTest<- ic_np(datMat)
plot(icTest,bty="n")

I didn't change the default axis labels, so your values correspond to "time" here. $S(t)$ is the survival function for your data, although the boxes might look strange. The package vignette explains:

Looking at the plots, we can see a unique feature about the NPMLE for interval censored data. That is, there are two lines used to represent the survival curve. This is because with interval censored data, the NPMLE is not always unique; any curve that lies between the two lines has the same likelihood.

Based on the plot, you would accept the range of 10-20, corresponding to $S(t) = 0.5$, as including the median. The IQR would be 5 - 25 (corresponding to $S(t) = 0.75, S(t) = 0.25$).
If you have a reasonable parametric form for your data you can do much more with this type of modeling, as Frank Harrell suggests in his answer.
Answer: If you can order the levels of the observations, you can determine the median, and the 1st quartile and 3rd quartile.

In your sample data, the observations could be ordered, with the exception that you have to decide if "10 - 20" is greater then "10", or if they would have the same rank when ranked.

IRQ itself, as the difference between the 1st and 3rd quartile, wouldn't necessarily make sense.

There are different methods to determine the value of quantiles.  For example, R has 9 options ( www.rdocumentation.org/packages/stats/versions/3.6.2/topics/quantile ).  Some are more appropriate for non-continuous data.

With discontinuous data, you may get answers that are e.g. "Between 'good' and 'very good'.  In your sample data, the median would be between "10" and "10 - 20", assuming those are two different when ranked.

The following can be run in R (or at e.g. rdrr.io/snippets/ ).  This assumes that "10 - 20" is greater than "10".  And uses R quantile type 1, which will not return answers that straddle two levels.

.
Observed = c("5", "10", "< 1", "10 - 20", "25", "> 90")

Obs.factor = factor(Observed,
                    ordered = TRUE,
                    levels = c("< 1", "5", "10","10 - 20", "25", "> 90") )

quantile (Obs.factor, type=1, probs=0.50)

quantile (Obs.factor, type=1, probs=0.25)

quantile (Obs.factor, type=1, probs=0.75)

Answer: If you only had "< 1" occuring you could compute the median.  In general you can't estimate what you want unless you assume a smooth parametric distribution and explicitly handle left, right, and interval censoring in computing the likelihood function so that you can get maximum likelihood estimates of the parameters of that distribution.  Then you compute the mean and quantiles which are functions of those underlying parameters.  It's pretty involved.
Comment: I think this answer is way too pessimistic.  For instance, 10-20 clearly is the median and if Tukey's hinges would be acceptable as quartiles, they are both uniquely defined at 7.5 and 22.5.
Comment: The interval censored values cause special problems if the interval is wide.  Yes if you want to state the median as an interval you can stay honest in some cases without resorting to parametric distribution fits.
Comment: Thanks, so there is really no straightforward way of solving this, even if the numbers represented percentages on a scale of 0% to 100%? Would you recommend taking the median of such ranges to get whole numbers (e.g. using a value of 15% for the "10%-20%" cell and using 95% for the "> 90% cell). Perhaps these could then be used along with the other whole number values to calculate the median and IQR?
Comment: No straightforward way, and I don't recommend assuming the midrange characterizes an interval.  Best you can do easily is to compute proportions of all possible levels/intervals.
Comment: I don't see why you can't proceed with (some) combinations of left and right censoring. The median of {x: x < 1} , 1, and {y: y >1} is pretty clearly 1, regardless of the values of x and y. As the proportion of censored data approaches the median's breakdown point, you might not be able to provide an exact value, but you can still say something sensible: the median of (e.g., <1, 5, <10, >50) is no more than 7.5


Fazer DIV sumir com JavaScript

Question: Então gente estou com um problema, tenho dois input do tipo radio (sim e não) e preciso que quando o input "não seja selecionado a DIV suma e quando o input "sim" seja selecionado ele volte. Procurei em alguns lugares mas sempre dá algum erro tipo:

ReferenceError: Mudarestado is not defined.

function Mudarestado(el) {
  var display = document.getElementById(el).style.display;
  if (document.cadastroDeAvaliacaoNew.possuiCaderneta[0].checked)
    document.getElementById(el).style.display = 'block';
  else
    document.getElementById(el).style.display = 'none';
}

if (document.cadastroDeAvaliacaoNew.possuiCaderneta[0].checked ||
  document.cadastroDeAvaliacaoNew.possuiCaderneta[1].checked) {} else {
  alert('6 - A criança caderneta de saúde sem seleção');
  document.cadastroDeAvaliacaoNew.possuiCaderneta.focus();
  return false;
}

if (document.cadastroDeAvaliacaoNew.possuiCaderneta[0].checked) {
  function mostraDiv() {
   document.getElementById("visibilidade").style.display = "blockj"
  }

  if (document.cadastroDeAvaliacaoNew.curvaPeso[0].checked ||
    document.cadastroDeAvaliacaoNew.curvaPeso[1].checked) {} else {
    alert('7 - O peso da criança está com curva sem seleção');
    document.cadastroDeAvaliacaoNew.curvaPeso.focus();
    return false;
  }

  if (document.cadastroDeAvaliacaoNew.curvaAltura[0].checked ||
    document.cadastroDeAvaliacaoNew.curvaAltura[1].checked) {} else {
    alert('8 - A altura da criança está com curva sem seleção');
    document.cadastroDeAvaliacaoNew.curvaAltura.focus();
    return false;
  }
} else if (document.cadastroDeAvaliacaoNew.curvaPeso[1].checked) {
  function someDiv() {
   document.getElementById("visibilidade").style.display = "none";
  }

} else {
  alert('6 - A criança caderneta de saúde sem seleção');
  document.cadastroDeAvaliacaoNew.possuiCaderneta.focus();
  return false;
}

function mostraDiv() {
  document.getElementById("visibilidade").style.display = "block";
}

function someDiv() {
  document.getElementById("visibilidade").style.display = "none";
}

 6 - A criança possui caderneta de saúde?  *

 <input class="campoSelecao"
  type="radio" name="possuiCaderneta" value="1" onclick="mostraDiv()"
  title="Marque esta opção se a criança possuir caderneta de saúde" {selpossuiCaderneta1}=""/>Sim

 <input class="campoSelecao"
  type="radio" name="possuiCaderneta" value="0" onclick="function (){someDiv()"
  title="Marque esta opção se a criança não possuir caderneta de saúde" {selpossuiCaderneta0}="" />Não

Observe na caderneta da criança:

  7 - O peso da criança está com curva:

  <input class="campoSelecao"
  type="radio" name="curvaPeso" value="1
  title="Marque esta opção se a curva de peso da criança está Ascendente" {selcurvaPeso1}=""/>Ascendente

  <input class="campoSelecao"
   type="radio" name="curvaPeso" value="2"
   title="Marque esta opção se a curva de peso da criança está Descendente" {selcurvaPeso2}=""/>Descendente

  <input class="campoSelecao"
   type="radio" name="curvaPeso" value="3"
   title="Marque esta opção se a curva de peso da criança está Horizontal" {selcurvaPeso3}=""/>Horizontal

  Peso: <input class="alinhamentoDireita" type="text" name="pesoAtual" id="pesoAtual" size="4"
   maxLength="6" value="{pesoAtual}"  title="Peso da criança na realização da avaliação" /> Kg

  8 - altura da criança está com curva:

  <input class="campoSelecao"
   type="radio" name="curvaAltura" value="1"
   title="Marque esta opção se a curva de peso da criança está Ascendente" {selcurvaAltura2}=""/>Ascendente

  <input class="campoSelecao"
   type="radio" name="curvaAltura" value="2"
   title="Marque esta opção se a curva de peso da criança está Horizontal" {selcurvaAltura2}=""/>Horizontal

  Altura: <input class="alinhamentoDireita" type="text" name="alturaAtual" id="alturaAtual" size="3"
   maxLength="5" value="{alturaAtual}" title="Altura da criança na realização da avaliação"> m

Answer: Existem vários erros de sintaxe no seu código, nunca, jamais, em hipótese alguma, de o mesmo id para mais de um elemento (pelo menos de cabeça não me vem aonde isso pode ser útil) como você fez aqui:

function div(valor) {
  if (valor) {
    document.getElementById("visibilidade").style.display = "block";
  } else {
    document.getElementById("visibilidade").style.display = "none";
  }
}

 6 - A criança possui caderneta de saúde?  *

 <input
  type="radio" name="possuiCaderneta" value="1" onclick="div(true)"
  title="Marque esta opção se a criança possuir caderneta de saúde"/>Sim
 <input class="campoSelecao"
  type="radio" name="possuiCaderneta" value="0" onclick="div(false)"
  title="Marque esta opção se a criança não possuir caderneta de saúde" />Não

Observe na caderneta da criança:

  7 - O peso da criança está com curva:

  <input class="campoSelecao"
  type="radio" name="curvaPeso" value="1"
  title="Marque esta opção se a curva de peso da criança está Ascendente" {selcurvaPeso1}=""/>Ascendente

  <input class="campoSelecao"
   type="radio" name="curvaPeso" value="2"
   title="Marque esta opção se a curva de peso da criança está Descendente" {selcurvaPeso2}=""/>Descendente

  <input class="campoSelecao"
   type="radio" name="curvaPeso" value="3"
   title="Marque esta opção se a curva de peso da criança está Horizontal" {selcurvaPeso3}=""/>Horizontal

  Peso: <input class="alinhamentoDireita" type="text" name="pesoAtual" id="pesoAtual" size="4"
   maxLength="6" value="{pesoAtual}"  title="Peso da criança na realização da avaliação" /> Kg

  8 - altura da criança está com curva:

  <input class="campoSelecao"
   type="radio" name="curvaAltura" value="1"
   title="Marque esta opção se a curva de peso da criança está Ascendente"/>Ascendente

  <input class="campoSelecao"
   type="radio" name="curvaAltura" value="2"
   title="Marque esta opção se a curva de peso da criança está Horizontal" />Horizontal

  Altura: <input class="alinhamentoDireita" type="text" name="alturaAtual" id="alturaAtual" size="3"
   maxLength="5" title="Altura da criança na realização da avaliação"> m

Comment: na verdade eu tinha colocado o segundo id para um teste e esqueci de apagar depois.

Mesmo resolvendo o problema aqui, lá continua dizendo que o valor fa função div é nulo ou não definido. Eu faço estágiario e faço manutenção nesse sistema, então estou tentando compreender certas partes dele ainda.
Comment: @DouglasNunes, tudo bem? Se possível, copia aqui todo html e js... fica melhor de nós entendermos e te ajudar da melhor forma, tranquilo?

Fazer DIV sumir com JavaScript


Is there a way to see the date of when webforms were opened and closed?

Question: I'm using Drupal 9 and would like to know when a webform was closed to check that we haven't had a security breach and received submissions after the form was closed.
Answer: No, there is not, Webforms are config and config elements don't store revision information. If you have the database logging module enabled, you might find a DB log entry though when a webform config was saved (see <code>/admin/reports/dblog</code>). But this log doesn't say which field (or if any field at all) has been changed, it just means "the save button was clicked".
(And if you have a security breach, this info would be untrustworthy anyways, because all those logs can be manipulated programmatically from within Drupal too.)


What does the tilde before a function name mean in C#?

Question: I am looking at some code and it has this statement:
~ConnectionManager()
{
    Dispose(false);
}

The class implements the IDisposable interface, but I do not know if that is part of that the tilde(~) is used for.
Answer: ~ is the destructor

Destructors are invoked automatically, and cannot be invoked explicitly.
Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.
Destructors cannot be used with structs. They are only used with classes.
An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.
Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.
When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.

Finalize
In C#, the Finalize method performs the operations that a standard C++ destructor would do. In C#, you don't name it Finalize -- you use the C++ destructor syntax of placing a tilde ( ~ ) symbol before the name of the class.
Dispose
It is preferable to dispose of objects in a Close() or Dispose() method that can be called explicitly by the user of the class. Finalize (destructor) are called by the GC.
The IDisposable interface tells the world that your class holds onto resources that need to be disposed and provides users a way to release them. If you do need to implement a finalizer in your class, your Dispose method should use the GC.SuppressFinalize() method to ensure that finalization of your instance is suppressed.
What to use?
It is not legal to call a destructor explicitly. Your destructor will be called by the garbage collector. If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the IDisposable interface.
Comment: I don't know how it used to be in the past. But now destructors are inherited. Check this link for more information (check the example at the end): http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx
Comment: @RononDex point 3 of the very page you link to states *"Finalizers cannot be inherited"*, which contradicts your comment. It's admittedly all a bit confusing because while they can't be inherited, *"the `Finalize` method is called recursively for all instances in the inheritance chain, from the most-derived to the least-derived"*. Note that that's *not* the same behaviour you'd get from inheritable destructors, though.
Comment: @MarkAmery ah I see, so basically they get called in the reversed order compared to something that is inherited?
Comment: So if some C# code that is the result of a decompiler has a method like this, it can safely be deleted? This seems to be confirmed by the fact that it has 0 references
Answer: This is a finalizer. To be honest, you should very rarely need to write a finalizer. You really only need to write one if:

You have direct access to an unmanaged resource (e.g. through an IntPtr) and you can't use SafeHandle which makes it easier
You are implementing IDisposable in a class which isn't sealed. (My preference is to seal classes unless they're designed for inheritance.) A finalizer is part of the canonical Dispose pattern in such cases.
Answer: It is used to indicate the destructor for the class.
Comment: They're both correct, depending on which C# spec you read. The most recent MS one (unified C# 3.0) refers to them as destructors (e.g. section 10.13) but the ECMA spec refers to them as finalizers.
Comment: @1800INFORMATION: The *syntactic element* is properly called a destructor.  If a class has a destructor, a C# compiler will auto-generate a finalizer which includes a generally-useless `try/finally` block that ensures that the parent `Finalize` method gets called.  Most things that are true of destructors are true of finalizers, and vice versa, but the words mean slightly different things.
Answer: Same as C++, it is the destructor; however in C# you do not call it explicitly, it is invoked when the object gets collected by the garbage collector.
Answer: See Destructors (C# Programming Guide).  Be aware, however that, unlike C++, programmer has no control over when the destructor is called because this is determined by the garbage collector.
Answer: ~ usually represents a deconstructor.  which is run right before a object dies.
Here is a description of C# deconstructors i found
Comment: the correct term should be destructor/finalizer, not deconstructor. Deconstructor means a syntax to deconstruct a constructor.


Print Queue History/Log

Question: I need to view and track the history of a printer's queue. I am running Windows XP Pro with a various set of HP printers.
If the OS or the printer does not keep a log, is there a third party application that can perform this service?
Edit:
The printers are attached to a machine via USB then shared for other users.  The printers recieve print jobs from a group of people and we need to be able to track who sends what and when.
I am looking for an easy way for the user of the computer to track the jobs going to the printer.
We plan on moving to network printers but I am not sure how long that will take.  So, we need a solution for the interim.
Ideally I think I would prefer an application that solely does print tracking.
Regards
Answer: I think you can try PaperCut Print Logger
Answer: You'll get these in the standard Windows event logs.
Comment: I only found warnings and errors in the event logs.  I could not find a history of documents.
Answer: Going forward, you'll want to look at the various print auditing solutions available.  I doubt that they will be able to retroactively look at jobs printed before installation and configuration (if that is what you are trying to do - the question doesn't make this clear).
Also, are you printing to desktop printers or MFP devices?  I've seen some MFPs maintain slightly more detailed logs than the windows event log.
Comment: I understand that past jobs will probably not be able to be recovered. All of the printers are HP all-in-ones of varying models.
Answer: Every time a user user prints on a windows client it's logged in the system event log.  You get basic information on the job (user, print queue, file name, etc.)  Usually logged under the print spooler service.  On a single client system things are usually not too noisy that you can't piece together the print history, but a print server with multiple users (or windows xp box acting as a print server) can quickly produce enough events to flush the log buffers and you'll have a small window in which you can see events.  There are products out there like Print Manager Plus that are designed for printer management and can provide better stats, but really any log management app (like splunk) can help you wrangle large volumes of print logs.
As for logs options on the printer, that depends on the what printers you have and what logging they have buried deep within their config menus but I haven't seen many with many logging options for things that aren't errors.  However, if it's a network printer the best you could ever hope to get is the IP address of the print server that sent the job.

Print Queue History/Log


Finding Dice Probability

Question: Here is my current code:
import random

rolls = 1000  # Set number of rolls here.
num_dice = 2    # Set Number of Dice here.
dice_list = []

for i in range(rolls):
    dice = sum([random.randint(1, 6) for _ in range(num_dice)])
    dice_list.append(dice)

for i in range(num_dice, (num_dice * 6)+1):
    count = dice_list.count(i)
    count = float(count)
    print("Number of {}'s rolled: {} Probability: {}%".format(i,count, round((count / rolls) * 100),2))

My problem is when calculating the percentage of i, it returns the all percentage as 0%.
Update: As I was going through StackOverflow, I've found out why it was returning the percentage to 0%. To get the actual percentage, you need the "count" variable as a decimal form.
Comment: If you rolled 126 8s, you percentage would be `126/1000` which is `0.126` or 12.6%. You care calculating `126/(1000 * 100)` which is `126/100000`, which is wrong. You just have parenthesis in the wrong place. You probably want `(count / rolls) * 100`
Comment: Your "update" is totally incorrect.  It's perfectly OK to have `count` as an integer variable, and casting it to `float` as you did is totally unnecessary since Python 3.
Comment: P.S. `sum` works with a generator as easily as it does a list, so your brackets are redundant: `sum(random.randint(1, 6) for _ in range(num_dice))`.
Comment: P.P.S.  If you're still using a version of Python 2, you need to specify that in your question.  Python 2.7 became [officially unsupported as of January 1, 2020](https://www.python.org/doc/sunset-python-2/) and it is unreasonable for us to assume it when you're asking a question.
Comment: Hi @MarkRansom. The platform that I'm using is Pycharm CE (Python 2.7)
Comment: The last edit you did totally invalidated the correct answers you got.  Don't do that.
Answer: If i'm not wrong it should be (count / rolls) * 100. This seems to not output 0. But, I just graduated kindergarten, so don't take my word.
import random

rolls = 1000  # Set number of rolls here.
num_dice = 2    # Set Number of Dice here.
dice_list = []

for i in range(rolls):
    dice = [random.randint(1, 6) for _ in range(num_dice)]
    x = sum(dice)
    dice_list.append(x)

for i in range(num_dice, (num_dice * 6)+1):
    count = dice_list.count(i)
    print(f"Number of {i}'s rolled: {count} Probability: {round((count / rolls)*100,2)}")

Answer: try this
import random

rolls = 1000  # Set number of rolls here.
num_dice = 2    # Set Number of Dice here.
dice_list = []

for i in range(rolls):
    dice = [random.randint(1, 6) for _ in range(num_dice)]
    x = sum(dice)
    dice_list.append(x)

for i in range(num_dice, (num_dice * 6)+1):
    count = dice_list.count(i)
    print("Number of {}'s rolled: {} Probability: {}%".format(i, count, round(count/rolls*100,2)))

Output
Number of 2's rolled: 37 Probability: 3.7%
Number of 3's rolled: 57 Probability: 5.7%
Number of 4's rolled: 78 Probability: 7.8%
Number of 5's rolled: 114 Probability: 11.4%
Number of 6's rolled: 145 Probability: 14.5%
Number of 7's rolled: 160 Probability: 16.0%
Number of 8's rolled: 129 Probability: 12.9%
Number of 9's rolled: 123 Probability: 12.3%
Number of 10's rolled: 80 Probability: 8.0%
Number of 11's rolled: 50 Probability: 5.0%
Number of 12's rolled: 27 Probability: 2.7%

Comment: Besides the answer, do explain what you did so that OP understand where the issue was.
Comment: hi @Ank, I have updated the calculation `round(count / (rolls * 100)),2` to become `round(count/rolls*100,2)`
Comment: I've updated my code. You need the "count" as a decimal form (float(count)).
Comment: @CalebMurnan have you tried your updated code?  It still doesn't work.
Comment: @MarkRansom, I've updated the code. I needed to have the count as a new variable for float(count).
Comment: @CalebMurnan don't correct the code in the question so it doesn't show your problem anymore, that's totally unfair to those that answered and useless to those who see your question in the future.
Comment: hi @CalebMurnan, your newly edited code `round((count / rolls) * 100),2)` gets output `(3, 2)`, whereas you meant to do `round(count/rolls*100,2)` output `3.4`

Finding Dice Probability


How does the bottom participant steer in two-man luge?

Question: Based on this statement, found here:

Typically, the 2-man luge is slower because they start further down on
  the track, but it is much harder to steer because the man on top is
  the only one that can see, but the man on the bottom is the one that
  is most able to contribute to the steering.

How does the bottom participant steer in two-man luge? Since the top participant is the only one that can see down the track, how does the bottom participant know when to steer and in what direction?
I notice there are handles from the top participant's suit the bottom participant grabs onto...does this have any significant effect?
Answer: The bottom driver is like the suspension for the sled, resulting in a smoother travel. And yes, the handles for the bottom athlete are significant too. The top  man who sees the track signals the man in bottom (mostly using head movement) to help steer.
Read this article for more info: http://www.slate.com/blogs/five_ring_circus/2014/02/13/doubles_luge_sochi_games_2014_what_do_the_two_men_do_in_two_man_luge.html
Comment: +1 Thanks for the answer. This is a good way to summarize the article you reference to answer my question in your own words without changing what the article says. Good work.


Unitary Vandermonde matrices other than DFT?

Question: We know that building a Vandermonde matrix from all the different roots of 1 makes a unitary matrix up to scale ($M^* = c\cdot M^{-1}$) performing the discrete Fourier transform. Obviously, arbitrary permutation of the roots still makes a unitary matrix.
Are there any other unitary Vandermonde matrices? It feels like the answer is "no", but it's not obvious to me how to prove it.
Comment: $M_{km}=e^{i(m-1)(t+2\pi \sigma(k)/n)}$ for some permutation $\sigma$ of $1\ldots n$.
Answer: Let $V$ denote a size-$n$ square Vandermonde matrix associated with values (i.e. its second column is) $x_1,x_2,\dots,x_n$. The "dot-product" of any two rows is given by
$$
(VV^*)_{j,k} = \sum_{p=0}^{n-1} (x_j \bar x_k) =
\begin{cases}
\frac{1 - (x_j\bar x_k)^n}{1 - (x_j \bar x_k)} & x_j\bar x_k \neq 1\\
n & x_j\bar x_k = 1.
\end{cases}
$$
With that, we see that in order for $V$ to have orthogonal rows (equivalently in order for $VV^*$ to be diagonal), it must be that $x_j \bar x_k$ satisfies $x_j \bar x_k \neq 0$ and $(x_j \bar x_k)^n = 1$ for all $j \neq k$. In order for $V$ to have rows of the same length (i.e. for $VV^*$ to be a multiple of the identity), it must hold that the following values are equal:
$$
(VV^*)_{j,j} = \sum_{p=0}^{n-1}|x_j|^{2p} =
\begin{cases}
\frac{1 - |x_j|^{2n}}{1 - |x_j|^2} & |x_j|\neq 1\\
n & |x_j| = 1.
\end{cases}
$$
Ultimately, this means that we must have $|x_j| = |x_k|$ for all $j \neq k$. From the fact that $(x_j\bar x_k) = 1$, we must have $(|x_j||x_k|)^n = 1$, so it must hold that $|x_k| = 1$ for all $k$.

With that established, here are a few other Vandermonde matrices that are a multiple of a unitary matrix. Note that for any $x_1$ with $|x_1| = 1$, we can take $x_j = \omega^{j}x_{1}$, where $\omega = \exp(2 \pi i/n)$. We can of course permute these choices $x_j$ (and hence the rows of the Vandermonde matrix); some of these permutations can be reached by choosing an alternative primitive root of unity instead of $\omega$.
The Vandermonde matrices obtained as above can all be expressed in the form
$$
V = PWD_\gamma, \quad D_\gamma = \pmatrix{1\\&\gamma \\ && \ddots \\ &&& \gamma^{n-1}}
$$
where $P$ is a permutation matrix, $W$ denotes the (unnormalized) DFT matrix, and $|\gamma| = 1$. $\gamma$ corresponds to our choice of $x_1$.
These are the only Vandermonde matrices that are multiples of unitary matrices.
To see that this is the case, let $x_1,\dots,x_n$ denote the values associated with such a Vandermonde matrix. As discussed above, we have $|x_j| = 1$ for all $j$, and in particular $x_1 \neq 0$. Consider the values $x_j \bar x_1$ for $j = 2,\dots,n$. We note that the values $x_j\bar x_1$ must be distinct for all $j = 2,\dots,n$; otherwise, we have a Vandermonde matrix associated with repeated values, which means that the matrix is not invertible and hence not a multiple of a unitary matrix. Moreover, we have $|x_j| = 1$ for all $j$, and we cannot have $x_j\bar x_1 = 1$. Finally, $x_j \bar x_1$ must be a root of unity.
With that we conclude that $x_j \bar x_1 = x_j/x_1$ is equal to an $n$th root of unity. That is, we have $x_1 \bar x_j = \omega^{p_j}$ where $\omega = \exp(2 \pi i/n)$ and $p_2,\dots,p_n$ are distinct and non-zero modulo $n$. That is,
$$
x_j = x_1 \omega^{p_j}, \quad j = 2,\dots,n,
$$
which means that our Vandermonde matrix is of the above form. $\square$

Given $p_1 = 0$ and $1 \leq p_2,\dots,p_n \leq n-1$, we can build the corresponding $P$ and $D_\gamma$ as follows: if we take $e_0,e_1,\dots,e_{n-1}$ to denote the standard basis of $\Bbb C^n$ (i.e. the rows of the identity matrix), then take $P$ to be the matrix whose $j$th row is $e_{p_j}$. From there, take $\gamma = x_1$.
Comment: Great comprehensive answer, thank you!


What's the difference between multiple R and R squared?

Question: In linear regression, we often get multiple R and R squared. What are the differences between them?
Comment: Can somebody provide formulas, especially how to compute multiple R
Answer: Capital $R^2$ (as opposed to $r^2$) should generally be the multiple $R^2$ in a multiple regression model. In bivariate linear regression, there is no multiple $R$, and $R^2=r^2$. So one difference is applicability: "multiple $R$" implies multiple regressors, whereas "$R^2$" doesn't necessarily.
Another simple difference is interpretation. In multiple regression, the multiple $R$ is the coefficient of multiple correlation, whereas its square is the coefficient of determination. $R$ can be interpreted somewhat like a bivariate correlation coefficient, the main difference being that the multiple correlation is between the dependent variable and a linear combination of the predictors, not just any one of them, and not just the average of those bivariate correlations. $R^2$ can be interpreted as the percentage of variance in the dependent variable that can be explained by the predictors; as above, this is also true if there is only one predictor.
Comment: So if in a multiple regression R^2 is .76, then we can say the model explains 76% of the variance in the dependent variable, whereas if r^2 is .86, we can say that the model explains 86% of the variance in the dependent variable? What's the difference in their interpretation?
Comment: As the answer suggests - "multiple R" implies multiple regressors. Is it possible to have multiple R value in single regressor model?
Answer: Multiple R actually can be viewed as the correlation between response and the fitted values. As such it is always positive. Multiple R-squared is its squared version.
Let me illustrate using a small example:
<code>set.seed(32)
n <- 100
x1 <- runif(n)
x2 <- runif(n)
y <- 4 + x1 - 2*x2 + rnorm(n)

fit <- lm(y ~ x1 + x2)
summary(fit) # Multiple R-squared:  0.2347

(R <- cor(y, fitted(fit))) # 0.4845068
R^2                        # 0.2347469
</code>
There is no need to make a big fuss around "multiple" or not. This formula always applies, even in an Anova setting. In the case where there is only one covariable $X$, then R with the sign of the slope is the same as the correlation between $X$ and the response.
Answer: I simply explain to my students that:

the multiple R be thought of as the absolute value of the correlation coefficient (or the correlation coefficient without the negative sign)!
The R-squared is simply the square of the multiple R. It can be through of as percentage of variation caused by the independent variable (s)

It is easy to grasp the concept and the difference this way.