Invalid dump format pgbackups:restore even with Dropbox download link

Question: I'm trying to transfer data from my local postgresql dump file to a Heroku database.
I've been trying to use pgbackups:restore using the tips I found in SO but this error below is a brick-wall: "INVALID DUMP FORMAT HTML document text". I think the problem definitely lies in dropbox.
I try to copy the URL From this Dropbox screen (the link on the Download button), after clicking the "Share" link. But the 'Invalid Dump Format HTML document text' error shown below is persisting. I've tried different permutations of the URL (https www, https dl, http www ... they all give me the same errors)

$ heroku pgbackups:restore HEROKU_POSTGRESQL_BLUE_URL 'https://dl.dropbox.com/s/80vy8mm6enwsdfo/mydb.dump'

HEROKU_POSTGRESQL_BLUE_URL (DATABASE_URL)  <---restore---  mydb.dump
!    WARNING: Destructive Action  !    This command will affect the
  app: terrysquotes  !    To proceed, type "appName" or re-run this
  command with --confirm appName

$ appName

Retrieving... done
!    An error occurred and your restore did not finish.  !    Please
  run heroku logs --ps pgbackups for details.

$ heroku logs --ps pgbackups

2014-06-22T16:44:11+00:00 app[pgbackups]: psql: bin//pg-latest/psql
  2014-06-22T16:44:11+00:00 app[pgbackups]:
  --------+------+------+------ 2014-06-22T16:44:11+00:00 app[pgbackups]: pg_restore: env LD_LIBRARY_PATH=bin//9.3
  bin//9.3/pg_restore 2014-06-22T16:44:12+00:00 app[pgbackups]: Invalid
  dump format: /tmp/4XHVprPkdu/mydb.dump: HTML document text
  2014-06-22T16:44:12+00:00 app[pgbackups]: download_progress: done
  2014-06-22T16:44:11+00:00 app[pgbackups]: Started:  Sun Jun 22
  16:44:11 UTC 2014 2014-06-22T16:44:11+00:00 app[pgbackups]:
  download_progress: start 2014-06-22T16:44:12+00:00 app[pgbackups]:
  download_progress: 486.0bytes 2014-06-22T16:44:11+00:00
  app[pgbackups]: Location:
  0d306785-c6e9-42a6-ab66-3fb55f7f0f6e:/tmp/4XHVprPkdu
  2014-06-22T16:44:11+00:00 app[pgbackups]:  Schema | Name | Type | Info
  2014-06-22T16:45:39+00:00 app[pgbackups]: psql: bin//pg-latest/psql
  2014-06-22T16:45:39+00:00 app[pgbackups]: download_progress:  496B
  2014-06-22T16:45:39+00:00 app[pgbackups]: (0 rows)
  2014-06-22T16:45:39+00:00 app[pgbackups]:  Schema | Name | Type | Info
  2014-06-22T16:45:38+00:00 app[pgbackups]: Location:
  41095e94-2a25-42c5-a778-0f37d6d0fbd9:/tmp/bI1zFet590
  2014-06-22T16:45:39+00:00 app[pgbackups]: download_progress: start
  2014-06-22T16:45:38+00:00 app[pgbackups]: Started:  Sun Jun 22
  16:45:38 UTC 2014 2014-06-22T16:45:39+00:00 app[pgbackups]:
  2014-06-22T16:45:39+00:00 app[pgbackups]: pg_restore: env
  LD_LIBRARY_PATH=bin//9.3 bin//9.3/pg_restore 2014-06-22T16:45:39+00:00
  app[pgbackups]: --------+------+------+------
  2014-06-22T16:45:39+00:00 app[pgbackups]: pv: bin//pv-latest
  2014-06-22T16:45:40+00:00 app[pgbackups]: download_progress:
  496.0bytes 2014-06-22T16:45:39+00:00 app[pgbackups]: 2014-06-22T16:45:40+00:00 app[pgbackups]: Invalid dump format:
  /tmp/bI1zFet590/mydb.dump: HTML document text
  2014-06-22T16:45:40+00:00 app[pgbackups]: download_progress: done
  2014-06-22T16:47:32+00:00 app[pgbackups]: 2014-06-22T16:47:32+00:00
  app[pgbackups]: psql: bin//pg-latest/psql 2014-06-22T16:47:32+00:00
  app[pgbackups]: download_progress: 226.0bytes
  2014-06-22T16:47:32+00:00 app[pgbackups]: pg_restore: env
  LD_LIBRARY_PATH=bin//9.3 bin//9.3/pg_restore 2014-06-22T16:47:32+00:00
  app[pgbackups]: download_progress: done 2014-06-22T16:47:32+00:00
  app[pgbackups]: pv: bin//pv-latest 2014-06-22T16:47:32+00:00
  app[pgbackups]:  Schema | Name | Type | Info 2014-06-22T16:47:32+00:00
  app[pgbackups]: Invalid dump format: /tmp/wahMuTNOLf/mydb.dump: HTML
  document text 2014-06-22T16:47:32+00:00 app[pgbackups]: Started:  Sun
  Jun 22 16:47:32 UTC 2014 2014-06-22T16:47:32+00:00 app[pgbackups]:
  2014-06-22T16:47:32+00:00 app[pgbackups]: download_progress:  226B
  2014-06-22T16:47:32+00:00 app[pgbackups]: download_progress: start
  2014-06-22T16:47:32+00:00 app[pgbackups]: Location:
  3a91ccfa-a2c0-4277-b84b-d2be43e4a834:/tmp/wahMuTNOLf
  2014-06-22T16:47:32+00:00 app[pgbackups]: (0 rows)
  2014-06-22T16:47:32+00:00 app[pgbackups]:
  --------+------+------+------ 2014-06-22T16:50:48+00:00 app[pgbackups]: psql: bin//pg-latest/psql 2014-06-22T16:50:49+00:00
  app[pgbackups]: download_progress: done 2014-06-22T16:50:48+00:00
  app[pgbackups]: Location:
  ff26e7c9-51b1-49a9-8eac-96380e518059:/tmp/e940S4ziPp
  2014-06-22T16:50:48+00:00 app[pgbackups]:
  --------+------+------+------ 2014-06-22T16:50:48+00:00 app[pgbackups]: download_progress:  486B 2014-06-22T16:50:48+00:00
  app[pgbackups]:  Schema | Name | Type | Info 2014-06-22T16:50:48+00:00
  app[pgbackups]: download_progress: start 2014-06-22T16:50:48+00:00
  app[pgbackups]: Started:  Sun Jun 22 16:50:48 UTC 2014
  2014-06-22T16:50:49+00:00 app[pgbackups]: download_progress:
  486.0bytes 2014-06-22T16:50:48+00:00 app[pgbackups]: pg_restore: env LD_LIBRARY_PATH=bin//9.3 bin//9.3/pg_restore 2014-06-22T16:50:48+00:00
  app[pgbackups]: 2014-06-22T16:50:48+00:00 app[pgbackups]:
  2014-06-22T16:50:48+00:00 app[pgbackups]: pv: bin//pv-latest
  2014-06-22T16:50:48+00:00 app[pgbackups]: (0 rows)
  2014-06-22T16:50:49+00:00 app[pgbackups]: Invalid dump format:
  /tmp/e940S4ziPp/mydb.dump: HTML document text
  2014-06-22T16:53:27+00:00 app[pgbackups]:
  --------+------+------+------ 2014-06-22T16:53:27+00:00 app[pgbackups]: download_progress:  386B 2014-06-22T16:53:27+00:00
  app[pgbackups]: Started:  Sun Jun 22 16:53:27 UTC 2014
  2014-06-22T16:53:27+00:00 app[pgbackups]: pg_restore: env
  LD_LIBRARY_PATH=bin//9.3 bin//9.3/pg_restore 2014-06-22T16:53:27+00:00
  app[pgbackups]: 2014-06-22T16:53:27+00:00 app[pgbackups]:
  download_progress: 386.0bytes 2014-06-22T16:53:27+00:00
  app[pgbackups]: Location:
  44aaa82b-b329-4ea8-b869-af74a2291d2d:/tmp/ar3nXH75CR
  2014-06-22T16:53:27+00:00 app[pgbackups]:  Schema | Name | Type | Info
  2014-06-22T16:53:27+00:00 app[pgbackups]: download_progress: start
  2014-06-22T16:53:28+00:00 app[pgbackups]: Invalid dump format:
  /tmp/ar3nXH75CR/mydb.dump: HTML document text
  2014-06-22T16:53:27+00:00 app[pgbackups]: psql: bin//pg-latest/psql
  2014-06-22T16:53:27+00:00 app[pgbackups]: 2014-06-22T16:53:27+00:00
  app[pgbackups]: pv: bin//pv-latest 2014-06-22T16:53:27+00:00
  app[pgbackups]: (0 rows) 2014-06-22T16:53:27+00:00 app[pgbackups]:
  download_progress: done 2014-06-22T17:01:39+00:00 app[pgbackups]:
  download_progress: start 2014-06-22T17:01:38+00:00 app[pgbackups]: pv:
  bin//pv-latest 2014-06-22T17:01:39+00:00 app[pgbackups]:
  download_progress:  486B 2014-06-22T17:01:39+00:00 app[pgbackups]:
  --------+------+------+------ 2014-06-22T17:01:38+00:00 app[pgbackups]: Started:  Sun Jun 22 17:01:38 UTC 2014
  2014-06-22T17:01:39+00:00 app[pgbackups]: pg_restore: env
  LD_LIBRARY_PATH=bin//9.3 bin//9.3/pg_restore 2014-06-22T17:01:39+00:00
  app[pgbackups]: 2014-06-22T17:01:38+00:00 app[pgbackups]: psql:
  bin//pg-latest/psql 2014-06-22T17:01:39+00:00 app[pgbackups]:  Schema
  | Name | Type | Info 2014-06-22T17:01:3 9+00:00 app[pgbackups]:
  download_progress: 486.0bytes 2014-06-22T17:01:39+00:00
  app[pgbackups]: download_progress: done 2014-06-22T17:01:38+00:00
  app[pgbackups]: Location:
  aa3c5322-1899-4811-b74e-fff91218fc6c:/tmp/wqC9ziSvIA
  2014-06-22T17:01:39+00:00 app[pgbackups]: 2014-06-22T17:01:39+00:00
  app[pgbackups]: (0 rows) 2014-06-22T17:01:39+00:00 app[pgbackups]:
  Invalid dump format: /tmp/wqC9ziSvIA/mydb.dump: HTML document text
  2014-06-22T17:01:56+00:00 app[pgbackups]: psql: bin//pg-latest/psql
  2014-06-22T17:01:56+00:00 app[pgbackups]: download_progress: start
  2014-06-22T17:01:56+00:00 app[pgbackups]: 2014-06-22T17:01:56+00:00
  app[pgbackups]: Location:
  d5f20719-b1b1-4a8f-9e92-bb45d19a5479:/tmp/S2eb3hRqgP
  2014-06-22T17:01:56+00:00 app[pgbackups]: pg_restore: env
  LD_LIBRARY_PATH=bin//9.3 bin//9.3/pg_restore 2014-06-22T17:01:56+00:00
  app[pgbackups]: (0 rows) 2014-06-22T17:01:56+00:00 app[pgbackups]:
  Started:  Sun Jun 22 17:01:56 UTC 2014 2014-06-22T17:01:56+00:00
  app[pgbackups]: pv: bin//pv-latest 2014-06-22T17:01:56+00:00
  app[pgbackups]:  Schema | Name | Type | Info 2014-06-22T17:01:56+00:00
  app[pgbackups]: --------+------+------+------
  2014-06-22T17:01:56+00:00 app[pgbackups]: download_progress:  386B
  2014-06-22T17:01:56+00:00 app[pgbackups]: 2014-06-22T17:01:56+00:00
  app[pgbackups]: download_progress: 386.0bytes
  2014-06-22T17:01:56+00:00 app[pgbackups]: download_progress: done
  2014-06-22T17:01:56+00:00 app[pgbackups]: Invalid dump format:
  /tmp/S2eb3hRqgP/mydb.dump: HTML document text
Answer: I think you want https://dl.dropboxusercontent.com/s/80vy8mm6enwsdfo/mydb.dump. See https://www.dropbox.com/help/201/en for details.


Integral Inequality $\int\limits_0^1f^2(x)dx\geq12\left( \int\limits_0^1xf(x)dx\right)^2.$

Question: Let $f:[0,1]\to\mathbb{R}$ be a continuous function such that $\int\limits_0^1f(x)dx=0$. Prove that $$\int\limits_0^1f^2(x)dx\geq12\left( \int\limits_0^1xf(x)dx\right)^2.$$
My approach as follow
Let $F(x)=\int\limits_0^xf(t)dt$.
Integrate by part we have
$$\int\limits_0^1F(x)dx=-\int\limits_0^1xf(x)dx.$$
By Cauchy-Schwarz inequality
$$\begin{aligned}
\left( \int\limits_0^{1/2}xf(x)dx\right)^2&\leq\left( \int\limits_0^{1/2}x^2dx\right)\left( \int\limits_0^{1/2}f^2(x)dx\right)=\frac{1}{24}\int\limits_0^{1/2}f^2(x)dx\\
\left( \int\limits_{1/2}^1(x-\frac{1}{2})f(x)dx\right)^2&\leq\left( \int\limits_{1/2}^1(x-\frac{1}{2})^2dx\right)\left( \int\limits_{1/2}^1f^2(x)dx\right)=\frac{1}{24}\int\limits_{1/2}^1f^2(x)dx
\end{aligned}$$
Hence $$\left( \int\limits_0^{1/2}xf(x)dx\right)^2+\left( \int\limits_{1/2}^1(x-\frac{1}{2})f(x)dx\right)^2\leq \frac{1}{24}\int\limits_{0}^1f^2(x)dx.$$
But I can't deduce the result.
Please help me. Thank in advanced.
Answer: Since $f$ has mean zero,
$$ \int_{0}^{1} x\,f(x)\,dx = \int_{0}^{1}\left(x-\frac{1}{2}\right)\,f(x)\,dx,\tag{1}$$
and by the Cauchy-Schwarz/Buniakowski inequality we have:
$$ \left(\int_{0}^{1}\left(x-\frac{1}{2}\right)\,f(x)\,dx\right)^2 \leq \int_{0}^{1}f(x)^2\,dx \int_{0}^{1}\left(x-\frac{1}{2}\right)^2\,dx \tag{2}$$
so we just have to check that:
$$ \int_{0}^{1}\left(x-\frac{1}{2}\right)^2\,dx = \frac{1}{12},\tag{3}$$
that is straightforward.
Comment: One could also notice that the $1/2$ is the optimal choice of constant.
Comment: @nbubis: if $f$ has mean zero, $\int_{0}^{1}\frac{1}{2}\,f(x)\,dx = 0$.
Comment: Must.. get.. more.. sleep :)
Comment: Where does the first line come from?
Answer: A "mechanical" way to deal with this question is to follow the proof
of Cauchy Inequality and write
\begin{aligned}
0&\leq \int_0^1 (x+\lambda f+\mu)^2\\
 &=E(f^2)\lambda^2+2\lambda E(xf) +\frac{1}{3}+\mu+\mu^2
\end{aligned}
Here $E(g)=\int_0^1 g,\;E^2(g)=(E(g))^2$. Thus
$$ \Delta_1=4 E^2(xf)-4 E^2(f)\left(\frac{1}{3}+\mu+\mu^2\right)\leq 0$$
Now treat $\Delta_1\leq 0$ as an inequality of $\mu$,
$$\Delta_2=E(f^2)\left (-\frac{1}{3}E(f^2)+4 E^2(xf)\right)\leq 0$$
If $E(f^2)=0$ then $f=0$ almost everywhere, so done. Otherwise, we have
$$ E^2(xf)\leq \frac{1}{12} E(f^2)$$


Problema na extração de texto usando PDFReader API

Question: Estou mexendo com a classe PDFreader para fazer a extração do texto de um documento PDF.
Fiz um documento bem simples para fazer um teste onde somente dou include no arquivo PDFreader.class.php e passei o caminho do PDF com a chamada citada no arquivo de exemplo dentro da pasta examples.
Quando tento rodar esse arquivo para me retornar o texto do PDF aparece o seguinte erro:

Notice: Undefined index: Font in C:\setti\www\dg\t2\PDFreader\PDFpage.class.php on line 317

Segue o código que esta no meu arquivo:

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

<?php
include ('PDFreader.class.php');

$PDF = new PDFreader();
try {
    $PDF->open('t1t.pdf');
    $text = $PDF->readText();
}
catch(PDFexception $e) {
    echo '
';
    echo "$e
\n";
}

echo "
Decoded text

\n";
foreach ($text as $row) {
    echo "$row
\n";
}
echo "
\n";
?>

Como consertar isso?
Answer: O código que você postou funciona no OS X. No site do package vemos o seguinte:

Ênfase minha: Pode ser que funcione em Windows.
E sendo a última atualização de 2010, acho que funcionar no seu sistema (C:\) vai ser... complicado.
Opções:
Fazendo esta busca, encontrei uma Q&A no Stack Overflow com várias sugestões: Is there a PDF parser for PHP?. Além das respostas visiveis, há um par de deletadas cujos links podem ser úteis aqui:

Reading the "clean" text from PDF with PHP
php.net : PDF Functions
Comment: Pois é, tava querendo um milagre pois tenho que arrumar alguma coisa para ler pdf logo, você teria algum que não seja o pdfparser???
Comment: @user1875730, atualizei a resposta com links úteis, boa sorte!


Unknown column errors because of table alias

Question: Because of truncated identifiers with more than 63 chars, causing Views to break
It causes errors like

SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'taxonomy_term_data_node__draggableviews_structure_weight_coalesce' in
  'order clause'

Goal: I want to change the table alias from _draggableviews_structure_ to _dv_
If I change
    $data['draggableviews_structure']['weight'] = array(
      'title' => t('Weight'),
      'group' => t('Draggableviews'),
      'field' => array(
        'help' => t('Display the weight value.'),
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'sort' => array(
        'help' => t('Sort entities by the draggableviews weight table field.'),
        'handler' => 'draggableviews_handler_sort',
      ),
    );

    $data['draggableviews_structure']['parent'] = array(
      'title' => t('Parent'),
      'help' => t('The parent entity id.'),
      'group' => t('Draggableviews'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
      ),
    );

  // Explain to every entity how to join with draggableviews structure table.
    $data['draggableviews_structure']['table']['join'][$info['base table']] = array(
      'handler' => 'draggableviews_join_handler',
      'left_table' => $info['base table'], // Because this is a direct link it could be left out.
      'left_field' => $info['entity keys']['id'],
      'field' => 'entity_id',
    );

to
   $data['dv']['weight'] = array(
     'title' => t('Weight'),
     'group' => t('Draggableviews'),
     'field' => array(
       'help' => t('Display the weight value.'),
       'handler' => 'views_handler_field_numeric',
       'click sortable' => TRUE,
     ),
     'sort' => array(
       'help' => t('Sort entities by the draggableviews weight table field.'),
       'handler' => 'draggableviews_handler_sort',
     ),
   );

   $data['dv']['parent'] = array(
     'title' => t('Parent'),
     'help' => t('The parent entity id.'),
     'group' => t('Draggableviews'),
     'field' => array(
       'handler' => 'views_handler_field_numeric',
     ),
   );

   // Explain to every entity how to join with draggableviews structure table.
   $data['dv']['table']['join'][$info['base table']] = array(
     'handler' => 'draggableviews_join_handler',
     'table' => 'draggableviews_structure',
     'left_table' => $info['base table'], // Because this is a direct link it could be left out.
     'left_field' => $info['entity keys']['id'],
     'field' => 'entity_id',
   );

This works. However, all of the views with draggableviews fields/sort components have disappeared. In the admin view, views complains able missing relationship, and it trying to fix them for you. If you read the fields, the view works again.
Is there a way to fix this, without manually changing everything? Is there a better way to solve it?
Answer: I've used the MD5 alias patch from that issue queue here: http://drupal.org/files/issues/views-571548_40.patch (#40) to fix that issue.
You may need to apply the patch manually to views/includes/query.inc
The good news is, if you can do that, it should fix all those alias truncation issues for you.


Python: is list() somehow inplace?

Question: I observed an order dependency when using list() that I don't understand. I'm starting with a zip mytup and I've tested 3 versions of code with the following outcomes. df_q is a regular pandas DataFrame:
#ver1
df_q.loc[list(mytup)] # first access works fine
df_q.loc[list(mytup)] # TypeError: Cannot infer number of levels from empty list

#ver2
list(mytup)
df_q.loc[mytup] # TypeError: object of type 'zip' has no len()
df_q.loc[mytup]

#ver3 works as excepted
mylist = list(mytup)
df_q.loc[mylist]
df_q.loc[mylist]

To me, since I'm getting an error only in the second call in ver1, I initially thought that list() somehow had some undocumented inplace behavior, but obviously it isn't as ver2 doesnt work. ver3 works as expected but I don't understand what's going on in 1/2.
Comment: `mytup` is a really misleading name for something that isn't a tuple.
Answer: The issue is that zip returns a zip object, which is an iterator. Most well-behaved iterators are single pass:
>>> z = zip((1,2),('a','b'))
>>> z
<zip object at 0x10193a908>
>>> next(z)
(1, 'a')
>>> next(z)
(2, 'b')
>>> next(z)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> list(z)
[]

In other words:
>>> z = zip((1,2),('a','b'))
>>> first = list(z)
>>> second = list(z)
>>> first
[(1, 'a'), (2, 'b')]
>>> second
[]

So, if you want to re-use the zipped values, you need to keep a reference around to the materialized list, just as you do in your third attempt.
Just to be clear, this isn't specific to the list function, but with anything that iterates over the zip-object:
>>> z = zip((1,2),('a','b'))
>>> d1 = dict(z)
>>> d2 = dict(z)
>>> d1
{1: 'a', 2: 'b'}
>>> d2
{}

Comment: @JohnSmith `zip` iterators are single pass, most iterators are. You can't reset them. This makes them very memory efficient, so if you *need* to use them more than once, you'll have to some materialized data structure around. Or just re-create the zip-object. Note, I would probably just do something like `my_list = zip(x, y); my_dict = dict(my_list)`
Comment: Thanks, that makes a lot of sense! Can you tell me what would be the appropriate way to reset the iterator if I wan't to e.g. list(z), dict(z) successively?

Python: is list() somehow inplace?


differences between conditional probability and dependency

Question: Sometimes, I read articles about conditional probabilities and other articles about conditional dependency. My question what is the main differences between them?
For example,
"https://en.wikipedia.org/wiki/Copula_(probability_theory)".
So, a copula is a measure of the dependency structures in the probability theory. Hence, the probability and dependency are different.
Answer: A simple search would have revelaed the answer, which is already clear from the names.

Conditional probability is a measure of the probability of an event given that another event has occurred.
Conditional dependence is a relationship between two or more events that are dependent when a third event occurs.
Comment: @thank you for your answer. Copula, for example, is a measuring method for the dependency structures. However, the mathematical expression of the copula is the probability of an event given another event.


AMD processors VS Intel Processors in virtualization and SQL tasks

Question: I need to buy a server.
This machine will be used as a virtualization host, therefore it will have a lot of v-machines sitting there using its resources.
One of those v-machines is a SQL Server that provides for our ERP which is used, intensively, by about 30 people, one automatic instance of that same ERP and one external app that provides messaging capabalities to our ERP everytime something of importance happens.
On top of that, i want to run RDS to about 20 offsite users, AD, and probably some other services like SMS messaging, and setting up our own email service...
I'm heading to a box that runs 2 AMD Opteron 6100 series (8 cores/pp), 32GB, RAID controller (512MB) and 8 SFF (500GB) in RAID 10.
Is this hardware fit to run such a setup? Any ideas, clues, thoughts?
I'm a bit worried about AMD performance when executing SQL tasks/jobs/queries...
Thanks for your help.
Comment: Product recommendations and "do my capacity planning" are illicit questions here!
Comment: Barata, I'm afraid that this question might get closed or downvoted to oblivion on the grounds that it's too subjective or maybe even not a real question. SF is more for question/answer format, not so much questions that elicit discussion.
Comment: elicit - not illicit :-)
Comment: @RyanRies I see two questions here: AMD vs. Intel, and is it enough?
Comment: Depends a little bit on which VM-techinique you are planning to use.
Comment: Not really. The technique doesnot Change the terrible IO bottleneck he has. On top, that is a low range Computer. IO wise it is REALLY low. RAM wise, too - that must a very small SQL Server.
Comment: @TomTom Depends on his application. My first VM-server-pair had 32GB, too. But there were no heavy-usage-DBs involved and I planned no more than 16 light VMs (light in terms of disk-IO).
Comment: @Nils WAit until next patch day. The last one took down our infrastructure half a day. Not sure WHAT Microsoft did ther, but exchange and SQL patches were blowing IO through the roof.
Answer: There's a lot of subjectivity to the question. What is satisfactory performance to you might not be satisfactory to someone else, like your users.
You're not likely to see significant differences between similarly-specced processors regardless of if they're AMD or Intel. You should be way more concerned about disk IO for SQL if it's a heavily written-to database.
Look into using a pass-through disk for your SQL databases. That way you don't have to suffer the I/O penalties of being inside of a VHD/VMDK.
Comment: @Nils Even WITHOUT it can perform. BUt we use a LOT MORE and a LOT FASTER discs for a machine like that. My smallest 64gb system has 8 discs and 2SSD that are transparently caching the hard discs to handlethe VM IO - and without the SSD it would be terrible in performance. And that does not include database, which uses a 10g ISCSI SAN with curretnly 18 discs for the SQL specific stuff. 8 DISCS wont work for more than a joke, regardless how you turn it, without some SSD caching in the line.
Comment: In Addition. Hyper-V in itself is very IO intensive. Put 20 machines on a Server and you get 20x the IO load. If anything, IO is nearl always the bottleneck when you get into virtualization.
Comment: Thanks Ryan. Indeed it's not a simple Q/A post. However your answer is quite helpfull and i'm gratefull for that.
Comment: @TomTom even Hyper-V can perform - if you dedicate disk-controllers to the VMs.
Answer: You're going to want to get some idea of the performance required by each planned VM, and then size your virtualization host(s) appropriately. You need to consider CPU, RAM, and IO (speed, latency, etc.) Especially latency if you're going to be serving RemoteApp off of a VM.
Realistically, you'll probably want more than one machine, and shared storage. Your concerns about the processor architecture WRT SQL are kind of off-base; you're not really asking the right questions.
Answer: 30 concurrent people are not that much.
It depends on the database design and the database make how well it handles read/write-requests.
On almost all datebases reads should come from RAM - so it is important to provide enough of that to your SQL-VM.
About AMD- the server-branch is dying out there. Apart from that CPUs don`t matter much here.
But what you need for write-requests is DISK-io. If you have no bottleneck there - ok. If you have it - invest in more RAM for your RAID-controller, and do use 15k-SAS 3,5" instead of 2,5" SFF.
Apart from that - if this is business critical - make it a cluster consisting of two identical machines.


Why are my $messages delayed one page refresh?

Question: I have a page with a very simple template:
<!DOCTYPE html>

<title>TEST REGISTRATION PAGE</title>

    <?php
        print drupal_get_form('user_register');
        print $messages;
        print $closure;
        print $main_content;
    ?>

Basically, it displays the registration form and nothing else.

I enter some bad data on the form — an already used username (admin), and no email address.
I click "create new account".
The page seems to submit and reload, but nothing has happened — no error messages are displaying.
I refresh the page (F5).
Firefox displays "to display this page, Firefox must send information that will repeat any action that was performed earlier" — so I know that my POST went through previously.
I click "resend" in that dialog window.
My error messages appear — "e-mail address field is required", "the name admin is already taken".

This occurs for all of the forms I've tested so far, not just the registration form.
Why is this happening? What can I do to fix it so that the error messages display the first time?
I'm happy to do whatever I need to do debug this, but I need some direction to start looking in. :)
Answer: Most likely the problem is that you are calling the form when the messages already have been created, which is why they don't appear. You need to call the form, earlier in the process of the page being built or get the messages, with drupal_get_messages.
What you really should do it is to create this functionality in a module and theme the page instead, of doing this in your theme. You could potentially run into many more problems like this.
Comment: OK, I think I finally might have fixed this. I've written a module called 'my_register_form' that does nothing but return `drupal_get_form('user_register')` in the `$block['content']`. I include that module via context and then the registration error messages show up correctly after submission. It seems overly complicated but it works and it lets me include the login / register forms how I want them. Thanks heaps for your help.
Answer: We solved the form validation problem, (form validation happening after the messages have been rendered, and showing up on the next request), by..
forcing the form validation in hook_node_view
/**
 * This is a fix for a bug where the validation error messages lag a
 * full request behind form submissions
 */
function your_module_node_view($node, $view_mode){
  // check that form id is the form you want
  if ( !isset( $_POST['form_id'] ) || $_POST['form_id'] != 'your_form_id' ){
    return;
  }
  // this forces validation of the form
  drupal_get_form('your_form_id');
}

Answer: I also suffered from this problem. @googletorp's answer helped me to solve it.
At the beginning of page tpl. Get the rendered content of forms i.e. for my case:
$register_form = drupal_get_form('user_register_form');
$register_form_content = render($register_form);

$form_user_pass = drupal_get_form('user_pass');
$form_user_pass_content = drupal_render($form_user_pass);

$login_form = drupal_get_form('user_login_block');
$login_form_content = render($login_form);

Then at the message print section, get the messages calling drupal_get_messages() at the page tpl. $messages is still unable to fetch the messages without another page refresh.
<?php
    $messages = drupal_get_messages('error');
    if(is_array($messages['error']) && count($messages['error'])) {
?>

                    <?php
                    foreach($messages['error'] as $item) {
                        echo '
'.$item.'
';
                    }
                    ?>

<?php
    }
?>

Then print the rendered form content at the proper section and it solved :).
Answer: Not directly a solution for the question asked, but I came across this when I was having the same problem:
If your form block is called directly from the tpl.php file (perhaps for layout reasons), then you'll get delayed messages.
I.e. I was loading a block with the following code in my template file:
$vars['contact_details'] = module_invoke('viewusercontact', 'block_view', 0);

And then rendering it in my tpl.php file.
<?php print render $contact_details ?>

Answer: I came across this issue on a Drupal 7.x installation and the problem was that the form was being loaded programmatically in HOOK_preprocess_node(). Moving it to HOOK_preprocess_page() fixed the issue.


Android save and show user preferences using custom DialogPreference

Question: I'm trying to print the value of a editText in my preferenceActivity, and for that I'm using a custom DialogPreference so the user can enter the price to filter and when he clicks "ok" it should print the filtered price in the activity. But when I click "ok" it shows me nothing, what am I missing?
public class MyDialogShow extends DialogPreference {

    private View view;
    private EditText maximo;
    private EditText minimo;
    private TextView valores;
    private Context context;
    private View v;

    @Override
    protected View onCreateDialogView() {
        // TODO Auto-generated method stub
        view= super.onCreateDialogView();

            LayoutInflater inflater = LayoutInflater.from(getContext());

            v = inflater.inflate(R.layout.pref_valor, null);

            valores = (TextView) v.findViewById(R.id.escolhaValor);

        minimo = (EditText) view.findViewById(R.id.minimo);

        minimo.addTextChangedListener(new TextWatcher() {
            boolean isEdiging;
            private String current = "";

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

                if (!s.toString().equals(current)) {
                    minimo.removeTextChangedListener(this);

                    String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance().getCurrency().getSymbol());
                    String cleanString = s.toString().replaceAll(replaceable, "");

                    double parsed;
                    try {
                        parsed = Double.parseDouble(cleanString);
                    } catch (NumberFormatException e) {
                        parsed = 0.00;
                    }
                    String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));

                    current = formatted;
                    minimo.setText(formatted);
                    minimo.setSelection(formatted.length());
                    minimo.addTextChangedListener(this);
                }
            }
        });

        maximo = (EditText) view.findViewById(R.id.maximo);

        maximo.addTextChangedListener(new TextWatcher() {
            boolean isEdiging;
            private String current = "";

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().equals(current)) {
                    maximo.removeTextChangedListener(this);

                    String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance().getCurrency().getSymbol());
                    String cleanString = s.toString().replaceAll(replaceable, "");

                    double parsed;
                    try {
                        parsed = Double.parseDouble(cleanString);
                    } catch (NumberFormatException e) {
                        parsed = 0.00;
                    }
                    String formatted = NumberFormat.getCurrencyInstance().format((parsed / 100));

                    current = formatted;
                    maximo.setText(formatted);
                    maximo.setSelection(formatted.length());
                    maximo.addTextChangedListener(this);
                }
            }
        });

        return view;
    }

    @Override
    public void onClick(DialogInterface dialog, int which){

        if(which == DialogInterface.BUTTON_POSITIVE) {

            SecurePreferences mSessao = new SecurePreferences(getContext(), "sessao");
            mSessao.put("filtro_pedidos_valor", minimo.getText().toString());
            mSessao.put("filtro_pedidos_valor_maior", maximo.getText().toString());

            valores.setText(mSessao.getString("filtro_pedidos_valor") + " - " + mSessao.getString("filtro_pedidos_valor_maior"));

            System.out.println("VALOR >>> " + mSessao.getString("filtro_pedidos_valor") + " - " + mSessao.getString("filtro_pedidos_valor_maior"));

        }else if(which == DialogInterface.BUTTON_NEGATIVE){

            System.out.println("CANCEL BUTTON");

        }
    }

    public MyDialogShow(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        super.setDialogLayoutResource(R.layout.dialog_layout);

        //super.setDialogIcon(R.drawable.ic);
    }

    public MyDialogShow(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        super.setDialogLayoutResource(R.layout.dialog_layout);

        //super.setDialogIcon(R.drawable.ic);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        persistBoolean(positiveResult);
    }

}

pref_valor.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2"
        android:gravity="center"
        android:paddingTop="10dp"
        android:paddingBottom="10dp">

        <TextView
            android:id="@+id/filtrarValor"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="Entre o valor"
            android:textColor="@color/black"
            android:textSize="@dimen/detalhe_cliente"
            android:entries="@array/listentries"
            android:entryValues="@array/listvalues"
            android:layout_weight="1"
            android:padding="10dp"
            android:gravity="left" />

        <TextView
            android:id="@+id/escolhaValor"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text=""
            android:textColor="@color/blue_dark"
            android:textSize="@dimen/detalhe_cliente"
            android:layout_weight="1"
            android:padding="10dp"
            android:gravity="right" />

    </LinearLayout>

</LinearLayout>

pref_xml:
<PreferenceCategory android:title="@string/fValorTitulo">

    </PreferenceCategory>

Answer: Declare current outside of the listener. Below the class declaration if you want to access it through out the class.
Also read up on scope:
http://www.java-made-easy.com/variable-scope.html
http://code.tutsplus.com/tutorials/learn-java-for-android-development-java-syntax--mobile-2612
Comment: I've updated the question and debugged it, I'm getting a null LayoutInflater, why?
Comment: Go read documentation. It's the best way to learn!
http://developer.android.com/reference/android/view/LayoutInflater.html


submit button event using javascript

Question: Hi I've an html page with submit button. I want to call that submit button event froma a different page using javascript.
is it possible? Can some one give me any example. I'm searching for it from hours.
thank you,
Comment: What do you mean by "from a different page"? What's the relationship between the two pages?
Comment: i mean just i want to pass credential to my authentication page (third party) and want to get response by using javascript
Answer: You can use form.submit() method.
<code>document.forms["myform"].submit();
</code>
Comment: form.submit() wil call current form right? but i want to call different page submit button
Comment: actually that page contains submit button. I want to call that submit button click event. Is it possible?
Comment: Or you require something like this? http://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit
Comment: no actually that is a third party authentication page. Instead of going there and validating just i want to pass credentials from my page and trying to get respoinse. Hope you got it. And it is not a popup window just it is a site

submit button event using javascript


PCIe x8 NIC in PCIe x16 slot

Question: I have a motherboard with only one x16 PCIe slot and no x8 slots. I am buying a NIC with very specific configuration, but it is available for x8 slots only. Can I plug a x8 card in a x16 slot? I have googled this question and this seems quite possible. However, I need answer from an expert. Also, are there any performance implications?
Answer: What should be: The PCIe spec states that all slots start at 1x/v1.0 and negotiate how many lanes they can use and what clock speed. It shouldn't matter which supports more lanes/clock, some slots are designed to take larger cards and smaller cards fit in larger slots. Whatever the highest spec both sides can communicate at (both the number of lanes and the clock/version), that is the speed that will be negotiated and used. Endpoints can support 1x, 2x, 4x, 8x, 16x, and 32x, though there are no slots specifically for 2x and 32x. Speed is specified by major version number (2.5, 5.0, 8, 16 GT/s).
What really is: Usually what should happen is what actually happens. But there are quite a few boards (especially enthusiast boards) that do not follow spec. Some motherboards will not use anything but a 16x video card in their first PCIe slot. Others will not auto-negotiate correctly (commonly falling back to less lanes - this seems particularly common with 2x cards that negotiate to 1x speed). In server grade hardware these problems are very rare, but it happens. If both the system/motherboard are from the same manufacturer as the card, you should be able to contact their support and find out if it's a supported configuration (if they don't know or can't answer it's a huge redflag and you should consider not buying from them/returning). Also, try searching your particular motherboard and see if anyone has reported a problem.
Comment: +1 for your "what really is" - had a few (not server grade) motherboards with x16 slots that wouldn't take anything but graphics cards
Comment: Aye, many consumer board BIOSes are broken. I hope that whatever he used to put a x8 NIC in will be better.
Comment: Awesome! This not only answers the original question, but also anticipates pretty much all follow up questions - and answers these too=) Thanks!
Comment: I plugged my ASUS ROG STRIX RX 460 GAMING that has PCIe 3.0 x8 and my motherboard has PCIe 3.0 x16 and it did not work. so I guess it is just a hit or miss situation.
Answer: Yes, you can plug in in and it will work fine.

Long version:
Three things are important for PCIe connection:

PCIe version (v1, v2 or v3. Lowest common version is used)
Number of lanes on the card you plug into a connector (e.g. x1, x4, x8 or x16)
Number of lanes supplied to the connector (e.g. x1, x4, x8 or x16)

Any combination of card and slot/connector_on_MB is possible.

Even longer version:
A x1 card will work fine in a x1 slot.
A x1 card will also work fine in a x4 slot. But it will be limited to x1 speeds.
A x1 card will also work fine in a x8 slot. But it will be limited to x1 speeds.
A x1 card will also work fine in a x16 slot. But it will be limited to x1 speeds.
A x4 card will work in an x1 slot, but will be limited to x1 speeds.
A x4 card will also work fine in a x4 slot.
A x4 card will also work fine in a x8 slot.  But it will be limited to x4 speeds.
A x4 card will also work fine in a x16 slot. But it will be limited to x4 speeds.
A x8 card will work in an x1 slot, but will be limited to x1 speeds.
A x8 card will also work fine in a x4 slot. It will be limited to x4 speeds.
A x8 card will also work fine in a x8 slot.
A x8 card will also work fine in a x16 slot. But it will be limited to x8 speeds.
A x16 card will work in an x1 slot, but will be limited to x1 speeds.
A x16 card will work in an x4 slot, but will be limited to x4 speeds.
A x16 card will work in an x8 slot, but will be limited to x8 speeds.
A x16 card will work in an x16 slot.
There are several kinds of PCIe connectors/slots on motherboards.
Slots allowing up to x16 lanes are most common. However the same physical connector can be used for x1, x4, x8 and x16. In many server class motherboards you will find slots which physically allow x16 cards, but with only 8 lanes connected.
The reverse is also possible. If you take a x1 connector and use a saw to open the end of the slot then you can physically connect a larger card and it should work. I know at least one company which does this to put PCIe x16 cards in PCIe x1 slots. (They use the PCIe x16 slots for other cards).
Answer: I have seen several posts on the web on installing PCIe x8 graphic card on server motherboad.
I have a IBM X3200 M3 (Xeon 3430 Quad Core) server.  Though the server has onboard graphics, I could install successfully a PCIe x8 graphic card.
ASUS GT-730-SL-2GD3-BRK
It takes some time (30-60 seconds) for IBM IMM to show up but works like a charm.
Trust this helps those who would like to convert their server into a kind of workstation.
Comment: I think the more complete and generalised answer above may be more applicable than this answer.

PCIe x8 NIC in PCIe x16 slot


Tile view for ListView in WPf

Question: How to simulate a tile view for a ListView in WPF?

I was trying the example shown here. But I can't get to the right solution... But I don't want to use that solution as I it's too much specific. So how will be the way to accomplilsh that?
EDIT: I'm trying this now and seems to work...
<ListBox ItemsSource="{Binding Path=ListObservableUsers, ElementName=AdminWindow}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <Image Source="{Binding Path=Picture}"></Image>

                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Where the ElementName=AdminWindow comes from <Window .... x:Name="AdminWindow"
And I created my own ObservableCollection<MyUser>
    public class MyUser
{
    public MyUser(int id, string dni, Bitmap picture)
    {
        Id = id;
        Dni = dni;
        Image img = new Image();
        FPhiMultipleSources.FromBitmapImage(img, picture);
        Picture = img.Source;
    }

    public int Id { get; set; }
    public string Dni { get; set; }
    public ImageSource Picture { get; set; }
}

...
public UCAdminMain()
public UCAdminMain()
{
    ListObservableUsers = new ObservableCollection<MyUser>();

    InitializeComponent();
    uiCurrent = SynchronizationContext.Current;

    // Create users to add with its image
    ....
    ListObservableUsers.Add(...);
}

And now I'm trying to put them inside a wrap panel. With no luck right now... Any ideas?
Answer:  <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>

try to use a wrappanel
Answer: An ItemsControl with a WrapPanel as the ItemsContainer would probably be a good fit for what you are trying to do.

Tile view for ListView in WPf


$x_1:=1$ , and $x_{n+1}:=x_n+\cos(x_n) ,\forall n \in \mathbb N$ , does $(x_n)$ converge ?

Question: If $x_1:=1$ , and $x_{n+1}:=x_n+\cos(x_n) ,\forall n \in \mathbb N$ , then is it true that the sequence $(x_n)$ is convergent ? If it does , what is the limit ?
Answer: Hint: Show that $f(x)=x+\cos(x)$ is increasing, that $x_2=1+\cos(1) \geq x_1$, and that $x_1<\frac{\pi}{2}$. Then show that $x_n$ is increasing, and $x_n\leq \frac{\pi}{2}$ for all $n$.
Comment: @DanielV: We have $x_2\geq x_1$, hence $x_3=f(x_2)\geq f(x_1)=x_2$, etc...
Comment: Nevermind , it is increasing.
Answer: Hint:
With induction you can prove that $1\leq x_{n}<\frac{1}{2}\pi\wedge x_{n}<x_{n+1}$
for each $n$. So the sequence is increasing and bounded.
Answer: If you have the contraction mapping principle, you can use it on $T(x) = x + \cos(x)$ on an appropriate interval containing $x = {\pi \over 2}$.
Alternatively, you can show $|x_n - {\pi \over 2}|$ decreases geometrically for $n$ large enough... if $y_n = x_n - {\pi \over 2}$, your recursion becomes $y_{n+1} = y_n - \sin(y_n)$, and $\sin y_n \sim y_n$ for small $y_n$.
Answer: Similar to the ideas given in the other answers, one can show the result using the following two properties:

$0\leq x \leq \pi/2$ $\Rightarrow$ $0 \leq x+ \cos(x) \leq \pi/2$.
$cos(x)\geq 0$, for $x\in[0,\pi/2]$.

To prove the first point, use
$x + \cos(x) = x + \sin(\pi/2-x)$ and the fact $\sin(x) \leq x$ for $x \geq 0$.
The first property says that $x_n \in [0,\pi/2]$. Used with the first, the second one proves that $x_n$ is increasing and hence convergent.


Solution to $\frac{n(n+1)}{2} \leq x<\frac{(n+1)(n+2)}{2}$ when given $x$

Question: I tried to find a solution to
$$\frac{n(n+1)}{2} \leq x<\frac{(n+1)(n+2)}{2} \tag0$$
when $x$ is given $(n \in \mathbb N_0, x \geq 0)$.
This inequality means $n$-th triangular number is the greastest triangular number less than or equal to $x$.
There is one and only one $n \in \mathbb N_0$ given $x \geq 0$.
$$\text{if}\; x \in [0, 1),\; n = 0$$
$$\text{if}\; x \in [1, 3),\; n = 1$$
$$\text{if}\; x \in [3, 6),\; n = 2$$
$$...$$
Split the inequality in two, we get
$$\frac{n(n+1)}{2} \leq x   \tag1$$
$$x<\frac{(n+1)(n+2)}{2}   \tag2$$
Focus on $(1)$. Using quadratic formula for $(1)$,
$$\frac{-1 - \sqrt{8x+1}}{2} \leq n \leq \frac{-1 + \sqrt{8x+1}}{2}   \tag{$1.1$}$$
Note that $n \in \mathbb N_0$, maximum value of $n$ is
$$n = \lfloor \frac{-1 + \sqrt{8x+1}}{2} \rfloor   \tag{1.2}$$
and this is the solution to the original inequality $(0)$. Only maximum value is allowed, because if $n=$ (value less than the maximum) is the solution, then $n=$ (the maximum value) is another solution, which breaks the uniqueness of $n$.
Similarly using quadratic formula for $(2)$,
$$n < \frac{-3 - \sqrt{8x+1}}{2}\; \lor\; n > \frac{-3 + \sqrt{8x+1}}{2}   \tag{$2.1$}$$
And the solution (the minimum value) is
$$ n =
     \begin{cases}
       \lceil \frac{-3 + \sqrt{8x+1}}{2} \rceil &\quad\text{if}\; \frac{-3 + \sqrt{8x+1}}{2} \not \in \mathbb N_0\\
       \frac{-3 + \sqrt{8x+1}}{2} + 1 &\quad\text{if}\; \frac{-3 + \sqrt{8x+1}}{2} \in \mathbb N_0\\
    \end{cases}\tag{$2.2$}$$
Actually $(1.2)$ and $(2.2)$ are the same thing with different notation.
Interestingly, I found
$$n = \lfloor \sqrt{\frac{\lfloor \sqrt{2x} \rfloor}{\lfloor \sqrt{2x} \rfloor +1}} \cdot \sqrt{2x} \rfloor   \tag3$$
I cannot find any relationship between $(3)$ and $(1.2)$ or $(3)$ and $(0)$, but it seems like $(3)$ is also a solution.
(I brute-forced for $x \in \mathbb{N}_0$, $x \leq 50000000$)
So this is my question: Is $(3)$ the solution to $(0)$?
P.S.
Modify $(0)$ slightly,
$$n(n+1) \leq 2x < (n+1)(n+2) \tag{0.1}$$
and substitude $X = 2x$
$$n(n+1) \leq X < (n+1)(n+2) \tag{0.2}$$
$$n = \lfloor \sqrt{\frac{\lfloor \sqrt{X} \rfloor}{\lfloor \sqrt{X} \rfloor +1}} \cdot \sqrt{X} \rfloor   \tag{3.1}$$
Now the problem is more simple: Is $(3.1)$ the solution to $(0.2)$?
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognize and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: The expression on the left is the sum of the numbers from $1$ to $n$ and the expression on the right is the sum of the numbers from $1$ to $n+1$.
Answer: Well, by solving:

$$x=\frac{\text{n}\left(\text{n}+1\right)}{2}\space\Longleftrightarrow\space\text{n}=\frac{\pm\sqrt{1+8x}-1}{2}\tag1$$
$$x=\frac{\left(\text{n}+1\right)\left(\text{n}+2\right)}{2}\space\Longleftrightarrow\space\text{n}=\frac{\pm\sqrt{1+8x}-3}{2}\tag2$$

We can see that we have the following solutions:

$$\text{n}=-\frac{1}{2}\space\wedge\space x=-\frac{1}{8}\tag3$$
For $-\frac{1}{8}<x<0$:
$$-\frac{\sqrt{1+8x}+1}{2}\le\text{n}\le\frac{\sqrt{1+8x}-1}{2}\tag4$$
For $x\ge0$:
$$\frac{\sqrt{1+8x}-3}{2}<\text{n}\le\frac{\sqrt{1+8x}-1}{2}\tag5$$

And for solving $\text{k}^2=1+8x$, such that $\sqrt{1+8x}\in\mathbb{N}$, you can see that:

$$x=\text{c}_1\left(1+2\text{c}_1\right)\space\wedge\space\text{k}=1+4\text{c}_1\tag6$$
Where $\text{c}_1\in\mathbb{Z}$
$$x=2\text{c}_2^2+3\text{c}_2+1\space\wedge\space\text{k}=3+4\text{c}_2\tag7$$
Where $\text{c}_2\in\mathbb{Z}$

So, we can see two cases for $x\ge0$:

$$\frac{1+4\text{c}_1-3}{2}=2\text{c}_1-1<\text{n}\le2\text{c}_1=\frac{1+4\text{c}_1-1}{2}\tag8$$
$$\frac{3+4\text{c}_2-3}{2}=2\text{c}_2<\text{n}\le1+2\text{c}_2=\frac{3+4\text{c}_2-1}{2}\tag9$$
Comment: This solution also works but the question is whether my solution is valid or not.
Comment: @JiwooPark As Andreas pointed out, yours is wrong.
Comment: @JanEerland How are you so sure that the OP solution is wrong? Do you have a counterexample?


How to declare this variable

Question: I am working on a app using App Lab (code.org). I am sorry if this is a very easy fix. I started javascript just 3 months ago and this is my first project.
I want the countdown to start once they click button "start_city_game_button" however I am getting this error
setInterval() callback parameter value (1000) is not a function

and
setInterval() milisecond parameter value (undefined) is not a number.

These errors appear in line 2.
var city_time = 60;
var city_time_counter = setInterval(1000);

function cityTimer() {
city_time = city_time -1;
  clearInterval(city_time_counter);
  }
}

I expect the timer to start once level has been started, however the time actually starts when the app starts. I have gone through many drafts of this code to find the correct anwser but I cannot find the way.

onEvent("back_mainscreen", "click", function() {
  setScreen("start_screen");
});
onEvent("instructions", "click", function() {
  setScreen("instructions");
});
onEvent("startgame", "click", function() {
  setScreen("city_screen");
});

// City Code
var city_tries = 0;
var city_time = 60;
var city_time_counter = setInterval(1000);

onEvent("start_game_city_button", "click",function() {
city_time = city_time -1;
console.log(city_time);
setText("second_city_time", city_time);
  if (city_time === 0) {
  setScreen("city_screen");
  clearInterval(city_time_counter);
  }
});

  onEvent("start_game_city_button", "click", function() {
  console.log("CONSOLE: Player Started City Level");
  console.log(city_tries);
  setScreen("city_game_screen");
  city_tries = city_tries + 1;
});

var score = 0;
onEvent("deer", "click", function() {
  setPosition("deer", randomNumber(50,240), randomNumber(50, 400));
  score = score + 1;
 setText("score_label", score);
});
// Ocean Code
var ocean_tries = 0;
onEvent("ocean_start_button", "click", function() {
    ocean_tries = ocean_tries + 1;
  console.log("CONSOLE: Player Started Ocean Level. Try");
    console.log(ocean_tries);
});
Comment: You aren't passing the function to be called to `setInterval`.
Comment: Check out the [documentation](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) for `setInterval`
Comment: First argument needs to be the function: `setInterval(cityTimer, 1000)`
Answer: The first parameter to setInterval is a function. And second parameter is amount of time.
var city_time_counter = setInterval(cityTimer,1000);

If you want the timer to start on click then attach a listener to the element and setInterval in that.
document.getElementById("start_city_game_button").addEventListener('click',()=>{
    city_time_counter = setInterval(1000);
})

And also if you need to decrease variable by 1 you can use a shorthand for that.
city_time = city_time -1;

The above line is same as
city_time--;

Comment: I need to define cityTimer. How do I do that? Thanks
Comment: @pdxryanpdx Your question is clear what is **cityTimer**
Comment: cityTimer is a 60 second timer
Comment: @pdxryanpdx Then your code should work. If its not working then create a snippet to show the actual problem.
Comment: https://gyazo.com/895bc60c53d90c0cf74ca6e4649acc59 thats my code. If you want, I can add all my code but it is very messy
Comment: ^^ is this what you meant as a snippet?
Comment: @pdxryanpdx No. Go to edit and create a snippet using **<>** sign
Comment: added snippet :)
Comment: I think I did this correctly. Please confirm. Thanks -pdx
Comment: @pdxryanpdx What is `onEvent`. Are you creating this on a particular platform?
Comment: I am using Code.org's AppLab
Comment: @pdxryanpdx You didn't mentioned that anywhere in the post. Please read this [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Comment: Will do. However I did include that. First line
Comment: what would you like me to do?
Comment: @pdxryanpdx Give me link where I could see the non-working code and test it.
Comment: Here is the link https://studio.code.org/projects/applab/hPo0MX3e_e53KOIdkfpjE8MIqxAyoPdmh3UEYOpigxE

How to declare this variable


Probability of one followed by another

Question: I am working on my homework and have been stuck on this problem for two hours:
There are 39 chocolates in a box, all identically shaped. There are 16 filled with nuts, 13 with caramel and 10 are solid chocolate. You randomly select one piece, eat it, and then select a second piece. Find the probability of selecting a solid chocolate, followed by a caramel chocolate. Write your answer as a fraction in the form a/b.
I do have the answer, it's 130/1482, or 5/57, however I don't know how this answer was made.
An explanation on how to do this would be very much appreciated. Unfortunately my teacher doesn't provide formulas for what we learn.
Answer: Hints:

What is the probability that the first piece is solid chocolate?
Given that the first piece was solid chocolate, what are the remaining $38$ pieces?
Given that the first piece was solid chocolate, what is the probability that the second piece is caramel chocolate?
Combining these results, what is the joint probability that the first piece is solid chocolate and the second piece is caramel chocolate?
Answer: We know there are $39$ chocolates total. $10$ of these are solid chocolate, and thus the probability of your first piece being solid is $10/39$.
Afterwards, we know $38$ chocolates remain, $13$ of which are caramel. Thus, there is a $13/38$ probability to pick caramel the second time.
Therefore, the probability you seek is the product of these two since you did them in sequence, and that yields
$$\frac{10}{39} \cdot \frac{13}{38} = \frac{130}{1482} = \frac{5}{57}$$

An equivalent way to work this out, if the above doesn't feel quite intuitive to you, is this... In how many ways can you pick a chocolate, have it be solid, then pick another, and have it be caramel? That answer is $13 \cdot 10$ since you have $13$ choices for one, and $10$ for the other.
Then consider how many ways in which you could pick two chocolates - in general, with no restrictions. That would be $39 \cdot 38$, since you have $39$ to start with, and then $38$ since you took one away.
We know that
$$\text{probability of an event} = \frac{\text{# of ways that event can occur}}{\text{# of total possible events}}$$
Therefore, the probability you seek is
$$\frac{13 \cdot 10}{39 \cdot 38}$$
which gives our answer from before.

Probability of one followed by another


roots of a polynomial inside a circle

Question: I am asked to show that for $n$ larger or equal to $2,$ the roots of $1 + z + z^{n}$ lie inside the circle $\|z\| = 1 + \frac{1}{n-1}$
Attempt1: Induction
for the case $n = 2,$ the roots of $1 + z + z^{2}$ lie inside the circle of radius $2.$ Now we consider $1 + z + z^{n+1},$ if i can factor this into $(1 + z + z^{n})q(x),$ then i assume the answer will follow from the roots of $q,$ but i can't see the factorization.
Thanks in advance.
Comment: It's a classic situation for Rouché's theorem.
Comment: oh sorry forgot to mention. I am supposed to show this without the theorem
Answer: For real $x>1+\frac{1}{n-1}$ then $$x^n = (1+(x-1))^n> 1+n(x-1) = x+(n-1)(x-1)> x+1$$
Now if $z^n+z+1=0$ then $\|z\|^n = \|z+1\| \leq \|z\|+1$. So, with $x=\|z\|$, we have $x^n\leq x+1$, so $\|z\|=x\leq 1+\frac 1{n-1}$.
Comment: oh the Bernoulli inequality...thanks
Comment: excellent! Could you clarify the $(1 + (x-1))^{n} > 1 + n(x-1)$ inequality?
Comment: Don't really need to think in terms of Bernoulli since $x-1>0$ and $n$ is an integer, and, for $a>0$, binomial theorem shows $(1+a)^n> 1+\binom{n}{1}a = 1+na$. Bernoulli is only "interesting" because it is true for $a\geq -1$...
Comment: Thomas, i am trying to apply the same principle to the roots of $1 + nz + z^{n}$ and to show that they lie inside $\|z\| = 1 + \frac{2}{(n-1)}.$ So for a real number outside of that range, i get $x^{n} > x + 2$ for $n > 2.$ Now looking at the equation and setting $\|z\| = x,$ i get $x^{n} \leq 1 + nx.$ My question is how should i relate these two results to get the contradiction? THanks
Comment: Doesn't seem to work in that case.  @ciao
Answer: Assume that a root $w$ of your polynomial lies outside the disk $\|z\|\leq \frac{n}{n-1}$. Then:
$$ \|w^n\| = \|w+1\|, \tag{1}$$
but, due to the following stronger version of the Bernoulli inequality, the LHS is greater than:
$$\left(1+\frac{1}{n-1}\right)^n \geq e\left(1+\frac{1}{2n-1}\right),$$
while the RHS is at most $2+\frac{1}{n-1}$, so the equality in $(1)$ cannot hold, contradiction. By the same way you can also prove a little tighter bound, i.e. that all the roots of your polynomial lies inside the disk
$$\|z\|\leq 1+\frac{7}{10(n-1)}.$$
Comment: That's not an obvious application of Bernoulli. Bernoulli, at least as defined on [Wikipedia](http://en.wikipedia.org/wiki/Bernoulli's_inequality), is $(1+x)^n\geq 1+xn$ for $x\geq -1$.
Comment: @ThomasAndrews: all right, it is a consequence of the fact that $a_n=\left(1+\frac{1}{n}\right)^{n+1/2}$ decreases towards $e$. I used to call it "Bernoulli inequality" anyway, but probably I am making an improper use of the words, thank you for pointing that out.
Comment: Ah, yes, I was unaware of that theorem. :)

roots of a polynomial inside a circle


Elasticsearch: Stem problem for polish on/ona

Question: I'm new in elasticsearch and having trouble with polish using elasticsearch search query, for example on/ona (means men/women in polish). The problem is if i use standard analyzer, it seems to understand men/women filter and return correct records, but when i tried "on", it will include both on and ona in returned records.
I tried using https://www.elastic.co/guide/en/elasticsearch/reference/1.7/analysis-keyword-marker-tokenfilter.html but it didn't work also.
Have anyone been in this situation before ? Can someone explain to me how this work and do u guys have solution for this ?
I tried
<code>index :
    analysis :
        analyzer :
            myAnalyzer :
                type : custom
                tokenizer : standard
                filter : [lowercase, protwords, porter_stem]
        filter :
            protwords :
                type : keyword_marker
                keywords : [ona]
</code>
I expected if i search for "on", it only appears records with "on" but not "ona" and vice versa.
Answer: You can integrate Lucene IK analyzer into elasticsearch with IK Analysis plug-in, and support custom dictionary.
You can add the segmentation you need in the custom dictionary.
https://github.com/medcl/elasticsearch-analysis-ik
I hope it will help you.
Comment: Thanks for the answer, but i was hoping if there was some filters or some coding that helps since involving a whole new analyzer is a bigger hack for me. Integration will need a lot of affects to works and tests to make sure it only affects the polish issue.


Confusion over terminology SSH, Shell, Terminal, Command Prompt and Telnet

Question: I don't usually use SSH if I can get away with it, but if I have to I do of course, and I've seemingly done this for years while still managing to remain slightly confused about these different terms ... from my basic research, this is my understanding, could someone verify/correct this?

Telnet ... before SSH, not secure
SSH ... ( secure shell ) the general name of the system/protocol
Shell ... short name for SSH
Command Line/Command Prompt ... the windows version
Terminal ... the Unix version, also used by apple.

Two further questions:

What is the Linux version commonly called, is it just called SSH ?
What is bash ?

EDIT ... not 100% convinced about the structure of my question above ... note to reader the above definitions to a certain extent turned out to be a bit off, see the answers below for better definitions
Answer:
Telnet provides the ability to communicate with a service, nothing more nothing less. If that service happens to be a shell on a server, great, but it's not always. I often use telnet to send a malformed HTTP request manually, or to manually run commands against an SMTP server.
SSH is way more than just a way of logging on to a server remotely. It can be used as a proxy to access remote services from your local computer, and it can be used as a protocol to run other protocols over (like scp)
A Shell is the name given to a command-line interpreter that runs on a computer to figure out what you're wanting to do and tries to do it. This could be sh, bash, csh, tcsch or even command.com
Command Line is the DOS shell, usually associated with Microsoft operating systems.
A terminal is ambiguous. It could be the OS X name for the shortcut to their shell. It could also be a physical thing that was used to interface with the shell of a multi-user Unix server (a popular one is the VT-100)

What is the Linux version commonly called, is it just called SSH ?

SSH is just a protocol that can access the shell of the server. It is extremely common, but there's also the older and insecure rsh or you can even log in to your Linux server with telnet if you're so inclined.

What is bash ?

It's a shell
Answer: You've got a small learning curve ahead of you:

A command line / command prompt is simply one way that programs present themselves to the user; via a CLI (command line interface). The other way is through a GUI (graphical user interface). Many programs have both kinds: you can choose which to use, graphical or command-line. It's a matter of taste. An example which offers both options is "zip". On Windows, there's the Winzip GUI as well as the zip CLI.
A shell is a particular kind of command line program: It's the "desktop" of the command line. It runs the command line and makes it all happen. It responds to what you, the user do (ie. type). On Unix, bash is the most popular shell. On Windows it's... cmd.exe? I'm not sure. Not my area of expertise.
A terminal is a bridge between the GUI and CLI worlds: it's a GUI program that starts a shell and lets you use CLI apps within its graphical window. Now, on OS X, the terminal program provided by Apple happens to be called Terminal, but that's a fluke. On Windows it's... Console, I think? There are many other terminal apps out there; xterm, etc. So, when you take your mouse and click the terminal icon, the computer launches two programs for you: the terminal (Terminal on a Mac), and the shell (bash, usually).

(Finally, you ask about ssh and telnet. You should always, always use ssh. Really, always. If anyone tells you not to and says not to worry, etc., you should demote your opinion of them.)
Both ssh and telnet are two command-line programs that make a network connection to another computer, and give you the command-line on that computer. So they can seem identical.
Telnet, though, is really just a network debugging tool. Anyone can eavesdrop on your telnet connection and see everything you're doing. Ssh, on the other hand, works like you'd expect. You connect to some other computer, and your communication over the network stays private.


GRE tunneling using Open vSwitch

Question: I am trying to implement tunneling as described here with the following setup (without any success):

ho1 is a host only interface. I want to connect Nested Guest 11 and Nested Guest 21.
I have read some other tutorials like:
https://blog.scottlowe.org/2013/05/07/using-gre-tunnels-with-open-vswitch/
http://networkstatic.net/open-vswitch-gre-tunnel-configuration/
https://costiser.ro/2016/07/07/overlay-tunneling-with-openvswitch-gre-vxlan-geneve-greoipsec/#.YIHTG9JR2Uk
but I'm clearly missing something. I think I'm doing something wrong with those tap devices used here.
UPDATE
Guest1 (network interfaces)
lo               UNKNOWN        127.0.0.1/8 ::1/128
ens33            UP             192.168.41.140/24 fe80::4f54:fbff:6d87:b5a7/64
ens34            UP             192.168.239.128/24 fe80::761f:aa88:a28a:aeba/64
virbr1           DOWN           192.168.100.1/24
virbr1-nic       DOWN
virbr0           DOWN           192.168.122.1/24
virbr0-nic       DOWN
virbr2           DOWN           192.168.10.1/24
virbr2-nic       DOWN
vboxnet0         UP             192.168.56.1/24 fe80::800:27ff:fe00:0/64
ovs-system       DOWN
br0              DOWN
tap0             DOWN           10.1.1.1/8 fe80::9401:52ff:fe46:86e6/64
br1              DOWN

ovs-vsctl show (I have removed other ports right now)
    Bridge br1
        Port br1
            Interface br1
                type: internal
    Bridge br0
        Port br0
            Interface br0
                type: internal
    ovs_version: "2.15.0"

According to this I should add a tap interface to br0, this command: ovs-vsctl add-port br0 tap0. I created tap0 with this command: ip tuntap add mode tap tap0. Here is the problem. I don't know what IP address I should use for the tap, or should I even assign it an address? and then how to connect it to the nested guest. I use VirtualBox for the nested guests and I tired to attach to bridge adapter on VirtualBox. In this case the nested guest didn't get and IP address.
Another thing that I don't understand from the picture here, is that how br0 is connected to the outside world (transport network) if I don't add eth0 to br0?
UPDATE 2
I also tried to use hostonly interface vboxnetX for the nested guest. In this case the nested guest had an IP address but when I added vboxnetX to br0 I lost connection between the guest and the nested guest.
Comment: You might want to [edit] your question to get a little more specific than "without success" - we cannot see your configuration, logs and test results.
Comment: @anx I have update the question. If there is any particular info that I should add please let me know.
Answer: I got it working. This answer helped me. I had two problems with my config.
First, I should have added an IP address for the nested guests. With tap0 up and connected to the nested guest, I configured a static IP for the nested guest.
Second, I noticed that I have a duplicate MAC address. That was because I had cloned the Guest1 after the installation of the Nested Guest 11, so Nested Guest11 and Nested Guest21 had the same MAC address. I changed the MAC address of Nested Guest21 and tried again.
It didn't worked at first. I was forced to restart Guest1 because of a crash. After that I tried again. This time the nested VMs were able to ping each other.
My configuration:
Guest 1
ovs-vsctl show
Bridge br0
    Port gre0
        Interface gre0
            type: gre
            options: {remote_ip="192.168.239.129"}
    Port tap0
        Interface tap0
    Port br0
        Interface br0
            type: internal
ovs_version: "2.15.0"

ip -br a
lo               UNKNOWN        127.0.0.1/8 ::1/128
ens33            UP             192.168.41.140/24 fe80::4f54:fbff:6d87:b5a7/64
ens34            UP             192.168.239.128/24 fe80::761f:aa88:a28a:aeba/64
virbr2           DOWN           192.168.10.1/24
virbr2-nic       DOWN
virbr1           DOWN           192.168.100.1/24
virbr1-nic       DOWN
virbr0           DOWN           192.168.122.1/24
virbr0-nic       DOWN
vboxnet0         DOWN
ovs-system       DOWN
br0              DOWN
gre0@NONE        DOWN
gretap0@NONE     DOWN
erspan0@NONE     DOWN
gre_sys@NONE     UNKNOWN        fe80::989f:9eff:fe5d:d7ce/64
tap0             UP             fe80::9401:52ff:fe46:86e6/64

Nested Guest11

Guest2
ovs-vsctl show
Bridge br0
    Port tap0
        Interface tap0
    Port gre0
        Interface gre0
            type: gre
            options: {remote_ip="192.168.239.128"}
    Port br0
        Interface br0
            type: internal
ovs_version: "2.15.0"

Nested Guest21

Forgot to add that in this case too, there is no connection between guest and nested guest, which I think is expected.

GRE tunneling using Open vSwitch


IIS Optimization

Question: What kind of optimization (performance or whatever) do you use when going live with IIS (on windows 2003) ?
Currently, I use 1 application pool per web site, but I think I can do more :)
Comment: I tend to think about giving the images and css directory their own pool also as it just keeps active processing separate from file serving
Answer: Even on large banks, I've rarely (can't remember when) done any optimizations on IIS that weren't just the addition of modules. I keep all the defaults.

Dynamic and Static Compression
Set Expires dates on Static content, images, JS, etc
Answer: Why would you consider using a single app pool per website as an optimization? Separating websites into different app pools should only be done if you have an explicit need for it like:

Different .NET versions
Different identity requirements
Crashing websites
Recycle schedules
Etc
Comment: Crashing website : check. I have an old application (isapi module), that keeps crashing. Needs manually restarting the application pool :) I'm glad we've 1 apppool per website.
Answer: Lots of good articles on TechNet:

Top Ten Ways To Pump Up IIS
Performance
Performance Tuning (IIS 6.0)
Optimizing IIS 6.0 Performance (IIS 6.0)
Performance Tuning
Guidelines for Windows Server
2003  (covers IIS 6 as a workload)
Performance Tuning Guidelines for
Windows Server 2008 (covers IIS 7 as a workload)
Answer: You should see what your score is in YSlow. We run that on all sites before they deploy. A few tips:

Minify your JS and combine it into one JS file (put that reference at the bottom of the html file).
Combine your CSS into one file.
Enable GZIP and deflate compression. Add .js and .css to the type of files it will compress. ZIPEnable is good for this.
Set up content expiration for 1 year. Remember that if you modify a css/js/image file after you do this, you will need to rename that file and update references so clients pull the latest version.
Disable E-Tags.

IIS Optimization


Usar métodos de uma Activity em um Fragmento

Question: Estou tentando usar alguns métodos de uma Activity em um Fragmento, porem não estou conseguindo, alguém sabe me dizer se é possível?
public class updateMarker extends Activity {
    TextView uid;

    //URL to get JSON Array
    private static String url = "http://t4web.hospedagemdesites.ws/alarme/update.php";

    //JSON Node Names
    private static final String TAG_USER = "markers";
    private static final String TAG_ID = "id";

    JSONArray markers = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.teste);

        new JSONParse().execute();
    }

    public class JSONParse extends AsyncTask<String, String, JSONObject> {
        private ProgressDialog pDialog;
        @Override
        public void onPreExecute() {
            super.onPreExecute();
            uid = (TextView)findViewById(R.id.uid);
            pDialog = new ProgressDialog(updateMarker.this);
            pDialog.setMessage("Carregando..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected JSONObject doInBackground(String... args) {
            JSONParser jParser = new JSONParser();

            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);
            return json;
        }
        @Override
        protected void onPostExecute(JSONObject json) {
            pDialog.dismiss();
            try {
                // Getting JSON Array
                markers = json.getJSONArray(TAG_USER);
                JSONObject c = markers.getJSONObject(0);

                // Storing  JSON item in a Variable
                String id = c.getString(TAG_ID);

                //Set JSON Data in TextView
                uid.setText(id);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

}

Pretendo usar todos os métodos dessa classe nesse Fragmento:
public class UpdatesFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.updates_layout, null);
    }
}

Alguém sabe me informar se é possível? Se sim, como?
Comment: Porque é que a classe *updateMarker extends Activity*?
Comment: A classe *updateMarker* só tem o método *onCreate*, quando diz "Pretendo usar todos os métodos" está a referir-se apenas em usar a *AsyncTask*?
Comment: @ramaral Estou me referindo ao onCreate e o AsyncTask
Comment: @ramaral sabe me dizer se consigo instanciar um AsyncTask ? Preciso executar ele em outra classe, é possível ?
Comment: O meu comentário anterior ia no sentido de lhe dar uma resposta onde explicaria como utilizar o *AsyncTask* em qualquer outra classe mas, em face do que você disse, não era isso que queria.
Comment: @ramaral na verdade, consegui transformar a minha Activity em um Fragmento, mas quero usar o mesmo AsyncTask em outras classes, pode me auxiliar ?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/33105/discussion-between-tharley-carvalho-and-ramaral).
Answer: Se o que quer é puder utilizar a AsyncTask em qualquer classe declare-a em um arquivo à parte e defina um construtor que receba um context e um listener para onde será passado o resultado.
public class MyParser extends AsyncTask<String, String, JSONObject> {

    //Interface que o Listener deve implementar
    public interface OnResultListener {
        void onResult(String id);
    }

    //JSON Node Names
    private static final String TAG_USER = "markers";
    private static final String TAG_ID = "id";

    private ProgressDialog pDialog;
    private Context context;
    private onResultListener listener;

    public MyParser(Context context, OnResultListener listener){

        this.context = context;
        this.listener = listener;
    }

    @Override
    public void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(context);
        pDialog.setMessage("Carregando..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected JSONObject doInBackground(String... args) {
        JSONParser jParser = new JSONParser();

        String url = args[0];
        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        return json;
    }
    @Override
    protected void onPostExecute(JSONObject json) {
        pDialog.dismiss();
        try {
            // Getting JSON Array
            JSONArray markers = json.getJSONArray(TAG_USER);
            JSONObject c = markers.getJSONObject(0);

            // Storing  JSON item in a Variable
            String id = c.getString(TAG_ID);

            //Chama o callback com o id
            if(listener != null){
                listener.onResult(id);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

Para utilizar:
MyParser parser = new MyParser(context, new MyParser.OnResultListener() {

    @Override
    public void onResult(String id) {

        //Utilize o id como entender.
    }
});

parser.execute("http://t4web.hospedagemdesites.ws/alarme/update.php");

Comment: O que é que isso tem haver com aquilo que você pediu? Não faço ideia do que seja essa *RetrieveTask*. Faça nova pergunta tendo em conta que não conhecemos o seu código e não conseguimos ler seu pensamento. :)
Comment: Infelizmente não me atende. Vamos lá, tenho uma classe que com marcadores no mapa, e cada marcação ele atualiza a anterior com o         new RetrieveTask().execute(); ! Quero que ao atualizar os marcadores, atualizar a quantidade de marcação com AsyncTask que postei anteriormente.
Answer: Para isto, você deve fazer um cast em getActivity()
 UpdateMarker updateMarker = ((UpdateMarker)getActivity());

Isto irá funcionar apenas se realmente a UpdateMarker for a Activity da Fragment
Comment: Thiago, sabe me dizer se consigo instanciar um AsyncTask ? Preciso executar ele em outra classe, é possível ?
Comment: Sim, para isso deixe a estática. Para instanciar use **new  UpdateMarker.JSONParse();**
Answer: Boa tarde !
Você pode instanciar uma async task sim !
Primeiro você utiliza um construtor para instanciar:

JSONParse parse = new JSONParse ();

Depois você executa a asynctask com os parâmetros que você declarou para serem passados:

parse.execute(var);

Comment: Tentei dessa forma porem ele não reconhece minha classe, então tentei         UpdatesFragment.JSONParse parse = new UpdatesFragment.JSONParse(); ! Mas também não deu certo, logs: Error:(100, 43) error: an enclosing instance that contains UpdatesFragment.JSONParse is required
Comment: A classe está num arquivo separado ? Se sim, importe a mesma e veja se da certo.
Comment: Ele esta em outra classe, mesmo importando ele não reconhece.
Comment: Como a classe esta estendendo uma activity, tenta usar um intent: Intent update = new Intent(this,updateMarker.class);
            startActivity(update);


Interchanging the order of limit and expectation

Question: Assume $\displaystyle\lim_{t\to0}X_t=\gamma\hspace{3pt}a.s.$ where $X_t\geq 0$.
I would like to show that $\displaystyle\lim_{t\to0}E[X_t]=E[\lim_{t\to0}X_t]=\gamma$, i.e. that it's possible to interchange the order of limit and expectation.
It would be sufficient to show $\displaystyle\lim_{t\to0}E[|X_t-\gamma|]=0$. I can't find a way to use the dominated/monotone convergence theorems, so I am wondering whether the following argument is valid:
$\displaystyle\lim_{t\to0}E[|X_t-\gamma|]
=\lim_{t\to0}E[|X_t-\gamma|{\bf 1}\{|X_t-\gamma|<M\}]
+\lim_{t\to0}E[|X_t-\gamma|{\bf 1}\{|X_t-\gamma|>M\}]$
For the first term we have by using the dominated convergence theorem and the fact that $X_t\to\gamma$ with probability one:
\begin{equation}
\begin{aligned}
& \displaystyle\lim_{t\to0}E[|X_t-\gamma|{\bf 1}\{|X_t-\gamma|<M\}]\\
& =E[\lim_{t\to0}|X_t-\gamma|{\bf 1}\{|X_t-\gamma|<M\}]\\
& =0
\end{aligned}
\end{equation}
For the second term we have by the inverse of Fatou's lemma and the fact that $X_t\to\gamma$ with probability one:
\begin{equation}
\begin{aligned}
& \lim_{t\to0}E[|X_t-\gamma|{\bf 1}\{|X_t-\gamma|>M\}]\\
& \leq\limsup_{t\to0}E[|X_t-\gamma|{\bf 1}\{|X_t-\gamma|>M\}]\\
& \leq E[\limsup_{t\to0}|X_t-\gamma|{\bf 1}\{|X_t-\gamma|>M\}]\\
& \leq E[\lim_{t\to0}|X_t-\gamma|{\bf 1}\{|X_t-\gamma|>M\}]\\
& =E[0]\\
& =0
\end{aligned}
\end{equation}
Combining we have $\displaystyle\lim_{t\to0}E[|X_t-\gamma|]=0$
Is this a valid solution or am I cheating somewhere?
Answer: The limsup version of Fatou's lemma only holds if there exists an integrable function $g$, such that $f_n < g$ for all n.  In that case, your proof is valid; if not, there are counter-examples (e.g. $f_n = \gamma + n * 1_{[0,1/n]}$ )


SQL-TRIGGER FAZENDO AUTO NUMERAÇÃO ERRADA

Question: Olá, estou estudando sql a pouquíssimo tempo então me desculpe se alguma nomenclatura não estiver ok.
Criei algumas triggers para meu banco de testes e em alguns casos está funcionando perfeitamente.
Em outros no entanto está criando sequencias erradas.
TENHO A TABELA CLIENTES POR EXEMPLO.
Onde criei a tabela e criei uma sequencia
CREATE SEQUENCE SEQ_CLI START WITH 1 INCREMENT BY 1 NOMAXVALUE;
Após criei a Trigger
CREATE TRIGGER "TRG_CLIENTE1"
  BEFORE INSERT ON "CLIENTE"
  FOR EACH ROW
   BEGIN
       SELECT "SEQ_CLI". NEXTVAL INTO:NEW.COD_CLI
       FROM DUAL;
  END;
Agora fazendo INSERT na tabela de cliente o primeiro COD_CLI gerado é 16, e não tem nada inserido antes disso.
Se alguém puder ajudar no que possa estar acontecendo agradeço.
Obs: Fiz todas as triggers e sequences da mesma maneira.
Answer: Uma sequência, assim como o auto incremento, propositalmente pula os valores se eles tiverem sido excluídos em algum lugar do tempo. Por exemplo:
<code>Criou o registro 13
Criou o registro 14
Deletou o registro 14
Criou o registro 15
</code>
Veja que mesmo ao excluir o registro com ID 14, o próximo a ser criado não será o 14, porém o 15.
O conceito de ID é pra ser único. Pode gerar inúmeros problemas se você reutilizar um ID, mesmo que ele tenha sido excluído.
Comment: Certo, entendi a questão, vai estar pulando IDs já usados.
Neste caso não foi excluído registros anteriores, o primeiro registro lançado começou no ID 16.
Mas na minha instrução eu havia feito para começar no 1. Sabes me dizer oque poder ter acontecido de errado?
Agradeço a atenção.
Comment: Você está compartilhando esse mesmo sequence (CREATE SEQUENCE) em outras tabelas?
Comment: Não usei em outras tabelas, porém quando estava inserindo fiz algumas tentativas até conseguir inserir, pois estava faltando alguma coisa, virgulas, parenteses etc, deve ter sido isso.
agradeço.
Comment: Atente também que Sequences garantem unicidade e não integridade , assim os "ids" podem perder a sequencia, algumas aplicações (Nota Fiscais , Núm de Apocices etc) não permitem isto e outra solução deve ser feita.


Are there any permanent points in ATP/WTA rankings?

Question: For example: Nadal finished 1st at the end of 2013. If, by assumption, he doesn't win any match in 2014 will he have 0 (or under 500 points - assuming that qualifing to the main table of tournaments grands you points) or there are some points for being so good in the past years that can't be erased?
I'm asking because Serena Williams hasn't shined at all this year (no important title) but it's still far away in the top, and it's only one Grand Slam left and it's the middle of the year.
Comment: Check out the points Serena has won in 2014. http://en.wikipedia.org/wiki/2014_Serena_Williams_tennis_season She has won 3 titles this year
Answer: You are correct - if Nadal didn't win a single match in 2014 his points total would fall back down to zero eventually.
Depending on the reason why a player isn't able to play for a long time (illness, injury, etc.) sometimes qualifies them to receive a protected ranking - read more about that here.


David Williams "Probability with Martingales" : Proof of Monotonocity of $L^p$ norms

Question: I find the author often leaves out 'obvious' steps..
How to fill in the missing steps in the proof below ?

I can see that $X_n \uparrow {|Y|}^{p}$ so through Monotone convergence $E(X_n) \uparrow E(|Y|^p)$, but what then ? is it that $E(X_n) \le {E(X_n)} ^ {r \over p}$ since both sides positive and r > p ?
Comment: I have added [proof-explanation tag](https://math.stackexchange.com/tags/proof-explanation/info), since your question seems to be mainly about the specific proof you included in the post. (As opposed to asking for any proof of this result.)
Answer: You have $$ E(X_n)^{1/p} \le ||Y||_r$$ and want to show $$||Y||_p\le ||Y||_r. $$ $X_n$ is a monontone sequence of RVs converging to $Y^p$ so by MON, $E(X_n)\to E(Y^p)$ which means $$ E(X_n)^{1/p}\to E(Y^p)^{1/p}=||Y||_p$$ so by the first inequality, $$ ||Y||_p=||Y||_r$$
Comment: yes that's it !  many thanks !


Correct sed syntax for variables

Question: I'm getting a syntax error when running sed in my bash script. Non of the similar issues on here have resolved my problem.
I need to update a line in a config for a VPN connection.
serverconfig='vpnsrv.tcp.ovpn'
auth='auth-user-pass'
update='../login.conf'

sed -i.bak "s/$auth/$update" $serverconfig

# I have also tried these:
#sed -i.bak 's/auth-user-pass/auth-user-pass "${update}"' $serverconfig
#sed -i.bak 's/auth-user-pass/auth-user-pass '"${update}"'' $serverconfig
#sed -i.bak 's/auth-user-pass/auth-user-pass\ "${update}"' $serverconfig
#sed -i.bak 's/auth-user-pass/auth-user-pass\ "$update"' $serverconfig
#sed -i.bak 's/'"$auth"'/'"$auth $update"' $serverconfig
# sed: -e expression #1, char 32: unterminated `s' command

Line in file "auth-user-pass" should found and replaced with "auth-user-pass ../login.conf". I'm unable to get passed the syntax error: sed: -e expression #1, char [#]: unterminated `s' command
Comment: *try changing the delimeter*
Comment: You just need a trailing slash: `sed -i.bak "s/$auth/$update/" $serverconfig`
Comment: I get `sed: -e expression #1, char 32: unterminated `s command` with: `sed -i.bak "s/$auth/$update/" $serverconfig`
Answer: Sed can use almost any character as its 'delimiter'. You're having trouble because your chosen delimiter / appears in your variable.
sed -i.bak "s,$auth,$update" $serverconfig

You can also perform this substitution as many times as possible with the global operation:
sed -i.back "s,$auth,$update,g" $serverconfig

Comment: Thanks for the tip, this solved my issue
Comment: @z3r0n0id, Thanks for showing your work. Please have a look at https://stackoverflow.com/help/someone-answers

Correct sed syntax for variables


What is a concrete example of Android app functionality that uses HashMap?

Question: I am a beginner in Android, and understand only very basically that HashMap class enables key/value pairs. But how does this translate into actually using this in an Android app? Could someone provide a simple, plain English example of what case you might want to use HashMap in an app? I cannot imagine a case where I might need it. Make up an Android app idea, if needed. Thanks in advance.
I am looking for a "big picture" analysis that will give some examples where you might use HashMap with certain Android functionalities you are trying to implement.
Comment: I really don't understand what is wrong with this question.
Comment: Downvotes without explanations do nothing for the StackOverflow community. If you want more information, or want me to reword my question, I would be happy to do that, if you would only point out what the difficulty is you are having with my question.
Comment: SimplePlan, I was not necessarily suggesting you downvoted, although thanks for letting me know, I was just talking to the people who did the downvote. Okay, so it will depend on your app, but when I ask myself the question, "when will I ever use HashMap?" I cannot think of an idea to use it. So I was just hoping others who have used it could share the examples of what kind of functionality they used it for. I do not know enough Android to know this, and looking up "HashMap examples in Android" on Google only shows me code, it does not explain what it does or what it will produce.
Comment: And a CS question is not allowed on here? There are a lot of people who have no CS degree who are trying to learn Android. So it would be wise to be patient with them, perhaps provide links, whatever you think it would take to help someone learn. I know I am not the only person learning Android without a CS background. I go to meetups a lot and they are filled with aspiring programmers who have no CS background.
Comment: @NoniA. the point is not about aspiring cs people. You need to go to help center and know how this site works http://stackoverflow.com/help.
Comment: Thanks Raghun... for that link, but I read through the questions not to ask, and the guidelines for the questions to ask, and I did not find any fault with my question, as it related to Android and an Android class, specifically, it is just that it had some CS background (but what question doesn't?) and so the focus seemed to shift to CS. When really it was about Android, and an example of how to use it. If I need to know more CS to understand the answer to my question, I don't see why someone's answer could not include that. I thought Aviad did a great job answering my question.
Comment: First let me clear one thing. Not downvoted your question and another thing it's dependent on your app and you want to used `HashMap`.
Answer: We could use HashMap to keep a list of employess together with their respective salaries.
We can do:
HashMap<String, Float> emplMap = new HashMap<String, Float>();

emplMap.put("fred", 1.000);

for(String name : emplMap.keySet()) {
   System.out.print(name + "'s salary is" + emplMap.get(name));
}

Should print

"fred's salary 1.000"
Comment: You could get yourself a book such as Thinking in Java. From that book you will learn things proper way and will understand everything. A very good book.
Comment: Thanks Alex, so then `HashMap` handles lists, where you want to use information from the list, correct? But then why not use ArrayList? Although I can't say I know a lot about `ArrayList` either, but just trying to understand the unique advantage of using `HashMap`. Is it so you can create a bunch of key value pairs and then get them, set them, or do other things with them when you need to?
Answer: HashMap or Map interface is not new on android, This is Java Collections framework.
Java collection are meant to be used in several cases to hold data and contain 3 interfaces:

List - Basically simple list,or linked list implementations
Set - The same as list but won't hold 2 equal obejcts(You need to implement you own equals and hashcode)
Map - as you said key value pair.

Uses:
List - For anything, just to hold data
Set - For list of data that we want that all of the items will be unique.
Map - Key value and the most common example is the use for DB items, or something with ids.. for example:
bookId, Book.. I that case you can take the object by id.. This is the most common
I attached link for Java collection tutorial.. It is very important framework that you have to know if you are going to develop java/android
http://tutorials.jenkov.com/java-collections/index.html
Hope that helps
Comment: NP.. But there are no 3 kind of HashMap.. There are 3 Type of Collections :). HaspMap is implementation for the Map interface. You have to read this article.. It is one of the important and must know framework in java.. Good luck :)
Comment: Thanks Aviad! That was a thorough and well-explained answer. I will go through these tutorials. I didn't realize collections was such a large topic, but very good to know. I am glad you pointed out that there are 3 kinds of `HashMap`s and thanks for stressing its importance in studying Android. I really appreciated it.
Comment: Oops, thanks! I most definitely will read this, asap. :)


If $R=K[X]/(X^n)$, can represent any element as polynomial with degree $<n$

Question: Let $K$ be a field and $R=K[X]/(X^n)$ where $n \in \mathbb{Z}_{n\geq1}$ and $(X^n)$ is the ideal generated by $X^n$. We denote $x:=X+(X^n) \in R$, any equivalence class $r$ in $R$ has a representing element of the form: $$r=a_0+a_1X+ \dots + a_{n-1}X^{n-1}.$$
I am confused about the statement in bold. How would I find such an element for $X^3 \in K[X]$ if $n=2$ for example?
Comment: Hint: Use Euclidean division in $k[x]$.
Comment: $X^3$ is allowed by that form. Unless I misunderstand your question.
Comment: Sorry! I edited it to include $n=2$
Comment: When you quotient by $(X^n)$ you're effectively saying any time you see $X^n$ you can replace the term with 0. So all terms of degree $\geq n$ will vanish.
Answer: $K[X]$ is a $K$-vector space with basis
$$1, X, X^2, X^3,\dots$$
Making the quotient by $(X^n)$, you are killing all elements of the basis of degree $\geq n$, getting a basis for $R$ which is simply $1, X,X^2, \dots, X^{n-1} \ \  (+(X^n))$.
So, a polynomial $\sum_k a_k X^k$ is transformed by killing all terms of degree $\geq n$, becoming $\sum_{k \leq n-1}a_kX^k$. In you particular example, $X^3$ becomes $0$.
Answer: By the Division Algorithm $\ f = q\, x^n + r\ $ with $\,\deg r < n,\,$ hence $\,f\equiv r\pmod{\!x^n}$
See this answer for further discussion of such normal forms in quotient of Euclidean domains.
Same for $R[x]/g$ over any commutative ring $R$ and any polynomial $g$ whose leading coeff is a unit (invertible), since this enables division with smaller (degree) remainder (as explained in the links).


Array java mostra itens especificos

Question: Olá , pessoal estou com uma duvida por exemplo  possuo o Array A {1,2,3,4,5} , faço outro array B {1,2,3} com os itens que desejo exclui do array A, e mostrar os itens que sobraram ex o 4 eo 5 , porém estou com parando um if dentro de um  for e a resposta sai completamente loca , algume poderia me ajudar ?
Não posso usar arraylist.
ex: A = {1,2,3,4,5}
novo array com os itens que desejo que não sejam exibidos :
B = {1,2,3}
dentro do for  com parar e mostrar apenas os itens diferentes
4 e 5
Segue abaixo o código que eu tentei
int qtdpessoas ;
        int exclui ;
        Scanner sc = new Scanner(System.in);
        qtdpessoas = sc.nextInt();
        int idpessoa [] = new int [qtdpessoas];

        for (int i = 0; i < idpessoa.length; i++) {

            idpessoa[i]= sc.nextInt();
            }

        exclui = sc.nextInt();
        int paraexcluir [] = new int [exclui];

        for (int i = 0; i < paraexcluir.length; i++) {
            paraexcluir[i]= sc.nextInt();
            }

        for (int i = 0; i < idpessoa.length; i++) {
            for (int j = 0; j < paraexcluir.length; j++) {
                if (idpessoa[i]!= paraexcluir[j]) {
                System.out.println(idpessoa[i]);
                }
            }

Comment: Já tentou algo? Se tiver, pode postar o código?
Comment: sim , vou reeditar aqui e se tu puder da uma olhada
Answer: Para obter o resultado que você deseja faça as seguintes alterações no seu código:

No if verifique se os elementos são iguais, e caso sejam, pule para a próxima iteração do laço;
Adicione um else if que verifique se está no último elemento e caso esteja utilize o System.out.println, assim você terá testado todos os elementos e esta condição só será satisfeita se nenhum elemento for igual.

O seu if ficará mais ou menos assim:
if (idpessoa[i] == paraexcluir[j]) {
  break;
} else if (j == (paraexcluir.length - 1)) {
  System.out.println(idpessoa[i]);
}

Array java mostra itens especificos


Event Not Counting Number of Characters in Tag

Question: I'm having issues where my JavaScript code is not counting the characters that is being input and I'm at a lost.  Any ideas?
HTML:

Student name:
<textarea id="studentName" cols="40" rows"3"></textarea>

0

JavaScript:
var $textareaElement = $("#studentName");

function textSize(event) {
   $("#stringLength").text($textareaElement.val().length);
}

/* Your solution goes here */
$(document).ready(function () {

$("#studentName").focus(function () {

$("#stringLength").html($(this).val().length);

});

});

Test:
Testing the number of characters in "Hi" is shown
Yours and expected differ. See highlights below.

Yours
  0
  Expected
  2

Testing the number of characters in "How are you?" is shown
Yours and expected differ. See highlights below.

Yours
  0
  Expected
  12

Testing the number of characters in "Good Game" is shown
Yours and expected differ. See highlights below.

Yours
  0
  Expected
  9
Comment: Where exactly is `textSize` being used in the logic?
Comment: @Taplar wouldn't it be called while utilizing the function for the script?
Comment: Where is it utilized?  You create the method and it's never used.
Answer: focus will fire when the element gains focus.  keyup is what you're looking for if you want to count characters as user types them into the input.


limit of a distribution

Question:
Show that $$\lim_{\epsilon \to 0^{+}}  \left\langle \frac{\epsilon}{x^{2}+ \epsilon} ,\phi \right\rangle =\langle \delta,\phi\rangle $$
  where $\phi\in D(\mathbb{R}) $ and $ \frac{\epsilon}{x^{2}+ \epsilon} \in D' (\mathbb{R}) $

What I tried is this:
$ \frac{\epsilon}{x^{2}+ \epsilon}$ is an integrable function hence
$\left\langle \frac{\epsilon}{x^{2}+ \epsilon} ,\phi\right\rangle$ defines an integral on $\mathbb{R}$:
$$\left\langle\frac{\epsilon}{x^{2}+ \epsilon} ,\phi\right\rangle = \int_{- \infty}^{\infty}\frac{\epsilon}{x^{2}+ \epsilon} \phi (x) dx$$
How can I take limit of the last equation?
Thank you from now on.
Comment: did you try partial integration and splitting up the integral at 0?
Comment: Wasn't it $\frac{\epsilon}{x^2 + \epsilon^2}$? And there's a constant factor ($\frac{1}{\pi}$) missing then.
Comment: @DanielFischer no. It is how I wrote it in the question.
Comment: In that case, substituting $x = \sqrt{\epsilon}\, y$ will show the limit is $0$, not $\delta$.
Comment: To prove what Daniel Fischer suggested, you can integrate by parts to see that you have $-\int_{-\infty}^\infty \phi'(x) \arctan(x/\epsilon) dx$. Now split this integral between $(-\infty,-\sqrt{\epsilon}),(-\sqrt{\epsilon},\sqrt{\epsilon})$ and $(\sqrt{\epsilon},\infty)$. The middle interval is small and everything is bounded so it is not important. What happens on the other two intervals? (Hint: how does $\arctan$ behave at large arguments?)
Comment: @Ian Is it $ arctan(x\ \sqrt \epsilon)$ in that integral?
Comment: @SerkanYaray No, I had it right.
Comment: @Ian No need to integrate by parts: $\frac {\epsilon}{x^2+\epsilon}\le 1[x^2\le \sqrt \epsilon]+\sqrt \epsilon[x^2> \sqrt \epsilon]$.
Comment: @A.S. I meant the first thing Daniel Fischer suggested (with the $\epsilon^2$ in the problem).
Comment: I am sorry,why do you need $ \epsilon ^{2} $ I really didn't understand why you are changing the problem?
Comment: With the $\epsilon$, your problem statement is wrong, in that the family of distributions in question converges to $0$, not $\delta$.
Answer: As some people pointed to you you should consider the delta sequence
$$ f_n(x) = \frac{n}{\pi}\frac{1}{1+n^2x^2}$$
Which gives
$$\lim_{n\to \infty} <f_n(x), \phi(x) > =<\delta(x), \phi(x) >$$
Note: you can put $\epsilon =\frac{1}{n}$ and consider the limit as $\epsilon$ goes to 0.

limit of a distribution