Error parsing file arguments error on jar with entry point creation

Question: I've create simple java project with single class - Main with main method printing Hello.
package com.foo;

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello!");
    }
}

Code was compiled to bin directory. I'm trying to create jar using command
jar -cfe project.jar com.foo.Main -C bin\

with no results, always returning Error parsing file arguments error.
I also tried many different variations, like
jar --create --file project.jar --main-class com.foo.Main -C bin

but none of it worked. I'm using Java 16
Answer: Try running this. It should create the 'project.jar'
jar --create --file project.jar --main-class com.foo.Main -C bin .

-C flag Temporarily changes directories (cd dir) during execution of the jar command while processing the following inputfiles argument.
This command changes to bin directory and adds to project.jar all files within the bin directory (without creating a bin directory in the jar file).
For more information check the -C part in the OPTIONS section :
https://docs.oracle.com/javase/7/docs/technotes/tools/solaris/jar.html#options
Comment: @sanastasiadis The . at the end of the -C commands is to go back to the original directory
Comment: I guess the difference between what OP tried and what you suggest, is the `.` at the end? Please explain. Thanks.
Comment: This helped me a lot. Thanks!
Comment: the . at the end tells which files to select: if you put a file or a list of files present in the subfolder, it will include those files, if you put . it will take all of the files in the folder
Answer: You need both a "=" after main-class and a "." at the end to selct al lthe files
jar --create --file project.jar --main-class=com.foo.Main -C bin .
or
jar cfe project.jar com.foo.Main -C bin .


Select Distinct with MAX() using SQL Server

Question: I am trying to get all distinct account numbers from 3 tables in SQL Server, but it seems that my way doesn't work, any suggestions?
SELECT distinct account, max(date_added) as date_added FROM table_one group by account
union
SELECT distinct account, max(date_added) as date_added, FROM table_two group by account
union
SELECT distinct account, max(date_added) as date_added, FROM table_three group by account  order by account asc

Comment: Using `DISTINCT` with a `GROUP BY` is redundant.  Can you elaborate on what *doesn't work*?
Comment: you have commas in second and third selects after 'as date_added' just before FROM.
Comment: Explain why you are using max in there.
Comment: The accounts are inserted every month, I need to get the distinct ones from the most current date. The error is a "Incorrect syntax near the keyword 'FROM', but I don't see any error there.
Comment: I saw that now, with the "," commas, now my issue is how to get rid of duplicated account numbers. Thanks for pointing out the commas issue!
Comment: Duplicates occur because of the different dates and tables.  First union all the tables together then get the max date grouping by account.  But as we didn't know if you wanted 1 distinct account record from each table or 1 distinct account and date from all 3 tables. @devart's solution met both methods.
Answer: 1
SELECT account, MAX(date_added) AS date_added
FROM table_one
GROUP BY account
UNION
SELECT account, MAX(date_added) AS date_added
FROM table_two
GROUP BY account
UNION
SELECT account, MAX(date_added) AS date_added
FROM table_three
GROUP BY account
ORDER BY account ASC

2
SELECT account, MAX(date_added) AS date_added
FROM (
    SELECT account, date_added
    FROM table_one
    UNION ALL
    SELECT account, date_added
    FROM table_two
    UNION ALL
    SELECT account, date_added
    FROM table_three
) t
GROUP BY account
ORDER BY account ASC

Comment: I tested the number 1 here, I am getting duplicated account numbers, thats why I was trying with distinct.
Comment: @Siyual already said that DISTINCT with a GROUP BY is redundant. or you mean something another? please provide for us expected and actual results
Comment: The number 2 option  here got rid of  the duplicated account numbers.
Comment: i don't have a crystal ball. please provide a small example with expected and actual results. thanks in advance.
Answer: Generate a set of data combining the results then get the max date for each account.  This generates an inline view from which we can get a distinct account and max date added.
SELECT account, max(date_Added) as Date_Added from (
SELECT account date_Added FROM table_one
union
SELECT account, date_added FROM table_two
union
SELECT account, date_added FROM table_three) B
Group by account

Answer: select account, MAX(date_added)
FROM (
    SELECT account, date_added FROM table_one
    union
    SELECT account, date_added FROM table_two
    union
    SELECT account, date_added FROM table_three
) X
group by account
order by account asc

So what this query does, it unions all the data from all of the three tables in one recordset, so you can work with it as it is one table. Imagine that you have 3 accounts, 1, 2 and 3, and there is following data for them spread accross those 3 tables:
Table One
Account | Date Added
--------+-----------
    1   | 01-01-2015
    2   | 01-02-2015

Table Two
Account | Date Added
--------+-----------
    3   | 01-03-2015
    1   | 01-02-2015

Table Three
Account | Date Added
--------+-----------
    2   | 01-04-2015
    3   | 01-05-2015

So after union all of those records out of all the three tables we get following 'table' (actually it is recordset stored in memory):
Union Data
Account | Date Added
--------+-----------
    1   | 01-01-2015
    2   | 01-02-2015
    3   | 01-03-2015
    1   | 01-02-2015
    2   | 01-04-2015
    3   | 01-05-2015

Than we just select account and latest date_added for each of the distinct account found within this set, so we get following results:
Result Data
Account | Date Added
--------+-----------
    1   | 01-02-2015
    2   | 01-04-2015
    3   | 01-05-2015

Feel free to ask any other questions you get related to this.
Comment: Please add some comments about your solution on why and how it solves the problem
Comment: @Odedra, Here you go, sorry for not posting it initially.
Answer: If you want a list with all accounts and each account only appears once, then you could do something like:
select distinct account from table_one
union
select distinct account from table_two
union
select distinct account from table_three

By using union you will not get duplicate rows, and since you are only selecting account you will get each account only once.
It is however unclear what you are doing with the date_added column.


Show $\max_{i\leq n} |X_i|^p/n$ converges to $0$ in probability

Question: $X_i$'s are i.i.d random variables and  $\mathbb E(|X_i|^p)=k<\infty$ for some $p,k$. I want to show $Z= \max_{i\leq n} |X_i|^p/n$ converges to $0$ in probability.
Here is what I have tried.
$$\mathbb P(Z\geq \epsilon)=1-P(Z< \epsilon)=1-\prod_{i\leq n}\mathbb P(|X_i|^p/n<\epsilon),$$by indepdence. That is $$1-\prod_{i\leq n}(1-\mathbb P(|X_i|^p/n\geq\epsilon))=1-(1-P(|X_1|^p/n\geq\epsilon))^n.$$ Now apply Chebyshev we have $$\mathbb P(Z\geq \epsilon)\leq1-(1-\mathbb E(|X_1|^p/n\epsilon))^n=1-(1-k/n\epsilon))^n$$ which does not converges to 0 as $n \to\infty$. I don't know If I can find any stronger inequality to make this proof work . Any suggestions will be appreicated.
Comment: Can we assume $p\geqslant1$?
Comment: @Math1000 1000 I don't think so.
Answer: Let $Y_n=\max_{1\le i\le n}|X_i|^p$. Then $Y_n/n\xrightarrow{p}0$ iff $n\mathsf{P}(|X_1|^p>n\epsilon)\to 0$ as $n\to \infty$ for all $\epsilon>0$. Since $\mathsf{E}|X_1|^p<\infty$,
$$
n\mathsf{P}(|X_1|^p>n\epsilon)\le \epsilon^{-1}\mathsf{E}[|X_1|^p 1\{|X_1|^p>n\epsilon\}]\to 0
$$
as $n\to\infty$ by the dominated convergence theorem.
Comment: So does the independence of  $X_i$'s matter in the problem?
Comment: Sorry, why $\mathbb P(Y_n>n\epsilon)=n\mathbb{P}(|X_1|^p>n\epsilon)?$
Comment: $$
\mathsf{P}(Y_n>a)\le \sum_{i=1}^n\mathsf{P}(|X_i|^p>a)=n\mathsf{P}(|X_1|^p>a).
$$
Comment: Indeed It think the last inequality should be $ n\mathsf{P}(|X_1|^p>n\epsilon)\le \epsilon^{-1}\mathsf{E}[|X_1|^p]$. Why does the indicator function appear (I assume this step is using Chebyshev)?
Comment: That step uses the fact that $\mathsf{P}(A)=\mathsf{E}1_{A}$...


Does the centralizer of the identity component map onto the component group?

Question: Let $G$ be a Lie group, $G_0$ the connected component of the identity, $\pi:G\to G/G_0$ the quotient map onto the component group, and $C_G(G_0)$ the centralizer of $G_0$ in $G$.
Question: Is it always the case that $\pi(C_G(G_0))=G/G_0$? If not, is there a "nice" non-trivial (e.g., not just the connected ones) class of Lie groups $G$ always having this property?
I suspect this is false in general, but there seem to be many natural examples where this occurs, such as in $\mathrm{GL}(n,\mathbb{R})$, which has the stronger property that $Z(G)$ maps onto $G/G_0$, or in the product of a connected Lie group with a discrete group.
Answer: No, the centralizer need not map surjectively onto the component group.
One family of counterexamples is proved by the Lie groups $O(2n) = \{A\in M_{2n}(\mathbb{R}): AA^t = A^tA = I\}$, which has the identity component  $SO(2n) = \{A\in O(2n): \det(A) = 1\}$.
Given any $A\in SO(2n)$ and any eigenvalue $\lambda$ of $A$, $B$ permutes the $\lambda$-eigenspaces of $A$:  if $v$ is an eigenvector of $A$ with eigenvalue $\lambda$, then $$\lambda (Bv) = B\lambda v = BAv = A(Bv).$$
For most $A$, these eigenspaces are $1$-dimensional, which implies that $B$ acts as $\pm 1$ on each one.  Doing this for all $A$ easily implies that every vector is an eigenvector for $B$, so $B = \pm I$.
But since $2n$ is even, $\det(\pm I) = 1$, so this means $B\in SO(2n)$.  That is, $C_{O(2n)}(SO(2n))\subseteq SO(2n)$.
Comment: I don't know of a nice non-trivial class of spaces where the centralizers map surjectively onto the component group.  To my thinking, compact Lie groups are among the nicest topological groups, and counterexamples appear the moment you get more than one component.
Comment: Perhaps "nice" was the wrong word, I was thinking more like "natural". For example, I was thinking something like (non-compact) semisimple, but in any case, I appreciate this clear counterexample.
Comment: @IianSmythe:  I think if you take my example and product it with $\mathbb{R}$, you get a non-compact semi-simple example.  I wasn't try to judge your selection of the word "nice".  Perhaps another way to phrase my comment is that apart from "connected", I don't know of a reasonable adjective to add which guarantees the centralizer maps to onto the component group.


Find a limit of a sequence with series

Question: Find the limit of given sequence, using only the definition and properties of limits of sequences:
$$
x_{n} = \frac{1 + \sqrt{2} + \sqrt[3]{3} + ... +\sqrt[n]{n}}{n}
$$
I've tried to add and substract n to get:
$$
x_{n} = \frac{(1 - 1) + (\sqrt{2} - 1) + (\sqrt[3]{3} - 1) + ... + (\sqrt[n]{n} - 1) + n}{n}  \le 1 - \frac{C(n - 1)}{n}, 0<C\le1
$$
Comment: **Hint:** One can prove that if $x_n\to \ell$, then $\frac{1}{n}\sum_{k=1}^n x_k\to \ell$ when $n\to \infty $.
Comment: You can apply [the arithmetic mean theorem](https://en.wikipedia.org/wiki/Stolz%E2%80%93Ces%C3%A0ro_theorem#Arithmetic_mean) and you get that $$\lim_{n\to\infty}x_n=\lim_{n\to\infty}\sqrt[n]n=1\;.$$
Answer: First off, $\sqrt[k]{k}\geq 1$ for all $k=1,2,...$, so
\begin{align*}
x_{n}\geq\frac{n\cdot 1}{n}=1,\quad n=1,2,...
\end{align*}
On the other hand, since $\sqrt[k]{k}\rightarrow 1$ as $k\rightarrow\infty$, given $\varepsilon>0$, there is an $N\in\mathbb{N}$ such that $\sqrt[k]{k}-1<\varepsilon$, $k\geq N$. Subsequently,
\begin{align*}
x_{n}&=\frac{1+\cdots+\sqrt[N-1]{N-1}}{n}+\frac{\sqrt[N]{N}+\cdots+\sqrt[n]{n}}{n}\\
&\leq\frac{1+\cdots+\sqrt[N-1]{N-1}}{n}+\frac{(n-N+1)}{n}(1+\varepsilon).
\end{align*}
For sufficiently large $n\geq N$, $x_{n}-1<\varepsilon$, so $x_{n}\rightarrow 1$ as $n\rightarrow\infty$.
Comment: Notice that your proof is the same proof of the Arithmetic Mean Theorem.
Comment: Hey I didn't see your link, I wrote by my own, thanks for reminding.

Find a limit of a sequence with series


Sum of all $x$ satisfying $|x-6| = m$ where $m\in\mathbb{R}^+$

Question: I have encountered this question in a book and it had me thinking about a different attempt to solve it, which I think isn't right but can't really comprehend.
Here is the basic way I solve it:
$$x-6 = m \implies x = m+6$$
$$x-6 = -m \implies x = 6-m$$
$$m+6+6-m = 12$$
Answer key also says $12$.
The other way is that we know that $|x-6|>0$ for all $x \in \mathbb{R}$ except for $x = 6$. Since $m>0$, we can say that the solution set of $x$ is $\mathbb{R}-\{6\}$ and therefore sum of all these values equals $-6$. (As far as I know, summing all $\mathbb{R}$ like this isn't valid. However and unfortunately, it's a commonly used way in solutions in this curriculum, so please ignore that part.)
Is the second way right in any sense? If yes or no please explain it because I couldn't come up with a good explanation other than saying $x$ depends on $m$, therefore it is not right.
Is $m$ a variable or a fixed number? I think it must be a fixed number or else we would end up with infinitely many solutions since it would state a function of $x$. Does $m$ being a variable or a fixed number have any impact on the first question?
Thank you in advance.
Comment: " (As far as I know, summing all R like this isn't valid. However and unfortunately, it's a commonly used way in solutions in this curriculum, so please ignore that part.)"  I'm very saddened to hear that.  That way of summing *isn't* valid and it really *shouldn't* be part of the curriculum.  Yes you can argue that for every $w>0$ there is exactly one $-w<0$ and $w+(-2)=0$ so $\sum_{x\in \mathbb R} x = 0$ but we could just as legally argue that for ever $w>0$ there is exactly one $-2w < 0$ so $\sum_{x\in\mathbb r} x = -\sum_{x\in \mathbb R^+} x = -\infty$.
Comment: $m$ is a fixed number, and your first approach, which abandons any attempt at *elegance* is (in my opinion) **definitely** the algorithm to use.  $m$ is a **fixed** but unknown number.  Further, your paragraph which begins "The other way is that we know..." strikes me as close to being gibberish.  In my opinion, the point of the problem is your willingness to dispense with elegance and **get down in the mud**.
Comment: $m \in \mathbb R^+$ but $m$ is not *any* value in $\mathbb R$.  We are presuming there is *one* particular value that we are being asked about.  (We don't know *what* it is but we do know it is something specific).  So the solutions set is *not* $\mathbb R-\{6\}$.  After all.  $9 \in \mathbb R-\{6\}$ but $x =9$ gives us $|x-6|=|3|=3$.  That is only equal to $m$ if $m$ is $3$ but we don't know $m$ is $3$.  And $53\in \mathbb R-\{6\}$ gives us $|53-6|=47$. Well, $3$ and $47$ can't *BOTH* equal $47$.  Also $m+27\in \mathbb R-\{6\}$.  Bute $|(m+27)-6|=m+21 \ne m$ so that is *NOT* a solution.
Answer:
Is $m$ a variable or a fixed number?

It's a fixed number.  And unknown fixed number.

I think it must be a fixed number or else we would end up with infinitely many solutions since it would state a function of x.

It's more that the question just wouldn't make sense.
You'd be expecten so solve for pairs of values of $m$ and for $x$.  And so long as $x = \begin{cases}m+6\\6-m\end{cases}$ then $\{(x,m)| x=m+6$ or $x = 6-m; m > 0\}$ would be the set of all pairs of solution.
But that wasn't what was asked.  You are asked to suppose $m\in \mathbb R^+$ and so solve for $x$ when $|x-6| = m$.  That is... $m$ is fixed.

Does m being a variable or a fixed number have any impact on the first question?

Has every impact.


Finding closest value in another table

Question: I'm quite new to SQL so bare with me. What I'm trying to do is return the value closest to another value in a different table for every record.
I'll show a simplified example of my two tables for clarification
First table is the one that I want the value ENTRY_YEAR matched to:

ID
ENTRY_VALUE

1001
1900

1002
2000

And the second table:

ID
ENTRY_VALUE
STATUS

1001
1880
SUCCES

1001
1930
FAIL

1001
1940
SUCCES

1002
1960
SUCCES

1002
1980
FAIL

So the end result I'm looking for is:

ID
ENTRY_VALUE
STATUS

1001
1880
SUCCES

1002
1980
FAIL

I have currently only managed to link the id's together but can't find a way to compare the ENTRY_VALUE in both tables and return the one closest to the Table1 entry.
So only this:
SELECT * from Table2

INNER JOIN  Table1 ON (Table2.ID = Table1.ID)

Once again my bad for the basic question, I have googled right about everything but can't get it to work so any help is very welcome!
Comment: How are ties resolved if the nearest before and nearest after are the same distance?   (Add details to the question text, not as a comment.)
Answer: First attempt
This is a (slower performing) query. First attempt! This is an approach using a "correlated subquery" so it runs the inner query for each row of the outer query. The strategy is, for each row, to determine what the min value is we are looking for, and then select only the rows that fit that criteria. But such queries can be slow at runtime, although the logic is very clean.
select
    a.id,
    b.entry_value,
    b.[status]
from
    Foo a
    inner join Bar b
    on a.id = b.id
where
    abs(a.entry_value - b.entry_value) =
        (select min(abs(t1.entry_value-t2.entry_value))
            from Foo t1
            inner join Bar t2
            on t1.id = t2.id
            where
                t1.id = a.id
            group by t1.id)

Second attempt
If you have many rows (in the tens of thousands or in any case if the previous query is just too slow), then this next one should be better performing. Second Attempt! If you run the two inner queries by themselves, you will probably see the strategy here of how we are joining them to get the desired result.
select A.Id, A.entry_value, A.[status]
from
    (
    select t1.id, t2.entry_value, abs(t1.entry_value-t2.entry_value) as diff, t2.[status]
    from Foo t1
    inner join Bar t2
    on t1.id = t2.id
    ) A
    inner join
    (
    select t3.id, min(abs(t3.entry_value-t4.entry_value)) as diff
    from Foo t3
    inner join Bar t4
    on t3.id = t4.id
    group by t3.id
    ) B
    on A.id = B.id
    and A.diff = B.diff

Note
I would probably not try to write either of these queries in MSAccess "Design view" although if I had too I am sure I could. But generally, this is a case where I would write the query "by hand" and paste it into your query directly using MSAccess "SQL view".
Caution
Beware that ties will result in two rows! Example:
First table has (1003,2000)
Second table has (1003, 1990, 'success') and (1003, 2010, 'fail')
You will have a result with two rows, one with success and the other with fail (!)
So you really should test with your data and look for such cases that might produce such ties (and decide what to do, if necessary).
Btw...
just for fun, here's how you might go for it in SQL Server.
But I think this will NOT work in MSAccess, unfortunately.
select
    T.id,
    T.entry_value,
    T.[status]
from
(
    select
        t1.id,
        t2.entry_value,
        abs(t1.entry_value-t2.entry_value) as diff,
        t2.[status],
        rank() over (partition by t1.id order by abs(t1.entry_value-t2.entry_value)) as seq
        from #Foo t1
        inner join #Bar t2
        on t1.id = t2.id
) T
where T.seq = 1;

Comment: I don't think you're handling breaking  ties
Answer: Use a simple subquery to find the minimum offset:
Select
    tbl1.ID,
    tbl2.ENTRY_VALUE,
    tbl2.STATUS
From
    tbl1
Inner Join
    tbl2 On tbl1.ID = tbl2.ID
Where
    Abs([tbl1].[ENTRY_VALUE] - [tbl2].[ENTRY_VALUE]) =
        (Select Min(Abs([tbl1].[ENTRY_VALUE] - [T2].[ENTRY_VALUE])) As Offset
        From tbl2 As T2
        Where T2.ID = tbl1.ID);

Output:

ID
ENTRY_VALUE
STATUS

1001
1880
SUCCES

1002
1980
FAIL

Note, that if the minimum offset for an ID exists twice, both records having this offset will be returned. Thus, you may have to aggregate the output.
Comment: This ended up being the easy solution! Thanks a lot

Finding closest value in another table


Assigning weightages to variables

Question: I have three variables which impact my output, however, I want to statistically establish weightage of each variable in determining/influencing the output. I have significant data points for the three variables that can be plotted.
Output = x* V1 + y* V2 + z* V3. Here, I want to determine x, y and z.
Can you suggest what approach should be adopted here?
Comment: Are you looking for linear regression?
Answer: First, the usual way to write this is $Y = b_0 + b_1X_1 + b_2X_2 + b_3X_3$
Second, it seems clear you want some form of regression. Which form will depend, primarily, on the nature of the output variable Y and the nature of the data. Re Y:  Is it continuous? Is it dichotomous? Is it ordinal?
If it is continuous, the usual starting place would be multiple linear regression; you would then have to check the assumptions.
Re The data: The main question is whether it is independent.

Assigning weightages to variables


Marginal pdf for $X$ given the simultaneous pdf for $(X,Y)$ (hard)

Question: PDF for $(X,Y)$ is given by
$$ f(x, y)=\left\{\begin{array}{cl}
\frac{4 y^{3}}{x^{3}} & \text { for } 0<y<1, y<x \\
0 & \text { else }
\end{array}\right.$$
By drawing the support of $(X,Y)$ I can see that I have to construct $g(x)$ piecewise as follows:
For $x \in (0,1]$ I have $g(x)=\int_0^x4x^{-3}y^3dy=x$.
For $x \in [1,\infty)$ I have $g(x)=\int_0^1 4x^{-3}y^3dy=x^{-3}$.
For $x \not \in (0,\infty)$ I have $f(x,y)=0$, and therefore $g(x)=0$.
So $g(x)$ written as a piecewise function
$$ g(x)=\left\{\begin{array}{ll}
x & ,  x \in (0,1] \\
x^{-3} & , x \in [1, \infty) \\
0 & , x \not \in (0, \infty )
\end{array}\right.$$
Can someone confirm that the method and result are correct? It will be nice to know :-)
Answer: It is fine. The marginal pdf is simply
\begin{align}
f_X(x)&=\int_0^{\min(x,1)}\frac{4y^3}{x^3}\,dy\,1_{(0,\infty)}(x)
\\&=\frac{(\min(x,1))^4}{x^3}1_{(0,\infty)}(x)
\\&=x1_{(0,1)}(x)+\frac1{x^3}1_{(1,\infty)}(x)
\end{align}
Here $1_A(x)$ equals for $1$ if $x\in A$ and equals $0$ if $x\notin A$.


TypeError: contacts.map is not a function

Question: Olá, pesquisei sobre o assunto e vi que pode ser erro que pode ser por conta de não estar recebendo um array. Porém, coloquei pra ser retornado um array na API, pode ser consultado aqui
https://agendaapplp3.herokuapp.com/contatos
só que na parte do react aparece esse erro, "TypeError: contacts.map is not a function".
segue o código:
   const ListContacts: React.FC = () => {

   const [contacts, setContacts] = useState <ContactsProps[]>([]);

   async function getContacts(){
       const response = await api.get<ContactsProps[]>("/contatos");
      setContacts(response.data);
   }
   useEffect(()=>{
       getContacts();
   },[]);

o erro está nessa parte abaixo.
{contacts.map((contact)=>(

                                    {contact.id}
                                    {contact.nome}
                                    {contact.email}
                                    {contact.telefone}
                                    {contact.idlocal}
                                    {contact.idtipocontato}

para se conectar a api, utilizei o axios
    import axios from "axios";

    const api = axios.create({
     baseURL:"https://agendaapplp3.herokuapp.com"
    })

    export default api;

sou novo em React, o que pode ser?
Comment: Voce nao deveria colocar no seu `setContacts` como `response.data.results`? pois ai sim seu `results` e um array.
Comment: coloquei e me apareceu isso Property 'results' does not exist on type 'ContactsProps[]'.  TS2339
Se adianta de algo, meu ContactsProps[] está assim:
interface ContactsProps{
    id:number;
    nome:string;
    email:string;
    telefone:string;
    idlocal:number;
    idtipocontato:number;

}
Answer: Resolvi seu problema, eu acho, colocando uma interface para o Response, e no setContacts colocamos response.data.results. Desta forma:

interface ContactsProps {
  id: number;
  nome: string;
  email: string;
  telefone: string;
  idlocal: number;
  idtipocontato: number;
}

interface Response { // Uma interface para o Response.
  data: {
    results: [];
  };
}

const api = axios.create({
  baseURL: 'https://agendaapplp3.herokuapp.com',
});

const ListContacts: React.FC = () => {
  const [contacts, setContacts] = useState<ContactsProps[]>([]);

  async function getContacts() {
    const response: Response = await api.get('/contatos'); // informamos ao TS que a resposta tera o formado do Response.

    setContacts(response.data.results); // set dos arrays para o contacts
  }
  useEffect(() => {
    getContacts();
  }, []);

  return (
    <>

      {contacts &&
        contacts.map((contact: ContactsProps) => (

            {contact.id}
            {contact.nome}
            {contact.email}
            {contact.telefone}
            {contact.idlocal}
            {contact.idtipocontato}

        ))}

    </>
  );
};

export default ListContacts;

Tente fazer os testes. Espero ter ajudado.
Comment: Caraca, resolveu mesmo, muito obrigado!
Mas poderia explicar? Como disse estou começando em react e por que do jeito que fiz estava errado?
Comment: nesse seu comentario anterior: `coloquei e me apareceu isso Property 'results' does not exist on type 'ContactsProps[]'. TS2339`, voce tentou atribuir a interface `ContactsProps` ao `response`?. Essa interface do `Response` nem era necessario, eu so coloque ela quando estava testando seu codigo e quando executei de primeira, funcionou. Mas explicando de uma maneira simples, a interface server pra voce `explicar` pro TS como vai ser a estrutura de um determinado objeto. Entao eu falei pro TS que o `response` teria a propriedade `data` e dentro de data teriamos o `results` do tipo array.
Comment: Entendi,  obrigado!


Select2 + Jquery - Problema no Autocomplete

Question: Consegui fazer o PlUGIN Select2 funcionar, porém o autocomplete não funciona.
<code>$(function () {

    $("#disciplina").select2({
        placeholder: "Disciplina",
        minimumInputLength: 0,
        ajax:{
            url: "busca.asp",
            type: "post",
            dataType: "json",
            delay: 150,
            data: function(params){
                return{
                    text: params.term
                };
            },
            processResults: function(data, params){
                params.page = params.page || 1;
                return{

                    results: data,
                    pagination:{
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
            cache: true
        }
    });

});
</code>

Alguém já passou por isso?
O retorno com console.log(data);

console.log(params);
Comment: Pode fazer um dump da informação que está receber do servidor (console.log)
Comment: @JorgeCosta já tentei colocar o console no retorno do ajax, mas a função deixa de funcionar. return{
      console.log(params.term);
                        text: params.term
                    };
Comment: cara, to umas 3 semanas nisso de popular um select, tá muito dificil. Cheguei perto agora, mas tô esbarrando nisso.
Comment: Faz console.log(data) antes do return, se estiver a usar o Chrome veja no inspector
Comment: @JorgeCosta fiz no processResults e deu certo, vou postar na pergunta a imagem do retorno.
Comment: Publiquei uma resposta essencialmente é da sua responsabilidade filtrar os dados do lado servidor quando usa ajax
Answer: Problema
Os dados não são estão a ser filtrados quando é digitada uma chave de pesquisa.
Segundo a documentação no site do plugin: https://select2.org/data-sources/ajax

Select2 expects results from the remote endpoint to be filtered on the
  server side.

Tradução
O Select2 espera que resultados devolvidos pelo endpoint remoto  definido sejam filtrados do lado do servidor.
Exemplo
Neste exemplo data é uma função permite personalizar o url da pesquisa, do lado servidor esses parâmetros devem ser utilizados para filtrar a lista devolvida.

Query parameters will be ?search=[term]&type=public

<code>$('#mySelect2').select2({
  ajax: {
    url: 'https://api.github.com/orgs/select2/repos',
    data: function (params) {
      var query = {
        search: params.term,
        type: 'public'
      }

      // Query parameters will be ?search=[term]&type=public
      return query;
    }
  }
});
</code>
Comment: Muito obrigado, mas tô desistindo, não tenho a minima ideia de como fazer isso. Cansado já. Valeu pela atenção.
Comment: Por favor coloque a minha resposta como certa, vou lhe indicar outro plugin  a ver em https://pt.stackoverflow.com/questions/316058/bootstrap-3-typeahead-listar-opções-com-base-em-pesquisa-exibindo-outro-campo
Comment: Eu vi la, mas não atende o que quero. É um autocomplete somente, o select2 é um select dinâmico.
Comment: creio que eu esteja muito perto da solução.
Comment: Não percebo porque não marcou a resposta como correcta, ela responde correctamente ao seu problema, o plugin que recomendei é efectivamente dinâmico, pode alterar o datasource enquanto altera a chave pesquisa
Comment: Ele não lista todas as opções e não se parece com um select, mas para outras situações é bem útil, mas não me atende.
Comment: o que quero é isso https://www.aprovaconcursos.com.br/questoes-de-concurso/questoes/instituicao/ENEM/filtro/auto


Does service module expect Base64 encoding for file uploads through http-post (drupal 7)?

Question: I have been having trouble getting a file to upload through http-post from my lisp application and I have noticed in all of the curl php examples I have found they have a like this:
<code>$file = array(
  'filesize' => filesize($filename),
  'filename' => basename($filename),
  'file' => base64_encode(file_get_contents($filename)),
  'uid' => $logged_user->user->uid,
);
</code>
which includes the call to base64_encode, I am not doing this from my lisp application and I always get a response of 200 but the file is not uploaded.  I am using Services 3.x and a RESt server.
Does Services require that file uploads are base64 encoded?
Answer: Short answer yes it does. There is a create raw method but unfortunately, it doesn't work very well b/c drupal 7s file handling is a joke.
Ive created a patch that will allow you to attach files to  a node and it uses multipart form, but its a work in progress.
http://drupal.org/node/1484992
Comment: Okay that's very good to know, thank you so much.  Also, would rest/file accept a multipart/form-data request normally?  All the curl examples use application/x-www-form-urlencoded which seems wrong for uploading files.  Is this due to the limitations of drupal you mentioned?
Comment: It supports multipart, but I'm not 100% sure for which  methods, if its only certain ones, or it is all. Examples are usually done in curl because you can do curl in almost every major web aware language. Either way, if this is the answer you were looking for, please mark it as the answer :P
Comment: Compared to all the previous versions, D7's file handling is amazing ;)


How can I pool posterior means and credible intervals after multiple imputation?

Question: I have used multiple imputation to obtain a number of completed datasets.
I have used Bayesian methods on each of the completed datasets to obtain posterior distributions for a parameter (a random effect).
How can I combine / pool the results for this parameter ?

More context:
My model is hierarchical in the sense of individual pupils (one observation per pupil) clustered in schools. I have done multiple imputations (using MICEin R) on my data where I included school as one of the predictors for the missing data - to try to incorporate the data hierarchy into the imputations.
I have fitted a simple random slope model to each of the completed datasets (using MCMCglmm in R). The outcome is binary.
I have found that the posterior densities of the random slope variance are "well behaved" in the sense that they look something like this:

How can I combine/pool the posterior means and credible intervals from each imputed dataset, for this random effect ?

Update1:
From what I understand so far, I could apply Rubin's rules to the posterior mean, to give a multiply imputed posterior mean - are there any problems with doing this ?
But I have no idea how I can combine the 95% credible intervals.
Also, since I have an actual posterior density sample for each imputation - could I somehow combine these ?

Update2:
As per @cyan's suggestion in the comments, I very much like the idea of simply combining the samples from the posterior distributions obtained from each complete dataset from multiple imputation. However, I should like to know the theoretical justification for doing this.
Comment: If the missingness of any given datum is independent of associated outcome value, it's correct to just throw all the posterior samples from the different imputed data sets together and take the mean and 95% credible intervals of the combined posterior samples.
Comment: @Cyan is that the same as saying that the missingness mechanism is either "missing at random" or "missing completely at random" but not "missing not at random" (the usual assumptions I learned about for performing MI)? Do you know any reference where this "throwing together" is justified formally ?
Comment: Multiple imputation IS a Bayesian procedure at its heart. If you use Bayesian methods for estimation (MCMC and such), you should just throw simluation of the missing data as an additional MCMC sampling step for a fully Bayesian model, and won't bother trying to come up with an interface between these approaches.
Comment: @StasK thank you for your comment. I will try to use that approach on my next project but unfortunately I don't have time to change the model now. I already ran the imputations and the Bayesian model on each imputed dataset - it took nearly 3 weeks to run. Do you think it is invalid for me to combine the posterior samples ?
Comment: Rubin's rules apply to moments only. I don't know if you can apply them to a distribution in a meaningful way. May be, may be not. It may well be that the best you can do is to say that the MCMC run produced the point estimates (posterior means) and standard errors (posterior variances), and then use Rubin's rules to get the overall point and variance estimates. You know how tragic the losses of d.f.s in hierarchical model can be, and how dangerous it is to pool the data: if you have 5 imputed complete data sets and 1M MCMC samples on each, it means you have 5 clusters, not 5M iid MCMC points.
Comment: @Joe King, I'm pretty sure the condition I described is one of either "missing at random" or "missing completely at random". My copy of Bayesian Data Analysis seems to have gone walkabout so I can't be sure. If I can find it, I'll check to make sure and report in.
Comment: @JoeKing did you ever find a solution?
Answer: With particularly well-behaved posteriors that can be adequately described by a parametric description of a distribution, you might be able to simply take the mean and variance that best describes your posterior and go from there. I suspect this may be adequate in many circumstances where you aren't getting genuinely odd posterior distributions.
Answer: Yes, based on the paper by Zhou et al , you can simply combine the MCMC draws from each imputed dataset and combine them together to approximate the posterior distribution. However, based on their simulations (as noted in the paper), this approach requires a large number of imputed datasets (e.g., 100).
Answer: If you use stata there is a procedure called "mim" that pooled the data after imputation using for mixed effect models.  I don't know if it is available in R.
Comment: Thank you. I may not have explained well - I have posterior samples already, from several imputed datasets, and I want to know if I can simply combine these and then form a multiply imputed credible interval ?


Alterar link da imagem dinamicamente dentro do

Question: Bom dia, amigos, pergunta de iniciante.
Tenho uma consulta que mostra numa tabela todos os registros do meu BD. Porém como são muitas colunas, limitei a exibir os nomes, data de nascimento alguns poucos dados. E criei uma última coluna com o link "dados completos" que ao ser clicado vai mostrar em outra janela todos os dados daquele registro. Esse é o código:
Dados Completos
Assim, a página abre com os dados completos daquele registro.
Meu problema é com a imagem. Quero exibir a foto do que está salva na pasta "img". O nome da imagem é o código do registro. Tentei assim:
<?php

include("classe/conecta.php");
$codigo = $_GET['codigo'];
$consulta = "SELECT * FROM CadPessoas WHERE Cod='$codigo'";
$con = $mysqli->query($consulta) or die($mysqli->error);
?>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

           <?php
           while($dado = $con->fetch_array()){ ?>

Mas não funcionou. Alguém pode me ajudar com essa última linha do meu código? Obrigado
Answer: <?php
   include("classe/conecta.php");
   $codigo = $_GET['codigo'];
   $consulta = "SELECT * FROM CadPessoas WHERE Cod='$codigo'";
   $con = $mysqli->query($consulta) or die($mysqli->error);
   ?>

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

      <?php
         while($dado = $con->fetch_array())
         {
            ?>
            <img src="img/<?=$dado['codigo'];?>.jpg"> //short hand do php
            <?
         }?>


Question on this study's design

Question: I am struggling to convince myself that my answer to this question for my stats assignment is correct as the way the question was asked is making me doubt my own answer. In brief, we have a supposed n=8 number of babies, where the study is interested in observing the weight growth (in ounces) of these babies over the span on 4 days.
In perspective, the sample table for the data is:-
Baby: Day1,      Day2,      Day3,      Day4

116,       116,       117,       118
91,        92,        93,        95
125,      127,        127,       128

.....

89, 90, 91, 93

The question I'm having issues with is:-
1) 'What is the design of the study? What are the fixed factors and random factors?'
This looks to me like a one-way repeated measures ANOVA is applicable. The day groupings are definitely the fixed factor here. What I am confused about, is that this study is not quite interested in the between subjects interaction but rather, the within subjects growth rate. As such, even though the random assignment of 8 babies seem like a random factor, it isn't relevant in a one-way repeated measure ANOVA, is it? (Ie. why would the question ask for multiple factors when this is a one-way design? Or can you actually have more than one random/fixed factor even though it is one-way? Or.. is this actually a 2-way mixed design?)
Answer: I would analyze this dataset with a random intercept ($b_0$) and a random slope ($b_1$) for time for every baby, together with a fixed intercept ($\beta_0$) and slope ($\beta_1$) for time as follows:
$$E(W_{ij}) = \beta_0 + \beta_1t_i + b_{0j} + b_{1j}t_i$$
with $t_i$ the time indicator of day $i$, $W_{ij}$ the weight of baby $j$ at time $i$. Hereby $b_0 \sim N(0, \sigma^2_0)$ and $b_1 \sim N(0, \sigma^2_1)$. The day groupings have thus a fixed effect and a random effect part. The variance of the random slopes $\sigma^2_1$ represents the within-subjects variability in growth rates. I would agree that this is indeed a mixed design.

Question on this study's design


translate(localize) specific title of web form use preprocess func

Question: I have specific webform call careers , i have use webform localization model but the model does not translate the node title , some one told me to use  preprocess node func. but i did not now how to create theme i try to write some thing like this

function [themeName]_preprocess_page(&$variables) {
  if($node['id'] == 6) {
  $node['title'] = t($node['title']);
    }

But it does not work
Answer: The code doesn't work because the function receives only a parameter, and that is not $node. The correct code should eventually be the following one.
function mymodule_preprocess_page(&$variables) {
  if(!empty($variables['node']) && $variables['node']->nid == 6) {
    $variables['title'] = t($variables['title']);
  }
}

I am assuming you want to change the title when the node ID is equal to 6.


How To Redirect to a Named Node upon Registration

Question: Given a D6 site where users must confirm their email address, I would like new registrants to be immediately redirected to a Page node which explains the email verification process.
I attempted to do this using Actions and Triggers, but "Trigger: After a user account has been created" executes before the activation email is sent and so the message is blocked and never gets out. This appears to be an unresolved issue tracing as far back as D5.
The Login Destination module is listed as supporting this feature for D7.x but not 6.x.
Answer: You can use the Rules Module to redirect a user after an account is created.

Simply add a new rule for the event "User account has been created"
Add an action of "Page redirect"
Fill in the information for the page you want to redirect the user to.

Make sure that "Immediately issue the page redirect" is not checked or else the same thing will happen and the email will not get sent.
Comment: Thanks! The Rules module is great and I foresee using it a lot int he future.
Answer: Another good solution would be to use LoginToboggan


Como fazer um dropdown autocompletar campo em Loop

Question: Como não tenho muito conhecimento de javascript Preciso de uma ajuda nesse meu problema aqui... Neste e formulário preciso que ao escolher um item no dropdown ele preencha o campo ao lado com o valor contido no seu value

Clonar

<form id="form1" name="form1" action="src/acao/cli.php" method="POST" enctype = "multipart/form-data" >

</form>

No dropdown desse formulario temos os seguintes dados no de entrada
<option value="Vilamar-10,00">Vilamar</option>

Preciso que ao escolher um item nesse dropdown ele autocomplete no campo name="valor" esse valore que vem após o nome do item
Answer: Segue solução encontrada. Utilizei do evento change para capturar o valor no momento que o usuário escolhe uma opção no select. Quebro o value do select em 2 partes[Nome-Valor], e pego somente a parte referente ao valor, adicionando ao input ao lado.

(function ($) {
        $('#destino_in').on('change', function () {
            var $self = $(this);

            $('#destino_out').val($self.val());
        });
        }(jQuery));

        $(function () {
        var divContent = $('#materialInst');
        var botaoAdicionar = $('a[data-id="1"]');
        var i = 1;
        // VARIAVEL ADD
        var destino;

        //Ao clicar em adicionar ele cria uma linha com novos campos
        $(botaoAdicionar).click(function () {
            $('

'+
            '<input type="text" name="estado" size="5" class="form-control" value="" />'+
            '<select name="destino_in_' + i + '" id="destino_in_' + i + '" class="form-control">'+
                '<option value="" selected disabled>Selecione...</option>'+
                '<option value="Vilamar-10,00">Vilamar</option>'+
                '<option value="Savoy-20,00">Savoy</option>'+
            '</select>'+
            '<input type="text" placeholder="Valor" name"valor_' + i + '" id="valor_' + i + '" class="form-control" />'+
            '<input type="text" size="5" name="numero" class="form-control" value="" />'+
            'Remover

').appendTo(divContent);

            $('#removehidden').remove();
            i++;
            $('<input type="hidden" name="quantidadeCampos" value="' + i + '" id="removehidden">').appendTo(divContent);

            // ADD AQUI

            // Aqui acontece a inserção dos valores no outro input
            // capturo todos os selects existentes
            destinos = document.querySelectorAll('select');
            // percorro todos pelo for
            for(var j = 0; j < destinos.length; j++) {
                // verifico no evento de change
                $(destinos[j]).on('change', function(){
                    // quando ocorrer, capturo o valor selecionado
                    var selected = $(this).val();
                    // divido a string em 2, separada pelo (-) [nome(-)valor]
                    var res = selected.split("-", 2);

                    // res[0] = "Vilamar";
                    // res[1] = "10,00";

                    // captura o id atual
                    var idAtual = $(this).attr('id');
                    // divide a string em 3, separada pelo (_) [destino(_)in(_)id]
                    var idFinal = idAtual.split("_", 3);
                    // idFinal[0] = "destino";
                    // idFinal[1] = "in";
                    // idFinal[1] = "{$id}";

                    // adiciono no input #valor o resultado do array na posição 1 no id capturado anteriormente na posição 2
                    $('#valor_' + idFinal[2]).val(res[1]);
                });
            }
            // FIM ADD
        });

        //Cliquando em remover a linha é eliminada
        $('#materialInst').on('click', '.linkRemover', function () {
            $(this).parents('.conteudoIndividual').remove();
            i--;
        });
    });

  Clonar
  <form id="form1" name="form1" action="src/acao/cli.php" method="POST" enctype = "multipart/form-data" >
  </form>

Comment: Quase perfeito meu amigo... só que se clonarmos mais vezes ele para de funcionar
Comment: @FabioHenrique atualizei o código, como solicitado. Da uma olhada ai.


undefined reference to `vtable for MyCalss'

Question: I've created new project with QTCreator using Empty Qt Project
MocTest.pro
QT += core
QT -= gui

TARGET = MocTest
CONFIG   += console

TEMPLATE = app

SOURCES += \
    main.cpp

main.cpp
#include <QCoreApplication>
#include <iostream>

class A : public QObject
{
    Q_OBJECT

public:
    A() {}

public slots:
    void slotA() {std::cout<<"Hi!";}
};

class B : public QObject
{
    Q_OBJECT

public:
    B () {}

    void doB() {emit ss();}

signals:
    void ss();
};

int main(int argc, char *argv[])
{
    QCoreApplication app (argc, argv);
    A a;
    B b;
    return app.exec();
}

I got errors
D:\Test\MocTest\debug\main.o:-1: In function `ZN1AC1Ev':
D:\Test\MocTest\main.cpp:9: error: undefined reference to `vtable for A'
D:\Test\MocTest\main.cpp:20: error: undefined reference to `vtable for B'
D:\Test\MocTest\main.cpp:4: error: undefined reference to `vtable for A'
D:\Test\MocTest\main.cpp:15: error: undefined reference to `vtable for B'
collect2.exe:-1: error: error: ld returned 1 exit status
Answer: Qmake ensures Moc is run on:

Files listed in the HEADERS variable. Qmake arranges to compile and link the resulting C++ implementation file by adding it to SOURCES.
Files listed in the SOURCES or OBJECTIVE_SOURCES variables are processed by moc. Qmake does not link any potential output, so the resulting moc output must be #included.

Looks like you need to put this:
#include "main.moc"

somewhere at main.cpp (probably at the end).
Details here: https://qt-project.org/forums/viewthread/21420
Answer: vtable references are generated by moc for class heriting QObject.
These are generated with files from HEADERS variable.
Then you have to separate headers and implementations. This would gives:
myclass.h
class A : public QObject
{
    Q_OBJECT

public:
    A();
public slots:
    void slotA();
};

class B : public QObject
{
    Q_OBJECT

public:
    B();
    void doB();
signals:
    void ss();
};

and myclass.cpp
#include "myclass.h"

A::A()
{}
void A::slotA()
{ std::coud << "Hi!; }

B::B()
{}
void B::doB
{ emit ss(); }

Also then TestMoc.pro
QT = core # default is QT = core gui, so -= gui is enough or just =core
HEADERS = myclass.h
SOURCES = myclass.cpp main.cpp

Keep in mind that it generally a bad idea to call signals in inline methods.
Also if you call doB in your main, before the app.exec(), it might not be handle because signals/slots are managed once the event-loop is run
Comment: What is that `vtable`?


What is a non-informative choice of parameters for a Dirichlet distribution?

Question: Dirichlet distribution is a conjugate prior for multinomial distribution. I want to impose a non-informative prior over sampling weights $\pi$ for a draw $x=(x_1,…,x_N)$ from a multinomial distribution with support $d=(d_1,…,d_K)$ (all the possible values that $x_i$ can take) and sampling weights $\pi=(\pi_1,…,\pi_K)$.
I was under impression that $Dir(\alpha)$ with $\alpha_i=1$ is a right choice. But I've read that (see e.g. this) $Dir(\alpha)$ with $\alpha_i=0$ yields an improper non-informative distribution.
Question:

Why $Dir(\alpha)$ with $\alpha_i=0$ is non-informative? Doesn't $\alpha\to 0$ impose higher sampling weight on a single data and zero on all others?
Shouldn't a uniform distribution $Dir(\alpha)$ with $\alpha_i=1$ be non-informative choice for the prior instead?
Answer: The main issue here is that "non-informative" is something of a term of art, and it can be formulated in various ways (see here for an interesting discussion on the subject).  In a certain strict sense, there is no such thing as a "non-informative prior" since every prior distribution is a specific distribution that has a number of specific probabilistic implications.  What we do have are several different methodologies that can form non-subjective priors (i.e., priors that depend only on the general form of the likelihood function without consideration of the data values).
There are several competing theories on formulating non-subjective priors.  This includes the theory of "reference priors", the Jeffries priors, and various others.  These theories lead to prior forms that are quite close to each other, but they do differ a little bit, and so there is also quite a bit of literature arguing over which is best.  If you would like to learn more about this, I strongly recommend you read some of the works of José Bernardo, who is probably the preeminent Bayesian statistician in this field.  (Another thing I would recommend is to read about the theory of "imprecise probability" by Peter Walley; in my view this method has a better claim to being truly objective and "non-informative" than choosing a specific prior via other theories.)
In regard to your specific questions, yes, the $\text{Dirichlet}(\mathbf{0})$ distribution is an improper distribution, so if you use it as a prior then it is an improper prior.  As to whether this prior is better or worse than the flat prior, I will leave it to you to have a read of the literature on improper priors and see the advantages of each method.  It is worth noting that they are not very different so long as you have a reasonable amount of data --- data manifests in the posterior as an increase of one in a parameter value for each observed data point.  Bayesian analysis has a number of useful consistency theorems that establish that posterior beliefs converge even with different priors, and for priors like this, that are only slightly different, this convergence is quite rapid.
Answer: I was inclined to agree with you, because I know rstan uses αi=1 as the default Dirichlet prior choice. Their default choices are intended to be weakly informative. But I found this paper discussing why Dir(0) is a valid choice. I don't understand it well enough to give a good summary, but it looks like Dir(0) is the only choice which is noninformative under transformations that preserve normality.


Como usar cookies em javascript

Question: Sei criar cookies em JavaScript, mas não sei como aplicar eles em algum projeto. Alguém poderia postar um exemplo de como usar cookies?
Comment: Dá uma olhada no link https://pt.stackoverflow.com/questions/217192/javascript-redirecionar-e-setar-cookies me ajudou bastante.
Answer: Como respondi em Gravar cookie e ler seu valor ao aceder ao web site para verificar se expirado
Você deve usar document.cookie para criar os cookies conforme a necessidade e o script deve rodar em um servidor (como Apache por exemplo), acesso local (protocolo file://) geralmente não funciona com cookies.

note que alguns navegadores bloqueiam cookies gerados pelo http://localhost, para contornar o problema use o endereço http://127.0.0.1

Para criar um cookie devemos usar os parâmetros suportados são:

;path= deve conter o caminho/path HTTP que poderá ser usado para limitar aonde o cookie deve ser acessível
;expires= deve conter data em formato GMT de quando vai expirar
;max-age= deve conter conter o tempo em segundos de quando o cookie deve expirar, não é necessário usar max-age e expires ao mesmo tempo
;secure especifica que o cookie só deve funcionar sobre o protocolo HTTPS

O nome do cookie (chave) e o valor podem ser codificados com encodeURIComponent para evitar que caracteres como espaços ou ; façam os dados se perderem.
Exemplo de com como criar um cookie:
document.cookie="<chave>=<valor>; expires=<data para expirar>; path=<caminho HTTP>";

Um exemplo de cookie que deve expirar em 31/12/2018 as 23:59:59 (em GMT):
document.cookie="chave=valor; expires=Mon, 31 Dec 2018 23:59:59 GMT;path=/"

Note que talvez ao invés de cookies você pode usar localStorage e sessionStorage (https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage)
Por exemplo com sessionStorage:
// Salva dados
sessionStorage.setItem("foo", "bar");

// Pega os dados
alert( "foo = " + sessionStorage.getItem("foo"));

Por exemplo com localStorage:
// Salva dados
localStorage.setItem("baz", "bar");

// Pega os dados
alert( "foo = " + localStorage.getItem("baz"));

A diferença entre sessionStorage e localStorage é que o primeiro expira sempre que o navegador é fechado, o segundo se mantém

Nota: se quiser usar localStorage com tempo para expirar veja esta outra resposta que criei Como fazer para que o Local Storage expire?

Mas como a questão sobre cookies, irei mostrar um exemplo com tal, então criei as seguintes funções:
function getCookie(k) {
    var cookies = " " + document.cookie;
    var key = " " + k + "=";
    var start = cookies.indexOf(key);

    if (start === -1) return null;

    var pos = start + key.length;
    var last = cookies.indexOf(";", pos);

    if (last !== -1) return cookies.substring(pos, last);

    return cookies.substring(pos);
}

function setCookie(k, v, expira, path) {
    if (!path) path = "/";

    var d = new Date();
    d.setTime(d.getTime() + (expira * 1000));

    document.cookie = encodeURIComponent(k) + "=" + encodeURIComponent(v) + "; expires=" + d.toUTCString() + "; path=" + path;
}

Para definir o seu cookie de ID, faça isto:
setCookie("chave", "valor");

Para ler o cookie que chamamos de chave faça assim:
var resultado = getCookie("chave");
console.log(resultado); //Exibe o resultado ou exibe null se tiver expirado ou não for acessível a partir do PATH da URL atual

Para definir um tempo para expirar o cookie faça assim:
setCookie("foo", "baz", 3600);//Expira o cookie "foo" em uma hora

Para restringir o cookie somente a certas caminhos HTTP (rotas) use assim:
setCookie("bar", "baz", false, "/pasta2/");//o cookie só estara acessível em urls como http://site/pasta2/*

Se quiser definir um tempo para expirar em um PATH especifico use assim:
setCookie("bar", "baz", 86400, "/pasta3/");//o cookie só estará acessível em urls como http://site/pasta3/* e irá expirar em 24 horas

Como usar cookies em javascript


Visual Code constantly changes included files in tsconfig.json

Question: Since a few versions, Visual Code constantly messes up my tsconfig.json by adding individual files to the include array when I add or rename files in my project.
Is there any setting to tell VC to NOT do that?
Answer: The TypeScript extension has a setting that updates imports on file move, this might be the culprit.

Typescript › Update Imports On File Move: Enabled
Enable/disable automatic updating of import paths when you rename or move a file in VS Code. Requires using TypeScript 2.9 or newer in the workspace.

Setting typescript.updateImportsOnFileMove.enabled to never will stop it from adding the files to include. You can also set it to prompt if you want to be asked.
Comment: @JerryGreen Setting it to `never` will make it work. I've updated the answer to reflect the changes in this setting.
Comment: Important to note that the question is about preventing VS Code from updating tsconfig.json specifically, and while this answer does do that, it also disables _all_ automatic updates, including updating imports in other .ts source files.


Do you know an FOSS alternative to EtherPad or a similar service with > 8 user limit?

Question: I'm at a summer program where about 30 students are taking collaborative notes during presentations. EtherPad works great for this but it has a limit of 8 users.
Do you know any alternatives?
Google Docs is not very robust for this kind of use (if you have used it before with more than 1 person you probably know).
Comment: I ended up contacting the etherpad people and they let us use a beta version of their product that allows more than 8 people. I highly recommend etherpad.
Answer: EtherPad has now gone open source. You can get the source for it and install it on your own server now.
Answer: If you don't mind using a desktop application there are alternatives like Gobby.
EDIT: Here is a list.  While not FOSS, Adobe Buzzword looks promising.
Answer: http://collabedit.com


systemd-resolve resolves incorrectly inside a network namespace

Question: I have an Ubuntu machine with a network namespace (ns1) connected to the host network namespace via veth. I created a MASQUERADE rule in iptables to access the internet and I can ping 18.104.22.168 from the network namespace.
When I do dig google.com from the host, it works and I see in the main interface:
08:03:02.376478 IP 10.0.10.40.51566 > 10.0.10.2.53: 48449+ [1au] A? google.com. (39)
08:03:02.378335 IP 10.0.10.2.53 > 10.0.10.40.51566: 48449 1/0/1 A 126.96.36.199 (55)

However, when I execute dig in the network namespace: sudo ip netns ns1 dig google.com, it does not work and this is what I see in the main interface of the host:
08:03:09.033958 IP 10.0.10.40.50888 > 10.0.10.2.53: 32798+ [1au] A? ip-10-0-10-40.eu-west-3.compute.internal. (69)
08:03:09.034152 IP 10.0.10.40.36297 > 10.0.10.2.53: 43961+ [1au] AAAA? ip-10-0-10-40.eu-west-3.compute.internal. (69)
08:03:09.034460 IP 10.0.10.2.53 > 10.0.10.40.50888: 32798 NXDomain 0/1/1 (144)
08:03:09.034460 IP 10.0.10.2.53 > 10.0.10.40.36297: 43961 NXDomain 0/1/1 (144)
08:03:09.034559 IP 10.0.10.40.50888 > 10.0.10.2.53: 32798+ A? ip-10-0-10-40.eu-west-3.compute.internal. (58)
08:03:09.034639 IP 10.0.10.40.36297 > 10.0.10.2.53: 43961+ AAAA? ip-10-0-10-40.eu-west-3.compute.internal. (58)
08:03:09.034837 IP 10.0.10.2.53 > 10.0.10.40.50888: 32798 NXDomain 0/1/0 (133)
08:03:09.034906 IP 10.0.10.2.53 > 10.0.10.40.36297: 43961 NXDomain 0/1/0 (133)

Why the request coming from the network namespace is not trying to resolve hostname google.com but hostname ip-10-0-10-40.eu-west-3.compute.internal? The latter is apparently the hostname of my Ubuntu machine
EDIT
If I stop systemd-resolve and add the upstream nameserver, it works. Therefore, it must be an issue with systemd-resolve
Comment: Use the FQDN `google.com.`. A FQDN always ends with a `.`! Not using a FQDN means you are using a relative domain name, which might be in your case `google.com.yourlocaldomain.`
Comment: Note that it does not look for `google.com.yourlocaldomain`. there is no google at all. I tried with the dot and same result
Comment: Then your DNS server is not resolving recursive. *bind9* DNS server has to be enabled to resolve recursive in its newer versions.
Answer: systemd-resolve will rewrite your DNS to point to it on 127.0.0.53 by default. It isn't reachable in the namespace you created so DNS lookups fail.
Try using dig google.com. @18.104.22.168 and it should work, whether systemd-resolve is running or not.


I want to get a statistic for the number of cases per person living in urbanised areas

Question: I have the number of  cases by country since the beginning of covid. It is simple to plot this against the population to get the cases per capita. But I also  have the population density per square kilometer and the percentage of the population living in urbanised settings. How do I show a plot which takes into account the latter data legitimately?
I have tried (cases to date/((population/100)*percentage of urbanised population)) but I am unsure if this is this legitimate.
Answer: It's not clear to me why you are dividing your population by 100, unless you are trying to scale your result to be the number of cases per 100 people living in an urbanized area.  Assuming you are not wanting that, then there is no need to divide your population by 100.
To obtain the number of cases per person living in an urbanized area is a simple calculation that boils down to computing the total number of people living in an urban area and the total number of cases.
To compute the total number of people living in an urban area, you'd simply compute the following:
\begin{eqnarray*}
Total\,Urban\,Population & = & \%\,Urban\,Population\times Total\,Population
\end{eqnarray*}
Once you have this figure, you simply take the total number of cases to date and divide by the Total Urban Population that you computed in the previous step:
\begin{eqnarray*}
Number\,Cases\,Per\,Urban\,Population & = & \frac{Total\,Cases\,to\,Date}{Total\,Urban\,Population}\times100\%
\end{eqnarray*}
That's all there is to it.
Comment: So that would be the average number of cases living in urban areas right? Thanks btw
Comment: That's the number of cases per person living in an urban areas.


Botão Toggle do Navbar não aparece

Question: Estou fazendo uma barra de menu responsiva com Bootstrap 4, porém quando eu reduzo o tamanho, o botão Toggle para abrir o menu colapsado não aparece. Segue o código HTML e CSS:
HTML:

        Init1

    <button class="navbar-toggler hidden-lg-up" type="button" data-
toggle="collapse"
        data-target="#navbarNav" aria-controls="navbarNav" aria-
expanded="false"
            aria-label="Toggle navigation">

    </button>

Home

Aprenda

Artigos

Sobre

Acesse Já!

CSS:
/*===================================== NAVIGATION========================================*/

/*====== LOGO ==========*/

.logo-txt {
color: #00838f;
font-size: 1.5em;
vertical-align: middle;
}

.logo::before {
content: "<";
font-weight: 400;
font-size: 2em;
vertical-align: middle;
color: #546e7a;
}

.logo::after {
content: "/>";
font-weight: 400;
font-size: 1.7em;
vertical-align: middle;
color: #546e7a;
}

/*========= NAVBAR ============*/

nav {
background-image: url(../img/menubar.png);
background-repeat: no-repeat;
}

Comment: Reduza o tamanho e coloque isso no console: `$(".navbar-toggler-icon").css("background","red");`. Veja se aparece alguma coisa.
Comment: Ficou um quadrado vermelho.
Comment: Pois é. O botão tá lá, só que tá sem nada. Deveria aparecer um hamburguer?
Comment: Sim. o navbar-toggler-icon é a classe pro botão hamburguer!
Comment: Vc não colocou o bootstrap css depois do js?
Answer: É preciso abrir a tag  com as classes requeridas pelo Bootstrap:

        Init1

    <button class="navbar-toggler hidden-lg-up" type="button" data-toggle="collapse"  data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

Home

Aprenda

Artigos

Sobre

Acesse Já!

Botão Toggle do Navbar não aparece


Keras Sequential model, more inputs

Question: I am quite new to machine learning and I am currently working on a "car value predictor" application. I stuck where I have to feed my data to my model. I have 4 inputs:

date: the car's first registration date (int)
km: the car's mileage meter (int)
consume: the car's consume type (one-hot encoded vector with 10 element e.g. for petrol: [1 0 0 0 0 0 0 0 0 0])
type: the car's type (for example: "BMW-320", stored in one-hot encoded vector with 440 element )

and one output:

the price of the car.

I would like to do something similar to this: https://i.stack.imgur.com/MpYRo.jpg
I have tried the following code which compiles but the output is not what I wanted:
model = Sequential([
Dense(128, input_shape=(1,), activation='relu', name='date'),
Dense(128, input_shape=(1,), activation='relu', name='km'),
Dense(128, input_shape=(10,), activation='relu', name='consume'),
Dense(128, input_shape=(440,), activation='relu', name='type'),
Dropout(0.5),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(1, activation='linear')
])
model.compile(loss='mse', optimizer='adam')
model.fit( x = {'date' : samples_train['input'][:,0],
                'km' : samples_train['input'][:,1],
                'consume':samples_train['input'][:,2],
                'type':samples_train['input'][:,3]},
           y = samples_train['output'],
           epochs=1000,
           batch_size=16,
           verbose=1,
           validation_data = ({'date' : samples_valid['input'][:,0],
                               'km' : samples_valid['input'][:,1],
                               'consume':samples_valid['input'][:,2],
                               'type':samples_valid['input'][:,3]}, samples_valid['output']),
           callbacks=callbacks)

Can anyone point out what am I doing wrong or how can I implement a model "structure" like on the picture?
EDIT:
I think this is what I was looking for. Can anyone confirm this? :)
input_1 = Input(shape=(1,), name='date')           # input layers
input_2 = Input(shape=(1,), name='km')
input_3 = Input(shape=(10,), name='consume')
input_4 = Input(shape=(440,), name='type')
dense_1 = Dense(256, activation='relu')(input_1)   # hidden layers
dense_1 = Dense(256, activation='relu')(input_2)
dense_1 = Dense(256, activation='relu')(input_3)
dense_1 = Dense(256, activation='relu')(input_4)
dropout_1 = Dropout(0.5)(dense_1)
dense_2 = Dense(256, activation='relu')(dropout_1)
dropout_2 = Dropout(0.5)(dense_2)
outputs = Dense(1, activation='linear')(dropout_2) # output layer

model = Model([input_1,input_2,input_3,input_4], outputs)

Thank you in advance.
Answer: I think your second Implementation is wrong.
By implementeing it like that, dense_1 will only have the value you gave it in the last line : input_4 = Input(shape=(440,), name='type') thus not taking into accunt the rest of the imputs for the rest of the network.
What you should do is concatenate your inputs into a single Line before feeding it to the first dense layer, like that :
from keras.layers import Concatenate

input_1 = Input(shape=(1,), name='date')           # input layers
input_2 = Input(shape=(1,), name='km')
input_3 = Input(shape=(10,), name='consume')
input_4 = Input(shape=(440,), name='type')

x = Concatenate()([input_1 , input_2 , input_3 , input_4]) # Concatenation of the inputs.

dense_1 = Dense(256, activation='relu')(x)   # hidden layers
dropout_1 = Dropout(0.5)(dense_1)

dense_2 = Dense(256, activation='relu')(dropout_1)
dropout_2 = Dropout(0.5)(dense_2)

outputs = Dense(1, activation='linear')(dropout_2) # output layer

model = Model([input_1,input_2,input_3,input_4], outputs)

Comment: Now I understand, why my network looks like this:
[(model.summarize())](https://imgur.com/a/g83Paec)

Thank you very much for the clarification!
Comment: Your implementation looks like: [(model.summarize())](https://imgur.com/a/rF0EMBT)

Keras Sequential model, more inputs


Limes $\lim_{n\rightarrow\infty}n^{3/2}(\arctan(\sqrt{n+1})-\arctan\sqrt{n})$

Question: How to deal with the the following limit:
$$\lim_{n\rightarrow\infty}n^{3/2}(\arctan(\sqrt{n+1})-\arctan\sqrt{n})$$
I'm clueless.
Comment: Hint: $\arctan \alpha + \arctan\beta=\arctan\left(\frac{\alpha+\beta}{1-\alpha\beta}\right)$
Answer: Hint: Use the fact that $\tan(x-y)=\frac{\tan x-\tan y}{1+\tan x\tan y}$ to express $\arctan(\sqrt{n+1})-\arctan(\sqrt{n})$ as
$$\arctan\left(\frac{\sqrt{n+1}-\sqrt{n}}{1+\sqrt{n+1}\sqrt{n}}\right).$$
Rationalize the numerator, and you should be on your way.
You will probably want to write $n^{3/2}$ as $\frac{1}{1/n^{3/2}}$. The rest is closely related to the limit as $t\to 0$ of $\frac{\tan t}{t}$.
Comment: There's a typo in your first equation: the denominator should be a sum, not a difference.
Comment: Many thanks, fixed, luckily it did not affect the rest, where the $+$ was used.


Win 2008 - MSI installer fails with firewall exception

Question: OS: Windows 2008 R2
Zabbix Agent 2 - 6.2.5
As admin, when installing Zabbix Agent 2 MSI package with a PowerShell script, I'm getting what seems to be a firewall exception. That causes MSI installer to rollback.
The MSI installation log displays some errors related to Windows Firewall.
My PS script uses these parameters:
<code>$argList = @('/norestart',
            '/qn',
            '/passive',
            '/l*v',
            "$zabbixDir\zabbixInstall.log",
            '/i',
            "$dirTemp\$msiAgentZabbix",
            "INSTALLFOLDER=$zabbixDir",
            "LOGFILE=$zabbixDir\zabbixAgent.log",
            "SERVER=$proxy",
            "SERVERACTIVE=$proxy",
            "HOSTNAME=$hostname",
            "ENABLEPERSISTENTBUFFER=1",
            "PERSISTENTBUFFERPERIOD=1d",
            "PERSISTENTBUFFERFILE=$zabbixDir\zabbixAgent.db",
            "ALLOWDENYKEY=AllowKey=system.run[*]",
            "HOSTMETADATA=`"windows $proxyname $metadata`"")
Start-Process msiexec.exe -Wait -PassThru -ArgumentList "$argList"
</code>
I've never had an issue with the MSI installer on Win 2008 VMs, but now, with other similar VMs, I'm getting these error messages.
MSI installation Log:
<code>MSI (s) (18:F8) [09:57:32:457]: Doing action: WixSchedFirewallExceptionsUninstall
Action ended 9:57:32: RemoveEnvironmentStrings. Return value 1.
MSI (s) (18:40) [09:57:32:457]: Invoking remote custom action. DLL: C:\Windows\Installer\MSIC223.tmp, Entrypoint: SchedFirewallExceptionsUninstall
MSI (s) (18:34) [09:57:32:457]: Generating random cookie.
MSI (s) (18:34) [09:57:32:517]: Created Custom Action Server with PID 8076 (0x1F8C).
MSI (s) (18:C8) [09:57:32:777]: Running as a service.
MSI (s) (18:C8) [09:57:32:777]: Hello, I'm your 32bit Impersonated custom action server.
Action start 9:57:32: WixSchedFirewallExceptionsUninstall.
SchedFirewallExceptions:  Component 'CONFIGFWx64' action state (1) doesn't match request (2)
SchedFirewallExceptions:  No firewall exceptions scheduled
MSI (s) (18:F8) [09:57:32:787]: Doing action: RemoveFiles
Action ended 9:57:32: WixSchedFirewallExceptionsUninstall. Return value 1.

(...)

ExecFirewallExceptions:  Installing firewall exception2 Zabbix Agent 2 listen port on port , protocol 6
ExecFirewallExceptions:  Error 0x800706d9: failed trying to find existing port rule
ExecFirewallExceptions:  Error 0x800706d9: failed to add/update port exception for name 'Zabbix Agent 2 listen port' on port , protocol 6
CustomAction WixExecFirewallExceptionsInstall returned actual error code 1603 (note this may not be 100% accurate if translation happened inside sandbox)
MSI (s) (F4:54) [08:00:09:652]: User policy value 'DisableRollback' is 0
MSI (s) (F4:54) [08:00:09:652]: Machine policy value 'DisableRollback' is 0
Action ended 8:00:09: InstallFinalize. Return value 3.
</code>
The oddest thing is that Windows Firewall is disabled on all VMs.
So, I can't see why that would be an issue for MSI installer.
If I start the MSI installer manually using its GUI, the installation works fine.
I'm not really sure the issue is the firewall, but that was all I could find.
Any idea?
Comment: Try enabling firewall once and install.
Comment: If temporarily enabling Windows Firewall isn't an option you could either edit the MSI file to remove the *firewall* custom actions or create a transform file which could then be applied by command-line, using `TRANSFORMS=` parameter. Editing and transform file creation can be done using Orca or InstEd tool (I prefer the latter).
Answer: Thank you all for your considerations.
Windows Firewall service was disabled on some hosts.
To bypass the issue, I enabled the service while maintaining the Firewall turned off.
After doing so, the installation was successful.
What still bothers me, is that, if installing with the traditional GUI, there were no issues. Only when installing with PS script it failed.
For now, by checking the Firewall service, I can use the MSI package with the script.


Symfony: Turning a SQL query into a correct Doctrine QueryBuilder Instance

Question: I need a working query builder in symfony for the following SQL:
SELECT
(SELECT COUNT(ii.invoice_id) FROM invoice WHERE invoice_number = i.invoice_number) as c,
i.id as invoice_id, i.invoice_number, ii.logistician_id FROM invoice i
LEFT JOIN incoming_invoice ii ON i.id = ii.invoice_id
GROUP BY invoice_id
HAVING c < 2;

Im testing since yesterday but i do not get it working.
public function findAllWithoutIncomingInvoice(): array
{
    return $this->createQueryBuilder('i')
        ->select('i, ii, COUNT(ii.invoice_id) FROM invoice WHERE invoice_number = i.invoice_number) as c')
        ->leftJoin('i.incomingInvoices', 'ii')
        ->groupBy('i.id')
        ->having('c < 2')
        ->setMaxResults(15)
        ->getQuery()
        ->getResult();
}

Error:

[Semantical Error] line 0, col 40 near 'invoice WHERE': Error: Class 'invoice' is not defined.
Comment: Can you also edit your post with the error you're getting?..
Comment: I'm not getting that part `(SELECT COUNT(ii.invoice_id) FROM invoice WHERE invoice_number = i.invoice_number)`, why do you select a count here ? Also, can you add your classes (invoice, incoming invoice) to your question please ?
Comment: @Preciel  Each invoice (i) can have multiple incoming_invoice (ii) entries. But i need only which have less than 2 entries.
Answer: You should properly name your aliases, it make it easier to read back your code.
Also, make sure you use double quote to write your DQL, as Doctrine will require simple quote around text values
As for your answer, it should be something close to this :
public function findAllWithoutIncomingInvoice(): array {
    $qb = $this->_em->createQueryBuilder();

    $qb->select("invoice")
       ->from(Invoice::class, "invoice")
       ->join("invoice.incomingInvoice", "incomingInvoice")
       ->groupBy("invoice.id")
       ->having("COUNT(incomingInvoice.id) < 2");

    return $qb->getQuery()->getResult();
}


Why does PHP's $_POST variable get values from HTML's name attribute instead of id attribute?

Question: I understand that when accessing values of HTML form elements in PHP, we must use the name attribute within the $_POST variable. However, I'm not sure I understand why that's the case. It seems to me like it may have been better for $_POST to use id attributes and take advantage of the insured uniqueness, rather than potentially finding multiple values if more than 1 form elements share the same name. I'm sure there's a good reason why name attributes are used instead of id, but I haven't been able to dig that up and curious to understand why.
Simple example:
index.html

    <form action="./some_script.php" method="post">
        <input type='text' id='text_input_id' name ='text_input_name'>
        <input type='submit'>
    </form>

some_script.php
<?php
    $value_from_id = $_POST["text_input_id"]; // will be null
    $value_from_name = $_POST["text_input_name"]; // will contain text input from form
?>

Comment: `id`s are unique across the page, yes, but `name`s don't have to be unique.  You can even send multiple values under the same `name` using `[]`.  Like `name="yourArray[]"`, if you add this to multiple fields, then you will get an array in `$_POST['yourArray']`.
Comment: Here's the docs for the `name` attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-name
Answer: The primary reason is that forms were added to HTML before IDs were.
However, an ID must be unique in an HTML document but a name doesn't. You can have multiple form controls with the same name.
Sometimes this is required e.g. in order to create a radio group:

<form>
  <input type="radio" name="availability" value="yes" id="availability_yes">
  Yes

  <input type="radio" name="availability" value="no" id="availability_no">
  No

  <input type="radio" name="availability" value="if need be" id="availability_inb">
  If Need Be
</form>

and sometimes it is just useful (e.g. when picking from a list of things).

<form>
  <fieldset>
    <legend>Acceptable Colours</legend>
    <input type="checkbox" name="colours[]" value="red" id="colours_red">
    Red

    <input type="checkbox" name="colours[]" value="green" id="colours_green">
    Green

    <input type="checkbox" name="colours[]" value="blue" id="colours_blue">
    Blue
  </fieldset>
</form>
Comment: Oh  yes, I forgot about that PHP oddity. (Normally no, but the question was PHP focused).
Comment: In the checkbox group, wouldn't you want `name="colours[]"`?


knockoutjs $index is not working in mapping plungin

Question: I am using asp.net mvc 3 and knockoutjs 2.0 and mapping plugin
I have converted my model as json as below using mapping plugin
viewModel=ko.mapping.fromJS(@Html.Raw(Html.Serialize(Model)));

my model is
 public class Jobs : EntityBase
    {

        [MLLAttr(ObjectType = MLLObjectType.Child, IsCreate = true, ParentName = "Jobs", IsRequired = true)]
        public List<JobOrder> JobOrder { get; set; }
   }

$index is not working.
Thanks in advance
Comment: `$index` was introduced in version 2.1.
Answer: As Michael pointed out, $index was introduced in knockout 2.1. You will need to update to use it


Stuck with solving inequality to find the product of highest and lowest integer solutions

Question: The inequality in question is
$$\sqrt{(5+2\sqrt{6})^{2x}}+\sqrt{(5-2\sqrt{6})^{2x}}\leq98$$
This time our job is to find the product of highest and lowest integer solutions.

My attempt
$$\sqrt{(5+2\sqrt{6})^{2x}}+\sqrt{(5-2\sqrt{6})^{2x}}\leq98$$
$$\sqrt{((5+2\sqrt{6})^{x})^2}+\sqrt{((5-2\sqrt{6})^{x})^2}\leq98$$
$$(5+2\sqrt{6})^x+(5-2\sqrt{6})^x\leq98$$
What next?

The solution is $-4$.
Answer: As $(5+2\sqrt6)(5-2\sqrt6)=1$
if $(5+2\sqrt6)^x=a>0$
$$a+\dfrac1a\le98\iff a^2-98a+1\le0$$
$a^2-98a+1=0\implies a=\dfrac{98\pm40\sqrt6}2=49\pm20\sqrt6=(5\pm2\sqrt6)^2$
$\implies(5+2\sqrt6)^{-2}=(5-2\sqrt6)^2\le a\le(5+2\sqrt6)^2 $
$\implies-2\le x\le2$
Comment: I think you should use $a$ instead of $t$ for consistency.
Comment: @Vuk, Thanks for your feedback
Answer: We have
$$
(a+b)^2+(a-b)^2= 2a^2+2b^2 = 98
$$
with $a = 5$ and $b = 2\sqrt 6$


Change mail headers and send back to Office 365 using Postfix

Question: I have a outbound and inbound connector setup on my Office365. Outbound connector is sending all emails from my users to Postfix which is on premises. I do some processing with Postfix and then I send this same email back to Office 365 without ever changing the From or To addresses.
It is possible my users can send to any domain so my Postfix should accept emails for any domain as long as it's coming from Office365.
Is it possible that I can receive email for example.com and save it in a Maildir folder, then make some changes to headers and send it to another SMTP server from the same Postfix instance?
Problem I have right now is that once Postfix is configured to accept email for a domain. I can't find a way to also send the emails destined for a user in that domain to another SMTP server. I have achieved it from the Python script but I want to see if I can achieve it using Postfix.
Comment: You could use relayhost, and not mess with the headers at all (messing with headers, even if possible, sounds like a very bad idea). But I don't know if you're trying to use this particular server to be the final destination for some people on the domain.... Google Postfix Split Domain Routing. I've never done it before, but I know it can be done.... https://serverfault.com/questions/575296/splitting-emails-for-a-single-domain-into-two
Comment: Thanks for the reply. I am adding another Key/Value to header. Also, I receive email let's say for email@example.com. I then give it to a Python script that adds a header and tries to send that same email (still the recipient stays the same email@example.com) to another SMTP server. But my Postfix complains that there is a loop and bounces the email message.
Comment: @David W: "messing with headers" can be a very good idea if you use OpenDKIM or SpamAssassin.
Comment: Thanks for the feedback. I admittedly am not an expert in this stuff. Unrelated: I think your response should be posted as a comment, and not as an answer.
Comment: yes I should, sorry about that.
Answer: The easiest way to do this is probably to pass the mail to an external script. You can make an alias which delivers to a local mailbox and pipes to a script using something like:
someuser: \someuser, "|/usr/local/sbin/relayscript.py"

in /etc/aliases. You will need to have alias processing enabled in main.cf with:
alias_maps=hash:/etc/aliases

Comment: Hmm, from your comment above it looks like you're trying to send to the same address? Your script should handle rewriting the 'To:' address to send to wherever you need the modified email to go, and then make its own SMTP connection. If you're using Python then https://docs.python.org/2/library/email-examples.html might give you some pointers on how to handle that.
Comment: Thank you James. I have achieved it form the Python script but i want to see if I can achieve it using Postfix. Here is the complete scenario. I have a outbound and inbound connector setup on my Office365. Outbound connector is sending all emails from my users to Postfix which is on premises. I do some processing with postfix and then i send this same email back to office 365 without ever changing the From or To addresses.  It is possible my users can send to any domain so my postfix should accept emails for any domain as long as coming from Office365.
Comment: Continued from previous comment: All these emails end up in the same folder. When email arrives a python script is triggered which adds another Header then tries to send the same email back to Office 365 to it can be sent to the actual destined recipient.
Comment: Presumably you don't have the relevant domains in `$mydestination` if it's any domain, so Postfix is acting as a relay? If that's the case you might be able to inject your header with `header_checks` (there's an example here https://unix.stackexchange.com/questions/44123/add-header-to-outgoing-email-with-postfix) and then use a `relayhost` setting to pass the mail to Office365 again. I presume there's some mechanism that stops Office365 just sending it back to you?
Comment: The mechanism is the header. So O365 is only sending emails to my Postfix if it doesn't have the header so to not create a loop. I am also doing some other stuff with emails thus can't use the header_checks the email has to pass to a script.
Comment: Sounds like using the script to pass it back is probably the sane solution if it's already in the mix. The other possibility I can think of is setting up a second SMTP instance in your `master.cf` on another port with different configuration and having your script pass the mail to that. I suspect that will be ugly and complicated, though.
Comment: Based on the comments, you were asking something totally different from your original post. I tried to help you to ask the right things by adding the details from these comments.
Comment: Thanks Esa. I am still waiting to see if someone knows how to achieve it using Postfix or if it is even possible.


why functions that returns tables are so much slower then running the actual query?

Question: I'm pretty new to PostgreSQL so I guess i'm missing some basic information, information that I didn't quite find while googling, guess I didn't really know the right keywords, hopefully here I'll get the missing information :)
I'm using PostgreSQL 11.4.
I've encountered many issues when I create a function that returns a query result as a table, and it executes it about 50 times slower then running the actual query, sometimes even more then that.
I understand that IMMUTABLE can be used when there is no table scans, just when I manipulate and return data based on the function parameters and STABLE when if the query with same parameters do a table scan and always returns the same results.
so the format of my function creation is this:
CREATE FUNCTION fnc_name(columns...)
RETURNS TABLE ( columns..) STABLE AS $func$
BEGIN
 select ...
END $func$ LANGUAGE pgplsql;

I can't show the query here since it's work related, but still... there is something that I didn't quite understand about creating functions why is it so slow ? I need to fully understand this issue cause I need to create many more functions and it seems right now that I need to run the actual query to get proper performance instead of using functions and I still don't really have a clue as to why!
any information regarding this issue would be greatly appreciated.
Comment: If your function really only contains one query, use a `language sql` function instead
Comment: @a_horse_with_no_name - thank you. that helped a lot. I do have some other queries with plgpsql language with several complex queries, how do I know for sure that creating a function doesn't make the query execution way slower?
Comment: I get a slow down of about 30%, not 50 fold.  I think you need to simplify the table/query to the point where you can share it, but it shows the same slowdown.
Answer: All depends on usage of this function, and size of returned relation.
First I have to say - don't write these functions. It is known antipattern. I'll try to explain why. Use views instead.

Result of table functions written in higher PL languages like Perl, Python or PLpgSQL is materialized. When table is small (to work_mem) it is stored in memory. Bigger tables are stored in temp file. It can have significant overhead.
Function is a black box for optimizer - is not possible to push down predicates, there are not correct statistics, there is not possible to play with form of joins or order of joins. So some not trivial queries can be slower (little bit or significantly) due impossible optimizations.

There is a exception from these rules - simple SQL functions. SQL functions (functions with single SQL statement) can be inlined (when some prerequisites are true). Due inlining the body of function is merged to body of outer SQL query, and the result is same like you will write subquery directly. So result is not materialized and it is not a barrier for optimization.
There is a basic rule - use functions only when you cannot to calculate some data by SQL. Don't try to hide SQL or encapsulate SQL (elsewhere - for simplification some complex queries use views not functions). Same rules are valid for all SQL databases (Oracle, DB2, MSSQL). Postgres is not a exception.
This note is not against stored procedures (functions). It is great technology. But it requires specific style of programming. Wrapping queries into functions (when there is not any other) is bad.


Json value in error during parse

Question: I have a following Json and want to print key and value.
We are receiving the data as
{\"dcFlag\":null,\"code\":null,\"packageQuantity\":null,\"analgesicTax\":false,\"shelfTicketName\":null,\"productType\":null,\"itemSizeValue\":null,\"unit\":null,\"unitPriceRequired\":false,\"unitPriceMeasure\":null,\"unitPriceDisplay\":null,\"itemSizeUOM\":null,\"australiaMadeGrown\":null,\"departmentCat\":null,\"categoryCat\":null,\"commodityCat\":null,\"subCommodityCat\":null,\"selectedUnit\":null,\"toConsumer\":true,\"toRetailer\":true,\"taxName\":\"1\",\"taxRate\":null,\"countryOfOrigin\":null}"

After JSON.parse the data is converted to
{"dcFlag":null,"code":null,"packageQuantity":null,"analgesicTax":false,"shelfTicketName":null,"productType":null,"itemSizeValue":null,"unit":null,"unitPriceRequired":false,"unitPriceMeasure":null,"unitPriceDisplay":null,"itemSizeUOM":null,"australiaMadeGrown":null,"departmentCat":null,"categoryCat":null,"commodityCat":null,"subCommodityCat":null,"selectedUnit":null,"toConsumer":true,"toRetailer":true,"taxName":"1","taxRate":null,"countryOfOrigin":null}

I tried
 var obj = JSON.parse(result);
                    console.log(obj);
                    $.each(obj, function(k, v) {
                        //display the key and value pair
                        console.log(k + ' is ' + v);
                    });

It's throwing an error as
Uncaught TypeError: Cannot use 'in' operator to search for '455' in

Any inputs?
Thanks for the help.
Comment: working just fine on my end.
Comment: Maybe it is already parsed?
Comment: Have you read the error you've posted? It doesn't seem relevant to the `JSON` string you've provided. Where is _`'455'`_ in your string? Something else in your code throws this error.
Answer: Don't use parse as the result is already parsed.

var obj = {"dcFlag":null,"code":null,"packageQuantity":null,"analgesicTax":false,"shelfTicketName":null,"productType":null,"itemSizeValue":null,"unit":null,"unitPriceRequired":false,"unitPriceMeasure":null,"unitPriceDisplay":null,"itemSizeUOM":null,"australiaMadeGrown":null,"departmentCat":null,"categoryCat":null,"commodityCat":null,"subCommodityCat":null,"selectedUnit":null,"toConsumer":true,"toRetailer":true,"taxName":"1","taxRate":null,"countryOfOrigin":null};
$.each(obj, function(k, v) {
    //display the key and value pair
    console.log(k + ' is ' + v);
});
console.log(obj);

If the result contain backslash then it works fine:

var result = '{\"dcFlag\":null,\"code\":null,\"packageQuantity\":null,\"analgesicTax\":false,\"shelfTicketName\":null,\"productType\":null,\"itemSizeValue\":null,\"unit\":null,\"unitPriceRequired\":false,\"unitPriceMeasure\":null,\"unitPriceDisplay\":null,\"itemSizeUOM\":null,\"australiaMadeGrown\":null,\"departmentCat\":null,\"categoryCat\":null,\"commodityCat\":null,\"subCommodityCat\":null,\"selectedUnit\":null,\"toConsumer\":true,\"toRetailer\":true,\"taxName\":\"1\",\"taxRate\":null,\"countryOfOrigin\":null}"';
debugger;
result=result.slice('0','-1');

var obj = JSON.parse(result);
$.each(obj, function(k, v) {
//display the key and value pair
console.log(k + ' is ' + v);
});

Comment: thanks for the quick response.I have updated the ticket can you look and suggest me thanks.
Comment: ok, i updated the second snippet please check that. It should work. You might be missing double quotes at the beginning and at the end.
Comment: Make sure of double quotes at the beginning and at the end of the string value in `result` variable.
Comment: that value is coming from thridparty.Do I need to add double quotes manually
Comment: Try adding manually. You can just use `var result = data.toString()` and check your console and tell me the error if it exist.
Comment: After anlaysing the response.I can see the double quotes at the start and end but at the start quotes there is a space and all other are started in second line is it because any hidden special character.?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/164758/discussion-between-ankit-agarwal-and-sree).
Comment: I have used  var data =  JSON.parse(result);
                        console.log(data);
                        for (var prop in data) {
                         console.log(prop);
                        } and it is printing numbers in the console log rather than keys

Json value in error during parse


In a meta-analysis, can you back calculate estimated group proportions from risk difference?

Question: In a meta-analysis of the risk difference, does it make sense to apply the weights & back calculate the expected proportions in each group?
For example, if you had the following:
<code>Study    RD     [95% Conf.  Interval]   % Weight

1        -0.132 -0.336  0.071           34.28
2        -0.033 -0.220  0.153           40.74
3        -0.080 -0.318  0.159           24.98

PooledRD -0.079 -0.198  0.040           100.00

Study   n/N      prop1      n/N      prop0
1       23/35    .6571429   30/38    .7894737
2       32/50    .64        33/49    .6734694
3       12/32    .375       15/33    .4545455
</code>
Would it be correct to apply the weights the proportions? ie, to give 58.0% vs 65.9%?
[note: calculated by weighting the proportions by the meta-analysis weights = .6571429*.3428 + .64*.4074 + .375*.2498 = 58.0% for prop1]
Or would you use the raw proportions (57.3% vs 65.0%)
[note: calculated by summing events over total = (23+32+12)/(35+50+32)*100 = 57.3% for prop1]
Comment: Can you edit to clarify this? Where do 58.0, 65.9, 57.3, and 65.0 come from? Is there any reason you want to do this or is it just curiosity?
Comment: Sorry - I wasn't very clear. The 57.3% and 65.0% come from summing the total with the event over the total in arms 0 and 1 (ie, for arm 1 [23+32+12]/[35+50+32]*100 = 57.3%). The 58.0% and 65.9% come from weighting the proportions by the weights from the meta-analysis (ie, for arm 1 (23/35)*.3428 + (32/50)* .4074 + (12/32)*.2498 = 58.0%). Regarding the reason, I have been asked to present the proportions by arm rather than just the risk difference, & am unsure whether the best way to proceed is to use the raw proportions or the weighted proportions?
Comment: Would you not want to meta-analyse the proportions, which for arm 1 gives 56.3 using the logit transformation? Arm 2 would be 64.8. Admittedly this is incompatible with the risk difference as it yields -0.084.
Comment: Thank you, I hadn't considered this - but it makes sense. I am concerned about the overall message to the "lay" public if the proportions/differences don't match up
Answer: Just to summarise the discussion from the comments.
In a comparative study the usual procedure is to compute some measure of discrepancy (a difference or a ratio usually) and then meta-analyse that using its standard error. An alternative approach might be to meta-analyse the values being compared and then compute the discrepancy measure from those summaries. In the specific case being considered here we have a risk difference and underlying it proportions. In general since in both cases the measures are analysed transformed and weighted the two procedures I outlined above will not give the same result.
I suppose this is an instance of Jensen's inequality.


How to enable camera feature in a sencha touch application using phonegap?

Question: I have developed one application in Sencha Touch 2. I want to design a page in such a way that
the page has a default image and one button below that. By clicking that  button device camera should open (device mainly iPad and iPhone) and after capturing the image lets see it stored in a folder named as "capture" in your device. Then the captured image should replace that default image.
I want to use PhoneGap compulsorily. I have seen PhoneGap APIs for camera but I don't get it how to use it exactly. I am using Mac and Xcode for development.
Comment: Hi! Have you tried the example from the online tutorial / doc? http://docs.phonegap.com/en/1.5.0/phonegap_camera_camera.md.html#Camera (First full example)
Comment: hey  i have tried  that  code. But it's working in a html button. But in my application I am creating buttons using js file using model-view-controller method. It's a sencha touch app. Please suggest how can I implement ?

Thanks
Comment: Could you add the js code you used for creating your button in your post?
Comment: ok sure..thanks now I am able to access camera but unable to replace the default image with image i have taken. when I am clicking "USE" button it's just vanishing and deafault image is remain there ... i am posting my code plz see..

Thanks
Answer: capturePhoto:function(){
<code>       navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });

       function onPhotoDataSuccess(imageData) {
       // Uncomment to view the base64 encoded image data
       // console.log(imageData);

       // Get image handle
       //
       var smallImage = document.getElementById('userLogo');

       // Unhide image elements
       //
       smallImage.style.display = 'block';

       // Show the captured photo
       // The inline CSS rules are used to resize the image
       //
       smallImage.src = "data:image/jpeg;base64," + imageData;
</code>
plz verify ...
Answer: In my app With sencha touch 2 and Phonegap 1.4
in Controller
on take photo button handler
<code>onTakePhotoButton: function(){
       // Retrieve image file location from specified source
        navigator.camera.getPicture(uploadPhoto, function (message) {
            alert('Get picture failed');
        }, {
            quality: 50,
            destinationType: navigator.camera.DestinationType.FILE_URI,
            sourceType: navigator.camera.PictureSourceType.CAMERA //or PHOTOLIBRARY
        }
        );
        function uploadPhoto(imageURI) {
            var options = new FileUploadOptions();
            options.fileKey = "file";
            var imagefilename = Number(new Date()) + ".jpg";
            options.fileName = imagefilename;
            options.mimeType = "image/jpeg";
            options.chunkedMode = false;
            var params = new Object();
            params.image = imagefilename;
            options.params = params;
            var ft = new FileTransfer();
            ft.upload(imageURI,your_request_upload_url_on_server, win, fail, options);
        }

        function win(r) {
            console.log("Code = " + r.responseCode);
            console.log("Response = " + r.response);
            console.log("Sent = " + r.bytesSent);
            var json_obj = Ext.decode(r.response);//remote server funciton upload return json type
            if(json_obj!=null && json_obj.response.image_name!=null){
                console.log(json_obj.response.image_name);
                imageDisplay.setSrc(your_image_root_tmp+json_obj.response.image_name+'?dc='+Number(new Date()));
            }else{
                Ext.Msg.alert('Errors', "The server response failure!");
            }

        }

        function fail(error) {
            alert("An error has occurred: Code = " + error.code);
        }
}
</code>
you can refer more detail here http://zacvineyard.com/blog/2011/03/upload-a-file-to-a-remote-server-with-phonegap
Comment: I have tried your code but it's not working. it's showing blank page. I think problem is declaring several functions in the same js page. "navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 100 });" function is working fine but "onPhotoDataSuccess" function is not been called. same thing is happening in your code also... suggest  some alternatives..

Thanks....fabre
Comment: try getPicture function with callback uploadPhoto function. uploadPhoto function with callback win function and fail function.