Why can i only choose one value in this form?

Question: I'm using this code to generate questions form database, it works! But i can only answer 1 question and save to database, why? If I try to answer multiple questions, the radio button value just moves around?
$question_id = mysqli_real_escape_string($con, $_POST['question_id']);
foreach ($_POST['answer_value'] as $question_id => $answer_id);

 $sql="INSERT INTO answers (question_id, answer_value)
  VALUES ('$question_id', '$answer_value')";

  if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
 }
 echo 'answer saved';
 mysqli_close($con);

 // generate all quetions
$query = "SELECT * FROM questions";
$result = @mysqli_query($con, $query);
echo '<form action="insert.php" method="POST">
                    Firstname: <input type="text" name="firstname">
                    Lastname: <input type="text" name="lastname">
                    Email: <input type="text" name="email">
';
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $body = $row['question_body'];
    $question_id = $row['question_id'];
    echo '

                '.$body.'
                <input type="radio" name="answer_value['.$question_id.']" value="0">
                <input type="radio" name="answer_value['.$question_id.']" value="1">
                <input type="radio" name="answer_value['.$question_id.']" value="2">

';

    }
     echo'<input type="submit"></form>

';
}
}
 ?>

Comment: Each radio button group needs a distinct name attribute. All of yours are sharing `name="answer_value"`
Answer: You need a separate radio group for each question. Use different names each time you go around the loop.
You can store your question id there instead of in a hidden input.
<input type="radio" name="answer_value[<?php echo $question_id; ?>]" value="1">

When this gets submitted back to the server, you will find that $_POST['answer_value'][] is an associative array with the question ids being the keys.
Comment: When adding:

My submit button is disappearing, I'm I interrupting the echo statement for the form?
Comment: You've used a `;` when you need a `.`
Comment: I really don't get what would like to be the correct POST for the question_id: $answer_value = mysqli_real_escape_string($con, $_POST['answer_value'][]);

 $sql="INSERT INTO answers (question_id, answer_value)
 VALUES ('$question_id', '$answer_value')";
Comment: `foreach $_POST['answer_value'] as $question_id => $answer_id` but
**Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from.
Comment: thx for the info abot sql injections. But i get an syntax error with
     foreach $_POST['answer_value'] as $question_id => $answer_id
Comment: Somehow I managed to miss the `()` off around it. See http://php.net/foreach for the proper syntax.
Comment: Thx for your reply, i really appreciate your help. I have edited my code above. When i try your solution i'm only saving the total count of questions answered in question_id in database? How Come?
Comment: You need to put the stuff you want to do for each item in the array *in a block following the `foreach` statement*.
Answer: If different radiobuttons have the same name, you can only choose one of them (you're grouping them). This is how it is mean to work, you can change to checkbox input instead:
<input type="checkbox" name="answer_value[]" value="1" />
<input type="checkbox" name="answer_value[]" value="2" />

Then you can check $_POST['answer_value'] to know ho many were checked and which value they had.
Comment: That would allow multiple answers per question, which isn't the goal.
Answer: Make each answer has the same name per question because all radio boxes with the same name are linked in html and will work as one big radiobutton group.
Use a question-ID tosolve that:
<input type="radio" name="answer_value_'.$row["question_id"].'" value="1">

Comment: Using a checkbox would allow multiple answers per question. That isn't the goal.
Comment: Okok, my bad, srry. I made a little misstake understanding what the author wants. There are multiple questions, I thought he was upset about multiple answer possibilities not workin~.
Answer: The problem here is that you are looping through the $_POST['answer_value'] but only grabbing the last value.
Try the following code instead:
    foreach ($_POST['answer_value'] as $question_id => $answer_id) {
      var_dump($question_id);
    }

Inside the brackets ({}), you may do your database insertion.
However, it might be a better idea to save the question and answers to a string that you'll later use in the mysql_query, to avoid unnecessary calls to the database.


Should I be concerned by frequent RAID warning message (unexpected sense - command aborted)?

Question: I have a Fujitsu host (PRIMERGY RX300 S6) running Windows Server 2008 R2 and Hyper-V (Version 6.1) with two virtual servers (one Windows Server 2008 R2 and one Windows Server 2012). Our 25 employees are continually connected to the virtual servers during the workday and read and write files to shared folders.
The storage controller on the host is RAID Ctrl SAS 6G 5/6 512MB (D2616) by LSI Corp.
Recently, I have discovered that the Raid manager displays very frequent warning messages. Nearly one every minute and sometimes up to 15 or 20 a minute.
Each warning message looks like the following:
<code>-------
Event: Warning
Date: Mar 18, 2015, 1:04:49 PM
Source: TOSHIBA MBF2600RC (1:0)
ID: 10909
Event: Adapter FTS RAID Ctrl SAS 6G 5/6 512MB (D2616) (0): Unexpected sense:
     Disk (1:0), CDB:28 00 1B 02 B5 80 00 00 80 00, Sense:(command aborted)72 0B 4B 04 00 00 00 20 80 1E 00 28 52 08 01 00 50 03 00 57 00 F3 3F 40 50 06 05 B0 00 02 72 BF 00 01 0C 00 00 00 00 00
------
</code>
Unfortunately, I have not been able to find out when this warning message started to occur.
The reason I am somewhat concerned about the warnings - apart from it just looking strange to me - is that Backup Exec has suddenly began to take 3-4 hours longer than usual to complete and now takes around 22-23 hours. Comparing job properties I can see that the job rate of Backup Exec for this particular server is down from around 800 MB/min to 550 MB/min.
My hardware provider has informed me that the message is merely informational, and that we should probably have the server replaced. It is 3,5 years old and I guess we should have it replaced within a year, but I would still like to get to the bottom of this matter.
Answer: The error decode is Bh/4Bh/0Bh = ABORTED_COMMAND/NAK_RECEIVED. I wrote my own tool to decode these and try to give a basic assessment at http://scsi.ev-en.org/
These errors indicate that you have a bad link somewhere, most often it is a bad cable but it can also be a bad port on either side (drive or slot).
Comment: Thanks. You and your tool are awesome! I will try to replace the cable.
Answer: Yes, you should be concerned. Not extremely concerned, but investigate it and - if necessary - replace some parts.
SCSI errors are usually generated by: problems with drivers/firmware or hardware faults.
Refer to: http://en.wikipedia.org/wiki/Key_Code_Qualifier
At minimum though, a SCSI error means 'something went wrong'. This may only be a minor problem, but a frequently occurring minor problem is a rather bigger problem, and means that there's something deeper going wrong.
Comment: I'm still having a look - these might well be manufacturer specific.
Comment: Thanks. I also can't find the interpretation of the exact code anywhere at all, so this is basically my way of investigating it :) My worry is exactly that the problem is slowing me down, which is pretty bad by itself.

I should note that device manager says that the driver software for the storage controller is up to date and our hardware supplier has informed me that firmware has been updated recently.

Also, every once in a while the warning message says "command aborted, no additional sense information" insted of just the usual "command aborted".


Possible to connect the zoom on two Highcharts graphs?

Question: I have a line graph and an area graph from the Highcharts API on my page that are x zoom-able like so:
chart: {
   type: 'line',
   zoomType: 'x'
}

Is it possible to make it so if I zoom in on one graph, it will apply the same zoom to the other graph? And vice versa?
I've looked online and in the API and I can't find anything but I feel like it should be possible.
Comment: Found this that appears to do what you want. http://stackoverflow.com/questions/14983931/link-multiple-chart-controls-in-highcharts
Comment: Yikes, that looks long-winded. So I take it that it's not part of the API?
Comment: Not directly. But since it is accessible via jQuery it should work fine.
Answer: This fiddle helped figure it out:
jsfiddle.net/Gv7Tg/27/
It basically overwrites the setExtremes method with a custom one to propagate the event to the other graphs.
 events:{
    afterSetExtremes:function(){
      ...
    }
 }

Comment: Highcharts is pretty cool.

You could send in a function doing something like this:
`function setExtremes() {
            var xMin = this.chart.xAxis[0].min;
            var xMax = this.chart.xAxis[0].max;
            vm.chart1.xAxis[0].setExtremes(xMin, xMax, true);
            vm.chart2.xAxis[0].setExtremes(xMin, xMax, true);
            vm.chart3.xAxis[0].setExtremes(xMin, xMax, true);
        }`
... Added bonus: even panning accross charts is supported in this way.


Capturing Responses other than 200 OK From Fetch

Question: I'm using the native fetch library as specified here. It seems that whenever a response other than a 200 OK is returned it throws an exception with the string response Uncaught (in promise) TypeError: Failed to fetch.
Was there a way to catch and branch on specific HTTP response codes and still view the response data? For example a 401 response?
I have attached my request code I am using as a wrapper for fetch.
static request(url, data) {

    let headers = {
        "Authorization": window.localStorage.getItem("Authorization"),
        "Content-Type": "application/json"
    };

    let options = {
        method: "GET",
        headers: headers,
        mode: "no-cors",
        cache: "no-cache",
    };

    if (data) {
        options = {
            method: "POST",
            headers: headers,
            mode: "no-cors",
            cache: "no-cache",
            body: JSON.stringify(data)
        }
    }

    return new Promise(async (resolve, reject) => {

        try {

            let response = await fetch(url, options);
            let jsonResponse = await response.json();
            return resolve(jsonResponse);

        } catch (error) {
            // hashHistory.push("/login");
            return reject(error);
        }

    })

}

Comment: [Never ever pass an `async function` to `new Promise`!](https://stackoverflow.com/questions/43083696/cant-throw-error-from-within-an-async-promise-executor-function/43083793#43083793)
Comment: Generally speaking you never need to construct a `Promise` object yourself. You can await `fetch` directly in your `request` function.
Comment: I think this is the main source of the issue! Thanks for the code review
Answer: "An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true. The code would look something like this (https://developer.mozilla.org/pt-BR/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful):
fetch('flowers.jpg').then(function(response) {
  if(response.ok) {
    response.blob().then(function(myBlob) {
      var objectURL = URL.createObjectURL(myBlob);
      myImage.src = objectURL;
    });
  } else {
    console.log('Network response was not ok.');
  }
})
.catch(function(error) {
  console.log('There has been a problem with your fetch operation: ' + error.message);
});

"
Answer: You can check Response Headers .status property, .text() to read Response. If Response is expected to be read more than once, you can use .clone()
let request = fetch("/path/to/resource");

request
.then(response => {

    const status = response.status

    console.log(status);

    if (status == 401) {
      // read 401 response
      response.text().then(res = > console.log(res));
      return "404.html"
    }
    if (status == 200) {
      return "200.html"
    }
})
.then(result => console.log(result))
.catch(err => // handle error);


Erro ao listar dados MYSQL via API RESTful com PHP (Ionic 3)

Question: Bom dia,
Estou com um problema em listar dados no ionic 3 usando o mysql. O problema é o seguinte, tenho um app que lista os comodos de uma casa e o consumo de cada comodo, mas não consigo buscar o id especifico de cada cômodo para que eu possa listar seu consumo.
Era pra listar desse modo:

Segue os Códigos (home.ts):
public carregarComodos(){
this.Id_usuario = {id: this.id};
this.consumoProvider.getComodos(this.Id_usuario)
.then(data => {
  this.comodo = data;
  console.log(this.comodo.id)

  this.Id_usuario2 = {id: this.comodo.id};
  this.consumoProvider.getAll(this.Id_usuario2)
  .then(data => {
    this.consumo = data;
  });
});

Provider
getAll(id){
return new Promise(resolve => {
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  let option= new RequestOptions({headers:headers});
  this.http.post(this.URL+'/usuarios/select_usuariozinho', JSON.stringify(id))
  .subscribe(data=>{
    resolve(data);
  }, err => {
    console.log(err);
  });
});

getComodos(id){
return new Promise(resolve => {
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  let option= new RequestOptions({headers:headers});
  this.http.post(this.URL+'/usuarios/select', JSON.stringify(id))
  .subscribe(data=>{
    resolve(data);
  }, err => {
    console.log(err);
  });
});

index.php
$app->post('/usuarios/select_usuariozinho', function() use ($app){
 (new \controllers\produto($app))->select_usuariozinho();
});
$app->post('/usuarios/select', function() use ($app){
 (new \controllers\produto($app))->select();
});

Controller
public function select_usuariozinho(){
        global $app;
        $dados = json_decode($app->request->getBody(), true);
        $dados = (sizeof($dados)==0)? $_POST : $dados;
        $id = $dados["id"];
        $sth = $this->PDO->prepare("SELECT * FROM consumo_atual WHERE
        comodo_id = :id order by id desc limit 1");
        $sth ->bindValue(':id',$id);
        $sth->execute();
        $result = $sth->fetchAll(\PDO::FETCH_ASSOC);
        $app->render('default.php',["data"=>$result],200);
    }
public function select(){
        global $app;
        $dados = json_decode($app->request->getBody(), true);
        $dados = (sizeof($dados)==0)? $_POST : $dados;
        $id = $dados["id"];
        $sth = $this->PDO->prepare("SELECT c.id,c.descricao FROM comodo c
        WHERE Usuario_id = :id");
        $sth ->bindValue(':id',$id);
        $sth->execute();
        $result = $sth->fetchAll(\PDO::FETCH_ASSOC);
        $app->render('default.php',["data"=>$result],200);
    }

Answer: Você pode fazer um JOIN e retornar o consumo já na query dos cômodos.
 $sth = $this->PDO->prepare("SELECT * from Comodos como INNER JOIN consumo_atual cons ON cons.comodo_id = como.id WHERE como.Usuario_id = :id")
Nesse momento você vai recebe as informações tanto de consumo quanto do cômodo, ai basta iterar e montar a visualização no APP.
Comment: muito obrigado, realmente funcionou


Typescript replace generic for object keys and value

Question: I have several code blocks that look like this. Is there any better way to do this with generics or some other typescript feature?
    const { authors } = book

    if (authors?.author) {
      if (Array.isArray(authors.author)) {
        book.authors = authors.author
      } else {
        book.authors = [authors.author]
      }
    }

and
    const { bookLinks } = book

    if (bookLinks?.bookLink) {
      if (Array.isArray(bookLinks.bookLink)) {
        book.bookLinks = bookLinks.bookLink
      } else {
        book.bookLinks = [bookLinks.bookLink]
      }
    }

I want to create a function that takes two parameters, say ('authors', 'author') or ('bookLinks', 'bookLink') and replace the variables, in the above code.
Comment: Is this JavaScript code or TypeScript code?  If the latter, what's the type of `book`?
Comment: Its TypeScript and the type of book is unknown, as I'm fetching from external API.

But this pattern is repeated in several places, so I want to make this generic
Answer: I'm not 100% sure I'm following the use case, but maybe your function could look like this:
function fixBook<K extends PropertyKey>(
    book: any, key: K, subKey: PropertyKey
): asserts book is { [P in K]?: unknown[] } {
    if (!book) throw new Error("This is not an object");
    const { [key]: prop } = book;
    if (prop?.[subKey]) {
        if (Array.isArray(prop[subKey])) {
            book[key] = prop[subKey];
        } else {
            book[key] = [prop[subKey]];
        }
    }
}

This should behave similarly to your above code.  It is an assertion function, which means that after you call it, it will narrow the type of the input object so you can access its properties.
Example:
const book: unknown = {
    authors: { author: "A" },
    bookLinks: { bookLink: ["b", "c"] }
}

Here we have book of type unknown... the annotated unknown makes the compiler forget the actual type, so this should replicate the situation in which you get book from an API and don't know what type it is:
book.authors.author; // error! object is of type unknown

Now we call fixBook() twice. First:
fixBook(book, "authors", "author");

After that statement, book has been narrowed from unknown to {authors?: unknown[]}.  (Note that it's not {authors: string[]}, since the compiler has no idea what type book?.authors?.author will be.  Following the different code paths, I think after you run the function, the particular property will either be undefined or some array of unknown type.)  And then:
fixBook(book, "bookLinks", "bookLink");

After that statement, book has been narrowed further to {authors?: unknown[]} & {bookLinks?: unknown[]}.  We can verify by accessing the authors and bookLinks properties:
console.log(book.authors?.join(",")); // A
console.log(book.bookLinks?.join(",")); // b,c

Looks reasonable.

Okay, hope that helps give you some direction; good luck!
Playground link to code
Comment: That works.
Could you please suggest a good resource or a book for advanced typescript.

The use-case, I'm just cleaning up the data from the external API, to make it proper JSON
Comment: Thank you @jcalz. I see a lot of effort went into the answer.


No group of order 10,000 is simple

Question: Question: Prove that no group of order 10,000 is simple.
Attempt at solution:
By the Sylow Theorems, the number of Sylow 5-subgroups can only be 1 or 16 (as this number needs to divide 10,000 and also be equivalent to 1 mod 5).
If there is 1 Sylow 5-subgroup, then it is automatically a normal subgroup (since its conjugate can only be itself), so the group is not simple.
If there are 16 5-subgroups...
Any help would be appreciated. Thank you!
Answer: $$|G|=10,000=2^4\cdot5^4$$
By Sylow theorems, there are either one or $\,2^4=16\,$ Sylow $\,5\,$-subgroups. If the latter is true, defining $\,P=\,$ Sylow $\,5\,$-sbgp. , we get
$$[G:N_G(P)]=16$$
Making act $\,G\,$ regularly (left shift, say) on the set of cosets of $\,N_G(P)\,$, we get a homom. $\,\phi:G\to S_{16}\,$ , which must be injective if we assume $\,G\,$ is simple, and thus our group is isomorphic with a subgroup of $\,S_{16}\,$, which is impossible (why? Lagrange's Theorem)
Comment: I realize this is a bit of an old question, but I was wondering 2 things. 1) Why must $\phi$ be injective? Couldn't $\ker(\phi)=G$? 2) Why does $\phi$ being injective tell us that $G$ is isomorphic with a subgroup of $S_{16}$? Thank you!
Comment: @lollab **If** a group is simple, then *any* hjomomorphism from it to any group is either trivial or injective, as the group cannot have non-trivial normal subgroups...In the above case it cannot be $\;\ker G=G\;$ since the the homomorphism determined by the regular representation of $\;G\;$ in $\;S_n\;$ is never trivial. And if $\;\phi: G\to H\;$ is injective then $\;\phi(G)\;$ is a subgroup of $\;H\;$ which is trivially isomorphic to $\;G\;$ as $\;\ker\phi=\{1\}\;$ ...
Answer: As Serkan mentioned, this is a classic Sylow simplicity problem where the order is too large to be a subgroup of the associated symmetric group.  I was expecting to see questions about simple groups of order 2012, and so was presently surprised to see this question from the future. Greetings from the past to our friends from the Y10K! However, I'm sad to see the techniques have not changed over the next 8000 years.
Serkan's proof works nicely for 10000, but 12 years ago we were not so futuristic and had to make do with the following proposition which I hope is useful to you:
Proposition:  A group of order $2^4 \cdot 5^n$ for $n \geq 2$ has a normal subgroup of order $5^n$ or $5^{n-1}$.
Proof: Let $G$ be such a group, $P$ a Sylow 5-subgroup. Sylow's theorems show that $N_G(P)$ is either $G$ or $P$, and the former is one of the conclusions. Hence we may assume $N_G(P)=P$. Consider the action of $P$ on the $G$-conjugates of $P$. $P$ fixes $P$, but cannot fix any other conjugate. Writing $16-1$ as a sum of divisors of $5^n$ can only be done as $5+5+5$. Hence in all three orbits $Q=N_P(P^g)=P \cap P^g$ has index 5 in $P$. Since $Q$ is maximal in both $P$ and $P^g$, $Q$ is normal in both $P$ and $P^g$. Hence $N_G(Q)$ is a group of order $2^i 5^n$ with more than one Sylow 5-subgroup. If $i <4$, this contradicts Sylow's theorem, so $i=4$ and $N_G(Q) = G$. $\square$
In fact, we can even be quite explicit about the structure of $G/Q$ in case the Sylow 5-subgroup is not normal. Then we have $G/Q \leq \operatorname{AGL}(1,16)$ has order $2^4 \cdot 5$ and is the unique non-abelian semi-direct product of the elementary abelian group of order 16 with a cyclic group of order 5. Of course $Q$ itself can be any group of order 125. The proof is merely that no other group of order 16 has an automorphism of order 5 (by Burnside's basis theorem), so every other Sylow 2-subgroup would centralize the Sylow 5-subgroup and thus normalize it.
Comment: Thank you Jack :-) Good to know the machinery was in place in year 2000!

No group of order 10,000 is simple


If $g(x)=\sum_{n} f_n x^n=\frac{2x^2+x^3}{1-x-x^2}$,then find the general expression for the coefficients,$f_n$.

Question: As evident $f_n=\frac{1}{n!}\frac{d^n}{dx^n}g(x)(at x=0)$.If I use Cauchy's integral formula to find the $nth$ derivative,then I'm stuck,because there also the derivative crops up while finding the residue.
Comment: $1/(1-x-x^2)=1+x+2x^2+3x^3+\cdots$ is the generating function for the Fibonnaci numbers. So the coefficients of $g(x)$ should be some linear combination of Fibonacci numbers themselves. To find this explicitly, the simplest approach is probably to find some recursion relation for $f_n$.
Answer: Notice that the denominator cancels in $\frac {-1 \pm \sqrt 5} 2$, so we shall investigate analyticity only on the open ball centered in $0$ and of radius $\frac {-1 + \sqrt 5} 2$.
Multiplying by the denominator, one gets that $(1-x-x^2) \sum \limits_{n \ge 0} f_n x^n = 2x^2 + x^3$, which means that $\sum \limits_{n \ge 0} f_n x^n - \sum \limits_{n \ge 0} f_n x^{n+1} - \sum \limits_{n \ge 0} f_n x^{n+2} = 2x^2 + x^3$, or further that
$$f_0 + f_1 x - f_0 x + \sum \limits _{n \ge 2} (f_n - f_{n-1} - f_{n-2}) x^n = 2x^2 + x^3 ,$$
which means that:
$$\begin{align}
&f_0 &=& 0 \\
&f_1 - f_0 &=& 0 \\
&f_2 - f_1 - f_0 &=& 2 \\
&f_3 - f_2 - f_1 &=& 1 \\
&f_n - f_{n-1} - f_{n-2} &=& 0 \ \forall n \ge 4 .
\end{align}$$
This leads to $f_0 = 0, \quad f_1 = 0, \quad f_2 = 2, \quad f_3 = 3$ and then $f_n = f_{n-1} + f_{n-2} \ \forall n \ge 4$, the last formula being precisely the formula giving the Fibonacci sequence, but with different first terms ("initial conditions").
There is a general approach to solving this kind of recurrences: for example, to the one given above attach the equation $r^2 = r + 1$. This has the roots $\frac {-1 \pm \sqrt 5} 2$, which makes us posit that
$$f_n = a \left( \frac {-1 + \sqrt 5} 2 \right)^n + b \left( \frac {-1 - \sqrt 5} 2 \right)^n \ \forall n \ge 4 ,$$
with $a,b$ to be found.
Compute $f_4, f_5$ from the above recurrence: $f_4 = f_3 + f_2 = 5$ and $f_5 = f_4 + f_3 = 8$. Then solve the system
$$\left\{ \begin{eqnarray}
5 = f_4 = a \left( \frac {-1 + \sqrt 5} 2 \right)^4 + b \left( \frac {-1 - \sqrt 5} 2 \right)^4 \\
8 = f_5 = a \left( \frac {-1 + \sqrt 5} 2 \right)^5 + b \left( \frac {-1 - \sqrt 5} 2 \right)^5
\end{eqnarray} \right.$$
to get
$$a = \frac {49} 2 + \frac {111} {10} \sqrt 5, \quad \frac {49} 2 - \frac {111} {10} \sqrt 5 .$$
Finally, then,
$$f_n = \left( \frac {49} 2 + \frac {111} {10} \sqrt 5 \right) \left( \frac {-1 + \sqrt 5} 2 \right)^n + \left( \frac {49} 2 - \frac {111} {10} \sqrt 5 \right) \left( \frac {-1 - \sqrt 5} 2 \right)^n \ \forall n \ge 4 .$$
(In fact, the sequence $(f_n) _{n \ge 2}$ is just the usual Fibonacci sequence without the first terms $0, 1, 1$.)
Answer: You may check that
$$ \frac{x}{1-x-x^2} = \sum_{n\geq 0} F_n x^n \tag{1} $$
holds just by multiplying both sides by $1-x-x^2$ and recalling that $F_{n+2}=F_{n+1}+F_n$.
It follows that:
$$\begin{eqnarray*} \frac{2x^2+x^3}{1-x-x^2} = 2\sum_{n\geq 0}F_n x^{n+1}+\sum_{n\geq 0}F_n x^{n+3}=2x^2+3x^3+\sum_{n\geq 4}F_n x^n.\tag{2}\end{eqnarray*} $$
Comment: +1. $\ldots$ where $F_{n}$ is a $\underline{Fibonacci\ Number}$.
Answer: Long division gives us that
$$
\begin{align}
\frac{2x^2 + x^3}{1-x-x^2}
&= -(x+1)+\frac{1}{1-x-x^2}\\
&=-x-1+1+x+2x^2+3x^3+\dotsb \\
&=2x^2+3x^3+5x^4\dotsb
\end{align}$$
Answer: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,\mathrm{Li}_{#1}}
 \newcommand{\mc}[1]{\,\mathcal{#1}}
 \newcommand{\mrm}[1]{\,\mathrm{#1}}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

Other answers pointed out the relation to the Fibonacci Numbers. However, it's desirable to have numerical expressions for the coefficients.

Note that the roots of $\ds{1 - x - x^{2} = 0}$ are $\ds{-\varphi}$ and
$\ds{1 \over \varphi}$ where $\ds{\varphi = {1 + \root{5} \over 2}}$ is the Golden Ratio:
\begin{align}
\color{#f00}{2x^{2} + x^{3} \over 1  - x - x^{2}} & =
-\,{2x^{2} + x^{3} \over \pars{x + \varphi}\pars{x - \varphi^{-1}}} =
-\pars{2x^{2} + x^{3}}\pars{{1 \over x + \varphi} - {1 \over x - \varphi^{-1}}}
{1 \over -\varphi^{-1} - \varphi}
\\[5mm] & =
{\root{5} \over 5}\pars{2x^{2} + x^{3}}
\pars{{\varphi^{-1} \over 1 + \varphi^{-1}x} + {\varphi \over 1 - \varphi x}}
\end{align}

With $\ds{\varphi\verts{x} < 1}$:
\begin{align}
\color{#f00}{2x^{2} + x^{3} \over 1  - x - x^{2}} & =
{\root{5} \over 5}\pars{2x^{2} + x^{3}}\sum_{n = 0}^{\infty}
\bracks{\varphi^{-n - 1} + \pars{-1}^{n}\varphi^{n + 1}}x^{n}
\\[5mm] & =
{\root{5} \over 5}\braces{\sum_{n = 0}^{\infty}
2\bracks{\varphi^{-n - 1} + \pars{-1}^{n}\varphi^{n + 1}}x^{n + 2} +
\bracks{\varphi^{-n - 1} + \pars{-1}^{n}\varphi^{n + 1}}x^{n + 3}}
\\[5mm] & =
{\root{5} \over 5}\braces{\sum_{n = 2}^{\infty}
2\bracks{\varphi^{-n + 1} + \pars{-1}^{n}\varphi^{n - 1}}x^{n} +
\sum_{n = 3}^{\infty}
\bracks{\varphi^{-n + 2} - \pars{-1}^{n}\varphi^{n - 2}}x^{n}}
\\[1cm] & =
{\root{5} \over 5}\,\bracks{2\pars{\varphi^{-1} + \varphi}}
\\[5mm] & +
{\root{5} \over 5}\sum_{n = 3}^{\infty}\bracks{%
2\varphi^{-n + 1} + 2\pars{-1}^{n}\varphi^{n - 1} +
\varphi^{-n + 2} - \pars{-1}^{n}\varphi^{n - 2}}x^{n}
\end{align}

\begin{align}
&\color{#f00}{\bracks{x^{n}}\pars{2x^{2} + x^{3} \over 1 - x - x^{2}}}
\\[5mm] & =
\left\lbrace\begin{array}{lcrcl}
\ds{2} & \mbox{if} & \ds{n} & \ds{=} & \ds{2}
\\[3mm]
\ds{{\root{5} \over 5}\bracks{\vphantom{\Large A}%
2\,\varphi^{-n + 1}\ +\ 2\,\pars{-1}^{n}\,\varphi^{n - 1}\ +\ \varphi^{-n + 2}\ -\ \pars{-1}^{n}\,\varphi^{n - 2}}}
& \mbox{if} & \ds{n} & \ds{=} & \ds{3,4,5,\ldots}
\\[3mm]
\ds{0}&&&&\mbox{otherwise}
\end{array}\right.
\end{align}
Answer: Suppose
$$
\frac{a+bx}{1-x-x^2}=\sum_{k=0}^\infty c_kx^k
$$
then
$$
\begin{align}
a+bx
&=\left(1-x-x^2\right)\sum_{k=0}^\infty c_kx^k\\
&=\sum_{k=0}^\infty c_k\left(x^k-x^{k+1}-x^{k+2}\right)\\
&=\underbrace{\ \ \ \ \ c_0\ \ \ \ \ \vphantom{()}}_{a}+\underbrace{\left(c_1-c_0\right)}_b\,x+\sum_{k=2}^\infty\left(c_k-c_{k-1}-c_{k-2}\right)x^k
\end{align}
$$
Since the coefficient of $x^k$ is $0$ for $k\ge2$, we must have $c_k-c_{k-1}-c_{k-2}=0$; that is,
$$
c_0=a\quad c_1=a+b\quad c_k=c_{k-1}+c_{k-2}
$$

$$
\begin{align}
\frac{2x^2+x^3}{1-x-x^2}
&=-1-x+\frac1{1-x-x^2}\\
&=-1-x+\underbrace{1+x+2x^2+3x^3+5x^4+\dots}_{\sum\limits_{k=0}^\infty F_{k+1}x^k}\\
&=\sum_{k=2}^\infty F_{k+1}x^k
\end{align}
$$


Como executar as dependências do maven?

Question: Estou fazendo uma aplicação dentro de uma maquina virtual e estou usando o maven ara instalar o Mahout, no Eclipse em um outro pc funcionou perfeito, mas ao fazer os mesmo projeto em uma maquina virtual fiz as seguintes etapas me dando o erro abaixo:
Instalei o maven e criei um projeto:
mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
editei o pom.xml e adicionei a dependecia do mahout:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.prisvo.app</groupId>
  <artifactId>my-app</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>my-app</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>org.apache.mahout</groupId>
      <artifactId>mahout-core</artifactId>
      <version>0.9</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
 </project>

Então adicionei meu codigo dentro do arquivo App.java que ficou desta forma:
package com.mycompany.app;

import java.io.File;
import java.util.List;

import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.ThresholdUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.UserBasedRecommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;

public class App
 {
    public static void main( String[] args ) throws Exception
     {
        DataModel model = new FileDataModel(new File("data/data.csv"));
        UserSimilarity similarity = new PearsonCorrelationSimilarity(model);
        UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, similarity, model);
        UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity);
        List<RecommendedItem> recommendations = recommender.recommend(567, 1);
        for (RecommendedItem recommendation : recommendations) {
          System.out.println(recommendation);
        }
     }
 }

executei este comando: mvn package e depois java -cp target/my-app-1.0-SNAPSHOT.jar com.mycompany.app.App. E me deu o seguinte erro:
 Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/mahout/cf/taste/model/DataModel
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
    at java.lang.Class.getMethod0(Class.java:3018)
    at java.lang.Class.getMethod(Class.java:1784)
    at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException:
org.apache.mahout.cf.taste.model.DataModel
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more

O Maven instalou as dependências certo, estou me esquecendo de algo?
Answer: Vai em Run AS depois em Maven Build depois em Goals :

ou no cmd digite:
mvn clean install package

Se o error continuar execute esses passos do link a baixo :Como usar MySql no Java EE?

Como executar as dependências do maven?


how to use a class with generics without having to declare the generic type

Question: First of all, I am coming from Java background so please forgive me for my mistakes:
This is my class
 class ParameterHandler<T>
 {

        public static Dictionary<string, Converter<T>> parameters =
               new Dictionary<string, Converter<T>>();

        public static void addParameter(string parameterName, Converter<T> converter){
            parameters.Add(parameterName, converter);
        }

        static T getValue(string parameterName, string stringValue){
            return parameters[parameterName].getValue(stringValue);
        }
 }

and this is my Converter interface
interface Converter <T>
{
        T getValue(string stringValue);
}

I wonder if I can use the parameterhandler without having to declare T as a generic type for it
I just need to do something like
ParameterHandler.addParameter("some", Some Implementation for Converter)

and to put you in the whole picture, this is one of my implementation for the Converter
class IntConverter : Converter<int>
{
        int getValue(string stringValue)
        {
            return int.Parse(stringValue);
        }
}

Comment: Do you want to have different types of converters in the dictionary `paramateres`?
Comment: @TaherRahgooy yes and I also have this  `public static Dictionary> parameters = new Dictionary>();` so the function `addParameter` will just add a new entry in this dictionary. u got me pllease?
Comment: What is the key being used for? Is it just storing a type name, or will you potentially have multiple converters for each `T`?
Answer: You can create a non-generic ParameterHandler class with a generic addParameter method:
public static class ParameterHandler
{
    public static void addParameter<T>(string name, Converter<T> c)
    {
        ParameterHandler<T>.addParameter(name, c);
    }
}

then you can use
ParameterHandler.addParameter("some", new IntConverter());

Comment: in that case, i would like to tell u more, i have this dictionary public static `Dictionary> parameters = new Dictionary>();`
what would i pass instead of `T`  please?
Comment: could you help pleaes?
Comment: @MarcoDinatsoli: Where is that defined? In this case `T` is `int`. If you want to declare it in a non-generic type then you'll need to use `object` for `T` and wrap your individual `Converter` instances in a class implementing `Converter`. Alternatively you could add a non-generic `Converter` interface with a `object getValue(string stringValue);` method.
Answer: You must define an interface that is base for all converters:
 interface Converter
 {
 }
 interface Converter<T> : Converter
 {
     T getValue(string stringValue);
 }

Then:
class ParameterHandler
{
    public static Dictionary<string, Converter> parameters =
           new Dictionary<string, Converter>();

    public static void addParameter<T>(string parameterName, Converter<T> converter){
        parameters.Add(parameterName, converter);
    }

    static T getValue<T>(string parameterName, string stringValue){
        if(!parameters[parameterName] is Convereter<T>)
             throw new Exception("Invalid Type");

        return ((Convereter<T>)parameters[parameterName]).getValue(stringValue);
    }
}

Note that, in your initial model, you have a different dictionary for each type T, Converter<int>.parameters and Converter<double>.parameters are not the same.
Comment: this is not safe, i can't pass `object` to my dictionary
Comment: @MarcoDinatsoli, Yes, but in your model the dictionary can contain just the one type for each `T`.
Comment: how can I use the getValue then ? i can't do something like this: `ParameterHandler.getValue(key, value)`
Comment: `ParameterHandler.getValue(key, value)`, or making the `getValue` return type as object.
Comment: i don't know the type in the runtime, it is okay it seems we are guessing here, thank you


Combinatorial distribution

Question: Need some help with this exercise:
There are $300$ students in a course. Each student can get a grade from $0-100$.
How many ways can you divide the scores to get an average of $60$?
I had struggles to isolate the scenario of the exact required average.
After that I know how to make the distribution.
Comment: Welcome to MSE. Questions like "Here is the task. Solve it for me!" are poorly received on this site. Therefore try to improve your question with an [edit](https://math.stackexchange.com/posts/3050322/edit). Improving could consist of providing some context concerning your task or by adding what you have tried so far and where did you struggle :)
Comment: Thanks you for the remark, I've edited it :)
Answer: First of all note that average of 60 implies a total score (sum of score of all students) $= 60\cdot300=18000$.
Also, let $x_i$ be the score of $i^{th}$ student. Then, $0\leq x_i\leq100$. I assume that you can only can integral grades.
Note that what you need is $x_1+x_2+\cdots+x_{300}=18000$
So, using generating functions, total possible ways$=$
$$\text{Coeff. of }z^{18000}\text{ in }(z^0+z^1+z^2+\cdots+z^{100})^{300}$$
$$=(\frac{z^{101}-1}{z-1})^{300}$$
$$=(z^{101}-1)^{300}\cdot(z-1)^{-300}$$
$$=\sum_{i=0}^{178}\binom{300}{i}\binom{300+(18000-101i)-1}{18000-101i}$$
$$=\sum_{i=0}^{178}\binom{300}{i}\binom{18299-101i}{18000-101i}$$
Note that I took $i\leq 178$ because $18000-101i\geq0\implies i\leq178.2$. And I'll be really honest. I don't know if there's any way to solve that summation.
Comment: This problem will be way easier for you to solve if you read about generating functions ;)
Comment: This is the subject of the next lecture I will have this week :)
Comment: I've came to something similar:

$\sum\limits_{j=0}^{300}\binom{300+18000-100j-1}{18000-100j}\binom{300}{j}(-1)^j$

Counting all the possibilities and limiting 100 for each "cell". After 180 I will just sum zeros.
Comment: There's a slight mistake. $(-1)^{18000-101j}$ will come from the other term too. So you need not include that. Further, the formula for negative binomial is $\binom{n+k-1}{k}$. You seem to have missed the -1. Also, it'll be 101j and not 100j because there're 101 terms in the geometric expression and not 100 ;)
Comment: -I don't understand why -1 is not necessary.
- Yes, you are right :)
- Why 101
Comment: You've included -1 only from the $(z^{101}-1)^{300}$ term if I'm correct. But it'll be from $(z-1)^{-300}$ term too right?
Comment: Each student can a get a grade from 0 to 100. They are 101 numbers (and hence possible values of $x_i$s) and not 100
Comment: I'm taking all the distribution scenarios and eliminating all the possibilities that there will be a student with more than 100.
Comment: Can you explain why you wrote 100? May be then i can tell where r u wrong
Comment: I'm taking all the possibilities to distribute 18000 "balls" to 300 "cells". From it I'm demanding for 100 maximum balls in each cell with the inclusion-exclusion principle.
Answer: Suppose there are $n$ students in a given course, and on a particular exam each student can receive an integer grade from $0$ to $100$. If the class average on the exam is exactly $60$, then how many different grade distributions are there for the students in the course?
What we are really doing is counting the solutions to a restricted Diophantine equation:
$$
s_1+s_2+\cdots+s_n=n\cdot60 \quad \text{with all } s_i\in[0,100]
$$
In the case $n=1$, there is clearly only one solution. In the case $n=2$, we will have $81$ solutions, and for $n\geq 3$ it becomes clear that there are difficult counting problems involved that yield some rather large numbers.
Thankfully, this problem has been well studied; what we are really doing is counting lattice points in some high dimensional polytope, which can be accomplished with Ehrhart polynomials. In particular, this post has an answer that demonstrates how you may go about computing the answer you seek!
Answer: The correct generating function is already given by Ankit Kumar.
So to find the exact solution, a few lines of Mathematica code is enough:
<code>g = (z^101 - 1)/(z - 1);
f = g^300;
SeriesCoefficient[f, {z, 0, 18000}]
</code>
283842333432402321353024303661058637351420936084067738626583506213864447957870755539611750086168273196143155816656392895618438969536797685183460631860648381858482057644617263985079629258986110897789595623952660661105103107276955285902613205328147901598400715242942785403171606118195123592165718190326762039521274137278366225940884773691094689005096899697160884662108869409844236284336801805326795531698837921700003716989423475547841836096863072991222376259898318028580853239559456607248039447660955555656440250262052607092640488420986795396794284727379957951608980168883759138931179704247147

Combinatorial distribution


SELECT NULL in OpenEdge Query

Question: I would like to be able to SELECT a NULL value in my SELECT list so I can use it later in a UNION (for example). When I try SELECT NULL AS my_null_value FROM some_table it gives me a syntax error. I can work around it by doing the following.
    SELECT CASE WHEN 1=1 THEN NULL END AS my_null_value
    FROM some_table

Is there a cleaner way to accomplish this? I feel like I have done this in less characters and in a simpler manner in the past than using a CASE statement.
Answer: I ending up finding it.
A simpler (or more shorthand) way to accomplish this is to use the following:
    SELECT NULLIF(0,0) AS my_null_value
    FROM some_table

SELECT NULL in OpenEdge Query


EC2 servers are slower than local machine

Question: We have been trying to do some performance benchmarking for our webapp written using python that uses mongodb heavily and we have found the following.
We tried using 1st Gen Extra Large ec2 servers with 8 ecu's and 15 GB memory

The python on ec2 servers is at least 30% slower than the local machine
The disk I/O is extremely slow. The mongostat and iostat results show that the disk write is around 1MBpS
The programs themselves run so much slower than  the local machine

We have not been able to figure out why all this is happening. The local machines we are talking about have 8GB RAM and i5 processors.
UPDATE
The way we tested python was that we ran a loop that would take 10 seconds to complete with no disk read or write. The same took at least 30% more time on each trial.
Does this relate to this?
https://forums.aws.amazon.com/thread.jspa?messageID=66988
Comment: The way we tested python was that we ran a loop that would take 10 seconds to complete with no disk read or write. The same took 30% at least 30% more time on each trial.
Answer: There are a number of factors for EC2 machines to be slow. Disks are not attached directly to the instance. Instead the ebs volumes are large network disks and whatever you write to them is sent across the network to these disks. Now usually the latency is quite low but, of course, in comparison to something which is directly attached to your machine it will appear slow.
It is a virtual machine. No matter what you do it has to compete with other machines for CPU cycles. Run top if you are using Linux and check out CPU steal percentage. A non zero number will indicate that there is high competition for CPU. In any case virtual CPUs are not as fast as actual CPUs for comparable Processors.
Another personal observation is that luck plays an important role in EC2 (yes!). At times you get an older hardware which is just not as fast. Another personal experience is that at times you get amd opteron processors which are usually not as fast as Intel based. I am not suggesting that AMD processors are bad but it seems that in this case Intel ones work faster. Maybe they are of newer generation.
Having maintained mongo on EC2, I totally understand your pain. I would suggest that try to keep as much data in-memory as possible. In general, EC2 is not actually designed for vertical scaling. It is beneficial to have a lot of smaller instance dividing work then have a huge instance doing everything alone.
Comment: EXCEPT 1Mbps / 10mbit is a joke for even a VPN. And no, remote discs can be super fast (checK: SAN).
Comment: They can be, I agree. But in case of AWS EBS, many times the disks show really bad IO. Many time we ran same apps on machines of comparable configs on EC2 and local and we saw great difference.
Also the performance of EBS and instance store vary a lot, latter giving a much better performance.
Answer: I got very good results with software-raiding EBS volumes to RAID0 -- saw slightly better than 50% increase in read speed, a little less for writes. We had an application that was completely useless on AWS until we did this and it saved our butts.
Also, your IO will fluctuate with time of day and how much other customers are using that cluster/machine. As I recall, the AWS fine print guarantees no more than 100 iops on a standard EBS volume, though you'll get much more most of the time. My phone is probably faster than 100 iops. If those fluctuations are not acceptable, create your EBS volumes with provisioned iops. That's a little more expensive, but allows you to set the minimum throughput your application can live with, and guarantees that you'll get it no matter what other AWS customers are doing.
As for this:
"The python on ec2 servers is at least 30% slower than the local machine"
This could also be distro-related, or specific to your app. You didn't say exactly what you mean by "30% slower." If your test involved disk access, see above (promise, it helps.) If not, you might want to provide more information on what you were testing.
Comment: Added a comment. Does this relate to this?

https://forums.aws.amazon.com/thread.jspa?messageID=66988
Answer: If you're really concerned about disk io, AWS offers Provisioned IO EBS volumes and EBS Optimized instances.
With Provisioned IO you can specify the average io performance you need from an EBS volume.  Normal EBS volumes have a value of 100, and you can specify up to 2000.  Additionally you could setup software RAID arrays out of multiple Provisioned IO EBS volumes to get higher throughput.
http://aws.amazon.com/about-aws/whats-new/2012/07/31/announcing-provisioned-iops-for-amazon-ebs/
Additionally EBS optimized images offer faster dedicated connectivity to EBS, at 500 and 1000 Mbps on m1.large, m1.xlarge and m2.4xlarge.
http://aws.amazon.com/ebs/
You can also check out the high-io instance, with attached SSD drives:

High I/O Quadruple Extra Large Instance
  60.5 GiB of memory 35 EC2 Compute Units (16 virtual cores*) 2 SSD-based volumes each with 1024 GB of instance storage 64-bit
  platform I/O Performance: Very High (10 Gigabit Ethernet) Storage I/O
  Performance: Very High*** EBS-Optimized Available: No** API name:
  hi1.4xlarge


Prove $x^n+1$ is irreducible over $\mathbb{Q}[X]$ iff $n=2^k$ for $k \in \mathbb{N}$

Question: Unfortunately, I cannot find any information on or anything similar to this particular question. Might be quite new.
In all honesty, I don't know how to tackle either side of this question. By induction? By contradiction?
The theorems I just learned are Eisenstein"s criterion and reduction by modulo $n$ but nothing else. And both do not seem to help in any explicit way.
Does anyone have ideas on how to solve this problem at all? Thank you
Answer:
If $n$ is divisible by an odd positive integer $d$, then $x^n+1$ is divisible by $x^{n/d}+1$.
If $f(x) = x^{2^k}+1$, apply Eisenstein to $f(x+1)$.
Comment: Of course if $n$ is odd, then $x=-1$ is a solution which is easier to notice.


Como alterar o nome da coluna References pelo Fluent Nhibernate?

Question: Na classe "LOG", estou tentando indicar o nome da coluna, o qual é um FK, usando References do FluentNHibernate. Tenho o seguinte estrutura de classe:
public class Pessoa
{
    public virtual int Id { get; set; }

    public virtual string Nome { get; set; }
}

public class PessoaAcesso : Pessoa
{
    public virtual string Login { get; set; }

    public virtual string Senha { get; set; }

    public virtual bool Administrador { get; set; }

    public virtual bool AcessoLiberado { get; set; }

    public virtual IList<Log> Logs { get; set; }

    public PessoaAcesso()
    {
        Logs = new List<Log>();
    }
}

public class Log
{
    public virtual int Id { get; set; }

    public virtual PessoaAcesso PessoaAcesso { get; set; }

    public virtual DateTime DataHora { get; set; }

    public virtual LogAcao Acao { get; set; }

    public virtual string Descricao { get; set; }
}

E seus mapenamentos:
public class PessoaMap : ClassMap<Pessoa>
{
    public PessoaMap()
    {
        Id(x => x.Id).GeneratedBy.Identity();

        Map(x => x.Nome)
            .Not.Nullable()
            .Length(100);
    }
}

public class PessoaAcessoMap : SubclassMap<PessoaAcesso>
{
    public PessoaAcessoMap()
    {
        KeyColumn("Id_Pessoa");

        Map(x => x.Login)
            .Not.Nullable()
            .Length(50);

        Map(x => x.Senha)
            .Not.Nullable()
            .Length(100);

        Map(x => x.Administrador)
            .Not.Nullable();

        Map(x => x.AcessoLiberado)
            .Not.Nullable();

        HasMany(x => x.Logs)
            .Cascade.All();
    }
}

public class LogMap : ClassMap<Log>
{
    public LogMap()
    {
        Id(x => x.Id).GeneratedBy.Identity();

        Map(x => x.DataHora)
            .Not.Nullable();

        Map(x => x.Acao)
            .Not.Nullable()
            .CustomType<int>();

        Map(x => x.Descricao)
            .Not.Nullable()
            .Length(200);

        References(x => x.PessoaAcesso)
            .Column("Id_PessoaAcesso")
            .Not.Nullable();
    }
}

Ao gerar a tabela no SQL Server, ele cria a coluna "Id_PessoaAcesso" corretamente, porém TAMBÉM cria a coluna "PessoaAcesso_id" permitindo null.
Já tentei indicar o nome da coluna dessa forma, mas obtém o mesmo resultado inesperado:
References(x => x.PessoaAcesso, "Id_PessoaAcesso")

Não estou entendendo o porque de estar criando uma coluna a mais. O que pode ser?
Comment: Pode postar o mapeamento da class de PessoaAcesso?
Comment: Adicionado @Fernando
Comment: `SubclassMap` faz o que, altera algum comportamento do mapeamento? Pode postar seu código também?
Comment: Adicionei a estrutura completa @Fernando
Comment: `SubclassMap` é igual `PessoaMap`? Que método é `KeyColumn("Id_Pessoa");`?
Comment: Estou usando SubClassMap, pois PessoaAcesso faz relação 1:1 com Pessoa (herança). Quanto isso está funcionando corretamente. O Problema está com o Log.
Comment: @Fernando adicionei no PessoaAcessoMap - HasMany(x => x.Logs).KeyColumn("Id_PessoaAcesso") e no LogMap - References(x => x.PessoaAcesso).Column("Id_PessoaAcesso"), e agora funcionou como esperado. Só não entendi direito o porque preciso indicar em ambas as relações o nome do Id. Crio uma resposta com essa solução, ou edito a pergunta?
Comment: Se seu problema foi resolvido, crie uma resposta com sua solução para que outros, possam identificar facilmente a solução para o problema. E também fica mais claro a solução para podermos analisar a sua duvida.
Answer: Fiz a indicação do nome da coluna tanto para PessoaMap() quanto para LogMap(). Funcionou.
public class PessoaAcessoMap : SubclassMap<PessoaAcesso>
{
    public PessoaAcessoMap()
    {
        KeyColumn("Id_Pessoa");

        Map(x => x.Login)
            .Not.Nullable()
            .Length(50);

        Map(x => x.Senha)
            .Not.Nullable()
            .Length(100);

        Map(x => x.Administrador)
            .Not.Nullable();

        Map(x => x.AcessoLiberado)
            .Not.Nullable();

        HasMany(x => x.Logs)
            .KeyColumn("Id_PessoaAcesso")
            .Cascade.All();
    }
}

public class LogMap : ClassMap<Log>
{
    public LogMap()
    {
        Id(x => x.Id).GeneratedBy.Identity();

        Map(x => x.DataHora)
            .Not.Nullable();

        Map(x => x.Acao)
            .Not.Nullable()
            .CustomType<int>();

        Map(x => x.Descricao)
            .Not.Nullable()
            .Length(200);

        References(x => x.PessoaAcesso)
            .Column("Id_PessoaAcesso")
            .Not.Nullable();
    }
}

Comment: A sim agora entendi, no Logs, você não estava especificando o nome da coluna para a relação HasMany, então estava utilizando a nomenclatura padrão, no caso: nome da classe + "_Id" (PessoaAcesso_Id), e já na relação References, você estava especificando um nome para a coluna, então ele estava atendendo os 2 mapeamentos.


How to avoid line breaks at StaffGroup boundaries

Question: I have recently started writing music notation with LilyPond. I find it convenient to split songs into different parts such as prelude, intro, interlude etc. So I have:
%prelude.ly
\new StaffGroup <<
  \override StaffGroup.SystemStartBracket.stencil = ##f

  \new Staff \with {
    instrumentName = "Piano"
    shortInstrumentName = "Pno"
  } \new Voice \relative c'' {
    c d e f
  }
>>

and
%intro.ly
\new StaffGroup <<
  \override StaffGroup.SystemStartBracket.stencil = ##f

  \new Staff \with {
    instrumentName = "Piano"
    shortInstrumentName = "Pno"
  } \new Voice \relative c'' {
    g a b c
  }
>>

Then I combine everything like so:
<<
  \chords {
    c,2 g,2 c,2 f,2 g,2 f,2 g,2 c,2
  }

  {
    \include "prelude.ly"
    \include "intro.ly"
  }
>>

This method works quite well for large scores. Except I get line breaks at StaffGroup boundaries as shown below:

Questions:

Does an average musician find these breaks annoying or are they quite common?
How can I avoid these breaks? Would be nice to get rid of the staff symbols at the boundaries as well.
Are there better ways of organising large scores?

Update: Answers below have suggested avoiding multiple staffgroups. But if possible I would prefer to have a new staffgroup for each part of score. This allows me the felxibility to add more instruments in parallel to a particular part without affecting anything else.
Answer: Your code essentially evaluates to something like
{
  %prelude.ly
  \new StaffGroup <<
    \override StaffGroup.SystemStartBracket.stencil = ##f

    \new Staff \with {
      instrumentName = "Piano"
      shortInstrumentName = "Pno"
    } \new Voice \relative c'' {
      c d e f
    }
  >>

  %intro.ly
  \new StaffGroup <<
    \override StaffGroup.SystemStartBracket.stencil = ##f

    \new Staff \with {
      instrumentName = "Piano"
      shortInstrumentName = "Pno"
    } \new Voice \relative c'' {
      g a b c
    }
  >>
}

You see that you are calling \new StaffGroup and \new Staff multiple times. This means that at the point in question Lilypond will simply create a new context, which is by default placed below the currently existing context. To achieve what you want you should not use \new ContextType, but \context ContextType = contextID. This will attempt to find a context of given type and ID (if nothing found a new context is created) and will switch to that context. So if you do
{
  %prelude.ly
  \context StaffGroup = "SG1" <<
    \override StaffGroup.SystemStartBracket.stencil = ##f

    \context Staff = "Staff1" \with {
      instrumentName = "Piano"
      shortInstrumentName = "Pno"
    } \new Voice \relative c'' {
      c d e f
    }
  >>

  %intro.ly
  \context StaffGroup = "SG1" <<
    \override StaffGroup.SystemStartBracket.stencil = ##f

    \context Staff = "Staff1" \with {
      instrumentName = "Piano"
      shortInstrumentName = "Pno"
    } \new Voice \relative c'' {
      g a b c
    }
  >>
}

it works as you intend. In fact you can even outsource the chordnames into the separate files:
{
  %prelude.ly
  <<
    \context ChordNames = "CN" \chordmode {
      c,2 g,2 c,2 f,2
    }
    \context StaffGroup = "SG1" <<
      \override StaffGroup.SystemStartBracket.stencil = ##f

      \context Staff = "Staff1" \with {
        instrumentName = "Piano"
        shortInstrumentName = "Pno"
      } \new Voice \relative c'' {
        c d e f
      }
    >>
  >>

  %intro.ly
  <<
    \context ChordNames = "CN" \chordmode {
      g,2 f,2 g,2 c,2
    }
    \context StaffGroup = "SG1" <<
      \override StaffGroup.SystemStartBracket.stencil = ##f

      \context Staff = "Staff1" \with {
        instrumentName = "Piano"
        shortInstrumentName = "Pno"
      } \new Voice \relative c'' {
        g a b c
      }
    >>
  >>
}

Comment: you are awesome!!
Answer: I've never seen anything like that before, it just looks like a mistake.

I suggest moving the common parts of your subfiles (prelude.ly & intro.ly) into the combining file (combine.ly), and making variables (\prelude & \intro) for the music in each of these.
Something like this:
%% prelude.ly

\version "2.24.1"

prelude = {
    \relative c'' {
        c2 d e f
    }
}

%\score {
%   \prelude
%}

%% intro.ly

\version "2.24.1"

intro = {
    \relative c'' {
        g2 a b c
    }
}

%\score {
%   \intro
%}

%% combine.ly

\version "2.24.1"

\include "prelude.ly"
\include "intro.ly"

<<
    \chords {
        c,2 g, c, f, g, f, g, c,
    }

    \new StaffGroup <<
        \override StaffGroup.SystemStartBracket.stencil = ##f

        \new Staff \with {
            instrumentName = "Piano"
            shortInstrumentName = "Pno"
        }
            \new Voice {
                \prelude
                \intro
            }
    >>
>>

This will give a "normal looking" score:

NB: When you are working on the subfiles, you'll want to uncomment the \score blocks, so that you will be able to see what you are doing (by compiling the subfiles) without having to compile the combine.ly file. Re-comment them when you have finished working on the subfiles, so that you don't get duplication in the combine.ly file.
Comment: Avoiding multiple staffgroups is the most straightforward solution. But if possible  I would prefer to have a new staffgroup for each part of score. This allows me the felxibility to add more instruments in parallel to a particular part without affecting anything else.
Comment: @kargirwar This comment should be part of your original post so that you get answers relevant to your goals.
Comment: Regarding your NB: Instead you can also do something like wrapping your `\score` blocks in `$(if (or (not (defined? 'INCLUDED)) (not INCLUDED)) #{ \score { ... } #})`. This will create a score unless you've done `INCLUDED = ##t`. Thus you won't have to do any comment/uncomment game but simply have a score created if compiled as single file and not if included (as long as the including file does `INCLUDED = ##t`).
Answer: Consider your code in toto:
<<
  \chords {
    c,2 g,2 c,2 f,2 g,2 f,2 g,2 c,2
  }

  {
    %prelude.ly
    \new StaffGroup <<
    \override StaffGroup.SystemStartBracket.stencil = ##f

    \new Staff \with {
      instrumentName = "Piano"
      shortInstrumentName = "Pno"
    } \new Voice \relative c'' {
    c d e f
    }
  >>
  %intro.ly
  \new StaffGroup <<
    \override StaffGroup.SystemStartBracket.stencil = ##f

    \new Staff \with {
      instrumentName = "Piano"
      shortInstrumentName = "Pno"
    } \new Voice \relative c'' {
      g a b c
    }
  >>
  }
>>

The image posted in the question is as expected, because a new staff group was started. But this is not what is actually desired. To get the desired result, the complete code should be more like this:
<<
  \chords {
    c,2 g,2 c,2 f,2 g,2 f,2 g,2 c,2
  }

  {
    \new StaffGroup <<
    \override StaffGroup.SystemStartBracket.stencil = ##f

    \new Staff \with {
      instrumentName = "Piano"
      shortInstrumentName = "Pno"
    } \new Voice \relative c'' {
      %prelude.ly
      c d e f
      %intro.ly
      g a b c
    }
  >>
  }
>>

Which is to say:
<<
  \chords {
    c,2 g,2 c,2 f,2 g,2 f,2 g,2 c,2
  }

  {
    \new StaffGroup <<
    \override StaffGroup.SystemStartBracket.stencil = ##f

    \new Staff \with {
      instrumentName = "Piano"
      shortInstrumentName = "Pno"
    } \new Voice \relative c'' {
        \include "prelude.ly"
        \include "intro.ly"
    }
  >>
  }
>>

In which the include files just contain the notes for that part of the piece.


DQN - How to feed the input of 4 still frames from a game as one single state input

Question: I was reading this blog about Deep Q-Learning.
1- In the The input section of the blog, I wanted to know how do we feed the 4 still-frames/screenshots from the game, that represent the input state, into the Policy network? Will all 4 frames be fed in one flattened tensor (where one image ends the next one starts, forming a continuous row input, in one tensor)? Or will they be fed separately one after the other into the network?
2- For preprocessing the images, do we avoid using the Max-pooling stage? My understanding is this process eliminate the need for spacial/position recognition in image-feature recognition. While in normal Conv-Net this is important for recognising image features regardless of where they appear in space and distance (so we us max-pooling). In Q-learning for games, the space/position of different elements on the image is important. Therefore, we remove the use of Max-pooling from the proprocessing stage. Is this correct?
3- Can anyone recommend a good implementation resource of Deep Q-learning, written from scratch (in Python), i.e. without the use of out-of-the-box libraries, like PyTorch, Keras and Scikit-learn ..etc, for a game, where image frame feeds from the game is required as states input. I'm thinking perhaps implementing the model from scratch gives a better control over customisation and fine tuning of the hyper-parameters. Or is it better to use out-out-of-the-box library? Any code implementation on this would be super helpful.
Many thanks in advance.
Answer:
Or will they be fed separately one after the other into the network?

The 4-frame "stack" is processed one frame at a time, so the tensor has 3 dimensions: it has shape (frame height, frame width, number of frames). It's not clear from your post, but the blog is probably referencing "Playing Atari with Deep Reinforcement Learning" by Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Alex Graves, Ioannis Antonoglou, Daan Wierstra, Martin Riedmiller which explains these choices and provides some citations for further reading.

do we avoid using the Max-pooling stage?

This depends on the specific model. Reading the primary literature about a model should clearly explain how it works.

Can anyone recommend a good implementation resource of Deep Q-learning, written from scratch (in Python), i.e. without the use of out-of-the-box libraries, like PyTorch, Keras and Scikit-learn ..etc, for a game, where image frame feeds from the game is required as states input.

There are lightweight implementations of reinforcement learning topics. One can be found in https://github.com/PacktPublishing/Deep-Reinforcement-Learning-Hands-On which is the code companion to Maxim Lapan's Deep Reinforcement Learning Hands-On.
However, this repository still uses pytorch for all of the generic neural network pieces. The reason is that there's simply no point to reinvent the wheel in terms of network construction, autograd, backprop and all the other standard neural network operations. The reinforcement learning portions of the code are very clearly written, although there is the occasional bug.
Comment: P.s. I tried to upvote your answer, but apparently I have to have at least 15 reputation to do that.
Comment: Awesome, thank you so much for the detailed answers and help @Sycorax. Sorry, I thought the hyper-link to the blog would work. I should've checked. It was actually for this blog I was refering to: http://deeplizard.com/learn/video/wrBUkpiRvCA . But you've answered my question anyway. I'll checkout the link you shared. Thank you so much again. :)


Set and modify model value depending on other model value

Question: I have this model:
class GiftCard extends Model

{
    use HasFactory;

protected $fillable = [
    'number',
    'hashed_number',
    'security_code'
];

protected function securityCode(): Attribute
{
    return Attribute::make(
        get: fn(string $value) => Crypt::decrypt($value),
        set: fn(string $value) => Crypt::encrypt($value),
    )->shouldCache();
}

protected function number(): Attribute
{
    return Attribute::make(
        get: fn(string $value) => Crypt::decrypt($value),
        set: fn(string $value) =>  Crypt::encrypt($value)
    )->shouldCache();
}

protected function hashedNumber(): Attribute
{
    return Attribute::make(
        set: fn(string $value) => hash('sha3-512' , $value) . Config::get("app.card_pepper"),
    )->shouldCache();
}

}

The model in the DB
public function up(): void
{
    Schema::create('gift_cards', function (Blueprint $table) {
        $table->id();
        $table->string('number');
        $table->text('hashed_number');
        $table->text('security_code');
        $table->timestamps();
    });
}

What I'm trying to do is automatically use the number to fill the field hashed_number because it depends on it and I don't want to give it as parameter. Is there a way to do it with mutators and remove hashed_number so the model looks like:
class GiftCard extends Model
{
    use HasFactory;

protected $fillable = [
    'number',
    'security_code'
];
.....

Comment: You can access any value of a Model in an Attribute, i.e. `protected function example(): Attribute { return Attribute::make(get: fn() => $this->number); }`. Calling `$giftCard->example` would return the value from `Crypt::decrypt($value);`
Comment: And, FYI, Laravel can do automatic encryption via the `Model::$casts` property. https://laravel.com/docs/10.x/eloquent-mutators#encrypted-casting
Comment: @miken32 that's a good idea thanks
Comment: @TimLewis I was trying to do it so I have not to handle the attribute each time
Answer: I finally found a way to do it:
class GiftCard extends Model
{
    use HasFactory;

protected $fillable = [
    'number',
    'security_code'
];

protected function number(): Attribute
{
    return Attribute::make(
        get: fn(string $value) => Crypt::decrypt($value),
        set: fn(string $value) => [
            'number' => Crypt::encrypt($value),
            'hashed_number' => hash('sha3-512' , $value) . Config::get("app.card_pepper")
        ],
    )->shouldCache();
}
}

protected function securityCode(): Attribute
{
    return Attribute::make(
        get: fn(string $value) => Crypt::decrypt($value),
        set: fn(string $value) => Crypt::encrypt($value),
    )->shouldCache();
}

In the set function return multiple attributes, the model in table:
public function up(): void
{
    Schema::create('gift_cards', function (Blueprint $table) {
        $table->id();
        $table->string('number');
        $table->text('hashed_number');
        $table->text('security_code');
        $table->timestamps();
    });
}


Exibir mensagem e esconder em alguns segundos

Question: Como fazer para mostrar uma notificação ao entrar no site e sumir depois de alguns segundos, com jQuery?
Tentei algo mas não consegui.
JSFIDDLE: http://jsfiddle.net/sunnypmody/XDaEk/
Código:
<!DOCTYPE html>

      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <meta charset="utf-8">
      <title>haxP v2</title>
      <link rel="shortcut icon" href="./favicon.png">
      <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>

               Welcome Underground

               Cada sonho que você deixa pra trás, é um pedaço do seu futuro que deixa de existir.

               Powered by Cruz

Comment: Bem vindo ao sopt. O que você já tentou, não tentativa alguma no código apresentado.
Comment: O problema é que eu não consigo encaixar Esse Códico: http://jsfiddle.net/sunnypmody/XDaEk/
Comment: Pode adicionar o link desse jsfiddle na pergunta? Clique em [edit]
Comment: JS Fiddle Adicionado
Answer: Exemplo didático:

// Iniciará quando todo o corpo do documento HTML estiver pronto.
$().ready(function() {
 setTimeout(function () {
  $('#foo').hide(); // "foo" é o id do elemento que seja manipular.
 }, 2500); // O valor é representado em milisegundos.
});

Foo Bar

Answer:
mostrar uma notificação ao entrar no site e sumir depois de alguns segundos

Usando o Exemplo que você mesmo deu :

$(document).ready(function(){  // A DIFERENÇA ESTA AQUI, EXECUTA QUANDO O DOCUMENTO ESTA "PRONTO"
  $( "div.success" ).fadeIn( 300 ).delay( 1500 ).fadeOut( 400 );
});

$( "#success-btn" ).click(function() {
  $( "div.success" ).fadeIn( 300 ).delay( 1500 ).fadeOut( 400 );
});

$( "#failure-btn" ).click(function() {
  $( "div.failure" ).fadeIn( 300 ).delay( 1500 ).fadeOut( 400 );
});

$( "#warning-btn" ).click(function() {
  $( "div.warning" ).fadeIn( 300 ).delay( 1500 ).fadeOut( 400 );
});
.alert-box {
 padding: 15px;
    margin-bottom: 20px;
    border: 1px solid transparent;
    border-radius: 4px;
}

.success {
    color: #3c763d;
    background-color: #dff0d8;
    border-color: #d6e9c6;
    display: none;
}

.failure {
    color: #a94442;
    background-color: #f2dede;
    border-color: #ebccd1;
    display: none;
}

.warning {
    color: #8a6d3b;
    background-color: #fcf8e3;
    border-color: #faebcc;
    display: none;
}

    <button id="success-btn">Success</button>
    <button id="failure-btn">Failure</button>
    <button id="warning-btn">Warning</button>

Successful Alert !!!

Failure Alert !!!

Warning Alert !!!

Answer: Não chega a ser necessário Javascript para isto, pode usar somente as animações das CSS visto que você quer exibir a notificação assim que o usuário entrar no site, não quando a página estiver completamente carregada ou o DOM estiver pronto.
Crie sua própria regra de comportamento com @keyframes, por exemplo:
@keyframes hide {
  from { opacity: 1 }
  to   { opacity: 0 }
}

E então usar essa regra para animar o elemento contendo a notificação.
Com a propriedade animation-delay você pode definir o tempo para a animação começar, se não quiser que ela ocorra instantaneamente, quando o usuário entrar na página. Por meio de animation-duration, define-se a duração que deve acontecer o que foi especificado na keyframe.
Para manter o estilo final (opacity: 0) no elemento alvo da animação, existe a propriedade animation-fill-mode que pode receber o valor forwards. E você terá isto:

@keyframes hide {
  from { opacity: 1 }
  to   { opacity: 0 }
}

div {
  animation: hide 2s 2s forwards
}

Notificação de 2 segundos...

Aplicando isto ao fiddle que foi postado nos comentários, ficaria assim:

@keyframes hide {
  from { opacity: 1 }
  to   { opacity: 0 }
}

.alert-box {
  animation: hide 2s 2s forwards;
  padding: 15px;
  margin-bottom: 20px;
  border: 1px solid transparent;
  border-radius: 4px;
}

.success {
  color: #3c763d;
  background-color: #dff0d8;
  border-color: #d6e9c6
}

Successful Alert !!!

Answer: Se for em Bootstrap você pode usar o window.setTimeout.
é muito mais fácil.
Abraço!

  <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
  Success! You have been signed in successfully!

Comment: Não precisa utilizar bootstrap para utilizar window.setTimeout
Comment: Eu sei! apenas dei uma sugestão, e nessa sugestão utilizei o Bootstrap como exemplo, talvez alguém que esteja utilizando essa biblioteca possa precisar, mais acho que o senhor não entendeu muito bem hehhehe Abraço!


Listar Banco de dados com Java ou PHP

Question: Gostaria de saber se há alguma forma de um aplicação mostrar todos os bancos de dados de uma conexão?
Atualmente uso o comando:
select
     *
from
     information_schema.TABLES;

Comment: se for todos os banco de dados é `SHOW DATABASES` (PHP/MYSQL) (https://dev.mysql.com/doc/refman/5.7/en/show-databases.html)
Comment: Não é só executar esta query pela aplicação?
Comment: banco de dados ou tabelas?
Answer: é so usar o SHOW DATABASES pelo menos comigo funcionou assim, usando PHP e mysql

Listar Banco de dados com Java ou PHP


How to fix picker dialog that is cutoff in smaller screens?

Question: In android application, I have used TimePickerDialog and DatePickerDialog. I want to develop this app in all different screen sizes.
The problem is, this dialog size is the same on all screen sizes. Dialog does not adjust its size as the size of the screen changes. So, on a smaller screen, the content of the dialog is cut off.
How can I adjust this dialog?
below is output I am getting in different size device. I even can't able to scroll in this dialog
App output1
App output2
Code of DatePickerdialog:
 DatePickerDialog datePicker;

 editText_date.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            datePicker = new DatePickerDialog(mActivity,new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int y, int m, int d) {
                 //other code here
                }
            },yy,mm,dd);

         //allow only future dates
            datePicker.getDatePicker().setMinDate(System.currentTimeMillis());
            datePicker.getDatePicker().setMaxDate(maxDate.getTimeInMillis());
            datePicker.show();
        }
    });

Comment: can you add a picture of the lost content? Could you share your code as well?
Comment: I have added code. Please check it
Answer: you can use these code block. if you will receive error you can write.
    private void dialogDatePickerLight() {
    Calendar cur_calender = Calendar.getInstance();
    DatePickerDialog datePicker = DatePickerDialog.newInstance(
            new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, monthOfYear);
                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    long date_ship_millis = calendar.getTimeInMillis();

                }
            },

            cur_calender.get(Calendar.YEAR),
            cur_calender.get(Calendar.MONTH),
            cur_calender.get(Calendar.DAY_OF_MONTH)
    );

    datePicker.setThemeDark(false);
    datePicker.setAccentColor(getResources().getColor(R.color.cyan_800_overlay));
    datePicker.setMinDate(cur_calender);
    datePicker.show(getFragmentManager(), "Title is here");

}

Comment: datePicker.setThemeDark() method is not available
Comment: @bhumivaghasiya device screen size very small. if above code not response for you you can use this answer for your device. https://stackoverflow.com/a/28291780/8738452
Comment: This is not solution of my problem.


How can I generate deb installable file for my ROS package(python code in the script folder)?

Question: How can I generate deb installable file from the python files in my package(in the script folder), so I can deliver the deb file to the client who can run the python executables in the package?
For example, I just completed the ROS tutorial and created the beginner_tutorials package in my catkin workspace. I also completed the Simple Publisher and Subscriber tutorials which mean the python talker.py and listener.py in the script folder in the beginner_tutorials package.Then I run the following command in the package folder,~/ROS/catkin_workspace/src/beginner_tutorials:
$ bloom-generate rosdebian --os-name ubuntu --ros-distro kinetic
$ fakeroot debian/rules binary
So it generated the deb file. After I installed the deb to a new machine and I try to run the command:
$ rosrun beginner_tutorials talker
$ rosrun beginner_tutorials talker.py
$ rosrun beginner_tutorials listener
$ rosrun beginner_tutorials listener.py
After the installation on the new machine. I can't run the talker and listener. There is no python file in the /opt/ros/kinetic/lib. but look inside of the deb file, there are python files in the /opt/ros/kinetic/lib folder. I don't know where the python file went after install the deb file. I was wondering how can I export the package with python script to a installable deb file and after I install the deb file on a new machine, I can run the python executable file on the new machine?
If someone can give me some hints or guidance, I would really appreciate it. Thank you in advance!
Jue Wang(Patrick)
Answer: You may just use CPack with following options:
(Package-wide CMakeLists.txt file)
#############
## Install ##
#############

set(CPACK_GENERATOR "DEB")

#Creating UNIX structured package
set(CPACK_CMAKE_GENERATOR "Unix Makefiles")
set(CPACK_PACKAGE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/../..")
set(CPACK_PACKAGE_VERSION 0.2.9)

#Set directory to /../ to avoid /share part of ROS_PACKAGE_PATH
set(CPACK_PACKAGING_INSTALL_PREFIX "$ENV{ROS_PACKAGE_PATH}/../")
set(CPACK_INSTALL_CMAKE_PROJECTS "${CMAKE_CURRENT_BINARY_DIR};${PROJECT_NAME};ALL;/./")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY
    "${PROJECT_NAME} - ${PROJECT_DESCRIPTION}")
set(CPACK_PACKAGE_NAME "${PROJECT_NAME}")
set(CPACK_PACKAGE_VENDOR "RCS")

#Now we can simply create the dependencies using almost the same package names as they declared in ROS repository
set(CPACK_DEBIAN_PACKAGE_DEPENDS "ros-kinetic-roscpp, ros-kinetic-std-msgs, ros-kinetic-message-runtime, ros-kinetic-sensor-msgs")

#IMPORTANT: set this to keep on auto-introspection for system dependencies like libc++6
set (CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)

#Keep Debian package structure untouched
set(CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION TRUE)

#Standard naming schema for Debian-based distros
set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}~${CMAKE_SYSTEM_NAME}_${CMAKE_SYSTEM_PROCESSOR}")
set(CPACK_PACKAGE_VENDOR "Technical University")
set(CPACK_PACKAGE_CONTACT "<email@example.com>")

#Turn the process on
include(CPack)

In case of simple catkin package structure you can simply uncomment and edit install sections of your CMakeLists.txt according to files your package required to install. Then run
catkin_make package

After that you will have the .deb package archive in the root directory of your ROS package. Now you can use dpkg-deb -c command to ensure the paths defined within the package are correct. To obtain the example download and examine any ROS package from the official binaries repository.


Relationships in Views always 4 results also if no reference for the field

Question: I have two content types :

meals
wine

In my content-type "meals" I have a entity reference to "wine".
Now I wanna create a views to show all meals, with a reference to wine.
I have create a views with following settings:

FILTER CRITERIA
= Content Type (= meals)
= (Content entity referenced from field_wine) Content: Published (Yes)
RELATIONSHIPS
= Entity Reference: Wine

In my view I get all results for that. So if a wine was tagged in 2 meals, I get a view with that two meals.
My Problem now: I always wanna show 4 meals. So I want to show the 2 meals + 2 others.
If i have a wine with 1 meals. So i want so show the 1 meal + 3 others.. and so on.
Do any know how to fill the results if the missing some meals?
Comment: So the "others" meals don't have wine, they have, for example, coke?
Comment: Can you elaborate little bit more.It seems like some information is missing Which is creating ambiguity.
Answer: I think the best way to do via https://www.drupal.org/project/views_field_view . So, below is the steps:-

Create a view for the meal which shows all meals and add one more field "nid" as a hidden parameter(just tick exclude from display) so that we will have an available token for nid.
Now, create another block of wine and pass meal's nid as a contextual fitler. so, it will give you all wine as per single meals.
The next step do the trick. Go back to block #1(meal's view) and and add global:view field and pass "[nid]" of the meal as a contextual filter in that field(you will find an option don't worry) and select the view and display of the #2(wine's block).
That's it, here you have all the meals with wines. :)

Hope it will solve your problem.


How to ignore accent in SQLite query (Android)

Question: I am new in Android and I'm working on a query in SQLite.
My problem is that when I use accent in strings e.g.

ÁÁÁ
ááá
ÀÀÀ
ààà
aaa
AAA

If I do:
SELECT * FROM TB_MOVIE WHERE MOVIE_NAME LIKE '%a%' ORDER BY MOVIE_NAME;

It's return:

AAA
aaa (It's ignoring the others)

But if I do:
SELECT * FROM TB_MOVIE WHERE MOVIE_NAME LIKE '%à%' ORDER BY MOVIE_NAME;

It's return:

ààà (ignoring the title "ÀÀÀ")

I want to select strings in a SQLite DB without caring for the accents and the case. Please help.
Comment: Not duplicate to the above - it is about correctly collating accented characters (upper/lowercase matching), not ignoring them.
Comment: possible duplicate of [Accented Search in sqlite (android)](http://stackoverflow.com/questions/14083446/accented-search-in-sqlite-android)
Answer: Generally, string comparisons in SQL are controlled by column or expression COLLATE rules. In Android, only three collation sequences are pre-defined: BINARY (default), LOCALIZED and UNICODE. None of them is ideal for your use case, and the C API for installing new collation functions is unfortunately not exposed in the Java API.
To work around this:

Add another column to your table, for example MOVIE_NAME_ASCII
Store values into this column with the accent marks removed. You can remove accents by normalizing your strings to Unicode Normal Form D (NFD) and removing non-ASCII code points since NFD represents accented characters roughly as plain ASCII + combining accent markers:
String asciiName = Normalizer.normalize(unicodeName, Normalizer.Form.NFD)
    .replaceAll("[^\\p{ASCII}]", "");

Do your text searches on this ASCII-normalized column but display data from the original unicode column.
Comment: Works for me as well, but Im wondering if there's no others way to do that
Comment: I wonder... is there any alternative way? I already did a "normalized" column solution, but for small, 1To1 strings. However, for One2Many Strings this solution might be overkill!! SQL can declare and use functions, right? Also, I am using RoomDB. Isn't there some helper in RoomDB for these things? I wonder...
Answer: In Android sqlite, LIKE and GLOB ignore both COLLATE LOCALIZED and COLLATE UNICODE (they only work for ORDER BY). However, there is a solution without having to add extra columns to your table. As @asat explains in this answer, you can use GLOB with a pattern that will replace each letter with all the available alternatives of that letter. In Java:
public static String addTildeOptions(String searchText) {
    return searchText.toLowerCase()
                     .replaceAll("[aáàäâã]", "\\[aáàäâã\\]")
                     .replaceAll("[eéèëê]", "\\[eéèëê\\]")
                     .replaceAll("[iíìî]", "\\[iíìî\\]")
                     .replaceAll("[oóòöôõ]", "\\[oóòöôõ\\]")
                     .replaceAll("[uúùüû]", "\\[uúùüû\\]")
                     .replace("*", "[*]")
                     .replace("?", "[?]");
}

And then (not literally like this, of course):
SELECT * from table WHERE lower(column) GLOB "*addTildeOptions(searchText)*"

This way, for example in Spanish, a user searching for either mas or más will get the search converted into m[aáàäâã]s, returning both results.
It is important to notice that GLOB ignores COLLATE NOCASE, that's why I converted everything to lower case both in the function and in the query. Notice also that the lower() function in sqlite doesn't work on non-ASCII characters - but again those are probably the ones that you are already replacing!
The function also replaces both GLOB wildcards, * and ?, with "escaped" versions.
Comment: I had to fix your regex to get it working, because it is inverted. Where is `.replaceAll("[aáàäâã]", "\\[aáàäâã\\]")` I had to use `.replaceAll("\\.*[aáàäâã]\\.*", "[aáàäâã]")`
Answer: You can use Android NDK to recompile the SQLite source including the desired ICU (International Components for Unicode).
Explained in russian here:
http://habrahabr.ru/post/122408/
The process of compiling the SQLilte with source with ICU explained here:
How to compile sqlite with ICU?
Unfortunately you will end up with different APKs for different CPUs.
Answer: You need to look at these, not as accented characters, but as entirely different characters.  You might as well be looking for a, b, or c.  That being said, I would try using a regex for it.  It would look something like:
SELECT * from TB_MOVIE WHERE MOVIE_NAME REGEXP '.*[aAàÀ].*' ORDER BY MOVIE_NAME;


How to write down a note that is sustained while there are other simultaneous pitches in the same bar?

Question: I'm writing down piano sheet music and I'm not sure how correctly to write a specific section. The left hand is playing a little arpeggio and I want the first note to be sustained. I came up with two ways to write it down (see below), but I'm not sure which is correct. So the question is: which is the right way to notate this? If it's the first method, I would also like to know if the starting rest is necessary?
Comment: @xnakos An adult should be able to play it with the left hand alone without too much difficulty, and without the aid of a pedal.
Comment: @xnakos I would use 5-2-1-2-1-2 as the fingering.
Comment: Can you play this with your left hand only? I think I injured my left hand just by looking at it! :)
Comment: @xnakos This is about as far as I can play it with one hand, but it's a fair point since the later parts might be a bit too wide even for me. Thankfully this piece is well suited for a sustain pedal, so straining a hand shouldn't be necessary. :)
Comment: @200_success I do not have a piano nearby, but I think that, as it is and without a pedal, the G-F#-G part can only be played with the thumb jumping, which will not sound that good. I do not believe that the index finger could reach that F#. But I do not have a piano nearby and I guess I am speculating a bit.
Comment: @200_success With your pinky stuck on the lowest G (the reason this question was asked)? Different hands require different measures, that is for sure. It just seemed impossible for me, in theory. Only a piano will tell! :)
Comment: @xnakos " I do not believe that the index finger could reach that F#." - it depends how flexible your hands are as well as how big they are. Playing a 7th fingered 5-2 shouldn't be a big deal at a "professional" level. Beginners, and/or children whose hands are still growing are a different situation of course.
Comment: You have a sustained note so there is no reason to try too hard to do legato with your top note.  I would just repeatedly use my thumb when comfortable.  There's no point of trying to stretch a 7th using pinky and index if it's slower and more cumbersome than just using all pinky and thumb.
Answer: The first way is correct, and yes, the initial quarter rest is important. It might not seem important in this example, but in more complex environments these rests are vitally important.
A performer will probably know what you mean if you were to write the second measure, but it's needlessly "busy." It also doesn't clarify that it's two separate musical lines occurring, which is clearly shown in the first measure.
Comment: I find it easier to explain both the rest and the use of the dotted whole note as there being two voices (bass and tenor) on the same staff. In fact, were the whole note to have a stem, it would be pointing down, to distinguish this voice from the upward pointing stems of the other voice.
Comment: The essential thing is to make it clear exactly *when* to play the first D. If there are no other notes, you need to rest to indicate that. If there was some music on the top staff, or if this pattern was repeated, maybe the rest is not absolutely *essential*, but since it doesn't take up any space on the score that could be used for anything else, there is no good reason *not* to include it.


Is it necessary to uninstall rubygems-update?

Question: I was reading the Agile Web Development with Rails book the other day. The author issues the following command to update rubygems:
gem update --system
gem uninstall rubygems-update

Why is it necessary/good-practice to uninstall rubygems-update after updating rubygems?
Answer: It's definitely not necessary to uninstall rubygems-update, as your rubygems functionality will function fine with it still installed.  It's optional/nice to do because it is only used for updating rubygems, and thus after rubygems has been updated the rubygems-update gem is simply an extra file and takes up space on your computer and shows up when you run gem list unnecessarily.


Making a fixed div scroll horizontally, & return to centre when page is maximised

Question: I have been hunting around for a solution to my problem and have solved the first half, but have one small outstanding snag that I am hoping someone can help me with.  I am reasonably well versed in html and css, and have been known to make use of the odd bit of very basic php, but am totally new to javascript / jquery, and am very much an amateur  when it comes to web design, so please be gentle with me and explain in simple terms!
I am trying to put together a website with a fixed width of 960px which, in wider browser windows, is centred.  For this I am using the following CSS:
#container {
 width:960px;
 margin:auto;
}

which is working fine.
At the top of this div, I want to have a fixed horizontal menu which floats above the rest of the page's content, which is the full 960px wide, and which stays glued to the top of the viewport and in view when the user scrolls vertically downwards.
While the window is wider than the 960px wide container, this is easy, and the following CSS works just fine:
#top {
 width:960px;
 position:fixed;
 top:0;
}

The problem is that, because the CSS position:fixed is always in relation to the viewport, if the window is shrunk to less than 960px wide, the page gains a scroll bar at the bottom and main content area scrolls to the right, but the fixed menu at the top does not, meaning that the right hand side of it is lost and cannot be accessed.
When searching for a solution to this I found this thread, in which it says that the following jquery code will do the trick:
$(window).scroll(function () {
 $('#top').css('left', -($(window).scrollLeft()));
});

Essentially, this alters the css on the #top div to move it left as the user scrolls right.  This seems elegant, simple and perfect for my needs.  After some faffing around trying to figure out how to make this work and where to put it, I have added the following code inside my body tags:

So far, so good!  When the page is first loaded, at a browser window wider than 960px, the menu is at the top and centred inside the container div, and stays fixed in place when the main content is scrolled up and down.  Then, when the window is shrunk to less than 960px and a horizontal scroll bar appears, the menu scrolls to the right alonside the main content.  Perfect!  Sadly, there is one more snag....
Although the scrolling then works fine while the page is narrow, if it is once again widened to more than 960px, the floating menu at the top stays over to the left hand side, rather than moving back to the centre along with the main content, because it still has the css "left" property as set by the jquery code again.  This breaks my lovely layout, and means that the menu is no longer in line with the main content.
Somehow, I need to essentially delete this bit of css as soon as the browser window goes above 960px wide and the horizontal scroll bar disappears.
Is there some sort of javascript / jquery that will do this?  I am completely new to all this, and so far searching has got me no-where.....
Any help or suggestions greatly appreciated!
Comment: Do you have this online somewhere we can see? Or can you paste the HTML?
Comment: Oops - seems this isn't working quite as well as I had initially thought.  I have just realised that the initial, centred layout when the browser is > 960px wide, also breaks when the content is scrolled vertically downwards, because the vertical scrolling also kicks in the jquery and sets the left property in the top div's css to 0, meaning that it jumps to the left hand side of the page.  So as well as a fix for returning the menu to the centre when the page is maximised after being shrunk, I also need to figure out how to only have a horizontal scroll trigger the existing jquery.... :(
Comment: tsdexter - yes, I do!  The page I am testing it on is here:
Comment: http://huntleywood.co.uk/NEW/v2/
Answer: I would try adding to your jquery
$(window).resize(function(){
    if ($(window).width() > 960) {
        $('#top').css('left', 'auto');
    } else {
        $('#top').css('left', -($(window).scrollLeft()));
    }
});

Does that work?
You can use this to just detect left scrolling:
var lastScrollLeft = 0;
$(window).scroll(function() {
var documentScrollLeft = $(document).scrollLeft();
if (lastScrollLeft != documentScrollLeft) {
    //your code here
    $('#top').css('left', -($(window).scrollLeft()));

    lastScrollLeft = documentScrollLeft;
}
});

Comment: Right, one thing at a time.  Because I keep making silly mistakes!  The first bit, to re-centre the menu when the window gets maximised, works a treat - thanks!  Re the 2nd bit, give me a minute and I'll test it....
Comment: Right, when I add the code to stop the menu moving left when the vertical scroll bars are used, this bit works (ie the menu stops jumping left inappropriately), but this seems to break the horizontal scrolling, too, so I'm back to the situation where, when the window is shrunk, the menu no longer scrolls.  But I'm not 100% sure I'm implementing this correctly.  Can you tell me exactly which bit of code should go where you have "//your code here"?
Comment: I updated it with your code. I think you might have the layout/build incorrect - you shouldn't necessarily need so much JS on a simple page. Tell me how you want the page to layout/function without any of the bugs and I'll see if I can help restructure the HTML/CSS. You can email me if it's easier.
Comment: Thanks so much!  I will drop you an email about it.....  I hugely appreciate the help, but don't seem to be able to up-vote your answers as I'm not reputable enough! ;)
Comment: *lol* nope - assumed I would find some way to email you by clicking on your username - just returned here to say I can't find it and ask if I was being blind or stupid! ;)
Answer: I fixed it! Yay!  Just goes to show what waiting 'til the morning and having a clear head will do.  Just needed to add a very simple "if" statement to the code which scrolls the menu to the left.
Here is the final solution, with big thanks to tsdexter!
$(window).scroll(function () {
 if (($(window).scrollLeft())>0) {
  $('#top').css('left', -($(window).scrollLeft()));
 }
});

$(window).resize(function(){
 if ($(window).width() > 960) {
  $('#top').css('left', 'auto');
 }
});

Now seems to be working picture-perfectly in Firefox - haven't tried the others yet!  fingers crossed....
Comment: Just a quick update - although this works, it is sadly slow and laggy.  When scrolling back to the left on a narrow screen, the css doesn't seem to update fast enough, leaving the menu bar too far to the right compared to the rest of the page.  *sigh*  This is worse in IE, where it is noticeable at reasonable scrolling speeds, but also happens in firefox and chrome if you scroll left fast.  The problem seems to be the "if" statement, remove that and the scrolling goes back to being super fast & smooth but I'm back to  having the issue of the menu moving horizontally when scrolling vertically:(
Comment: I did try that at the time (and again, just now), but apparently I don't have the "reputation" to do so!  :/  Sorry....  Would if I could!
Comment: Haha, you need to build up that rep :P


How can I calculate the precision and recall by the ground truth and prediction values of Caffe model?

Question: I have trained and tested my image datasets using Caffe, and the data in val.txt is the ground truth. But, how can I calculate the precision and recall by the ground truth and prediction values?
Could you pls give me some suggestions and recommend some python codes?
Answer: If you are using python, sklearn.metrics has a very rich collection of tools for assessing classification accuracy. If you want a simple precision/recall/F1 table, you can just use sklearn.metrics.classification_report. Your model doesn't have to be trained in sklearn for you to use the skelarn.metrics.