Como inserir gif animado no pygame

Question: Boa tarde, estou fazendo um trabalho do faculdade, é um jogo em python e preciso inserir um gif no código mas quando uso o comando pygame.image.load("correr.gif") ele monstra a imagem do gif congelada, ficando apenas uma imagem em png. Alguem pode me ajudar
segue o código inicial :
import pygame
pygame.init()
x = 352
y = 500
velocidade = 15
fundo = pygame.image.load("fundo_pista.png")
homem = pygame.image.load("correr.gif")

Comment: Erick, por favor, poste o seu código como exemplo, o que você fez até agora, como tentou etc.
Answer: A biblioteca pygame pode ler imagens e exibir imagens estáticas com poucas chamadas. Mas nao tem suporte a GIFs animados. Se quiser exibir uma animação em gif em Pygame, terá que usar uma biblioteca com suporte mais completo a GIF - por exemplo, a "pillow", extrair os frames e indicações de tempo desejadas, e exibir cada frame manualmente (chamando o método "blit" da sua tela no pygame, e o pygame.display.flip() )
Então - vamos lá:
A Pillow pode ser instalada como "pip install pillow"  - e aí, ela sabe carregar uma imagem, verificar se é uma animação, e extrair todos os frames.
Agora mesmo usando a PIL, não é possível obter quanto tempo é esperado para
cada frame (o formato GIF permite que cada imagem fique sendo exibido por um tempo personalizado -então você pode ter uma imagem parada por 3 segundos, e uma animação em sequência rápida). Acredito ser razoável trabalahr com 100 milisegundos (10fps)
para cada frame - podemos usar o método .tick()
 de uma instância de  pygame.time.Clock para isso.
Aí acontece que objetos do tipo Image do PIL não são compatíveis com objetos "Surface" do Pygame - é necessário converter de um tipo para o outro.
As duas bibliotecas permitem traduzir imagens de e para uma sequência de bytes -
(na PIL o método chama "tobytes", e na pygame, por conta do método ter sido
criado ainda no Python2, se chama "fromstring" - (mas aceita um objeto bytes))
Além disso, imagens em GIF usam o modo de imagem de "paleta" com um número reduzido de cores, elas tem que ser convertidas pra RGB antes de ser feita a conversão. (Trabalhar com paletas direto poderia ser possível, mas seria mais complicado).
A melhor forma de fazer essas duas pequenas operações é escrever uma funçãozinha
para cada uma dessas coisas:
import sys

import pygame
from PIL import Image

size=(800,600)
FORMAT = "RGBA"

def pil_to_game(img):
    data = img.tobytes("raw", FORMAT)
    return pygame.image.fromstring(data, img.size, FORMAT)

def get_gif_frame(img, frame):
    img.seek(frame)
    return  img.convert(FORMAT)

def init():
    return pygame.display.set_mode(size)

def exit():
    pygame.quit()

def main(screen, path_to_image):
    gif_img = Image.open(path_to_image)
    if not getattr(gif_img, "is_animated", False):
        print(f"Imagem em {path_to_image} não é um gif animado")
        return
    current_frame = 0
    clock = pygame.time.Clock()
    while True:
        frame = pil_to_game(get_gif_frame(gif_img, current_frame))
        screen.blit(frame, (0, 0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return

        current_frame = (current_frame + 1) % gif_img.n_frames

        pygame.display.flip()
        clock.tick(10)

if __name__ == "__main__":
    try:
        screen = init()
        main(screen, sys.argv[1])
    finally:
        exit()

(a conversão de imagens entre pil e pygame, eu adaptei a partir
do código aqui: https://riptutorial.com/pygame/example/21220/using-with-pil ,
a documentação para ler frames no PIL aqui: https://pythontic.com/image-processing/pillow/extract%20frames%20from%20animated%20gif )
Se for necessário ter o timing de frames de dentro do GIF isso tem que ser
adaptado, e temos que 'descer' até o código do PIL que lê os GIFs
e pegar os dados de lá - no limite, depois de pesquisar isso, fariamos
uma sugestão de melhoria (com pull request), à própria Pillow.

Como inserir gif animado no pygame


What is the limit $\lim_{n\to\infty}\sqrt[n]{n^2+3n+1}$?

Question: Can you try to solve it? I tried to do something but I do not know how to continue it:
\begin{align}
& \lim_{n\to\infty}\sqrt[n]{n^2+3n+1}=\lim_{n\to\infty}(n^2+3n+1)^{1/n} = e^{\lim_{n\to\infty} \frac{1}{n}\ln(n^2+3n+1)} \\[10pt]
= {} & e^{\lim_{n\to\infty}\frac{1}{n} \frac{\ln(n^2+3n+1)}{n^2+3n+1} (n^2+3n+1)}.
\end{align}
Comment: You could compare it to $\sqrt[n]{n}^2$
Comment: yeah ok but do you know if my method is good?
Comment: Erm, the easiest way is to l'Hopital it from your third expression.
Comment: I know it is easier. But I do not know l'Hospital and I need to do it with classic method. Do you have any idea how should I?
Answer: For positive values of $n$ we have$$\sqrt[n]{n^2}\lt \sqrt[n]{n^2+3n+1}\le\sqrt[n]{5n^2}$$ Note that $$\lim_{n\to\infty}\sqrt[n]{n}=\lim_{n\to\infty}\sqrt[n]{5}=\color{Red}{1}.$$ Hence by the squeeze we have the answer.
Comment: @OvyOvy The first bound is just that $3n+1>0$. The second bound is $3n+1 \leq 4n^2$, which should be clear when $n \geq 1$. So now the problem boils down to just $\lim_{n \to \infty} n^{1/n}$ which is an easier problem.
Comment: I don't know if it's worth noting or not but "5" is just a convenience. if $n > 1$, $ 3n + 1 < 3n^2 + n^2=4n^2$.  But if n > 3, say, then $n^2 + 3n + 1 < n^2 + n^2 + n^2/9 = 2\frac 19 n^2 < 3n^2$ and if $n > 4$, then $n^2 + 3n + 1 < n^2 + \frac 34 n^2 + \frac 1{16}n^6 = 1.8125 n^2$ so you could use 2. but that wouldn't be as direct or as simple.
Comment: Why is it like that?
Comment: $0\lt 3n+1\le 3n^2+n^2$
Answer: $$
\lim_{n\to\infty}\sqrt[n]{n^2+3n+1}\sim \lim_{n\to\infty}\sqrt[n]{n^2}=\lim_{n\rightarrow \infty}n^{2/n}\rightarrow1
$$
If this is not satisfying, you can also note that
$$
(n+2)^2=n^2+4n+2
$$
Which is always larger than $n^2+3n+1$ and you can squeeze
$$
\lim_{n\to\infty}\sqrt[n]{n^2}\leq\lim_{n\to\infty}\sqrt[n]{n^2+3n+1}\leq\lim_{n\to\infty}\sqrt[n]{(n+2)^2}\\
\Rightarrow
\lim_{n\to\infty}n^{2/n}\leq\lim_{n\to\infty}\sqrt[n]{n^2+3n+1}\leq\lim_{n\to\infty}{(n+2)^{2/n}}\\
\Rightarrow 1\leq\lim_{n\to\infty}\sqrt[n]{n^2+3n+1}\leq 1
$$
Comment: Why is it like that?
Comment: Why is what like what? the first similarity comes from the fact that for large enough $n$, $3n+1<<n^2$
Comment: Ok. I am a novice in limits and I do not master them very well.
Answer:
PRIMER
In THIS ANSWER, I showed using only the limit definition of the exponential function along with Bernoulli's Inequality that the logarithm function satisfies the inequalities
$$\frac{x-1}{x}\le \log(x) \le x-1 \tag 1$$
for $x>0$.

We will now use $(1)$ to show that $\lim_{n\to \infty}\frac1n \log(n)=0$.  To do so, we see from $(1)$ that for any $\alpha>0$
$$\begin{align}
\alpha \log(x) &=\log(x^\alpha)\\\\
&\le x^\alpha -1\\\\
&<x^\alpha\\\\
\log(x)\le \frac{x^\alpha}{\alpha}
\end{align}$$
Hence, we can assert that
$$\frac1n \log(n)\le \frac{n^{\alpha -1}}{\alpha} \tag 2$$
for any $\alpha >0$.
Since $(2)$ is true for any positive $\alpha$, it is certainly true for $0<\alpha <1$.  Therefore, for $0<\alpha <1$ we see that $\lim_{n\to \infty}\frac1n \log(n)=0$.

Next, using $\log(n^2+3n+1)\le \log(5n^2)=\log(5)+2\log(n)$, we see that
$$\begin{align}
\lim_{n\to \infty}\sqrt[n]{n^2+3n+1}&=\lim_{n\to \infty}e^{\frac1n \log(n^2+3n+1)}\\\\
&=e^{\lim_{n\to \infty}\frac1n \log(n^2+3n+1)}\\\\
&=e^0\\\\
&=1
\end{align}$$
as was to be shown!
Comment: I do not know L'Hospital's Rule thats why I ask what did I do wrong?
Answer: Hint: $$ \frac{1}{n} \ln \left( n^2+3n+1 \right) = \frac{1}{n} \ln \left( n \left(n+3+\frac{1}{n} \right) \right) = \frac{1}{n} \ln n + \frac{1}{n} \ln \left( n+3+\frac{1}{n} \right) $$
Write in the last expression:
$$ \frac{1}{n} = \frac{1}{n}-\frac{1}{n+3+\frac{1}{n}}+\frac{1}{n+3+\frac{1}{n}}= \frac{1}{n^2} \frac{3n+1}{n+3n+1} +\frac{1}{n+3+\frac{1}{n}}$$
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{{#1}}\,}
 \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{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#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{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\lim_{n \to \infty}{1 \over n}\ln\pars{n^{2} + 3n + 1}
\\[5px] = &\
\lim_{n \to \infty}
\ln\pars{\bracks{n + 1}^{\, 2} + 3\bracks{n + 1} + 1 \over n^{2} + 3n + 1}\qquad
\pars{~Stolz-Ces\grave{a}ro\ Theorem~}
\\[5mm] = &\ \color{#f00}{0} \qquad\implies\qquad
\lim_{n \to \infty}\root[n]{n^{2} + 3n + 1} = \exp\pars{\color{#f00}{0}} = \bbx{\ds{1}}
\end{align}


Is there a way to get fine grained progress of Elastic Transcoder job?

Question: I'm using read_job() API to monitor jobs' progress. This only gives me a very coarse info about the status being one of the: Submitted | In Progress | Complete | Canceled | Error.
However, I'd like to show the user a percentage or ETA when in the In Progress state. Is there any API which gives such a fine grained progress information?
Answer: I don't think the "job % complete" is available to us according to the docs:
http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/elastictranscoder-dg.pdf
The JSON status update only has the "PROGRESSING" state which means very little for a user.
Amazon is aware this is a wanted feature from developers, as seen here:
https://forums.aws.amazon.com/thread.jspa?messageID=477076&#477076


How to make this delete test independent?

Question: I want to check DELETE response. So should I make employee in this test or it should be in a different place(Before method for example)?
<code>      @Test(description="positive")
public static void deleteEmployeeEducation()
    Response res= given().
                      spec(Specifications.getRequestSpecAsEmpl()).
        body(Payloads.addEmployeeEducation("GGGG","ingieneer",2005,2010)).
                      when().
                      put(Endpoints.createEmployeeEducation()).
                      then().log().all().extract().response();
    JsonPath js= ReusableMethods.rawToJson(res);
    Integer  educationId=js.get("[0].id");

        given().
                spec(Specifications.getRequestSpecAsEmpl()).
                delete(Endpoints.deleteEmployeeEducation()+educationId).
                then().log().all().
                assertThat().statusCode(204);
</code>
Answer: If you want your delete test to be independent, then yes, it makes sense to first create the user in this test, then assert that deleting it works. The logical prerequisite is that an insert test has been successfully tested beforehand.
I wouldn't necessarily advise that you seek to make this delete test independent, however. Typically, in cases like this where you're testing CRUD operations provided by an API, it makes sense to have an integration test, with a logical order. If your API exposes insert, select, delete, update operations, then an integration test could be this sequence of tests, in this order:

Test insert works, with user 123
Test select works and returns user 123
Test update works, and updates user 123 to user 234. Probably add a select assertion within this test, and assert the select returns user 234
Test delete works. Probably add a select assertion which asserts no user is returned.

That would be my advice for the design of your test class, if I am correct in understanding that you're simply testing different CRUD operations.
The @Before method should be used for setting up prerequisites for the tests. It can make sense to create your employee in here if all your tests relate to the same employee. Otherwise, I would recommend my approach with the integration test.
Let me know if this helps.
Comment: Thanks a lot.  Is it better to make one CRUD test? (@Test CRUDEmployee()) or four dependent tests? (@Test createEmpl(){abc}; @Test readEmpl(abc),...)?
Comment: 4 tests. You're testing each operation, you're not testing the actual employee. And if one fails, it will be clear and concise which operation is faulty.


Complex Select and Input Text Filed Combo with add more and remove option

Question: I have a drop down also a text filed. User can select which kind of link they are providing and then give link in input text.
Also they can add more links of different kind. Only 1 link of 1 kind.
If they made mistake they can remove any link.
I am stuck in this problem and unable to figure out any simple solution.
Final output required is an array projectLinks. [{web:"url"},{android:"url"}]
Please help.

React Code:
import MainLayout from "./layouts/MainLayout";

const linkOptions = [
  { value: "web", label: "Web" },
  { value: "android", label: "Android" },
  { value: "ios", label: "iOS" },
  { value: "youtube", label: "Youtube" },
  { value: "twitter", label: "Twitter" }
];

type ProjectLinks = [
  { web?: string },
  { android?: string },
  { ios?: string },
  { youtube?: string },
  { twitter?: string }
];

export default function App() {
  const [projectLinks, setProjectLinks] = useState<ProjectLinks>();
  const [numberOfLinks, setNumberOfLinks] = useState(1);
  const handleChangeOption = (event: any) => {
    console.log(event.target.value);
  };
  const submit = () => {
    console.log("Submitted");
  };
  const handleAddLink = () => {
    setNumberOfLinks((prev) => prev + 1);
  };
  const handleRemoveLink = () => {
    setNumberOfLinks((prev) => prev - 1);
  };
  return (
    <MainLayout>

        {[...Array(numberOfLinks)].map((_, index) => (
          <LinkField
            key={index}
            handleChangeOption={handleChangeOption}
            handleAddLink={handleAddLink}
            handleRemoveLink={handleRemoveLink}
          />
        ))}
        <button className="btn btn-active mt-8" onClick={submit}>
          Button
        </button>

    </MainLayout>
  );
}

function LinkField({
  handleChangeOption,
  handleAddLink,
  handleRemoveLink
}: {
  handleChangeOption: (event: any) => void;
  handleAddLink: () => void;
  handleRemoveLink: () => void;
}) {
  return (

        <select onChange={handleChangeOption} className="select select-primary">
          {linkOptions.map((option, index) => (
            <option key={index} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
        <input
          type="text"
          placeholder="example.com"
          className="input input-bordered ml-1 mr-1"
        />
        <button
          className="btn btn-md btn-active ml-1 mr-1"
          onClick={handleAddLink}
        >
          Add
        </button>
        <button
          className="btn btn-md btn-active ml-1 mr-1"
          onClick={handleRemoveLink}
        >
          Remove
        </button>

  );
}

I am using tailwindcss with daisyui.
Comment: Data needs to be saved in state when choosing item from drop-down and on blur/change of input field, and on button(add) click can save data as key value pair and push it in an array
Comment: Are you restricting setProjectLincks for 5 items? Because this line can this issue - > useState()
Answer: I solved it by avoiding most of the state variables and used form submit.
import { useState } from "react";
import MainLayout from "./layouts/MainLayout";

const linkOptions = [
  { value: "web", label: "Web" },
  { value: "android", label: "Android" },
  { value: "ios", label: "iOS" },
  { value: "youtube", label: "Youtube" },
  { value: "twitter", label: "Twitter" }
];

type ProjectLinks = [
  { web?: string },
  { android?: string },
  { ios?: string },
  { youtube?: string },
  { twitter?: string }
];

export default function App() {
  const [count, setCount] = useState(1);
  const [urlError, setUrlError] = useState(false);
  const submit = (event: any) => {
    let urlTypeArray: string[] = [];
    let urlArray: string[] = [];
    let projectLinks: ProjectLinks[] = [];
    [...Array(count)].map((_, index) => {
      let url =
        count === 1 ? event.target.url.value : event.target.url[index].value;
      let urlType =
        count === 1
          ? event.target.urlType.value
          : event.target.urlType[index].value;
      if (
        urlTypeArray.includes(urlType) ||
        urlArray.includes(url) ||
        !url.length
      ) {
        setUrlError(true);
        return null;
      } else {
        urlTypeArray.push(urlType);
        urlArray.push(url);
        var urlObj: any = {};
        urlObj[urlType] = url;
        projectLinks = [...projectLinks, urlObj];
      }
    });
    if (!urlError && projectLinks.length) {
      console.log(projectLinks);
      // Action for URL submit to API
    }
    event.preventDefault();
  };
  const handleAddLink = () => {
    setCount((prev) => (prev < linkOptions.length ? prev + 1 : prev));
  };
  const handleRemoveLink = () => {
    setCount((prev) => (prev > 1 ? prev - 1 : prev));
  };
  return (
    <MainLayout>
      <form className="flex flex-col" onSubmit={submit}>
        {[...Array(count)].map((link, index) => (
          <LinkField
            key={index}
            index={index}
            handleAddLink={handleAddLink}
            handleRemoveLink={handleRemoveLink}
          />
        ))}
        <button
          className={`btn ${urlError ? "btn-disabled" : "btn-active"} mt-8`}
        >
          Button
        </button>
        {urlError ? (

 setUrlError(false)}
          >

              Duplicate URL Type or URL or URL is Empty.

        ) : null}
      </form>
    </MainLayout>
  );
}

function LinkField({
  handleAddLink,
  handleRemoveLink,
  index
}: {
  handleAddLink: () => void;
  handleRemoveLink: () => void;
  index: number;
}) {
  return (

        <select name="urlType" className="select select-primary">
          {linkOptions.map((option, index) => (
            <option key={index} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
        <input
          type="text"
          name="url"
          placeholder="example.com"
          className="input input-bordered ml-1 mr-1"
        />
        <button
          className={`btn ${
            index === linkOptions.length - 1 ? "btn-disabled" : ""
          } ml-1 mr-1`}
          onClick={handleAddLink}
          type="button"
        >
          Add
        </button>
        <button
          className={`btn ${index === 0 ? "btn-disabled" : ""} ml-1 mr-1`}
          onClick={handleRemoveLink}
          // type="button"
        >
          Remove
        </button>

  );
}


How to get last date of particular month from the month ID and year in SQL?

Question: How to get last date of particular month from the month ID and year in SQL ?
Inputs :
@MonthID INT = 2,
@Year    INT = 2015

Required output : 28/02/2015
Comment: Which **version** of SQL Server? As of SQL Server **2012**, there's an [`EOMONTH`](https://msdn.microsoft.com/en-us/library/hh213020.aspx) function for this exact purpose
Comment: Yes its SQL Server 2012 .. Got the answer ..Thank you
Answer: It's easy in SQL Server 2012+
To frame date from the year and month use DATEFROMPARTS (Transact-SQL)
To find the last day of month use EOMONTH (Transact-SQL)
Declare @MonthID INT = 2,
        @Year    INT = 2015

SELECT Eomonth(Datefromparts(@Year, @MonthID, 1))

For any thing less then Sql server 2012
SELECT Dateadd(dd, -1, Dateadd(mm, 1, Cast(Cast(@Year AS CHAR(4)) + '-'
                       + Cast(@MonthID AS VARCHAR(2))+'-'+'1' AS DATE)))

Note: If the variables are of Varchar type then you can remove the cast to varchar
Answer: You can find the last day of the month in the following manner
Declare @MonthID varchar(10) = '02', @Year varchar(10) = '2015'
select dateadd(dd,-1,dateadd(MM,1,cast(@Year+'-'+@MonthID+'-1' as date)))

Answer: This is how I did it.
DECLARE @MonthID INT = 3,
@Year    INT = 2015

DECLARE @InputDate DATE, @TempDate DATE, @OutputDate DATE

SET @InputDate = CAST(CAST(@Year AS VARCHAR) + '-' + CAST(@MonthID AS varchar) + '-01' AS DATE)
SET @TempDate = @InputDate

WHILE (DATEPART(m, @InputDate) = DATEPART(m, @TempDate))
BEGIN
    SET @OutputDate = @TempDate
    SET @TempDate = DATEADD(d,1,@TempDate)
END

SELECT @OutputDate


Fetching only first row from database

Question: I work with:
<code>$mandator = $this->database->select('Mandators', 'm')
     ->fields('m')
     ->condition('idMandators', $mandatorId)
     ->execute()
     ->fetchAll();
</code>
to retrieve my data from database. The result is an array with 1 array item. How can I retrieve always only 1 object, without the array? Like e.g. <code>->fetchOne</code>?
Answer: <code>$query = \Drupal::entityQuery('node')
            ->condition('status', 1)
            ->condition('type', 'my_content_type')
            ->condition('field_ref_au', $nid, '=')
            ->range(0,1)
            ->sort('created', 'DESC')
        ;
</code>
Answer: This works
<code>$database = \Drupal::database();
$row = $database->query("SELECT column_name FROM {table_name} WHERE column_required = :value", [':value' => $value]);
</code>
Answer: As per my understanding I would say
try to count the number of rows like this:
<code>$number_of_rows = db_select('node')->countQuery()->execute()->fetchField();
</code>
then iterate to get the first count.
Or:
<code>// Get a single record out of the database.
$node = db_query("SELECT * FROM {node} WHERE nid = :nid", array(':nid' => $nid))->fetchObject();
</code>
Answer: You can simply write (example get node) :)
<code>$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n)->fetchObject();
</code>
If you want to get a single value you can use fetchField()
Example (get node title):
<code>$node_title = db_query('SELECT title FROM {node} WHERE nid = :nid',
array(':nid' => $nid))->fetchField();
</code>
Comment: Thanks for your quick answers.

db_query() is deprecated/very old. I prefer the database object.

I am wondering, why the query methods are lacking documentation on drupal.org. We should probably add some. Even you could try them or use the evaluate expression function in phpstorm ide. Probably ->fetchField() and fetchObject() can be adapted to the database object.

Fetching only first row from database


Strange PDE solution

Question: Given the linear equation $$u_t -xt u_x = x$$ $x\in\mathbb{R}$, $t>0$, with IVP $u(x,0)=u_0(x)$, my solution comes to $u(x,t) = u_0(xe^{t^2/2})+xt$, but Maple gives a much more complicated solution to this IVP. I would appreciate if someone could please point out what I might not be doing right.
Assuming the parametrization $x=x(s), t=t(s), u=u(s)$, and applying the method of characteristics, we get: $$t_s=1, x_s=-xt,u_s=x,$$ so $$u_x = -\frac{1}{t}, u_t=x,$$ thus
$$u=xt+c_2, x=e^{t^2/2}c_3,$$ where $c_2, c_2$ are constants.
So, $u-xt=c_2, c_3 = xe^{t^2/2}$, $G(xe^{t^2/2})=u-xt$, and $G(x) = u_0(x)$, and we get $$u(x,t) = u_0(xt^{t^2/2})+xt$$
But Maple gives me this:
Comment: I've just spotted an error: $u_x$ should be $-\frac{1}{t}$. But then, $u=G(xe^{t^2/2})-\frac{x}{t}$. How does one then apply the initial condition?
Comment: OK, I've resolved the issue. Used a slightly different approach.
Answer: Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dt}{ds}=1$ , letting $t(0)=0$ , we have $t=s$
$\dfrac{dx}{ds}=-xt=-xs$ , letting $x(0)=x_0$ , we have $x=x_0e^{-\frac{s^2}{2}}=x_0e^{-\frac{t^2}{2}}$
$\dfrac{du}{ds}=x=x_0e^{-\frac{s^2}{2}}$ , letting $u(0)=f(x_0)$ , we have $u(x,t)=f(x_0)+\int_0^sx_0e^{-\frac{\tau^2}{2}}~d\tau=f(xe^\frac{t^2}{2})+\int_0^txe^\frac{t^2-\tau^2}{2}~d\tau$
$u(x,0)=u_0(x)$ :
$f(x)=u_0(x)$
$\therefore u(x,t)=u_0(xe^\frac{t^2}{2})+\int_0^txe^\frac{t^2-\tau^2}{2}~d\tau$

Strange PDE solution


Mathematics of Ritardando

Question: Beyond feel & experience, is there a rule conductors use for ritardando in terms of  (a) its rate, (b) its change in rate, and/or (c) the relationship between the final tempo and the tempo of the piece?
(In getting my software to execute a ritardando, I employed over four measures a measure-by-measure decrease in tempo, and what sounded "right" to me ultimately was decreasing the tempo by 4 bpm, then a further 9, then a further 16 (pleasing pattern) to arrive at 127/156 (close to 3/4) the original tempo.)
Comment: In Musescore, I'm normally fine with linearly changing the tempo, with the same decrement every the same number of beats. I often have to change the tempo more than once per bar to make it sound right, though.
Answer: "Beyond feel and experience"? Using a mathematical formula to create a ritard in music would not be beyond using instinct, but vice versa. It's nearly impossible to create an authentic ritard in computerized music because composers don't create ritards to slow down the music, but to create an emotional reaction in the audience. The rates of ritards depend on countless criteriae such as harmony, melody, timbre, and rhythm, and what the musician has had for lunch.
Computers are thus extremely impractical music makers. It is up to you to decide what is pleasing and program the computer to follow your wishes, if possible. Whatever you decide is pleasing, it is extremely probably that someone out there will disagree with you. The best you can do is make an intelligent decision about the music.
In terms of following ritadando markings in the score:
At the end of a piece
Ritardando markings at the end of a piece should generally be greater than other ritardandos throughout the piece, unless otherwise specified. If the music was slow to begin with, musicians should be careful not to slow too dramatically.
When there is a dashed line (- - -) indicating the length of the ritard
Musicians should gradually slow the music down until the dashed line ends in the score. There may or may not be a tempo indicated to arrive at. Obey any "a tempo" markings.
When there is a ritard marking alone
Obey the ritard marking intelligently.
Answer: "...is there a rule conductors use for ritardando in terms of (a) its rate, (b) its change in rate, and/or (c) the relationship between the final tempo and the tempo of the piece?"
Not that I'm aware of. Such a rule would be of little value, because -- unless you're practicing with a drum machine, or other device that permits varying tempo -- there's generally no good way (other than feel) to for conductors or performers to accurately measure their tempo during a performance. They're certainly not likely to be thinking "Now this beat has to be played 10% longer than the previous one, and the following beat has to be 17.4% longer than that..."
However, if I had to guess a general shape of a tempo curve in a ritard, they generally seem to be monotonically decreasing (you don't speed up again in the middle of a ritard), and concave downward (i.e., the most ritard'ing comes just before the end of the ritard). But to what degree this is true is up to the conductor or performers to decide.
On the other hand, about the most prescriptive that I've usually seen music notation get is poco rit. (just a little bit of ritardando), or molto rit. (much ritardando). And of course, the dashed line that Richard mentions, to indicate the duration of the ritard.
That said, I am interested in what the tempo curves of actual performances would look like. I know that approximate tempo maps can be created for real performances, and I'd be surprised if someone, somewhere, hasn't researched what these curves look like.
Answer: I don't know if there are any conductors who conduct a ritardando or accelerando mathematically (i doubt it!), but if you want to compare a growth (which means both increase and decrease) in some musical parameter with natural phenomena you could use exponential growth:
f(t) = a.e^kt

with a being the initial value of your parameter (in your case the duration of a note), k the growth rate (k>0 for increase and k<0 for decrease) and t being your unit of measurement (i.e. time or an index number of a note in a sequence of notes).
This could be implemented in the programming language Python as follows:
import math

def exp_growth(init_val, growth_rate, idx):
    """calc the exponential growth"""
    return init_val * pow(math.e, growth_rate * idx)

def ritard(init_dur, ritard_rate, n_notes):
    """prints single durations of a ritard. and its overall dur"""
    duration_samples = [exp_growth(init_dur, ritard_rate, t) for t in  range(n_notes)]
    duration = sum(duration_samples)
    print("Ritard.: {}".format(duration_samples))
    print("Overall duration of ritard.: {} seconds".format(duration))

# With init_dur = 0.6 seconds, every note has a 10%
# increase in duration, get the ritard. durations over 5 notes:
ritard(0.6, 0.1, 5)

In this example i get the durations of every note during a ritardando over 5 notes, where my first note has a duration of 0.6 seconds (say a quarter note at tempo M.M.100) and every note should have a duration increase of 10% (relating to its preceding note). The above code will print:
Ritard.: [0.6, 0.6631025508453886, 0.7328416548961019, 0.8099152845456019, 0.8950948185847621]
Overall duration of ritard.: 3.7009543088718546 seconds

Mathematics of Ritardando


Multi threads c#

Question: Gostaria de criar um programa para atuar várias threads em um processo, deixando-o mais rápido, ou seja, as threads trabalhando juntas para terminar o serviço mais rápido. Porém cada uma trabalha individualmente no processo.
Código exemplo:
class Program
{
    static void Main(string[] args)
    {
        Soma s = new Soma();
        Thread[] Threads = new Thread[5];
        for (int i = 0; i < 5; i++)
        {
            Threads[i] = new Thread(new ThreadStart(s.PrintNumbers));
        }

        foreach (Thread t in Threads)
            t.Start();

        Console.ReadLine();
    }
}
class Soma
{
    double soma = 0;
    public void PrintNumbers()
    {
        for (int i = 0; i < 5; i++)
        {
            if (i%2 != 0)
            {
                soma -= i;
            }
            else
            {
                soma += i;
            }
        }
        Console.WriteLine(soma);
    }
}

Comment: Este código é muito esquisito, provavelmente tem erros, mas não posso afirmar porque não sei o objetivo. O ideal é usar `Task` e não `Thread` e neste caso executará mais lento que se fizer sequencial. https://pt.stackoverflow.com/q/123173/101 e https://pt.stackoverflow.com/q/1946/101
Comment: Então, o objetivo é realmente responder se uma aplicação de múltiplas threads terá um resultado melhor, porém não estou conseguindo fazer com que várias threads trabalhem no mesmo processo.(fins didáticos)
Comment: Não da pra dizer somente com um caso isolado como esse, pra esse seu código, só o fato da nova thread alocar novos recursos já ia deixar mais lento.
Comment: o código em si não é esse, é apenas um exemplo
Answer: Use Pools de Threads. Exemplo:
using System;
using System.Threading;

public class Fibonacci
{
    private int _n;
    private int _fibOfN;
    private ManualResetEvent _doneEvent;

    public int N { get { return _n; } }
    public int FibOfN { get { return _fibOfN; } }

    // Constructor.
    public Fibonacci(int n, ManualResetEvent doneEvent)
    {
        _n = n;
        _doneEvent = doneEvent;
    }

    // Wrapper method for use with thread pool.
    public void ThreadPoolCallback(Object threadContext)
    {
        int threadIndex = (int)threadContext;
        Console.WriteLine("thread {0} started...", threadIndex);
        _fibOfN = Calculate(_n);
        Console.WriteLine("thread {0} result calculated...", threadIndex);
        _doneEvent.Set();
    }

    // Recursive method that calculates the Nth Fibonacci number.
    public int Calculate(int n)
    {
        if (n <= 1)
        {
            return n;
        }

        return Calculate(n - 1) + Calculate(n - 2);
    }
}

public class ThreadPoolExample
{
    static void Main()
    {
        const int FibonacciCalculations = 10;

        // One event is used for each Fibonacci object.
        ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
        Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
        Random r = new Random();

        // Configure and start threads using ThreadPool.
        Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
        for (int i = 0; i < FibonacciCalculations; i++)
        {
            doneEvents[i] = new ManualResetEvent(false);
            Fibonacci f = new Fibonacci(r.Next(20, 40), doneEvents[i]);
            fibArray[i] = f;
            ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
        }

        // Wait for all threads in pool to calculate.
        WaitHandle.WaitAll(doneEvents);
        Console.WriteLine("All calculations are complete.");

        // Display the results.
        for (int i= 0; i<FibonacciCalculations; i++)
        {
            Fibonacci f = fibArray[i];
            Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
        }
    }
}

Fonte: Como usar um pool de threads (C#)
Answer: Se as suas operações não realizam operações de IO, ou se não pode utilizar o .net 4.5 ou posterior, pode fazer uso do Parallel.For.
var s = new Soma();
Parallel.For(0, 5, i => PrintNumbers());

agora se está à utilizar o .net 4.5 ou posterior, poderá fazer uso das palavras magicas async/await.
static void Main(string[] args)
{
    Task.Run(Exec).GetAwaiter().GetResult();
}

static async Task Exec()
{
    var s = new Soma();
    var tasks = new Task[5];
    for (int i = 0; i < 5; i++)
        tasks[i] = s.PrintNumbers();
    await Task.WhenAll(tasks);
}

class Soma
{
    double soma = 0;
    public async Task PrintNumbers()
    {
        await Task.Yield();
        for (int i = 0; i < 5; i++)
        {
            if (i%2 != 0)
            {
                soma -= i;
            }
            else
            {
                soma += i;
            }
        }
        Console.WriteLine(soma);
    }
}

Porem o Parallel.For tem uma vantagem sobre o async/await, o mesmo cria um particionamento interno para evitar que seja criadas mais Threads que o necessário.
Porém também particionar as suas Tasks de forma manual, porém não terá à ajuda do Parallel para calcular o numero ideal de partições.
static void Main(string[] args)
{
    Task.Run(Exec).GetAwaiter().GetResult();
}

static async Task Exec()
{
    var s = new Soma();
    var particoes = 3;
    var tasks = Enumerable.Range(0, particoes).Select(x => Task.CompletedTask).ToArray();
    for (int i = 0; i < 7; i++)
    {
        var particao = i % particoes;
        tasks[particao] = tasks[particao].ContinueWith(async t => await s.PrintNumbers());
    }
    await Task.WhenAll(tasks);
}

class Soma
{
    double soma = 0;
    public async Task PrintNumbers()
    {
        await Task.Yield();
        for (int i = 0; i < 5; i++)
        {
            if (i%2 != 0)
            {
                soma -= i;
            }
            else
            {
                soma += i;
            }
        }
        Console.WriteLine(soma);
    }
}

Multi threads c#


Tensorflow: how to make sure all samples in each batch are with different labels?

Question: I wonder whether there is a way to apply constraints on the batches to generate in Tensorflow. In particular, I would like to produce batches containing different labels.
Suppose I have five possible labels, {A, B, C, D, E}, I would like batches like (A, C, E, D, B) or (B,E,D,C,A). Basically, I want to avoid batches with equal labels such as (A, A, D, E, C) or (A, B, B, B, E).
Answer: Implementing what you asked
Batching simply extracts BATCH_SIZE samples from whatever it gets as input and packs them together, so technically yes, that's possible. It's up to you, however, making sure that the input to batch() is sorted the way you want.
Probably the most efficient way to do this would be to have 5 tf.data.Datasets, each with a specific label, zip them together to obtain one "batched" dataset with labels always in the same order, then .map on it tf.random_shuffle to obtain a random permutation of the batch and feed this to your network.
I'd also throw in a .shuffle after the random permutation, just t make sure that the network doesn't see the same batch always in the same order.
In code that would look something like:
data = [ tf.constant([chr(ord('A')+i), chr(ord('a')+i) ]) for i in range(5) ]

per_label_datasets = [tf.data.Dataset.from_tensor_slices(d) for d in data]
dataset = tf.data.Dataset.zip(tuple(per_label_datasets)) # now an item has shape len(per_label_datasets) and one item from each
dataset = dataset.map(lambda *args : tf.random_shuffle(args)) # lambda needed because random_shuffle takes only one argument
dataset = dataset.shuffle(10) # optional

it = dataset.make_one_shot_iterator()
batch = it.get_next()

sess = tf.Session()
print(sess.run(batch))
print(sess.run(batch))

sample output:
[b'a' b'c' b'd' b'e' b'b']
[b'C' b'B' b'A' b'D' b'E']

Personal note
I don't know what model you're using, and I assume out there there are models for which this would make sense, but in most models the order of samples in the batch is meaningless because results are averaged together over a batch when calculating the loss. So, if you really need this, there are ways to do it, but make sure you actually need it before starting to code the pipeline.
Comment: I agree with your personal note, indeed I need to tweak my batch generator because I'm implementing a triplet loss function where I want to compare different examples and similar examples.


How to show that $\mathbb{R}^N$ is a complete metric space

Question: How may I show that for $N \geq 2$, $\mathbb{R}^N$ is a complete metric space given that the metric defined is $d = ||x-y||_2$?
A complete metric space is a metric space where every cauchy sequence converges in the space.
I think I would start off saying that given our metric $d = ||x-y||_2$, and some sequence $x_n$, then the sequence is cauchy if $||x_n - x_m||_2 < \epsilon$ for some $n,m > M$ where $M$ is a positive integer. Since I must show that the sequences converge in the metric space, I will have to of course use the definition of a converging sequence. That is, the converging sequences definition is: $\forall_{\epsilon > 0} \exists_{N \in \mathbb{N}}, \; \forall_{n > N} \left ( (x_n - L) < \epsilon \right)$.
Though, i'm not quite sure how to tie my information together.
Answer: I imagine that you know that $\mathbb{R}$ is complete. Right?
Then the idea is to look at the coordinates (there are $N$) of your sequence.
Answer: Suppose that $\{x_n\}$ is Cauchy. Then, each sequence of components $\{x_{n,i}\}$ ($i=1,\ldots,N$) is Cauchy and, by the completeness of $\mathbb{R}$, convergent to some $L_i$. Let $L=(L_1,\ldots,L_N)$. Then, $x_n\to L$.


Files migration failed

Question: I am trying to migrate Drupal 7 site to Drupal 8. Other migration processes work well, but only file migration fails.
I have files in sites/default/files/.
This is my migrate_plus.migration.upgrade_d7_file.yml
uuid: c6ddfa39-c76a-4457-ba30-8db364387f45
langcode: en
status: true
dependencies:
  module:
    - file
id: upgrade_d7_file
migration_tags:
  - Drupal 7
label: Files
source:
  plugin: d7_file
process:
  fid: fid
  uid: uid
  filename: filename
  uri: uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
destination:
  plugin: entity:file
  source_path_property: filepath
  urlencode: true
migration_dependencies:
  required: {  }
  optional: {  }

And, I execute it with this drush command:
drush8 migrate-import upgrade_d7_file

This process returns this error message:
Processed 446 items (0 created, 0 updated, 446 failed, 0 ignored) - done with 'upgrade_d7_file'

What am I doing wrong here?
Answer: First off, when there are failures, check the messages table to see what the specific failures are:
$ drush8 mmsg upgrade_d7_file

In this case, I'm sure what you'll find is that it couldn't copy the files, because it couldn't find them - your .yml file does not include source_base_path, so there's no way for the migration to know where to copy the files from.
I'm guessing when you ran drush migrate-upgrade --configure-only to generate your migrations, you forgot --legacy-root - this value (either the address of your site such as http://www.example.com if you want to scrape the files directly over the web, or an absolute local filepath if you've copied the files onto your D8 server) will be used to set source_base_path in your destination configuration.

Files migration failed


How to make convert ResultSet Query to JSON using gson in eclipse?

Question: The code that I have written is:-
import com.google.gson.Gson;
import com.google.gson.JsonObject;

 public class JsonFileCreation{
    public static JsonArray convertToJSON(ResultSet resultSet)
            throws Exception {
        JsonArray jsonArray = new JsonArray();
        while (resultSet.next()) {
            int total_columns = resultSet.getMetaData().getColumnCount();
            JsonObject obj = new JsonObject();
            for (int i = 0; i < total_columns; i++) {
                obj.put(resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase(), resultSet.getObject(i + 1));
            }
          jsonArray.put(obj);
        }
        return jsonArray;
    }
public static void main(String args[]) {
        Gson gson = new Gson();
        JsonArray jsonArr = new JsonArray();
        ....
        }

Which is showing error in the line. It is showing put(String,Object) is not defined for the type Json Object.
jsonArray.put(obj);

My ResultSet Query is-
sql = "SELECT * FROM EMPLOYEE";
ResultSet rs = stmt.executeQuery(sql);

The table looks like this:
Click here to view the table
I am a beginner. Please help me with how to write the code correctly and get the json output in the browser.
Comment: Hi there and welcome to Stack Overflow.  You mention that your code gives you an error, please edit your question to include the details of the error.  There are plenty of errors that can be generated by code that doesn't work, and we can't help you without knowing more details.  (We also don't want to guess at what the error might be, because if we guess wrong, we will have provided a fix to the wrong error, which wouldn't be helpful.)
Comment: I have mentioned it now.. If you can help, it will be great!
Answer: The error you are getting is:

put(String,Object) is not defined for the type JsonObject.

And if you have a look at the Gson Javadoc for JsonObject, that message is correct.  The JsonObject class has no put method.
Instead, there are some add methods, and it is likely that you will want to use those.
However, there is no add method that takes any type of object and puts it into JSON.  You will have to handle the various different types of value yourself.  You may get null values, strings, numbers, dates and possibly others too.
I would suggest creating a new method, something like the following, to handle adding a single value to your JSON object obj.  It would check the given value among a few different types that it knows of, and use the relevant JsonObject add or addProperty methods to add the values:
    private static void addValueToJSON(JsonObject obj, String propertyName, Object value) throws Exception {
        if (value == null) {
            obj.add(propertyName, JsonNull.INSTANCE);
        } else if (value instanceof Number) {
            obj.addProperty(propertyName, (Number)value);
        } else if (value instanceof String) {
            obj.addProperty(propertyName, (String)value);
        } else if (value instanceof java.sql.Date) {
            // Not clear how you want dates to be represented in JSON.
            // Perhaps use SimpleDateFormat to convert them to a string?
            // I'll leave it up to you to finish this off.
        } else {
           // Some other type of value.  You can of course add handling
           // for extra types of values that you get, but it's worth
           // keeping this line at the bottom to ensure that if you do
           // get a value you are not expecting, you find out about it.
           throw new Exception("Unrecognised type of value: " + value.getClass().getName());
        }
    }

Once you've done this, you would call your new method by replacing the line
                obj.put(resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase(), resultSet.getObject(i + 1));

with
                addValueToJSON(obj, resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase(), resultSet.getObject(i + 1));

Finally, you wrote that your error occurred on the line
jsonArray.put(obj);

I don't believe this is correct, as on this line you are not attempting to call a method on a JsonObject.  However, the JsonArray class also has no put method, so there is an error on this line too.  The error in this case is much easier to fix: like the JsonObject class, the JsonArray class also has add methods, but you can use the one that takes a JsonElement because you are adding a JsonObject to the array and JsonObject extends JsonElement.  The fix this time is just a case of replacing
jsonArray.put(obj);

with
jsonArray.add(obj);

Comment: Thank you for the help! It did help me a lot!


MSSQL query not working, even if there is data

Question: Trying to run a more complex SQL query on an MS SQL server, but I get no data output. Logically should be fine, but I cant see why it doesnt work:
SELECT D.NAME DATABASE_NAME,T.NAME TABLE_NAME,I.NAME INDEX_NAME,C.NAME COLUMN_NAME
FROM sys.dm_db_index_physical_stats (NULL, NULL, NULL , NULL, 'LIMITED') XXX
INNER JOIN SYS.DATABASES D
ON D.DATABASE_ID = XXX.DATABASE_ID
INNER JOIN SYS.TABLES T
ON T.OBJECT_ID = XXX.OBJECT_ID
INNER JOIN SYS.INDEXES I
ON I.OBJECT_ID = T.OBJECT_ID
INNER JOIN SYS.INDEX_COLUMNS IC
ON IC.OBJECT_ID = I.OBJECT_ID
INNER JOIN SYS.COLUMNS C
ON C.OBJECT_ID = IC.OBJECT_ID
ORDER BY D.NAME, T.NAME
If I run SELECT * FROM sys.dm_db_index_physical_stats (NULL, NULL, NULL , NULL, 'LIMITED'), I get proper data, so the other query should work, but still doesn't.
Any ideas?
Answer: I would imagine that you are running this in master..  the sys.dm_db_index_physical_stats reports at global level, the other tables are at a database level.
you can confirm this by USE  and executing you should see data returned.
You may also want to use sp_msforeachDB  ( http://weblogs.sqlteam.com/joew/archive/2008/08/27/60700.aspx) to execute the code in each database.


Spring MVC handling session expired

Question: I'm working with Jboss EAP 6.2, Java EE 6 and Spring MVC 4.0.2.
When the session expired I want to execute a page redirect.
I have developed a Spring Interceptor
@Component
public class SessionExpiredInterceptor extends HandlerInterceptorAdapter {

    static final Logger logger = Logger.getLogger(SessionExpiredInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     final HttpSession session = request.getSession(false);
         if ( session == null || session.isNew() ) {
             ConfigurationProperties confProp = ConfigurationProperties.getInstance();
             logger.info("Sessione scaduta, redirect home page");
             request.getSession(true);
             response.sendRedirect(request.getContextPath() + "/" +
                     confProp.getInstance().getProperty("session.expired.redirect"));
         }
        return true;

    }
}

but I have the following exeception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.navigator': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: JBWEB000043: Cannot create a session after the response has been committed
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:353)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.getTarget(CglibAopProxy.java:676)
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:627)
    it.lispa.sire.finanziamentionline.web.mvc.model.Navigator$$EnhancerBySpringCGLIB$$b6b810e.addNavigationMessages(<generated>)
    it.lispa.sire.finanziamentionline.web.mvc.UserSessionInterceptor.preHandle(UserSessionInterceptor.java:91)
    org.springframework.web.servlet.HandlerExecutionChain.applyPreHandle(HandlerExecutionChain.java:130)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
JBWEB000071: root cause

java.lang.IllegalStateException: JBWEB000043: Cannot create a session after the response has been committed
    org.apache.catalina.connector.Request.doGetSession(Request.java:2627)
    org.apache.catalina.connector.Request.getSession(Request.java:2361)
    org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:790)
    org.springframework.web.context.request.ServletRequestAttributes.getSession(ServletRequestAttributes.java:79)
    org.springframework.web.context.request.ServletRequestAttributes.getSessionMutex(ServletRequestAttributes.java:212)
    org.springframework.web.context.request.SessionScope.get(SessionScope.java:91)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:338)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.getTarget(CglibAopProxy.java:676)
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:627)
    it.lispa.sire.finanziamentionline.web.mvc.model.Navigator$$EnhancerBySpringCGLIB$$b6b810e.addNavigationMessages(<generated>)
    it.lispa.sire.finanziamentionline.web.mvc.UserSessionInterceptor.preHandle(UserSessionInterceptor.java:91)
    org.springframework.web.servlet.HandlerExecutionChain.applyPreHandle(HandlerExecutionChain.java:130)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:847)

The navigator bean is injected in some @Controller and other Interceptor.
This is a Interceptor that use Navigator bean:
    @Component
    public class UserSessionInterceptor extends HandlerInterceptorAdapter {

        @Autowired
        private Navigator navigator;

        static final Logger logger = Logger.getLogger(UserSessionInterceptor.class.getName());

        public static ConfigurationProperties getAuthenticationProps() throws IOException {
            return ConfigurationProperties.getInstance();
        }

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
...}
}

The following is the interceptor configuration in spring.xml

<mvc:interceptor>
    <mvc:mapping path="/**"/>
    <mvc:exclude-mapping path="/static/**" />
    <mvc:exclude-mapping path="/index.jsp" />
    <mvc:exclude-mapping path="/logout" />
    <mvc:exclude-mapping path="/ajax-logout" />
    <bean class="it.lispa.sire.finanziamentionline.web.mvc.SessionExpiredInterceptor" />
</mvc:interceptor>

<mvc:interceptor>
    <mvc:mapping path="/home"/>
    <mvc:exclude-mapping path="/static/**" />
    <mvc:exclude-mapping path="/logout" />
    <mvc:exclude-mapping path="/ajax-logout" />
    <bean class="it.lispa.sire.finanziamentionline.web.mvc.UserSessionInterceptor"/>
</mvc:interceptor>

Can you help me?
Thanks.
Comment: Can you show us where your `navigator` bean is declared and where it is injected?
Comment: @SotiriosDelimanolis It is injected in some controller and other Spring Inspector
Comment: @SotiriosDelimanolis i have inserted it in the question. Thanks
Comment: The `preHandle` at the beginning of your question is in `SessionExpiredInterceptor`?
Comment: @SotiriosDelimanolis Yes
Answer: What happens here is that SessionExpiredInterceptor acts before UserSessionInterceptor. If it detects that the session is new, it performs a redirect
response.sendRedirect(request.getContextPath() + "/" +
    confProp.getInstance().getProperty("session.expired.redirect"));

Once you do a redirect, you've basically stated that you're finished processing the request and have sent a response (301 status code). But instead, in your code, you are returning true from preHandle which indicates to the DispatcherServlet that it should continue handling the request, execute the other interceptors and eventually reach the @Controller.
You don't want this. In the if block, return false after the sendRedirect.

Spring MVC handling session expired


Can we define an enum variable like an array?

Question: i have below enum :
enum words= {dog, cat, horse, hen, goat, pig, sheep};

can i assign a new enum constant as below :
words word = words[4];

What i want to do is get a random number between 0 and words.size() .and i want to pick that word from the enum . is it possible?
int wordno = (rand()%8);

words word = (words)wordno;

Comment: `words word = (words)wordno;` would work. Why do you need operator `[]` while cast could achieve it?
Comment: Shivani Garg, With 7 in `{dog, cat, horse, hen, goat, pig, sheep};`, `int wordno = rand()%7;` makes more sense.
Comment: If you add an additional element `num_words` to the `enum`, then this element will have the value of the number of elements in the array. You can then use `num_words` instead of hard-coding the value `7` or `8`.
Answer: Your enum declaration is a bit wrong. It should be
enum words {dog, cat, horse, hen, goat, pig, sheep};

Since C++11 it is usually also better to use an enum class instead, see this question for details:
enum class words {dog, cat, horse, hen, goat, pig, sheep};

Note that enum enumerators already have a numeric value. If you don't specify these numeric values manually, they are from left-to-right starting from zero increasing by one. So e.g. horse has the numeric value 2 in your enumeration.
However, it is not directly allowed to convert between the numeric value and the enumeration implicitly. If you need to do that, you must use static_cast:
auto word = static_cast<words>(wordno);

When doing this, you need to be careful however (which is also why the explicit cast is required), because you are not allowed to cast an integer value that is outside the range of numeric values of the enumeration in this way. In your code you do rand()%8 which can return values up to 7, but the largest numeric value in your enumeration is 6 for sheep. You would have undefined behavior with that.
auto can be replaced by words. It just lets the compiler figure out the correct type, so I don't have to write it twice. (It is already in the static_cast.)
As a sidenote, rand is not a good random number generator for many reasons (see e.g. this question). Since C++11 you can use the more modern <random> library, see this question.
Also as a sidenote I suggest avoiding C-style casts such as (words)wordno. Instead use static_cast as I showed above. You are much less likely to make serious mistakes this way, since the C-style casts are usually too permissive in what casts they allow.

For words word = words[4];, this syntax does not work. But it is not really necessary, since as above, you can initialize word directly with the value 4 with an explicit cast.
auto word = static_cast<words>(4);

But if you are intending to assign a constant value, you should just use the enumerator directly. That is what they are for:
auto word = words::goat;

Comment: i want the enum to take a different constant value (from the given values in {}) in every run. but in this case it just takes the value to be the random number that is generated. Instead i want it to hold the values as 'dog' or'cat'
Comment: @ShivaniGarg It is not clear to me what you mean. After the assignment, `word` will be of type `words` and hold one of `words::dog`, `words::cat`, etc. randomly.
Comment: int main(){

 enum words { dog, cat, horse, hen, goat, pig, sheep}
  srand(time(0));
int wordno = (rand()%7);
//words word = (words)wordno;

words word = static_cast(wordno);

std::cout<<word<<std::endl;
}

now the output is a integer whereas i want the output to be the string ,e.g. dog
Comment: @ShivaniGarg The name of an enumerator is a purely compile-time concept. You cannot get a string to print from an enumerator's name, the same as you can't get a string to print from a variable's name. If you want to assign strings to the enumerators, write a function that uses `switch` on `words` and returns the corresponding string to each enumerator.


Java: Create method to print all multiples of 3 between 1 and n?

Question: So the question is asking to create a method that will take an integer x as a parameter and print out all integers from 0->x that are multiples of three.
I can print out the number of times three divides x like so:
  public int Threes(int x){

    int i = 0;
    for(int counter = 1; counter <= x; counter++){
        if (counter % 3 ==0){
            i ++;
        }

    }
        return i;

but I'm not sure how to print out each multiple of 3!?
Comment: if (counter % 3 ==0){
            i ++; System.out.println(counter);
        }
Comment: That program does not print out the number of times three divides `x`.  Rather, that returns the number of multiples of `3` less than `x` FYI
Answer: for(int counter = 1; counter <= x; counter++){
    if (counter % 3 ==0){
        System.out.println(counter);
    }

}

Answer: An even quicker approach would be to increment by 3
public void Threes(int x) {
    for (int counter = 3; counter <= x; counter = counter + 3) {
        System.out.println(counter);
    }
}

This loop will jump right to the multiples of 3, instead of counting every single number and having to do a modulo check for each iteration. Since we know that 1 and 2 are not multiples of 3, we just skip right to 3 at the beginning of the loop. If the input happens to be less than 3, then nothing will be printed. Also, the function should be void since you're printing instead of returning anything.
(Your title says 1 to n, but your question says 0 to n, so if you actually need from 0 to n, then change the declaration of counter to int counter = 0;)
Answer: Jason Aller wow that was so simple and elegant. This one builds on it by counting down from 300 to 3, by 3's.
public class byThrees {

public static void main(String[] args) {
    for (int t = 100; t >= 0; t--) {
        System.out.println(t*3);

Answer: Best practice using the For-loop in Java.
public class MultiplesOfThree {

    public static void main(String []args){
        for (int m = 1; m<=12; m++){
            System.out.println(m*3);
        }
    }
}


Lower Semi-Continuous Functions Arising from Plane Flows

Question: If $X$ is a Hausdorff space, by a flow I mean a continuous surjection $F: X \times \mathbb{R} \rightarrow X$ such that $F(x, s + t) = F(F(x,s), t)$ for all $x \in X$ and $s, t \in \mathbb{R}$.  If $x$ is periodic (or fixed) under $F$, then let $p_F(x)$ denote the minimal non-negative time such that $F(x, p_F(x)) = x$.  Otherwise, write $p_F(x) = \infty$.
In other words, $p_F(x)$ is the length of the period of $x$, and is infinite when $x$ is not periodic.
Then by a continuity argument you can show that the function $p_F(x)$ is lower semi-continuous from $X$ into $[0, \infty]$; especially, if $x_n \rightarrow x$ and $ 0 < p_F(x) = r < \infty$, then every finite accumulation point of $\lbrace p_F(x_n) \rbrace$ is a positive integer multiple of $r$, as necessary due to the continuity of F.

What lsc functions $f: \mathbb{R}^2 \rightarrow \mathbb{R}$ arise as $p_F$ for some plane flow $F$?

It's not all of them: For example, if $f$ is constantly $1$ except at a single point, where it takes the value $\frac{1}{2}$.  By the above argument, any jump discontinuity must be an integer multiple of the lower limit value, but the previous example shows that this is not sufficient.  Note that in the plane any non-periodic orbit of a flow is homeomorphic to $\mathbb{R}$, providing another 'obvious' constraint.
What are some other properties that might be sufficient to allow an associated flow?
Comment: The concept of a flow usually has $F(x, 0) = x$ for all $x$ as well (thus it identifies the partticles flowing by their position at time $0$). With that addendum, you'll also need to make a small adjustment to the definition of $p_F(x)$ to keep it from always being $0$.
Comment: Just to be clear, in your question what was $X$ has become $\mathbb{R}^2$, right?
Comment: Yeah, $X$ is the plane.  I couldn't decide if it was better to just state the definitions for the plane and have them seem very phenomenal, or state them generally.  Maybe it was the wrong call on this one xD
Comment: That $F(x,0) = x$ is implied from the definition of flow, it doesn't need to be specified.  There's no need to make adjustments to the definition.  If $F$ is the constant flow then that's fine, $f \equiv 0$ is lsc.
Comment: If $x\in X$ and $F(x,t)=x$ for each $t\in\mathbb R$ then $p_F(x)=0$, right?
Comment: In an answer, I drafted some steps to demonstrate that $p_F$, when it takes finite values, is continuous between those values. Are there known counterexamples ?
Answer: Some preliminary observations, which can be helpful, but are too long for a comment.
Define a relation $\sim$ on $X$ putting $x\sim y$ if there exist $s,t\in\mathbb R$ such that $F(x,s)=F(y,t)$. It is easy to check that $\sim$ is an equivalence relation, so $X$ splits into equivalence classes of $\sim$. Moreover, for each such class $C$ and each $x\in C$ we have $C=F(x,\mathbb R)$. It suggests to call equivalence classes of the relation $\sim$ orbits. It is easy to check that $p_F$ is constant on each orbit (as I understood, if $x\in X$ and $F(x,t)=x$ for each $t\in\mathbb R$ then $p_F(x)=0$, so we assume this). We have a partition $X=\bigcup_{T\in [0,\infty]} X_T$, where $X_T=\{x\in X:p_F(x)=T\}$ for each $T\in [0,\infty]$, and each $X_T$ is a disjoint union of orbits.
Not fix any finite $T$. If $T>0$ then each orbit $C$ constituting $X_T$ is homeomorphic to a circle. Moreover, put $\widetilde{X}_T=\{x\in X: F(x,T)=x\}$. By the continuity of $F$, $\widetilde X_T$ is closed. But $\widetilde{X}_T=X_0\cup\bigcup_{n\in\mathbb N} X_{T/n}$.
Answer: Not an answer, but some hopefully useful remarks, supported by hand-waving arguments.
We would like to show that when $p_F < \infty$ in a zone, it is continuous.
Suppose $p_F$ is discontinuous. Then $\exists x, p_F(x)=T$, and $\exists (x_n), x_n \to x$ and $p_F(x_n) \not \to T$. We also suppose $\forall n, p_F(x_n) < \infty$.
Call $O(x)$ the orbit of $x$. It has period $T$.
Suppose $F(x_n,t)$ converges to $F(x,t)$ uniformly on $t$.
(Building a counterexample in $\mathbb R^2$ looks difficult, because the $O(x_n)$ cannot cross each other, so it rules out the usual counterexample to "pointwise convergence implies uniform convergence").
Then as $n \to \infty$, it should be possible to prove that $p_F(x_n)$ modulo $T$ $\to 0$, due to continuity of $F$.
As $O(x)$ is continuous and cannot cross itself, it is a Jordan curve, a closed loop.
Due to uniform convergence of $O(x_n)$ to $O(x)$, and the fact that $p_F(x_n)[T]\to 0$, we should be able to prove that $\exists n, O(x_n)$ makes at least $2$ loops around $O(x)$ (if it is exterior to $O(x)$), or around some point inside $O(x)$ (if it is interior to $O(x)$).
But in $\mathbb R^2$ it is impossible for a continuous curve to make $2$ or more loops around something without self-intersecting.
Note that this continuity of $p_F$ would hold in $\mathbb R^2$, but not in $\mathbb R^d$ for $d>2$: in $\mathbb R^3$ it is possible for $O(x_n)$ to follow $O(x)$ closely and make $p \ge 2$ loops while not self-intersecting.


Weird property of the functions $f(x)=x^e, g(x)=x^\pi$ and $h(x)=x^\sqrt{2}$

Question: I was messing around on desmos and all of these functions seem to be only defined for $x=0$ and $x>0$. Is this an error on desmos' part or are they really only defined for $x=0$ and $x>0$ and if so, why? Does it have something to do with the exponents being irrational and what about the exponents being irrational makes these functions undefined for negative values?
Comment: Desmos is likely ignoring the case for $x<0$ because [these functions are complex-valued](https://www.wolframalpha.com/input?i=Plot%5B%7BRe%5Bx%5EPi%5D%2CIm%5Bx%5EPi%5D%7D%2C%7Bx%2C-1%2C1%7D%5D) in this domain.
Comment: @finnbratfisch You can use the fact that $e^{i\pi} = -1$ as a starting point.
Comment: @AaronHendrickson And moreover multivalued , so we would have to choose a specific branch. Therefore, it makes sense to declare $a^b$ undefined for $a<0$ and irrational $b$.
Comment: Do you happen to know why they are imaginary in this domain?
Comment: @finnbratfisch Well, with a little hand waving we could write $x^\pi=(\sqrt x)^{2\pi}$.  What do we know about the square roots of negative real numbers?
Comment: Yes that makes sense, but could you tell me why $x^\pi=(\sqrt{x})^{2\pi}$?
Comment: @Peter It is multivalued but I thought this was TMI and would confuse the OP.
Comment: @finnbratfisch This is a rule of exponents (although I am ignoring some technicalities such as multivaluedness). Simply write $x^\pi=x^{2\pi/2}=(x^{1/2})^{2\pi}=(\sqrt x)^{2\pi}$.
Comment: @AaronHendrickson This exponention rule is not correct if $x$ is not a nonnegative real number. This incorrectness is used in many fake-proofs, so it is no good idea to write $x^{\pi}$ this way , if $x$ is negative.
Comment: @Peter Yes Peter. I know. But the OP does not have sufficient background for the correct explanation you gave. What I wrote gives a heuristic approach to understanding why it's complex valued at an appropriate level for the OP.
Answer: Recall that $x^y = e^{y \ln x}$.  This raises the question of how to take the logarithm of a negative number.  It can be done by using Euler's formula $e^{i\theta}=\cos \theta + i \sin \theta$.  So, if you can express a complex number in polar form as $x = r(\cos \theta + i \sin \theta) = re^{i\theta}$, then $\ln x = \ln r + i\theta$.
If $x$ is a negative real number, then we must have $\cos \theta = -1$ and $\sin \theta = 0$, which means that $\theta$ must be an odd multiple of $\pi$, i.e., $\theta = (2n + 1)\pi$ for some integer $n$.  So $\ln x = \ln r + i(2n + 1)\pi$.
So, for the case of $f(x) = x^e$ (with $x$ negative), that works out to $f(x) = e^{e(\ln r + i(2n + 1)\pi)} = e^{e \ln r}e^{ie(2n + 1)\pi} = r^e(\cos (e(2n + 1)\pi) + i \sin (e(2n + 1)\pi))$.  This is a real number only if $e(2n + 1)$ is an integer.  But because $e$ is an irrational number, that never happens.  Therefore, the function must be complex-valued.
Comment: I wish I could understand this because it is most likely right but I don't.


d3 path is being drawn twice while attempting path tween

Question: I am using this technique to tween a path in d3:
https://bl.ocks.org/mbostock/5649592
I am animating arcs between nodes. My data looks like this:
this.transfers = [[1, 480, 0, 5], [2, 0, 480, 20], [3, 0, 720, 5], [3, 240, 720, 5], [3, 480, 720, 5], [5, 480, 0, 5]];

The goal of the code is to visualize gameplay. The first element of each inner array above is the round of the game, the next two are the x coordinates of nodes that transferred some points -- the first node arching to the second -- and the fourth is the number of points that were transferred. I am trying to program an arc to tween between the nodes that took part in the transfer, with the arc sweeping from one node to the other. This is the code for the tweened arc:
this.linkAnimation = this.svg.append('g')
  .selectAll('path')
  .data (self.transfers)
  .enter()
  .append('path')
  .attr('fill', 'none');

this.timedAnimation();

timedAnimation( ) {
  for (let j = 0; j < this.rounds+1; j++ ) {

    this.linkAnimation = this.linkAnimation
      .transition()              // transition for delay between rounds
      .delay(2000)
      .attr('d', (t, i) => {
        if (j == t[0]) {
          let denominator = (t[1] < t[2])? 1.75 : 2; // to keep forward and reverse arcs from tracing the same path
          return ['M', t[1], self.height, 'A',
            (t[1] - t[2])/2, ',',
            (t[1] - t[2])/denominator, 0, 0, ',',
            t[1] < t[2] ? 1 : 0, t[2], ',', self.height]
            .join(' ');
        }
      })
    .attr('stroke-width', d => this.linkWidth(d[3]))
    .call(this.transition);
  }
}

transition(path) {
  path.transition()
    .duration(2000)
    .attrTween("stroke-dasharray", self.tweenDash);
}

tweenDash(path) {
  let l = this.getTotalLength(),
    i = d3.interpolateString("0," + l, l + "," + l);
  if (l == 0) { return; } else {
    return function(t) { return i(t); };
}

The issue is that each arc is drawing twice consecutively. It is fully drawn (not tweened) once right before the tweened arc appears.
Answer: At the start of the animation you have to initialize the stroke-dasharray.
Choose a really big size for the initial dash, bigger then any of the path lengths you are going to draw.
.attr('stroke-width', d => this.linkWidth(d[3]))
.attr('stroke-dasharray', "0,1000000")
.call(this.transition);

Comment: Can you explain what was happening? Before adding the code you suggested, the code was drawing one arc (not tweened) and then drawing the same arc tweened directly after that.
Comment: look for the docs of `stroke-dasharray` and slow the animation down (long duration) and see what happens with and without this line.


Preencher um listbox com predicate

Question: Estou estudando DDD e WebAPI e à medida que vou encontrando dificuldades, vou pesquisando e tentando resolver. Claro, que à s vezes me deparo com coisas simples para alguns aqui e não consigo resolver de imediato.
Às vezes até entendo o que tem que ser feito, mas não sei como fazer, como é o caso agora. Com projeto Console, eu fiz, mas troquei para um Windows Form e estou tendo essa dificuldade.
Preciso preencher um ListBox, como resultado de um Foreach lambda resultante de uma lista de um Predicate. A questão está no ForEach, assim:
private void button1_Click(object sender, EventArgs e)
{
    string[] teste = new string[] { "um", "dois", "tres", "quatro", "cinco" };
    Predicate<string> p = objetoTeste => objetoTeste.Length >= 4;

    var i = from items in teste
            where (p(items))
            select (items);

    i.ToList().ForEach(listBox1.Items.Add()**==>> Dúvida aqui**);

    /*foreach (var item in teste)
    {
        listBox1.Items.Add(item);
    }*/
}

A questão é como chamar o ListBox1.Items.Add() e preenchê-lo dentro do foreach
Answer: Assim
i.ToList().ForEach(item => listBox1.Items.Add(item));

Se o parâmetro do método Add for do mesmo tipo de item (string, neste caso) ainda dá pra fazer mais simples
i.ToList().ForEach(listBox1.Items.Add);

Veja funcionando .NET Fiddle.

Preencher um listbox com predicate


use install4j show ClassNotFoundException error

Question: i use install4j create a install Application,i install the Application in my computer,
but when i open the Application ,it show error:
java.lang.ClassNotFoundException: BOOT-INF.classes.com.lwpoct.lwproject.Application
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at com.exe4j.runtime.LauncherEngine.launch(LauncherEngine.java:80)
    at com.exe4j.runtime.WinLauncher.main(WinLauncher.java:94)
    at com.install4j.runtime.launcher.WinLauncher.main(WinLauncher.java:25)

how can i solve it,thanks
Answer: The main class of your launcher has to be configured as com.lwpoct.lwproject.Application and not as BOOT-INF.classes.com.lwpoct.lwproject.Application.


Como evitar o erro "zend_mm_heap corrupted"?

Question: No meu dia a dia de desenvolvimento PHP e entrega de releases, volta e meia recebo o seguinte erro quando um build é feito em nosso ambiente de integração contínua:
zend_mm_heap corrupted

Trata-se de um erro fatal, que trava o script de deploy e tenho que mandar construir o build novamente.
Do que se trata esse erro, e como posso evitá-lo?
Obrigado!
Comment: Na verdade no título o erro está correto, mas no corpo estava errado (escrevi "zend_mm_head"). Agora deve ficar um pouco mais fácil de tentar descobrir a causa :)
Answer: Não entendo muito sobre o assunto, mas dando uma pesquisada pelo SOEN, resolvi trazer uma tradução, para ver se posso ajudar alguém.
Possíveis soluções:
Aumentar o output buffering
De acordo com a resposta do próprio autor da pergunta no SOEN, ele configurou o php.ini, aumentando o tamanho do output_buffering. Ao ser questionado sobre "o que o output buffer tem a ver com isso", ele justificou-se usando essa resposta;
Configurar USE_ZEND_ALLOC:
De acordo com uma das respostas da questão em inglês acima, o problema foi resolvido utilizando o comando no bash:
export USE_ZEND_ALLOC=0

Uma sugestão de definir essa variável no arquivo /etc/apache2/envvars foi dada em um comentário da resposta no SOEN
Desabilitar o opcache:
Segundo uma das respostas, ao desabilitar o opcache, o problema foi resolvido:
 opcache.enable_cli=0


Changing representation in deep neural network

Question: Say I have a neural net that outputs a vector of length 4 such as:
[0, 1, 2, 3]

Now say that the only way to calculate the loss is to convert this output to a one-hot vector matrix and pass that into the loss function:
[[1, 0, 0, 0],
 [0, 1, 0, 0],
 [0, 0, 1, 0],
 [0, 0, 0, 1]]

This is a hypothetical question (obviously the answer to this question wouldn't be to the aforementioned scenario, but to another more realistic, relevant one).

So, once we have calculated the loss using the one-hot vector matrix, is it still possible to back propogate and train the network even though there were two different representations used. A more general question would be, if I convert representations from the output of the neural net to the loss function ( output of neural net => some representation conversion => loss function), is it still possible to back propogate and optimize?
Comment: how does the neural network output integers as in the first one?
Comment: It was more of a hypothetical scenario. In reality, that wouldn't happen, but it's just an example of representation conversion.
Answer: It depends on how you do this.

If you're using PyTorch and you do all of your operation using torch.Tensor objects, then the answer is "yes, you can backprop this loss correctly because that's the whole point of using torch.Tensor objects."  So, this code will work:
loss = torch.eye(x.size).dot(x).sum() where x is your 4-vector. Just replace sum with whatever differentiable function(s) you need. (Rounding or other non-differentiable operations are not suitable.)

If you dump your torch.Tensor objects to numpy, this is not possible because a numpy.array object does not record gradients, nor does it have a backward method.


AutoEncoder feature layers is unstable

Question: I am replicating a linear autoencoder method based on this example here; https://towardsdatascience.com/build-the-right-autoencoder-tune-and-optimize-using-pca-principles-part-ii-24b9cca69bd6
Basically, it is using a one layer linear autoencoder to compare with PCA. X is randomly generated from a normal distribution with dimension 5. The core part of the code looks like this.
encoder = Dense(encoding_dim, activation="linear", input_shape=(input_dim,), use_bias = True)
decoder = Dense(input_dim, activation="linear", use_bias = True)

autoencoder = Sequential()
autoencoder.add(encoder)
autoencoder.add(decoder)

autoencoder.compile(metrics=['accuracy'],
                    loss='mean_squared_error',
                    optimizer='sgd')
autoencoder.summary()

autoencoder.fit(X_train_scaled, X_train_scaled,
                epochs=nb_epoch,
                batch_size=batch_size,
                shuffle=True,
                verbose=0)

The feature layer is
w_encoder = autoencoder.layers[0].get_weights()[1]
w_decoder = autoencoder.layers[1].get_weights()[1]

Every time I fit the model, the output for w_encoder is significantly different
Encoder_weights
[[ 0.5596451  -0.7303996 ]
 [-0.08105161  0.43715334]
 [ 0.7571198   0.4995086 ]
 [-0.68543106  0.0496945 ]
 [-0.46657953  0.1231109 ]]
Decoder_weights
[[ 0.5596451  -0.7303996 ]
 [-0.08105161  0.43715334]
 [ 0.7571198   0.4995086 ]
 [-0.68543106  0.0496945 ]
 [-0.46657953  0.1231109 ]]

vs
Encoder_weights
[[ 0.49870995 -0.594432  ]
 [-0.03552848  0.3591121 ]
 [ 0.6754906   0.42547104]
 [-0.5236658   0.02657888]
 [-0.36780515  0.07721919]]
Decoder_weights
[[ 0.49870995 -0.594432  ]
 [-0.03552848  0.3591121 ]
 [ 0.6754906   0.42547104]
 [-0.5236658   0.02657888]
 [-0.36780515  0.07721919]]

Is there any way to make the layer metrics stable between runs?
Answer: This can happen for many reasons.

The weight of your network is initialized randomly each time, so it's possible to get different results each time you run.

Your data loader is random in nature and randomly pulling samples.

If you want reproducibility, try the following,
Use seeds.
SEED = 1997
os.environ['PYTHONHASHSEED']=str(SEED)
random.seed(SEED)
np.random.seed(SEED)
tf.random.set_seed(SEED)

In the case of running on an Nvidia GPU, you should also use tensorflow-determinism
pip install tensorflow-determinism

and you use it like this:
import tensorflow as tf
import os
os.environ['TF_DETERMINISTIC_OPS'] = '1'

For Tensorflow < 2.1, add above and this:
from tfdeterminism import patch
patch()

Comment: I've already tried using the SEED, and I also add a kernel initializer in each layer. But the output is still different

AutoEncoder feature layers is unstable


How can I have a view to load more rows on clicking a "Load more" button?

Question: We have created a view, myview, where we want to display 3 nodes (content type = basic) and add a View All button on page load. The purpose of the 'View All' button will be to show 6 more (the view is supposed to show max 9).
How can we display 3 nodes with a View All button?
What we tried, but the view did not display the view all button nor did it allow me to limit to total of 9. I also could not find an appropriate view hook to do what i am looking for.
View settings:

Change pager plugin to full
change pager plugin to mini
Comment: Seems the [Views Infinite Scroll](https://www.drupal.org/project/views_infinite_scroll) module can provide exactly what you want. See the tutorial: https://www.reinisfischer.com/views-infinite-scroll-load-more-ajax-drupal-8
Answer: Looks like Views Infinite Scroll  is a good option for you:

Views infinite scroll allows you to load and display pages of any view inline, using AJAX (this has been called infinite scrolling, load more, autopaging, endless pages and more). The pager can be triggered with the press of a button or automatically as the user scrolls to the bottom of the view's content.

Here's the pager settings:
Answer: There are more ways of solving it depending on your circumstances.
The obvious way is through 2 views displays with different paths, or as parent-child path3 for the first one and path3/path9 for the second one (you can set them as Drupal tabs that way, so Drupal tab can play the role of your button "Show 6 more"). Set one to only show 3 items, the other one to show 9. Add a text area in the Views Footer of your first display and add the anchor HTML that leads to the page link of your second views display.
If you know a bit of Ajax you could display one of the displays as an attachment that has pager offset set to 3, and use Ajax button to make it display.

You can allow users to choose how many items are displayed by Exposing the Full or Mini pager with the option Allow user to control the number of items displayed in this view and enter 3, 9 while setting Items per page to 3.
This way you will see 3 items to start with, but there will be a dropdown above your results where users can choose either 3 or 9. If they choose 9 the page will reload to show 9 items in the results.
Using the Pager this way also gives you parameters on your links so you can even build links/button elsewhere on your site to link to a page with a particular number of results path3?items_per_page=9.
The downside for you may be that there are also pager links at the bottom of the results (Previous, Next) that you might not want displayed. Maybe you can hide them with CSS.
You should also research into the Pager related modules, maybe Views flexible pager and Pagerer can help.


Is this a good question? - How to have a single city, that exports future tech, without breaking the world economy

Question: I'm trying to figure out how Academy City, which is a city with that demonstrates technology that is 20-30 years in the future, and that technology keeps increasing with time... (or is kept at that distance while behind the scenes tech keeps moving forward... and new tech is rolled out whenever it seems people Outside the City are catching up...)
I'm trying to figure out how to price the city's goods so tech companies can exist and keep the world from being dependent on Academy City's tech...:
Perhaps it's like Mass Effect, and Academy City just sells what is high-end Outside tech but just a bit better... Like that Asari group on Illium...

So my question would have been like:

If a location can make better products that are better by percentage 'p', at speed 's' times the normal rate of a city, with exportation speed at worst a week (supersonic jets), and can make a y% better version of their product in time 't', where 't' is 3 months (Look at Armored Suit development speed of new versions...)... etc.
Answer: I think we have accepted economies that are not existent, as long - and that is my guess - they're somewhat similar to real economies, such that answering these questions gives insights that have some sort of external validity.
See also

Would a question about an abnormality in a simulated economy be acceptable here?


UIGestureRecognizer blocking table view scrolling

Question: I'm using a custom UIGestureRecognizer subclass to track gestures on my InfoView class. The InfoView class is a subview of a custom UITableViewCell subclass called InfoCell.
I've added my gesture recognizer to my root view (the parent view of everything else on screen, because the purpose of my custom gesture recognizer is to allow dragging of InfoCell  views between tables). Now, everything works as it should except one thing. I'm using the following code in my UIGestureRecognizer subclass to detect touches on the InfoView view:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UIView *touchView = [[touches anyObject] view];
    if ([touchView isKindOfClass:[InfoView class]]) {
        // Do stuff
    }

The problem here is that the touches on the InfoView object are being intercepted, therefore they are not being forwarded to the UITableView which contains the InfoCell, which is the parent view of the InfoView. This means that I can no longer scroll the table view by dragging on the InfoView view, which is an issue because the InfoView covers the entire InfoCell.
Is there any way I can forward the touches onto the table view so that it can scroll? I've tried a bunch of things already:
[super touchesBegan:touches withEvent:event];
[touchView.superview.superview touchesBegan:touches withEvent:event]; (touchView.superview.superview gets a reference to its parent UITableView)
But nothing has worked so far. Also, the cancelsTouchesInView propery of my UIGestureRecognizer is set to NO, so thats not interfering with the touches.
Help is appreciated. Thanks!
Answer: Check out the UIGestureRecognizerDelegate method: - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
If this returns YES it will prevent your gesture recognizer from stomping on the one that UIScrollView is using to detect scrolling.
Comment: I have been beating my head on the wall on this one. Thanks ! :D
Answer: UIGestureRecognizer has a property "cancelsTouchesInView" which is set to YES by default. This means that touches in a UIView are cancelled when a gesture is recognized. Try to set it to NO to allow the UIScrollView to receive further touch events.
Answer: I had a line in my touchesBegan method that set the state property of the gesture recognizer to UIGestureRecognizerStateBegan. Removing this line seems to fix the problem.
Answer: You can try add this  notification
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if ([gestureRecognizer class] == [UIPanGestureRecognizer class]) {
        UIPanGestureRecognizer *panGestureRec = (UIPanGestureRecognizer *)gestureRecognizer;
        CGPoint point = [panGestureRec velocityInView:self];
        if (fabsf(point.x) > fabsf(point.y) ) {
            return YES;
        }
    }
    return NO;
}

Comment: this is the right answer, prevent the panGesture to start if gesture is vertical.


Quantitative evaluations for image classification

Question: Hello I am working on the classification of different weed categories. I want to know what quantitative evaluation I can do other than find the accuracy?
Answer: There are a number of popular evaluation metrics for classification other than accuracy measures such as recall, precision, AUC or F-scores.
Instead of listing them all here, I think it is best to point you towards some interesting resources that can kick-start your search for answers.
This article gives a rather nice overview:
Evaluation Metrics for Classification - Medium.com post by Niklas Donges
A source that is a little harder to follow, but gives a more comprehensive overview of possible metrics can be found in the scikit-learn model evaluation documentation
Even if you are not planning on using scikit, the metrics remain relevant. It also lists differences between binary classification and multi-class classification setting very thoroughly.
Hope this helps!


Creating a trigger in mysql to save changes made in one table into another

Question: I'm new to using triggers but having read quite a bit on it I think its the best solution to what I need. I have a table in mysql called employees and I want to create an audit trail of changes made to employees into another table called employee_changes. But I only want to create the audit entries for only the columns that have changed in the employees table. So for instance if the user changes the employee's salary, I want a row to be created in employee_changes capturing the ID of the employee, the name of the column that was changed (in this case salary), the old value and new value of the salary as well as the date and name of the user. The name of the user that made the change will always be updated in a field (LastUpdatedBy) in the employees table when the record is saved on the front end, so by the time the trigger is firing, it can get the user name from the LastUpdatedBy column.
With the help of This Post and This Post I was able to come up with this code:
DELIMITER //
CREATE TRIGGER emp_update
AFTER INSERT
ON employees FOR EACH ROW
BEGIN
DECLARE col_names CURSOR FOR
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'employees'
ORDER BY ordinal_position;
select FOUND_ROWS() into num_rows;
SET i = 1;
the_loop: LOOP
IF i > num_rows THEN
    CLOSE col_names;
    LEAVE the_loop;
END IF;

FETCH col_names
INTO col_name;

 IF OLD.col_name <> NEW.col_name THEN
    INSERT INTO employee_changes (EmployeeNumber, FieldName, OldValue, NewValue, ChangeDate, ChangedBy)
    VALUES(OLD.EmployeeNumber, col_name, OLD.col_name, NEW.col_name, NOW(), NEW.LastUpdatedBy);
 END IF;

SET i = i + 1;
END LOOP the_loop;

END //
DELIMITER ;

But when I run it, nothing happens, no trigger is created in INFORMATION_SCHEMA.TRIGGERS. And so when I update the employees table, nothing happens in my employee_changes table.
I feel like I'm almost there but I'm stuck.
Thanks for your help.
Comment: Please execute your code somewhere where you can read the error messages (e.g. from workbench or mysql client). You have some errors in your code (variable declaration, use of `old` in an `insert` trigger).
Answer: The following line definitely throws an error:
IF OLD.col_name <> NEW.col_name THEN

because col_name is not the name of a field, it is a variable. This will never work in MySQL, you have to provide the exact column names. Forget the dynamic query of the column names, you have to hard code the test for each column.
Similarly, in the insert statement you cannot use the OLD.col_name or NEW.col_name formula, you have to explicitly provide the field names one by one. If you change the structure of the table, then you have to change the code of the trigger.
Unfortunately, this is a limitation of MySQL, currently I'm not aware of any solution or workaround for this issue.
Comment: Thanks Shadow, but I have dozens of tables each with quite a number of fields. Is there another way I could perhaps achieved the same result?
Comment: Unfortunately, this is a limitation of MySQL, currently I'm not aware of any solution or workaround for this issue in mysql. You could try to implement the logging on application level (you know what data is changed in the application) or you may attempt to turn on MySQL binary log and then process the binlog using mysqlbinlog application and gather all changes from it on a regular basis.


Sample size selection (sample to generally represent population traits)

Question: Let's say I have 100,000 images total. I have around 15 categories for the images. I do not know how the 100,000 are distributed across these categories.
I'd like to select N images at random, then manually classify them and arrive at an approximate of how my 100k images are grouped into the 15 categories. Eg, cat1: 5%, cat2:3%, cat3:10%, ..... cat15:8%
What's the best rule for calculating N, so that my sample's distribution over the 15 categories, represents the population reasonably well?
Answer: Arrived at a reasonable guess for N through simulation: N of around 400 gives strong directional results of the population distribution.
<code>import random
from collections import Counter

items = ['dog', 'cat', 'bird', 'plane', 'circus', 'turtle', 'oven', 'food', 'running', 'hello']
weights=[10, 20, 35, 5, 18, 3, 19, 4, 5, 12]

pop_counter = Counter(random.choices(items,  weights=weights, k=100000)).most_common(10) # Our population

# Get the populatino into a list
population = []

for item, count in pop_counter:
    population.extend([item] * count)

assert(len(population) == 100000)

# Print out the %'s
for item, count in pop_counter:
    print(item, count/100000)

bird 0.26634
cat 0.15414
oven 0.14347
circus 0.13777
hello 0.09207
dog 0.07775
plane 0.03826
running 0.03777
food 0.03081
turtle 0.02162

for item, count in Counter(random.sample(population=population, k=400)).most_common():
    print(item, count/400)

bird 0.2425
circus 0.165
cat 0.155
oven 0.1475
hello 0.105
dog 0.0875
running 0.035
food 0.0325
plane 0.0175
turtle 0.0125
</code>


Python Selenium check if new element becomes available

Question: I am trying to make a bot that checks when there are new houses on the website so that i can use selenium's click events.
How can i keep track of this list and check when there are new houses added to the website? I have created a list filled with  elements of the available houses, but don't know how to go further on from here..
Thanks for the help!
from selenium.webdriver.chrome.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait

def create_driver():
    options = Options()
    options.add_experimental_option("detach", True)
    service = Service(executable_path="/usr/local/bin/chromedriver")
    driver = webdriver.Chrome(service=service, chrome_options=options)

    return driver

def login(driver):
    driver.find_element(By.NAME, 'txtEmail').send_keys('email@example.com')
    driver.find_element(By.NAME, 'txtWachtwoord').send_keys('XXXXXXX')
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="CybotCookiebotDialogBodyButtonAccept"]'))).click()
    #driver.find_element(By.ID, 'CybotCookiebotDialogBodyButtonAccept').click()
    driver.find_element(By.CLASS_NAME, 'btn-secondary').click()

def search_page(driver):
    driver.find_element(By.XPATH,"//a[@href='/zoekopdracht/']").click()

def list_of_woningen(driver):
    woningen = []
    woningLijst = driver.find_elements(By.CLASS_NAME,"stretched-link")

    for x in woningLijst:
        woningen.append(x.text)

    return woningen

def start_session(driver,url):
    driver.get(url)
    login(driver)
    search_page(driver)
    list_of_woningen(driver)

    #return driver.page_source
if __name__ == '__main__':
    start_session(create_driver(),'https://hurenbij.vesteda.com/')

Comment: do you have a local list of houses? or is that every time you open the website, the program collects the current houses and the data will be gone when the program is closed?
Comment: No , not a local list.. It is a list created of the current houses. Data will be gone when program closes.. @Hannonqaoud
Comment: run loop which every few seconds loads page again, scrapes all data again and compares data with your list.
Answer: i dont know if a there's an event lister that you can deploy or anything similar, but you can do it the manual way, you can re check if anychanges has occurred every 30 seconds or so.
def check_for_changes(driver, old_list):
    print("Checking for changes")
    new_list = list_of_woningen(driver)
    if old_list == new_list:
        print("No changes found")
        return False
    else:
        print("Changes found")
        print("Old list: ", old_list)
        print("New list: ", new_list)
        return True

def start_session(driver, url):
    driver.get(url)
    login(driver)
    search_page(driver)
    old_list = list_of_woningen(driver)
    while not check_for_changes(driver,old_list):
        sleep(30) # 30 seconds
        # a better approach for this, is to make a wait thread, if there are other functionalities for tha program
        driver.refresh()
    else:
        print("ALERT!!!")

once again there might be a better solution with a built in selenium event listener, but this is a valid solution.


Missing assembly reference in Razor view

Question: I have a MVC application which works fine when returning JSON for my API controllers. I've added a controller which should return a razor view, however I'm getting the following error when trying to load the page:

One or more compilation references are missing. Possible causes
include a missing 'preserveCompilationContext' property under
'buildOptions' in the application's project.json.
The type or namespace name 'DevTestViewModel' does not exist in the namespace 'MyApp.Api.Models' (are you missing an assembly
reference?)

I've simplified my view to:
@model List<MyApp.Api.Models.DevTestViewModel>

Hello World

My model class is:
namespace MyApp.Api.Models {
    public class DevTestViewModel {

        public int Id { get; set; }

        public string Name { get; set; }

    }
}

I've tried adding a _ViewImports.cshtml:
@using MyApp.Api

I've also followed the suggestion in the error and set preserveCompilationContext in my project.json but it's made no difference:
"buildOptions": {
  "emitEntryPoint": true,
  "preserveCompilationContext": true
},

It works fine when debugging locally. It's only once I publish to Azure that I'm have the problem. Not sure what I'm missing.
Comment: `project.json` file no longer exists in .Net Core Visual Studio 2017. The problem might have been solved in new version.
Comment: @Win unfortunately upgrading to VS 2017 isn't currently an option. I doubt my problem is an issue with the framework though as I can't get any views with models to work. I'm pretty sure I must just be missing something simple, just not sure where to look.
Comment: I've managed to update to VS 2017 and still have the same issue.
Answer: It looks like there was an issue with the deployment to Azure. Re-creating the Web App in Azure and then redeploying fixed the issue.
Answer: nuget install Microsoft.AspNetCore version 1.1.1