Intersecção de palavras com dicionários em Python

Question: Olá!
No livro do Wendel Melo, Introdução ao Universo da Programação com Python, tentei realizar o último exercício, mas não estou conseguindo.
Enunciado:
Faça um programa que leia três strings do usuário e liste cada palavra
que apareça ao menos uma vez em uma das strings. Cada palavra só
deve ser listada uma única vez, e junto a ela os textos em que a mesma
aparece. Seu programa deve contemplar uma função que receba as strings
lidas e retorne um dicionario onda as chaves são compostas pelas palavras
e os itens são conjuntos indicando os textos em que cada chave (palavra)
aparece.
Exemplo:

Eu fiz este código, ele apresenta os respectivos itens do texto1, texto2 e texto3, porém eu não sei como seguir, porque as palavras se repetem ao decorrer do código. Creio que uma boa solução seria utilizando o intersection, método dos conjuntos, em alguma parte do código, porém eu não sei como transformar essa interseção nas palavras texto1, texto2 e texto3, pois o método só retornará o elemento da interseção e não o conjunto onde ele se encontra. Desde já, agradeço quem me ajudar.
def tDicionario(texto1, texto2, texto3):
    palavras = {}

    for palavra in texto1:
        print('{}: '.format(palavra))

    for palavra in texto2:
        print('{}: '.format(palavra))

    for palavra in texto3:
        print('{}: '.format(palavra))

if __name__ == '__main__':

    texto1 = input('Entre com o texto 1: ').split()
    texto2 = input('Entre com o texto 2: ').split()
    texto3 = input('Entre com o texto 3: ').split()

    print('Listagem de palavras: ')
    print(tDicionario(texto1, texto2, texto3))

Answer: A forma mais fácil é usando um dicionário em Python onde cada uma de suas chaves representa uma palavra, e o seu valor associado é uma lista dos números dos textos em que uma dada palavra aparece. Utilizar conjuntos também seria viável, mas acredito ser mais simples de seguir a lógica do programa dessa forma.
Também fica mais simples se você pedir o input e logo em seguida colocar os dados pra dentro do dicionário, ao invés de pedir os inputs separadamente. Se você fizer isso dentro de um loop, fica fácil de checar se a palavra já consta no dicionário, ou se ela já apareceu mais de uma vez na mesma frase. Isso inclusive trivializa a generalização do seu programa: dá para pedir um número arbitrário de frases pro usuário apenas modificando uma linha.
Veja o exemplo a seguir:
# Iniciamos com o dicionário vazio
resultado = {}

# Número de frases a pedir para o usuário
numero_de_frases = 3

for n in range(numero_de_frases):
    # n começa de 0, adicionamos 1 e convertemos
    # para string para simplificar nossa vida
    num_texto = str(n + 1)

    # Pega input do usuário
    texto = input(f'Entre com o texto {num_texto}: ')
    lista_de_palavras = texto.split()

    # Itera sobre lista de palavras
    for palavra in lista_de_palavras:
        # Se a palavra é inédita no dicionário, cria uma nova lista
        if palavra not in resultado:
            resultado[palavra] = list()
        # Pega a lista de números dos textos onde a palavra aparece
        lista_num_textos = resultado[palavra]
        # Se a palavra já apareceu no texto, pulamos a linha abaixo
        # (evita entradas repetidas quando a palavra está duplicada)
        if num_texto not in lista_num_textos:
            lista_num_textos.append(num_texto)

# Itera sobre dicionário e mostra os resultados
for palavra, lista_num_textos in resultado.items():
    string_num_textos = ', '.join(lista_num_textos)
    print(f'A palavra "{palavra}" aparece no(s) texto(s): {string_num_textos}')

Answer: De acordo com a terceira frase do enunciado da questão...

Seu programa deve contemplar uma função que receba as strings lidas e retorne um dicionário onda as chaves são compostas pelas palavras e os itens são conjuntos indicando os textos em que cada chave (palavra) aparece.

...podemos implementar uma função para resolver a questão.
Para montarmos a referida função podemos utilizar algumas lógicas. Neste caso, podemos utilizar a seguinte lógica:

Capturar os três textos sugeridos e armazena-los em uma lista;
Enviar esta lista como parâmetro para a função que montará o dicionário;
Montar o dicionário;
Exibir os resultados idênticos ao sugerido na questão.

Pois bem, um dos códigos possíveis para esta lógica é:
def localiza_palavra(lista_textos):
    o = range(1, len(lista_textos) + 1)
    dicionario = dict()
    for texto, posicao in zip(lista_textos, o):
        for palavra in texto:
            if palavra not in dicionario:
                dicionario[palavra] = list()
            r = dicionario[palavra]
            if posicao not in r:
                r.append(posicao)
    return dicionario

if __name__ == '__main__':
    lista = list()
    for i in range(1, 4):
        lista.append(input(f'Entre com o texto {i}: ').split())

    resultado = localiza_palavra(lista)

    print('Listagem de palavras:')
    for key, item in resultado.items():
        print(f'{f"{key}:":<10}', *[f'texto {x},' for x in item])

Observe que ao executarmos o código, devemos digitar os três textos. Esses textos são capturados como lista e, em seguida, armazenados em outra lista.
Depois disso esta lista será enviada como parâmetro para a função localiza_palavra().
Chagando lá o primeiro bloco for, com ajuda da função zip(), percorrerá simultaneamente as listas lista_textos - formada por todos os textos digitados - e o - formada pelas ordens dos textos.
Em seguida o segundo bloco for percorrerá cada palavra do texto atual e, com ajuda do bloco if será verificado se a respectiva palavra não está contida no dicionário. Caso a palavra não esteja no dicionário, o dicionário receberá como chave a respectiva palavra cujo valor é uma lista.
Esta lista será montada com as posições dos respectivos textos.
O segundo bloco if verificará se a posicao atual não pertence à r - lista formada pelas posições. Caso, a posição não se encontre em r, a posição será adicionada.
Terminada todas as interações possíveis, os resultados serão exibidos.
A exibição dos valores é realizada pelo último bloco for do código.
A última linha de código...
print(f'{f"{key}:":<10}', *[f'texto {x},' for x in item])

...executa o seguinte:

Exibe o valor da chave (key) acompanhada de " : " no canto esquerdo de um total de 10 espaços;
Exibe o desempacotamento de um lista montada por list comrehension, onde cada elemento  é formado pela palavra texto seguida do número de ordem do texto.


Probability of cards without combinatorics

Question: 5 cards are dealt from a well shuffled standard deck of cards.  What is the probability of getting 2 kings and 2 jacks?
I started by evaluating each choice in turn. Probability that the first card is a king= 4/52. That the second card is a king=3/51, that the third card is a jack=4/50, that the fourth card is a jack=3/49 and that the last card is neither a jack nor a king =44/48.
I multiply these all together to get 6336/311875200.  I know I am missing the factor to address the possible arrangements, but I am not sure how to determine this.
Any help would be appreciated
Comment: The factor for the possible arrangements is the number of distinct arrangements of the letters KKJJO. I could tell you how to do that, but I can't tell you how to do it without combinatorics.
Comment: I think I may have answered my own question (after staring at Gerry Myerson's comment).  The possible ways to arrange KKJJO are as follows: The Kings can be ordered 5C2 ways, the jacks can be ordered 3C2 ways, and the last card can be ordered 1C1 way.  Which equals 30.  Thank you Gerry.
Comment: please procede with your answer.  I'd like to know why I would use 5C3 or 5C2 or a combo of them (I think the correct factor is 30, but I can't reason it out).
Comment: When you say "without combinatorics", what exactly do you mean?  If you mean that you don't have specific background in combinatorics (eg taking a course or similar), then let us know a little of what background you do have, so we know what kind of techniques to use.
Comment: I think I am missing something basic here.  I can solve the problem as follows: 4C2*4C2*44C1/52C5, however, when I try to verify the results using the method shown above, I am off by a factor of 30.  I took a stats and prob class in college a long time ago, and I am trying to refresh my memory.
Answer: Write down all the possible patterns KKJJO such as JKOKJ.
Check they each have the same probability, so for example JKOKJ has probability $$\frac{4}{52}\times \frac{4}{51}\times \frac{44}{50}\times \frac{3}{49}\times \frac{3}{48}.$$
When you have the patterns and have checked none are repeated and none are missing then add up the probabilities of the distinct patterns.  This the same as multiplying the probability of a single pattern by the number of distinct patterns.
If you are not multiplying by thirty then you have made an error.
If you want to use combinatorics to save time, you are multiplying by $\dfrac{5!}{2!\times 2! \times 1!}$ since there are two kings, two jacks, and one which is neither a king nor a jack.


File upload form element that will allow the user to select files from server

Question: I want to achieve (Create a form that will allow the user to select files from server) in Drupal 8.3 and have followed steps 1 to 4 but for some reason it's not working at my end.
Can someone shed light how code can be updated in Drupal 8.3 to achieve above?
Thanks
Comment: I dont know the exact code to be used for ur scenario. but i was referred the attached link in your question. some of the methods are depreciated in drupal 8 . like drupal_add_js . Please refer below link. so you will get some idea. https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module and also hook_menu is depreciated in drupal 8. All route configuration is done via **routing. yml.file** Below links may helpfull to you.
https://www.drupal.org/docs/8/api/routing-system/structure-of-routes
Comment: Thanks but I already know above ref links and have successfully attached js. But my problem still remains unresolved.
Answer: I have achieved this in version 8.3 by enabling IMCE module and with the following logic i.e
1)

'edit-image-file-path-1' is id value for form field 'image_file_path_1'.
2)
$form['image_file_selector'] = array(
  '#markup' => t("
Image File *
Click to choose Image File
"),
);
$form['image_file_path_1'] = array(
  '#type' => 'textfield',
  '#attributes' => array('readonly' => 'readonly'),
  '#default_value' => $result->image_file_path_1,
);


Control compared to 4 treatment groups

Question: I'm not very strong as far as stats go, and not super familiar with this site, so I'm sorry if any formatting is wrong here. I've tried searching for this answer but I'm still lost.
I'm interested in determining if 3 new treatments (W1, W2, W3; n=100 in each W group) are similar to an established treatment (D, n=150), and different from a control (C, n=150). I have one discrete, numerical dependent variable (DV, a score out of 10). I'm a broke student, so I'm trying to do this in R as we don't have budget for SPSS, etc.
Normality is iffy (when looking at visual outputs in R via ggplot, the curve tends to be highest at lower scores - as in highest near 3 as opposed to in the actual middle at 5, again sorry if I'm reporting this in an incorrect way). BUT I've been reading that doesn't always rule out t-tests/other things that assume normality.
If I understand things right, multiple t-tests risk losing information, as this increases chances or error with each test.
Running a linear regression with dummy variables might be what I want to do, but I'm at a loss as how to do that in R.
Any help at all would be greatly appreciated, and happy to give more information if aspects are missing.
#edited to add histogram of residuals from one-way ANOVA
Answer: A classic test for multiple treatments against a baseline is Dunnett's Test. That does multiple t-tests for each treatment against the baseline group in a way that pools data from the groups and takes the multiple comparisons into account. That is implemented for example in the DescTools package. There's an example of implementation on this page. It would probably make the most sense to compare the new treatments against the established treatment rather than against the control. With your group sizes you might be able to get away with t-tests, as the critical assumption is normality of the sampling distribution of group means rather than within-group normality.
You might better use the non-parametric Mann-Whitney-Wilcoxon Test, which is almost as powerful as a t-test when normality holds and can outperform it otherwise. That's implemented in the two-sample version of wilcox.test() in R. You only have a small number of pairwise comparisons of interest (each of 3 new treatments against standard treatment, perhaps standard treatment against control), so restricting yourself to those few comparisons and using the R p.adjust() function with a "holm" correction for multiple comparisons could work well while controlling for false-positive errors.
Answer: With your sample sizes I would try the (unbalanced) one-way ANOVA, checking to see if residuals are nearly normal. Also, look to see if the five groups have similar variances.

If so, do Tukey HSD multiple
comparisons. Various pages online, perhaps this one
should show the way. [BTW, be sure to declare your factor variable as.factor and that the F-statistic has 4 numerator degrees of freedom.]

If residuals are nearly normal and variances obviously unequal, begin with oneway.test in R. If there are significant differences, then use Bonferroni ad hoc comparisons via t tests.

If residuals are clearly not normal, explore Kruskal-Wallis nonparametric "ANOVA." If there are significant differences to explore, use
suitable ad hoc tests to avoid 'false discovery' due to
multiple analyses on the same data.

Ordinarily, I would try to show analysis of an example with fictitious
data, but I don't have enough insight into the nature of
your data to avoid a possibly misleading example. If you
are in doubt following my outline above, maybe you can show boxplots of the five
groups and a normal probability plot (Q-Q plot. in R qqnorm) of residuals
in an edited version of your question.
Comment: Oh, after some searching I have run a Bartlett test, and p>0.05, so Tukey sounds like next step - thanks!
Comment: This is very helpful, BruceET! Thank you!
The residuals seem pretty normal after plotting as a histogram. Could you explain what you mean by the similar variance to check for between groups? Is this the standard deviation for each group or something else?
Comment: Reasonable first step. On to one-way ANOVA w/ Tukey's HSD. // IMHO, starting with what ought to be _ad hoc_ tests is not only widely deprecated but carries a small but worrisome chance of reaching incorrect conclusions.
Comment: Ah, I didn't realize Bartlett's was ad hoc. What is a post hoc equivalent?
Comment: Bartlett's is a reasonable preliminary to ANOVA. "Ad hoc" or "Post hoc" tests usually come after significant ANOVA to see which group means differ. // My view is that checking pairs of levels in advance of ANOVA may lead needlessly to 'false discovery".
Answer: The original question related to finding evidence for whether a treatment is similar to another treatment.  This is not what null hypothesis testing does.  To really answer the OP's question would require something like a Bayesian posterior probability of similarity, once you define similarity, e.g., the absolute value of the difference in two means being less than some number.

Control compared to 4 treatment groups


Find 3 last digits of power of power where base is huge

Question: Given $a=135797531$, find 3 last digits of $a^{a^{320}}$.
Now, I know that I need to solve: $a^{a^{320}}(\mod 1000)$.
What I know: $a\in{U_n}$ (Euler's group - Multiplicative group of integers modulo n) so that means Euler's theorem applies and $a^{\phi(1000)}\equiv1(\mod 1000)$ where $\phi(1000)=400$.
I also saw here that the exponent is congruent to the exponent modulo $\phi(1000)$ but I don't understand why and under what conditions..
I don't know how to continue from here..help!
Comment: Calculate $b=a\,\text{mod}\,1000$ and $c=a\,\text{mod}\,400$ then you'll need to find $b^{c^{320}}$. We can then calculate $\varphi(400)$ and use Euler's theorem again to reduce the power of $320$
Answer: Theorem: If $b$ and $c$ are non-negative natural numbers, $m$ and $a$ are co-prime, $b = c\enspace\text{mod}\,\varphi(m)$, then $a^b = a^c\enspace\text{mod}\,m$.
Proof: Without loss of generality, suppose that $b>c$. Then $b=c+k\cdot\varphi(m)$ where $k$ is a natural number. $$a^b = a^{c+k\cdot\varphi(m)} = a^c\cdot (a^{\varphi(m)})^k = a^c \enspace\text{mod}\,m$$
Where we used Euler's theorem for $a^{\varphi(m)} = 1\enspace\text{mod}\,m$, and the fact that $$a'=a''\enspace\text{mod}\,m\,\land\,b'=b''\enspace\text{mod}\,m\implies a'b'=a''b''\enspace\text{mod}\,m$$
End of proof.
Suppose we want to calculate $a^{a^{320}}$ modulo $1000$. We can first calculate $a^{320}$ modulo $\varphi(1000)=400$ since $a$ and $1000$ are co-prime, using the theorem above.
To calculate $a^{320}$ modulo $400$, we can calculate $320$ modulo $\varphi(400)=160$, because, again, $400$ and $a$ are co-prime.
$$320 = 0\enspace\text{mod}\,160 \implies a^{320} = 1\enspace\text{mod}\,400 \implies a^{a^{320}}=a\enspace\text{mod}\,1000 $$
And because $a=531\enspace\text{mod}\,1000$, then
$$a^{a^{320}}=531\enspace\text{mod}\,1000  $$
Comment: Amazing, thanks a bunch! the second explanation really cleared things up.
Comment: I think you wrote 360 instead of 320 in exponents' exponent.
And how did you find $a (mod 400)$?
Comment: @eagleye yes, you're right, thanks. I've edited my post for more clarity, and also corrected my mistakes. It's a lot easier now that there's $320$ in exponent


Angular MatBadge not showing full number when it's higher than 99

Question: I have a notification count that shows the quantity of notifications for a specific user, but when the user has more than 99 notifications, the matBadge doesn't show the full number, it shows '1...', like the image below. Can anyone tell how to fix? I want to display the full number.

I tried to change da position of the badge or increasing the badge area but it did not work
Comment: you need to overwrite and make badge bit bigger
.mat-badge-*** { width: 28px;
    height: 28px;
    line-height: 28px;}
depending on which badge you are using replace *** with one of these values. 'small' | 'medium' | 'large'

Angular is great. but unfortunately, Material library is bit funky. well at least it is free :)
Answer: Setting a fixed width and height is not the best option out there.
Add the following CSS in styles.scss:
.mat-badge-content {
  width: auto !important; // Set the width to auto
  height: auto !important; // Set the height to auto
  min-width: 22px; // But the width should be at least 22px (in case the number is 99 or less)
  min-height: 22px; // But the height should be at least 22px (in case the number is 99 or less)
  aspect-ratio: 1/1; // Keep the circle shape
  display: flex; // Required in order for align-items and justify-content to work
  align-items: center; // Center the number vertically
  justify-content: center; // Center the number horizontally
  padding: 2px; // Add a bit of padding so that the number is not placed all the way to the border of the circle
}

Screenshot:

See the live demo.


How to make formule bigger in org-mode of Emacs?

Question: I found Org-mode + LaTeX to be a very wonderful tool.  How can I alter the scale of formula?  Currently it is too small for me.  I know how to scale the Emacs font (C-x+), but this does not work for LaTeX formulas.
How can make the LaTeX formulae bigger in Org-mode?
I have tired to change some parameters, but the problem still remains.
Thank you for your patience!
Answer: According to the
documentation
or (info "(org) Previewing LaTeX fragments")
You can customize the variable `org-format-latex-options' to
influence some aspects of the preview. In particular, the `:scale'
(and for HTML export, `:html-scale') property can be used to
adjust the size of the preview images.

A quick
C-hvorg-format-latex-optionsRET
gives us:
org-format-latex-options is a variable defined in `org.el'.
Its value is (:foreground default :background default :scale 1.0 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0 :matchers
             ("begin" "$1" "$" "$$" "\\(" "\\["))

Documentation:
Options for creating images from LaTeX fragments.
[snip]
:scale       a scaling factor for the size of the images, to get more pixels
[snip]

For example, to set the scale to 2.0:
(setq org-format-latex-options (plist-put org-format-latex-options :scale 2.0))

Comment: Do not forget to `(require 'org)` in advance.
Comment: But this affects inline and display equations. Is there a way to set separate settings for inline and display equations?
Comment: What if I want to change the scale per file or only the scale of a snippet?


mutual information for testing set enrichment?

Question: I've created a process that associates members of two sets, specifically codes from the International Classification of Diseases (ICD) hierarchy  and the semantically richer Monarch Disease Ontology (MonDO). (MonDO already does something similar, but my method also associates ICD codes that have a path to a MonDO term via other terms in a linked data cloud.)
I would like to find the MonDO association that is most enriched for each ICD term. (One ICD code can be associated with multiple MonDO terms, and vice versa. ) I have started with a "hammer and nail" approach that's familiar to me: a hypergeometric calculation like one would use for gene set enrichment(1,2), except I'm calculating a test statistic with R's dnorm instead of testing hypotheses and returning p-values.
I have some subjective comfort with the hypergeometric approach (see below), but my boss (a genetics professor) would like me to try an information entropy or mutual information approach. I have no idea how to get started with that. My reading has led me to believe that mutual information is about the relationship between two variables, not between specific levels of those variables.  Along those lines, R's infotheo::mutinformation and  widyr::pairwise_pmi both seem to return summary statistics for the dataset, not an assessment of each association.

Hypergeometric reality check:
For the ICD associations that I've spot checked, the MonDO term with the lowest hypergeometric statistic generally has the best semantic alignment (subjectively speaking), even if the lexical similarity is low. For example, my process finds the following associations from ICD9CM:250.4, "Diabetes with renal manifestations":
+---------------+----------------+--------------------------------------+
|  MonDO.term   | hyperg.density |             MonDO.label              |
+---------------+----------------+--------------------------------------+
| MONDO:0005016 |     -7.8638915 | diabetic nephropathy                 |
| MONDO:0005015 |     -4.0628001 | diabetes mellitus (disease)          |
| MONDO:0005240 |     -4.0516889 | kidney disease                       |
| MONDO:0002908 |     -4.0406997 | glucose metabolism disease           |
| MONDO:0037792 |     -3.9797537 | carbohydrate metabolism disease      |
| MONDO:0020595 |     -3.5348043 | disease of retroperitoneum           |
| MONDO:0002118 |     -3.4197708 | urinary system disease               |
| MONDO:0005066 |     -3.2170997 | metabolic disease                    |
| MONDO:0005151 |     -3.1992739 | endocrine system disease             |
| MONDO:0021145 |     -2.4329025 | disease of genitourinary system      |
| MONDO:0044965 |     -1.9260256 | abdominal and pelvic region disorder |
| MONDO:0021199 |     -0.1740629 | disease by anatomical system         |
| MONDO:0024505 |     -0.1172667 | disorder by anatomical region        |
+---------------+----------------+--------------------------------------+

I'm modelling this as an urn that contains one ball for each ICD code. Each ball is annotated with one or more MonDO terms. Referring to R's formula
dval <- dhyper(x, m, n, k)

I'm using 1 for both x and k, because I know that I'm drawing one known ICD code, and testing for the enrichment of a MonDO term that my method has associated. N is the total number of ICD codes that have been associated with at least one MonDO code, m is the total number of the associated ICD codes that have been specifically associated with a given MonDO code, and n = N - m.
Answer: Here's the solution my boss and I have come up with
To summarize: my process can associate a given ICD diagnosis code with multiple MonDO disease terms, but one of our collaborators is requesting a single "best" MonDO term for each ICD code.
We're considering the informational value of each MonDO term to be
1/(total number of associated ICD terms)

We'll probably scale or normalize that by some constant, but even without any normalization, it generates subjectively reasonable rankings like the ones for ICD9CM:250.4, "Diabetes with renal manifestations", in the question.


Determining which service Windows Firewall is blocking?

Question: I'm working on setting up a hardened application server with the Windows Firewall enabled.
OS is 2008 R2. We're using the Advanced firewall settings and have IPSec and Kerberos authentication if it matters. One of my other hosts (192.168.100.21) needs to reach my server (192.168.100.29) in order for my application to work properly. If I allow all inbound traffic from that IP it functions flawlessly. That unfortunately doesn't meet my regulatory requirements.
The auditing events show that the connection attempt is being made to svchost, however it isn't succeeding. How can I determine which service(s) are attempting to be accessed?
I've used the debugging auditing shown below to determine the svchost behavior.
<code>auditpol /set /subcategory:"Filtering Platform Packet Drop" /success:enable /failure:enable
auditpol /set /subcategory:"Filtering Platform Connection" /success:enable /failure:enable
auditpol /set /subcategory:"IPsec Driver" /success:enable /failure:enable
auditpol /set /subcategory:"IPsec Main Mode" /success:enable /failure:enable
auditpol /set /subcategory:"IPsec Quick Mode" /success:enable /failure:enable
auditpol /set /subcategory:"IPsec Extended Mode" /success:enable /failure:enable
</code>
Answer: As you know SVCHOST is just an umbrella service for underlying services, most of which manifest themselves as DLLs, as opposed to EXEs.  If it were me, I'd use three Microsoft SysInternals tools and TASKLIST:

ProcessMonitor : This will let you actually see the TCP/UDP requests, and more specifically, which port(s) are being used
TCPView : This lets you see TCP/UDP connections come and go (kind of like a live NETSTAT)
ProcessExplorer : This will let you see dig around and see exactly which SVCHOST instance is being referenced

So, once you've seen the TCP/UDP activity, and you know which SVCHOST is being referenced, and you know which ports, you can use TASKLIST to see which services are being hosted by that SVCHOST (tasklist /svc /fi "imagename eq svchost.exe"), and then, using the port number, deduce exactly which service it is.
That would be my approach anyway.  Good luck.


Common code in React component constructor and componentWillReceiveProps

Question: I often come to this sort of situation when using statefull React components.
I need to do some operation on props - either do some processing which I do now want to have in render() or set state according the values in props.
As I want to do this when component is initially mounted as well as when the props are updated, I end up with a boilerplate code like this:
constructor(){
    super(props)
    const modifiedProps = doSomethingWithProps(props)
        ...
    this.state = {initialState}
}

componentWillReceiveProps(nextProps) {
    const modifiedProps = doSomethingWithProps(nextProps)
         ...
    this.setState({newState})
}

doSomethingWithProps(props){
        ...
}

Is there a better way how to do this ?
Comment: Agreed, I wouldn't use `constructor` for this, `componentWillMount`, is usually where I put all my code for this kind of thing.
Comment: if you are not setting state, you can use `componentDidMount` instead of `constructor`
Comment: @TryingToImprove Is `componentDid/WillMount` called even when the props are just updated ?
Comment: "Better" how? That's a fairly canonical way to extract functionality.
Comment: That is a boilerplate for me and one which happens quite often.
Comment: @dev-null no, it will not.
Answer: Answering based on the question's comments, which I found quite helpful --
If there's a bunch of work that needs to be done based on props, componentWillMount allows you to use this.setState() in your helper functions and minimize the work that's done in the constructor.  This can clean up a bunch of otherwise duplicated code.
constructor(){
    super(props)
    this.state = {initialState}
}

componentWillMount() {
    this.doSomethingWithProps(this.props);
}

componentWillReceiveProps(nextProps) {
    this.doSomethingWithProps(nextProps)
}

doSomethingWithProps(props){
    ...
    this.setState({newState})
}

Answer: Why not pass the props to the component after they are transformed?
This can be achieved in a couple of ways:

Use a simple stateless container, which transforms the props and passes them to this component.
export const Container = (props) =>
    <YourComponent modifiedProp={doSomethingWithProps(props)} />

Use a connected component and do the transformation inside the mapStateToProps method:
const mapStateToProps = (state, ownProps) => ({
    modifiedProp: doSomethingWithProps(ownProps)
});

export const ConnectedComponent = connect(mapStateToProps)(YourComponent);

The first option is really a stripped-down version of the second.
You may also be interested in using selectors to compute the derived props that you pass to your component.


Kaminari Navigation Menu doesn't show up

Question: I'm using Kaminari for pagination.
Using the following lines in my controller:
@public_items =Array.new
@items= Item.all
@items.each do |item|
    if (item.is_public)
        @public_items <<item
    end
end
@public_items = Kaminari.paginate_array(@public_items).page(params[:page]).per(4)

and this line in my view
<%paginate @public_items %>
<% @public_items.each do |item| %>
.....
<%end%>

The pagination works fine meaning i can navigate to different pages by going to items?page=2 for example but the page navigation menu () doesn't show up!
and <%paginate @public_items %> does not create any html code
Answer: Shouldn't it be:
<%= paginate @public_items %>

Including the equals sign. Without the equals sign it hides it.


Conditions for convergences of a net

Question: I got stuck on this problem and got no clue to solve it. Can anyone one here help me? I really appreciate.

Let $X$ be a set and $\mathcal{A}$ the collection of all finite subsets of $X$, directed by inclusion. Let $f: X \rightarrow \Bbb{R}$ be an arbitrary function and for $A \in \mathcal{A}$, let $z_{A} = \sum_{x\in A}f(x)$. Then the set $< z_{A} >$ converges in $\Bbb{R}$ iff $\{x: f(x) \neq 0 \}$ is a countable set $\{x_{n}\}_{n \in \Bbb{N}}$ and $\sum_1^\infty|f(x_{n})| \lt \infty$, in which case $z_{A} \rightarrow \sum_1^\infty f(x_{n})$

Thanks so much
Answer: The $\Leftarrow$ direction is pretty straightforward, I think.
For the $\Rightarrow$ direction, try the contrapositive.  There are two cases to consider; the case that the function has uncountable support, and the case where the function has countable support, but does not converge absolutely on that support. You have to show that $\langle z_A\rangle$ does not converge in either case.
The second condition is again pretty straightforward: if the series does not converge absolutely, then there is a sequence $x_{n}$ for which the sequence of partial sums $\sum_{n=1}^{k}f(x_{n})$ does not converge, and you're done.
The more interesting case is when the function has uncountable support.  Use the pigeonhole principle to conclude that there is some rational $q$ such that the set $$\big\{x\in X \,\big\vert\, \vert f(x)\vert >q\big\}$$ is infinite.  It should be easy from there.
Comment: "if the series does not converge absolutely, then there is a sequence $x_n$ for which the sequence of partial sums $\sum_{n=1}^{k}f(x_n)$ does not converge". Can you please explain about this point? I don't get it. Thanks
Comment: Suppose that there are only countably many $x\in X$ for which $f(x)\neq 0$. Fix an enumeration $\langle x_{k}\vert k\in\mathbb{N}\rangle$. Then we are saying that $$\sum_{k=1}^{\infty}\vert f(x_{k})\vert$$ does not converge. Let $\langle l_{j}\vert j\in\mathbb{N}\rangle$ be such that the subsequence $\langle x_{l_{j}}\vert j\in\mathbb{N}\rangle$ picks out those $x$ such that $f(x)>0$, and let $m_{j}$ be similar for the $f(x)<0$. If it were the case that both $$\sum_{j=1}^{\infty}f(x_{l_{j}})$$ and $$\sum_{j=1}^{\infty}f(x_{m_{j}})$$ converge, then $\sum f(x_{k})$ would converge absolutely.

Conditions for convergences of a net


Retrofitting void methods to return its argument to facilitate fluency: breaking change?

Question:
"API design is like sex: make one mistake and support it for the rest of your life" (Josh Bloch on twitter)

There are many design mistakes in the Java library. Stack extends Vector (discussion), and we can't fix that without causing breakage. We can try to deprecate Integer.getInteger (discussion), but it's probably going to stay around forever.
Nonetheless, certain kinds of retrofitting can be done without causing breakage.

Effective Java 2nd Edition, Item 18: Prefer interfaces to abstract classes: Existing classes can be easily retrofitted to implement a new interface".

Examples: String implements CharSequence, Vector implements List, etc.

Effective Java 2nd Edition, Item 42: Use varargs judiciously: You can retrofit an existing method that takes an array as its final parameter to take varags instead with no effect on existing clients.

An (in)famous example is Arrays.asList, which caused confusions (discussion), but not breakage.
This question is about a different kind of retrofitting:
Can you retrofit a void method to return something without breaking existing code?
My initial hunch points to yes, because:

Return type doesn't affect which method is chosen at compile time

See: JLS 18.104.22.168 - Return Type Not Considered
Thus, changing return type doesn't change which method is chosen by the compiler
Retrofitting from void to return something is legal (but not the other way around!)

Even when you use reflection, things like Class.getMethod doesn't distinguish on return type

However, I'd like to hear a more thorough analysis by others more experienced in Java/API design.

Appendix: The Motivation
As suggested in the title, one motivation is to facilitate fluent interface style programming.
Consider this simple snippet that prints a shuffled list of names:
    List<String> names = Arrays.asList("Eenie", "Meenie", "Miny", "Moe");
    Collections.shuffle(names);
    System.out.println(names);
    // prints e.g. [Miny, Moe, Meenie, Eenie]

Had Collections.shuffle(List) been declared to return the input list, we could have written:
    System.out.println(
        Collections.shuffle(Arrays.asList("Eenie", "Meenie", "Miny", "Moe"))
    );

There are other methods in Collections that would've been much more pleasant to use if they were to return the input list instead of void, e.g. reverse(List), sort(List), etc. In fact, having Collections.sort and Arrays.sort return void is especially unfortunate, because it deprives us from writing expressive code such as this:
// DOES NOT COMPILE!!!
//     unless Arrays.sort is retrofitted to return the input array

static boolean isAnagram(String s1, String s2) {
    return Arrays.equals(
        Arrays.sort(s1.toCharArray()),
        Arrays.sort(s2.toCharArray())
    );
}

This void return type preventing fluency isn't just restricted to these utility methods, of course. The java.util.BitSet methods could've also been written to return this (ala StringBuffer and StringBuilder) to facilitate fluency.
// we can write this:
    StringBuilder sb = new StringBuilder();
    sb.append("this");
    sb.append("that");
    sb.insert(4, " & ");
    System.out.println(sb); // this & that

// but we also have the option to write this:
    System.out.println(
        new StringBuilder()
            .append("this")
            .append("that")
            .insert(4, " & ")
    ); // this & that

// we can write this:
    BitSet bs1 = new BitSet();
    bs1.set(1);
    bs1.set(3);
    BitSet bs2 = new BitSet();
    bs2.flip(5, 8);
    bs1.or(bs2);
    System.out.println(bs1); // {1, 3, 5, 6, 7}

// but we can't write like this!
//  System.out.println(
//      new BitSet().set(1).set(3).or(
//          new BitSet().flip(5, 8)
//      )
//  );

Unfortunately, unlike StringBuilder/StringBuffer, ALL of BitSet's mutators return void.
Related topics

Method chaining - why is it a good practice, or not?
Answer: Unfortunately, yes, changing a void method to return something is a breaking change. This change will not affect source code compatibility (i.e. the same Java source code would still compile just like it did before, with absolutely no discernible effect) but it breaks binary compatibility (i.e. bytecodes that was previously compiled against the old API will no longer run).
Here are the relevant excerpts from the Java Language Specification 3rd Edition:

13.2 What Binary Compatibility Is and Is Not
Binary compatibility is not the same as source compatibility.

13.4 Evolution of Classes
This section describes the effects of changes to the declaration of a class and its members and constructors on pre-existing binaries.
13.4.15 Method Result Type
Changing the result type of a method, replacing a result type with void, or replacing void with a result type has the combined effect of:

deleting the old method, and
adding a new method with the new result type or newly void result.

13.4.12 Method and Constructor Declarations
Deleting a method or constructor from a class may break compatibility with any pre-existing binary that referenced this method or constructor; a NoSuchMethodError may be thrown when such a reference from a pre-existing binary is linked. Such an error will occur only if no method with a matching signature and return type is declared in a superclass.

That is, while the return type of a method is ignored by the Java compiler at compile-time during the method resolution process, this information is significant at run-time at the JVM bytecode level.

On bytecode method descriptors
A method's signature does not include the return type, but its bytecode descriptor does.

8.4.2 Method Signature
Two methods have the same signature if they have the same name and argument types.

15.12 Method Invocation Expressions
15.12.2 Compile-Time Step 2: Determine Method Signature
The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.
22.214.171.124 Example: Compile-Time Resolution
The most applicable method is chosen at compile time; its descriptor determines what method is actually executed at run time.
If a new method is added to a class, then source code that was compiled with the old definition of the class might not use the new method, even if a recompilation would cause this method to be chosen.
Ideally, source code should be recompiled whenever code that it depends on is changed. However, in an environment where different classes are maintained by different organizations, this is not always feasible.

A little inspection of the bytecode will help clarify this. When javap -c is run on the name shuffling snippet, we see instructions like this:
invokestatic java/util/Arrays.asList:([Ljava/lang/Object;)Ljava/util/List;
             \______________/ \____/ \___________________/\______________/
                type name     method      parameters        return type

invokestatic java/util/Collections.shuffle:(Ljava/util/List;)V
             \___________________/ \_____/ \________________/|
                   type name        method     parameters    return type

Related questions

java: what is this: [Ljava.lang.Object;?

On non-breaking retrofitting
Let's now address why retrofitting a new interface or a vararg, as explained in Effective Java 2nd Edition, does not break binary compatibility.

13.4.4 Superclasses and Superinterfaces
Changing the direct superclass or the set of direct superinterfaces of a class type will not break compatibility with pre-existing binaries, provided that the total set of superclasses or superinterfaces, respectively, of the class type loses no members.

Retrofitting a new interface does not cause the type to lose any member, hence this does not break binary compatibility. Similarly, due to the fact that varargs is implemented using arrays, this kind of retrofitting also does not break binary compatibility.

8.4.1 Formal Parameters
If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[].

Related questions

Difference between double… and double[] in formal parameter type declaration

Is there absolutely no way to do this?
Actually, yes, there is a way to retrofit a return value on previously void methods. We can't have two methods with the same exact signatures at the Java source code level, but we CAN have that at the JVM level, provided that they have different descriptors (due to having different return types).
Thus we can provide a binary for e.g. java.util.BitSet that has methods with both the void and non-void return types simultaneously. We only need to publish the non-void version as the new API. In fact, that's the only thing we can publish at the API, since having two methods with the exact same signature is illegal in Java.
This solution is a terrible hack, requiring special (and spec-defying) processing to compile BitSet.java to BitSet.class, and thus it may not be worth the effort to do so.
Comment: Regarding the "terrible hack", see the [bridge-method-injector](http://bridge-method-injector.infradna.com/) tool. There are serious downsides but it works.
Answer: If you have to deal with source compatability only, then just go ahead.  Changing from void to a return type will not break.
But to address the thing you actually want to do:
I consider the problem with fluent interfaces is that the lines tend to get rather long and - after formatting - somewhat unreadable.   For builders it works fine, but I'd probably not use it for anything else.
Is this for playing with it, or because you've found that this is really great?
Comment: "Is this for playing with it" - playing, learning, etc. Nothing serious for now.
Comment: Then do some toy stuff not used by others for now.  Especially the Builder pattern requires a lot of typing to be fully functional.
Answer: If you can't retrofit, you still can wrap your class into a new one which uses the same methods but with correct returns (MyClassFluent).
Or you can add new methods but with different names, instead of Arrays.sort() we could have Arrays.getSorted().
I think that the solution isn't to force things, just deal with them.
EDIT: I know I didn't answer to the "retrofitting of void methods" question, but your answer is already really clear.
Comment: LOL I just realized that you're the one who wrote this answer. http://stackoverflow.com/questions/3550469/how-to-compare-2-strings-containing-same-characters/3550519#3550519 - yes, we 10K-ers can see deleted answers. That answer is the one that finally made me investigate this problem in greater detail. I'm glad that I'm not the only one who wished that `Arrays.sort` returns the array.
Comment: Alternatives of course exist, but since some types of retrofitting to improve an API is possible (e.g. can you imagine if making `String` a `Comparable` is a breaking change???), I'd like to know where the boundaries are, and how far it can be pushed.
Comment: As you said, this kind of retrofitting isn't the "standard one". Making `String` a `Comparable` means that we *add* something, here you want to *change* something. I'm not even sure that we can call that retrofitting.
Comment: Well, the Arrays.sort() problem happens to me way too often. But I expect a returned result from a static method, not parameters updated. For example if StringBuilderUtils.toUpperCase(StringBuilder sb) existed, I would expect to get a new StringBuilder, not a modified sb and a void return.


Memcache integration is not loaded

Question: I'm trying to setup memcache on my drupal 7 site. I have a memcache server setup and working and I've used setsebool -P httpd_can_network_memcache 1 to allow apache to communicate with it. I've also confirmed that port 11211 tcp is open in ip tables.
I've installed the memecache drupal extension, the PECL extension in PHP and when I run phpinfo(); I see that memcache is loaded.
In settings.php on my drupal web server I have the following:
/**************************************************
 * MEMCACHE
 **************************************************/
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['memcache_servers'] = array(
        'memcacheserver.ourdomain.local:11211' => 'cluster'
);

$conf['memcache_bins'] = array(
        'bin1' => 'cluster'
);

$conf['memcache_key_prefix'] = 'sdrupal';

However when I go to the status reports page I see the following:
Memcache integration    Memcache integration is not currently loaded.
Check README.txt and ensure that memcache.inc is configured correctly in settings.php
I've read through the readme.txt file repeatedly and of course you can see I have memcache.inc specified above.
I thought perhaps I had a conflict with the varnish module, or the apc module as those also set cache_backends - but its an array so I think thats ok. I also commented them out and I'm still seeing the error above.
I also confirmed that sites/all/modules/memcache/memcache.inc exists.
Why isn't drupal loading/finding memcache.inc?
Thanks
Brad
Comment: I've setuop a test memcache page as follows which works: addServer('memcacheserver.ourdomain.local', 11211) or die ("Could not connect");
    $memcache->addServer('memcacheserver.ourdomain.local', 11211) or die ("Could not connect");

$memcache->set('mytestvariable', "this is the data in my test variable", false, 60) or die ("Unable to save the data to the server");
    echo "Data has been stored in the cache";

$result = $memcache->get('mytestvariable');
    echo "Retrieved data from the server:";

var_dump($result);
?>
Comment: Please [edit](http://drupal.stackexchange.com/posts/68494/edit) rather than comment if you have some clarifications to add.
Answer: You've got to add these lines to your settings.php file to run memcache proper:
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

If you're on top of a multisite installation also don't forget to add this one:
$conf['memcache_key_prefix'] = 'unique_key';

More information about configuration and setting memcache for drupal you can find here.
Answer: To get this to work I had to comment out the following line:
//$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';

And add:
// the path to the core cache file
include_once('./includes/cache.inc');
// the path to the memcache cache file
include_once('./sites/all/modules/memcache/memcache.inc');

I'd love to know why this is necessary and what the difference is but at the moment it seems to be working.
Answer: You need to flush APC cache somehow to make the command work. Restarting Apache will do just fine. No need to manually use include_once() to load the fields.
In my case, this was cased by the APC setting apc.ttl that was set to 0 to prevent the cache from expiring until Apache was restarted.
Answer: Please check the following example:
/**
 * Memcached Configuration
 */
if (class_exists('Memcache') || class_exists('Memcached')) {

  // Make memcache the default cache class.
  $conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc'; // NOTE: Just verify path where you've memcache module placed.
  $conf['cache_default_class'] = 'MemCacheDrupal';
  $conf['memcache_key_prefix'] = 'drupal_';

  // Ensure that the special cache_form bin is assigned to non-volatile storage.
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

  // Support for Memcached PECL extension
  // This new extension backends to libmemcached
  // and allows you to use some of the newer advanced features in memcached 1.4.
  if (class_exists('Memcached')) {
    // Enable the binary protocol, which is more advanced and faster.
    $conf['memcache_options'] = array(
        Memcached::OPT_BINARY_PROTOCOL => TRUE,
    );

    // Memcached takes options directly from Drupal.
    $conf['memcache_options'] = array(
        Memcached::OPT_COMPRESSION => TRUE, // Turn off compression, as this takes more CPU cycles than its worth for most users.
        Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT, // Allows you to add/remove servers easily.
    );
  }
}

It will automatically detect which memcache extension are you using and it'll load classes only it's present. In addition it has some common useful stuff.

Troubleshooting:

check that your memcache module is enabled,
go to /admin/reports/status/php and verify that you've section called memcache or memcached (if not, you've to properly install it, check your logs),
when using command line, check your memcache via: php -m | grep memcache
check at /admin/reports/status if you still having some issues,
make sure that your memcached is up and running,
Comment: How can we do this setting for drupal 8 memcache

Memcache integration is not loaded


Forcing a callback function to occur on another function

Question: I'm using this proprietary 360 viewer — http://truview.ortery.com/ImageCreator/SampleWeb/HTML5Viewer_cylindrical.html
It's not responsive and all the JS it runs in obfuscated/encoded so I cannot modify it.
I want to run JS after it's happened to remove the inline style declarations it adds so that it becomes responsive.
This is the JS I need to run after the viewer has initialised
jQuery('.animateCreatorContainer, .animateCreatorPhoto').removeAttr('style');

Answer: To force that as a callback, you have to be in control of the flow of execution. In order to do that, the 360 viewer needs to know that it has to execute a callback after its completed whatever it needs to complete.
In other words, you have to code the 360 viewer so that it'll call a callback. You limited options:

Don't use that library
Modify the library code

This is only if the 360 viewer operates asynchronously, or at a point when you cannot determine the exact time the code execution is happening.
Normally, to force synchronistic flow of execution, you'll just put your calls one right after the other:
doSomething();

doSomethingElse();

Anything that occurs in doSomethingElse that can modify elements acted on by doSomething will do so. So that's your third option (making sure you remove the style attribute only after you know the 360 viewer code has executed.)
Comment: Thanks… I tried executing after but it basically seems to happen before `animate360()` has finished and so the viewer fails completely… whereas if i leave out that `removeAttr` line… then load page and manually strip it out of the loaded DOM then I get what I want. I might just build my own 360 viewer :D


How to redirect user after logout from ADFS?

Question: I have a page that authenticate using ADFS and it have logout but it don't logout from ADFS only from the site. How can I logout from ADFS and then redirect to a page from my site? I've try this url:
https://{auth-server}/adfs/ls/?wa=wsignout1.0&wreply=https://example.com/landingPage

it logout but don't redirect back to my site, how can I redirect to certain page after logout?
Answer: Hey it's old but this solution might help someone in need some day :D.
The page to which you are to redirecting needs to be in the adfs trusted page lists. If it's not present in the trusted URI, ADFS just ignore your request. So basically you can't redirect to https://example.com/landingPage if it's not a trusted URI.
It is thoroughly explained here :
https://www.sevecek.com/EnglishPages/Lists/Posts/Post.aspx?ID=93
I tried, Geh123's answer, it didn't work. You don't need the braces !
Answer: Try this one:
https://{auth-server}/adfs/ls/?wa=wsignout1.0&wreply={https://example.com/landingPage}

Note that there now are curly braces around the data of the wreply parameter.
Comment: Please provide an explanation.


Different representation of consecutive sixteenth notes

Question: These are two different bars from "John Thompson's Grade 3" arrangement "Hungarian Rhapsody no.2".
Is there a difference between the time value of the first F in the first picture and the first D in the second picture?
Answer: The difference in the way you would play these is very subtle.
Beams convey information about subtle shifts in phrasing, and about how the composer wants you to subdivide the beats in the measure for rhythmic emphasis. This is up to the interpretive skill of the performer. When you perform groups of sixteenth notes, you don't necessarily mechanically give all of them the same precise duration. You don't necessarily make each note's attack happen exactly on a "quantized grid" at a precise moment in time, if you know what I mean.
These four measures are exactly the same pitches with exactly the same note durations, but a skilled musician would phrase each measure slightly differently.
Comment: This answers a different question.  The slur over-rides any possible subtleties in the beaming.
Comment: Wrong. Subtleties of articulation are indicated by slurs, staccato dots, etc.. There are none in this answer. If one example were in 4/4 and another in 2/2, the one in 4/4 would have 4 beats to the bar, and you might argue that that implies a slight accent at the start of each of those 4 beats, and that 2/2 would thus imply a different pattern of accents. But even that argument would be debatable. Beaming doesn't imply anything about articulation at all.
Answer: No difference in note length, no. The editor might just want to show some phrasing information, but to be honest I don't see the point. The slur does that just as well, or even better.
Answer: Given the slur, I think I can risk a definitive answer - no, there's no difference.  Not even a subtle one.
Comment: No, you *can* subtly change the volumes of each note under the same slur.
Comment: And would you?  For that sort of beaming difference?  Really?
Comment: There's a fair chance I might.


What do I set GUID to in Feeds Import?

Question: I was told I should use GUID and tick Unique setting for best method of filtering out duplicate content each time cron runs. But what do I set GUID to? My XML sources has like only ,  etc.
Now I am using Title as unique for duplicates. But I get lots of random issues, Feeds Import doesn't import all feeds after each cron, or even better, it gets stuck e.g. 'Importing 48%' and etc.
I got 4 feed imports that parse XML from external site, all from same site (also Drupal). Also I use custom module to trigger them when running cron, because by default Feed Import doesn't even react to hourly cron.
So trying various solutions, maybe this GUID thing will solve this.
I also use XPath XML parser.
Answer: You can use a the node or article URL as it's Unique and a lot of feeds use it with no issues at all
Comment: I forgot to mention I use XPath XML parser, so if Target is Node ID, what do I set it to in Settings for XPath XML parser under nid field? Also put in just 'nid'?

What do I set GUID to in Feeds Import?


What is a good software for data collection à la  CDC's Epi Info?

Question: I am a medical student working on a project which requires massive data that are collected manually through data entry operators. Although I am using traditional tool used by epidemiologists, Epi Info, I just wanted to know if anyone could recommend some good alternatives--not necessarily free/open source though preferred.
The data has been already collected, but its all in papers, spanning over five years. It contains ~22 fields and is for many individuals, by that I mean >100,000. Im from India, although Im in a medical college, this project is our sole endeavor (i.e, self funded). Double data entry proposal in on table but a final call on check mechanisms will be taken only after the pilot study.
The whole data is hand written (literally scribbled) and is indeed inconsistent at many places. Although I have almost designed the whole form in Epi Info which involves drop down boxes, radio buttons, check boxes and takes advantage of Check Code wherever required. My concerns with Epi Info are- the present version ie., EI7 though promises to incorporate Geocode, unfortunately I could not get it to work, even after getting separate keys from Bing. But, as a potential solution I would be using Google API, which would though limit queries ~2500/day/IP (yes there are workarounds).
Secondly, Epi Info is painfully slow and its giving me some hard time whether to place confidence in it for a such a huge data especially when merging will be required and when reimporting of the data will be required after editing it in excel (geocoding and other cleaning discrepancies). Personally latest version has a very good Dashboard for data analysis, but many among us are in favour of SPSS.
Lastly, we are not in favour of any web based application (ofcourse because we dont have internet everywhere here, and that has to be fast as well), an offline solution is required.
Comment: The data has been already collected, but its all in papers, spanning over five years. It contains ~22 fields and is for many individuals, by that I mean >100,000. Im from India, although Im in a medical college, this project is our sole endeavor (i.e, self funded). Double data entry proposal in on table but a final call on check mechanisms will be taken only after the pilot study.
Comment: The whole data is hand written (literally scribbled) and is indeed inconsistent at many places. Although I have almost designed the whole form in Epi Info which involves drop down boxes, radio buttons, check boxes and takes advantage of Check Code wherever required.
My concerns with Epi Info are- the present version ie., EI7 though promises to incorporate Geocode, unfortunately I could not get it to work, even after getting separate keys from Bing. But, as a potential solution I would be using Google API, which would though limit queries ~2500/day/IP (yes there are workarounds).
Comment: Secondly, Epi Info is painfully slow and its giving me some hard time whether to place confidence in it for a such a huge data especially when merging will be required and when reimporting of the data will be required after editing it in excel  (geocoding and other cleaning discrepancies). Personally latest version has a very good Dashboard for data analysis, but many among us are in favour of SPSS. @Jonathan
Comment: Are you looking for data entry software (database) or statistical analysis software? Be more specific and perhaps we can help.
Comment: Yes, Im looking for a data entry software, which would enable me to create data entry operator friendly forms which after filling would in turn generate a database in an excel sheet.
Comment: Can you give us a better idea of what kind of data you're collecting?  Is this cross-sectional?  Longitudinal?  Are you collecting many fields for a few individuals, a few fields for many individuals, many for many?  How massive is massive?  What country are you in, and which institutions are you affiliated with?  Are you doing double data entry?  We need so much more info!
Comment: Can you tell us more about the data format, and edit the original question to include the information in there? The more details the better. For example, if the data is typed/printed on paper and present on consistent styles of forms, you will probably want to use one of the many form-scanning-OCR solutions out there. If it's handwritten or inconsistent then you will need more manual methods.
Comment: Also it would help to know why you are looking for an alternative to Epi Info. There are many potential tools and knowing more about your desires will help with making a recommendation. Is it too slow/costly? Not enough data validation? etc.
Answer: Very interesting question.  The three tasks you have at hand (data entry, geocoding, and data analysis) are all things that can be done by one program or by three (or more) completely separate programs.  This isn't an "answer", exactly, but I've outlined my experiences below.
Data Entry:

MS Access: The old standby.  Build forms and enter data.  Potentially hazardous if you have multiple users entering data simultaneously.  I've used this for some small projects and would prefer to avoid it in the future - I had weird problems with records linked across tables, but your data sounds like you have just one table.  You'd have to have sufficient licenses and computers with Windows.  I find it slow, but most of my Access DBs are on a network drive across campus, so that's part of the problem.
SurveyMonkey: SurveyMonkey can make a reasonably good data entry tool for simple, form-based input - there are a few configuration tweaks necessary, but I've used this for entering a few thousand surveys.  It's web-based, so you'd need a sufficiently reliable Internet connection, but otherwise you're using SurveyMonkey's hardware.  Shouldn't be any problem with multiple simultaneous data entry, and it has several options for data export.  You'd need at least the Select plan (US$17 per month) to get unlimited questions and respondents.
RedCAP: Vanderbilt University runs a consortium around its RedCAP software, which is purpose-built for research (including medical research).  You have to be part of the consortium to use it, though, and I think most consortium members host their own servers - but you might be able to piggyback on someone else's.
A homebrew solution built on a web framework (e.g., Django or Rails): Provides maximum control, but also has the highest technical capacity requirements.  I've played around with Django a bit and I think you could get a 22-field form up pretty quickly.  I don't think 22 x 100k counts as "big" where Django is concerned.

Data Analysis:
Does Epi Info support writing code for analysis, or is it limited to the widgets and other menu-driven choices I saw in the tutorial video?  Coding up an analysis is key for being able to reproduce results and find errors, so if Epi Info doesn't have that, SPSS would be an improvement.  Better still, R - it's free, has a really robust community, and has packages that will let you do just about any kind of analysis you'd like. All of three of these should be able to import data from whatever data entry option you choose, so don't worry about that.

Geocoding (and, I'm assuming, some mapping):
The maps in Epi Info looked nice! That was the segment of the intro video that really drew my attention.  But there are many ways to geocode your addresses, and it may be easier to do data entry in your system of choice and then bulk-geocode the addresses afterward (that'll save you 100,000 clicks of that 'Get Coordinates' button, anyway). There are several options for that - Bing and Google, of course, and many others (check out the geocoding questions on our sister site, GIS.StackExchange). I think it would be especially worthwhile to check out bulk geocoders that explicitly refer to their ability to code in India - many geocoders (e.g., SmartyStreets) are nation-specific, and many others are just going to return crappy results.  A number of geocoding APIs are available through packages in R, and there are a variety of packages available for mapping.
So - I would definitely consider using Epi Info for only the things that it's doing well for you (the form creation and data entry looks nice, but if it's slow, what can you do?), and reaching out to other tools for the things it's not doing well.  My ideal version of this would probably be double-data-entry in a Django database, automatic geocoding through an API or by sending a file to a service (whichever gets the most accurate results, and analysis and mapping in R.
Comment: I've been using the `sp`, `spatstat` and `ggmap` R packages for a much smaller project and they've worked well. My concern would be how well Google covers the areas of India you want to geocode.
Comment: Also, a quick search for open source forms found Orbeon (http://www.orbeon.com/forms/orbeon-forms), whose Community Edition might be useful.
Comment: MS Access is not a solution, the data is indeed linked at some places, and most of us are not in favour of it. SurveyMonkey and RedCap are web based solutions.
Actually SurveyMonkey is a very good tool if you are planning to collect data from the applicants directly and yes ofcourse I will look into it.
RedCap is also a very good solution, but the first view over the map on its homepage shows no institution in India are using it. And even if I plan to become a partner the page clearly states...
Comment: "The technical core staff will need to be affiliated with your institution, not a third-party software vendor or service provider." The latter would have been my case, so this cant be a solution. Yes for futute, I will look into it. Django has a coding curve to it, plus its again webbased.
Now for Geocoding I have found a solution. I will be using [GeodesiX](http://www.calvert.ch/geodesix/) with excel and because we will be doing geocoding simultaneosly on the amount of data being entered everyday, we can use two or 3 IPs to overide the requests barrier. For analysis SPSS is a good.
Comment: So finally the question is if there is any offline form builder, which supports linking within and is capable of handling large amount of data and finally export it in excel! @Matt Parker
Comment: @Ankush That sounds like Access, I'm afraid - the 2007 and 2010 versions should be able to handle the amount of data you've got.  There's really not much else in that particular niche, though you might browse the answers to [this question](http://stackoverflow.com/questions/221826/alternatives-to-access). A couple of years ago I was setting up a multi-site data entry system that couldn't use the Internet (too many organizational policies to overcome), and I wound up using Access. It was okay, and would probably have been better if I were more skilled at Access.
Comment: @Ankush Django does come with a light, built-in server, so you could distribute the application to run on disconnected computers and then merge the results together.  You'd still have to code it up, of course...
Comment: @MattParker Thanks a lot for all your help.Finally Im pushing all my hopes with Epi Info (28 fields),because the only other option otherwise would be MS Access, and even Im not as good at it vis-a-vis Epi Info.And will try contacting CDC through EpiInfo forums, in case of trouble.But it was a good learning experience about various options which I may consider in future,for other projects.
Now we have to look at other logistic problems ie.,getting data entry operators,etc and rest after pilot study.
Thanks again for the personal research you did.Thanks everybody else and best wishes from India.
Answer: In my view you must opt for MS Excel for this work it will automatically generated the forms to fill up the data based on your database structure.
Comment: Excel is an awful recommendation for this (Access is defensible). I've never seen a form for excel that was more than a few items, and I have no idea what you are talking about with "excel will automatically generate forms", perhaps you should elaborate and point to some examples.
Comment: (-1) Please don't put email addresses in answers. Please consider reading the FAQ on how to formulate good answers. It would help for you to provide some firm justification for this recommendation.
Comment: I totally agree with Andy W, excel insnt the recommended one, plus it doesnt automatically generate forms, you have to use Visual Basic Editor, and it can be a learning curve. I know EpiInfo pretty well, but if there could be a possible good alternative, even if reasonably priced.


Bypass drupal theme with hook_menu() function?

Question: I have a page within Drupal administration where I want to bypass all of the normal Drupal theming and calculations to only show the HTML that's returned by the function. Is this possible?
 $items['admin/special_blank_page'] = array(
    'title' => 'PDF',
    'page callback' => 'special_blank_page',
    'type' => MENU_LOCAL_TASK,
  );

//...

  function special_blank_page(){
      $html ='Only show this HTML';
      return $html;
  }

Answer: Just to offer an alternative to Ayesh K's solution, you can set the delivery callback of your menu item

The function to call to package the result of the page callback function and send it to the browser. Defaults to drupal_deliver_html_page() unless a value is inherited from a parent menu item. Note that this function is called even if the access checks fail, so any custom delivery callback function should take that into account. See drupal_deliver_html_page() for an example.
Comment: +1. I think this is the better approach and this might work with existing menu router items as well (I haven't tried it yet though).
Comment: See also [ajax_deliver](http://api.drupal.org/api/drupal/includes%21ajax.inc/function/ajax_deliver/7) for another `delivery callback` example
Comment: I've just written an example of a custom `delivery callback`, see http://drupal.stackexchange.com/questions/54733#answer-138566
Answer: Yes, if you print the output instead of returning it.
function special_blank_page(){
      $html ='Only show this HTML';
      print $html;
  }


Unable to open asset URL: file:///android_asset/activity_a

Question: I just began android coding and I'm still learning from my mistakes. I use WebView to load internal html pages and I want to open another activity window which will be a barcode scanner by clicking a hyperlink on webview. However I get this error
Unable to open asset URL: file:///android_asset/activity_a://qrcodeactivity
AndroidManifest.xml
<activity android:name="qrcodeactivity" >
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT" />
                <action android:name="android.intent.action.VIEW" />
                <data android:scheme="activity_a" />
            </intent-filter>
        </activity>

index.html
Activity A

MyWebClient Java
    private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        if (url.equals("activity_a://qrcodeactivity")) {
            Intent intent = new Intent(getContext(), qrcodeactivity.class);
            startActivity(intent);
            return true; // Handle By application itself
        } else {
            view.loadUrl(url);

            if (loader.equals("pull")) {
                swipeContainer.setRefreshing(true);
            } else if (loader.equals("dialog")) {
                if (!pd.isShowing()) {
                    pd.show();
                }
            } else if (loader.equals("never")) {
                Log.d("WebView", "No Loader selected");
            }

            return true;
        }

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (pd.isShowing()) {
            pd.dismiss();
        }

        if (swipeContainer.isRefreshing()) {
            swipeContainer.setRefreshing(false);
        }
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        webView.loadUrl("file:///android_asset/" + getString(R.string.error_page));
    }

        }

Answer: WebView has no idea what activity_a:// is. Apparently, it is treating it as a relative reference, as if it were activity_a/.
Since you are using this in a WebView, there is no need to invent your own scheme. You are checking the entire URL in shouldOverrideUrlLoading().
So, you could change the HTML to:
Activity A

and change your if to match:
if (url.equals("file:///qrcodeactivity")) {

And, you can get rid of the <intent-filter> from your <activity>. Having that is dangerous, anyway, as you are indicating that any app on the device can start that activity, as an activity with an <intent-filter> is exported.
Comment: Hello, thank you so much for your answer. I did you changes however i'm still getting the same error.

file:///qrcodeactivity not found
Comment: @zontrakulla: Sorry, I forgot the scheme in the `if` test. See the updated answer. Basically, your `if` needs to match the URL that `WebView` generates.
Comment: Worked perfectly! Thank you so much.


Erro de CORS Ionic 3

Question: Estou tentando conectar o meu aplicativo com um servidor backend em Laravel
Possuo um interceptador que adiciona os cabeçalhos na requisição:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('----------------- SESSION -----------------');
console.log(this.session.token);

this.token = this.session.token;
const headers = this.buildRequestHeaders();
const authRequest = req.clone({
  setHeaders: {
    'Access-Control-Allow-Credentials': 'false',
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "Content-Type",
    "Access-Control-Allow-Methods": "OPTIONS,POST,GET",
    'Authorization': `Bearer ${this.token}`
  }
});

return next.handle(authRequest);

}
Já no servidor tenho um middleware:
<?php

namespace App\Http\Middleware;

use App\Helpers\JsonResponseHelper;
use Closure;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Middleware\GetUserFromToken;

class JwtCheck extends GetUserFromToken
{
    public function handle($request, Closure $next)
    {
        header('Content-Type', 'application/json');
        header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Request-Headers', 'Origin, Authorization, Content-Type, Accept');
        header('Access-Control-Allow-Origin', '*');
    if (strpos($request->headers->get("Authorization"), "Bearer ") === false) {
        $request->headers->set("Authorization", "Bearer " . $request->headers->get("Authorization"));
    }

    if (!$token = $this->auth->setRequest($request)->getToken()) {
        $data['errors'] = trans('auth.failed');
        $message = trans('auth.failed');
        return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
    }
    try {
        //$user = $this->auth->authenticate($token);
        $user = JWTAuth::parseToken()->authenticate($token);
    } catch (TokenExpiredException $e) {
        $data['errors'] = trans('messages.token-expired');
        $message = trans('messages.token-expired');
        return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
    } catch (JWTException $e) {
        $data['errors'] = $e->getMessage();
        $message = trans('messages.error');
        return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
    } catch (TokenInvalidException $e) {
        $data['errors'] = $e->getMessage();
        $message = trans('messages.error');
        return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
    } catch (Exception $e) {
        $data['errors'] = $e->getMessage();
        $message = trans('messages.error');
        return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
    }
    if (!$user) {
        $data['errors'] = trans('auth.failed');
        $message = trans('auth.failed');
        return JsonResponseHelper::dataResponse(trans('messages.error'), $data, true, 401, $message);
    }
    $request->merge(array("user" => $user));
    $request->merge(array("token" => $token));

    return $next($request);
    }
}

Esse é o meu problema:

Essa é a requisição enviada para o servidor:
Comment: Primeiro, não poste código como imagem; o site, que é voltado a programação, suporta perfeitamente a formação de código fonte, by @AndersonCarlosWoss. Deixa só as duas ultimas imagens.
Answer: Caso tenha acesso a sua aplicação backend, configure o CORS em sua aplicação laravel, caso não possua e esteja realizando acesso localhost, configure o proxy do seu frontend, porém quando for realizar o build para colocar em produção, ai teria de configurar proxy em servidor, por isso recomendo a configuração do CORS em seu laravel backend

Erro de CORS Ionic 3


AG-Grid sorting is not working with TreeData

Question: I have an ag-grid with Tree Data. (https://www.ag-grid.com/javascript-grid-tree/).
I am facing an issue that column is being sorted in lexicographical order instead of Asc/Desc. For number columns, it should be sorted by max/min value. Here is the JsFiddle link: https://jsfiddle.net/pbjqdw6w and see the behavior of Currency column.
enableSorting: true
Answer: You need to provide your own sorting function if you want to override the default behaviour.
Take a look at the Sorting Docs for more information, but in a nutshell you need to supply a sorting function on the column in question:
colDef.comparator = function (valueA, valueB, nodeA, nodeB, isInverted) {
    return valueA - valueB;
}


How to configure my local Drupal site to contact my local Apache Solr server?

Question: I installed Apache Solr server on my local machine and installed the Apache Solr Search module on my Drupal 7 site. When I configure the module and click submit an error message appears:

Your site was unable to contact the Apache Solr server.

But when I go to http://localhost:8983/solr/#/ my Solr admin opens.
Comment: What if you try with http://127.0.0.1 instead of http://localhost
Answer: You haven't added any cores to Solr and you need to add at least one core and adjust the connection properties.
You will probably need the Solr 7 config from Search API Solr Search, as Apache Solr Search only has config for 5.x. The commands you need to run are: (replace CORE with the actual name)

cd /opt/solr/server/solr
sudo mkdir -p CORE/conf
sudo cp -R search_api_solr/solr-conf/7.x/* CORE/conf
cd /opt/solr
sudo -u solr ./bin/solr create -c CORE -d server/solr/CORE/conf

This should take the config files and create a core with those files. Then adjust your connection to http://localhost:8983/solr/CORE


tap-win32 networking in colinux / portable_ubuntu

Question: I'm trying to set up two network adapters on portable ubuntu remix, which is based on colinux; one slirp for outgoing access, and one tap for fast communication with the host. The slirp host works just fine, but I can't communicate between the host and colinux using the tap interface.
I added the tap interface by downloading http://www.henrynestler.com/colinux/tools/netdriver-tap84.zip and running
tapcontrol.exe install OemWin2k.inf TAP0801co

. I renamed it to coLinux_Tap, so that it would be easy to differentiate between this and the Tap adapter I have for OpenVPN. I configured it with a static IP, 192.168.3.1/255.255.255.0, no gateway.
I added
eth1=tuntap,"coLinux_Tap"

to my portable_ubuntu.conf file, and added a static config to /etc/networking/interfaces which reads:
auto eth1
iface eth1 inet static
address 192.168.3.2
network 192.168.3.0
netmask 255.255.255.0
broadcast 192.168.3.255

When I boot Portable Ubuntu, the device remains disconnected, and no packets are seen in windows as being either sent or received. Ping from Windows returns "request timed out". Ping from Linux also times out, although there at least ifconfig indicates packets being sent (but not received) on eth1.
I've also tried forcing the "media connected" option in Windows to Always instead of Application Controlled, with no change.
Any ideas?
EDIT: I think my routes are OK(ish).
If the device is not set to always connected, then no route exists for 192.168.3.anything, and it can't be added. If I force the coLinux_Tap device to be connected, it has a route set already:
c:\>route print | grep 192.168.3
      192.168.3.0    255.255.255.0      192.168.3.1     192.168.3.1       20
      192.168.3.1  255.255.255.255        127.0.0.1       127.0.0.1       20
    192.168.3.255  255.255.255.255      192.168.3.1     192.168.3.1       20
        126.96.36.199        240.0.0.0      192.168.3.1     192.168.3.1       20
  255.255.255.255  255.255.255.255      192.168.3.1     192.168.3.1       1

Answer: Solved!
The portable ubuntu release does not included the daemon needed to attach to the TAP device!
I downloaded the 0.7.3 release from http://www.henrynestler.com/colinux/releases/0.7.3/packages/daemons-0.7.3-20080524.zip, and extracted colinux-net-daemon.exe to my portable ubuntu directory; now everything works correctly! (although the default DISPLAY is still the slirp device, but that's easy enough to fix).
Answer: Man.  I've been through so many variations of pear-shaped with colinux and TAP that I'm sure I must have seen this one, but it's like a maze of twisty little network configs in my mind.
Maybe give this a try, from cmd on the Windows side:
route add 192.168.3.0 255.255.255.0 192.168.3.1

Hopefully it will figure out to use the TAP adapter.  If not, you might be able to tell it to with IF 2 or whatever on the end, if you can figure out what interface number it is.
If that doesn't work, you might want to try bridging your TAP adapter and Local Area Connection (some form of that exists, I hope?).  Disgusting, I know, and prone to screwing things up, but I've wound up forced to do it at least once.
Comment: I added my post to indicate the route [that way I could get formatting].

I don't want to bridge the TAP and local network: I want networking to work via slirp, as I can't attach another device to my company network.


Busca por proximidade

Question: Estou em busca de tutoriais que me auxiliem a implementar uma busca por proximidade (como nesse link:https://www.palfinger.com/pt-BR/bra/representantes-de-vendas/localizador-de-representante). Percebam que além da sua localização ele utiliza outros filtros (select e checkbox). Bom, meu forte é front-end, mas ja comecei a aprender PHP e mySQL.
Como eu chego a esse resultado? Que tipo de tutoriais eu devo buscar? Quais são as linguagens usadas? Tudo que vcs puderem me esclarecer quanto a isso seria ótimo.
Agradeço desde já.
Comment: Olha o site do http://www.banco24horas.com.br/para-voce/busca-banco24-horas
Comment: aqui tem a API: https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
Answer: No PHP é basicamente isso:
<code>   public function getGeocodeAddress($lat, $long)
        {
            $url = "https://maps-api-ssl.google.com/maps/api/geocode/json?latlng=" . $lat . "," . $long . "&sensor=true";

            $data = @file_get_contents($url);
            $jsondata = json_decode($data, true);
            if (is_array($jsondata) && $jsondata['status'] == "OK") {
                $addressComponents = $jsondata['results'];
                for ($i = 0; $i < count($addressComponents); $i++) {
                    for ($j = 0; $j < count($addressComponents[$i]['address_components']); $j++) {
                        $typeName = $addressComponents[$i]['address_components'][$j]['types'][0];
                        if ('locality' == $typeName) {
                            return strtolower($addressComponents[$i]['address_components'][$j]['long_name']);
                        }
                    }
                }
            }
            return null;
        }
</code>
Olha aqui a saída: http://ideone.com/rePEIv

Busca por proximidade


Is there any technique to do in postgresql 9.3 so that it start returning 1 and 0 instead of "t" and "f" for boolean type

Question: Actually i am migrating my ms sql server into postgresql 9.3 and we were using int data type to store 1 and 0 for boolean values but in postgresql9.3 it is not possible. what did i get when i did a little research on datatype of postgresql:
In Postgresql:-
For Integer type datatype:-

insert into ask(aint) values(1)         working
insert into ask(aint) values('1')       working

insert into ask(aint) values(true)      not working

select * from ask where aint=1;     working
select * from ask where aint='1';   working
select * from ask where aint=true;  working

*For smallint type datatype:-

insert into ask(asmall) values(1);      working
insert into ask(asmall) values('1');    working
insert into ask(asmall) values(true);   working

select * from ask where asmall = 1      working
select * from ask where asmall = '1'    working
select * from ask where asmall = true   not working

so if i want to use smallint then the problem that i am getting is , i can not compare any boolean field and if i use integer then i can not insert any boolean value eventhough i can compare booelan field. And
i can not use boolean data type as it return "t" for true and "f" for false
so what i want is?

is there any way to compare smallint with boolean?
Or Is there any way to insert boolean values in integer type data type.
Or can we do something so that boolean type start returning 1 for true and 0 for false.

So can somebody please help me? it's emergency! thanks
Comment: But still: why are you trying to do that? What is the *real* problem you are trying to solve?
Comment: Hi..thanks for replying quickly, i edited now, actually my problem is, i want 1 for true and 0 for false after executing query instead of 't' and 'f'.
Comment: actually i have written to show that we can use either 1 or '1' in different statement, any way i edited and written whole query.now you can see.
Comment: Again: what is the *real* problem  you are trying to solve? Why don't you just use a `boolean` and `true`/`false` when inserting/updating?
Comment: actually our project already supporting oracle and sql server and i want one more database support as postgresql, but all code has written to insert 1 for true and return the same and we are using hibernate3 also and it's work in both the databases, so now i want the same for postgresql. is it possible? have you read the all 3 question that i have written in my post?
Answer: By default, there is no such conversion - implicit conversion is by default used only for data types from similar groups (e.g. integer and bigint).
Fortunately, you can always add new implicit cast if you really need to do so.
First, we will create a new function to convert smallint to boolean. To do this, we will use existing C function bool_int4.
CREATE OR REPLACE FUNCTION int2(boolean)
  RETURNS smallint AS
'bool_int4'
  LANGUAGE internal IMMUTABLE STRICT
  COST 1;

Now we can create new implicit cast from boolean to smallint:
CREATE CAST (boolean AS smallint) WITH FUNCTION int2(boolean) as implicit;

And finally, we are ready to compare smallint and boolean directly:
select 1::smallint=true

PostgreSQL documentation warns everyone that bad things can happen when you use implicit casting unwisely:

It is wise to be conservative about marking casts as implicit. An
  overabundance of implicit casting paths can cause PostgreSQL to choose
  surprising interpretations of commands, or to be unable to resolve
  commands at all because there are multiple possible interpretations. A
  good rule of thumb is to make a cast implicitly invokable only for
  information-preserving transformations between types in the same
  general type category.

You can get list of casts for specified types from pg_catalog, from table pg_cast:
select
  castsource::regtype,
  casttarget::regtype,
  castcontext
from
  pg_catalog.pg_cast
where
  castsource::regtype in ('boolean','smallint','integer') and
  casttarget::regtype in ('boolean','smallint','integer')
order by
  castsource::regtype,
  casttarget::regtype;

This will return (9.1.9):
castsource;casttarget;castcontext;
boolean;integer;e
smallint;integer;i
integer;boolean;e
integer;smallint;a

Comment: thanks Tomas, actually i tried the same cmd as you have written, and it's returning two more,"boolean";"smallint";"i"   "smallint";"boolean";"i" so is it safe to use them. and please tell me how to use them.
Comment: @Krishna What exactly do you mean? There are only four casts defined among `integer`, `bigint` and `boolean` in pg 9.3.1 by default, see this [SQLFiddle](http://sqlfiddle.com/#!15/d41d8/2483). If you see more rows then you are either using different query or someone else already made changes to db configuration. If you run this query after creating casts than it is probably correct even though `smallint;boolean` was probably inserted by someone else. This modification should be generally safe, but don't expect any guarantee.
Comment: i want to cast boolean into smallint, sorry i am using ppas9.3 oracle compatible and it is returning 2 more as i have mentioned above, No nobody did any configuration, i just installed and did not do any changes. so can you please tell me the exact query that i can use to cast.
Comment: sorry i want to cast smallint to boolean
Answer: if the column if of the boolean type then cast it to integer to compare to integer:
select the_boolean_column::int = 1;

to insert a boolean value as smallint cast it to integer fisrt
insert into t (integer_column) values (boolean_value::int::smallint)

to make the boolean_column always return integer create a view
create view v as
select boolean_column::int as integer_column
from t

When you query a boolean column it does not return 't' or 'f'. It returns a boolean value, true or false or null. The string representation of the value is up to the client, hence the 't'.
Comment: thanks Clodoaldo, but i want internal casting. i don't want any change in my code. so is there any way to get 1 and 0, i am using ppas9.3


How to create multiple instance of mongos router server?

Question: I'm trying to configure a mongo sharded system. What I have configured right now is as follows:
2 Configuration servers
1 mongos router server
4 sharded servers
I've configured everything and its working perfectly. Now I want to try to create more instances or replica of my MONGOS server but unable to find any documentation about it. Please help.
Thanks in advance.
Comment: Hi, welcome to SO. Please update your question and provide a MRE (stackoverflow.com/help/minimal-reproducible-example)
with relevant code parts.
Comment: `mongos` is a software component. and it is not bound to a dedicated hardware (like a config server). You can have any number of `mongos` instances. See this note: [Sharded Cluster Components - Number of mongos and Distribution](https://docs.mongodb.com/v4.2/core/sharded-cluster-components/#number-of-mongos-and-distribution).
Answer: mongos processes are independent. You can follow the same procedure you used to start your first one to start as many as you like.


Is $argmin_{\mathbf{x}} f(\mathbf{x})=argmin_{\mathbf{x}} \log{f(\mathbf{x})}$ always true?

Question: Assuming
$\mathbf{x}\in \mathbb{R}^n$,
$f(\mathbf{x})\gt0 \forall\mathbf{x}\in\mathbb{R}^n$,
is $argmin_{\mathbf{x}} f(\mathbf{x})=argmin_{\mathbf{x}} \log{f(\mathbf{x})}$ always true?
Why?
Answer: due to $\log$ is monotonous and $f(x) \geq f(y)$ if and only if $\log f(x) \geq \log f(y)$