Riemann integral and Cauchy integral

Question: Take the following exercise taken from the book :
http://188.8.131.52/main/DD7D07B152D8622B441B7E63F9D4461E
https://libgen.lc/ads.php?md5=091431F03323DE6C347E43D0475FC387
(see page 14).

Consider the function defined on $[-1,0]$ by $f(x) = 1/\sqrt(-x)$ on
$[-1,0)$ and, $f(0) =0$. Since this function is not bounded on $[-1,0]$, the Riemann integral does not exist. Show that, nevertheless, the
Cauchy integral of this function over this interval does exist.

For the Riemann part, it's ok.
For the Cauchy part, I would like to show that for any sequence $(x_k)_{1\le k\le n}$ such that $-1=x_0<x_1<\dots<x_n=0$, we have
$$\sum_{k=1}^n\frac{x_k-x_{k-1}}{\sqrt{-x_{k-1}}}<\infty$$ when $k\to \infty$.
I cheat and write that
$$\sum_{k=1}^n\frac{x_k-x_{k-1}}{\sqrt{-x_{k-1}}}<\int_{-1}^0\frac{1}{\sqrt{x}}=2$$
and I conclude.
What would be the right way to do it ?
Comment: When $k=n$ you have $0$ in the denominator.
Comment: sorry yeah it was in the first sum, it's the right node. I corrected
Comment: What is the Cauchy integral in this context? I'm not familiar with it.
Comment: @zhw: It is Cauchy's definition as a limit of approximating sums of the form $\sum_{k=1}^nf(x_{k-1})(x_k - x_{k-1})$ as the partition norm tends to $0$ -- always evaluating the integrand at an endpoint of a subinterval. See for example [here](https://www.jstor.org/stable/2007121?seq=1#metadata_info_tab_contents) and [here](https://math.stackexchange.com/q/2590462/148510).
Comment: I think the point of Bressoud's exercise is that a Cauchy sum can converge to an improper Riemann integral when the function is unbounded and the Riemann integral does not exist. This always works if the integrand is monotone as it is here, but not in general.
Answer: The Riemann and Cauchy integrals both exist over $[-1,-c]$ where $c > 0$, since $f$ is bounded and continuous on that interval.
For any $\epsilon > 0$ there exists $\delta > 0$ such that for a partition $P: -1 = x_0 < x_1 < \ldots < x_{n-1} = -c$ with $\|P\| < \delta $, we have
$$2(1- \sqrt{c})-  \epsilon = \int_{-1}^{-c}\frac{dx}{\sqrt{-x}}- \epsilon \leqslant \sum_{k=1}^{n-1} \frac{x_k - x_{k-1}}{\sqrt{-x_{k-1}}}\leqslant \int_{-1}^{-c}\frac{dx}{\sqrt{-x}}+ \epsilon  = 2(1- \sqrt{c})+ \epsilon$$
With $x_n = 0$ we have
$$\sum_{k=1}^{n} \frac{x_k - x_{k-1}}{\sqrt{-x_{k-1}}}= \frac{0- (-c)}{\sqrt{c}}+ \sum_{k=1}^{n-1} \frac{x_k - x_{k-1}}{\sqrt{-x_{k-1}}}= \sqrt{c}+ \sum_{k=1}^{n-1} \frac{x_k - x_{k-1}}{\sqrt{-x_{k-1}}}$$
Thus,
$$-\epsilon/2 \leqslant \sum_{k=1}^{n} \frac{x_k - x_{k-1}}{\sqrt{-x_{k-1}}} -(2 - \sqrt{c}) \leqslant \epsilon/2,$$
and when the norm of the full partition $P': -1 = x_0 < x_2 < \ldots < x_{n-1} < x_n = 0$ is sufficiently small we have both $\|P\| < \delta$ and $\sqrt{c} < \epsilon /2 $
$$\left| \sum_{k=1}^{n} \frac{x_k - x_{k-1}}{\sqrt{-x_{k-1}}} -2 \right| \leqslant \left| \sum_{k=1}^{n} \frac{x_k - x_{k-1}}{\sqrt{-x_{k-1}}} -(2-\sqrt{c}) \right| + \sqrt{c}\leqslant \sqrt{c} + \epsilon/2 < \epsilon$$

Riemann integral and Cauchy integral


xmlconfigurator.configure not throwing exceptions

Question: I am trying to configure log4net for an application.
<code>System.IO.FileInfo fi = new System.IO.FileInfo("some junk file name");
log4net.Config.XmlConfigurator.Configure(fi);
log4net.Config.XmlConfigurator.ConfigureAndWatch(fi);
</code>
I got surprised, when above code is not throwing any exception !!!!
when file doesn't exists , why log4net is not throwing any exception ? Isn't it bad design ?
Is there any reason behind designing such behaviour ??????
If it is not throwing any exception , how can i know, the file is parsed successful and working properly ?
Answer: I believe this is deliberate: look at the section "Is Log4Net a reliable logging system" in the Log4Net FAQ.
The idea is that a logging subsystem should not throw exceptions causing your application to crash simply because of a bug or configuration error within the logging subsystem.
As for validating your configuration file, you can test that a configuration file produces the expected output in a development environment before deploying to production.  Don't modify production configuration files except with tested tools (no manual editing).
Also I understand that you can add an attribute "debug=true" to the log4net element to enable internal log4net debugging.  Though you'd presumably need at least one appender to be configured correctly to see the internal debugging output.  I've never tried this though.


Variable-Length Array in MySQL

Question: I'm writing an application in PHP that uses a MySQL database to store information. One of the pieces of information that it has to store is an array of names, but the array has no set length. It could range from one to many items. Is there a way to store this array in MySQL and be able to retrieve it by specifying just one item from the array?
For example, I want to be able to store something like this in a table:
Foo        Bar
-------------------
[baz,car]  fiz
[abc,def]  ghi

Then, I want to be able to tell MySQL just to search for car and SELECT the first row in the table above.
Is there a feasible way to implement this?
Comment: Normalizing your data would make this unnecessary and your life a lot easier
Answer: The way to implement it is to "normalized" the schema. There are several related ideas which comprise schema normalization, but the critical one here is that your data should be represented with two tables and a relationship between. The relationship is called, "one to many", since for one "Bar" there are one-or-more "Foo".
A necessary step, then, is to add unique identifier columns to your schema (easiest just to use auto-incrementing integers), and then query using the JOIN mechanism to relate your data.
this is why we call MySQL (and many others) a "relational" database.
Bar
+----+----------+
| id |   name   |
+----+----------+
| 01 |   fiz    |
+----+----------+
| 02 |   ghi    |
+----+----------+

Foo
+----+--------+----------+
| id | bar_id |   name   |
+----+--------+----------+
| 01 |   01   |  baz     |
+----+--------+----------+
| 02 |   01   |  car     |
+----+--------+----------+
| 03 |   02   |  abc     |
+----+--------+----------+
| 04 |   03   |  def     |
+----+--------+----------+

And here is what the join looks like to select the "fiz" record based on "car" in the Foo relation
SELECT
  Bar.*
FROM Bar
  JOIN Foo ON Bar.id = Foo.bar_id
WHERE Foo.name = "car"

And if you want the entire list of Foo relations for each bar with a matching Foo:
SELECT
  Bar.*,
  GROUP_CONCAT(Foo.name)
FROM Bar
  JOIN Foo ON Bar.id = Foo.bar_id
WHERE Foo.name = "car"
GROUP BY Bar.id

Comment: Yes, both of the `id` columns should be declared as `PRIMARY KEY`, which enforces a unique constraint. The declaration might look like this: `id int unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY`
Comment: Ah, so this would be a good place to use a `unique` index, right?
Answer: Either
SELECT Bar FROM tbl
WHERE FIND_IN_SET('car', Foo)

Variable-Length Array in MySQL


Nginx config as reverse proxy

Question: I need to configure nginx as reverse proxy. It should allow access to /phpmyadmin with a reverse proxy to private_ip:5000.
This is part of nginx.conf:
location ~ /phpmyadmin {
   rewrite ^.*\/phpmyadmin(\/?)(.*)$ /$2 break;
   proxy_pass        https://192.168.99.6:5000;
   proxy_redirect     off;
   proxy_set_header   Host $host;
}

And this config works except in cases:

https://192.168.99.6:5000/phpmyadmin. But with a / at the end, that's okay.
I get a 404 error after logging in, but if I press "back" everything is fine.
I also get 404 error after logging out.

Please help me fix this. All services are in the k8s cluster.
Answer: It's not immediately obvious what the goal is here.
If the backend service is listening with a URI that matches /phpmyadmin and you have a location block for /phpmyadmin in your nginx config, then it should be entirely sufficient to simply put:
location /phpmyadmin {
  proxy_pass https://192.168.99.6:5000;
  proxy_set_header Host $host;
}

If the goal is to drop the /phpmyadmin URI segment, then something like:
location /phpmyadmin/ {
  proxy_pass https://192.168.9.6:5000/;
  proxy_set_header Host $host;
}

From my understanding of your description you don't actuallt need the rewrite at all.
Comment: This is a training project that aims to understand all of these technologies. Without rewriting, in the first case, it turned out 404, in the second - 502.

Nginx config as reverse proxy


Divisibility of integer numbers

Question: If we have two integers $a$ and $b$ such that $a = \frac{5b}{6}$, is $a$ divisible by $5$?
If so, why is that?
I don't see it.
Comment: Hint: consider the prime factorization of $b$.
Comment: Are you familiar with the Unique Factorization Theorem?
Comment: Intuitively, you should note that dividing by $6=2\cdot 3$ cannot take away a factor $5$
Answer: No prime factorisation is really required here: we have $5b=6a$,so $5$ divides $6a$. Now $5$ is prime, hence  by Euclid's lemma, it must divide one of the factors. As it does not divide $6$, it must divide $a$.
Answer: If $a$ is an integer then $b = 6k, k\in \mathbb{Z}$ so $$a = 5k \Rightarrow a \equiv 0 \pmod{5}$$
Comment: Could you please explain the downvote?
Answer: If $a$ is an integer, then it is obvious that $6$ divides $5b$ or more specifically $b$.
Hence we can say that, $b=6k$ for some integer $k$.
So $a=5k$
Thus we can conclude that $5$ divides $a$, since $5$ divides $5$.
Comment: Why the downvote?
Comment: @user309293 If you like my answer, you can accept it by clicking the "tick" mark on the left side of my answer, or even you can upvote it. :-)
Comment: Also why is this answer downvote?

Divisibility of integer numbers


É viável utilizar copyBulk com datatable para carga de dados em SGBD?

Question: Passei por uma experiência em efetuar grande carga de dados a partir de arquivo texto, que necessitava ser criticada antes de gravar no BD. Utilizei DataTable com copybulk. Percebi que a carga dos dados no DataTable e posteriormente no BD eram rápidas. Recebi críticas a respeito do uso do DataTable. A vantagem do DataTable é a possibilidade de criação de índices e cria-lo idêntico à tabela do BD.
Comment: Que críticas você recebeu? Você está questionando a viabilidade de utilizar o copyBulk em qual sentido?
Comment: ´Não questiono o uso do copyBulk. É muito eficiente e rápido. A  crítica que recebi é que datatable á uma tecnologia ultrapassada e que é lenta. No meu caso a performance foi muito boa (cerca de 100.000 registros). O que me incomoda é que os padrões existentes muitas vezes são vistos como uma lei, e quem não a utilizar pode ser considerado um "marginal". Adoro padrões, mas não me deixo escravizar por nenhum deles. Afinal foram desenvolvidos por profissionais como nós.
Comment: Bem, entendo muito pouco de C#, e portanto não sou qualificado para responder. Entretanto a sua pergunta parece mais um desabafo do que uma pergunta procurando uma resposta. Não consegui entender que tipo de informações você espera ver em uma resposta. Tente editar ela para deixar mais claro qua é especificamente a sua dúvida e o que é que você espera ver na resposta.
Answer: Sim, é viável, desde que atenda e resolva o seu problema em específico.
Como em todo tipo de software, não há apenas uma única linguagem ou uma única tecnologia ou um único padrão para implementar software. Software deve ser entendido como uma solução para um determinado problema. A linguagem, tecnologia ou padrão vai depender de uma série de variáveis, como por exemplo: Necessidades do cliente, infra estrutura do cliente, custos com hardware e licenciamento, mão de obra e conhecimento disponível em sua região, tempo de vida do software etc.
Para um programa simples de importação de dados que será utilizado para migrar de um sistema pra outro ou de um banco de dados para outro, se for utilizado uma única vez e depois descartado, o padrão de design utilizado ou a linguagem ou bibliotecas não importará muito pois não é algo que você dará manutenção no futuro. Então, resolvendo o seu problema hoje, implemente da maneira que funcionar e atender bem. Mas caso esse programa seja utilizado frequentemente, e haja necessidade de mantê-lo, modificá-lo ou evoluí-lo, pense melhor nessa questão, pois outras pessoas terão de mexer no código, então é bom que utilize um padrão mais atual, pois é raro encontrar no mercado profissionais que trabalhem com tecnologias mais antigas. Procure entrar em consenso com seu time ou sua equipe.


Array stored in a string type : PHP

Question: Today i faced weird problem it is
$stringvar = '["image_link1","Image_link2"]';

Now i want to covert it into type array,
    like
Array => [0] Image_link1, [1] Image_link2

I tried to juggling the type but it's giving me
Array => [0] '["image_link1","Image_link2"]'

Right now I am using
str_replace() to replace '[', ']' with blank. then explode.
Is there any best workaround for it?
Comment: That string format is JSON.
Answer: The string is formatted in JSON notation.
PHP offers the convenient function json_decode() to decode that:
<?php
$stringvar = '["image_link1","Image_link2"]';
print_r(json_decode($stringvar));

The output of the above script is:
Array
(
    [0] => image_link1
    [1] => Image_link2
)

Comment: JSON uses curly braces for objects and square braces for arrays.
Answer: I didn't try your code but at first it looked weird for mee too.
I believe you can get rid off the apostrophes here $stringvar = '["image_link1","Image_link2"]';
so it gives you :
$stringvar = ["image_link1","Image_link2"];

This should work or you can also try :
$stringvar = array("image_link1","Image_link2");

Good luck ;)
Comment: LOL, this is good thinking! I doubt that is the OPs issue, more likely he receives the string from some API or similar out of his control. But it certainly is good to point this out! +1
Comment: Oh yeah, I didn't understand the question that way. So then, you're right json_decode(); will do the trick ;)

Array stored in a string type : PHP


Can't solve this:

Question: I'm a beginner.....I cant seem to solve this problem involving multiple methods....the method using the scanner isn't doing anything
package bucky;

import java.util.Scanner;

public class test {
    public static void main(String args[]){

        input();
        for(int time=1;time<values[2];++time){

            double A=values[1]*Math.pow(1+values[3], time);

        System.out.println("You have: "+A+ " subscribers today");
        }}

        public static double[] input(){
            Scanner s=new Scanner(System.in);
            double[] values=new double[3];

            System.out.println("Enter the Principal value: ");
            values[1]=s.nextDouble();
            System.out.println("Enter the no. of days: ");

            values[2]=s.nextInt();
            System.out.println("Enter the Rate of growth : ");
            values[3]=s.nextDouble();
            return values;
        }
}

Comment: Now, what exactly you want to do? Nothing clear from your question. Please check on how to ask questions.
Comment: And the question is?
Comment: Welcome to Stack Overflow, please read [the welcome tour](http://stackoverflow.com/tour) and [How do I ask a good question](http://stackoverflow.com/help/how-to-ask), it will help you getting better answers.
Comment: It doesn't compile. `values[]` is not accessible in main method
Comment: @Lucero The question was remove my errors.
Answer: input() has to be assigned to values right? Like: double[] values = input();
Also, the indexing in array starts with 0... so values[0] is the first value and so on.
Try this code:
public static void main(String args[])
{
    double[] values = input();
    for (int time = 1; time < values[2]; ++time)
    {
        double A = values[1] * Math.pow(1 + values[3], time);

        System.out.println("You have: " + A + " subscribers today");
    }
}

public static double[] input()
{
    Scanner s = new Scanner(System.in);
    double[] values = new double[3];

    System.out.println("Enter the Principal value: ");
    values[0] = s.nextDouble();
    System.out.println("Enter the no. of days: ");

    values[1] = s.nextInt();
    System.out.println("Enter the Rate of growth : ");
    values[2] = s.nextDouble();
    return values;
}

Comment: Are you sure you can call the static method `input` like this? doesnt it need to be `test.input()` (test as the class he defined) or remove the static qualifier?
Comment: Yeap, you can call static method like that as long as it is in the same context (class). If you remove the qualifier then you'll need the instance of object to access the method.
Comment: Well, you are right. Might have done that without knowing. Thanks
Comment: already tried before asking.....error :Exception in thread "main" java.lang.Error: Unresolved compilation problems:
 Cannot make a static reference to the non-static field s
 Cannot make a static reference to the non-static field s
 Cannot make a static reference to the non-static field s

 at bucky.test.input(test.java:28)
 at bucky.test.main(test.java:10)
Comment: never mind....user218046....dude you are awesome....thanks man.....if you don't mind my asking, where did i go wrong.....thanks again
Comment: Well: 1) You've called method input() and haven't saved its returned values somewhere (to use in for loop); 2) because the main method is static it can directly call only the static methods from its body (he can't see non-static methods as they doesn't exist without their class object) and also it can call methods of objects who were created in its body: like... new Someone().input(); 3) when getting data from array the indexing of elements starts from 0... so myArr[0] is the first element, myArr[1] is the second and so on... until myArr[ myArr.length - 1 ] which is the last element.
Answer: Try double[] values = input(); in main method.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class test { public static void main(String args[])
{

    double[] values = input();
    for(int time=1;time<values[2];++time){

        double A=values[0]*Math.pow(1+values[2], time);

    System.out.println("You have: "+A+ " subscribers today");
    }}

    public static double[] input()
    {
        Scanner s=new Scanner(System.in);
        double[] values=new double[3];

        System.out.println("Enter the Principal value: ");
        values[0]=s.nextDouble();
        System.out.println("Enter the no. of days: ");

        values[1]=s.nextInt();
        System.out.println("Enter the Rate of growth : ");
        values[2]=s.nextDouble();
        return values;
    }

}

Again it is going to throw an arrayoutofbondsexception...change values[1] with values[0] values [2] with values[1] and values[3] with values[2]..

Can't solve this:


symmetric polynomial inequality?

Question: I put $n\ge 2$ balls of various sizes into an urn.  I draw two balls (without replacement) from the urn.  With each draw, I draw any given ball with probability proportional to its size.
Can you show that the expected size of the first ball is at least the expected size of the second ball?
The expectations are easy to calculate.  For $i\in[n]$, let $s_i>0$ be the size of ball $i$.  Let $S=\sum_{i=1}^n s_i$ be the sum of the sizes.  Then

The expected size of the first ball is $~~~~~~~~~\displaystyle\sum_{i=1}^n \frac{s_i^2}{S}.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(i)$
The expected size of the second ball is $~~~\displaystyle\sum_{i=1}^n \frac{s_i}{S} \Big(\sum_{j\ne i} \frac{s_j^2}{S-s_i}\Big).~~~~~~~(ii)$

You need to show (i) is at least as large as (ii).  For $n=2$ it is easy to show.
Of course the inequality is tight if all balls are the same size.
For the case $n=3$, the inequality is equivalent to, for $a,b,c\ge 0$,
$$a\frac{b^2+c^2}{b+c} + b\frac{a^2+c^2}{a+c} + c\frac{a^2+b^2}{a+b} \le a^2 + b^2 + c^2.$$
Thanks!
Answer: Answering my own question, for the record...
Let random variables $x_1$ and $x_2$ be the sizes of the first and
second balls drawn, respectively.  Let $F$ be the set containing the indices of the
first two balls drawn.
We want to show that $E[x_1 - x_2] \ge 0$.
To show it, it suffices to show that $E[x_1 - x_2~|~ F=\{i,j\}] \ge 0$
for any two balls $i$ and $j$.
By calculation, $E[x_1 - x_2 ~|~ F=\{i,j\}] \ge 0$ is equivalent to
$$\frac{s_i}{S} \frac{s_j}{S-s_i}(s_i - s_j)
~+~\frac{s_j}{S} \frac{s_i}{S-s_j}(s_j - s_i) ~\ge~ 0.$$
(Recall $S$ is the sum of the sizes, so $s_i/S$ is the probability that $i$ is drawn first.)
Simplifying a bit, this reduces to the inequality
$$- s_j(s_i-s_j) - s_i(s_j - s_i) ~\ge~ 0$$
which is equivalent to
$$(s_i- s_j)(s_i-s_j) ~\ge~ 0,$$
which is true.

symmetric polynomial inequality?


Solve $\int_{0}^{\delta*b} \sqrt{log(\frac{\delta}{x})}dx $

Question: Could you help me to show that the integral
$$\int_{0}^{\delta*b} \sqrt{log(\frac{\delta}{x})}dx
$$
with $\delta>0$ and $b>0$ is just a multiple of $\delta$, i.e. $\int_{0}^{\delta*b} \sqrt{log(\frac{\delta}{x})}dx=C_b\delta$ with $C_b \in \mathbb{R}$?
*$log$ is the natural logarithm
Comment: Try a rescaling of the variable.
Comment: What is $b?$ The RHS does not depend on $b,$ or is $C=C(b)?$
Comment: Yes, question edited
Answer: Hint
Start changing variable $$\sqrt{\log \left(\frac{\delta}{x}\right)}\implies x=\delta e^{-t^2}\implies dx=-2 \delta e^{-t^2} t\,dt$$ So $$\int \sqrt{\log \left(\frac{\delta}{x}\right)}\,dx=-2 \delta\int e^{-t^2} t^2 \,dt$$ Now, one integration by parts to get a function which is familiar.
I am sure that you can take it from here.
Comment: Could it be possible for you to write also the integration region of the transformed integral? Thank you
Comment: I let that part to you. It is very simple : what is $t$ when $x=0$ ? what is $t$ when $x=\delta\,b$ ?
Comment: Ok, I get lower bound $-\infty$ and upper bound $\sqrt{-\log(b)}$. Now integration by parts: $\int t^2e^{-t^2}dt=\int t t e^{-t^2}dt=-\frac{1}{2}\int t (-2t)e^{-t^2}dt=-\frac{1}{2}te^{-t^2}+\frac{1}{2}\int e^{-t^2}dt$. What is $\int e^{-t^2}dt$?
Comment: I have another doubt: writing $\int_{0}^{\delta*b} \sqrt{log(\frac{\delta}{x})}dx
$ implicitly means assuming $b<1$?


How can I reset the program if the user inputs something not acceptable?

Question: I'm making a ping pong game where I ask for user input on their paddles. I have the screen and one paddle showing up and some user input for how they want to customize their paddle. But after asking for input, how can I rerun the program when the user inputs something not acceptable?
This is my code so far:

<canvas id="gameArea" width="1000" height="800"></canvas>

Comment: Example: https://javascript.info/task/repeat-until-correct
Answer: You can have a function promptPaddle() or something similar, which you can call again:

function promptPaddle() {
    let padH = prompt("how long would you like your paddle? 70 to 110 are good values");
    let padL = prompt("how wide would you like your paddle 2? 1 to 15 are good values");
    let padColor = prompt("What color paddle do you want?");
    handleInput(padColor, padL, padH)
}

const colors = ["white", "red", "blue", "green", "purple", "aqua", "brown", "cyan", "yellow"]

function handleInput(padColor, padL, padH) {
    if (colors.indexOf(padColor) === -1) {
        alert("that color is not supported");
        return promptPaddle();
    }
    if (70 < padH || padH < 110) {
        alert("please enter an acceptable value");
        return promptPaddle();
    }
    if (1 < padL || padL < 15) {
        alert("please enter an acceptable value");
        return promptPaddle();
    }
    // Got proper input, do whatever now
}

// Need to call it once to start the process
promptPaddle();

I should mention that it might be better to do this "loop validation" for each prompt separately. Right now, you can enter a wrong padH but otherwise a correct padL and padColor, but only after you've entered all 3 values will it go "actually your first value was already wrong, now re-enter all 3 again".
Comment: thanks so much for the reponse didnt really expect any. Im new to programming so thanks alot
Comment: im sorry i still dont understand
Comment: Your question was decently written and showed some effort, so unless it's a very complex question that's hard to answer, you'll usually get a quick response. And lots of people here like people that try to learn
Comment: @ZayanHasan Basically, your program will go `Ask question > check input > handle input`. If `check input` sees the input is wrong, you'd go back to `Ask question`. That's what my code does: `promptPadde()` asks the questions, `handleInput()` checks the inputs, and if there's a mistake, it returns to `promptPaddle()`. Otherwise it'll continue doing whatever `handleInput()` is supposed to do (which I marked with a simple comment)
Comment: lol thanks, but when i run this program it says uncaught error in line 18: colors not defined btw its the line right after function handle input
Comment: Ah, I just noticed I moved that `const colors` into the wrong place. My code was more of an overview of "you can do more or less this", not a perfect piece of code you could just copy-paste. I'll change it anyway
Comment: oh i see so where can i see it updating
Comment: Yay it works but even when i enter an acceptable value for the paddle it stills says to enter a acceptable one
Comment: should i add like an else statement that just continues the program if the input is acceptable, and if so, how?
Comment: @ZayanHasan I basically copied your comparison and just noticed you're using `70 < padH < 110`. I should've caught that, but that's not proper JavaScript, Well, _it is_, but it's checking `(70 < padH) < 110`, e.g. `someBoolean < 110`. You probably meant to use `(70 < padH) || (padH < 110)` instead
Comment: im stuck in a loop and cant go to the website screen, its just asking me to reenter a better input
Comment: Pressing F5 (or worst case, ctrl+W to close the tab) should get you out of the loop and allow you to reopen the site after fixing the code
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/235071/discussion-between-kelvin-schoofs-and-zayan-hasan).
Comment: ok i made the change in the inequality comparison.
Comment: i quit i cant do it


How can I calculate the best sail size for the current wind?

Question: Being a beginner in windsurf, I have several sails from 4.7 to 7.5 meters sq.
I find myself wondering how I can set the correct sail for the current wind.
How do we know what sail to use, and when to use it?
Is there any rule of thumb?
Answer: I came across a windsurfing blog post with a link to an Excel spreadsheet (titled "Ultimate Windsurfing Equipment Size Calculator"), developed by James Douglass. His spreadsheet runs some calculations using several factors:

windsurfer's weight
sail size

The spreadsheet has several reports/graphs:

Boards:

Minimum size beginners board you should be using
Ideal first short board
Smallest size windsurf board that can be uphauled

Sails:

Two lists showing different wind strengths & what size sail you should be using
A separate list showing wind strength & sail size for a beginner
A graph showing ideal sail size versus wind speed

This spreadsheet might offer the type of info you're looking for. Mr. Douglass also provides an online version of his spreadsheet.
He also provides the following advice to beginners in this "Top 16 Windsurfing Questions Answered" FAQ:

Question #6- I'm a beginner windsurfer looking for my first sail. What kind of sail should I get, and in what size?
Answer You should get a sail between 2 and 7 meters squared, depending on your size and the wind speed you are likely to sail in
  most often. Check the windsurfing equipment calculator to see what's
  right for you (pink line on chart). As you get better, you can start
  using sails closer in size to those recommended for experienced
  sailors (blue line on chart). Your first sail should have a minimum of
  3 and a maximum of 6 battens, and should have no camber inducers or
  "cams" on any of the battens. Also, avoid sails and masts made before
  the year 2000 and sails advertised for racing.

Another site had some pointers regarding sail size:

For an amateur windsurfer, sails ranging from 5 to 6.5 square meters in size are recommended as they work well for light winds up to winds of 4-5 knots.

This article offers a quick overview of sails, with this final recommendation:

We suggest you start off by choosing light-wind sails to get the knack
  of windsurfing. Eventually, you can experiment with various sizes of
  the sails, and finally find the one that appeals to you the most.

Enjoy!
EDIT: Added info from James Douglass' FAQ and a link to an online version of his calculator.
Answer: In addition to JW01's post, a key step change in the sizes you should use comes at the point you progress past uphauling to water starts.
When you uphaul, a large sail can be incredibly difficult, as the wind tries to push it back down into the water, and if you can't uphaul rapidly you will tend to pivot round leaving the mast pointing upwind - so a smaller sail is ideal.
Once you can water start, a bigger sail actually makes life much easier, as all you have to do is lie in the water upwind of the board, with the mast on your shoulder (very easy) and pop it up to catch the wind. A nice big sail can then lift you onto the board in even relatively light winds.
Of course the other aspect not mentioned is sea and wind conditions - if the sea is choppy, a smaller sail can be much easier to manage, but if the wind is gusty a large sail can help ride through the lulls.
Answer: Unfortunately there is no simple answer because so many factors influence what is the right sail size (roughly in order of importance for beginners):

What you aim to do. Do you want to be planing? Do you want to do lightwind freestlye tricks? Do you want to improve sail handling? Do you want to learn to use a harness?
Your skill level
Your weight
Wind strength
Board size and board type
Sail type (Slalom, Wave, Freestyle, Foil, etc.)
Fin size
Stability / Gustiness of the wind
Wave size

Depending on what you want to do, in the same 9-10m/s wind a very experienced windsurfer weighing 75kg could have a:

6.8m2 slalom sail and a 110L slalom board for blasting around.
5.6m2 freestyle sail and 95L freestyle board for doing freestyle tricks.
5.3m2 wave sail and 90L wave board for riding waves.
3.3m2 wave sail and 220L board if practicing something new that improves sail handling technique (e.g. heli-tack, backwinded sailing, reversing, board-sail 360)

The practical advice for beginners who don't really care about progress and just want to enjoy:

You will eventually get to know your gear and what sail is good for points 1-9. Just get on the water, start with bigger boards (160 -
250L, keel preferred) and smaller sails (3m2 - 5m2) (start with 3m2 if you weight 60kg or less, 5m2 if you weight 100kg) and you can slowly
increase the sail size according to your comfort level.

The practical advice for beginners if you want to progress fast:
Take the biggest board you can find (220L+) and smallest sail you can find (3m2 - 5m2) (start with 3m2 if you weight 60kg or less, 5m2 if you weight 100kg) and practice these super-fun tricks and techniques:

Tacks
Fast tacks (can you get to the other side in four steps, three steps, two??)
Gybes by flipping the sail first then the legs
Gybes by flipping the legs first then the sail
Sailing in switch stance
Heli-tacks
Board-sail 360's
Backwinded sailing
Reversing
And the ten or so other "light-wind" techniques (you can do these in moderately strong wind (7-9ms) too, just make sure you have a 3m2 - 3.5m2 sail in these conditions if you weigh 75kg).

When you learn to do each one it is so rewarding and fun you want to do them all the time!!!!!
Why am I giving this advice?

Decide: Do you want progress (might look sill short term, but gives amazing results in long term) or try to look pro right away (also looks silly in short term because you don't have the skill, no learning, no results in the long term)?

From having taught over 500 people to windsurf I can say most people
try to progress way too fast (we live in the era of instant
gratification). Windsurfing is about enjoying the journey and the
daily practice, being on the water and in nature. Many times I have
had a student weighing 80kg with a 100L board and 6.6m2 sail come to a
course to learn gybes. They barely stay upright with that gear, even
just trying to sail in a straight line. I put them on a 220L board and 4.5m2 sail and
then they are in the sweet spot for learning: they are falling down
30% of the time during training the gybes but make 70% of them: enough
that we can see what is going wrong and start improving. If you are
falling in over 50% of the time you are slowing your progress. We make
the board as stable as possible because windsurfing is all about
sail technique. If most of your focus is going into the board
something is terribly wrong. In fact, if you want to progress even
faster, the best thing you can do is practice on land because that
is the most stable surface you can ever get, allowing you to focus on
sail technique completely.
As an example, while being a windsurf instructor (3 years on the water pretty much every day) I found I could progress my own skill level fastest with a 220L board and 4.0m2 sail in wind speed of 1-7m/s, I weigh 75kg.
It felt so strange when people with a few months of experience (on the water only weekends) would come with 6-7m2+ sail size and 100L boards to attend my gybe courses. The difference in what I was doing to maximize progress and what they were doing to try and look pro couldn't be more dramatic.
Comment: There's a lot of commentary here that seems more targeted at general advice for a novice windsurfer than about choosing an appropriate sail size. I'm wondering if you can reduce the added commentary to just that which directly address the query.
Comment: Asking what is the appropriate sail size is like asking what are appropriate shoes for sports. The question is extremely general, hence the general answer.
Comment: Answering generally on how to choose a sail size is fine, because that is the question. Generally discussion of teaching and learning however is not answering the question. We aim to establish Q&A that do exactly that, unlike discussion forums or messageboards.


Jogando mais de um campo txt dentro do banco de dados

Question: Colegas.
Estou querendo pegar os dados de um arquivo txt que contém o nome e matrícula do usuário. Ex.:
Fernando Pessoa; 000011;
Ruth Cardoso; 000012;
....

Ao tentar pegar dessa forma:
    $diretorio = 'arquivos/';
    $arquivos = $diretorio . $_FILES['dados']['name'];

    if (move_uploaded_file($_FILES['dados']['tmp_name'], $diretorio . $_FILES['dados']['name'])) {
            $ler = fopen($arquivos,"r");
            $conteudo = fread($ler,filesize($arquivos));
            $dividir = explode(";",$conteudo);

              foreach($dividir as $valores){
                   echo $dividir[0]." => ".$dividir[1]."
";
                   // aqui faço o cadastro
           }
    }

Ele retorna apenas o primeiro nome e matrícula repetindo conforme a quantidade total de dados cadastrados no txt. Se tiver 30 nomes e matrículas, está trazendo 30 vezes Fernando Pessoa 000011 e nao os outros dados
Answer: Existem dois pontos onde está a falhar:

O explode primeiro teria de ser por quebra de linha (\n), e só depois por ';'
dentro do seu foreach está sempre a fazer echo dos mesmos dados ($dividir[0], $dividir[1])

Versão correta:
...
$dividir = explode("\n",$conteudo);
foreach($dividir as $valores){
    $exp = explode(';', $valores);
    if(isset($exp[1])) {
        echo $exp[0]. " => ".$exp[1]."
";
        // aqui faço o cadastro
    }
}
fclose($ler);

Comment: Perfeito Miguel. Funcionou. Obrigado !
Comment: @Fox.11 Depois de ler o arquivo feche o *handle* com `fclose($ler)`.
Comment: De nada @Fox.11. Ainda bem
Comment: @zekk, obgado vou editar de acordo, esqueci-me
Answer: Isso acontece porque você está acessando um valor fixo do array e não o elemento atual da iteração.
Altere: $dividir[0] e $dividir[1] por $valores[0] e $valores[1].
O modo de como fazer isto já foi explicado na resposta do Miguel, segue abaixo outra alternativa:
$diretorio = 'arquivos/';
$arquivo = $diretorio . $_FILES['dados']['name'];

if (move_uploaded_file($_FILES['dados']['tmp_name'], $arquivo)) {
  $conteudo = file_get_contents($arquivo);
  $linhas = explode("\n", $conteudo);

  foreach($linhas as $linha){
     if (empty($linha)){
       continue;
     }
  list($nome, $id) = array_map('trim', explode(";", $linha));

  echo "Nome: $nome - Matrícula: $id\n";
  // Fazer o cadastro...
}

É usado o file_get_contents() ao invés do fopen() para lidar com o arquivo.
A função trim() é para eliminar o espaço em branco entre o separador ; e os números.


Postfix: send all bounce messages to postmaster

Question: The situation is that we have a number of guests, say 80, sending through a central mail infrastructure out to the web. The way the network is setup the mail server cannot necessarily initiate connections back to each of the senders.
I understand I can disable bounce messages completely by turning disabling the bounce daemon but I'm concerned if I do this I will miss system-problems. What would be good if all bounces went to postmaster and I could look for them there. There is no reason to ever try to contact the senders back.
Any ideas how to achieve this? Googling mentioned NOTIFY=NEVER and some stuff about smtpd_command_filter although what I'm doing feels like it should be simpler than that. I can get the bounce messages to postmaster using notify_classes but I think that relies upon the bounce daemon.
I'm running CentOS 5.5 and postfix 2.3.3-2.1.el5_2
EDIT:
soft_bounce=yes seems to be another way to disable bounces, but this is not exactly what I want
Answer: In main.cf set notify_classes=bounce and bounce_notice_recipient=postmaster (which should be the default.
And then postmaster gets the copies of every bounce message.
You MUST NOT disable bounces. They are needed to notify the sender! And as there has to be a sender for a mail, this particular sender will be informed.
What do you mean by "cannot necessarily initiate connections back to each of the senders"? The server never initiates a "connection" to the sender. It delivers a bounce into the inbox of the sender. And don't tell me that you allow people to send mails without having an account at the mail system.
Comment: You should also consider enabling resource and software problem notification: `notify_classes = resource, software, bounce` (see: http://www.hsc.fr/ressources/cours/postfix/doc/basic.html)
Comment: _cannot necessarily initiate connections back to each of the senders_ could mean that the server doesn't have outbound Internet connectivity to send bounces back to external servers, isn't it?.
Answer: Using canonical_maps to rewrite all local, Postfix-generated addresses should allow you to set the envelope address (different from the sender) and have the bounces returned to a central postmaster address. Maybe http://s19n.net/articles/2011/postfix_nullclient.html can give some hints:
/etc/postfix/main.cf
myhostname = host.example.com
canonical_maps = hash:/etc/postfix/canonical

/etc/postfix/canonical
@host.example.com   email@example.com

Comment: This worked for me, I was trying to get the bounce address to be email@example.com rather than email@example.com! Helped me out a lot!


How can I avoid page faults with QML when using signals to communicate with and remove dynamic items?

Question: This pertains to a QML/C++  tile-based 2d Tower Defense Style Game
https://github.com/mikeNickaloff/TowerDefense-FullCommand-v2
The issue:
I decided to simply create my own form of collision checking, which is  very efficient.. but it has a slight problem:
The collision checking system I wrote generates  thousands and thousands of  page faults  very quickly -- over 1 million in a couple minutes.
The collision checking is responsible for handling bullet collisions.
I was wondering if anybody could help me pick out the fundamental flaw in the design that is causing the huge spike in page faults.
The Relevant Code
  main.qml   [ 3 functions ]
  property Component attackerComponent: Qt.createComponent("src_qml/AttackerVisual.qml");

/* create a dynamic attacker   */
    function create_atttacker(i_attacker)  {
        var component;
        component = attackerComponent;
        if (component.status == Component.Ready) {

            var dynamicObject = component.createObject(background, { /* properties here  from i_attacker */ });

   /*  CONNECTIONS  FROM   DYNAMIC ATTACKER OBJECT TO MAIN.QML */
            dynamicObject.show_particles.connect(particleOverlay.customEmit);
            dynamicObject.removeAttacker.connect(removeAttacker);

        }
    }

/* remove an attacker from the game */

function removeAttacker(attackerObject) {

     /*   mark the tiles that this attacker was on now inactive
          so that guns wont continue to shoot at them */

     var current_tile = attackerObject.current;
     var target_tile = attackerObject.target;
     current_tile.isActiveTarget = false;
     current_tile.isActiveTarget = false;

    /*   disconnect the show particles signal from the particle system */

    attackerObject.show_particles.disconnect(particleOverlay.customEmit);

    /*   Remove the attacker from the game's traqcking system */

    game.board.removeAttacker(attackerObject);

    /* destroy the attacker object */

    attackerObject.destroy();

}

/*  create a new bullet that can be fired from  a Gun Item (gunObj) */

function create_projectile(gunObj, target_x, target_y) {
    var projectileComponent =
          Qt.createComponent("src_qml/ProjectileVisual.qml");

    if (projectileComponent.status == Component.Ready) {

        var newObj = projectileComponent.createObject(background, {/* default properties from gunObj */ } );

        /* add projectile to magazine for later firing */

        gunObj.add_ammo_round(newObj);

    }
}

 Projectile.qml  [ 1 animation ]
Item {
  ...

ParallelAnimation {
       running: true;
       id: anim1
       NumberAnimation { property: "x"; ... }
       NumberAnimation { property: "y"; ... }

       onStopped: {

          /*  send signal from target_square  that the projectile
              hit this square */
          target_square.projectile_hit(min_damage, max_damage, splash_distance);
       }
   }

 Here's where things start to get convoluted, and I suspect is the source of the page faults

 Attacker.qml   [ 1 Animation,  1 Function ]
Item {

 id: viz

 ParallelAnimation {
        running: true;
        id: anim1
        NumberAnimation {  property: "x"; ... }
        NumberAnimation {  property: "y"; ...  }

        onStopped: {

           /* move one square forward along the attacker's path */
            current = target;
            target = next_path_square();

         /* disconnect from old path square so it doesnt send
           projectile hit events     */

            current.projectile_hit.disconnect(projectile_hit);
            target.projectile_hit.connect(projectile_hit);

            target.isActiveTarget = true;
            current.isActiveTarget = false;
        }
   }

 function projectile_hit(min_damage, max_damage, splash_distance) {

    /* check if Attacker hasnt been already destroyed */
    if (viz) {

        /*  send signal back to main.qml for particles */

        viz.show_particles(endX, endY);

        var attackerHealth = attacker.health;

        attackerHealth -= (Math.random() * (max_damage - min_damage)) + min_damage;

        if (attackerHealth < 1) {

                /* send signal back to main.qml   to destroy
                   this attacker */

                viz.removeAttacker(attacker);

        }

   }

Everything seems to work fine, but it seems to cause an infinitely increasing amount of page faults everytime a bullet hits an attacker and destroys it.
Thanks again for any advice you might have. Let me know if anything needs to be explained in better detail.. I cut out most/all of the irrelevant code already but didn't really give an in-depth explanation of how the whole process works.
Comment: I know that it won't be helpful, but the fatal flaw is that you're writing the so called "business logic" in QML/javascript. QML should only deal with presentation, js code should be short and it should not operate on the data of the application. Application's main logic should be coded in C++.
Comment: @Velkan could you please explain what is fatal to use more or less complex JavaScript code within QML file? Furthermore the javascript code used in question is not really business logic but setting some properties of QML component.
So how do you want to do this from C++ side?
Comment: Estimate how many components and items are created and destroyed. Also, note that there is no need to do `Qt.createComponent()` every time (it's probably re-parses the QML code). About application logic: for games I do a separate renderer, so QML is used only for the overlay GUI. If I had a requirement to render the whole game with QML - I would probably do all logic in C++, and then give coordinates/states of the objects via the `QAbstractListModel`s to QML. QML could render that with `ListView`s and maybe do some basic interpolation.
Comment: QML's javascript engine is not a general-purpose engine. It does its job best at evaluating bindings. Any other use is fine as long as it's done once, e.g. in setup code, or infrequently, e.g. when reacting to user input. Writing game logic in javascript is fine when you're running on a web browser with a general-purpose javascript runtime. QML doesn't have one. They ditched V8 precisely because it was way too high overhead to evaluate bindings in QML. The page faults are because the runtime goes through lots of pages, and possibly you leak memory, too (yes, JS code can leak!).
Comment: I already have most of the game written in C++, and only some of the logic is written in QML -- most of the complex stuff is actually in C++ anyways.

I can probably migrate the rest of the logic to C++ pretty easily -- interesting to note that they don't have a general purpose Javascript parser with QML -- seems fairly counter-productive  to even have a Javascript implementation at all with QML
Comment: @Velkran  That is what the purpose of the NumberAnimations are -- they are basically acting as interpolators for the dynamically created items like bullets that are basically only going to be there for a short time and then disappear -- and rather than re-parsing the entre QML file  I actually have it set up so that each Gun has a "Clip" with 3-4  bullet items that are invisible, and they just cycle which one is made visible and then fires the animation and puts it back on top of the gun invisible when finished -- seems to work fine -- only issue is with the Attackers
Answer: Figured it out -- it didnt really have anything to do with the fact that the Logic was written in QML, or with the files I posted in the question.
The fact was that there were too many large files to post them all up here, so I picked the top 3 parts I thought were the most likely culprits.
Apparantly in the end it was all because I had a C++ Q_INVOKABLE method which was directly bound to a property which had code involving the looped generation of a somewhat complex list being casted to QVariant --
The solution was to simply change the property acccessor  from MEMBER to READ  and then save the MEMBER separately and then just return the pre-computed value whenever QML wanted it.
This pretty much wrapped up all of the memory issues.
Thanks everyone for your input
For reference:
In  Board.cpp

   class Board : public QObject {
Q_OBJECT

/* bad Property at fault */

/*    Q_PROPERTY(QVariant attackers READ attackers) */

/* fixed version */
Q_PROPERTY(QVariant attackers MEMBER m_attackers)

public:
Board(QObject *parent = 0 );

/* bad declaration */
/* QVariant attackers() {
    QVariant rv;
    foreach(Attacker * attacker, this - > m_attacker_hash.values()) {
        rv.append(QVariant::fromValue(attacker));
    }
    return rv;
} */

/* Good declaration */
QVariant  m_attackers;

/*   One time population of m_attackers */
Q_INVOKABLE bool update_attackers() {
    QVariant rv;
    foreach(Attacker * attacker, this - > m_attacker_hash.values()) {
        rv.append(QVariant::fromValue(attacker));
    }
    m_attackers = rv;
    return true;

}
};


Retornar um CURSOR de uma procedure SqlServer com sql dinamico (sp_executesql)

Question: No oracle eu posso fazer da seguinte forma :
OPEN MY_CURSOR FOR 'SELECT * FROM MY_TABLE'

Como obter esse resultado no SqlSever? Quero retornar um cursor montando um sql dinâmico na procedure.
Atualmente estou usando assim:
CREATE PROCEDURE MY_PROC(@PARAM INT)
AS
SELECT * FROM MY_TABLE

Answer: Jeterson, você vai estar combinando o pior dos dois mundos, um cursor e uma query dinamica, mas você deve saber a necessidade..
Olha esse exemplo:
declare @sSQL nvarchar(4000)
Declare @des_Name VarChar(200)

set @sSQL = 'Declare Teste_cursor CURSOR FOR Select name from sys.objects'

exec sp_executesql @sSQL

OPEN Teste_cursor
FETCH NEXT FROM Teste_cursor
INTO @des_Name

WHILE @@FETCH_STATUS = 0
BEGIN
Print @des_Name

FETCH NEXT FROM Teste_cursor
INTO @des_Name

END
CLOSE Teste_cursor
DEALLOCATE Teste_cursor


Per-user routing doesn't seem to work

Question: So, I'm trying to implement per-user routing so that I'm able to route all btpd torrent traffic over a VPN. Unfortunately, btpd does not currently allow you to bind to a specific IP address. :(
I decided to try to follow this guide.
Basically, you mark any packets and then do SNAT or DNAT or MASQUERADE to the packets, then use ip rules to force a specific route table.
In the end, my setup:
(To my router)
eth1  Link encap:Ethernet  HWaddr 00:0a:cd:18:8a:ae
      inet addr:172.29.5.10  Bcast:172.29.5.255  Mask:255.255.255.0
      inet6 addr: fe80::20a:cdff:fe18:8aae/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:2073338425 errors:0 dropped:0 overruns:0 frame:0
      TX packets:2031270514 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:3014149031 (2.8 GiB)  TX bytes:1897259705 (1.7 GiB)
      Interrupt:17 Base address:0x6c00

(my VPN)
tun0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
      inet addr:10.1.1.4  P-t-P:10.1.1.4  Mask:255.255.255.0
      UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
      RX packets:7842859 errors:0 dropped:0 overruns:0 frame:0
      TX packets:8040846 errors:0 dropped:41433 overruns:0 carrier:0
      collisions:0 txqueuelen:100
      RX bytes:1544016294 (1.4 GiB)  TX bytes:1737654278 (1.6 GiB)

iptables -t mangle -vnL (this is where I mark the packets):
Chain PREROUTING (policy ACCEPT 42 packets, 3595 bytes) pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 42 packets, 3595 bytes) pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes) pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 36 packets, 3461 bytes) pkts bytes target     prot opt in     out     source               destination
0     0 MARK       icmp --  *      *       0.0.0.0/0            0.0.0.0/0           owner UID match 1000 MARK set 0x2a
0     0 MARK       udp  --  *      *       0.0.0.0/0            0.0.0.0/0           udp dpt:!53 owner UID match 1000 MARK set 0x2a
0     0 MARK       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           owner UID match 1000 MARK set 0x2a

Chain POSTROUTING (policy ACCEPT 36 packets, 3461 bytes) pkts bytes target     prot opt in     out     source               destination

My iptables -t nat (Where I switch the source address):
Chain PREROUTING (policy ACCEPT 10 packets, 536 bytes) pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 10 packets, 536 bytes) pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 6 packets, 360 bytes) pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 6 packets, 360 bytes) pkts bytes target     prot opt in     out     source               destination
0     0 MASQUERADE  all  --  *      tun0    0.0.0.0/0            0.0.0.0/0

Output of ip rule show:
0:      from all lookup local
32761:  from all fwmark 0x2a lookup 42
32762:  from 10.1.0.0/16 lookup 42
32766:  from all lookup main
32767:  from all lookup default

And finally, output of ip route show table 42:
default via 10.1.1.1 dev tun0

Now, everything seems to work fine when I do a tcpdump on my VPN interface at first. But, then it become apparent that my programs are not recieving the SYN-ACK of the threeway hand shake.
This is the output of the user with uid 1000 running curl ifconfig.me:
21:34:08.585901 IP 10.1.1.4.55707 > www1465.sakura.ne.jp.http: S 342876994:3342876994(0) win 5840 <mss 1460,sackOK,timestamp 2892988166 0,nop,wscale 6>
21:34:08.852160 IP www1465.sakura.ne.jp.http > 10.1.1.4.55707: S 530223170:3530223170(0) ack 3342876995 win 65535 <mss 1368,nop,wscale 6,sackOK,timestamp 248042701 2892988166>
21:34:11.587175 IP 10.1.1.4.55707 > www1465.sakura.ne.jp.http: S 342876994:3342876994(0) win 5840 <mss 1460,sackOK,timestamp 2892991168 0,nop,wscale 6>
21:34:11.848906 IP www1465.sakura.ne.jp.http > 10.1.1.4.55707: S 530223170:3530223170(0) ack 3342876995 win 65535 <mss 1368,nop,wscale 6,sackOK,timestamp 248042701 2892991168>
21:34:14.890209 IP www1465.sakura.ne.jp.http > 10.1.1.4.55707: S 530223170:3530223170(0) ack 3342876995 win 65535 <mss 1368,nop,wscale 6,sackOK,timestamp 248042701 2892991168>
21:34:17.603173 IP 10.1.1.4.55707 > www1465.sakura.ne.jp.http: S 342876994:3342876994(0) win 5840 <mss 1460,sackOK,timestamp 2892997184 0,nop,wscale 6>
21:34:17.863614 IP www1465.sakura.ne.jp.http > 10.1.1.4.55707: S 530223170:3530223170(0) ack 3342876995 win 65535 <mss 1368,nop,wscale 6,sackOK,timestamp 248042701 2892997184>
21:34:20.901869 IP www1465.sakura.ne.jp.http > 10.1.1.4.55707: S 530223170:3530223170(0) ack 3342876995 win 65535 <mss 1368,nop,wscale 6,sackOK,timestamp 248042701 2892997184>
21:34:26.962022 IP www1465.sakura.ne.jp.http > 10.1.1.4.55707: S 530223170:3530223170(0) ack 3342876995 win 65535 <mss 1368,nop,wscale 6,sackOK,timestamp 248042701 2892997184>
21:34:39.099655 IP www1465.sakura.ne.jp.http > 10.1.1.4.55707: S 530223170:3530223170(0) ack 3342876995 win 65535 <mss 1368,nop,wscale 6,sackOK,timestamp 248042701 2892997184>

As you can see, the masquerading seems to be working and I'm getting a return response. However, curl acts like it is not receiving the response. This is quickly verified with a netstat -an | grep SYN which shows curl was trying to use my internel network, not the VPN.
tcp        0      1 172.29.5.10:58000       22.214.171.124:80        SYN_SENT

I've tried doing SNAT and DNAT versus MASQUERADE to the same exact result. At this point, I'm not sure why curl is not recieving a response. Thanks.
Comment: Wouldn't it just be easier to fix `btpd` so it could bind to a specific IP address?
Comment: Just to be clear, this has been solved. I had disabled rp_filter on both eth1 and tun0, but I did not disable it on "all". Disabling rp_filter on all, as well as on the individual interfaces was what was required.
Answer: Please verify that rp_filter is disabled.  See section 10.1 of the LARTC HOWTO..  Also see this answer on a similar question

Also, if you do a ip route show table main | grep 'dev tun0' you will probably see a route like below.  You need to create a route like this your table 41.
10.1.1.0/24  proto kernel  scope link dev tun0 src 10.1.1.4

Comment: Sorry, should have specified above that reverse path filtering is disabled.  I stand corrected.  rp_filter was diabled on the individual interfaces, but it ALSO had to be disabled under all as well.
Answer: The solution is to disable rp_filter as said earlier. But you shouldn't disable rp_filter in vain. I tried this and found out you need to switch it off only on the "per-user" interface, which was ppp0 in my case:
echo 0 | sudo tee /proc/sys/net/ipv4/conf/ppp0/rp_filter

Of course you can do it more correct by putting it to /etc/sysctl.conf.

Per-user routing doesn't seem to work


Google Marker Manager not defined

Question: im trying to create a google marker manager but get the error message marker is not defined, ive commented out the code that is causing the problem, i have it set to user clicking on the map and places a marker, i want it to be able to do this automatically appearing on the google map using the GOOGLE MARKER MANAGER
@{
    ViewBag.Title = "Index";
}

Index

Error Message: MarkerManager is not defined
Answer: You're mixing up Google Maps API 2 and API 3 code.
Remove the v=2 parameter or change it to v=3 (or v=3.5 for instance).
Change this:
sensor=truese
to either
sensor=true or sensor=false
Remove the API key, that's only required for API 2.
Get rid of all the GMap2, GLatLng type of code that is for API 2 and change it all to be in API 3 syntax.
Comment: You could probably start here: http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/docs/examples.html
Comment: i've updated my code, i have a new problem now, sorry for the confusion.. i will give your solution a go and see what happens, stupid me mixing up the API codes.
Comment: trying it your way still causing problems, i will stick to the coding amendment i have done in my first post and wait till someone can help/guide me
Comment: 'your way' is still using API 2 code which isn't compatible with API 3.  Are you calling in the JS file that the Marker Manager requires?
Comment: how do i change it to API 3 then? this is all kinda newish to me. Damn i dont have the JS file where can i download that from or can i call it externally?
Comment: i follow that and using the markermanager.js file still says GBound is not defined, seems there are  problems with the js file, is there another way around this?

Google Marker Manager not defined


Determine the convergence/divergence of $\sum_{n=1}^{\infty}{\frac{2.4.6...(2n)}{1.3.5...(2n-1)}}$?

Question: How can I determine the convergence/divergence of $\sum_{n=1}^{\infty}{\frac{2.4.6...(2n)}{1.3.5...(2n-1)}}$?
I tried using the Ratio Test
$|a_n|=\frac{2.4.6...(2n)}{1.3.5...(2n-1)}$
$|a_{n+1}|=\frac{2.4.6...(2n).(2n+2)}{1.3.5...(2n-1)(2n+1)}$
$\lim_{n -> \infty}{|a_{n+1}|/|a_n|} = \lim_{n->\infty}{\frac{2n+2}{2n+1}}= 1$ therefore I can't reach any conclusion.
I don't know another way to solve this. Please help.
Comment: The convergence test one should *always check first* is whether the general term goes to 0 or not.
Answer: Hint for every n we see that the even numbers are greater than corresponding odd numbers. Ie $2>1,2.4>3,2.4.6>1.3.5.. $ thus $\frac {2}{1}>1,\frac {8}{3},\frac {48}{15}.. $ thus each term is greater than $1$ thus sum of  product diverges


Predicting from a highly skewed dataset

Question: I would like to find the factors that contribute to a particular event happening. However that event occurs only about 1% of the time. So if I have a class attribute called event_happened,  99% of the time the value is 0, and 1 only 1% of the time. Traditional data mining predictions techniques (decision tree, naive bayes etc) don't seem to be working in this case. Any suggestions as to how should go about mining this dataset? Thanks.
Answer: This is the typical description of the task Anomaly detection task
It defines its own group of algorithms:

In data mining, anomaly detection (or outlier detection) is the identification of items, events or observations which do not conform to an expected pattern or other items in a dataset.

And a statement about the possible approaches:

Three broad categories of anomaly detection techniques exist. Unsupervised anomaly detection techniques detect anomalies in an unlabeled test data set under the assumption that the majority of the instances in the data set are normal by looking for instances that seem to fit least to the remainder of the data set. Supervised anomaly detection techniques require a data set that has been labeled as "normal" and "abnormal" and involves training a classifier (the key difference to many other statistical classification problems is the inherent unbalanced nature of outlier detection). Semi-supervised anomaly detection techniques construct a model representing normal behavior from a given normal training data set, and then testing the likelihood of a test instance to be generated by the learned model.

What you would choose is a question of personal flavor.
These approaches will help "learn" to find out outlier events; then the model that "predicts" them will define the factors that you are interested in.
Comment: @Mateva, thanks, but in OUtlier detection you're trying to know who the outliers are. In my case, I already know them. I just need to find out what is making them become outliers.
Comment: @user3853906 I am not sure you can differentiate these tasks completely. How do you describe each event? Are the factors you are interested in part of this description?
Comment: ... and to avoid confusion, I mean what are the attributes of the events in your data? What kind of outputs you would expect?
Comment: @Mateva, lets say my attributes are hour_of_the day, day_of_the_week, state, customer_age, customer_gender etc. And I want to find out which of these factors contribute to my event occurring. Of course I could do a univariate analysis (say the event occurs with 60% male and 40% female customers), but that wouldn't give me the complete picture. I want a multivaraite analysis with Decision Tree or LOgistic Regression or something.
Comment: @user3853906 Why don't you add that to your question? It will greatly help the readability and improve the question.
Comment: @user3853906 Based on your answer, I believe you need classification, but your result will be the model.
Answer:
lets say my attributes are hour_of_the day, day_of_the_week, state, customer_age, customer_gender etc. And I want to find out which of these factors contribute to my event occurring.

Based on this answer, I believe you need classification, but your result will be the model itself.
So, you perform, say, logistic regression, but your features are the data attributes themselves(some literature doesn't even separate features and attributes).
You have to somehow normalize this data. This can be tricky. I would go for boolean features(say hour_of_event==00, hour_of_event==01, hour_of_event==02,...)
Then, you apply any classification model, you end up with weights against each of the attributes. The attributes with (the highest weights will be the factors that you need).
Answer: This is an unbalanced classification problem.
I'm pretty sure I have seen some surveys and overview articles on methods that can handle unbalanced data well. You should research this term ("skew" is a bit broad, and may not get you the results you are looking for).

Predicting from a highly skewed dataset


How to send parameters to AJAX POST method of another PHP website and fetch JSON information

Question: I am researching on "how to parse the content from other website". I am using HTML DOM parsing to fetch the information. Problem i am facing is with websites which contains AJAX POST calls to fetch the information. Example website: Massachussets
1.Here doctors information is fetched using ajax post method
Request URL:http://www.massgeneral.org/assets/javascripts/facets/doctors/doctors.ashx
Request Method:POST

How do i pass the parameters to post methods here?. What i tried is
<?php
echo '
Massachusetts Information
';
// extra headers
//$headers[]= "Accept-Encoding: gzip, deflate";
$fields['center'] = "";
$fields['centerPreSelected'] = false;
//$fields['displayPaging'] = false;
$fields['gender'] = "";
$fields['isEmpty'] = true;
$fields['languages'] = [];
$fields['letter'] = "A";
$fields['letter'] = "";
$fields['locations'] = array();
$fields['numberOfPages'] = 15;
$fields['numberPerPage'] = 50;
$fields['page'] = 1;
$fields['program'] = "";
$fields['range'] = array('Item1' => 0,'Item2' => 49);
$fields['saytLimit'] = "20";
$fields['term'] = "";

$POSTFIELDS = http_build_query($fields);

$headers[] = "Accept: application/json, text/plain, */*";
$headers[] = "Accept-Encoding: gzip, deflate";
$headers[] = "Accept-Language: en-GB,en;q=0.5";
$headers[] = "Connection: keep-alive";
$headers[] = "Content-Type: application/json";
$headers[] = "Host: www.massgeneral.org";
$headers[]="Referer: http://www.massgeneral.org/doctors/";

$login_submit_url = "http://www.massgeneral.org/assets/javascripts/facets/doctors/doctors.ashx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER,  0);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt($ch, CURLOPT_URL, $login_submit_url);
curl_setopt($ch, CURLOPT_HTTPHEADER,  $headers);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
$result = curl_exec($ch);

echo $result;

It did not fetched the doctors information.
Please provide links or idea to parse it.
Comment: If I understand you correctly, you're trying to scrape the content of a website, but that website uses AJAX to populate its content. So when you use cURL to get the website's content, it's missing the content populated by AJAX, and you want to know how to get that.. right?
Comment: Are you wanting to do this for a particular site where the AJAX call is known ahead of time, or for any given site that may contain such a call?
Comment: What you want to extract in that information? Have you tried `DOMDocument`?
Comment: Nope.This i heard for first time.I want to retrieve all doctors information from that site.
Comment: @Nick Coons .Exactly !...I think i m missing some parameters to send while calling AJAX POST
Comment: To any given site contain such call. I picked [Massechusets](http://www.massgeneral.org/doctors/) as of now
Answer: You're using http_build_query() which creates a "foo=1&bar=2" style format. The site is expecting json so you want to use json_encode() instead.
Also, leave out the gzip header unless you're sure you really want to deal with a gzipped response.
Comment: Take out the gzip header. It's sending you a gzipped response because that's what you asked for.
Comment: When i replaced `http_build_query()` with `json_encode()` it return output like this : ���`I�%&/m�{J�J��t��`$ؐ@������iG#)�*��eVe]f@�흼��{���{���;�N'���?\fdl��J�ɞ!���?...................can you please suggest where all i need to make changes in my code?


Nginx with http/https - Http seemed redirected to https all the time

Question: I've this really weird behaviour with my ubuntu 10.04 / nginx 1.2.3 server.
Basically I changed the SSL certificates this morning.
And ever since it has been behaving weirdly on all apps.
Godaddy is reporting that HTTPS/SSL setup is correct.
When I try a page it still works correctly when I'm using HTTPS.
But when I try using HTTP nginx reports error :
400 Bad Request
The plain HTTP request was sent to HTTPS port

After looking around on google for hours, I've tried different setup (while originaly my setup was working correctly for longtime, I just renewed certificates)
I kindof found a half solution by adding this to my config :
error_page 497 $request_uri;
The realllly weird thing is that when I use this setup :
server {
    listen 80;
    server_name john.johnrocks.eu;

    access_log /home/john/envs/john_prod/nginx_access.log;
    error_log /home/john/envs/john_prod/nginx_error.log;

    location / {
        uwsgi_pass unix:///home/john/envs/john_prod/john.sock;
        include uwsgi_params;
    }

    location  /media  {
        alias   /home/john/envs/john_prod/johntab/www;
    }

    location  /adminmedia  {
        alias   /home/john/envs/john_prod/johntab/www/adminmedia;
    }
}

I still have the same error when using HTTP (while nothing is setup for HTTPS here)??
I'm getting crazy on this !
**Update
Even with this config :
server {
    listen       80;
    server_name  john.johnrocks.eu;

    access_log  /home/john/envs/john_prod/nginx.access.log;

    location / {
        root   /home/john/envs/john_prod/johntab/www;
        index  index.html index.htm;
    }
}

I get error 400 (The plain HTTP request was sent to HTTPS port) on everything I try to load ..
Comment: Basically it seems that all traffic is redirect to the 443 port whether I try seeing a page with http or https
So all my apps are working correctly in https
but when I try http I get error 400 "the plain http request was sent to https port"
The weird thing is that I didn't change my setup
All was working fine before
I just renewed the ssl certificates from godaddy
Any idea ??????
Comment: Now I have change my vhost file many times with suggestions from internet
doesn't change a thing
I halve fixed it with
error_page 497 $request_uri;
so it's a trick that catch the error and return what's requested instead
now my webpage is completely weird
it loads, but all the additional resources are loaded, but with error 400
Answer: I don't know about the 400 error, but if you had an 301 (permanent) redirect in your previous config, the browser might still have stored this redirect in the cache and doesn't check the original. Maybe purging your caches might help.
Answer: So I found out what the problem was.
The problem comes from how nginx loads the vhosts configurations.
If you look at nginx.conf, you will find this line
include /etc/nginx/sites-enabled/*;

So this loads all the "vhosts" into the main nginx.conf in a random order.
So what happend is that the error was somewhere else, in another vhost .. and it was making all the vhosts fail basically (no error was detected by nginx, it was not an error per se but a bad configuration).
So I removed all the sites-enabled vhosts, and put them back one by one, reloading nginx and testing the site each time until I got them all right and then voilà
Comment: Thanks for sharing how you fixed it. Why don't you select your answer as the right answer?


Ports needed for IP Subnet discovery Kaspersky Security Center 10

Question: I'm trying to discover computers based on IP subnets.
The administration server is not part of the same workgroup or active-directory as the clients, so this is the only way to do it.
I can discover about 1/3-1/2 of my computers.
I tried disabling the windows firewall totaly on one of the computers, and it seemed to add itself to the list of unmanaged computers.
When just opening for ICMPv4, so the management server can ping the target client-computer it does not work.
It looks like I'm missing some ports that needs to be open in the windows firewall - but the great internet can't tell me which ports!
Have anyone done this before, and got a clue about what ports I'm missing? Disabling Windows Firewall for all clients, to install the Kaspersky one is not much of a solution.....
Comment: You may find this interesting http://support.kaspersky.com/us/9297
Comment: @krisFR Thanks for the hint - but unfortunately, none of that helps.. Seems like I've found a solution - so I'll answer my own question.
Answer: In addition to the ICMP, Kaspersky Security Center uses NETBIOS to communicate with it's clients. The problem I ran in to was that Windows 8 have disabled "file and printer-sharing" in addition to ICMP in the Windows Firewall.
When allowing both those to pass, the clients show up!


Solving equation $x^3+x^2+x=1$

Question: Find a solution for equation $x^3+x^2+x=1$.
I found $x=0.54369 (which is  approximately equal to Cosine of 57 degree) by
trial and error as follows:
$(0.6)^3+(0.6)^2+0.6=1.176$...
$(0.5)^3+(0.5)^2+0.5=0.875$...
so $0.5< X < 0.6$
and $(0.54369)^3+(0.54369)^2+ 0.54369=1.000002936$
can anyone gives an anlytic solution for this equation?
Thanks for solution, it could be more useful if it was in detail.
Comment: Use Cardano's formulas.
Comment: I doubt there's anything you can do that's nicer than just using the cubic formula.  According to WolframAlpha, your solution is incorrect and the correct solution is $x = 1/3 ((17+3 \sqrt{33})^{1/3}-2/(17+3 \sqrt{33})^{1/3})-1/3$.
Comment: @EricWofsey: the OP's value is exact in all the given decimals.
Comment: @YvesDaoust: But their proposed identification of it with a cosine value is not correct.
Comment: @EricWofsey: well, the value is $\cos57.0648791\cdots°$, which bears some resemblance with the OP's answer (fixing the conversion from degrees to radians). But the use of a cosine is indeed irrelevant here.
Comment: You may use honer's method to solve this
Answer: If you use Cardano's method, you will notice that the equation has only a real root.
Using the depressed equation $$t^3+pt+q=0$$ you have $p=\frac{2}{3}$ and $q=-\frac{34}{27}$. Looking at the hyperbolic solution for one real root leads to $$t=\frac{2\sqrt{2}}{3} \sinh \left(\frac{1}{3} \sinh ^{-1}\left(\frac{17}{2
   \sqrt{2}}\right)\right)$$ Back to $x$ the solution write $$x=-\frac 13+\frac{2\sqrt{2}}{3}  \sinh \left(\frac{1}{3} \sinh ^{-1}\left(\frac{17}{2
   \sqrt{2}}\right)\right)$$ which is $\approx 0.5436890$ while $\cos \left(\frac{57\pi  }{180}\right)\approx 0.54463904$
Comment: Shame on the silent downvoter.
Comment: @YvesDaoust. Once more ! What is really bad is that I tried to exactly follow the steps given in the Wikipedia page.
Comment: You mean the depressed $t^3+pt+q=0$

Solving equation $x^3+x^2+x=1$


File upload empty in custom form

Question: I have a really simple form with a file upload. It actually used to work until I recently noticed it's not saving the file. When I check for the submitted values, the file field is empty, but the file is in $_FILES.
Here is how I build the form:
function tag_graphics_form($form_state) {
    $form = array();
    $form['tag'] = array(
        '#required' => TRUE,
        '#type' => 'textfield',
        '#title' => t('Tag'),
        '#size' => 30,
      );
    $form['image'] = array(
        '#type' => 'file',
        '#title' => t('Image for tag page'),
        '#description' => 'Recommended width for image: 605px'
    );
    $form['description'] = array(
        '#type' => 'textarea',
        '#title' => t('Page Description for SEO')
    );
    $form['#attributes'] = array('enctype' => "multipart/form-data");
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save'
    );
    return $form;
}

And this is how I process things in the submit:
function tag_graphics_form_submit( $form, &$form_state ) {
    // save the image and put to the database
    print_r($form_state['values']);  // the image field is completely empty here. other fields are ok
    print_r($_FILES); // the uploaded file is here just fine
    if ($form_state['values']['image']) { // all of this used to work...
        $validators = array();
        $file = file_save_upload('image', $validators, file_directory_path());
        file_set_status($file, FILE_STATUS_PERMANENT);
        $filepath = $file->filepath;
    }
    // more code...
}

Answer: function tag_graphics_form($form_state) {
    $form = array();
    $form['#attributes'] = array('enctype' => "multipart/form-data");
    $form['tag'] = array(
        '#required' => TRUE,
        '#type' => 'textfield',
        '#title' => t('Tag'),
        '#size' => 30,
      );
    $form['image'] = array(
        '#type' => 'file',
        '#title' => t('Image for tag page'),
        '#description' => 'Recommended width for image: 605px'
    );
    $form['description'] = array(
        '#type' => 'textarea',
        '#title' => t('Page Description for SEO')
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save'
    );
    return $form;
}

function tag_graphics_form_validate($form, &$form_state){
  $field = 'image';

  $directory = file_directory_path();
  if (file_check_directory($directory, FILE_CREATE_DIRECTORY, $field)) {
    $validators = array();
    if ($file = file_save_upload($field, $validators, $directory)) {
      file_set_status($file, FILE_STATUS_PERMANENT);
      $form_state['storage']['file'] = $file;

    }
  }
}
function tag_graphics_form_submit(&$form, &$form_state){
  print_r($form_state['storage']['file']);
}

Comment: @Moshe Nice to hear you :)

File upload empty in custom form


Integração MongoDB com ASP.NET MVC 5 e PostgreSQL

Question: Estou construindo um projeto em ASP.NET MVC 5 com banco de dados PostgreSQL, neste banco existe uma tabela de histórico que crescerá em cerca de 500 mil linhas por mês e teremos relatórios que pegarão dados de períodos de um ano.
Então pensamos em utilizar o MongoDb para esta tabela específica e todo o restante do banco seria com PostgreSQL.
Visto que teremos um performance bem maior nesta tabela usando MongoDb.
Vale a pena utilizar este tipo de arquitetura com PostgreSQL e MongoDb no mesmo projeto?
Se sim, qual a melhor forma de fazer e quais ferramentas?
Se não, qual o método mais apropriado?
Answer:
Vale a pena utilizar este tipo de arquitetura com PostgreSQL e MongoDb no mesmo projeto?

Se seu projeto realmente trabalhar com dados relacionais e não relacionais, vale muito a pena sim. E aparentemente, para seu fim, é bem apropriado.

Se sim, qual a melhor forma de fazer e quais ferramentas?

Parece que será seu primeiro contato com MongoDb, certo? Recomendo esse curso de introdução ao MongoDB. Me ajudou bastante no meu primeiro contato. E para recuperar os dados, vc pode sincronizar os dados com um ElasticSearch com Kibana.

Se não, qual o método mais apropriado?

É sempre o arquiteto do software quem deve tomar essas decisões. Se vc é o cara que está desenhando o sistema, é vc quem deve decidir. Brinque um pouco com bases NoSQL como MongoDB, e vc irá descobrir um mundo novo de possibilidades e quebras de alguns limites, claro que tudo isso junto com a quebra de vários paradigmas.
Comment: Obrigado pela resposta


ActiveAdmin's export to .csv is missing object attributes (Rails 3.2)

Question: I am using Active Admin 0.6.3 in my Rails 3.2 app. When I use the link in the bottom-left corner of an index to export to .csv I am noticing that several of the object's attributes are being left out, including some crucial ones.
For example, I am trying to export the Jobs table. Every job has a user_id attribute that shows which user is associated with the job. However, this row is not appearing in the .csv file generated by the export action.
When I export to JSON, all of the object's database attributes are present. However, none of the custom columns that I created in the ActiveAdmin index are included in the export. This is a separate but related problem.
Can anyone help me understand why this is taking and find a solution so that all of the database attribtues for my objects shows up in the .csv? And is not possible to have AA export what's actually in my AA index (including custom columns) and not just the values pulled directly from the object in the db?
Answer: As it turns out, AA provides instruction in its docs about how to customize the .csv export format. The process is very similar to customizing the index view itself:
http://activeadmin.info/docs/4-csv-format.html


How do I prove there exists a such measurable function?

Question: Let $V$ be a closed subspace of $L^2([-1/2,1/2]^n)$.
Let $f:(S^1)^n\rightarrow \mathbb{C}$ be a continuous function.
Define $\rho:[-1/2,1/2]^n\rightarrow (S^1)^n:x\mapsto (e^{2\pi i x_1},...,e^{2\pi i x_n})$.
I have proven that for each continuous function $f\in C((S^1)^n,\mathbb{C})$, $f\circ \rho \in V$.
With this information, how do I prove that $V=L^2([-1/2,1/2]^n)$?
Since $C([-1/2,1/2]^n,\mathbb{C})$ is dense in $L^2([-1/2,1/2]^n)$, it suffices to prove that $C([-1/2,1/2]^n,\mathbb{C})$ is contained in $V$.
However, I'm stuck here. Let $f:[-1/2,1/2]^n \rightarrow \mathbb{C}$ be a continuous function. Then, does there exist $g\in C((S^1)^n,\mathbb{C})$ such that $||g\circ \rho -f||_2 <\epsilon$ for each $\epsilon>0$? How do I prove this?
I have an idea but it is really hard to formalize the proof. I want a formal one..
Comment: Of course there is such a $g$, namely $f \circ \rho$.  That's not what you need.  You need to start with a $g$ and approximate it by $f \circ \rho$.
Comment: @RobertIsrael Edited thank you!
Comment: My idea is this. Note that $f$ is bounded. Hence, consider a domain $[-1/2,1/2-\delta]^n$ such that the measure of $[-1/2,1/2]^n \setminus [-1/2,1/2-\delta]^n$ is smaller than $\epsilon/M$. Then, expand the restricted $f$ on this small rectangle to the original rectangle to construct such $g$.
Answer: Hint: Start by defining $g$ on $\rho([-1/2,1/2-\delta]^n)$, where $\delta > 0$ is sufficiently small, to make $g \circ \rho = f$ on $[-1/2, 1/2-\delta]^n$, and extend to all of $(S^1)^n$ using the Tietze extension theorem.
Comment: this was somewhat in my mind. I did not think to apply Tietze on $(S^1)^n$! But I tried to apply Tietze on $[-1/2,1/2-\delta]^n$ and this was where I was stuck. Thank you!


How do I use hook_search_api_solr_search_results_alter() to alter search results?

Question: I want to alter the results of a Drupal 8.x search_api_solr search using hook_search_api_solr_search_results():
function sbn_search_api_solr_search_results_alter(\Drupal\search_api\Query\ResultSetInterface $result_set,
                                                     \Drupal\search_api\Query\QueryInterface $query,
                                                       \Solarium\QueryType\Select\Result\Result $result) {
 $resultset_data = $result->getData();
  // Get docs in response results
  $results = $resultset_data['response']['docs'];
  foreach ($results as $id => &$item) {
    // get the doc and array id
  }
}

I know that the docs I seek are in the search results:
dsm($result);

returns
stdClass Object
(
    [__CLASS__] => Solarium\QueryType\Select\Result\Result
    [numfound:protected] => 5
    [maxscore:protected] => 1.8644972
    [nextcursormark:protected] =>
    [documents:protected] => Array
        (
            [0] => stdClass Object
                (
                    [__CLASS__] => Solarium\QueryType\Select\Result\Document
                    [fields:protected] => Array
                        (
                            [ss_search_api_id] => entity:node/47:en
                            [ss_search_api_language] => en
                            [score] => 1.8644972
                        )

 ...
    [data:protected] => Array
        (
            [response] => Array
                (
                    [numFound] => 5
                    [start] => 0
                    [maxScore] => 1.8644972
                    [docs] => Array
                        (
                            [0] => Array
                                (
                                    [ss_search_api_id] => entity:node/47:en
                                    [ss_search_api_language] => en
                                    [score] => 1.8644972
                                )

                            [1] => Array
                                (
                                    [ss_search_api_id] => entity:file/85:en
                                    [ss_search_api_language] => en
                                    [score] => 1.784599
                                )

Let's say that the doc in question that I want to remove from $result object is:
$resultset_data['response']['docs'][$id]

How do I alter the $result object to remove this doc from results?  Every attempt I have made to access the $result object as an array has resulted in these types of errors:

Error: Cannot use object of type Solarium\QueryType\Select\Result\Result as array

Error: Cannot access protected property Solarium\QueryType\Select\Result\Result::$response

Any suggestions or documentation on this would be highly appreciated.
Answer: I have installed search_api, search_api_solr and search_api_attachments.  The View that I am reading with the hook is a Solr indexed view returning solr index extracts.
I discovered this was how to read the result rows:
  $result_items = $result_set->getResultItems();
  // Iterate through doc ids
  foreach ($result_items as $docid => $value) {
    // process info from $docid and/or $value
  }

$docid will be the Solr document id, i.e.: entity:node/47:en
In my case, all the information I need, entity type and entity id, are in the document id.
If I want to remove the result row:
unset($result_items[$docid]);

And at the end of the hook:
$result_set->setResultItems($result_items);


Find range of $f(x)=3^x+5^x-8^x$

Question: Find range of $f(x)=3^x+5^x-8^x$.
My attempt:
On observation one sees that $f(1)=0$.
On taking $g(x)=\left(\frac{3}{8}\right)^x+\left(\frac{5}{8}\right)^x-1$ and then observing that
$g'(x)=\left(\frac{3}{8}\right)^x \ln\left(\frac{3}{8}\right)+\left(\frac{5}{8}\right)^x \ln\left(\frac{5}{8}\right)<0$
we can conclude that $f(x)$ is negative for $x\in (1,\infty)$.
Also $\lim_{x\rightarrow-\infty}f(x)=0$.
Only thing to be done is to find maximum value of $f(x)$
Comment: You are correct in your reasoning. The maximum value is a positive number $m$ and then the range is $(-\infty,m]$. Use the same divide by trick and equate the derivative of the modified function to zero to find the exact maximum $m$. It will probably be an ugly expression, which can be evaluated
Answer: Considering the function $$f(x)=3^x+5^x-8^x$$ by inspection we have $$f(-\frac 12)=-\frac{1}{2 \sqrt{2}}+\frac{1}{\sqrt{3}}+\frac{1}{\sqrt{5}}\approx 0.67101$$ $$f(0)=1$$ $$f(\frac 12)=-2 \sqrt{2}+\sqrt{3}+\sqrt{5}\approx 1.13969$$ $$f(\frac 34)=-4 \sqrt[4]{2}+3^{3/4}+5^{3/4}\approx 0.86638$$ So, as already answered by Ahmed S. Attaalla, we can safely start Newton method for the zero of $f'(x)$ using $x_0=\frac 12$.
The iterates will then be
$$\left(
\begin{array}{cc}
n & x_n \\
 1 & 0.412626 \\
 2 & 0.397630 \\
 3 & 0.397236 \\
 4 & 0.397235
\end{array}
\right)$$ and, for the converged solution, $f(x)\approx 1.15811$ is the maximum.
From a numerical point of view, instead of looking for the zero of $$f'(x)=\ln 3 (3^x)+\ln 5 (5^x)-\ln 8 (8^x)$$ it would be more efficient to look at at zero of $$g(x)=x \log (8)-\log \left(\frac{3^x \log (3)+5^x \log (5)}{\log (8)}\right)$$ which is almost a straight line in the area of interest. Using the same $x_0=\frac 12$, the iterates would then be instead
$$\left(
\begin{array}{cc}
n & x_n \\
 1 & 0.396751 \\
 2 & 0.397235
\end{array}
\right)$$
As you can see, the first iterate is "almost" the solution.
Answer: $$f'(x)=\ln 3 (3^x)+\ln 5 (5^x)-\ln 8 (8^x)$$
Does not have a zero in term of elementary functions so you'll have to resort to numerical methods of approximation.
Newtons method for example,
$$x_{n+1}=x_{n}-\frac{\ln 3 (3^{x_n})+\ln 5 (5^{x_n})-\ln 8 (8^{x_n})}{(\ln 3)^2 3^{x_n} (\ln 5)^2 5^{x_n}-(\ln 8)^2 8^{x_n}}$$
Let $x_1$ be a number of your choice that lets the sequence converge.
Then by considering the signs of $f'(x)$ and the end behavior of $f(x)$ you may show:
$$\text{max} f(x)=f(\lim_{n \to \infty} x_n)$$
For the minimum consider:
$$\lim_{x \to \infty} (3^x+5^x-8^x)=\lim_{x \to \infty} (8^x((\frac{3}{8})^x+(\frac{5}{8})^x-1))$$
Which we consider because after proving $f$ to be decreasing on $x \in (\lim_{n \to \infty} x_n,\infty)$ or the easier $x \in (1,\infty)$, that leaves the question decreasing to some bound or decreasing to $-\infty$?
Answer: If you draw the function, it looks like this. So its range is $(f_{max}, -\infty)$

following is to analyze the function $f(x)=3^x+5^x-8^x$.

$\lim\limits_{x\to -\infty} f(x) =0 $
$\lim\limits_{x\to +\infty} f(x) =\lim\limits_{x\to +\infty} 8^x((\frac38)^x+(\frac 58)^x-1)=- \infty $
$f(1) = 0$
$f(0) = 1$

derivative of $g(x)=3^x+5^x-8^x$ is $g'(x)=ln3(3^x)+ln(5)(5^x)$. The derivative is positive and monotonically increasing.
derivative of $h(x)=8^x$ is $h'(x)=ln8(x^8)$. The derivative is positive and monotonically decreasing.
So if there is any root, there is only one for $g'(x)=h'(x)$ or $f'(x)=0$. And this root is global optima. Because the minimum is $-\infty$, this point should be the global maximum.
Because $f'(0)=\ln3+\ln5-\ln8=0.62$ and $f'(1)=3\ln3+5\ln5-8\ln8=-0.529$, the root of $f'(0)$ should be between $(0,1)$. Keep using bisection method, (or more advanced, using Newton method), you will find the maximum value at 0.397 with $f_{max}=1.158$.
Answer for range is $(-\infty, 1.158)$

Find range of $f(x)=3^x+5^x-8^x$


Trying to use a SmartHost with my Exchange 2010 server

Question: I'm trying to use a SmartHost with my Exchange 2010 Server.
SmartHost details:
Secure SMTPS: securemail.internode.on.net 465 <-- Note: that's port 465
Configure your existing SMTP settings (in your email program) to:

use authentication (enter your Internode username and password, enter your username as email@example.com).
enable SSL for sending email (SMTPS).

So I've added the smart host details to my Org Config -> Hub Transport. I then used PowerShell to add the port:-
Set-SendConnector "securemail.internode.on.net" -port 465

I've then added my username/password (as suggested above) to the SmartHost as Basic Authentication (with no TLS).
Then I try sending an email and I get the following error message :-
451 4.4.0 Primary target IP address responded with: "421 4.4.2 Connection dropped due to ConnectionReset."
So i'm not sure how to continue. I also tried ticking the TLS box but stll I get the same error.
If i don't use SMTPS (secure SMTP, on port 465) and use basic SMTP on port 25 with no Authentication, email gets sent.
Any ideas?
EDIT:
Btw, I can telnet to that server on port 465 from my mail server .. just to make sure i'm not getting firewall'd, etc.
Answer: Internode (an iiNet for that matter) are very fussy when using SmartHosts. Even though you're authenticating with your username and password, because your email is not being sent from an @internode from address, they may be rejecting your email.
I had this happen with iiNet, on a business account. They were happy to open up Port 25 inbound, but wouldn't help me with sending emails via the Exchange smarthost. Also, the IP address they gave me had bad history so I couldn't even just send via MX.
Interesting that it works via non-secure though, so I could be way off the ball here.
If you find it's not this, and something else, please let me know as I'd be interested to try it for iiNet.
Comment: For me, the issue has never been about using a smarthost with internode. In fact, I'm using/have been for years (using it with Exchange 2003). I'm just doing it over port 25 .. and not port 465. I'm not sure if I can tell exchange 2010 to use SSL for a smarthost. I've set the port via command line .. i've set the auth details (which i'm assuming I've ticked the correct box). Hmm....


Converter Inteiro para Decimal em Oracle

Question: como faço para converter um número inteiro para decimal no oracle?
Hoje, a consulta saindo dessa forma.

75

Porém, eu quero que saia com 2 casas decimais, dessa maneira.

75,00

Segue abaixo a sintaxe da coluna.
select nvl(sum(ve.vl_vencimento),0) Valor_Total_da_Ordem from ordem_compra

Answer: Pode sempre utilizar a função TO_CHAR:
SELECT  TO_CHAR(NVL(SUM(ve.vl_vencimento), 0), '999999D99') Valor_Total_da_Ordem
FROM    ordem_compra

Comment: Obrigado @JoãoMartins, deu certo.
Comment: De nada! Aproveite e dê um UP na resposta :)
Answer: Se sua aplicação já tem tratativa baseada nos tipos do oracle, é possível fazer um type cast do campo desejado usando a função CAST
select Cast(nvl(sum(ve.vl_vencimento),0) as DECIMAL(10,2)) Valor_Total_da_Ordem from ordem_compra


What will happen if we interchange @service and @repository annotation in the spring MVC

Question: Why we needs to use @service inside the service Implementation and @repository in the DAO Implementation. There are no problem occur when I interchange the @service and @repository annotation in the spring MVC.
Comment: That would probably screw up your transactions. A service needs to pass transactions that need propagation to the DAO. Both are components so creation of a bean wont be a problem.
Answer: According to documentaion @Repository,@Service,@Controller are all synonyms. They all are just specializations of @Component annotation. So, generally, they can be used one instead of other. But ... you should not do this.
First reason: any of these annotations make clear the role of your component in the application. Shows - is this component belongs to the controller, service, or data layer.
Second reason: some of these annotations processed differently by different Spring modules. For example, Spring Data JPA will process @Repository and will try to replace with implementation any interface marked by this annotation. Spring also will apply automatic exception translation to such classes. Another example: Spring Web MVC processes @Controller, and uses classes marked with it in URL mappings.
Actually, in future versions, some modules of Spring could process @Service in a particular way. Not as simple @Component. That's why documentation advises:

It is also possible that @Repository, @Service, and @Controller may
carry additional semantics in future releases of the Spring Framework.
Thus, if you are choosing between using @Component or @Service for
your service layer, @Service is clearly the better choice.
Answer: It depends on what you use for the remainder of the framework. In theory nothing changes as the @Service and @Repository annotations are basically @Component annotations. The same could be said for @Controller or @Endpoint (for Spring Ws and there are more).
However they express an intent of what a class is (a service, a repository) and makes it clear to the user to what layer that class belongs.
However if you also use Spring for transaction managemnt then @Repository is also a trigger for adding exception translation to that class (also see the reference guide).
Although nothing has to break it probably will at some point.
Answer: According to documentation
Service.java

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
  @AliasFor(annotation = Component.class)
  String value() default "";
}

Repository.java

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
  @AliasFor(annotation = Component.class)
  String value() default "";
}

So after reading documentation, it seems we don't get immediate error and theoretically is possible but it is not good practice.If in future Spring offically add new line of code then we may get error.


How to calculate this limit :$ \lim_{x\to 1} x^{(\frac{1}{x-1})}$

Question: The graph of this function shows that the limit should be approximately $2.7$, but I don't know how to approach it mathematically, the form after direct putting of $x = 1$ is $1^{\infty}$, which is an indeterminate form, so we can proceed with L'-H$\hat{o}$pital's rule, but I don't really know how to do that. Please help me with this limit.
Comment: Note that L'Hopitals rule only applies to the $\frac{0}{0}$ and $\frac{\infty}{\infty}$ indeterminate forms.
Comment: Hint: $x = 1 + \frac{1}{\frac{1}{(x-1)}}$
Answer: Set $x-1=h$ to find $$\lim_{h\to0}(1+h)^{1/h}=\lim_{n\to\infty}\left(1+\dfrac1n\right)^n=?$$
Answer: $x^{{1\over{x-1}}}$
$=e^{{{ln(x)}\over{x-1}}}$
$lim_{x\rightarrow 1}{{ln(x)}\over{x-1}}$ is the derivative of $ln(x)$ at $1$ which is $1$. So the limit is $e$.
Answer: Let $y = x^{(1/(x-1))}$
Take the natural log of both sides.
$ln(y) = (1/(x-1))\ln(x)$
Notice if you plug in $x = 1$ you get $0/0$, so you can apply L'Hospital's Rule.
Just take the derivative of the numerator and denominator (separately). The derivative of $\ln(x) = 1/x$ and the derivative of $x-1$ is just $1$.
So $\ln(y) = 1/x$.
Now this is an easy limit, $ln(y) = 1$.
But that's not the limit you want.
Apply the exponential function to both sides.
Then you see the limit is $e$.
Hope this helps!
Answer: Consider $$y=x^{\frac{1}{x-1}}$$ and let $x=1+t$ to make
$$y=(1+t)^{\frac{1}{t}}\implies \log(y)=\frac 1 t \log(1+t)$$ which is simple using L'Hospital.
If you want more than the limit, use Taylor series to get
$$\log(y)=\frac 1 t \left(t-\frac{t^2}{2}+\frac{t^3}{3}+O\left(t^4\right) \right)=1-\frac{t}{2}+\frac{t^2}{3}+O\left(t^3\right)$$ Continue with Taylor using
$$y=e^{\log(y)}\implies y=e-\frac{e t}{2}+\frac{11 e t^2}{24}+O\left(t^3\right)$$ which shows the limit when $t \to 0$ and also  how it is approached.