How to find copula-based conditional probability P(U|V>=v)?

Question: Using the Copula operator $C$, which for any (possibly dependent) RVs $U$ and $V$ represents the joint cumulative DF of their inverse probability transform. That is, $U^* = F^{-1}_U (U) \sim \mbox{Uniform}(0,1)$ and similarly for $V$. Therefore, $C(u, v) = P(U^* < u, V^* < v)$.
Copulas generally allow one to visualize the dependence relation between two random variables on a square.
I would like to formulate the conditional probability $P(U | V \ge v)$ as a function of the copula of $U$ and $V$.
I am starting with the notion that:
$P(U \le u|V \ge v) = 1-C(u,v)/v$.
But don't know where to go.
Comment: Can you give some context, e.g., actually define the symbols you're using?
Answer: Your problem boils down to pure "conditional probabilities":
$$P(U \leq u | V \geq v) = \frac{P(U \leq u, V \geq v)}{P(V \geq v)}$$
Let's assume two uniform random variables $U,V \sim {\rm U}(0,1)$ with copula $C$. Think of the problem geometrically supposing you have a large sample of your copula $C$. The probability of $P(U \leq u | V \geq v)$ is the amount of points in the top-left rectangle of the unit square spanned by $(0,v)$ and $(u,1)$ (assuming u is on your x-axis and v on your y-axis) divided by all points above the line at $v$. Instead of "number of points", we can also think of the probability mass based on the copula density $c$. To calculate the mass of the top-left rectangle, we take the entire mass 1 and subtract the mass of the area of points larger than $u$ (which is $1-u$) and the mass of the area of the lower left rectangle (spanned by $(0,0)$ and $(u,v)$) that is the copula value (i.e., $C(u,v)$). The divisor is the mass of the area larger than $v$ (which is $1-v$)):
$$P(U \leq u | V \geq v) = \frac{1-\big((1-u) + C(u,v)\big)}{1-v} = \frac{u-C(u,v)}{1-v}$$
Initially, you asked for the conditional density. That is, driving the above ideas to infinite small rectangles, for every $u$ the integral of the copula density $c$ from $v$ to 1, re-scaled by the entire probability mass still to be distributed in the conditioning area:
\begin{eqnarray}
f(u | V \geq v) &=& \frac{1}{{1-v}} \int\limits_{v}^{1} c(u,x) ~ {\rm d}x \\
 &=& \frac{1}{{1-v}} \left(\frac{\partial}{\partial u} C(u,1) - \frac{\partial}{\partial u} C(u,v) \right) \\
 &=& \frac{1 - \frac{\partial}{\partial u} C(u,v) }{{1-v}}
\end{eqnarray}
Note that the conditional density is merely the derivative with respect to $u$ of the above conditional CDF. See below for a R-code snippet that implements (and empirically double-checks) the above.
<code>library(copula)
library(spcopula)

conFunLarger <- function(u, v=0.25, copula=gumbelCopula(4)) {
  (1-dduCopula(cbind(u,rep(v,length(u))), copula))/(1-v)
}

plot(1:100/101,conFunLarger(1:100/101),type="l")
sum(conFunLarger(1:1000/1001)*1/1001)
</code>


Is piano a percussion instrument

Question: Could the piano be considered a percussion instrument as it has hammers hitting on suspended strings? Just an interesting thought...
Answer: Yes.  When used as an orchestral instrument - as part of the orchestra rather than as a solo - then it is normally regarded as part of the percussion section.
Comment: Dupe - 'Strings versus percussion - what is a piano'.
Answer: Yes, sometimes it's useful to recognise the percussive element of the piano.
But we mustn't get too hung up on classification.  Piano has strings, which are played (sort of) percussively, but doesn't fit either the 'stringed instruments' or 'percussion instrument' category very well.  Likewise organ and 'wind instrument'.   Recognise these aspects, and don't lose sleep over which pigeon-hole they go in!
Comment: Nice, I like your answer! Don't lose sleep over which pigeon hole they go in! Brilliant.
Comment: Indeed.  Classifications are a useful shorthand but don't necessarily cut nature at the joints (as Plato thought they did).  Guitars and even flutes are also "percussive" to some extent.

Is piano a percussion instrument


Enviar dados apenas para o sidebar.blade.php

Question: Preciso montar um menu usando as categorias cadastradas. Como posso fazer isso sem usar uma view?
Tenho meu layout.blade.php com um @include('sidebar')
Minha consulta funciona na view categorias.blade.php, preciso apenas receber os dados da consulta no meu sidebar.blade.php
CategoriaController:
public function listar() {
    $categorias = Categoria::where('categoria_id', '0')->with('todasCategorias')->get();
    return view('categorias', compact('categorias'));
}

Fiz a consulta direto no sidebar.blade.php.
Funcionou, mas creio que essa não seja a maneira correta, alguém conhece outra forma?
$categorias = App\Categoria::where('categoria_id', '0')->with('todasCategorias')->get()

Answer: Veja o código abaixo.
Na linha do return use with, para dizer que você vai carregar a página com a lista de categorias. Você faz withCategorias. Categorias é o nome que você vai usar no foreach na blade. E a variável dentro é a variável que faz a consulta, $categorias.
public function listar() {
    $categorias = Categoria::where('categoria_id', '0')->get();
    return view('categorias')->withCategorias($categorias);
}

Depois na blade você faz:
@foreach($categorias as $item)
   $item->nome_do_campo
@endforeach

Pode usar a função __construct()
public function __construct(){
   $categorias = Categoria::where('categoria_id', '0')->get();
   view()->share('categorias', $categorias);
}

Depois aplica o mesmo conceito acima do foreach na sidebar.blade.php.
Comment: Diego, obrigado pela resposta. Acho que não fui muito claro. Na verdade esse sidebar.blade.php não está no categoria.blade.php. O sidebar estará em todas as páginas do site. Eu importo o sidebar no meu layout.blade.php
Comment: Sabe usar a função `__construct` ?
Comment: Sim, mas não funciona dessa forma. Lembrando que a `view` `categorias` não tem nada a ver com a `sidebar`. Na verdade onde tem `categorias` nem tem o `sidebar`.
Comment: O `sidebar` não vai em toda página ? É só colocar essa função `__construct()` no **controller** principal, que chama todas as suas páginas.
Answer: Resolvi usando o Service Injection do Laravel 5.1.
No meu sidebar.blade.php adicionei:
@inject('categorias', 'App\Categoria')

@foreach($categorias->listar() as $categoria)

{{ $categoria->nome }}

@endforeach

Documentação: http://laravel.com/docs/5.1/blade#service-injection


can I use RxJava to write ejb apps to be deployed in WebSphere 8

Question: EJB 3.x specs say, not to create and manage threads, can I use RxJava without me explicitly doing that.
notes: What I am worried about is, do RxJava implicitly create and manage threads even for simple tasks? if yes, then it becomes in-eligible to be used for EJB 3.1 development.
I am using WebSphere 220.127.116.11, java 7, EJB 3.1
Comment: With Java EE7 (EJB 3.2), there is a safe way to do thready things using Concurrency Utilities (JSR-236). We have a sample that shows this integration: https://github.com/WASdev/sample.rxjava. I mention it only because you opened the question with 3.x. ;)

For EJB 3.1 with WebSphere 22.214.171.124, do you mean Liberty or traditional?
Comment: sorry, I should have been explicit. I am talking about EJB 3.1 WAS8.5.5 Traditional Full Profile
Answer: In RxJava there are two operations, "subscribeOn" (http://reactivex.io/documentation/operators/subscribeon.html)  and "observeOn" (http://reactivex.io/documentation/operators/observeon.html) that allow you to specify a Scheduler (ie: JEE Executor) that will be used to create a new thread to use when it's carrying out the subscribe / observe routines.
By default though, if you don't specify any schedulers, then it would run all in the same thread, so you're ok.
Comment: Thank you, I will try that.


GCC does not generate debugger information when using -g, -ggdb, -g3, or -ggdb3

Question: I'm using GCC 4.4.1 and GDB 7.0-ubuntu on Ubuntu 9.10 (Karmic Koala). However, GCC won't generate debugger information when using any of the following switches: -g, -g3, -ggdb, or -ggdb3.
So when I run the program with GDB, it's as if there wasn't any debugger information generated. I have created very simple test source files in a new, empty folder.
Here is one example:
#include <stdlib.h>
#include <stdio.h>

int main (int argc, char **argv)
{
     char    msg[4];

     // Allocate 4 bytes on the stack
     strcpy (msg, "Hello, World!");

     // Overflow
     printf ("%s\n", msg);
     return 0;
}

Here is my command line sequence:
gcc -g ./mytest.c -o mytest
gdb ./mytest

I have previously turned on MALLOC_CHECK_=1 in order to test the stack overflow problem in the code. And this works, so I get a stack trace. But the stack trace is no different whether I include the debug information or not. With the debugger information, I expected to see a line number of a file for where the problem occurred under GDB. However, this doesn't happen.
Comment: did you pass -gANYTHING to the linking command line?
Comment: post the command line that you use to compile your program, and the message you get that leads you to think that your exe has no debug information
Comment: Good question. Since its only linking to the standard libs, I just used: gcc -ggdb ./test.c -o test.o. To have debugger info included, am I required to compile and link in two steps?
Comment: Whoops. You just made an executable named test.o, if that.
Answer: It works fine. I ran the debugger on my computer. I had to add
#include <string.h>

to compile it though. I called the file debugger.c. Here are the steps:
gcc -g debugger.c
gdb a.out

which will start the debugger
GNU gdb 6.3.50-20050815
...
...
(gdb) run
Starting program: /Developer/stackoverflow/extern/a.out
Reading symbols for shared libraries +. done

Program received signal SIGABRT, Aborted.
0x00007fff88040886 in __kill ()
(gdb) backtrace
#0  0x00007fff88040886 in __kill ()
#1  0x00007fff880e0e4f in __abort ()
#2  0x00007fff880d5693 in __chk_fail ()
#3  0x00007fff8802f851 in __strcpy_chk ()
#4  0x0000000100000f04 in main (argc=1, argv=0x7fff5fbff958) at debugger.c:9
(gdb)

But it seems like your problem isn't running the debugger, but getting the information where your code failed. You can use backtrace to achieve that.
Answer: You want:
gcc -g test.c -o mytest
gdb mytest

Never call anything "test" - it clashes with a shell built in. and "test.o" would by convention be the name of an object file, not an executable.
Comment: Good points. But that doesn't solve the problem. Is there another reason this might happen?
Comment: @CJJ You still haven't said why you think the executable doesn't have debug information - what message are you getting that makes you think that is the case?
Answer: Your comment says you ran:
gcc -ggdb ./test.c -o test.o

That's probably not what you want.
gcc -ggdb -o mytest test.c

is likelier to be successful. If gdb ralphs on that then you have something wrong with your installation of gcc or gdb.


Como unificar os resultados de count POSTGRES?

Question: Bom dia, eu preciso que essa query retorne o resultado unificado, diferente do que me retorna, alguém tem alguma ideia de como faz isso no Postgres?? fui até maio(mai) mas continua até o final dos meses, meu parâmetro $1 é ANO .
RETURN QUERY SELECT DC.cod_descricao_status, DC.nome,

        (CASE WHEN TEMP.ano IS NULL THEN $1 ELSE TEMP.ano END) AS "ano",
        (CASE WHEN TEMP.jan IS NULL THEN 0 ELSE TEMP.jan END) AS "jan",
        (CASE WHEN TEMP.fev IS NULL THEN 0 ELSE TEMP.fev END) AS "fev",
        (CASE WHEN TEMP.mar IS NULL THEN 0 ELSE TEMP.mar END) AS "mar",
        (CASE WHEN TEMP.abr IS NULL THEN 0 ELSE TEMP.abr END) AS "abr",
        (CASE WHEN TEMP.mai IS NULL THEN 0 ELSE TEMP.mai END) AS "mai"
FROM public.pla_descricao_status_tarefa AS DC

        INNER JOIN

    (SELECT S.cod_descricao_status, D.nome,             EXTRACT(YEAR FROM S.data_alteracao) AS "ano",
    COUNT(CASE WHEN(EXTRACT(MONTH FROM (S.data_alteracao)) = 1) THEN S.data_alteracao END) AS "jan",
    COUNT(CASE WHEN(EXTRACT(MONTH FROM (S.data_alteracao)) = 2) THEN S.data_alteracao END) AS "fev",
    COUNT(CASE WHEN(EXTRACT(MONTH FROM (S.data_alteracao)) = 3) THEN S.data_alteracao END) AS "mar",
    COUNT(CASE WHEN(EXTRACT(MONTH FROM (S.data_alteracao)) = 4) THEN S.data_alteracao END) AS "abr",
    COUNT(CASE WHEN(EXTRACT(MONTH FROM (S.data_alteracao)) = 5) THEN S.data_alteracao END) AS "mai",

    COUNT(S.data_alteracao) AS TOTAL
    FROM (SELECT DISTINCT ON (cod_descricao_status, cod_tarefa)cod_descricao_status, cod_tarefa, data_alteracao FROM public.pla_status_tarefa) AS S
    INNER JOIN public.pla_tarefa AS T ON T.cod_tarefa = S.cod_tarefa
    INNER JOIN public.pla_descricao_status_tarefa AS D ON D.cod_descricao_status = S.cod_descricao_status
    WHERE (S.cod_descricao_status = 1 OR S.cod_descricao_status = 7 OR S.cod_descricao_status = 4) AND T.custo_executante LIKE CONCAT($2,'%') AND T.custo_executante NOT LIKE '101'
    AND T.flg_excluido = '0'
    AND EXTRACT(YEAR FROM S.data_alteracao) = $1
    AND T.cod_tarefa IN (SELECT S1.cod_tarefa FROM public.pla_status_tarefa AS S1 WHERE S1.cod_descricao_status = 1)
    GROUP BY S.cod_descricao_status, D.nome, S.data_alteracao)
    AS TEMP ON DC.cod_descricao_status = TEMP.cod_descricao_status
    WHERE DC.cod_descricao_status = 1 OR DC.cod_descricao_status = 7 OR DC.cod_descricao_status = 4;
    END;

ele me retorna assim :
(1,"ENV - Enviado",2020,0,0,0,0,0,0,0,0,0,0,1,0)
(1,"ENV - Enviado",2020,0,0,0,0,0,0,0,0,0,0,1,0)
(1,"ENV - Enviado",2020,0,0,0,0,0,0,0,0,0,0,1,0)
(4,"CAN - Cancelado",2020,0,0,0,0,0,0,0,1,0,0,0,0)
(4,"CAN - Cancelado",2020,0,0,0,0,0,0,0,1,0,0,0,0)
(4,"CAN - Cancelado",2020,0,0,0,0,0,0,0,1,0,0,0,0)
(7,"FIN - Finalizado",2020,0,0,0,0,0,0,0,0,1,0,0,0)
(7,"FIN - Finalizado",2020,0,0,0,0,0,0,0,0,1,0,0,0)
(7,"FIN - Finalizado",2020,0,0,0,0,0,0,0,0,1,0,0,0)
(7,"FIN - Finalizado",2020,0,0,0,0,0,0,0,0,1,0,0,0)
eu quero unificalos:
(1,"ENV - Enviado",2020,0,0,0,0,0,0,0,0,0,0,3,0)
(4,"CAN - Cancelado",2020,0,0,0,0,0,0,0,3,0,0,0,0)
(7,"FIN - Finalizado",2020,0,0,0,0,0,0,0,0,4,0,0,0)
Desde já agradeço!
Answer: Visto que o objetivo é:

Unificar os resultados de count

Visto que sua consulta já está resultando nas informações parciais que você precisa, basta realizar o agrupamento deste resultado parcial.
Uma possibilidade é considerar o resultado da sua consulta já existente como se fosse uma tabela, a qual chamarei de r lembrando da palavra resultado:
select cod_descricao_status, nome, ano, sum(jan) as janeiro, sum(fev) as fevereiro, sum(mar) as marco, sum(abr) as abril
  from (
    //Sua consulta original entra aqui
  ) as r
  group by r.ano, r.cod_descricao_status, r.nome
  order by r.ano, r.cod_descricao_status, r.nome

Não realizei análise da sua consulta pra verificar se existem melhorias a serem realizadas. Observei apenas o que pode ser feito para obter o resultado esperado.
Comment: Obrigado amigo, funcionou aqui, agradeço pela atenção!!
Comment: Bom dia, e como ficaria no caso? pois tentei empregar aqui, mas não deu muito certo ..
Comment: Veja se o exemplo disponibilizado no Fiddle (http://sqlfiddle.com/#!17/77ff7/4) auxiliar no entendimento.
Comment: Mas no caso minha tabela não possui uma escala por mês no caso:

cod_status| cod_tarefa| cod_usuario|  cod_usuario_alocado| cod_descricao_status|data_prevista_termino| obs   | data_alteracao | flg_excluido|
      55      |  26  |       99     |                 71      |       1  |  NULL            | NULL | "2018-04-05 10:09:02" | false         |
Comment: Sim, fiz a consulta considerando que seu trecho `COUNT(CASE WHEN(EXTRACT(MONTH FROM (S.data_alteracao)) = 1) THEN S.data_alteracao END) AS "jan",` está gerando a informação. Você pode produzir um ambiente de simulação no Fiddle? Nos fornece a url para podermos simular a consulta.  Busque melhorar sua pergunta, pois com a quantidade de votos negativa, corre o risco de ser fechada. Tente simplificar a consulta para facilitar o entendimento. No exemplo que fiz no Fiddle, considerei que você com sua consulta original já está obtendo o resultado que você menciona no corpo da sua pergunta.


About uniform continuity of function on unbounded interval

Question: Let $f$ be continuous function on $[0,\infty)$. If $f$ is uniform continuous on $[k,\infty)$  for some $k$ then $f$ is uniform continuous on $[0,\infty)$
 I start proof as:
Now f is uniform continuous on $[K,\infty)$ and also on $[0,k+1]$.
So we get the following for $ \epsilon>0$:

When I tried it myself I took $\delta= \min\{\delta_1, \delta_2\}$  why do we take 1 in this set not able to understand? Please help me.
Comment: We need $\delta\leqslant1$ so that if $|x-y|<\delta$, then both $x$ and $y$ lie in either $[k,\infty)$ or $[0,k+1]$. Consider what would happen if $\delta_{1},\delta_{2}$ were larger than 1, say $\delta_{1}=\delta_{2}=2$. Now suppose $x=k-1/3$ and $y=k+1+1/3$. We can't say anything about $|f(x)-f(y)|$ despite the fact that $|x-y|<2$.
Answer: You need that $x,y$ are both in $[0,k+\color{red}1]$ or both in $[k,\infty)$. You can conclude this only if $|x-y|\le 1$.
Alternatively, you might have worked with $[0,k+\delta_1]$ instead of $[0,k+1]$.


Find a vector field with the properties given below:

Question: I'm having trouble figuring out this homework question for my Calculus III class:
"Find a field $\vec{G}=P(x,y)\vec{i}+Q(x,y)\vec{j}$ in the $xy$-plane with the property that at any point $(a,b)\neq (0,0)$, $\vec{G}$ is a vector of magnitude $\sqrt{a^2+b^2}$ tangent to the circle $x^2+y^2=a^2+b^2$ and pointing in the clockwise direction. (The field is undefined at $(0,0)$.)"
I have to fill in the answers for $P(x,y)$ and $Q(x,y)$.
I've tried parameterizing the circle with a variable $t$, but that didn't seem to get me anywhere. Once I got the problem wrong, it said to differentiate the circle in terms of $x$ and use the slope to find the vector field. So then I tried implicit differentiation, treating $a$ and $b$ as constants and $y$ as a function of $x$:
$\frac{d}{dx}\left(x^2+y^2=a^2+b^2\right)$
$2x+2y\frac{dy}{dx}=0$
$\frac{dy}{dx}=-\frac{x}{y}$
Now that I got this slope, I'm not sure how to use this to find the vector field. And it makes it even more confusing since this is clockwise. Any help would be appreciated! Thank you! :)
Answer: For perpendicularity you need $Pa+Qb=0$, and you also need $P^2+Q^2=a^2+b^2$ (at the point $(a,b)$). Solving the system you get $(P,Q)=(-b,a)$ or $(P,Q)=(b,-a)$. Only the second is oriented clockwise. So your answer is
$$
P(x,y)=y,\qquad Q(x,y)=-x.
$$
Comment: Ah I see. But how does this satisfy the condition that $(a,b)\neq (0,0)$?
Comment: Also how did you get the equation $Pa+Qb=0$?
Comment: At $(0,0)$ you do not have a direction to be perpendicular to. You could define your field to be $(0,0)$ there to make it continuous. $Pa+Qb$ is the dot product $(P,Q)\cdot(a,b)$ which must be zero because your field is perpendicular to the radius vector at any point, as it is tangent to the circle through the given point centered at the origin.
Comment: Ah, that makes sense, thank you!


How do I convert a percentage from a 1%-100% scale to a different scale?

Question: So if I have 9%, and this 9% fits in where 0 is the lowest and 100% is the highest, what would that 9% be if 25% is the lowest and 75% is the highest?
What would the formula be to convert a percentage or a "normal" scale to a different scale?
Answer: In your scale from 0 to 100, 9 essentially represents that you are 9% of the way into the distribution:
$$9 = 0 + 9\%(100 - 0)$$
Now that your range is restricted to 25 to 75, 9% of the way into the distribution is:
$$25 + 9\%(75 - 25) = 29.5$$


Calculating arrangements using the multinomial coefficient

Question:
The students $A,B,C$ are in a group of 28 students, which is randomly split in 7 groups of 4 people each.

In how many ways can the students be arranged in seven teams of 4?
And what's the probability that any two of $A,B,C$ are in the same group?

So I thought you could do this with a multinomial coefficient: $$A=$$$$28 \choose 4,4,4,4,4,4,4 $$
But apparently, you have to divide this answer by $7!$ Can anybody explain why? (it says because there are $7!$ double counts, but I don't understand why)
And for the second part. There are three ways that any of the two are in the same group: $(A,B); (A,C) ; (B,C)$.
So the total amount of possibilities are $A$, and the possibilities we want are what I thought $26\choose 2,4,4,4,4,4,4 $ $\times 3$ because there are 3 ways in which it could happen, but this is also wrong. Can anybody explain why?
Comment: The order of the $7$ groups is not important, that's why.
Comment: @barakmanos So in a multinomial coefficient, there is an order within the groups? I didn't know that.
Comment: Not sure how to answer this question, but in your calcultaion, the order of the groups is important.
Comment: @barakmanos I think I get the first part now.
Answer: It is a mistake to treat multinomial coefficients as the answer to a question, because it tempts you to memorize instead of understanding. It is far better to solve the problem directly, and then to observe, having solved and understood the problem, that the answer can be described in terms of a multinomial coefficient.
First, write out a list of the 28 students. You know that this can be done in $28!$ ways.
Treat the first four students as being in the first group, the next four in the second group, and so on. Then ask the question: "How much of an over-estimate is $28!$ of the number of possible arrangements?"

Within each group, the order of the four students doesn't matter. You have therefore counted each group $4!$ times. All in all, this means you have over-estimated by a factor of $4!^7$.
But also, the order of the groups doesn't matter. By pretending that it did matter, you have over-estimated by a factor of $7!$.

All in all, therefore, $28!$ is $4!^7\times 7!$ larger than the true count of the number of possible arrangements. The number of arrangements is thus $$\frac{1}{7!}\frac{28!}{4!\times 4!\times 4!\times 4!\times 4!\times 4!\times 4!}\text,$$ which you are entirely free to express as a multinomial if you are fond of multinomials.


Can't login to dovecot using gmail as an email client

Question: I've used this installation
configure-email-server-using-postfix-dovecot
When I try to use gmail as the email client (connecting to my server through port 993) I get this error
Unable to establish secure SSL connection to email.example.com

My dovecot -n output
auth_mechanisms = plain login
mail_location = maildir:/var/mail/vhosts/%d/%n
mail_privileged_group = mail

passdb {
  args = /etc/dovecot/dovecot-sql.conf.ext
  driver = sql
}
protocols = imap lmtp
service auth-worker {
  user = vmail
}
service auth {
  unix_listener /var/spool/postfix/private/auth {
    group = postfix
    mode = 0666
    user = postfix
  }
  unix_listener auth-userdb {
    mode = 0600
    user = vmail
  }
  user = dovecot
}
service imap-login {
  inet_listener imap {
    port = 0
  }
}
service lmtp {
  unix_listener /var/spool/postfix/private/dovecot-lmtp {
    group = postfix
    mode = 0600
    user = postfix
  }
}
ssl = required
ssl_cert = </etc/ssl/certs/dovecot.pem
ssl_key = </etc/ssl/private/dovecot.pem
userdb {
  args = uid=vmail gid=vmail home=/var/mail/vhosts/%d/%n
  driver = static
}

When I check the logs I see this
 dovecot: imap-login: Disconnected (no auth attempts in 25 secs) ....

PS: the cert is a self signed.
Comment: You do realise that GMAIL only supports POP3 for checking/importing mail from other email accounts? enable POP3 over SSL on port 995...
Comment: gmail does support sending through other mail servers via TLS/SSL (authenticated), but not checking mail over IMAP.
Comment: What authentication methods have you tried in TB?
Comment: Thanks for actually using your domain, makes life a lot easier. That said, when you say you "use gmail" do you mean you sent a message through gmail to your server? If so, can you post the relevant lines from your mail log?
Comment: no. I mean using gmail as an email client. Trying to connect to my server through 993
Comment: ok. Next I've tried thunderbird. Trying imap on 993 but I get the same error in my syslog
Answer: As per @HBruijn's comment, Gmail only supports retrieving email through POP3, not IMAP. This has been confirmed on their product forums
Both Gmail and Dovecot support POP3 over SSL, which you should be able to use by opening port 995 on your firewalls, and directing Gmail at it.
Answer: for use pop3 with ssl on gmail to fetch mail
FOR CLIENT SIDE:

enter fqdn
enter your full email address
select port 995
select use ssl

FOR SERVER SIDE:
SSL certificate must:

match domain name of server  (FQDN)
in your case email.example.com not example.com
be valid
not self signed

put this in dovecot config and see logs i'll bet it's certificate issue
# Log unsuccessful authentication attempts and the reasons why they failed.
auth_verbose = yes

# In case of password mismatches, log the attempted password. Valid values  are
# no, plain and sha1. sha1 can be useful for detecting brute force password
# attempts vs. user simply trying the same password over and over again.
auth_verbose_passwords = yes

# Even more verbose logging for debugging purposes. Shows for example SQL
# queries.
auth_debug = yes

# In case of password mismatches, log the passwords and used scheme so the
# problem can be debugged. Enabling this also enables auth_debug.
auth_debug_passwords = yes

# Enable mail process debugging. This can help you figure out why Dovecot
# isn't finding your mails.
mail_debug = yes

# Show protocol level SSL errors.
verbose_ssl = yes

@downvoter: Care to explain your vote?


True until disproven or false until proven?

Question: I've noticed something about my coding that is slightly undefined. Say we have a two dimension array, a matrix or a table and we are looking through it to check if a property is true for every row or nested dimension.
Say I have a boolean flag that is to be used to check if a property is true or false. My options are to:

Initialize it to true and check each cell until proven false. This
gives it a wrong name until the code
is completely executed.
Start on false and check each row until proven true. Only if all rows are true will the data be correct. What is the cleanest way to do this, without a counter?

I've always done 1 without thinking but today it got me wondering. What about 2?
Comment: Thanks for the replies.

I managed to get the same effect only after using additional boolean values. There was no simple check.

I underestimated how different it would be because it is only one value that is changing. The problem with setting the property to true is that the next elements may suddenly disprove it.

I suppose you could name it propertyUnproven = true and then set to false when invalid.

What if the loop itself requires the correct answer before the flag is set to false?
Answer: Depends on which one dumps you out of the loop first, IMHO.
For example, with an OR situation, I'd default to false, and as soon as you get a TRUE, return the result, otherwise return the default as the loop falls through.
For an AND situation, I'd do the opposite.
Answer: They actually both amount to the same thing and since you say "check if a property is true for every row or nested dimension", I believe the first method is easier to read and perhaps slightly faster.
You shouldn't try to read the value of the flag until the code is completely executed anyway, because the check isn't finished. If you're running asynchronous code, you should guard against accessing the value while it is unstable.
Both methods "give a wrong name" until the code is executed. 1 gives false positives and 2 gives false negatives. I'm not sure what you're trying to avoid by saying this - if you can get the "correct" value before fully running your code, you didn't have run your code in the first place.

How to implement each without a counter (if you don't have a foreach syntax in your language, use the appropriate enumerator->next loop syntax):
1:
bool flag = true;

foreach(item in array)
{
    if(!check(item))
    {
        flag = false;
        break;
    }
}

2:
bool flag = false;
foreach(item in array)
{
    if(!check(item))
    {
        break;
    }
    else if(item.IsLast())
    {
        flag = true;
    }
}

Comment: Thank you, I like this answer. How clean you personally find it?
Answer: Go with the first option. An algorithm always has preconditions, postconditions and invariants. If your invariant is "bool x is true iff all rows from 0-currentN have a positve property", then everything is fine.
Don't make your algorithm more complex just to make the full program-state valid per row-iteration. Refactor the method, extract it, and make it "atomic" with your languages mechanics (Java: synchronized).
Answer: Personally I just throw the whole loop into a somewhat reusable method/function called isPropertyAlwaysTrue(property, array[][]) and have it return a false directly if it finds that it finds a case where it's not true.
The inversion of logic, by the way, does not get you out of there any quicker.  For instance, if you want the first non-true case, saying areAnyFalse or areAllTrue will have an inverted output, but will have to test the exact same cases.
This is also the case with areAnyTrue and areAllFalse--different words for the exact same algorithm (return as soon as you find a true).
You cannot compare areAnyFalse with areAnyTrue because they are testing for a completely different situation.
Answer: Make the property name something like isThisTrue.  Then it's answered "yes" or "no" but it's always meaningful.
In Ruby and Scheme you can use a question mark in the name: isThisTrue?.  In a lot of other languages, there is a convention of puttng "p" for "predicate" on the name -- null-p for a test returning true or false, in LISP.
Answer: I agree with Will Hartung.
If you are worried about (1) then just choose a better name for your boolean.  IsNotSomething instead of IsSomething.
Comment: Is that a clear name though?

(For some reason Stackoverflow just added three comment boxes)


Ler um valor especifico no Json com PHP

Question: Eu já pesquisei em todos os sites, porém não consegui achar uma forma de pegar o valor da totalPage.
Estou lendo Json com o PHP e preciso pegar esse valor pra fazer a paginação.
Segue abaixo os dados.
object(stdClass) # 1(3) {
    ["requestInfo"] =>
    object(stdClass) # 2(3) {

        ["status"] =>
        string(2)"OK"
        ["message"] =>
        string(7)"SUCCESS"
        ["generatedDate"] =>
        NULL

    }
    ["pagination"] =>
    object(stdClass) # 3(4) {
        ["page"] =>
        int(1)
        ["size"] =>
        int(10)
        ["totalSize"] =>
        int(1400)
        ["totalPage"] =>
        int(140)
    }
    ["offers"] =>
    array(10) {
        [0] =>
        object(stdClass) # 4(10) {
            ["id"] =>
            string(8)"11248674"
            ["name"] =>
            string(156)"Smartphone Motorola Moto G5 Plus TV XT1683 Platinum com 32GB, Tela 5.2 ´ ´, Dual Chip, Android 7.0, 4G, Câmera 12MP, Processador Octa - Core e 2GB de RAM"
            ["product"] =>
            object(stdClass) # 5(11) {
                ["id"] =>
                int(630970)
                ["name"] =>
                string(40)"Smartphone Motorola Moto G 5 Plus XT1683"
                ["shortName"] =>
                string(22)"Motorola 5 Plus XT1683"
                ["priceMin"] =>
                float(891.65)
                ["priceMax"] =>
                float(1819)
                ["discount"] =>
                int(50)
                ["thumbnail"] =>
                object(stdClass) # 6(4) {
                    ["url"] =>
                    string(113)"https://thumbs.buscape.com.br/celular-e-smartphone/smartphone-motorola-moto-g-5-plus-xt1683_600x600-PU9a0ba_1.jpg"
                    ["height"] =>
                    int(600)
                    ["width"] =>
                    int(600)
                    ["otherFormats"] =>
                    array(4) {
                        [0] =>
                        object(stdClass) # 7(3) {
                            ["url"] =>
                            string(113)"https://thumbs.buscape.com.br/celular-e-smartphone/smartphone-motorola-moto-g-5-plus-xt1683_100x100-PU9a0ba_1.jpg"
                            ["height"] =>
                            int(100)
                            ["width"] =>
                            int(100)
                        }
                        [1] =>
                        object(stdClass) # 8(3) {
                            ["url"] =>
                            string(113)"https://thumbs.buscape.com.br/celular-e-smartphone/smartphone-motorola-moto-g-5-plus-xt1683_200x200-PU9a0ba_1.jpg"
                            ["height"] =>
                            int(200)
                            ["width"] =>
                            int(200)
                        }
                        [2] =>
                        object(stdClass) # 9(3) {
                            ["url"] =>
                            string(113)"https://thumbs.buscape.com.br/celular-e-smartphone/smartphone-motorola-moto-g-5-plus-xt1683_300x300-PU9a0ba_1.jpg"
                            ["height"] =>
                            int(300)
                            ["width"] =>
                            int(300)
                        }
                        [3] =>
                        object(stdClass) # 10(3) {

                            ["url"] =>
                            string(113)"https://thumbs.buscape.com.br/celular-e-smartphone/smartphone-motorola-moto-g-5-plus-xt1683_600x600-PU9a0ba_1.jpg"
                            ["height"] =>
                            int(600)
                            ["width"] =>
                            int(600)
                        }
                    }
                }
                ["userRating"] =>
                object(stdClass) # 11(2) {
                    ["comments"] =>
                    int(226)
                    ["rating"] =>
                    int(9)
                }
                ["category"] =>
                object(stdClass) # 12(5) {
                    ["id"] =>
                    int(77)
                    ["name"] =>
                    string(20)"Celular e Smartphone"
                    ["thumbnail"] =>
                    object(stdClass) # 13(1) {
                        ["url"] =>
                        string(50)"http://imagem.buscape.com.br/bp5/categorias/77.jpg"
                    }
                    ["hasProduct"] =>
                    int(444)
                    ["hasOffer"] =>
                    int(8297)
                }
                ["hasOffer"] =>
                int(70)
                ["link"] =>
                string(96)"https://developer.lomadee.com/redir/validation/?sourceId=xxxxxxxxxxxxxxxxxx&appToken=xxxxxxxxxxxxxxxxxx"
            }
            ["category"] =>
            object(stdClass) # 14(6) {
                ["id"] =>
                int(77)
                ["name"] =>
                string(20)"Celular e Smartphone"
                ["thumbnail"] =>
                object(stdClass) # 15(1) {

                    ["url"] =>
                    string(50)"http://imagem.buscape.com.br/bp5/categorias/77.jpg"
                }
                ["hasProduct"] =>
                int(444)
                ["hasOffer"] =>
                int(8297)
                ["link"] =>
                string(96)"https://developer.lomadee.com/redir/validation/?sourceId=xxxxxxxxxxxxxxxxxx&appToken=xxxxxxxxxxxxxxxxxx"
            }
            ["link"] =>
            string(96)"https://developer.lomadee.com/redir/validation/?sourceId=xxxxxxxxxxxxxxxxxx&appToken=xxxxxxxxxxxxxxxxxx"
            ["thumbnail"] =>
            string(61)"https://thumbs.buscape.com.br/T100x100/__2.903294-dbe7fcb.jpg"
            ["price"] =>
            float(891.65)
            ["discount"] =>
            int(50)
            ["installment"] =>
            object(stdClass) # 16(2) {
                ["quantity"] =>
                int(10)
                ["value"] =>
                float(104.9)
            }
            ["store"] =>
            object(stdClass) # 17(6) {
                ["id"] =>
                int(5756)
                ["name"] =>
                string(11)"Casas Bahia"
                ["thumbnail"] =>
                string(46)"https://www.lomadee.com/vitrine/logo903294.gif"
                ["ebit"] =>
                object(stdClass) # 18(3) {

                    ["id"] =>
                    int(30)
                    ["name"] =>
                    string(12)"e-bit Ótima"
                    ["rating"] =>
                    int(4)
                }
                ["link"] =>
                string(96)"https://developer.lomadee.com/redir/validation/?sourceId=xxxxxxxxxxxxxxxxxx&appToken=xxxxxxxxxxxxxxxxxx"
                ["ocb"] =>
                bool(false)
            }
        }

Comment: Insira o `json` completo a pergunta
Comment: Bom dia, adicionei o código completo, dá uma olhada
Answer: Retorne os valores como json e use json_decode(), que retornará um objeto ou matriz se o segundo valor for verdadeiro. Exemplo:
$json = '{"paisId":"84","produtoId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['paisId'];
echo $json['produtoId'];
echo $json['status'];
echo $json['opId'];

Comment: Fiz da forma que você passou, mais não voltou nenhum resultado, fiz dessa forma $json = json_decode($json_file, true);
echo $json['totalPage'];
Comment: Faça um var_dump($json); e me diga o que retornou.
Answer: Note que Você tem retorno de Objetos não arrays (o true do json_decode o converte em um array associativo, particularmente prefiro trabalhar com objetos). Fique atento na hierarquia dos elementos, senão ficará impossível manipulá-los.
Então para manipular os valores (como objetos) deverá usar:
$objeto = json_decode($json);
echo $objeto->pagination->totalPage;

No caso do array associativo:
$associativo = json_decode($json, true);
echo $associativo["pagination"]["totalPage"];

Ler um valor especifico no Json com PHP


Can't resolve 'child_process'

Question: This is my main.ts file:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

const fs = require('fs');
import * as child from 'child_process';

const components = fs.readdirSync(`src/app`);
components.forEach(component => compileComponent(component));

 function compileComponent(component) {
    const buildJsFiles = `ng run elements:build --aot --main='MyProject/my-components/src/app/${component}/compile.ts'`;
    const bundleIntoSingleFile = `cat dist/tmp/runtime.js dist/tmp/main.js > dist/tmp/my-${component}.js`;
    const copyBundledComponent = `cp dist/tmp/my-${component}.js dist/components/`;
    child.execSync(`${buildJsFiles} && ${bundleIntoSingleFile} && ${copyBundledComponent}`);
 }

However, I get the error: Can't resolve 'child_process'.
In my webpack.config.js file I have:
externals: { child_process: 'child_process' },

I don't use Electron. I also tried adding in package.json:
"browser":{ "child_process": false }

And it doesn't work.
Answer: Angular code is compiled targeting browser clients, and you cannot use child_process on a browser. So I assume that webpack does not bundle that library, hence why the error.
Adding "browser":{ "moduleName": false } instructs the bundling tool to not bundle the module for the build.  This is useful for instance for crypto module, for which you've got a browser API that you'd want to use instead of the node js module. But this will not fork for child_process, for which there is no browser API.

Can't resolve 'child_process'


Redis: weird protocol/network errors

Question: I'm running Redis and connecting from Ruby using ezmobius's Redis gem[1].
Periodically (about once a day) I get a series of exceptions in my Rails app caused by Redis returning strange results.
They are often triggered by an exception such at this:
Redis::ProtocolError: Protocol error, got '3' as initial reply byte

or
Redis::ProtocolError: Protocol error, got '9' as initial reply byte

or sometimes
Errno::EAGAIN: Resource temporarily unavailable - Timeout reading from the socket

It usually requires a restart of my Rails servers to clear up the connection problem. I'm running Fedora Core 8, Rails 2.3.8, Redis gem 2.0.3. I've got the system_timer gem installed. Anybody got any ideas how I can stop these errors?
[1]Redis gem
Answer: I've just noticed the same thing in my background workers, which store tasks in queues in Redis and also communicate through Redis pub/sub. Google results suggest that this can happen if you use the same Redis object from more than one thread... I'm not sure if this is the case in my app, I'll have to investigate this (but I do have threads there).
Answer: I had a slightly similar issue with
Errno::EAGAIN: Resource temporarily unavailable - Timeout reading from the socket

Turns out, my redis-server had a timeout set to 300 seconds on connections. After 5 minutes, redis was killing the connection to my workers and they were logging the error above.
If your socket timeouts are happening every x seconds, its no doubt redis killing your 'idle' connection!
Answer: When initializing the connection, make sure to pass the :thread_safe option:
Redis.connect(:thread_safe => true)

Redis: weird protocol/network errors


can we use a HP JetDirect in reverse?

Question: I have the following situation
I have an Ethernet only HP Printer which I need to connect to a parallel port PC.
Could I use an External JetDirect card to connect my Ethernet printer to a Parallel port PC?
--UPDATE--
There is an Ethernet port on the PC but it's being used to connect to the Domain. So I can't unplug the PC's ethernet. The room which has the PC has only 1 Ethernet port so we can't connect 2 devices to the network simulataneously.
The Printer has an Ethernet port only so I can't connect it via Parallel port cable.
But if I can bridge the Ethernet port to Parallel port that would solve my problem.
Answer: If the computer and the printer are on the same network, that's your answer; use Ethernet. I'm assuming the printer does not have a parallel port. You won't be able to use the Jetdirect "in reverse".
Comment: Ok. That answered my question about using the JetDirect in reverse. Thanks!
Answer: If the PC doesn't have a network card, buy one.  Really, that's the simplest solution and you don't want to dick around with trying to make some sort of parallel-to-ethernet bridge that no one will understand after you leave.
If you don't want the PC to be on the network in general, buy a switch in addition to the network card, and assign static IPs to the JetDirect and to the PC.  Then they can live together alone on their on LAN and no one will bother them.
Comment: Ah, true.  "In my day, we had to crimp RJ45 crossover jacks on CAT3 cables ourselves, and we liked it!"
Comment: No switch required for most modern NICs (with auto MDI-X)
Answer: Based on your update, a simple $15 hub should solve your problem. Cheaper than a jetdirect, too.
A $10 nic would also work, but it will be a lot harder to set up correctly.
Answer: Buy a cheap hub or switch - blammo, the room magically has more Ethernet ports.
Comment: You can't *do anything* about this without buying *something.* If you can't drop $20 on a cheap hub, or scrounge one from the parts closet, or hack up a cable splitter (bad option, but might work), then you're truly up a creek sans paddle.
Comment: Who the hell voted this down? :-)
Comment: cant buy equipemt. We are on a freeze. Thats why we're trying to figure out how to accomplish this (if possible). If we didn't have the freeze, we'd have a new port installed or buy a new printer.
Answer: If you can use the external you can use the Jet direct on the printer.  You will need ethernet in either case. Can you explain the issue in more detail?  Does the PC not have ethernet?  Can it be added?
Can you provide the printer model?
Answer: Unless you require gigabit performance for your PC/Printer I'd recommend either splitting the cable at both ends to give you two jacks or purchasing a breakout cable for both ends. This way will give you two ports that will support 10/100 devices.
This is the breakout cable I mentioned.
Comment: OMG, why would the OP want to buy that for a total of $17 when a dinky switch will do what he wants? Maybe if he wants to run a phone line into there, too, but that's not what's described.
Comment: @cjc because no network admin would like to have unmanaged consumer-grade shit on his premises but rather connect all equipment to managed switch ports. Do a new cable run if possible or split cables (preferably [properly](http://www.ampnetconnect.az/neptun/neptun.php/oktopus/download/6760/)) if it's not.
Comment: Not to flame or anything but I'm going to anyways...Recommending someone daisy chain CHEAP switches like that is seriously irresponsible.
Comment: What specifically is "seriously irresponsible" about using a cheap switch in this sort of edge case?
Comment: Maybe thats a bit of an overstatement on my part, but I've seen more "dinky switches" bring down a network than most of the other common causes combined.
Comment: Ernie - sure, if someone makes a loop. Otherwise, it shouldn't introduce any problems.

can we use a HP JetDirect in reverse?


How to fix the widget script on blogger permanently

Question:

The code is above , and is not visible in the "edit html" menu on blogger. I can't delete it. Can I delete the code permanently?
Comment: can you please add any examples?
Comment: Refer to a similar question - https://stackoverflow.com/questions/16911018/how-to-remove-blogger-css-widget-bundle/48957618
Comment: Does this answer your question? [How to remove Blogger CSS widget bundle](https://stackoverflow.com/questions/16911018/how-to-remove-blogger-css-widget-bundle)
Answer: Yes you can. Add b:js='false' attribute to your html tag.
 ...


Viewing a bitmap in a fixed space in mfc

Question: I am trying to design an application that loads bitmap images. I have bitmaps of varying sizes but I want them to be displayed on a constant space ( like a rectangle of size 500x500). I've tried StretchBlt() in the following way but the results are disappointing and the images are still of varying sizes. The code is mentioned below. Thanks in advance.
DcForClientClientDc.StretchBlt(0, 0 , 500, 500, &bmDC, 0, 0, 1000, 1000, SRCCOPY);

Comment: Why in the name of C++ somebody would downgrade this question, instead explaining to the original poster what is wrong with the question?
Comment: You'll find explanations of the arguments in the documentation for [`StretchBlt`](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-stretchblt).
Comment: Also keep in mind the proportions on the image you want to fit. Will they be the same? Otherwise you also need to consider ratios in your scaling so that it fits nicely in the constrained space.
Answer: You should pass to StretchBlt the actual size of the image you want to scale, but you are using 1000 x 1000.
Comment: thanks for the help . It works now andrew and vlad <3


enable jquery ui effects in theme .info file

Question: Now I should add something like <?php drupal_add_library('system', 'effects.bounce'); ?> to my page.tpl.php to enable jquery ui effects to use in views_slideshow_cycle module.
is there anyway to do this inside theme .info file?
Answer: No, it's not possible to add a Drupal library through a module or theme's .info file. You can add single CSS/JS files, but not a defined library.
That means it's physically possible to download separate copies of system libraries and include them statically in your theme, but you should not do this. It's not the 'Drupal' way, and it makes things very difficult to maintain.
You're right in thinking the logic shouldn't be in your page.tpl.php file, it should rather be inside your theme's hook_preprocess_page function in the template.php file.
That way the library will be added in time to be included in the page, you maintain a nice level of separation between logic and display, and your theme will be protected in the case that core updates need to be applied to the libraries you're using.
Answer: Sure, download jquery ui from http://jqueryui.com/ and put the javascript file you need in your theme then add a line
scripts[] = relative/path/to/file.js

Just make sure that jquery UI is binding to the jQuery variable and not $ and you should be good to go.
Comment: yeah, fair call. I guess you could extend the syntax of the .info file similar to the way that Omega does things if you really needed this functionality.
Comment: Drupal core already includes jQuery UI; adding another copy of the library doesn't make sense and will be a nightmare for maintainability
Comment: But that's exactly what the OP seems to be asking for...
Comment: I read it that the OP was looking for a way of including the system javascript libraries by way of an .info file. Making duplicated/forked versions of those files to be manually included is bad for a couple of reasons: 1. It reduces maintainability 2. When other modules in the system include the same libraries the proper way, there will be duplicate JS files in the page. This is bad for page load times and could introduce code conflicts
Comment: Yeah, I understand why you wouldn't want to do it but that doesn't stop me telling the OP how they *could* do what I thought they were asking how to do. You can't use the .info file to pull in system js but you can use it to pull in theme js. If you properly scope and namespace everything you won't get code conflicts. In D6 I regularly ran the painfully outdated core version of jQuery in parallel with a newer version, just need to use noConflict(). No need to downvote me for directly answering a question, downvote the question itself if you think the OP is asking how to do something "bad"..
Comment: I don't think the question is bad though, the OP doesn't ask for a way to get around the fact that libraries can't be added in .info files, he asks if it's possible, which it isn't. Sorry but this just bad advice, hence the down-vote
Comment: Yeah that would be a great solution...worthy of a module on drupal.org I think :)


Put a field in views with the vocabulary of the taxonomy term from a contextual filter

Question: I have a view which accepts taxonomy terms as contextual filters.
Now, what I would like to have is to put the vocabulary of the term in a field. Relationships?...
On the nodes that arewhown by views there are two fields with taxonony terms, and the view can be sorted by both. I want to access the very one the view is filtered with.
Comment: Is it a node view or a taxonomy view?
Comment: this is a node view, (ie, a view of nodes), filtered by tax terms
Answer: Add a term relationship based on the term field.

Then add a taxonomy Vocabulary Name Field using that relationship.
Comment: The thing is the node there are two fields with taxonony terms, and the view can be sorted by bot, and I want to access the very one the view is sorted with.
Answer: If you put a field in views with taxonomy vocabulary name then there is no need to use relationship. While creating a new view just select -
Show -> Taxonomy Terms
But if you want to show other content fields with that view then use relationship -
Taxonomy term: Content with term
Comment: I edited the question to make it more clear: I need to access the vocabulary of the term that is being used for filtering.


Problem in Python with function only writing one line to file

Question: I am trying to write a function in Python 3 that will write all lines that end with the string 'halloween' to a file. When I call this function, I can only get one line to write to the output file (file_2.txt). Can anyone point out where my problem is? Thanks in advance.
def parser(reader_o, infile_object, outfile_object):
    for line in reader_o:
        if line.endswith('halloween'):
            return(line)

with open("file_1.txt", "r") as file_input:
    reader = file_input.readlines()
    with open("file_2.txt", "w") as file_output:
        file_output.write(parser(reader))

Comment: Not very sure but is it because u r using return and not write?
Comment: Why not pass the output to the parser method and replace return(line) with output_file.write(line) ?
Comment: @Bogdan I don't think that's a good idea. One method should be responsible for finding the matches, another for writing the files, if you're going to split it up. If you're going to have the function do the writing, it should just do everything, like in the generator expression version of my answer.
Answer: def parser(reader_o):
    for line in reader_o:
        if line.rstrip().endswith('halloween'):
            yield line

with open("file_1.txt", "r") as file_input:
    with open("file_2.txt", "w") as file_output:
        file_output.writelines(parser(file_input))

This is called a generator. It can also be written as an expression instead of a function:
with open("file_1.txt", "r") as file_input:
    with open("file_2.txt", "w") as file_output:
        file_output.writelines(line for line in file_input if line.rstrip().endswith('halloween'))

If you're on Python 2.7 / 3.2, you can do the two withs like this:
with open("file_1.txt", "r") as file_input, open("file_2.txt", "w") as file_output:

You don't need to do readlines() on the file, just telling the loop to iterate over the open file itself will do the exact same thing.
Your problem was that return always would exit the loop on the first match. yield stops the loop, passes out the value, then the generator can be started again from the same point.
Comment: Thank you! `yield()` solved my problem. I really appreciate your thorough answer and detailed explanation. You also taught me a few other cool things like the two `with`s statement. Again, thank you!
Answer: line.endswith('halloween') might only work on the last of a file, since all other lines will have a newline appended. rstrip the line first. Also, use yield instead of return.
if line.rstrip().endswith('halloween'):
    yield line

Note that this will also strip off spaces at the end of the line, which may or may not be what you want.
You'll also have to modify your consumer to
with open("file_2.txt", "w") as file_output:
    for ln in parser(reader):
        file_output.write(ln)

Answer: Perhaps your parser function should be a generator. At the moment it's only called once and returns the first line that has "halloween" in it.
Like the following:
def parser(reader_o):
    for line in reader_o:
        if line.endswith('halloween'):
            yield line

with open("file_1.txt", "r") as file_input:
    with open("file_2.txt", "w") as file_output:
        file_output.writelines(parser(file_input))


Proving that the series $\displaystyle \sum_{k=1}^{\infty}\frac{m}{n^k}$ converges to $\frac{m}{n-1}$

Question: I would appreciate any feedback about the correctness of the proof and some potential other techniques!
Proposition: Let $m, n \in \mathbb{R}$, such that $\vert n \vert \gt 1.$ Then the series $\displaystyle \sum_{k=1}^{\infty}\frac{m}{n^k}$ converges to $\dfrac{m}{n-1}$.
Proof: We observe, that this is a geometric series in the form of $m\times n^{-k}$. Since the series is a geometric series, which converges, (EDIT) because if $\vert n \vert \gt 1$, then $\vert \frac{1}{n}\vert \lt 1$. Thus, we can use the geometric series test to first, find the common ration and then compute the sum. The common ratio, $r=\dfrac{a_{n+1}}{a_n}$, after substituting $a_n$, we have: $\frac{m}{n^2}:\frac{m}{n}$ $\implies \frac{mn}{n^2 m}$. After simplifying the expression, we get $r=\frac{1}{n}$. Therefore, we can evaluate the sum of the series using the closed form, $S_n=\frac{a_1}{1-r}$. Substituting $r$, we get: $S_n=\dfrac{a_1}{1-\frac{1}{n}}$. After doing the algebraic manipulations, we get $S_n=\dfrac{m}{n-1}$, as desired.
Comment: Hint: $|n|>1$ means $\left|\frac1n\right|<1.$ This is a geometric series.
Comment: @bb_823 The value of the geometric series is $\sum_{j=0}^\infty q^j = \frac{1}{1-q}$ for all $q\in\mathbb{R}$ such that $\vert q \vert < 1$. In this case, $q = 1/n$. It doesn't matter which sign $n$ and hence $q$ has.
Comment: Your proof looks good. However, as mentioned in the above comment, you should verify that the series actually does converge.
Comment: What if $n<-1$, you'll then have alternating series, which obviously converges, but to what value?
Comment: Interesting, it seems, that if $n \in \mathbb{Z}$, then this property still holds, however if $n \notin\mathbb{Z}$, then the series seems to converge to a random(?) value.
Comment: @Csoriburi See my comment above, it doesn't matter if $n$ is an integer or a real number or even a complex number as long as $\vert n \vert > 1$.
Comment: @stange Yes, thank you for your answer. Sadly, I didn't see your comment in time. It is quite interesting!
Answer: Another way is
to look at the partial sums
and use
$\dfrac{1-x^j}{1-x}
=\sum_{k=0}^{j-1} x^k
$.
$\begin{array}\\
\sum_{k=1}^{j-1}\dfrac{m}{n^k}
&=\frac{m}{n}\sum_{k=1}^{j}\frac{1}{n^{k-1}}\\
&=\dfrac{m}{n}\sum_{k=0}^{j-1}\frac{1}{n^{k}}\\
&=\dfrac{m}{n}\dfrac{1-\frac1{n^j}}{1-\frac1{n}}\\
&=m\dfrac{1-\dfrac1{n^j}}{n-1}\\
&=\dfrac{m}{n-1}-\dfrac{m}{n^j(n-1)}\\
\end{array}
$
so
$\left|\sum_{k=1}^{j-1}\dfrac{m}{n^k}-\dfrac{m}{n-1}\right|
=\dfrac{m}{n^j(n-1)}
$.
Therefore, to make
$\left|\sum_{k=1}^{j-1}\dfrac{m}{n^k}-\dfrac{m}{n-1}\right|
\lt \delta
$,
is is enough to make
$\dfrac{m}{n^j(n-1)}
\lt \delta$,
and this can be done
by making $j$
large enough
so that
$n^j > \dfrac{m}{\delta(n-1)}
$.
If you are allowed
the use of logs,
this is just
$j
\gt \dfrac{\log(m)-\log(\delta(n-1))}{\log(n)}
$.
If not,
you can use Bernoulli's inequality
($(1+x)^j \ge 1+xj > xj$)
to have
$n^j = (1+(n-1))^j
\gt (n-1)j
$
so
$\dfrac{m}{n^j(n-1)}
\lt \dfrac{m}{j(n-1)(n-1)}
= \dfrac{m}{j(n-1)^2}
$.
Therefore, if
$\dfrac{m}{j(n-1)^2}
\lt \delta$,
or
$j > \dfrac{m}{\delta(n-1)^2}
$,
we have
$\dfrac{m}{n^j(n-1)}
\lt \delta$.
This is, of course,
much worse than
the inequality with log,
but it is completely elementary.


Python. Requests. Post. Usual ways to log in don't work

Question: Try to log in in this site "websim.worldquantchallenge.com/login", but usual ways don't work. In most cases and websites we can use next form:
session = requests.session()
url = 'https://websim.worldquantchallenge.com/login'
data = {
    'EmailAddress': '<YOUR_MAIL>',
    'Password': '<YOUR_PASS'
}
result = session.post(url, data = data)
print(result)

But in this situation I get "response 403".
Simle ways of Authentication as "HTTPBasicAuth" or "HTTPDigestAuth" also do not work. So how can I log in in this case?
Comment: perhaps the website doesn't want you logging in via code?
Comment: What is the request sent when you login through the UI ?
Comment: Have you tried opening a browser's developer console, switching to the network view, and watching the actual login sequence for that site? It may surprise you.
Answer: First of all, you have to make sure that the website's policy allows login via code.
If so, the url of the post should be:
url = 'https://websim.worldquantchallenge.com/login/process'

Comment: And sorry again, but could you explain me how did you know that it could help? =)
Comment: I tried to observe from the Chrome's network view what was the address of the POST sent from the form page!
Answer: As far as I can tell the form is handled by javascript, so you don't really know what url the data is going to. For issues with websites where request doesn't seem to work, I've used selenium. It uses the chrome driver to pull up the page in the browser. You then find the element by class or id and fill in the form and click submit.
A lot of websites are moving to this javascript interaction style to prevent automated code from scrapping their site. I also see code for captcha so you might have to deal with that if that presents itself.
Comment: Yea, I use selenium now, but want to speed up my working
Comment: A mix between requests and selenium after logging in works too.
Answer: I would suggest logging in through the website with developer tools activated and looking at the request/response content.
Some possible reasons for not being able to log in using your usual method:

the form changed (e.g. 'EmailAddress' replaced by 'Username', a new field in the form)
the authentication method changed (e.g. new url, OAuth2...)
the website is preventing programmatic access by filtering on user-agent or adding hidden fields in the login form

And, a basic question: have you looked at the error message you're getting with the 403 (print(result.text)) ?
Comment: When i had got response 405, i looked at result.text, and didnt get any information.
Now i tried to do it and understood what you mean, although other user helped me with this problem )
Thanks.


How to re-write Guice Interface DI Injector.getInjector().getInstance(Interface.class) on Spring or EE

Question: Guice is avaliable for getting instance of Interface.class,
But how we can get the same thing for Interface in Java EE or Spring?
TestVar testVar = Injector.getInjector().getInstance(Interface.class)

Answer: Using spring the IoC container is the ApplicationContext. You can directly request it like this.
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
Interface myService = ctx.getBean(Interface.class);

Or you can inject it to your component.
Keep in mind this is a bad practice. You should never request the container directly. You should let it resolve dependencies for you.
Comment: JEY, thank you for your answer. I know about that usage. But my case is about injecting Interface. Guice can getInstance(Interface), but I'm not sure about Spring or EE.
Comment: You can do ctx.getBean(Interface.class) that doesn't change anything


Need assistance setting up a class to send email, it gets called from the main class

Question: I am trying to send an email from my application when a user logs in for the first time. The email consists of a activation code.
Update: I downloaded the latest javamail API and also the latest JAF (JavaBeans Activation Framework) and it does not compile due to imports being unknown symbols. How do I import from the javax package?
Here is the code that I got so far:
import java.util.ArrayList;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Email {
    static String smtpHost;
    static int smtpPort;
    static String from;
    static String to;
    static String subject;
    static String content;

    public Email(String toEmail, String code){
        smtpHost = "localhost";
        smtpPort = 25;
        from = "firstname.lastname@example.com";
        to = toEmail;
        subject = "Hello from Nestroia.com";
        content = "This is your activation code: " + code;
    }

    public Email(String toEmail, String name, String password){
        smtpHost = "localhost";
        smtpPort = 25;
        from = "email@example.com";
        to = toEmail;
        subject = "Hello from Nestroia.com";
        content = "This is your Login information.\n"
                + "Name: " + name + "\n"
                + "Password: " + password;
    }

    public static void send() throws AddressException, MessagingException {

        // Create a mail session
        java.util.Properties props = new java.util.Properties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", ""+smtpPort);
        Session session = Session.getDefaultInstance(props, null);

        // Construct the message
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        msg.setSubject(subject);
        msg.setText(content);

        // Send the message
        Transport.send(msg);

Here is the stacktrace:
java.lang.RuntimeException: java.lang.ClassFormatError: Absent Code attribute in     method that is not native or abstract in class file javax/mail/Address
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(Unknown Source)
at com.sun.glass.ui.win.WinApplication$2$1.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/mail/Address
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at Nestroia.Nestroia_Main$6$1.handle(Nestroia_Main.java:669)
at Nestroia.Nestroia_Main$6$1.handle(Nestroia_Main.java:559)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.SkinBase$5.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.SkinBase$5.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1300(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
... 7 more

Comment: then paste the exception ...it will give a clear picture ..
Comment: What is the question here? Are you getting an exception?
Comment: @ArturGVieira Please edit your question to include the stack trace.
Comment: im getting an exception. it doesn't allow me to send the email, that is the reason I posted. Is there something wrong with the code that can be spotted right away?
Answer: I'm guessing you probably have just the javaee.jar in your classpath, which has the definitions of the javax.mail.* classes but not the actual implementation.
You should download the javamail api if you dont already have. Found here
Answer: You're running with a javaee.jar that does not contain implementations. It's a "stubbed" implementation that is just intended to enable compilation, not execution. This post provides more details. (It's referring to Java EE 5, but the same holds true for 6.)
Answer: This post provides explanation and possible solution. You might need to adjust your class path.


Caminho relativo para arquivos de fontes em Angular 4

Question: após criar uma aplicação padrão Angular com o ng new aplicacao e inseridas as bibliotecas do PrimeNG, Bootstrap, Fontawesome a aplicação roda normalmente através do ng server.
Após rodar o ng build e subir a aplicação no servidor tudo funciona desde que a aplicação rode apartir da raiz do domínio (ex: www.abc.com.br). Se a aplicação rodar de uma pasta (ex: www.abc.com.br/appteste) e feitos os ajustes nos caminhos dos .js, a aplicação carrega normalmente mas os arquivos referente as fontes (.woff, .woff2, .ttf, .svg, .eot) ficam sendo buscandos na raiz do domínio com isso apresentando erro 404.
Ou seja, os caminhos dos arquivos citados acima não ficam relativos a pasta que a aplicação está rodando. Como tudo é "juntado" pelo Webpack não sei onde devo alterar para modificar o caminho dos arquivos citados acima.
Alguém sabe como corrigir? Desde já agradeço a todos que puderem ajudar.
Comment: Você pode adicionar o caminho das fontes no arquivo SCSS principal da sua aplicação.
Answer: Quando você cria um projeto com ng cli, na raiz do projeto é criado um arquivo: .angular-cli.json dentro deste arquivo voce tem o tag styles e scripts. Então voce so precisa adicionar os caminhos corretor nesse arquivo, por exemplo:
"styles": [
    "../node_modules/roboto-fontface/css/roboto/sass/roboto-fontface.scss",
    "../node_modules/normalize.css/normalize.css",
    "../node_modules/font-awesome/scss/font-awesome.scss",
    "../node_modules/ionicons/scss/ionicons.scss",
    "../node_modules/bootstrap/scss/bootstrap.scss",
    "../node_modules/leaflet/dist/leaflet.css",
    "../node_modules/chartist/dist/chartist.css",
    "../node_modules/fullcalendar/dist/fullcalendar.css",
    "../node_modules/handsontable/dist/handsontable.full.css",
    "../node_modules/ng2-slim-loading-bar/style.css",
    "../node_modules/angular2-toaster/toaster.css",
    "app/theme/theme.scss",
    "styles.scss"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/easy-pie-chart/dist/jquery.easypiechart.js",
    "../node_modules/jquery-slimscroll/jquery.slimscroll.js",
    "../node_modules/tether/dist/js/tether.js",
    "../node_modules/bootstrap/dist/js/bootstrap.js",
    "../node_modules/handsontable/dist/handsontable.full.js",
    "../node_modules/chroma-js/chroma.js"
  ],

Answer: Olá, a solução para o caso específico é definir o deploy-url no comando ng build:
ng build --prod --deploy-url=/apptest/ --env=dev


why does escape character \b shows an unknown character?

Question: i have a simple line of code
 print("Hello \bWorld!")

and the output instead of HelloWorld! is

what is the problem ? im using python 3.5. i took the code from w3school.com
Answer: Your console output is incapeable of displaying the '\b'. This has nothing to do with python.
It works in Visual Studio: You can verify it by setting a breakpoint in your debugger and inspect the value (most IDEs have UTF-8 support) - the windows console f.e. has not.
Debugging output in Visual Studio:

vs. console output in windows:

and (here it looks like yours)

for
k = "Hello \bWorld!"
print(k)

Comment: thanks for answer . isnt \b suppose to erase the last character before it ?or im misunderstood? why in the output space is still there?there is an space and and unknown char. and picture is for pycharm IDE .  and also even if i write the "Hello \bWorld!" in a file instead of printing and open it with app like notepad++ even there its not displayed correctly .
Comment: @mike If you do `with open("f.txt","w") as f: f.write("Hello \bWorld")` you file with contain exactly that .. a space followed by a `'\b'` - it does not miracuously remove the space and the \b (and before/after then the remainder of your string) from your string before writing. If you _print_  `"Hello \bWorld"` in a compatible shell, it will only print `"HelloWorld"` - see _console output in windows_ above. Your IDE decided to display the full string instead without applying the \b to the space.
Comment: @ Patrick Artner another question . i would be thankful if you would clarify this for me. suppose i have text file with some text in it if i do ***write("\b")*** is it suppose to delete the last character in the file ?
Comment: @Mike no - it will write an additional character to the file, which is `'\b'` (or binary \x08 )
Answer: \b

ASCII backspace ( BS ) removes previous character in Python 3.x:
print("ab\bc")

OUTPUT:
ac

In your case its not something related to Python but the console itself.
As I get:
print("Hello \bWorld")   # HelloWorld

pyFiddle
Python Escape Characters


Limit of a certain function

Question: My analysis book gives two definitions of a function approaching a limit $l$ as $x$ approaches $x_0$.

For all $\epsilon\gt 0$ there exists $\delta>0$ such that if $x_0-\delta<x<x_0+\delta$ then $l-\epsilon<f(x)<l+\epsilon$.
If $x_1,x_2,x_3,\ldots$ is a sequence which converges to $x_0$ then the sequence $f(x_1),f(x_2),f(x_3),\ldots$ converges to $l$.

Is there a proof that these definitions are equivalent?
Answer: 1$\implies$ 2:
consider a sequence $x_n\to x_0$. Then for $n$ big enough you have
$x_n-\delta<x_0<x_n+\delta$ and then $l-\epsilon<f(x_n)<x+\epsilon$, so
$f(x_n)\to l$.
2$\implies$ 1:
If 1 is false, there is a certain $r>0$ such as for every $\delta$, there is
$x_\delta$ for which
$$
x_\delta -\delta < x_0 < x_\delta +\delta\\
f(x_\delta) > f(x)+r\ \ \ \text{ or }  \ \ \ f(x_\delta)  <f(x) - r
$$
Consider the sequence $x_{\frac 1n}$ ($\delta = \frac 1n$).
Then $x_\frac 1n\to x_0$ and $f(x_{\frac 1n})\nrightarrow l$, so 2 is false.

Limit of a certain function


How to interact with gui application using windows service

Question: I have an application in java in which I have start and stop buttons in swing. I want to make a windows service which automatically clicks on start button. Is it possible and if it's possible how to do it?
Answer: You must find a way to identify the main window of your swing application from the Windows service (common usage is the title bar)
Then, you search in subwindows how to identify the Start button (generally the id, but you could use text)
All that must be done only once, using the Windows SDK tools and/or you knowing from the GUI application
Now the service :

searches the top-level windows for the right one
searches the relevant button
gets it position
uses SendInput API function to simulate a MOUSEEVENTF_LEFTDOWN and MOUSEEVENTF_LEFTUP event over the button

The last part could be done in Java (with Robot), but the others will need to use Windows API


Value returning as undefined

Question: I need to get my latitude and longitude. Inside my function, it returns very well, but if i try to call the same this.latitude but out of function, it returns as undefined.
localizar() {

this.geolocation.getCurrentPosition().then((position) => {

  this.latitude = position.coords.latitude;
  this.longitude = position.coords.longitude;

  // Here it returns
  console.log('teste: ', this.latitude, this.longitude);

})
// Here returns as undefined
console.log('lat: ', this.latitude, 'lng: ', this.longitude)

}
Comment: This is standard Promise behavior. You *have* the value inside the `.then` but you are not guaranteed to have it elsewhere without `await` or `.then` (or just wait long enough, but don't do that).
Comment: There is a way to get these value? Using await? Is that?
Answer: You can use async/await features.
async localizar() {
    const position = await this.geolocation.getCurrentPosition();
    this.latitude = position.coords.latitude;
    this.longitude = position.coords.longitude;

    // your logic here
}

More info about async functions and Promises:
Answer: async localizar() {
  const position = await this.geolocation.getCurrentPosition();
  this.latitude = position.coords.latitude;
  this.longitude = position.coords.longitude;

  // your logic here
}

Value returning as undefined


How do I gather information from each loop in a while loop python

Question: I want to gather information from a while loop each time it loops over. For example, if you have a while loop that runs forever and encases an input asking for a number, and you add the numbers over time, how should I do that? Example:
while True:
  a = int(input("Enter a number "))
  a = a + a

Is there any way to do this? Thank you so much!
Comment: Put a variable outside of the loop
Comment: Could you clarify what that means?
Comment: Does this answer your question? [Is it possible to have a user enter integers and add them using a while loop in python?](https://stackoverflow.com/questions/60849323/is-it-possible-to-have-a-user-enter-integers-and-add-them-using-a-while-loop-in)
Answer: total = 0
while True:
  a = int(input("Enter a number "))
  total = total + a

  print(f"The total is {total}")

Comment: While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
Answer: total = 0
while True:
  a = int(input("Enter a number"))
  total = total + a

  print("The sum is ", total)

Comment: Thanks this helped a lot!
Comment: Don't use `sum` as a variable name. It hides the built-in [`sum()`](https://docs.python.org/3/library/functions.html#sum).


Onde achar o caminho do banco de dados android?

Question:

SQLiteDatabase BancoDados = null;
String NomeBanco = "Cadastro";

CriaBanco();

public void CriaBanco(){
        try{
            BancoDados = openOrCreateDatabase(NomeBanco, MODE_WORLD_READABLE, null);
            String SQL = "CREATE TABLE IF NOT EXISTS tabCadastro11 ( _id INTEGER PRIMARY KEY, nome TEXT, imagePath TEXT ) ";
            BancoDados.execSQL(SQL);
            Criapasta();
            MensagemAlerta("Banco de Dados", "Banco Criado com Sucesso");
        }catch(Exception erro){
            MensagemAlerta("Erro Banco de Dados", "Não foi possivel criar o Banco" + erro);
        }
        finally {
            BancoDados.close();
        }
    }

    public void Criapasta() {
        File f = new File("/data/data/com.example.gabrielbonatto.oficial/databases/Cadastro"); //Já tentei o NomeBanco e o BancoDados
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(f);
            fos = new FileOutputStream("/mnt/sdcard/meu_banco_dump.db");
            while (true) {
                int i = fis.read();
                if (i != -1) {
                    fos.write(i);
                } else {
                    break;
                }
            }
            fos.flush();
            Toast.makeText(this, "DB dump OK", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "DB dump ERROR", Toast.LENGTH_LONG).show();
        } finally {
            try {
                fos.close();
                fis.close();
            } catch (IOException ioe) {
            }
        }
    }

Li vários tutoriais para onde vai o arquivo db criado em uma aplicação Android, porém eu só acho usando na IDE Eclipse e não no Android Studio.
Alguém sabe para onde esse arquivo do banco de dados criado na aplicação vai ? Queria saber porque queria usar SQLite Browser para ver o meu banco
Answer: Para abrir essa opção no Android Studio siga os seguintes passos:
Tools > Android > Android Device Monitor

Lá dentro o caminho é o mesmo do DDMS tradicional do eclipse
/data/data/"seu package"/databases/"seu banco"

Lembrando que se você estiver utilizando um aparelho físico como "emulador" você deverá obter acesso de "super user" para conseguir visualizar seu Banco dentro do aparelho. Para obter esse acesso faça da seguinte maneira:
Navegar até a pasta .\sdk\platform-tools pelo ms-dos e executar o adb da seguinte forma.
.\sdk\platform-tools>adb devices

List of devices attached
0123456789ABCDEF device
Este comando listará os dispositivos ativos e lhe dará o identificado do dispositivo, feito isto:
adb -s 0123456789ABCDEF shell

Depois acessar via super usuário:
$ su
# chmod 777 /data
# chmod 777 /data/data
# chmod 777 /data/data/br.com.dominio.projeto
# chmod 777 /data/data/br.com.dominio.projeto/databases
# chmod 777 /data/data/br.com.dominio.projeto/databases/banco.db

Após executar os comandos acima entre no DDMS selecione novamente o dispositivo e navegue ate
data/data/"seu projeto"/databases/banco.db

Comment: A resposta do @FelipeDouradinho, se enquadra perfeitamente para você então, faça um dump para exportar para o SD seu BD.
Comment: o caminho do DDMS só tem a pasta data e nada mais, não achei o nome do meu banco lá sendo q ele já esta criado
Comment: Você está utilizando um aparelho físico pra isso? se tiver você precisa liberar o acesso ao banco, dac maneira que expliquei
Comment: estou usando emulador  Bluestack
Comment: vou editar minha resposta colocando um print
Comment: é só jogar no código e ja era ?
Answer: Está em:
//data/data/<SEU-APLICATIVO>/databases/<nome-do-seu-banco>

Coloque seu banco <nome-do-seu-banco> fora desta pasta usando um Gerenciador de Arquivos e renomeie a extensão para .db3 para usar no SQLiteExplorer
Se estiver usando um emulador, use o DDMS para navegar nas pastas.
Se desejar criar um "dump" do seu banco usando o Java no Android
File f=new File("/data/data/<seu-app>/databases/<seu-database>.db3");
FileInputStream fis=null;
FileOutputStream fos=null;

try
{
  fis=new FileInputStream(f);
  fos=new FileOutputStream("/mnt/sdcard/meu_banco_dump.db");
  while(true)
  {
    int i=fis.read();
    if(i!=-1)
    {fos.write(i);}
    else
    {break;}
  }
  fos.flush();
  Toast.makeText(this, "DB dump OK", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
  e.printStackTrace();
  Toast.makeText(this, "DB dump ERROR", Toast.LENGTH_LONG).show();
}
finally
{
  try
  {
    fos.close();
    fis.close();
  }
  catch(IOException ioe)
  {}
}

Para saber se o arquivo do banco de dados existe:
File f = new File(...);
if(file.exists())
{

}

Seu manifest.xml deve ter permissão de acesso ao cartão SD:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Comment: onde eu poderia colocar o Dump ? logo após ter criado o banco ou antes?
Comment: @GabrielSantanaBonatto, a classe `new File()` acima não cria um banco, ela seta apenas o arquivo, portanto, o banco já deve existir antes de mover o dump
Comment: nessa parte /data/data//databases/.db3 ,  = nome da aplicação ;  = nome do banco ; /mnt/sdcard/meu_banco_dump.db = posso deixar assim ?
Comment: Opa, sim, basta substituir `` pelo nome da sua aplicação (como estiver no `manifest.xml` e `` pelo nome (literal) do seu banco.
Comment: então, eu criei o banco, mas só que esta dando "DB dump ERROR" , eu testei os dois SQLiteDatabase BancoDados = null e o  private String novoNome = null, vou editar meu código para vc ver
Comment: No `debug` você consegue saber se o arquivo existe? (atualiei minha resposta)
Comment: java.io.FileNotFoundException: /data/data/Oficial/databases/NomeBanco.db3: open failed: ENOENT (No such file or directory)
java.io.FileNotFoundException: /data/data/Oficial/databases/BancoDados.db3: open failed: ENOENT (No such file or directory)
(testei com os 2)
Comment: Sem colocar a extensão ".db3" também dá problema? Outra coisa, `Oficial` está correto? Lembre-se que deve ser o caminho do pacote seguido do nome da aplicação, ex.: `com.seusite.oficial`
Comment: retirei a extensão db3, o Oficial acho que estava incorreto, porque eu coloquei o pacote completo mas mesmo assim ainda da problema de diretório
Comment: Depois de muito sacrifício eu consegui colocar no /mnt/sdcard/meu_banco_dump.db , tinha que colocar o NomeBanco que era Cadastro e sem a extensão .db3...  e agora como eu faço para abrir ele com o SQLite Browser ?
Comment: Opa, como você fez? Me fale por favor, para eu atualizar a resposta. O `SQLite Browser` pode ser obtido em http://sqlitebrowser.org/
Comment: File f=new File("/data/data//databases/.db3"); tire o db3, e no  é o nome do banco que é do tipo String na aplicação na hora de criar o banco, ou seja, não é a variavel que vc vai colocar, é o nome que vc já colocou na aplicação do seu banco
Ex: String NomeBanco = "Cadastro";
File f=new File("/data/data/com.example.gabrielbonatto.oficia/databases/Cadastro")
Comment: Mas agora como eu faço para selecionar o arquivo que esta lá no sdcard dentro do emulador?
Comment: O ideal é mover para o mesmo local do DB! Aí já seria um novo tópico hehe


SQLServer Trigger apos update

Question: Vamos imaginar o seguinde cenário:
CREATE TABLE invalido (
   ds_valor character varying(255)
)

CREATE TABLE email (
    email character varying(255)
)

agora preciso de uma trigger que toda vez que eu execute um UPDATE ou INSERT na tabela email ele verifique se o valor está na tabela  invalido, se estiver então deve substituir o que seria inserido na tabela email por email invalido.
Mesma situação da: PostgreSQL Trigger apos update porem com SQLServer
Comment: David, você pode adicionar a pergunta o que tentou até agora?
Answer: Basicamente, é isso aqui
CREATE TRIGGER [dbo].AfterUpdateOrInsertEmail
ON [dbo].email

AFTER INSERT, UPDATE
AS
BEGIN

    IF EXISTS (SELECT * FROM [dbo].invalido inv WHERE inv.ds_valor = (Select Inserted.Email From Inserted))
    BEGIN
        Update Email Set email = 'inválido' From Inserted;
    END
END

Comment: Update Email Set email = 'inválido' From Inserted; isso não precisa de where? coloquei o where e funcionou
Comment: Entrou em looping :(
Comment: Ora, mas a estrutura é exatamente essa da pergunta? Eu repliquei a estrutura aqui e funciona normal.
Comment: Vou ver se tem alguma outra trigger que possa ter bugado...
Answer: O ideal para que a estrutura funcionasse da melhor forma era que sua tabela email tivesse um id único, assim seria possível fazer com uma trigger instead of que faria o tratamento antes mesmo de do insert ou update.
Você pode criar uma trigger com inner join na tabela invalido, garantindo que apenas os registros inválidos serão alterados.
CREATE TRIGGER trg_after_iu_email ON email AFTER INSERT, UPDATE
AS
BEGIN
  set nocount on;

  UPDATE ema
     SET ema.email = 'email invalido'
    FROM email ema
         INNER JOIN inserted ins on ins.email = ema.email
         INNER JOIN invalido inv on inv.ds_valor = ins.email;
END;
GO

Observação: Caso exista um registro na tabela invalido com o valor email invalido a trigger entrará em looping infinito.

SQLServer Trigger apos update


msysgit - how do I use gitk to search for string in commit ignoring case

Question: I'm sure this question seems really simple. I have a git repository and I am reviewing it in gitk. There is an option to:
Find Next prev commit adding/removing string: some string IgnCase All fields
There are commits that contain Some String (exactly as I just cased it) and if I search for it exactly as cased gitk will show the matches. However if I search as I did above using some string then there are no matches. Maybe it's late and I'm tired but why doesn't that work? Does anyone here use msysgit? I'm using git version 1.7.11.msysgit.1.
Thanks
Answer: gitk internally calls git diff-tree -S<string> in that case, which performs a case sensitive search. In fact, git diff-tree seems to even accept a (somewhat undocumented) "-i" option to ignore the case, but gitk does not make use of that. In short, it's a bug in gitk as it should either disable "IgnCase" when searching added / removed strings or make use of "-i".


How to map a trajectory to a vector?

Question: I have a series of data points in this form (timestamp, lat, long) for a set of users. Each user has a trajectory when he travels from point A to point B. There might be any number of points from A to B. They are ordered data points based on time stamp. I want to transform them as a vector to do various analysis tasks. One thought I have is to look at turns and make them as a dimension. I would like to know more approaches.
What I want is a one vector representing the whole trajectory, think of it like one point for a trajectory.Right now I have a collection of 3d points.
I would like to do trajectory similarity search. If there are two trajectories that in time are travelling close to each other then they are similar. Think of it like this you are going from house to work at 9am. Somebody else at 9:10 am also his home for work and stays some distance from you. Since u have the same workplace , you will most likely have same trajectory. Something like a classifier built on top of a trajectory. I can do activity detection in a trajectory, I can do a source destination analysis too.
Comment: Can you give an example of transformation to vector? From the mathematical point of view your data is already a collection of vectors in three dimensional space, clearly you want something else. So the example would be very welcome.
Comment: possible duplicate of [Similarity measures between curves?](http://stats.stackexchange.com/questions/27861/similarity-measures-between-curves)
Comment: @Quartz The same geometrical curve traveled at different speed patterns is relevant to me
Comment: It's also important what kind of analysis is to be run. As a first step I would try a Karhunen-Loeve expansion on the (naively vectorized) paths anyway, that would "automatically" build the structure needed to capture path features.
Comment: I'm afraid the edit doesn't respond to the comment by @Quartz, which asks for essential information: what kind of "various analysis tasks" do you contemplate?
Comment: @whuber Does the edit help? Let me know if I can give more informatiom.
Comment: It's getting there. But what precisely do you mean by "similar"? An answer to that will suggest appropriate ways to encode the trajectories.
Comment: @whuber Added more description. Does this help?
Comment: Yes: you are asking for how to measure closeness of curves in space-time. All the myriad solutions available in other dimensions (such as 2 and 3) are available to you, subject to a decision on your part concerning how to trade differences in time off against differences in location. (Actually, the same need for a choice of metric is apparent even when just comparing curves in 3D, because often elevation differences have a different meaning than horizontal differences.) Anyway, your concern is about *comparing* trajectories rather than *transforming* them.
Comment: @whuber If I can transform trajectories, I just want to see different kinds of exploration I can do and maybe get some interesting results. I do not know what they might be though
Comment: I would also suggest to focus on comparison and a distance between vector valued time series. Implicitly such distance will act on both time and space, but mixing them in the input already might be confusing: then any distance would have to "know" that already and undo it. Unless you just want a very simple distance and have "the real thing" in the mapping, which means you're using a mapping to implicitly define a (two step) distance, which is also legitimate but must be done with care.
Comment: Important preprocessing of the input trajectiories: shall the same geometrical curve traveled at differents speed patterns be considered the same? It seems so after the comment from @whuber. Then you might want first to factor out the travel pattern in time and get a curve parametrized by length. This allows for much simpler distances, such as the maximum spatial distance in the pair of points over each length. Also the K&L expansion is only interesting at that point.
Comment: Global Alignment kernels can be useful for time-series classification. The underlying idea is to render the well-known DTW distance to a valid PSD kernel. With this kernel, SVM can do the learning and predictions. See http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.388.5363&rep=rep1&type=pdf
I've used for various time-series classification tasks and the results were good.
Answer: I would start with dynamic time warping. As long as you have the distance between any two points (lat,long) this approach should work. It adjusts for different speeds of motion. For instance, you and I live in the same village and go to work to the same factory, but I stop by a coffee shop on the way. It takes longer for me to arrive but we're more or less on the same path, so the similarity measure adjusts for different time scales.
This is different from what you have in mind. It seems that you want to come up with one value (vector) to represent the trajectory, then calculate the distance between the vectors. I'm suggesting you to use the distance measure between the trajectories directly, without intermediate step.
Answer: If you only consider instantaneous turns, i.e., changes in direction, I don't think this will uniquely define the position at a next time instance -- unless each user is travelling at a constant known speed (no indication of this in your question). Since you are moving across a (spherical, I infer?) surface, you will probably need at least a second coordinate to determine you positions uniquely. Why not simply build the $2 \times N$ array $[\bf{x}(t); \bf{y}(t)]$ per user with time stamp as a parameter, then concatenate this to a $1 \times (2N)$ vector $[\bf{x}(t) \bf{y}(t)]$ you must have a vector (or $1 \times (2N\times M)$ for $M$ tagged users? You could also take arc length $s(t)$ for the travelled path as a parameter instead. Are the time stamps at regular intervals; otherwise you will need a separate vector for them for look-up. PS: I cannot see a link with stats; is this relevant to Cross Validated?
Answer: For each user, you have two time series, lat(t) and long(t). I think that's the simplest representation -- I wouldn't try to complicate things by converting to some definition of turns, which would not only be more difficult, but also would require being very careful about the initial starting point and treating it differently in any analysis. (It's probably noisier as well.)
Keeping the data as lat & long time series also keeps it simple for the most likely use -- where you will look at a various time windows at different times - there's no need to constantly recalculate a starting point at the beginning of a new time window being analyzed.
If every users' time series lat & long were all sampled at the exact same times, as noted in another reply you can just concatenate the two time series vectors into one long vector.  A similar example that had 5 time series looked like this:
 .  Then you have one long vector for each user that you can analyze just like any other vector for pattern recognition, distance measures, clustering, etc.
For distance measures between users, you're typically going to use a weighted form depending on the application.  For instance, when focusing on convergence towards a common destination, you'd increase the weights the most towards the end of the time window (whether looking at euclidean calculations, max distance, etc.).
But, the original question seems to say that there may be differing numbers of points between A and B for different users.  And in any case, even for the same sampling interval, it's likely that that the times aren't exactly the same (maybe differing by some constant because sampling started at different times).  Furthermore, it's quite possible that there will be some missing data. In any of these cases, conceptually, you'd need to think of each time series in continuous form, perhaps fitting a curve to it, and resampling every user at the exact same times.  (That's analogous to the resampling that occurs in photo analysis when you shrink a picture).   Then your time series vectors for lat & long are the same length and correspond exactly to the same times, so that the concatenated vectors for each user over some time period can be compared to each other correctly.

How to map a trajectory to a vector?


UNHEX XML data from MySQL in SQL server

Question: I have selected XML data (TEXT column type) from MySQL using:
SELECT HEX(CONVERT(column USING utf16le)) FROM table

How can I get data back to XML in SQL server (now stored in NVARCHAR field)?
Comment: When downvoting, explain your reason. This question is related to https://stackoverflow.com/questions/36082433/exporting-table-with-blob-and-utf8-string-fields-from-mysql-to-ms-sql-server-201
Answer: Right answer is to use this in SQL server:
CAST(
CONVERT(varbinary(MAX), column, 2)
as nvarchar(max))

UNHEX XML data from MySQL in SQL server


Can Random(Int32).Next(minValue, maxValue) be used as a Linear Congruential Generator?

Question: Can
<code> System.Random(Int32).Next(minValue, maxValue) ;
</code>
be used as a sort of Linear Congruential Generator?
Answer: So, the answer is NO. Because Random() changes from version to version in .NET. I cannot use Random(Int32).Next(minValue, maxValue) as a sort of Linear Congruential Generator. Ugh!
Comment: you have to compile your code targeting a specific version of .Net, so your program will always be with the same implementation of Random unless you change the target framework and re-compile.
Answer: Yes, System.Random will always give the same next value given the same seed and boundaries, the constant is the seed which you can optionally supply. So you would NOT want to change the seed each time you call Next() as your line does, instead:
<code>var myRandom = new Random(mySeed);
var value = myRandom.Next(minValue, maxValue);
var anotherValue = myRandom.Next(minValue, maxValue);
...
</code>
Comment: Be aware that the implementation of Random has changed multiple times in the past. That means the same seed gives different random numbers on different .NET Framework versions. Most likely it will give different numbers again when .NET 5 is released someday.
Comment: To continue on what Felheart said, if you want to avoid the chance that the internal implmentation will change causing a new sequence for the same seed use a RNG with a well defined behavior. A easy way to do this is just use any of the Crypto stream chipers and read the stream of bytes you get out from a given key.