Convert.ChangeType converte data de forma errada

Question: O método Convert.ChangeType está convertendo a data de forma errada eu espero 24/02/2015 e vem 23/02/2015. Alguém sabe o motivo?
Exemplo do código:
using System;
using System.Globalization;

namespace ConsoleApplication4
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string data = @"2015-02-24T01:00:01-01:00";

            Console.WriteLine(DateTime.ParseExact(data, "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture));//CONVERTE ERRADO
            Console.WriteLine(DateTime.Parse(data));//CONVERTE ERRADO

            Console.WriteLine((DateTime?)Convert.ChangeType(data, Nullable.GetUnderlyingType(typeof(DateTime?))));//CONVERT ERRADO
            Console.WriteLine((DateTime)Convert.ChangeType(data, typeof(DateTime)));//CONVERT ERRADO

            Console.ReadLine();

        }
    }
}

Comment: Você espera *24/02/2015* e está retornando *24/02/2015*, não é o certo?
Comment: Corrigido. Desculpe estou no trabalho fiz isso correndo.
Comment: Pra mim está certo: https://dotnetfiddle.net/3Fd28k
Comment: @bigown, editei a pergunta para mostrar o resultado do meu console. Tem alguma idéia?
Comment: Por enquanto não, mudei para testar outras culturas mas continua ok. É provável que tenha alguma coisa com seu ambiente. Eu duvido que uma diferença de versão do .Net esteja produzindo resultados diferentes. https://dotnetfiddle.net/8bfSTH
Comment: Eu achei esse formato em XML de NFe. Infelizmente não acho mais exemplos de data nesse formato. Existe um formato padrão para data em XML?
Comment: Que eu saiba não, em tese cada um pode criar o formato que quiser. Tem um formato para a definição do XML. Mas o problema não é de formato, ele parece estar ok, tanto que eu mostrei que funciona. Precisaria descobri porque o seu .Net não está fazendo o mesmo.
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/21989/discussion-between-reiksiel-and-bigown).
Answer: Achei!!!
Seguinte a data vem com essa parte: -01:00 que quer dizer a timezone. Quando convertemos uma data ele adapta para a timezone do PC.
O programa converteu para o valor: 24/02/2015 01:00:01 na timezone -1, no meu caso, estou em SP e a timezone é -3 ele subtrai 2h e fica com o valor 23/02/2015 23:00:01.
Comment: Dê aceite na reposta para a pergunta não ficar em aberto :-)
Comment: Claro. Eu tinha te falado que era por causa do seu ambiente. Tem a ver com isto: http://pt.stackoverflow.com/a/46489/101


Is it always true that $H^0(X)\cong\ \widetilde{H}^0(X)\oplus\mathbb{Z}?$

Question: It does follow from $\widetilde{H}^0(X)\cong Hom(\widetilde{H}_0(X),\mathbb{Z})$ and the fact that it's true for homologies and $Hom(\mathbb{Z}^n,\mathbb{Z})=\mathbb{Z}^n,$ right?
I am just confused that this property is always noted for homologies, but I've never seen it written out for cohomologies.
Answer: Let $\epsilon:X\rightarrow\ast$ be the collapse map onto the 1-point space. Then
$$\widetilde H^n(X)=coker(H^n(\ast)\xrightarrow{\epsilon^*} H^n(X)).$$
If $X$ is nonempty, then it has a point $x$, and this defines a map $x:\ast\rightarrow X$ satisfying $\epsilon \circ x=id_\ast$. It follows from functorality that $\epsilon^*$ is split injective in this case, and in particular
$$H^n(X)\cong \widetilde H^n(X)\oplus H^n(\ast)\qquad \forall n\in\mathbb{Z}.$$
If $X$ is empty, then people often define its reduced homology to be $\mathbb{Z}$, so the answer to your question is affirmitive even in this case, but I mean what are you even doing with your life at this stage?
Comment: @Haldot the argument I gave clearly works for all $n$, and any generalised cohomology theory. If you are using ordinary homology, then $H^n(\ast)=0$ if $n\neq 0$ and $H^n(X)=0$ for $n<0$, so there isn't much happening if $n\neq 0$. The argument you gave for $\widetilde H^*(\emptyset)$ is correct, and what I was referring to.
Comment: You mean for $n=0,$ right?
Btw, about empty set. Doesn't it follow from the augmented chain complex that $\widetilde{H}_{-1}(\emptyset)=\mathbb{Z}$ and $\widetilde{H}_{k}(\emptyset)=0$ for $k>0?$ And same from cohomologies.


Win football game by running backwards?

Question: If a football team is one point behind with less than two minutes remaining, wouldn't the logical move be to run the ball back into their own end zone to score a 2-point safety? Even if you are in field goal range, the field goal is uncertain, but the 2-point safety is a sure thing and difference between 2 points and 3 points is meaningless in a one-point game.
Has any team won by doing this? If so, how far did they run backwards?
Comment: Are you suggesting that the team A, who is one point behind, run backwards to score a safety (which is 2 points for *team B*) and punt the ball back to team B after the safety with under 2 minutes remaining (in which team A is now behind by 3 points)? I may be ignorant to what you're suggesting, so I'm asking for clarification.
Comment: Okay, maybe I misunderstood, the 2 points is scored by the team without the ball? In that case the strategy would not work.
Comment: Correct. I posted this as an answer below.
Answer: Your suggestion would be foolish.
Rule 11, Section 5, Article 1 in the 2016 NFL Rulebook defines a safety as:

if the offense commits a foul in its own end zone or;
when an impetus by a team sends the ball behind its own goal line, and the ball is dead in the end zone in its possession or the ball is out of bounds behind the goal line.

To take your example, let's say Team A does what you suggest. They run backwards for a safety, fulfilling the requirement of "when an impetus by a team sends the ball behind its own goal line, and the ball is dead in the end zone in its possession." This gives Team B 2 points.
Rule 11, Section 5, Article 2 defines what takes place after a safety:

After a safety, the team scored upon (Team A in your example) must put the ball in play by a
  free kick (punt, dropkick, or placekick) from its 20-yard line. An
  artificial or manufactured tee cannot be used. See 6-1-1-b and 6-1-3.

Thus, Team A, now 3 points behind, is free kicking the ball to Team B. Team B gains possession the ball with under 2 minutes remaining. As they are up by 3, Team B can proceed to attempt to run the clock out and win the game.
Comment: @TylerDurden Gotcha. If a team is up by more than 2 points, an intentional safety isn't needed to run down the clock (and you'll be giving the ball to the defending team, giving them a chance to score). Running/kneeling the ball and/or getting a first down is almost always enough to run the clock out.
Comment: I see, I thought the 2 points went to the team with the ball, not the defending team, so it was a mistake on my part. I see that the main use of intentional safety would be to run down the clock when ahead by more than 2 points.

Win football game by running backwards?


Can I use IntelliJ to develop WSO2 ESB API?

Question: I am using the WSO2 Eclipse version to develop my WSO2 ESB project.
I am asking if exist something like of an IntelliJ plugin to develop my WSO2 ESB API into IntelliJ Idea IDE. I mean something that shows the graphical flows.
Is it possible or not?
Comment: Most of time i just use text editor with xml support to write all i need. And extensibly use IntellJ Idea to write xslt tranfrormations for WSOESB.
Comment: There is none at the moment.
Answer: At the moment there is no IdeaJ plugin that you can use. You need to use the WSO2 Developer studio which is based on eclipse
Answer: Yes you can ,I have used intellij for this but there is no plugin available for it.But you can use it without plugin as well.


Find third degree polynomial with real coefficients so that $P(1-i)=2+i$ and $P(i)=1-2i$

Question: Find third degree polynomial with real coefficients so that $P(1-i)=2+i$ and $P(i)=1-2i$
$P(x)=ax^3+bx^2+cx+d$
How to find $a,b,c,d\in\mathbb{R}$
Answer: Keep in mind that
\begin{align}
i^2 &= -1 \\
i^3 &= -i
\end{align}
And
\begin{align}
(1-i)^2 &= (1-i)\cdot(1-i)=1-2i+i^2=-2i \\
(1-i)^3 &= (1-i)\cdot(-2i)=-2i+2i^2=-2i-2
\end{align}
Then by substitution you will have four equations
$(1)\,\,d-b=1$
$(2)\,\,c-a=-2$
$(3)\,\,c+d-2a=2$
$(4)\,\,-2a-2b-c=1$
Use $(2)$ and $(3)$ together to get $d$ in terms of $a$. Then use other equations to get $b$ and $c$ in terms of $a$. Then solve for $a$ in any of the four equations. Then solve for $b$, $c$, and $d$ using the relations that you found.
Comment: Let me suggest to delete the two lines involving $\sqrt{-1}$, which add nothing to the solution but only use a disputable notation.
Answer: Write out $P(i)=1-2i$ in terms of $a,b,c,d$. Separate the real and the imaginary parts of that equation to get two equations (you can do this since you know that the coefficients are real). Do the same with $P(1-i)$. You should now have four linear equations that with some luck can be solved.
Comment: Who said about dividing? $P(i) = (d-b)+i(c-a)=1-2i$.
Comment: Dividing $P(x)$ with $i$ gives $-i(ax^3+bx^2+cx+d)$ but $P(i)=1-2i$. What happens with the real part?
Comment: @display_error I said nothing about division. I said to _separate_ the real and imaginary parts. For instance, if you had had the equation $x+yi=1+i$, and you wanted real solutions for $x$ and $y$, then it would be straight-forward to solve the equation because the real part ($x=1$) and the imaginary part ($yi =i$) are independent. In your case, the equations might _look_ a bit different, but the same trick works nicely.


CI/CD Github Workflow not finding build directory

Question: I am currently writing my first CI/CD workflow with Github Actions.
I try to build the application inside the runners workspace and then only copy the docker-compose file and the .dist/ directory with the build artifacts to my vps and start a docker container there.
The build steps are successful, but I struggle to copy the build directory (./dist/*) to my vps.
It tells me that the tar archive is empty...
here is my workflow
name: CI/CD Pipeline

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      # Checkout Repository to the runner's workspace.
      - name: Checkout repository
        uses: actions/checkout@v3
      # Set up Node.js on runner's workspace.
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 20.10.0

      # Install dependencies, build and test.
      - name: Install dependencies
        run: |
          npm ci

      - name: Build and test
        run: |
          npm run build

      - name: List Dist Contents
        run: ls -R ./dist

  deploy:
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Deploy to VPS
        uses: firstname.lastname@example.com
        with:
          HOST: ${{ secrets.HOST }}
          USERNAME: ${{ secrets.USERNAME }}
          PORT: ${{ secrets.PORT }}
          KEY: ${{ secrets.SSH_KEY }}
          source: |
            ./dist/*
            ./docker-compose.prod.yml
          target: "/usr/src/app"

      - name: Execute remote deployment script
        uses: appleboy/ssh-action@master
        with:
          HOST: ${{ secrets.HOST }}
          USERNAME: ${{ secrets.USERNAME }}
          PORT: ${{ secrets.PORT }}
          KEY: ${{ secrets.SSH_KEY }}
          script: |
            # Change directory to the app folder
            cd /usr/src/app

            # Stop and remove the container
            docker-compose down

            # Set environment variables stored in Github secrets
            echo "VITE_BASE_URL=${VITE_BASE_URL}" > .env
            echo "DATABASE_URL=${DATABASE_URL}" > .env
            echo "NODE_PORT=${NODE_PORT}" > .env
            echo "SECRET_KEY=${SECRET_KEY}" > .env
            echo "REFRESH_SECRET_KEY=${REFRESH_SECRET_KEY}" > .env

            # start container and detach
            docker-compose up -d

The workflow fails with this message
drone-scp version: v1.6.14
tar all files into /tmp/bgHcjxzAcm.tar.gz
tar: empty archive
exit status 1

I logged the dist content right after the build step and it looks totally fine everythink is created. Not sure what iam doing wrong here.
UPDATE:
tried using one job.
name: CI/CD Pipeline

on:
  push:
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    steps:
      # Checkout Repository to the runner's workspace.
      - name: Checkout repository
        uses: actions/checkout@v3
      # Set up Node.js on runner's workspace.
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 20.10.0

      # Install dependencies, build and test.
      - name: Install dependencies
        run: |
          npm ci

      - name: Build and test
        run: |
          npm run build

      - name: List Dist Contents
        run: ls -R ./dist

      - name: Deploy to VPS
        uses: firstname.lastname@example.com
        with:
          HOST: ${{ secrets.HOST }}
          USERNAME: ${{ secrets.USERNAME }}
          PORT: ${{ secrets.PORT }}
          KEY: ${{ secrets.SSH_KEY }}
          source: |
            ./dist/*
            ./docker-compose.prod.yml
          target: "/usr/src/app"

      - name: Execute remote deployment script
        uses: firstname.lastname@example.com
        with:
          HOST: ${{ secrets.HOST }}
          USERNAME: ${{ secrets.USERNAME }}
          PORT: ${{ secrets.PORT }}
          KEY: ${{ secrets.SSH_KEY }}
          script: |
            # Change directory to the app folder
            cd /usr/src/app

            # Stop and remove the container
            docker-compose down

            # Remove old .env file
            rm .env

            # Set environment variables stored in Github secrets
            echo "VITE_BASE_URL=${VITE_BASE_URL}" > .env
            echo "DATABASE_URL=${DATABASE_URL}" > .env
            echo "NODE_PORT=${NODE_PORT}" > .env
            echo "SECRET_KEY=${SECRET_KEY}" > .env
            echo "REFRESH_SECRET_KEY=${REFRESH_SECRET_KEY}" > .env

            # start container and detach
            docker-compose up -d

Comment: In the official [examples](https://github.com/appleboy/scp-action?tab=readme-ov-file#example), the `source` is a CSV e.g. `source: 'dist/*,docker-compose.prod.yml'`.
Comment: Yes thats it, thanks so much!!!
Comment: The jobs are run on different runner machines. You have to [share data between jobs](https://docs.github.com/en/actions/using-workflows/storing-workflow-data-as-artifacts#passing-data-between-jobs-in-a-workflow) to make them available e.g. via artifacts. In your particular example, you can first combine both jobs into one to see how that works. Once everything is fine, you can then decide if you need separate jobs or not.
Comment: unfortunately I get the same error, even if I only use one job.
Answer: Thanks to Azeem for the answer!
I had to use Comma-Separated Values (CSV) for the source...
here are the docs, should have red them. Sorry!


Problemas ao passar parametro URL

Question: No código abaixo, como faço para pegar os valores do input IdObra e IdCliente e passar pela url <a href="<?=base_url("/index.php/ProdutosObras")?>"? Estou utilizando um modal.

        <input type="hidden" type="text" class="form-control" id="idObra" name="idObra" value="idObra">

        <input type="hidden" type="text" class="form-control" id="clienteObra" name="clienteObra" value="clienteObra">

        Nome Obra
        <input type="text" class="form-control" id="nomeObra" autofocus name="nomeObra">

        Valor Obra
        <input type="text" class="form-control" id="valorObra" name="valorObra">

        Tipo Obra
        <input type="text" class="form-control" id="tipoObra" name="tipoObra">

        Status Obra
        <select class="form-control" name="statusObra" id="statusObra">
            <option value="Em andamento">Em andamento</option>
            <option value="Finalizada">Finalizada</option>
            <option value="Parada">Parada</option>
        </select>

    <?php

        echo "
";
        echo "Cliente";
        echo "<select  class='form-control' name='clienteObra' id='clienteObra'>";
        foreach ($clientes as $cliente):
        {
          echo "<option value='$cliente[id_cliente]'>$cliente[nomeCliente]</option>";
        }
        endforeach;
        echo "</select>";
        echo "
";
    ?>

    <a href="<?=base_url("/index.php/ProdutosObras")?>" class="button" target="_blank">Adicionar Produtos

Comment: Porque o tipo do campo 'IdObra' está hidden ?
Answer: Você pode adicionar um evento de click nesse botão e fazer uma função com javascript para concatenar os valores dos inputs com a url, por exemplo :
<button onclick="produtosObras()" id="btnUrl" href="<?=base_url("/index.php/ProdutosObras/")?>" class="button" target="_blank">Adicionar Produtos</button>

Comment: Obrigado pela ajuda.
Answer: No evento onclick são atribuídos às respectivas chaves dos parâmetros  os valores recuperados através da função do JavaScript document.getElementById que serve para retornar um elemento do DOM que é identificado por um ID específico.
<a href='' onclick="this.href='<?=base_url("/index.php/ProdutosObras")?>?p='+document.getElementById('idObra').value+'&q='+document.getElementById('clienteObra').value">update

Não sei se essa parte <?=base_url("/index.php/ProdutosObras")?> está correta, aliás, nunca tinha visto isso antes. Porém fiz um teste com o exemplo abaixo onde substituo <?=base_url("/index.php/ProdutosObras")?> por https://pt.stackoverflow.com e funciona bem:

<input type="hidden" type="text" class="form-control" id="idObra" name="idObra" value="Value_idObra">
<input type="hidden" type="text" class="form-control" id="clienteObra" name="clienteObra" value="Value_clienteObra">

update

Comment: Sua resposta está na fila de análise de publicações de baixa qualidade, provavelmente porque não tem nenhum texto e só um código. Vou clicar no botão "Parece OK", mas eu sugiro a você editar a resposta para colocar um pouco de texto nela.
Comment: @VictorStafusa, botão? que botão é esse?
Comment: Esse daqui: https://i.stack.imgur.com/jWwCi.png
Comment: Hehehe, entendi
Comment: Ola, obrigado pelo retorno. Mas o que vem como valor é simplesmente idObra e clienteObra e não os valores que estão nos inputs.
Comment: Resolvido. muito obrigado. a solução postada está ok.
Comment: os valores que estão nos inputs também  são idObra e clienteObra, alterei no exemplo para Value_idObra e Value_clienteObra

Problemas ao passar parametro URL


Need to match exact string within a varchar column in SQL Server

Question: I have a two-part problem in which I am pulling all #hashtags from a column to display which #hashtags were "trending" for a particular time frame to display on an SSRS report. And then I have a sub-report in which the user can click the #hashtag and be taken to all records from the table in which the #hashtag appeared.
To pull the #hashtags from the table, this thread showed me how I could accomplish this feat using two functions and a cross apply.
Now I am trying to find an exact match of a text string in a varchar(max) column from a table in SQL Server.  My current query uses a LIKE statement:
ticketDescription LIKE  '%' + @paramHashtag + '%'

This presents a problem because I do have similar #hashtags such as #update and #updateinfo and the LIKE statement returns #updateinfo hashtags when I am searching for #update hashtags.
I tried to use WHERE CONTAINS (ticketDescription, @paramHashtag) but we do not have full-text enabled and I am not sure that is a possiblility.
If full-text search is not an option, is it possible to look for exact matches on the parameter that will be passed to the query?
Below is sample data from the ticket descriptions:
CREATE TABLE [dbo].[Trending](
[TicketDescription] [varchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Values inside the TicketDescription column:
#Update  Corrected last name and driver's license number.
#Update  Update customer's last name.
#Update  Update last name, address
#update - Profile updated. Corrected last name.
#updateinfo
#updateinfo
#updateinfo
#updateinfo
#Update  Update residency status
#update #SSNdiscrepancy   John Doe called in claiming this was their SSN, please advise.
#update  Updated residency status
#Update  Changed residency from in-state to out-of-state
#Update  Updated Customer's last name
#updateinfo
#updateinfo
#Update - updated customer's last name

Comment: Presumably you want to find the first character that isn't a letter or a number or a hash. e.g. `SELECT SUBSTRING(TicketDescription, 1, PATINDEX('%[^#A-Z0-9]%', TicketDescription) - 1)` If it's always a space after the hash tag, you can use `CHARINDEX(' ', TicketDescription)` instead. Match the parameter on this. This assumes your hash tag is always the first character in your strings. If it isn't, then a slight modification of this is necessary.
Comment: Unfortunately, the first character might not be # and the field might contain multiple #hashtags as well. But the #hashtag should end after the first empty space - so in the sample data above, the 1st record's #hashtag would only be #Update.
Comment: Hm. Then you could search based on whether @param = ticketdescription (e.g. the ticketdescription is the hashtag alone) or `ticketdescription like '%' + @param + ' %'` (note the space before the second percent symbol)... I guess you'd need to include cases where it ends with the parameter but has other text beforehand, e.g. `or right(ticketdescription, len(@param)) = @param`.
Comment: Maybe a silly idea. But why not simple search for the param + a space?
Answer: Here's an example of how you could write a query that should deliver the results you expect (by checking for a match on your hashtag and then a character that isn't a letter or a number - e.g. a space, comma, etc after the hashtag):
DECLARE @T TABLE (TicketDescription VARCHAR(MAX));
INSERT @T VALUES
('junk text #Update  Corrected last name and driver''s license number.'),
('more junk text#Update  Update customer''s last name.'),
('asdfadsf #Update  Update last name, address'),
('#update - Profile updated. Corrected last name.'),
('#updateinfo'),
('#updateinfo'),
('#updateinfo'),
('#updateinfo'),
('#Update  Update residency status'),
('#update #SSNdiscrepancy   John Doe called in claiming this was their SSN, please advise.'),
('#update  Updated residency status'),
('#Update  Changed residency from in-state to out-of-state'),
('asdfasdfadf#Update  Updated Customer''s last name'),
(' asdfadsf #updateinfo'),
('asdf #updateinfo'),
('#Update - updated customer''s last name'),
('#Update'),
('#Update,example with a comma after hashtag');

DECLARE @param VARCHAR(255) = '#update';

SELECT TicketDescription
FROM @T
WHERE TicketDescription LIKE '%' + @param + '[^A-Z0-9]%' -- Hashtag + something that isn't a letter or number.
OR RIGHT(TicketDescription, LEN(@param)) = @param; -- Or it matches the very last part of the given TicketDescription.

Comment: Thanks ZLK - I understand what you are doing with '%' + @param + '[^A-Z0-9]% but could you explain what the purpose of Right(Ticket...)? It works and I appreciate that, but I would like to know what the second portion does as well.
Comment: @MISNole The `RIGHT` part is picking up things where the very last part of the TicketDescription is the param. e.g. 'generic text #update' would be picked up. It would also pick up something where the entire TicketDescription is the hash tag (e.g. if your param was "#updateinfo", all the rows with just "#updateinfo" would be picked up). These would not have a space (or anything) after the hash tag, so you need to build a rule for those.
Comment: Thanks ZLK - I appreciate the solution and the explanation.


Propositional logic, valid entailment

Question: I have an old exam-question but don't know how to solve
this type of problems. So If someone could give me a hint  it would be much appreciated.
Is the following entailment valid?
$$
(p \rightarrow q) \rightarrow r, \neg r\land \neg s, (q \rightarrow p) \lor t, t \rightarrow (r \lor p) \vdash t
$$
If I assume that the right handside is false$(\neg t)$ and show that the left handside holds, then the entailment is not valid. But how?
EDIT
For
$$
\neg r \land \neg s
$$
to be true then both  r and s must be false.
And if r is false then $$(p \rightarrow q)$$ must be false.
 And since $$(q \rightarrow p)$$ must be true, then p is true and q is false.
When t is negated, all premises is satisfiable and therefor the entailment is not valid. Am I right?
Comment: Have you made any progress?
Comment: Oh. Thanks for asking. Not really. I'm I a making it more complicated when adding a negation to 't'(right hand side)?
Comment: Yes, indeed; since the conclusion may be false with all premises satisfied, therefore $t$ is not entailed by those premises.
Comment: I have now tried this when assuming t is false and when t is true. Both times all premises is true if p is true and q is false. Is it then correct to say that the entailment is not valid but satisfiable?
Comment: Yes, and therefore....
Comment: Not sure what you mean here but since they ask if the entailment is valid, the answer should be no, it is not.
Comment: ...t is not entailed by the premises.
Answer: If all of the premises and the negation of the conclusion can be satisfied, then the conclusion is not a logical entailment of the premises.
$$\{(p \rightarrow q) \rightarrow r, \neg r\land \neg s, (q \rightarrow p) \lor t, t \rightarrow (r \lor p), \neg t\}$$
Clearly, the negation of the conclusion may be satisfied when $t$ is false.  That also satisfies the fourth premise, but the third premise would then only be satisfied when $q$ implies $p$.
$$\{(p \rightarrow q) \rightarrow r, \neg r\land \neg s, (q \rightarrow p) \lor \bot, \bot \rightarrow (r \lor p), \neg \bot\}$$
Carry on..
Comment: When you say it also satisfies the fourth premise, do you mean that (r v p) could be either true or false here?
Comment: Yes, @LarsLogik . $t\to(r\vee p)$ is satisfied when $\lnot t$ is; so that does not fix $r$ or $p$. For that, look to the second premise, $\lnot r\land\lnot s$.

Propositional logic, valid entailment


How to handle a LocalDateTime from API that returns datetime in different format?

Question: I'm using a rest template to call an API in Java, which returns this object :
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
public class MyObject {
    //@JsonDeserialize(using = LocalDateTimeDeserializer.class)
    private LocalDateTime accessTime;
    private String name;
}

The problem is that the accessTime retrieved by the API looks like this :
2020-04-29 12:52:57

And I can't use a LocalDateTimeDeserializer.
This is the following error:
Can not deserialize value of type java.time.LocalDateTime from String \"2020-04-29 12:52:57\": Text '2020-04-29 12:52:57' could not be parsed at index 10

How can I handle this ? Thank you
Comment: Do [this question and its accepted answer](https://stackoverflow.com/questions/40327970/deserialize-java-8-localdatetime-with-jacksonmapper) help?
Comment: Assuming you're using the `JavaTimeModule`, Jackson is already using `LocalDateTimeDeserializer`, so it would be redundant to annotated your field.
Comment: @deHaar I saw this answer before posting my question, but I have the following error "Attribute value must be constant" at "@DateTimeFormat(iso = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))"
Answer: I guess you are looking for a method which will receive the local date time in string from the API and then use this method and store the converted localdatetime format. This is the method which can help you:
private LocalDateTime TryPase(string accessTime)
{
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); //edit your format
return LocalDateTime.parse(accessTime, formatter);
}

Comment: Thank you, but I'd like to avoid using methods since the object is directly mapped during the restTemplate post, that's why I'm looking for a JsonFormatter or whatever
Comment: That would be a better option indeed


Generate values with runif and a probability density function

Question: I'm trying to use the rejection method (accept/reject) to simulate samples of various dimensions from the distribution with density function of probability

And graphically check whether the sample comes from a population with Beta distribution (1/2, 3).
Here's what I've done:
<code> # 1. Define sample size
nvals <- 5000

# 2. Rejection sampling method
reject.beta <- function(nvals)
{
  x.aceite <- NULL
  u.aceite <- NULL
  nx <- 0
  x.rejected <- NULL
  u.rejected <- NULL
  nrejected <- 0
  while(nx < nvals) {
    Y <- runif(1,0,1) #I can't use uniform distribution
    U <- runif(1,0,1.875) #1.875 = 30/16
    if(U <= (15/16)*(Y^(-1/2))*(1-Y)^2) {
      nx <- nx + 1
      x.aceite[nx] <- Y
      u.aceite[nx] <- U
    } else {
      nrejected <- nrejected + 1
      x.rejected[nrejected] <- Y
      u.rejected[nrejected] <- U
    }
  }

  plot(x.aceite,u.aceite,pch=20,col="green",xlab="x",ylab="f(x)",main="Beta(1/2,3) - pontos escolhidos pelo Método de Rejeição")
  lines(x.rejected,u.rejected,pch=20,col="red",type="p")
  x.aceite
}

XX <- reject.beta(nvals)
hist(XX,breaks=20,prob=TRUE,xlim=c(0,1),ylim=c(0,3),main="Distribuição(2,3) obtida pelo Método de Rejeição")
x.val <- seq(0,4,0.001)
lines(x.val, dbeta(x.val, 1/2, 3) ,col="blue")
</code>
However, I can't use uniform distribution to solve this, I need to use the probability density function:

The suggestion I've got was to assign Y variable with a value from this p.d.f using the inversion method. (I thought extracting a value between the min and max would suffice)
Can someone please tell me how can I do that?
Answer: I assume you have a cumulative density function $F$ and you want to sample a random variable $Y$ whose distribution functions is $F$ ($Y \sim F$).
To do this note that $F(Y)$ is uniformly distributed. Let $U \sim Uni[0,1]$ then you know that $F^{-1}(U) \sim Y$. This means that all you have to do to sample from $Y$ is to generate a sample $u$  from $U$ and compute $F^{-1}(u)$.
To find $F^{-1}(u)$ in R you might find the function uniroot very useful, since all you really want is a solution for the equation $F(x) = u$.
Comment: Sorry, I cant provide a R example, but I will gladly answer any question you have. If you are having trouble understanding what I wrote and can't formulate a question I encourage you to check the [wikipedia article](https://en.wikipedia.org/wiki/Rejection_sampling) about the Rejection Sampling algorithm.
Comment: Too bad I'm not that good at statistics to understand what you're saying. +1 though
Comment: Can you provide an R example? I'm having trouble in understanding what you're saying


Adding a Javascript library

Question: I apologize for asking this for the 100th time but I just cannot understand the previous answers.   There are 2 modules (form placeholder and chosen)where cannot get their libraries included.
Step 1: I downloaded their libraries and placed them in the libraries folder.
Step 2: I included 2 new libraries in the THEME.info.yml
libraries-extend:
  bootstrap/framework:
    - bootstrap_kampuster/framework

libraries:
  - bootstrap_kampuster/chosen
  - jquery.placeholder

However, neither one of the 2 is loading right now. Is there anything else I need to add somewhere? FYI, my THEME.libraries.yml looks like this;
framework:
  css:
    theme:
      css/style.css: {}
      css/animate.min.css: {}

  js:
    js/custom.js: {}
    js/misc/waypoints.min.js: {}

    dependencies:
    - core/jquery

Comment: What is bootstrap loading, from local or a CDN?
Comment: @joehoe, hi there, loading bootstrap from local.
Comment: [Adding stylesheets (CSS) and JavaScript (JS) to a Drupal theme](https://www.drupal.org/docs/theming-drupal/adding-stylesheets-css-and-javascript-js-to-a-drupal-theme)
Answer: You need to add this to YOURTHEME.theme file:
function siderise_preprocess_block(&$variables) {
  // Attach the global-scripts library to all blocks.
  $variables['#attached']['library'][] = 'YOURTHEME/YOURFRAMEWORK';
}

make sure you update the function with your theme and your framework in the bottom line

Adding a Javascript library


In a Phoenix application, what is the difference between the :port key of the :http and :url configurations?

Question: I'm currently working in a Phoenix app and had this question when modifying my /config/* files.
Currently the configuration for my Endpoint contains the following:
config :my_app, MyApp.Endpoint,
  http: [port: 8080],
  url: [host: "example.com", port: 80]
...

After reading both documentations for the :http config and the :url config its still not clear to me:
What is each :port config used for and how are they different?
Answer: The port in :url is used to generate URLs (like the _url Router helpers) within the application while the port in :http is the TCP port the application will bind the HTTP server to. This is useful because your publicly accessible URLs will most likely be port 80 (default HTTP port) or 443 (default HTTPS port), while your application may run on another port behind a reverse proxy, load balancer, or a caching server (like Nginx,  HAProxy, Varnish). If there was only one configuration for both, you wouldn't be able to host more than one application on one port of the server while still generating valid URLs in the _url Router helpers.
Comment: Thanks for the answer! I think you meant *while the port in :http is the TCP port ...* though.


Rails Find with Active Resource Ignoring Parameters

Question: I have two Rails apps, one client using ActiveResource and one service.  I am testing the following command via the console:
User.find(:all, :params => {:email_address => "firstname.lastname@example.com"})

I get back all the records in my user table and not just the one specified in my email parameter.
When I go look at the log for my service app it shows as follows
Started GET "/users.json?email_address=myemail%40domain.com" for 127.0.0.1 at 2011-12-29 11:29:06 -0600
   (0.4ms)  SHOW search_path
  Processing by UsersController#index as JSON
  Parameters: {"email_address"=>"email@example.com"}
  User Load (0.7ms)  SELECT "users".* FROM "users"
Completed 200 OK in 40ms (Views: 35.7ms | ActiveRecord: 3.3ms)

My parameter was not included in the SQL statement.
Any insight?
Comment: please post your service app users_controller index method
Comment: try using :conditions instead of :params
Comment: Here is my index

at users = User.all

    respond_to do |format|
      format.json { render json: @users }
    end

Using conditions doesnt pass throught the params and produces this

Started GET "/users.json" for 127.0.0.1 at 2011-12-29 12:08:41 -0600
  Processing by UsersController#index as JSON
  User Load (0.3ms)  SELECT "users".* FROM "users"
Completed 200 OK in 12ms (Views: 7.0ms | ActiveRecord: 4.1ms)
Comment: The User controller and model on both the client and service were generated from a scaffold and are so far unchanged except for changing the model on the client side to use Active Resource and set the self.site url.
Comment: @user1084769, are you sure you're talking about ActiveResource and not ActiveRecord?
Answer: Based on your comment on the original question, your controller still looks like this:
class UsersController < ActionController::Base
 def index
   @users = User.all
   respond_to do |format|
     format.json { render json: @users }
   end
 end
   #other methods down here
end

But in order to get your index view to render just the ones that match the email, you need to update the index method to:
class UsersController < ActionController::Base
 def index
   @users = User.find_all_by_email_address(email_address)
   respond_to do |format|
     format.json { render json: @users }
   end
 end
   #other methods down here
end

Comment: thanks jstim.  i found the distinction between params and conditions with relation to activeresource and activerecord to be the same as well.  my goal is to login a user from the activeresource client to the activerecord service app.  when the two parameters are validated the user data is sent back to the client so i can set a session.

in my original question i was first trying to send an email address and get back a user but have still been unsuccessful.  when i query data like this out of the normal by id, do i need special routes or something in the controllers to handle this?
Comment: I don't think you need anything special. These are all available as part of AR or AS. As someone mentioned above, though, there may be something in your controller that is overriding this search. Can you post your controller?
Comment: To clarify as well, which app holds the User table? Is it the one using AR or AS? Are you caching users on both sides or could you be getting your db calls mixed up?
Comment: ActiveRecord holds the user table.
Comment: so all this talk about ActiveResource isn't relevant to the question of the search syntax. I'll update my answer to show the proper AR calls, but it would still be helpful to see your controller to confirm there isn't something overwriting your search.
Comment: The User controller and model on both the client and service were generated from a scaffold and are so far unchanged except for changing the model on the client side to use Active Resource and set the self.site url.
Comment: This is a long shot but is there any way your app cached the original request and is just hitting the cache instead of polling the db? Should show up in your development log if so.
Comment: possible.  I was running these queries in terminal on the mac
Comment: I think you are onto something in your code example, but what does the controller look like on the activeresource side?
Comment: @user1084769 try this on the service app side `@users = User.where params`. This way all queries would be supported and not just by_email_address.
Answer: Conditions are passed to ActiveRecord find method via :conditions option and not :params. So your find call should be like that:
User.find(:all, :conditions => { :email_address => "firstname.lastname@example.com" })

or in more Rails 3 style:
User.where(:email_address => "firstname.lastname@example.com").all

You can find full list of available parameters for find method in docs.


What does this weird notation mean (looks like "#.1")?

Question: I play guitar using the following scale, which I think is C major. (I don't know the name, but I follow the number on the music note, and it works.)

I came across the following note:

As you can see, this is not a normal .1. It has a # sign beside it. How can I play this on my guitar?
(I am a guitar beginner, with no musical knowledge, so a more detailed answer would be appreciated.)
Comment: [Related question](http://music.stackexchange.com/questions/4914/is-there-a-specific-name-for-sheet-music-that-uses-numbers-erhu-sheet-music)
Answer: This notation is not common in English material, but it appears that the numbers correspond to the notes of C major scale. 1=C 2=D etc.
The middle octave has no dots. A dot below means it's an octave below, a dot above means it's an octave higher.
So #.1 is probably C# which is one fret higher than the higher C. That's fret 2 on the B string.
This does leave me wondering what the 0 represents. A rest, maybe?
Comment: An 0 in tabs usually stands for an open string.
Comment: I'm not familiar with this notation, but I would assume if you wanted a 2 you'd write a 2 – so perhaps this is a 1, but bent? (I.e. the string is pulled sideways to make the note sharper.)


Model stability and variability

Question: I am using polynomial regression to predict mean occupancy in a hospital unit using average length of stay (LOS) and arrival rate to the unit. I am using different percentages of training sets to train the model and 5 fold cross validation to pick the best model. For each percent of training set, the model is trained 20 different times. The final models are then used to make predictions on the test set. However, when I obtain the results of the 20 runs, the "average LOS" coefficients are highly variable (in magnitude and opposite signs) from one model to the other. Is there a way to 'quantify' this coefficient variability? or is there a way to measure 'model stability'?
Comment: No point doing train/test/validation splits for polynomial regression. This is a "smooth" function (unlike regression trees) so you're better off using all the data to fit your model, and make use of model averaging techniques
Answer: Yes, there is. In a recent paper we present a framework for doing exactly what you describe.
The procedure is implemented in the R package stablelearner which you can find here stablelearner package.
The basic idea is to use a resampling strategy that generates pairs of learning samples that do not overlap overly much and an evaluation set that does not overlap with the learning samples. Then the model in question is fitted to each of the learning samples and based on both estimated models a pair of predictions (one from estimated model 1, one form estimated model 2) are generated for the evaluation data. For the prediction pairs a similarity measure gets calculated and aggregated over all data in the evaluation set. This is repeated B times and a summary statistic or the whole "stability distribution" is used to gauge the stability. In the paper, a 0.9*Bootstrap resampling with out-of-bag evaluation is recommended.
Polynomial regression is supported by the package (in form of the linear model). Here's a toy example:
R> library(stablelearner)
R> data(iris)
R> model<-lm(Sepal.Length~Sepal.Width+I(Sepal.Width^2),data=iris)
R> set.seed(1)
R> stab<-stability(model,control=stab_control(sampler=bootstrap,v=0.9))
R> summary(stab)

Call:
lm(formula = Sepal.Length ~ Sepal.Width + I(Sepal.Width^2), data = iris)

Sampler:
B = 500
Resampling method = Bootstrap sampling with 90.0% data
Evaluation method = OOB

Sampling summary:
                           avg min max
Learning sample size   135.000 135 135
Learning overlap        53.080  38  68
Evaluation sample size  24.428  15  35
Evaluation overlap       0.000   0   0

Similarity summary:

, , Concordance correlation coefficient

  5%     25%    50%    75%    95%
lm 0.0102 0.4355 0.6429 0.8169 0.9591

R> boxplot(stab)

Answer: I wanted to comment but don't have enough reputation to do so. Why would I be getting NA values for the Concordance Correlation Coefficient?
I tested it with two models:
    m1 <- glm(count_formula, family="quasipoisson", data=cohort,
              weights=weights)

where weights is just a column of 1's and
    m2 <- glm(count_formula, family="quasipoisson", data=cohort,
              weights=weights)

where weights are calculated propensity scores.
Both models return NA values for the CCC when I run
    stab <- stability(m1, control=stab_control(sampler=bootstrap,v=0.9))

or
    stab <- stability(m2,control=stab_control(sampler=bootstrap,v=0.9))

Model stability and variability


Where can i find a .net implementation of atof?

Question: Is there an implementation for the c language's atof function in the .net world?  float.Parse does not behave the same.
Some behavioral differences.

"50 Apple" will return 50.
"50 Apple. 1" will return 50.
"Apple" will return 0.
Comment: It might help if you described the difference in behavior.
Comment: I believe that Single.Parse should do what you want. Could you give an example where it doesn't have the behavior that you want?
Answer: If you mean you want to duplicate atof's leniency (ignoring preceding whitespace and trailing non-numeric characters), you can do this (assuming C# 3.0):
float myAtof(string myString)
{
    Predicate<char> testChar = c => c == '.' ||
                                    c == '-' ||
                                    c == '+' ||
                                    char.IsDigit(c);

    myString = new string(myString.Trim().TakeWhile(testChar).ToArray());

    if (myString.Length > 0)
    {
        float rvl;

        // accounts for bogus strings of valid chars, e.g. ".-":
        if (float.TryParse(myString, out rvl))
        {
            return rvl;
        }
    }

    return 0;
}


Why is it useful to have a synchronized collection in Java

Question: I have came know that the difference between ArrayList and Vector class is that Vector class is synchronised whereas the ArrayList is not. I know what is synchronization, but can anyone explain how it is useful in this context?
Comment: What is synchronization?  Knowing that should give a good clue on why it is useful for collections, or any object for that matter.
Comment: I have got a clue but I don't want to assume it.
Answer: Synchronization is used in the context of Concurrency. This clearly explains why synchronization is essential:

Threads communicate primarily by
  sharing access to fields and the
  objects reference fields refer to.
  This form of communication is
  extremely efficient, but makes two
  kinds of errors possible: thread
  interference and memory consistency
  errors. The tool needed to prevent
  these errors is synchronization.

Synchronized class/method/instance/statement variables prevents concurrent usage of the synchronized class/method/instance/statement.

When one thread is executing a
  synchronized method for an object, all
  other threads that invoke synchronized
  methods for the same object block
  (suspend execution) until the first
  thread is done with the object.'

Source.
Vectors are thread-safe (meaning synchronized) while ArrayList aren't. You can allow thread safety by using Collections.synchronizedList(...).
Answer: public class ThreadSafeExample {
    private Vector<String> names = new Vector<String>();

    public void addName(String name) {
       names.add(name);
    }
}

This class will work fine even if multiple threads call the addName(..) method. With ArrayList, it won't - you will have missing values.
The performance of Vector, ArrayList is benchmarked here. Note that there also exists Collections.synchornizedList(..) which makes any list synchronized.
Note that this applies when the collection is used as an instance field. If  the vector is declared within a method, then you gain nothing with the synchornization (no other thread can use it anyway). In fact, there is something called "escape analysis", which in this case removes the synchornization if it is not needed. But I think it is not on by default.
Comment: I didn't. That's the point - Vector does not require external synchornization.
Comment: I think you forgot a synchronized somewhere?
Comment: Yeah, OK.  Calling the enclosing class ThreadSafeClass threw me :-)
Answer: I did not wanted to redirect you, but I have the same thing to say as here: http://manikandanmv.wordpress.com/2009/03/21/vector-vs-arraylist/

Vector

Vector is thread safe, because vector objects are synchronized which means you can access vector objects from any number of threads at the same time without affecting its data.
Due to the above reason, In performance wise Vector is slightly slower than ArrayList
Double the size of its internal array when it runs out of space.

ArrayList

ArrayList is just opposite of Vector class. Its not thread safe, suppose if you are using ArrayList instances in multiple threads surely which leads to create some problems while accessing.
ArrayList comes from Collection Framework family. So its easy to developers to convert in to any other datastructure formats.
Increases its array size by 50 percent.

ArrayList are more preffered and you can externally synchronize them by Collections.syncronizedList(..)
Answer: Synchronization of a list is necessary if multiple threads may access it concurrently. Synchronization is an unnecessary (but not necessarily significant) cost if only a single thread can access the list.
I personally tend to use ArrayList by default, and synchronize access to it if required.
Using the common List<> interface to refer to instances of Vector or ArrayList allows you to switch implementations more easily.
Answer: ArrayList was meant to replace Vector however it is not thread safe by design. I would suggest only using ArrayList and not making use of Vector since it was not designed ground up to be part of the Collections. If you need thread safety on your ArrayList you can do...
List list = Collections.synchronizedList(new ArrayList(...));

Answer: You ask what synchronization is useful for? You might enjoy Doug Lea's book Concurrent Programming in Java.  Although it is slightly dated, it gave a good academic treatment of the issues inherent in multiple threads of execution accessing the same data structures.  For actual application and a more up-to-date treatment, you would read Java Concurrency in Practice.
As Doug Lea would put it, you want threads of execution to make progress.  But you also want to preserve the integrity of data structures.
In the case of Vector and ArrayList, suppose two threads went to add an item 'at the same time'.  One of the things that needs to be done is that the count of items in the  needs to be incremented.  This is something hidden from you, but is nonetheless important to the collection itself.  It would not do for ThreadA to see that before it added the item, the count was 3, and tried to write 4, but meanwhile ThreadB had already incremented it to 4 and it should now be 5!
Synchronisation is one approach to solving this problem.  Essentially, when two threads attempt to access the same object and it encounters a 'synchronized block' (which sometimes may be an entire method), ThreadB has to wait until ThreadA is finished and 'releases the lock'.  That way, there is no chance of the two threads reading the count and then two threads writing the count.  By forcing an order on the operations of the threads (synchronizing them), there is a read/write followed by another read/write.


Active Directory Corrupted In Windows Small Business Server 2011 - Server No Longer Domain Controller

Question: I have a rather bad problem with my Windows SBS 2011. First of all, I'll give the background to what caused the problem. I was setting up a new small business server network. I had my job about finished. The server was working great, all the workstations had joined the domain, and I had all my applications and data moved to the server. I thought I was done. But then it happened. I tried adding one more computer to the domain, and to my dismay the computer name was set to the same name as the server.
Apparently when a computer joins a domain with the same name as another machine that is already on the domain, it overrides the first one. For normal workstations, this is not a big deal, you just delete the computer from AD and rejoin the original computer to the domain. However, for a server that is the domain controller it is a whole different story. Since the server got overridden in AD, it is no longer the domain controller. The DNS service is not working and all kinds of other services are failing also.
So the question is, what are my options? I am embarrassed to admit it, but since this is a new server one thing I did not have setup yet was backup. So I have no backups to work from. I am worried that things are broken enough that I might need to do a reinstall. However, I already have several days worth of configuration into this server, so I would obviously prefer if there was a fix that would prevent me from needing to do a reinstall. All the server components are there and installed correctly, but they are misconfigured (I think it is basically just Active Directory). So I have the feeling that if I did the right thing I could solve the issue without a reinstall. Is there anyway to rerun the component that installs the initial configuration to "convert" the base windows server 2008 r2 install into a SBS? In other words in the program files folder there is an application called SBSsetup.exe, is there anyway to rerun this and have it reconfigure AD, etc. to work with SBS?
Any insight will be greatly appreciated. Thanks.
Comment: Just some quick ideas.. Did you run [dcdiag](http://technet.microsoft.com/en-us/library/cc731968(WS.10).aspx)?  What do the SRV records in DNS look like?  What is the SID of the DC?  What is the SID of the workstation?
Comment: Here is a pastebin of the output from dcdiag: http://pastebin.com/RWmk0Wyz. As far as the DNS records, when I go to DNS it says The DNS server has not been configured. But the problem actually is that DNS is failing to start. So I cannot look at what the records are. How do I go about checking the SID stuff?
Comment: [getsid](http://technet.microsoft.com/en-us/library/cc784314(WS.10).aspx).  What are the errors that are logged when you try to start DNS?  DNS is critical to AD, as it advertises the location of all offered services.
Comment: Here is the only error that DNS is generating when it is staring:

Event Type: Error
Event Source: DNS
Event Category: None
Event ID: 4000
Date:  11/18/2011
Time:  10:10:45 AM
User:  N/A
Computer: [Removed From Post For Security]
Description:
The DNS server was unable to open Active Directory.  This DNS server is configured to obtain and use information from the directory for this zone and is unable to load the zone without it.  Check that the Active Directory is functioning properly and reload the zone. The event data is the error code.

Data:
0000: 2d 23 00 00
Comment: What errors do you have in `Directory Service` event log?  You have to figure out how to get your AD started.  Make sure that the DC is the only machine with its IP address.  You can always use `dcpromo` to demote the DC essentially destroying the domain, but that's last resort.
Comment: In the Directory Service log there is first an information level entry : http://pastebin.com/HFXirQKE. Next there is a warning level entry: http://pastebin.com/KdJBce29. And last of all it makes an error level entry: http://pastebin.com/aAT1tQU5. What do you think my chances are? Should I just give up and do a reinstall?
Comment: I'm having trouble really wrapping my head around the issues as they seem to be quite large in count.  You would have to troubleshoot each issue that has occurred, and fix it from backward and forward (each AD related service relies on another, etc, etc.).  Depending on your time constraint, it would be a very good learning experience.  However, rebuilding the domain by demoting the "last DC" then promoting it again might be faster.  My suggestion is to have a back up in place, and even a secondary DC, so that you can seize rolls if necessary (even on a VM on secondary hardware).
Answer: You have a DNS issue.  You must have DNS running in order for AD to run.  It is possible that the client registered its IP and broke things. (although for the life of me, I cannot believe AD would allow that)
Try this - find the workstation's IP then shut it down.  Add that IP to the NIC of the domain controller. This should allow the computer name to get associated with the right IP address.
If it doesn't help, try uninstalling DNS and reinstalling.  Once it is loaded run ipconfig /registerDNS on the DC to recreate the AD records


Perform a t-test in multiple regression matrix

Question: I have the following matrices: $$ X'X $$ $$X'y$$$$ y'y $$
I know that the B matrix can be computed as follows : $$ B = (X'X)^{-1}X'y $$
If I want to perform a t test for a specific B, say $$B_{1}$$, I know that I must follow the formula : $$ t = \frac{B_{1} - B_{0}}{\textrm{se}(B_{1})} $$
However, if I only have the 3 aforementioned matrices, how can I compute the standard error of a given $B?$
Answer: If $\epsilon$ designate your residuals, estimator variance matrix is given by $Var(\hat{\beta}) = \sigma^2(X'X)^{-1}, \sigma^2 = Var(\epsilon)$ in my class notes but I can't demonstrate it so can't be a 100% sure.
EDIT : this thread gives (and proves) $Var(\beta_1) = \frac{\sigma^2}{\sum\limits_i (x_i - \bar{x})^2}$ so I guess my notes are still good enough :)
Comment: Even I am trying to get my head around this. From what I understand, to obtain 'e' you need Y and predicted Y matrices (which are not there). I guess there is some way you can get those from y'y.
Comment: How can you not have $\hat{Y}$ if you have $X$ and $\beta$ ? Because I would say that you can not derive estimators variance without some kind of information on the residuals.
Comment: according to the question only 3 matrices are available: X'X, X'y and y'y. Matrix X is not there.
Comment: Is that a self-study case ?
Comment: homework case rather ;)
Comment: So there must be a solution, but I can't find any reference in which $\hat{Y}$ is not needed for $Var(\beta)$ to be computed


Overlaying Text in VLC using WPF

Question: I am creating a program that displays song lyrics using WPF. I want to use videos as the background(using VLC player). How can I overlay the lyrics over the video background?
Thanks in advance.
Answer: This may not be possible directly in WPF. I assume that you would need a WinformsHost  to host the VLC player. It's a known issue(limitation) that WPF controls and winforms can't share the same screen area(airspace limitation). However there are many workarounds for this limitation, one of them being adding 2 WPF windows overlayed.
Alternatively you can try upgrading to WPF 4.5(Using VS-2012), this issue seems to b e fixed there.
Read:
https://msdn.microsoft.com/en-us/library/aa970688(v=vs.100).aspx
http://bartwullems.blogspot.in/2010/11/wpf-and-winforms-airspace-problem.html?m=1

Overlaying Text in VLC using WPF


How do I find a good reverb pedal for a huge, soul-filling sound?

Question: I'm looking to experiment with some post-rock sort of stuff, and my guitar sound is just far too empty right now. I've got an echo park that I've been messing around with, but given that it's primarily a delay pedal it's not expanding my tone in the way I'd like.
I've looked around a bit, and there's obviously tons of options with different focuses. I'm worried that if I just jump into something I'll end up with a sound more suited to 60s surf or something.  How can I find a reverb pedal that might give me this big sound I'm looking for?
Note:
I checked out this question, but there's really no info on reverb pedals specifically: What are most common effects (pedals) for Post-rock music genre?
I also realize that technique is much more important than the pedal itself, but I just want a decent starting point.
Answer: As I have written many times before, I can recommend something to you until I'm blue in the face but you may hate it for your sound. So, instead of giving you a fish, I'm gonna teach you to fish.
Any reverb in existence will get you towards the sound you are looking for--you just may like certain units better. Usability, feature set, tone, it all should play a part in your decision. Surf over to ProGuitarShop and hit their reverb pedal section. Give everything there a listen and pick the one you think sounds the best and has all the bells and whistles (or lack thereof) you want. If you don't like any of those, head to your local guitar shop and play with whatever they have there. Effects require experimentation. I can talk to the utility of certain effects, and even discuss some very nice implementations of those concepts, but in the end it relies totally on the user's taste. That's why there are about 5 billion overdrives on the market. Some electrical engineer out there thought overdrive XYZ didn't do ABC so he made his own to fill out the feature gap.
As for worrying about sounding like surf: surf is a genre that heavily relies on technique in addition to reverb. Whack some 16th notes at around 120-132 bpm with a verb'd out sound plus a slapback delay tone and bingo--you got surf. Play quarters with a dotted eight delay with the exact same reverb setting and you have yourself a nice ambient/textural tone. Effects do not entirely define a genre (as you stated in your question). It's a composite of many, many parameters. See this question for further related discussion on what defines a player's tone.
With all that non-subjective stuff said, here's a list of my favorite reverbs :D. Again, your mileage may vary.
Malekko Chicklet => Tiny, tiny footprint, easy to use controls and a wide range of sounds. It's digital (which is sometimes a no-no for me) but still sounds lush. Were I in the market for a reverb this little guy would be my first stop.
TRex Room Mate => Not for the feint of pocketbook. This one gets you a nice, lush, analog tube driven reverb that is very, very tweakable.
Electro Harmonix Holy Grail => This and it's big brother, the Holy Grail Plus, or the Cathedral are solid choices. All with versatile sounds, and decently affordable. I owned a Holy Grail for much of my early music career and it worked for me.
Comment: ... and as for the 5 billion overdrives; 4 billion of them are TS-8 clones, the major differences being the specific values of various capacitors, how close a cap has to be to that ideal, and whether they use tube, electrolytic or mica caps.
Comment: Great answer. I've rewritten the question to fit so it won't be closed.
Comment: A fave of mine, though digital, is the Digitech HardWire Stereo Reverb. The entire Hardwire line is worth a look; I also have their Tube Overdrive and Valve Distortion pedals; great ones both. I'll keep my Boss analog chorus though.
Answer: A consideration for reverb pedal use is whether you use distortion in your amp, or do you run it clean and rely on a distortion pedal in your effects chain?
In a traditional guitar to combo amp setup, the reverb spring tanks in the amp are after the pre-amp, so any distortion the pre-amp generates gets fed into the tank, then passed to the power amp, so you are "reverbing" the distortion, then passing it on to the power-amp section for final amplification. This results in a smoother sustaining sound, similar to what you'd hear from someone like Carlos Santana.
If you use a reverb pedal, and you're feeding that into the pre-amp of the amp then distorting the sound, you'll get an entirely different sound. It might not be what you expect or want. Transitions between notes will cause the distortion to generate some harsh sounds as it receives multiple notes at once. That happens when we play a chord into a distortion, but soloing could result in some "interesting" sounds, more like a ring-modulator. You'll have to try it and see if it's what you want.
If you have an amp with an effects loop, you might want to put the reverb pedal into that loop, not into your normal pre-amplifier effects chain, just so you can get a more traditional sound of distortion -> reverb.
If your amp is clean, and you don't have an effects loop, put the reverb after any distortion pedals then feed that into the pre-amp in, to make the overall guitar sound closer to the traditional sound of a distorted amp pushing sound into the tank then to the power-amp.
Of course, that's if you want to sound like a normal system. You're always free to change things up to get "your" sound.
Answer: I hear raves and I hear rants about the Holy Grail Nano. I don't have one, so I do not know.
You might check into getting an amplifier that comes with a built in reverb tank. It will be a tube or valve amp and probably give you a fuller sound than any pedal.
Answer: I cannot recommend the neunaber WET reverb enough. If you are looking for a post-rock style reverb, this one is hard to beat.
It goes from slight shimmer to ghost trails to whale songs.
http://neunaber.net/products/wet-mono-reverb-v4
Answer: The Electro Harmonix Holy Grail reverb pedals were very nice IMO.
They no longer have the one I had listed on their website, but the Holy Grail Nano is very similar.
See here.


What happens when await suspends an async function?

Question: main(){
    PrintLotsOfStuff();
    GoShopping();
    HaveAGoodDay();

}

PrintLotsOfStuff(){
    printDailyNewsDigest();
    printWinningLotteryNumbers();
    printWeatherForecast();
    printBaseballScore();
}

async printDailyNewsDigest() {
   var newsDigest = await gatherNewsReports();
   print (newsDigest);
}

gathernewsReports() {}

if we look on https://dart.dev/tutorials/language/futures, we can see that gatherNewsReport() and print(newsDigest) get run after all the functions in the function that called the async function.
However, in the situation I outlined above, there is one more level. In that case, how does the flow look?
First PrintLotsOfStuff() calls printDailyNewsDigest(), which calls gatherNewsReports(), which then suspends, passing control back to printLotsOfStuff().
This then runs printWinningLotteryNumbers, printWeatherForecast, and printBaseballScore. What happens next if the await still hasn't returned?
Does it return to the upper level and then run GoShopping() and HaveAGoodDay()?
Comment: How about testing it with some `console.log()`s?
Comment: You just asked [the exact same question](https://stackoverflow.com/questions/56699312/does-code-higher-in-stack-get-run-while-waiting-for-await-to-complete-in-async-f), then deleted it. Why are you expecting a different response?
Comment: is it so hard to get a response. yes, I can build a fiddle. I will go do that then. I thought just asking would be easier, but I will do that then.  All I wanted was confirmation or disagreement as to whether my understanding is right or wrong
Comment: You're not returning anything... (oh, that's not what you were asking)
Comment: _"I thought just asking would be easier..."_ - Asking is fine but you're supposed to do some research before you ask. And in that case the easiest "research" would have been to execute the code (after modifying `gathernewsReports()` to return a `Promise` otherwise the `await` would be useless) and checking the output.
Comment: @andreas understanding and debugging asynchronous behaviour of JS is hard, you just have proven that by yourself (it doesn't matter wether you do `await Promise.resolve()` or `await undefined`)
Comment: @JonasWilms _"(it doesn't matter wether you do `await Promise.resolve()` or `await undefined`) "_ - And where exactly did I say that TO should return `Promise.resolve()` or `undefined`?
Comment: @andreas "otherwise the await would be useless"
Answer:
First PrintLotsOfStuff() calls printDailyNewsDigest(), which calls gatherNewsReports, which then suspends, passing control back to printLotsOfStuff().

Exactly. In other words: printDailyNewsDigest() executes synchronously till it reaches the first await, then the function yields its execution and the function call evaluates to a Promise (so a Promise gets returned to the function that called it). As PrintLotsOfStuff() ignores that promise, execution will continue synchronously from then on.

This then runs printWinningLotteryNumbers, printWeatherForecast, and printBaseballScore. What happens next if the await still hasn't returned?

Synchronous execution can't be interrupted. printDailyDiggest definetly did not continue execution yet.

Does it return to the upper level and then run GoShopping() and HaveAGoodDay()?

Sure.
Now if that was done, the call stack is empty and the engine has time to execute the next task. Now somewhen whatever printDailyDiggest awaited will be done, and printDailyDiggest will continue its execution
Comment: Thank you. It's not that i don't want to do research. It's that i have a very similar case in front of me of people using async incorrectly all over the case causing all sorts of bugs. So much so that i question whether i am interpreting what i see correctly. I'm guessing that awaits on a higher level will not return till the first one returned.
Comment: Totally agree, I don't get why your previous question was downvoted (and all those other comments / answers getting it wrong proves that it is obviously not that easy)
Comment: And yes, if you would make `PrintLotsOfStuff()` `async` and would `await printDailyNewsDiggest()` then calling `PrintLotsOfStuff()` will return a Promise, that only resolves after `printDailyNewsDiggest` finished execution. That Promise can then be `await`ed again and so on.
Comment: Anyway i have used Async await a lot about 3 years ago but it wasn't buried multiple layers down and i never had to worry about these details much.


Erro instalação pacote "tabulizer" no R

Question: Estou tentando instalar o pacote tabulizer no R e não estou conseguindo. Tentei também baixando diretamente do CRAN, mas também não deu certo. Tentei também instalando o tabulizerjars em separado, mas também não obtive sucesso.
========================================================
> sessionInfo()
R version 3.4.4 (2018-03-15)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.2 LTS

Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1

locale:
 [1] LC_CTYPE=pt_BR.UTF-8       LC_NUMERIC=C               LC_TIME=pt_BR.UTF-8
 [4] LC_COLLATE=pt_BR.UTF-8     LC_MONETARY=pt_BR.UTF-8    LC_MESSAGES=pt_BR.UTF-8
 [7] LC_PAPER=pt_BR.UTF-8       LC_NAME=C                  LC_ADDRESS=C
[10] LC_TELEPHONE=C             LC_MEASUREMENT=pt_BR.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] devtools_2.1.0 usethis_1.5.1

=======================================================================
> # Instala pacote extrai tabela de pdf
> install.packages("tabulizer", dependencies = TRUE)
Installing package into '/home/jairo/R/x86_64-pc-linux-gnu-library/3.4'
(as 'lib' is unspecified)
also installing the dependency 'tabulizerjars'

tentando a URL 'https://cloud.r-project.org/src/contrib/tabulizerjars_1.0.1.tar.gz'
Content type 'application/x-gzip' length 10902674 bytes (10.4 MB)
==================================================
downloaded 10.4 MB

tentando a URL 'https://cloud.r-project.org/src/contrib/tabulizer_0.2.2.tar.gz'
Content type 'application/x-gzip' length 1047758 bytes (1023 KB)
==================================================
downloaded 1023 KB

* installing source package 'tabulizerjars' ...
** package 'tabulizerjars' successfully unpacked and MD5 sums checked
** R
** inst
** preparing package for lazy loading
** help
* installing help indices
** building package indices
** testing if installed package can be loaded
Error: package or namespace load failed for 'tabulizerjars':
 .onLoad failed in loadNamespace() for 'tabulizerjars', details:
  call: NULL
  error: .onLoad failed in loadNamespace() for 'rJava', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: impossível carregar objeto compartilhado '/usr/lib/R/site-library/rJava/libs/rJava.so':
  libjvm.so: não é possível abrir arquivo compartilhado: Arquivo ou diretório inexistente
Erro: loading failed
Execução interrompida
ERROR: loading failed
* removing '/home/jairo/R/x86_64-pc-linux-gnu-library/3.4/tabulizerjars'
Warning in install.packages :
  installation of package 'tabulizerjars' had non-zero exit status
ERROR: dependency 'tabulizerjars' is not available for package 'tabulizer'
* removing '/home/jairo/R/x86_64-pc-linux-gnu-library/3.4/tabulizer'
Warning in install.packages :
  installation of package 'tabulizer' had non-zero exit status

The downloaded source packages are in
    '/tmp/RtmpSzF9Hj/downloaded_packages'

Answer: Tive uma pequena epopeia para instalar esse pacote no meu computador. Primeiro eu atualizei o meu java. Depois tive que instalar o pacote rJava. Para instalar o tabulizer fui direto no R, sem ser através da IDE (utilizo o RStudio) e inicializei como administrador. Só então utilizei o install.packages("tabulizer", dependencies = TRUE).
Não sei exatamente como seria no seu caso, pois vc utiliza um sistema operacional diferente do meu, mas deixei o passo a passo do que eu fiz, pois pode servir de orientação para você adaptar para a sua situação.
Comment: Atualizei o Java, mas na instalação do rJava já deu erro...

checking whether Java run-time works... ./configure: line 3766: /usr/lib/jvm/default-java/jre/bin/java: No such file or directory
no
configure: error: Java interpreter '/usr/lib/jvm/default-java/jre/bin/java' does not work
ERROR: configuration failed for package 'rJava'
Comment: Me parece que ele não está encontrando o java na sua máquina, ou não possui privilégio para acessá-la. Reveja os privilégios do usuário que está tentando instalar o pacote.
Comment: Já estava com os privilégios... não consegui mesmo. Na verdade não sei como resolver. Mas muito obrigado pelas ajudas e apoio.

Erro instalação pacote "tabulizer" no R


SSL Cipher Suite Order GPO

Question: Thanks in advance for reading. I'm using Win Server 2012 R2 to dish out group policies.
I've created a GPO to define the SSL Cipher Suite Order under Policies > Admin Templates > Network > SSL Confugration Settings and have set it to "Enabled".
I'm using a list of strong cipher suites from Steve Gibsons website found here.
I've put them all on 1 long line as it states to do.
I've also manipulated a default registry value located at:
<code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Cryptography\Configuration\Local\Default\00010002
</code>
These are the same values I'm using from Gibsons site - on separate lines with no commas
My registry values change but I cannot get the SSL Configuration settings to display "Enabled"
Does anyone have insight on how to correct this issue?
Answer: Please make sure the SSL Cipher suites box does not exceed more than 1023 characters.

SSL Cipher Suite Order GPO


Unable to update android studio from 3.1 to 3.1.1

Question: I am trying to update android studio from 3.1 to 3.1.1 it showing below error while patch

Error Log
<code>java.io.IOException: Cannot delete: C:\Program Files\Android\Android Studio\lib\external-system-rt.jar
    at com.intellij.updater.Utils.tryDelete(Utils.java:108)
    at com.intellij.updater.Utils.access$000(Utils.java:15)
    at com.intellij.updater.Utils$1.visitFile(Utils.java:71)
    at com.intellij.updater.Utils$1.visitFile(Utils.java:68)
    at java.nio.file.Files.walkFileTree(Files.java:2670)
    at java.nio.file.Files.walkFileTree(Files.java:2742)
    at com.intellij.updater.Utils.delete(Utils.java:68)
    at com.intellij.updater.BaseUpdateAction.replaceUpdated(BaseUpdateAction.java:118)
    at com.intellij.updater.UpdateAction.doApply(UpdateAction.java:77)
    at com.intellij.updater.PatchAction.apply(PatchAction.java:201)
    at com.intellij.updater.Patch.lambda$apply$2(Patch.java:401)
    at com.intellij.updater.Patch.forEach(Patch.java:473)
    at com.intellij.updater.Patch.apply(Patch.java:392)
    at com.intellij.updater.PatchFileCreator.apply(PatchFileCreator.java:78)
    at com.intellij.updater.Runner.install(Runner.java:355)
    at com.intellij.updater.Runner.main(Runner.java:133)
</code>
Can anyone provide the solution for this
Comment: Have you looked at the log? There may be more details...
Comment: does your user has admin rights ?
Comment: Maybe it is not admin permission. Give permission to the folder.
Comment: @MattJones there is same error unable to delete lib\external-system-rt.jar
Comment: @Lucifer yes i have admin rights
Comment: ok, @MJM, close your studio, and try with run as administrator option.
Comment: @K.Sopheak permission to which folder?before this it's working fine
Comment: @Lucifer it's not working,i have updated the question with error log
Comment: try manually cut & paste that .jar file to d: and then retry with update
Answer: It's resolved after only restarting a system.


NTP offset between PDCe and DC (Both Hyper-V)

Question: I'm facing an issue, here is the context:

1 PDCe (192.168.1.3 and Hyper-V virtualized) is set as NTP server, its source for time is VM IC Time Synchronization.
1 DC (Hyper-V virtualized) is retrieving NTP informations from PDC, mentioned above, configured with: w32tm /config /manualpeerlist:192.168.1.3 /syncfromflags:domhier /reliable:yes /update

The problem is that there's a big delay between PDCe and DC (approx. 22secs, seen with w32tm /monitor, delay is called offset).
How can I manage to fix this annoying delay?
Answer:
Don't use a manual peer list if you're syncing from the domain hierarchy.
Sync your PDCe from an external time source - not the Hyper-V host.
Disable Hyper-V host time sync for your virtual DCs.
Comment: **For virtual machines that are configured as domain controllers, it is recommended that you disable time synchronization between the host system and guest operating system acting as a domain controller.**  - From this article dated August 2013.  So it isn't clear at all, Microsoft appears to have several conflicting recommendations.  http://technet.microsoft.com/en-us/library/virtual_active_directory_domain_controller_virtualization_hyperv(WS.10).aspx
Comment: Wrong on 3 - on 2012 R2 at least.... 2012 yes, 2012 r2 leave it running. It is smart enough to integrate well and it is needed for boot scenarios.
Comment: @TomTom do you have a link? I'm sure you're right, but the "Virtualizing Domain Controllers" TechNet article doesn't mention this.
Comment: 2012 r2 added a great deal of new features to allow domain controllers to just work. Including ability to use snapshots with automatic updating of the dc etc. time service http://blogs.msdn.com/b/virtual_pc_guy/archive/2010/11/19/time-synchronization-in-hyper-v.aspx is quite clear to never disable time service ;)


Firebase Cloud Notification shows 0 opens 0 clicks

Question: I have integrated Firebase Cloud Notifications for Push Notifications in my iOS App written in Swift.
Although, the notifications are working as expected and I can see the Number of Deliveries, It doesn't show the Open Count and Click Count.
I have searched for similar questions on StackOverflow but none of them has been answered yet.
As you can see in the screenshot below, the number of sends is being tracked but not Open Count or other things.
Any Help is Appreciated.
Answer: We had a similar issue and it was caused by the missing Firebase Analytics library.
Documentation for iOS:

Step 4: Add Firebase SDKs to your app
...
4. Choose the Firebase libraries you want to use.
If Google Analytics is enabled in your Firebase project, make sure to add
FirebaseAnalytics. For Analytics without IDFA collection capability, add
FirebaseAnalyticsWithoutAdId instead.

Documentation for Android:

Step 4: Add Firebase SDKs to your app
...
// Add the dependency for the Firebase SDK for Google Analytics
implementation 'com.google.firebase:firebase-analytics'

Google Analytics also has a setup guide in the Admin UI (Admin - Property - Data Streams, select the stream, click "SDK Setup Instructions"):


How to understand the spectral measure for the spectral representation of a wide-sense stationary process?

Question: Let {$a_n$} be a wide-sense stationary process and {$X_n$} be its spectral representation (discrete Fourier transformation? ).
Let $b_n$ be the covariance function of $X_n$.
According to the Bochner Theorem, there exists a measure $\rho$ defined on the borel sigma algebra on $R$ s.t.
$$ b(n) = \int_{[0, 1)}e^{2\pi i \lambda n}d\rho(\lambda)$$
How should I understand measure $\rho$?
Answer: It might be easier to instead look at $b(n)/b(0)$, which would then give $\frac{1}{b(0)}d\rho(\lambda)$ as your measure. This is now a CDF when you define $F(\lambda):=\frac{1}{b(0)}\rho([0,\lambda])$, and $b(n)/b(0)$ is the associated characteristic function. So then $\frac{1}{b(0)}d\rho$ becomes the spectral density. Explicitely $b(n)/b(0) = E[e^{inX}]$, where $X$ is, up to a constant multiple, the random variable whose distribution is the spectral density.
Comment: Thanks for the comment. Whats $\rho(\lambda)$ mean again? I thought it is only legit to write $d\rho(\lambda)$
Comment: Whoops. Dropped a $d$. Fixed


Flutter & Geocoder & Geolocator : How do I get the country name in English?

Question: I have been trying to get the phone location. And for reason, the geocoder gets the country name in Korean. The phone main language is in English anyway. But why do I get it in Korean tho?
<code>_getCurrentLocation() async {
      Position position =
          await getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

      final coordinates =
          new Coordinates(position.latitude, position.longitude);

      final addresses =
          await Geocoder.local.findAddressesFromCoordinates(coordinates);
      var first = addresses.first;
      print(first.adminArea);
      print(first.countryName);
    }
</code>
Console
<code>I/flutter ( 7221): We have Latitude: 37.4219983, Longitude: -122.084
I/flutter ( 7221): Latitude : 37.4219983 & Longtitude : -122.084
I/flutter ( 7221): California
I/flutter ( 7221): 미국
</code>
Please have a look and help me in this. Thank you.
Answer: Try This
<code> String _address = ""; // create this variable

void _getPlace() async {
 List<Placemark> newPlace = await
_geolocator.placemarkFromCoordinates(_position.latitude, _position.longitude);

// this is all you need
 Placemark placeMark  = newPlace[0];
 String name = placeMark.name;
 String subLocality = placeMark.subLocality;
 String locality = placeMark.locality;
 String administrativeArea = placeMark.administrativeArea;
 String postalCode = placeMark.postalCode;
 String country = placeMark.country;
 String address = "${name}, ${subLocality}, ${locality}, ${administrativeArea}
 ${postalCode}, ${country}";

 print(address);

  setState(() {
  _address = address; // update _address
   });
  }
</code>
Comment: i didnt find placemarkFromCoordinates , geolocator: ^8.2.1
Comment: ok...but how does it solve the problem? If the phones lang is not eng then the country name will be in another language like korean, or whatever the user set as default on their phones
Answer: Change your phone language. Or using a "first.countryCode".


Problem with system of equations $(x,y,z)$

Question: System of equations:
$$\begin{cases}\frac{x}{yz}+\frac{y}{zx}+\frac{z}{xy}=\frac{3}{xyz}\\xy+yz+zx=3\end{cases}$$
Solution:
$$\begin{cases}\frac{x}{yz}+\frac{y}{zx}+\frac{z}{xy}=\frac{3}{xyz}\\xy+yz+zx=3\end{cases}\Rightarrow\begin{cases}x^2+y^2+z^2=3\\xy+yz+zx=3\end{cases}$$
$x^{2}+y^{2}+z^{2}=xy+yz+zx$
$(x+y+z)^{2}-2(xy+yz+zx)=xy+yz+zx$
$(x+y+z)^{2}-2*3=3$
$(x+y+z)^{2}=9$
What should I do next?
Answer: Hint:
$$(x-y)^2+(y-z)^2+(z-x)^2=?$$
Alternatively, $$x^2-x(y+z)+y^2+z^2-yz=0$$
As $x$ is real, the discriminant must be $\ge0$
But $$(y+z)^2-4(y^2+z^2-yz)=-3(y-z)^2\le0$$
Answer: By the calculations you have made, your system is actually eqivalent to $$\begin{cases}x^2+y^2+z^2=3\\(x+y+z)^2=9\end{cases}$$Which is, at the same time, equivalent to the systems $$\begin{cases}x^2+y^2+z^2=3\\x+y+z=3\end{cases} \quad \begin{cases}x^2+y^2+z^2=3\\x+y+z=-3\end{cases}$$But you can check using the distance formula between a point and a plane (or in many other ways) that the planes $x+y+z=3$ and $x+y+z=-3$ are both tangent to the sphere $x^2+y^2+z^2=3$, so the only solutions are $x=y=z=\pm1$
Answer: For the system $\begin{cases}x^2+y^2+z^2=3\\x+y+z=3\end{cases}\quad$ just offset the variables $\begin{cases}x=1+X\\y=1+Y\\z=1+Z\end{cases}$
Then you get $\begin{cases}3+X+Y+Z=3\\3+2X+2Y+2Z+X^2+Y^2+Z^2=3\end{cases}\implies X^2+Y^2+Z^2=0$
Which in the real domain has only the $(0,0,0)$ solution.
For $x+y+z=-3$ proceed similarly with $x=X-1,y=Y-1,z=Z-1$.


Calculate $\lim_{x \to 0} (e^x-1)/x$ without using L'Hôpital's rule

Question: Any ideas on how to calculate the limit of $(e^x -1)/{x}$ as $x$ goes to zero without applying L'Hôpital's rule?
Comment: Some of the answers in other posts might answer your question. For example, see these questions: http://math.stackexchange.com/questions/152605/proving-that-lim-limits-x-to-0-fracex-1x-1, http://math.stackexchange.com/questions/403876/show-that-lim-limits-x-to0-fracex-1x-1
Comment: $x\leq e^x-1 \leq xe^x$ an squeeze theorem
Comment: Do you know what is the derivative of $x\mapsto e^x$?
Comment: the basic fact is $e$ is defined as either $\lim_{n\to\infty}(1+1/n)^n$ or $\sum_{k=0}^{\infty}k!^{-1}$
Answer: Using Bernoulli's Inequality, for all $x$ so that $|x|\le n$,
$$
1+x\le\left(1+\frac xn\right)^n\tag{1}
$$
Therefore, letting $n\to\infty$, we get for all $x$,
$$
1+x\le e^x\tag{2}
$$
Furthermore, for $|x|\lt1$,
$$
1-x\le e^{-x}\implies\frac1{1-x}\ge e^x\tag{3}
$$
Thus, subtracting $1$ from $(2)$ and $(3)$ gives
$$
x\le e^x-1\le\frac x{1-x}\tag{4}
$$
Since we are looking for the limit as $x\to0$, assume that $|x|\lt1$. Whether $x$ is positive or negative, $(4)$ says that
$$
\frac{e^x-1}{x}\text{ is between $1$ and }\frac1{1-x}\tag{5}
$$
Therefore, by the Squeeze Theorem, we get
$$
\lim_{x\to0}\frac{e^x-1}{x}=1\tag{6}
$$
Answer: I don't know if this is really "without" Hôpitals rule for you but if you are allowed to use
$$
\exp(x)=\sum_{k=0}^\infty \frac{x^k}{k!}
$$
the limit is straightforward since this sum converges locally uniformly.
Answer: Observe that when $x$ is very small near $0$, we have:
If $x > 0 \Rightarrow 1+x < e^x < 1 + x + 2x^2 \to 1 < \dfrac{e^x-1}{x} < 1 + 2x$, and letting $x \to 0^{+}$, we have: $\displaystyle \lim_{x \to 0^{+}} \dfrac{e^x-1}{x} = 1 \tag{1}$,
and for $x < 0 \Rightarrow 1 > \dfrac{e^x-1}{x} > 1 + 2x$, and letting $x \to 0^{-}$, we have:
$\displaystyle \lim_{x\to 0^{-}} \dfrac{e^x-1}{x} = 1 \tag{2}$.
$(1),(2) \Rightarrow \displaystyle \lim_{x \to 0} \dfrac{e^x-1}{x} = 1$.
Answer: $$e^x=1+x+1/2x^2+\cdots$$
$${e^x-1\over x}={x+x^2/2+\cdots\over x}=1+\frac12x+\cdots$$
$$\lim_{x\to0}{e^x-1\over x}=\lim_{x\to0}1+\frac12x+\cdots=1.$$


golang fiber defer os.Remove() not called

Question: In my golang project I need to delete a file once it has been downloaded by user. I use defer but it is not called after download so the file is not deleted. The code is as follows:
<code>func (h *Handler) Download(c *fiber.Ctx) error {
    filename := c.Query("filename")
    c.Attachment(filename)
    tempFile := filepath.Join(os.TempDir(), filename)

    //Open the file for reading
    file, err := os.Open(tempFile)
    if err != nil {
        return err
    }
    //delete the file when everything is done, not working
    defer os.Remove(tempFile)

    //read the file
    b, err := ioutil.ReadAll(file)
    if err != nil {
        return er.Wrap(err)
    }

    //close the file explicitly after reading
    err = file.Close()
    if err != nil {
        return er.Wrap(err)
    }

    //also I tried to delete the file explicitly but keep getting error saying that the file is being used by another process
    //os.Remove(tempFile)
    //send the file to user
    return c.Send(b)
}
</code>
Any ideas how to fix it would be welcome. Thank you.
Answer: mybe os.Remove return a error,eg. tempFile's path is error
use follow code to see the error
<code>    defer func() {
        err := os.Remove(tempFile)
        if err != nil {
            fmt.Printf("%v\n", err)
        }
    }()
</code>


Form calculations, only first field works

Question: I need to sum all prices and multiply them with quantity. Problem is that only first field calculates good, others take price value of first. Help please
This is were I came for now:

$('.orderForm__item').on('input', function() {
  var totalSum = 0;
  $('.quantity, .price').each(function() {
    var quantity = $(this).val();
    var price = $('.price').attr('value');

    if ($.isNumeric(quantity)) {
      totalSum += parseFloat(quantity) * parseFloat(price);
    }
  });
  $('#total').text(totalSum);
});

<form id="form" class="orderForm">

    Item
    <input min="0" max="99" type="number" class="quantity" name="quantity" />

    (1.70 KM)

    Item
    <input min="0" max="99" type="number" class="quantity" name="quantity" />

    (3.0 KM)

    Item
    <input min="0" max="99" type="number" class="quantity" name="quantity" />

    (15 KM)

    Item
    <input min="0" max="99" type="number" class="quantity" name="quantity" />

    (1.70 KM)

</form>
Total: <output id="total"></output>
Answer: You should each for orderForm__item and find quantity, price per item:

$('.orderForm__item').on('input', function() {
  var totalSum = 0;
  $('.orderForm__item').each(function() {
    var quantity = $(this).find('.quantity').val();
    var price = $(this).find('.price').attr('value');

    if ($.isNumeric(quantity)) {
      totalSum += parseFloat(quantity) * parseFloat(price);
    }
  });
  $('#total').text(totalSum);
});

<form id="form" class="orderForm">

    Item
    <input min="0" max="99" type="number" class="quantity" name="quantity" />

    (1.70 KM)

    Item
    <input min="0" max="99" type="number" class="quantity" name="quantity" />

    (3.0 KM)

    Item
    <input min="0" max="99" type="number" class="quantity" name="quantity" />

    (15 KM)

    Item
    <input min="0" max="99" type="number" class="quantity" name="quantity" />

    (1.70 KM)

</form>
Total: <output id="total"></output>


Function to provide a default value when working with std::map

Question: I am trying to write a function, which will give me a default value when the key is not inside a std::map. In all cases will my default value be numerical_limit::infinity().
Hovewer this simple example is not working.
#include <iostream>
#include <map>
#include <limits>

template<typename KeyType, typename ValueType>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const KeyType & key)
{
    if(!map.contains(key))
    {
        return std::numeric_limits<ValueType>::infinity();
    }
    else
    {
        return map[key];
    }
}

int main()
{
    std::map<std::string, int> map;
    auto el = mapDefaultInf(map, "alexey");
    std::cout << el << std::endl;

    return 0;
}

Error is:
main.cpp:29:42: error: no matching function for call to 'mapDefaultInf(std::map, int>&, const char [7])'

Can someone help me understand the error.
Thanks in advance.
Comment: `std::numeric_limits::infinity()` is not meaningful for non-floating point types (more specifically those that do not have `std::numeric_limits:has_inifinity == true`). I think you might intend it to be `std::numeric_limits::max()` for such types.
Answer: You have constrained your template too much, as it is written it requires the keys in the map to be the of the same type as key parameter.
That fails because your map stores std::string but you pass a string literal which technically has a type of const char[7].
Just make the header:
template<typename KeyType, typename ValueType,typename T>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const T& key)

It will allow implicit conversions to take place at map.contains(key) call and will just fail with more complicated error message if you pass it an incompatible type. It's not like the current error is a pinnacle of readability anyway.
Comment: I tried a more complicated `ValueType mapDefaultInf(const std::map & map, const typename std::map::key_type & key)` signature, which removed the requirement for `typename T`, but is harder to read. I like yours better. Be sure to note in your answer that `std::map::operator[]` will fail on `const std::map` types, so they need to use `std::map::at`.
Comment: @JohnFilleau I'll admit, I did not try to run the code, thanks about `[]`. Yea, nice idea, it enables implicit casts and makes the type inside the function fixed.
Answer: First of all you use operator[] on the map object inside the function.  That will never be allowed because it is a non-const function and you have passed the map by const reference.  Instead you should rewrite the function implementation to use iterators:
template<typename KeyType, typename ValueType>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const KeyType & key)
{
    const auto it = map.find(key);
    return it != map.end() ?  it->second : std::numeric_limits<ValueType>::infinity();
}

Second of all you have an ambiguity in the key type.  You need to pass in a std::string.  Like this:
auto el = mapDefaultInf(map, std::string("alexey"));

Comment: This answer works so I upvoted it, but Quimby's allows the user to not have to manually translate everything to a string.
Comment: Oh I agree with Quimby in that regard.  I was just trying to keep it simple (and I didn't want to steal his answer!)
Comment: @Joe Nice catch about `[]`, feel free to "steal" from me in the future ;)


variational inference with KL

Question: i am self-studying variational inference - and in Murphy's book "A probabilistic perspective on machine learning" it is discussed that minimizing the forward KL divergence (which is stated to be zero-avoiding for q) $$KL (p||q) = \sum\limits_{x} p(x)log \frac {p(x)}{q(x)}$$ gives different results than minimizing the reverse KL divergence $$KL (q||p) = \sum\limits_{x} q(x)log \frac {q(x)}{p(x)}$$ (which is stated to be zero-forcing for q). It is subsequently linked to the diagrams per below. I was hoping whehter someone can share the intuition on how the formulas for reverse and forward KL lead to the different approximations per below.
Answer: The KL divergences can be seen as a product of a weighting function $w(x)$ and a penalty function $g(x)$, i.e. $KL(q||p) = \sum_x w(x)g(x)$ with $w(x) = q(x)$ and $g(x) = \log\frac{q(x)}{p(x)}$ in the case of the reverse KL divergence. Whenever the weighting function is close to zero, i.e. $w(x) \approx 0$, the product of $w(x)g(x)$ is also close to zero and the value of the penalty function $g(x)$ does not contribute to the KL divergence no matter how large it is.
Consider first the case of reverse KL divergence. When $q(x)$ is close to zero, the penalty term $g(x) = \log\frac{q(x)}{p(x)}$ is ignored and therefore the reverse KL divergence ''ignores'' the portion of $p(x)$, which is not covered by $q(x)$. On the other hand, when $q(x)$ has significant mass and $p(x)$ is close to zero the penalty term $g(x)$ will be large. Therefore the reverse KL divergence discourages situations where $q(x)$ is high and $p(x)$ is small leading to the ''zero-forcing''-effect.
We can now make a similar analysis of the ''forward'' KL divergence. Now the weighting function corresponds to the target distribution $p$, i.e. $w(x) = p(x)$. Thus, when $p(x) \approx 0$ the value of the penalty $g(x) = \log\frac{p(x)}{q(x)}$ is largely ignored. Thus, there is almost no cost of having large $q(x)$ when $p(x)$ is small. On the other hand we see that when $p(x)$ has significant mass and $q(x)$ is small the contribution to the KL divergence is large. Combining these two properties leads to the ''zero-avoiding'' property.
Comment: super helpful. i now understand how hence in one case q(x) can cover parts of the space where p(x) has no density, and where in other cases, through the cost involved, the algo will avoid this.

variational inference with KL


Using localToGlobal to switch image positions

Question: I am trying to convert from coordinates of a parent container to global stage coordinates. This is the object and the container:
 imgSprite.addChild(imgInstance); //imgInstance is imported from class
 imageContainer.addChild(last);
 imageContainer.addChild(imgSprite); // imgSprite and last are to be replaced

Basically, I want to switch positions of two images in imageContainer.
I applied the localToGlobal() function, but that hasn't had any effect. What did I do wrong?
This is my function that replaces them. Note: this code belongs to class main, parent of container is stage and every imgSprite is just added to imgContainer and moved via obj.x, obj.y (not in the code).
function click(e:MouseEvent):void {
    var p1:Point = e.currentTarget.localToGlobal(newPoint(e.currentTarget.x, e.currentTarget.y));
    var p2:Point = last.localToGlobal(new Point(last.x, last.y));
    e.currentTarget.x = globalToLocal(p2).x;
    e.currentTarget.y = globalToLocal(p2).y;
    last.x = globalToLocal(p1).x;
    last.y = globalToLocal(p1).y;
}

As I understand it, every object has local and global positions. So, here I convert a local position to a global, and then again when moving the other object to this position, I convert it to local, as they belong to the same parent it should result in matching coordinates, but my images start flying around in all directions and I start pulling my hair.
Answer: var p2:Point = last.localToGlobal(new Point(last.x, last.y));

should be
var p2:Point = last.localToGlobal(new Point(0, 0));

The Point argument within localToGlobal() is the point within the DisplayObject that you want to globalize. So if last is located at (50,50) within its parent container, your code is really asking for the global coordinate of (50,50) within last. In this case, (0,0) is (last.x, last.y).


I can't figure out how to use Apache Ivy

Question: I want to have a JAR file repository on my local network so all other Eclipse users use the same JAR files in Repository for their dependencies. I don't want Maven or Ant, I just want to use Ivy to share my JAR files, how do I do this? which XML file should I use? Can't find a simple solution online.
Comment: The best way to manage a shared repository is to install something like Sonatype Nexus. The alternative is of course ivy which can build and use a repository, but which require a shared ivy settings file. For an example see: http://stackoverflow.com/questions/1200762/good-ivy-tutorial-for-local-repository/2279596#2279596 This example can be expanded to use alternative resolvers like ssh or sftp for operation over a network
Answer: For start here is an example of ivy.xml file
<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="[your organization]"
        module="your module[for example commons-io]"
        status="integration">
    </info>
    <publications>
        <artifact name="[your jar name]" ext="jar"/>
    </publications>

Second an important step is creating an ivy.settings file.
<ivysettings>
  <resolvers>
    <filesystem name="public">
      <ivy pattern="/path/to/my/public/rep/[organisation]/[module]/ivy-[revision].xml" />
      <artifact pattern="/path/to/my/public/rep/[organisation]/[module]/[artifact]-[revision].[ext]" />
    </filesystem>
  </resolvers>
</ivysettings>

This is just part of the ivy.setting file and the resolver name should represent
your own repository for publications and downloading jars from your  local network .
Read more about Adjusting ivy settings on http://ant.apache.org/ivy/history/2.1.0/tutorial/defaultconf.html
.
How ever ivy can't do the publish work for you ,and you will have to use ant
just small build.xml file .
Read on apache site http://ant.apache.org/ivy/history/2.2.0/use/publish.html
I hope it will be helpful.