AWS CDK receiving Object Created event through EventBridge and trigger Lambda

Question: I'm trying to use EventBridge to trigger a Lambda function whenever a new object is uploaded to a specific Bucket. My CDK code is:
import { StackProps } from "aws-cdk-lib";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as iam from "aws-cdk-lib/aws-iam";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as events from "aws-cdk-lib/aws-events";
import * as targets from "aws-cdk-lib/aws-events-targets";
import * as lambdaEventSources from "aws-cdk-lib/aws-lambda-event-sources";

import { Construct } from "constructs";

export interface TServiceStackProps {
  bucketName: string;
}

export class TranscriptionServiceStack extends Construct {
  // Allow access to the counter function
  public readonly inputBucket: s3.Bucket;
  public readonly outputBucket: s3.Bucket;

  constructor(scope: Construct, id: string, props: TServiceStackProps) {
    super(scope, id);
    /**
     * Create input bucket where videos TO BE transcribed get uploaded.
     */
    this.inputBucket = new s3.Bucket(this, "InputBucket", {
      bucketName: props.bucketName + "-inputs",
      eventBridgeEnabled: true,
    });
    /**
     * Create output bucket where transcribe results get stored.
     */
    this.outputBucket = new s3.Bucket(this, "OutputBucket", {
      bucketName: props.bucketName + "-outputs",
    });
    /**
     * Create iam statement for transcribe admin policy.
     */
    const adminTranscribePolicyStatement = new iam.PolicyStatement({
      effect: iam.Effect.ALLOW,
      actions: ["transcribe:*"],
      resources: ["*"],
    });
    /**
     * Handler function for QUEUING jobs, handling status updates, and saving results.
     */
    const transcribeHandler = new lambda.Function(this, "TranscribeHandler", {
      runtime: lambda.Runtime.NODEJS_14_X,
      code: lambda.Code.fromAsset("lambda/transcribe-service"),
      handler: "transcribe.handler",
      environment: {
        INPUT_BUCKET_NAME: this.inputBucket.bucketName,
        OUTPUT_BUCKET_NAME: this.outputBucket.bucketName,
      },
    });
    /**
     * Associate transcribe policy with lambda handler
     */
    transcribeHandler.role?.attachInlinePolicy(
      new iam.Policy(this, "TranscribeAdminPolicy", {
        statements: [adminTranscribePolicyStatement],
      })
    );
    /**
     * Rule for detecting a new object uploaded to input bucket.
     */
    new events.Rule(this, "InputBucketUploadRule", {
      description: "Watches for s3 object:put events.",
      eventPattern: {
        source: ["aws.s3"],
        detailType: events.Match.equalsIgnoreCase("object created"),
        detail: {
          bucket: {
            name: [this.inputBucket.bucketName],
          },
        },
      },
      targets: [new targets.LambdaFunction(transcribeHandler)],
    });
    /**
     * Rule for detecting status updates from Transcribe service.
     */
    new events.Rule(this, "TranscribeEventRule", {
      description: "Watches for Transcribe state events.",
      eventPattern: {
        source: ["aws.transcribe"],
        detailType: events.Match.equalsIgnoreCase(
          "Transcribe Job State Change"
        ),
        detail: {
          TranscriptionJobStatus: [
            "COMPLETED",
            "FAILED",
            "QUEUED",
            "IN_PROGRESS",
          ],
        },
      },
      targets: [new targets.LambdaFunction(transcribeHandler)],
    });
    /**
     * Handler gets to read and delete objects from inputBucket
     */
    this.inputBucket.grantReadWrite(transcribeHandler);
    this.inputBucket.grantDelete(transcribeHandler);
    /**
     * Handler gets to read objects from inputBucket
     */
    this.outputBucket.grantReadWrite(transcribeHandler);
  }
}

Whenever I upload a new object to the inputBucket, there are no events being triggered or observed by CloudWatch (or the specific EventBridge resource).
Any idea what I'm missing?
Comment: have you checked that in s3 aws console, the properties tab/ EventBridge is showing `on`?
Comment: Yeah, when I go into the Console and look at the bucket, it says "Send notifications to Amazon EventBridge for all events in this bucket: On"
Answer: After diving deeper into the docs I found that you need to create a CloudTrail resource for collecting these events and then add the relevant event sources to the trail.
    /**
     * Create a CloudTrail resource for capturing events.
     */
    const eventsTrail = new cloudtrail.Trail(this, "TranscriptionServiceTrail");
    /**
     * Add S3 selector for input bucket's object created events.
     */
    eventsTrail.addS3EventSelector(
      [
        {
          bucket: this.inputBucket,
        },
      ],
      {
        readWriteType: cloudtrail.ReadWriteType.WRITE_ONLY,
      }
    );

Adding the following to my stack enabled the EventBridge to start receiving events and triggering my lambda.
Comment: Thanks Sebastian! Do you have the doc where you found that?
Answer: If anyone doesn't want to enable CloudTrail, another option is s3 event notification. Currently, it support Lambda, SNS and SQS
Example
this.inputBucket.bucket.addEventNotification(
     s3.EventType.OBJECT_CREATED_PUT,
     new s3n.LambdaDestination(transcribeHandler )
    )

ref: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_notifications-readme.html


Swift zoom with scrollview not centered

Question: When setting (selected by taking a picture) the image of my imageview (which is inside a scrollview) is set but a little to the right and not centered as is supposed to be
Im not using storyboard, everything is made programmatically
//creating frames
    imgBorder.frame.size = CGSize(width: view.bounds.size.width * 0.7,     height: view.bounds.size.height * 0.7)
        imgBorder.center.x = self.view.bounds.width * 0.5
        imgBorder.center.y = self.view.bounds.height * 0.5
        imgBorder.image = UIImage(named: "imageBorder")
        self.view.addSubview(imgBorder)
        self.view.bringSubviewToFront(imgBorder)
<code>    scrollImg.delegate = self
    scrollImg.frame = CGRect(x: view.bounds.size.width * 0.5 -     imgBorder.frame.size.width/2, y: view.bounds.size.height * 0.5 - imgBorder.frame.size.height/2, width: imgBorder.bounds.size.width, height: imgBorder.bounds.size.height)
    scrollImg.minimumZoomScale = 1.0
    scrollImg.maximumZoomScale = 6.0

    self.view.addSubview(scrollImg)

    imgPicture.frame.size = scrollImg.frame.size
    imgPicture.center.x = scrollImg.center.x
    imgPicture.center.y = scrollImg.center.y

    scrollImg.addSubview(imgPicture)
</code>
First image shows when i take the picture (the problem in this post)
Second shows the picture im taking
Third shows that zoom is working fine with border limits
Answer: I was able to fix the problem removing these lines of code:
<code>imgPicture.center.x = scrollImg.center.x
imgPicture.center.y = scrollImg.center.y
</code>

Swift zoom with scrollview not centered


Am I understanding this proof correctly regarding that there does not exist a polynomial such that $p(0), p(1),\dots$ are all prime?

Question: Proposition: There does not exist a polynomial $$P(x)=a_0+a_1x+\dots+a_nx^n$$ with integer coefficients and of degree at least $1$ such that $P(0), P(1),P(2),\dots$ are all prime numbers.
Proof: Assume the contrary and let $P(0)=p, p$ prime. Then $a_0=p$ and $P(kp)$ is divisible by $p$ for all $k\ge 1$. Because we assumed these numbers were prime, it follows that $P(kp)=p$ for $k\ge 1$. Therefore, $P(x)$ takes on the same value infinitely many times. A contradiction. Hence the conclusion.
Am I understanding this correctly that $k$ is either real or rational and by the last line they mean that this is the constant function as we could write any real number $r$ as $\frac r p \cdot p$ and thus getting the result?
Edit: If $k$ is supposed to be an integer, then what happens when $x$ equals other prime numbers? It doesn't seem to be the constant function in that case.
Also, is this a good way to write a proof in which verification of crucial parts of the argument are left to the reader?
Comment: $k$ is an _integer_. This relies on the result that a nonconstant polynomial never takes on the same value infinitely many times, which it assumes the reader already knows. (For a hint, first prove a nonzero polynomial of degree $n$ can't hit zero more than $n$ times. Use the fact that if $p(a)=0$, then $x-a$ is a factor of $p(x)$.)
Answer: Well, if you plug in $x=kp$ for some $k\in\mathbb N$, you will get that $$P(kp) = p + a_1kp + \ldots + a_nk^np^n.$$ Notice that this means $$P(kp) = p(a_1k + \ldots + a_nk^np^{n-1})$$
where $(a_1k+\ldots+a_nk^np^{n-1})$ is an integer. But $kp$ is a natural number, so $P(kp)$ must be prime by the hypothesis. This is crucial: if $k$ could be any real number, we could not say that $P(kp)$ must be prime and get a contradiction.
You are correct in saying this must mean $P$ is a constant function. This is due to the fundamental theorem of algebra, as otherwise $P(x) - p$ would have infinitely many roots.
Comment: My only problem with it being the constant function is that this only holds for multiples of $p$ and not other prime numbers as that case is never discussed.
Comment: If a polynomial is constant at infinitely many points, it *must* be constant everywhere else: therefore, this case is sufficient to determine all of the other cases. This is due to the fundamental theorem of algebra. If $P(x) = p$ for infinitely many $x$, then $P(x) - p = 0$ for infinitely many $x$. Therefore, by the fundamental theorem of algebra, $P(x) -p= 0$ for all $x\in\mathbb R$, so $P(x) = p$ for all $x\in\mathbb R$. I hope this helps :)
Answer: The proof as written in the OP is confusing. This is how I would write it.
For completeness: For $P(x)$ to be prime for each integer $x$, it follows that $P(0)=a_0$ must be prime, and so $a_0$ must be prime. But consider $P(ka_0)$ for any integer $k$. Then you can check that for each such $k$, that $P(ka_0)$ is a multiple of $a_0$. [Indeed, $$P(ka_0)=$$ $$a_0+a_1(ka_0)+\ldots a_n(ka_0)^n$$ so $P(ka_0)$ is a sum of $n+1$ terms all divisible by $a_0$, so from this it follows that $P(ka_0)$ then must also be divisible by $a_0$.] So for $P(ka_0)$ to be prime, it follows that $P(ka_0)$ must be $a_0$ itself for all integers $k$, or there is an integer $x=ka_0$; $k$ an integer; such that $P(x)$ is a multiple of $a_0$ but not $a_0$ itself and is thus $P(x)$ is not prime.
So now suppose $P$ has positive degree, and write degree$(P)=n$. Then there are only at most $n$ integers $k$ such that $P(ka_0)$ is actually $a_0$ itself. [Otherwise the polynomial $P(x)-a_0$ is also a polynomial of positive degree $n$ and would have more than $n$ roots which is impossible.] This must mean that if $P$ has positive degree $n$, there is an integer $k$ such that $P(ka_0)$ is a multiple of $a_0$ but not $a_0$ itself so there is an integer $x=ka_0$ such that $P(x)$ is not prime.
So if $P$ is such that $P(x)$ is prime for all integers $x$, then $P$ must have degree $0$ i.e., $P(x)=a_0$ for all $x$. And so [also noted in the top paragraph] $a_0$ itself must be prime.
Comment: Thanks a lot for the proof!!. This makes it way more easier to understand the proof. I also felt that the proof was not written in a clear enough way which lead me to ask this question.
Answer: $k$ is a integer.
If a  polynomial equation $Q(x)=0$ has infinitely many solutions then $Q(x)=0$ for all $x$. In fact, if it has more than $n$ roots, where $n$ is the degree of $Q$ then $Q(x)=0$ for all $x$. Apply this to $Q(x)=P(x)-p$.  Since the degree of $P$ is at least $1$ we have reached a contradiction.
Answer: No, $k$ is an integer. The proof uses the fact that a polynomial of degree $n$ is defined uniquely by it's evaluation in $n+1$ points.
Comment: In particular, knowing $P(0),\cdots,P(np)=p$ is enough to conclude $P(x)=p$.


Files deleted but not subfolders

Question: Need to purge out the contents of a folder, forcing everything to get cleaned out.
Hmm, why would the subfolders not be removed from within testdir1?
$pathvar = "D:\temp\testdir1"
Get-ChildItem -Path $pathvar -Include *.* -File -Recurse | foreach { $_.Delete()}

Comment: `-File` only returns files. You must remove that parameter if you want to return files and directories.
Answer: AdminOfThings is correct. -File only grabs file just as -Directory only grabs folders. Not specifying one of them will grab files and folders.

Files deleted but not subfolders


How to fix on loading spring-context?

Question: What is the possible reason annotation from spring-context cannot be found? I already called spring context on my pom file, but upon calling org.springframework.stereotype.Repository my eclipse cannot find it.
Any help is much appreciated.
Below is my configuration and how I call it.
Comment: Please consider **copy/paste your code into your question** instead of using what it seems to be a picture of your screen taken with your smartphone? It's for search engine... Please...
Answer: The class is definately in that package, try to:

Right click on project -> Maven -> Update project..
Project -> Clean

If that does not help.. then remove the project and import it again as a maven project.
Comment: Thank you very much @Maciej Kowalski. It Now workes.

How to fix on loading spring-context?


Does Weblogic/Glassfish guarantees the order of application deployment?

Question: Java EE 5 does not guarantee any application deployment ordering.
This feature was introduced in Java EE 6.
We use Oracle WebLogic 10.3.2 and it is Java EE 5 compliant.
We also use GlassFish 3.
We have an ear with several war files.
As I can see both WebLogic and GlassFish start the applications in the order in which they are specified in application.xml.
Is this the way how WebLogic/GlassFish deploy applications from an ear?
Or could the order be different from time to time?
Answer: I don't know how it's implemented internally, at least from my experience WebLogic always start modules inside an ear as the order they're specified in application.xml.
In our project there is dependency between some modules so we adjust their order in application.xml to make sure the one being depended is loaded at first.


MVC MultiSelectList default value ignored

Question: I am trying to create a multiselect list and specify the default values for the dropdown, but the default values I am providing are being ignored.
My controller looks like this:
var ProvisionFromDb = (from Provision in db.Provisions
                      orderby Provision.Provision1 ascending
                      select new SelectListItem
                          {
                              //select all items
                              Selected = true,
                              Text = Provision.AltDescription,
                              Value = Provision.Provision1.ToString()
                          }).ToList();
ViewBag.ProvisionDropdown = new MultiSelectList(ProvisionFromDb, "Value", "Text");

In my view, I have the following statement:
@Html.ListBox("ProvisionId", (MultiSelectList)ViewBag.ProvisionDropdown)

Everything works, except for the default values not being selected. I assume this is because of MultiSelectList not recognizing the selected property in the SelectList objects.
What is the simplest way to correct this?
Additional info: In the razor view statement, "ProvisionId" represents the name/ID of the select dropdown that is being created.
Comment: If `ProvisionId` is a property in your model, then setting the `Selected` property of `SelectListItem` is ignored (its the value of `ProvisionId` which determines whats selected)
Answer: The solution here was to put the defaults into an overloaded MultiSelectList constructor, where the 4th parameter is an array representing values of the default selected items.
In my case, I did not need to define a model. The following worked:
ViewBag.ProvisionDropdown = new MultiSelectList(ProvisionFromDb, "Value", "Text", new[] {"Selected Value1","Selected Value2"});

A linq query could have also been used to generate this array based on the "Selected" property of SelectListItem.
Answer: The options rendered as selected are determined by the value of what you're binding to. Here, namely, "ProvisionId". If that's a property on your model, you should use ListBoxFor instead and then set it to the list of Provision1 values you want to be selected. If it's not a property on your model, you can set something like ViewBag.ProvisionId with that list.


Number of solutions of $x^2+y^2=1 \mod p^2$ with prime $p=3\mod 4$

Question: I am asked to find the number of solutions of $x^2+y^2=1 \mod p^2$, with $p=3 \mod 4$ prime.
I thought a possible way was to apply Hensel's lemma, to shift the $\mod p$ solutions to $\mod p^2$ solutions, but I am not able to conclude my argument. Can someone help me?
Comment: Do you know how many solutions there are (mod $p$), to start?
Comment: What have you tried? The lifting seems straightforward.
Comment: how many solutions mod $p \; ? \;$
Answer: Suppose we have $ x^2 + y^2 = -1 \pmod{p}$.
We want to lift it to a solution, namely:
$$ -1 \equiv (x+k_y p)^2 + (y+k_yp)^2 \equiv x^2 + y^2 + 2(k_xx + k_yy)p \pmod{p^2}.$$
This happens when $k_x + k_y = A$ (for you to determine).
Hence, with every initial solution in mod $p$, there are $B$ (for you to determine) solutions in mod $p^2$.
Comment: Since we start from $x^2+y^2=1 \mod p$, I think the lifting provides $1\equiv (x+k_x p)^2+(y+k_y p)^2\equiv x^2+y^2+2p(k_x x + k_y y)\mod p^2$; am I wrong?
But then how can I continue?
Comment: @Stan Oh yes, you're right about the calculation. How can you continue? What condition needs to be satisfied?
Comment: Well, you want $ 2(k_x x + ky y)\equiv 0 \pmod{p}$ as the condition right? So if $ p\neq 2, xy\neq 0$, then how many solutions can do you get?


Angular form select option value equals option text

Question: I'm using this example of nested cascading selects http://jsfiddle.net/jhsousa/Mekhy/ ... I've got it in a form which when submits emails the values of the select options through. I've added NAME="" and ID="" to achieve this. However only a number is sent through.
How can I get the selected option .value to equal the .text which it is populated by?
This is my first experience with Angular so not having any joy.
I tried adding:
    obj.value as obj.text for obj in array
to the ng-options. But the entire thing stopped working because ng-options already has a value.
Thanks.
Answer: There is no NICE way to get the text.
The only way is to activate a function call that loop through the Dropdown options elements and find the correct ID and extract the text from the optons.
Comment: I thought it might need to be done using the event for selecting an option.    'ng-change="changeContinent()"'


"in jquery before function on click function not working

Question: I am adding html form with jquery function in wordpress using before function but in html code click event is not working
I am using on click function but may be not getting idea about delegate
jQuery(document).ready(function( $ ){
  $("#slider-6-layer-11").before("
<form action='#' class='form-horizontal' style='display: inline-flex;'><select style='width: 350px;font-size:30px;color: #888484;font-weight: 600;' class='form-control' name='type'><option class='form-control new' value='i am'> I am a</option><option id='container' class='form-control'  value='rentar'>Rentar</option><option class='form-control expand' value='buyer'>Buyer</option><option class='form-control expand' value='seller'>Seller</option></select><button id='mybutton' type='submit' style='display:inline-flex;height:50px;'></button></form>
");
 $('.new').on('click',function () {
    alert("Hello!");

  });
});

dont getting classname='new' don't know why
Comment: `classname` is not a valid attribute for setting `class` - It comes from react which takes that prop and set the `class` attribute as that value
Comment: [Event handler not working on dynamic content [duplicate]](https://stackoverflow.com/questions/15090942/event-handler-not-working-on-dynamic-content)
Answer: Use change event on <select> instead since events aren't supported on <option> cross browser
$('#search select').on('change',function () {
   if($(this).find(':selected').hasClass('new')){
      alert('Hello')
   }
});


Como funciona o switch por baixo dos panos?

Question: Vendo esses comentários sobre o uso do switch fica a dúvida como ele funciona mesmo e porque ele é diferente do if quando apenas comprar pela igualdade de uma variável única contra uma sequência de valores.
Como isso é compilado?
Ele deve ser preferido ao if?
Answer: Como isso funciona é detalhe de implementação, não é especificado e você não pode se valer disto para fazer algo que só funcione se for implementado de uma forma específica.
O que nós sabemos é que o compilador faz o melhor possível para otimizar o seu uso. Nem sempre ele consegue ou é viável, por isso não há garantias do que ocorrerá. Ele pode funcionar de forma análoga ao if em alguns casos, mesmo que não exatamente da mesma forma.
Mas ele vai tentar gerar uma tabela de desvios (branch table). Com isso ele precisa fazer só uma comparação e pode achar o endereço que ele deve dar um salto na execução de acordo com uma tabela, mais ou menos como um array.

Obviamente precisa ser uma comparação simples com dados simples,
deve ser denso, ou seja, não pode ter muitas lacunas entre os valores possíveis. Mesmo que não tenha algo a executar para um valor no meio da sequência, ele precisa criar um espaço na tabela para ele. Se tiver muitas lacunas o espaço ocupado pela tabela pode ser grande demais,
precisa ter um número mínimo de opções para compensa a tabela,
não ocorre desvios durante cada bloco de case.

Tem uma série de detalhes que pode variar em cada caso, mas a ideia é que uma busca que poderia levar tempo O(n), passe levar O(1). Obviamente que um bom compilador considera a arquitetura alvo e gera o código que é mais adequado para ela.
Internamente ele funciona muito como um polimorfismo.
Não ligue para os detalhes não importantes para esse assunto nos códigos abaixo.
Se criarmos um switch para pegar nomes de meses poderemos ver qual o Assembly gerado:
#include <string.h>
#include <stdlib.h>
char *mes(int i) {
  char *texto = (char *)malloc(10);
    switch (i) {
      case 0:
        strcpy(texto, "janeiro");
        break;
      case 1:
        strcpy(texto, "fevereiro");
        break;
      case 2:
        strcpy(texto, "marco");
        break;
      case 3:
        strcpy(texto, "abril");
        break;
      case 4:
        strcpy(texto, "maio");
        break;
      case 5:
        strcpy(texto, "junho");
        break;
      case 6:
        strcpy(texto, "julho");
        break;
      case 7:
        strcpy(texto, "agosto");
        break;
      case 8:
        strcpy(texto, "setembro");
        break;
      case 9:
        strcpy(texto, "outubro");
        break;
      case 10:
        strcpy(texto, "novembro");
        break;
      case 11:
        strcpy(texto, "dezembro");
        break;
    }
    return texto;
}

Veja o Assembly gerado no Compiler Explorer. Também coloquei no Github para referência futura.
Aqui ele faz a comparação uma vez e acha o endereço na tabela:
    cmp     DWORD PTR [rbp-20], 11
    ja      .L2
    mov     eax, DWORD PTR [rbp-20]
    mov     rax, QWORD PTR .L4[0+rax*8]
    jmp     rax

Logo abaixo está a tabela e em seguida os blocos de código que devem ser executados.
Se fizer um if haverá uma comparação para cada valor:
#include <string.h>
#include <stdlib.h>

char *mes(int i) {
  char *texto = (char *)malloc(10);
    if (i == 0) {
      strcpy(texto, "janeiro");
    } else if (i == 1) {
      strcpy(texto, "fevereiro");
    } else if (i == 2) {
      strcpy(texto, "marco");
    } else if (i == 3) {
      strcpy(texto, "abril");
    } else if (i == 4) {
      strcpy(texto, "maio");
    } else if (i == 5) {
      strcpy(texto, "junho");
    } else if (i == 6) {
      strcpy(texto, "julho");
    } else if (i == 7) {
      strcpy(texto, "agosto");
    } else if (i == 8) {
      strcpy(texto, "setembro");
    } else if (i == 9) {
      strcpy(texto, "outubro");
    } else if (i == 10) {
      strcpy(texto, "novembro");
    } else if (i == 11) {
      strcpy(texto, "dezembro");
    }
    return texto;
}

Veja o Assembly gerado no Compiler Explorer. Também no Github.
Pode ver o código se tiver poucas opções (Github). Não otimiza tanto.
Agrupar cases não é um problema e otimiza, como pode ser visto no código (Github). Quando há a cascata ele coloca um item na tabela para cada case, mas a otimização ocorre do mesmo jeito. O break é usado para determinar quando deve encerrar e não continuar andando na tabela.
Já ter muitas lacunas é um problema e praticamente transforma no código do if. Veja como fica (Github).
Mas esse código fica melhor se for um array mesmo. Veja como é mais simples (Github).
Você pode estar pensando que só pode usar um array se for para pegar um valor simples e guardar em algum lugar. Na verdade é possível fazer o mesmo com blocos de código em função e chamar cada função de acordo com o valor de busca, a tabela seria dos endereços das funções.
O GCC tem até uma forma mais explícita de fazer isto, mas não funciona em outros compiladores.
Conclusão
Então é isso, a performance costuma ser melhor. Mais do que a performance deve preferir ele sempre que ele fizer sentido, sempre que for uma sequência a ser analisada. Isso valor para números, caracteres, enumerações, ou outras formas que se resumem a números simples.
O mesmo vale para muitas linguagens que prezam pela performance. Tem linguagem que tem isso mais para enfeite mesmo, ou mais para dar uma sintaxe mais adequada e não traz muita vantagem interna. Mas de forma geral ele não é só porque é mais "bonitinho", ele tem uma função própria e se for usado corretamente não tem desvantagens.
Não use onde não precisa, não tenha medo onde ele é adequado.
Comment: Pensando em alternativas de linguagens, qual forma mais fácil de saber se aquela específica está usando o jeito "mais bonitinho" e não o jeito mais performático?
Comment: @AckLay não sei se entendi o que quer saber.
Comment: Basicamente isso - com a outra diferença que nos computadores de hoje, a sequencia if/else if será quase instântanea - com várias camadas de otimização desde o código gerado pelo compilador até a previsão de saltos interna da CPU - mas quando a linguagem C foi criada podia haver  diferença de vários ciclos de clock entre a tabela de saltos gerada pelo switch/case e a sequencia de if/else if/
Comment: Mas ainda há ganho em fazer desta forma, os compiladores estão baseados em muito estudo para garantir que o que está sendo feito é o melhor sempre, tanto que se não for o melhor a otimização não é feita. Se for o mesmo resultado e ocupar mais espaço, ele já não fará a otimização. Pelo menos em compiladores decentes.


$\underset{x\rightarrow\infty}\lim{\Big(\sqrt{\cosh{x}}-\sqrt{\sinh{x}}\Big)}e^{\frac{3x}{2}}$

Question: $$\underset{x\rightarrow\infty}\lim{\Big(\sqrt{\cosh{x}}-\sqrt{\sinh{x}}\Big)}e^{\frac{3x}{2}}$$
$$\underset{x\rightarrow\infty}\lim{\Bigg(\sqrt{\frac{e^{4x}+e^{2x}}{2}}-\sqrt{\frac{e^{4x}-e^{2x}}{2}}\Bigg)}$$
Should I use L'Hopital's s rule from this point?
Comment: To those voting to close: please, comment to explain the reason. The OP is a new contributor, and may not be fully aware of the policies causing your votes.
Answer: I think a natural approach would be\begin{align}\lim_{x\to\infty}\left(\sqrt{\cosh x}-\sqrt{\sinh x}\right)e^{3x/2}&=\lim_{x\to\infty}\frac{\left(\sqrt{\cosh x}-\sqrt{\sinh x}\right)\left(\sqrt{\cosh x}+\sqrt{\sinh x}\right)}{\sqrt{\cosh x}+\sqrt{\sinh x}}e^{3x/2}\\&=\lim_{x\to\infty}\frac{e^{x/2}}{\sqrt{\frac{e^x+e^{-x}}2}+\sqrt{\frac{e^x-e^{-x}}2}}.\end{align}Can you take it from here?
Answer: For those, Taylor expansions are very useful and give a systematic way to solve the problem. You have
$$\begin{align}
\Big(\sqrt{\cosh{x}}-\sqrt{\sinh{x}}\Big)e^{\frac{3x}{2}}
&= \Big(\sqrt{\frac{e^x+e^{-x}}{2}}-\sqrt{\frac{e^x-e^{-x}}{2}}\Big)e^{\frac{3x}{2}} \\
&=\frac{e^{\frac{x}{2}}}{\sqrt{2}}\Big(\sqrt{1+e^{-2x}}-\sqrt{1-e^{-2x}}\Big)e^{\frac{3x}{2}} \\
&=\frac{e^{2x}}{\sqrt{2}}\Big(\Big(1+\frac{e^{-2x}}{2}+ o(e^{-2x})\Big)-\Big(1-\frac{e^{-2x}}{2}+ o(e^{-2x})\Big)\Big) \\
&=\frac{e^{2x}}{\sqrt{2}}\Big(e^{-2x} + o(e^{-2x})\Big) \\
&=\frac{1}{\sqrt{2}}(1 + o(1)) \xrightarrow[x\to\infty]{} \boxed{\frac{1}{\sqrt{2}}}
\end{align}$$
where we used the fact that $\sqrt{1+u} = 1+\frac{u}{2} + o(u)$ when $u\to 0$.


Why are "music bags" with the metal bar a distinct bag for sheet music?

Question: Though these look old-fashioned one can still buy "music bags", special satchels or briefcases designed to carry sheet music. They are easily distinguished from other bags because one of the handles is replaced by a metal bar over the other handle. Here's a picture of one sold now by the Cambridge Satchel Company:

Is there a practical advantage to this style of bag enclosure when transporting music? If so what is the advantage?
Comment: I realise that the tag `sheet-music` is incorrect but I need at least one tag to submit a question and all the others I could think of do not exist on the site.
Answer: I think the tag 'sheet music' is apposite.A lot of music was written out on single sheets, rather than in a manuscript book.As such, it helped if it was kept flat. The metal bar as one of the closers did just that.It stopped the bag from flexing across its widest side.
Comment: Yes, an attractive notion, but do leather cases without the bar really crease in half? And anyway, the bar doesn't lie low enough to prevent this much.
Comment: Good answer, but with the stitching along the base these bags (or at least the music bags I've seen and used) are not that flexible length-ways anyway.
Answer: It's a bag suitable for transporting sheets or books in the size typically used for printed music and manuscript paper (though, for obvious reasons, A4/Letter is becoming a de facto standard outside professional publishing).
French publishers have traditionally used a rather larger size, which explains why when you come across a sheet marked 'Editions Durand' it often has tattered edges!
If there's a better explanation for the design than 'tradition', I've yet to discover it.
Comment: 'Traditions' always start somewhere, before they get accepted by more and more people!


How to get base class's generic type parameter?

Question: I have three class as following:
public class TestEntity { }

public class BaseClass<TEntity> { }

public class DerivedClass : BaseClass<TestEntity> { }

I already get the System.Type object of DerivedClass using reflection in runtime. How can I get the System.Type object of TestEntity using reflection?
Thanks.
Answer: I assume that your code is just a sample and you don't explicitly know DerivedClass.
var type = GetSomeType();
var innerType = type.BaseType.GetGenericArguments()[0];

Note that this code can fail very easily at run time you should verify if type you handle is what you expect it to be:
if(type.BaseType.IsGenericType
     && type.BaseType.GetGenericTypeDefinition() == typeof(BaseClass<>))

Also there can be deeper inheritance tree so some loop with above condition would be required.
Comment: I get DerivedClass's type object dynamically, so can not hard-coding. I have Resolved.
Comment: I did not hard-code `DerivedClass` there is stub `var type = GetSomeType();`
Answer: You can use the BaseType property. The following code would be resilient for changes in the inheritance (e.g. if you add another class in the middle):
Type GetBaseType(Type type)
{
   while (type.BaseType != null)
   {
      type = type.BaseType;
      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(BaseClass<>))
      {
          return type.GetGenericArguments()[0];
      }
   }
   throw new InvalidOperationException("Base type was not found");
}

// to use:
GetBaseType(typeof(DerivedClass))

Answer: var derivedType = typeof(DerivedClass);
var baseClass = derivedType.BaseType;
var genericType = baseClass.GetGenericArguments()[0];

Answer: It think this should work:
var firstGenericArgumentType = typeof(DerivedClass).BaseType.GetGenericArguments().FirstOrDefault();

Or
var someObject = new DerivedClass();
var firstGenericArgumentType = someObject.GetType().BaseType.GetGenericArguments().FirstOrDefault();


Model selection using a standard p-value approach

Question: I need to perform model selection using a standard p-value approach. Using logistic regression we would like to compare the following models:
Y =       A + B + C + D
Y = A*B + A + B + C + D
Y = A*C + A + B + C + D
Y = A*D + A + B + C + D

I performed the following analysis in R:
first  <- glm(Y~G+N+E+C,     family="binomial")
second <- glm(Y~G*N+G+N+E+C, family="binomial")
third  <- glm(Y~G*E+G+N+E+C, family="binomial")
fourth <- glm(Y~G*C+G+N+E+C, family="binomial")

summary(first)
summary(second)
summary(third)
summary(fourth)

anova(first, second, third, fourth, test="Chisq")

However, I think I do not have the right output here for a model selection based on p-values?
anova(first, second, third, fourth, test="Chisq")
# Analysis of Deviance Table
# Model 1: Y ~ G + N + E + C
# Model 2: Y ~ G * N + G + N + E + C
# Model 3: Y ~ G * E + G + N + E + C
# Model 4: Y ~ G * C + G + N + E + C
# Resid. Df | Resid. Dev | Df | Deviance | Pr(>Chi)
# 1   595   |  609.90    |
# 2   594   |  609.90    | 1 | 0.000169 |   0.9896
# 3   594   |  609.81    | 0 | 0.087775 |
# 4   594   |  609.90    | 0 | -0.085001|

So, how to perform a model selection here, using a standard p-value approach?
Comment: Why do you "need to perform model selection"? This is almost never a good idea, (see: [why-is-variable-selection-necessary](http://stats.stackexchange.com/questions/18214//18245#18245). It is certainly a bad idea using p-values (see: [algorithms-for-automatic-model-selection](http://stats.stackexchange.com/questions/20836//20856#20856)).
Comment: Hi, It's just an assignment for school here. I also need to argue why p-values are a bad idea, so you helped me out here! Thanks
Comment: That sounds good, @Sophie. If this is a school-assignment, you need to add the `[self-study]` tag. Note that our policy is special in this situation; please review our [help page](http://stats.stackexchange.com/help/on-topic) & the [self-study wiki](http://stats.stackexchange.com/tags/self-study/info), & let us know what you've done already & where you're stuck.
Comment: Hi, I have the analysis performed, but I don't know wether I performed it correctly... Can I post my R-script, Output and interpretation as a question, and add [self-study] or/and [homework]? Or is that not acceptable here?
Comment: There is no `[homework]` tag anymore, just add the `[self-study]` tag, & understand that we will treat this specially as noted at the links I provided above.
Comment: Like this: http://stats.stackexchange.com/questions/68622/perform-model-selection-using-bayes-factors-based-on-the-bic-statistic
Comment: Please don't open a new question, @Sophie. Just add the `[self-study]` tag to *this* one.
Answer: Could it be possible to formulate these models as a nested structure?
First you would have a model like
Y=A*B+A*C+A*D+A+B+C+D

which is H1, and then
Y=A*B+A*C+A+B+C+D

which is H0.
Now you could do a Likelihood-Ratio test which is -2*logLik(H0)+2*logLik(H1) and is distributed as a $\chi^2$ with $k+p-k$ degrees of freedom where $p$ is number of extra parameters in the H1. If the result is large then you can say that it is not proper to use the H0 model, H1 is needed to explain variation in the original data (seen in the extra deviance which increases if second largest is used versus largest model).
This could be done in steps: first take largest model as H1, and second largest as H0; in the next step (if H0 is rejected) you will take second largest model as H1 and third largest model as H0. And so on...
Comment: Hi, I only need to compare the models as specified above, which means that I have got non-nested models. I need to use a standard p-value approach, only one I could think about here was the Chi-square. Which means that I can only compare model 1 with all the others, but not model 2 with model 3 for example. However, the statistics favor model 1 with p-values above .72. But than the question remains, is this the best way to perform model selection using a standard p-value approach?


AWS Elastic Load Balancer (Public To Internal)

Question: I am trying to build up a multi-tiered architecture on AWS.
I have a public facing ELB which has my autoscale webserver instances running on docker. I also have in my private subnet backend servers running on docker containers behind an internal elb.
I need my public facing elb to forward some request to the backend servers via the internal elb but am on-sure on how that can work. According to the doc below this can work.
https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-internal-load-balancers.html
Anyone achieved this before who can provide assistance?
Comment: What type of load balancer, an Application Load Balancer? How will the load balancer know which requests need to go to which instances? You can't point a load balancer to another load balancer (note how the article you linked doesn't show that). An application load balancer can send different requests to different instance target groups, which may accomplish what you need.
Answer: I understand you have the following resources:

1 Public facing ELB
2+ Web servers in autoScaling and the application is deployed in Docker
1 Private ELB
2+ backend servers

Query:-
How to forward the requests from public facing ELB to internal ELB.
Solution and suggestion:
You cannot directly Route the request from ELB to ELB. In your webserver you have to mention the internal ELB endpoint to route the traffic to your private ELB.


Distance Variable with unequal intervals

Question: Suppose that $x$ takes the following values:  0 feet from start, 10 feet from start, and 15 feet from start. Let the outcome variable be $y$. How would you interpret the regression coefficient of $x$ ($\beta_1$) in a linear regression? Would it be: a unit increase in $x$ is associated with an expected increase of $\beta_1$ in $y$? It seems that this would be a problem because a unit could be an increase from $x=0$ to $x=10$ or an increase from $x=10$ to $x=15$.
Comment: A "unit," by definition, is $1$.  Thus it would be one-tenth the change from $x=0$ to $x=10$ or one-fifth the change from $x=10$ to $x=15$.
Answer: If x is coded with 0, 10 and 15, then no: the coefficient would be interpreted as a one unit (i.e. 1-foot) increase in $x$ is associated with a Blah-Dee-Blah unit change in $y$.
However, if $x$ is coded 0, 1, 2 (i.e. ordinally), then you've got some problems.
Answer: If your variable is coded in 'feet from start' there's no problem, the coefficient of $x$ is in  per foot from start.
If you have it coded in some other fashion (0,1,2, or 1,2,3, or -1,0,1) say, it doesn't represent an interval scale but a set of ordinal categories. If those are treated appropriately, then you still don't have a problem, though you'll have two coefficients, not one. How they're interpreted depends on how you wrote your model.
So how is $x$ coded?


UE4 NDK android-19 cannot locate 'log2'

Question: I am having a problem with a run-time error that says

caused by: java.lang.UnsatisfiedLinkError: Cannot load library:
  reloc_library[1307]:  1838 cannot locate 'log2'...

The higher versions above 19 are fine, however, on devices in the version lower then 19, my game is crashed by the reason.
What I did is
I declared two definition of log2 and log2f at mygame.h
<code>#include "CoreMinimal.h"
#define log2f(x) (logf(x)/logf(2.0f))
#define log2(x) (log(x)/log(2))

DECLARE_LOG_CATEGORY_EXTERN(LogGhost, Log, All);
</code>
But still it doesn't work.
Answer: The problem was fixed after UE4.16.3

UE4 NDK android-19 cannot locate 'log2'


How to use List

Question: I need to get the list of billers from my database.
here is my code:
public static List<dynamic> GetBillers()
{
    DataLayer.DLContext context = new DataLayer.DLContext();

    var Billers = (from b in context.Biller
                   where b.IsActive == true && b.IsDeleted == false
                   select new
                   {
                       ID = b.ID,
                       DisplayName = b.DisplayName
                   }).ToList();

    return Billers;
}

I am getting this error:

Cannot implicitly convert type Collections.Generic.List<AnonymousType#1> to System.Collections.Generic.List<dynamic>

Please help.
Comment: Why not just create a Dto to store the objects? Then you aren't relying on `dynamic`..
Comment: http://stackoverflow.com/questions/16645626/cannot-implicitly-convert-type-system-collections-generic-listanonymoustype1 will help you
Answer: (from b in context.Biller
 where b.IsActive == true && b.IsDeleted == false
 select (dynamic) new {
     ID = b.ID,
     DisplayName = b.DisplayName
 }).ToList();

should do the job. Personally, though, I'm not sure it is a particularly helpful move - I would suggest returning a known class / interface instead. dynamic has various uses, but this isn't a good one.
Answer: Cast to dynamic:
var Billers = (from b in context.Biller
               where b.IsActive == true && b.IsDeleted == false
               select new
               {
                   ID = b.ID,
                   DisplayName = b.DisplayName
               }).ToList<dynamic>();

Answer: you can not assign a List<T> to a List<dynamic> object. You need to add each object one by one;
        var temp = new List<dynamic>();
        foreach (object obj in Billers)
        {
            temp.Add(obj);
        }

Comment: It can also be done in the existing query; also, here you are significantly changing the semantic: the original query only made the `ID` and `DisplayName` available - presumably quite deliberately. This makes the original object available. That can be good or bad, but : it isn't the same as the result of the code in the question.

How to use List


Django: Pipfile.lock dependency installation problem

Question: I am working on a Django Project (in Docker) and use pipenv for installation of various packages. When installing the latest package, I made a mistake by using
docker-compose exec web pipenv install dateutil instead of python-dateutil, which is the correct package name.
What happened is that  the installation failed with the message that there is no package with this name. Nevertheless dateutil showed up in my pipfile. So I tried to remove it from the file via docker-compose exec web pipenv uninstall dateutil which did not work, as the package is not installed. I went on and simply deleted dateutil from my pipfile and installed python-dateutil with the correct name.
When I tried to rebuild my image afterwards I got the following error message:
Installing dependencies from Pipfile.lock (789763)…
remote: Failed to load paths: /bin/sh: 1: /root/.local/share/virtualenvs/code-_Py8Si6I/bin/python: not found
remote:
remote: Output:
remote: Failed to load paths: /bin/sh: 1: /root/.local/share/virtualenvs/code-_Py8Si6I/bin/python: not found
remote:
remote: Output:
remote: Failed to load paths: /bin/sh: 1: /root/.local/share/virtualenvs/code-_Py8Si6I/bin/python: not found
remote:
remote: Output:
remote: Removing intermediate container 84c77fef6192
remote:  ---> 109aa5618fd4
remote: Step 8/8 : COPY . /code/
remote:  ---> 5afe012dfe80
remote: Successfully built 5afe012dfe80
remote: Successfully tagged 3c44f0505a52f77469b72b43bc40afe49fed878e:latest

My app still works (locally and in production), but I would like to understand (1) what would have been the correct way to solve such an incident and (2) if there is a way to solve it (=getting rid of the error messages every time I rebiuld the image) after the incident
Comment: Those errors may be a pipenv 2020.x bug:
https://github.com/pypa/pipenv/issues/4220
Comment: Also, since you do version-control your Pipfile and Pipfile.lock (you do, right?), the easiest way to recover is to reset those to a known-good state and rebuild your container(s).
Comment: yes I version-control my Pipfile and Pipfile.lock and will follow your suggestion, thanks for your quick help!
Answer: I have downgraded to pipenv 2018.11.26
sudo python -m pip install pipenv==2018.11.26


Setting secure cookies

Question: In scanning a Drupal 7 site with Qualys, we're getting the issue

150122 Cookie Does Not Contain The "secure" Attribute

Is there a way to systematically add the Secure vs HTTPOnly flag to cookies? Would Secure Cookie Data serve this? If so, how do I test that Cookies are secure?
Moreover, this site automatically forwards to https. The user spends no time over port 80 but instead is directly shuttled to 443. We have an administrator who wants nothing but to see this test passed; regardless of the previous fact.
The Cookie in Question:
has_js=1

Would the following in settings.php be sufficient:
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_httponly', 1);

Answer: Which cookie is this? All of Drupal 8's cookies are secure.
The exception is BigPipe's no-JS cookie, see https://www.drupal.org/node/2678628 — but there are no security consequences there.
If that's the one that is triggering this alert, then the problem is clear: your security testing tool is making blanket statements that don't make sense.
Comment: I've adjusted my question to denote Drupal 7.
Comment: I just got this finding from our security scan on Drupal 8 also.
Answer: It appears I can tell Apache to do this for me:
Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure

Comment: Can you please elaborate how you did it?

Setting secure cookies


catch return value in CMake add_custom_command?

Question: how do I grab the return value of command invoked by add_custom_command?
I thought I could do something like this,
macro(mac param1)
    execute_process(COMMAND process ${param1} RESULT_VARIABLE res_var)
    if(${res_var} ....

endmacro(mac)

add_custom_command(COMMAND mac(param1))

but that won't work. I found out that even a plain
macro(mac)
endmacro()

add_custom_command(COMMAND mac())

does not work. Upon building, sh complains:
/bin/sh: 1: Syntax error: end of file unexpected

or, if I do not use the macro but call execute_process in add_custom_command itself:
/bin/sh: 1: Syntax error: word unexpected (expecting ")")

I guess that add_custom_command does not expect macros or built-in functions to be passed. However, how can I get the return value from the command in add_custom_command? Or, less specifically, how can I catch that the command in add_custom_command failed?
Answer: The commands run by add_custom_command do not run until build time, so you can't "catch" that they failed during CMake's configure/generate steps.
If a custom command fails, then anything that depends on the output of that custom command will either be avoided, because make stops after that, or if make keeps going after errors, it will eventually return an error at its conclusion, and give some sort of "failed build" message.
You can always write an equivalent script that runs as a custom command, and then in that script, do something after certain types of errors. If you use cmake in -P script processing mode, you can make a cross platform script that calls execute_process and analyzes the return value.
For example:
configure_file(
  ${CMAKE_CURRENT_SOURCE_DIR}/script.cmake.in
  ${CMAKE_CURRENT_BINARY_DIR}/script.cmake
  COPYONLY
)
add_custom_command(COMMAND ${CMAKE_COMMAND} -P
  ${CMAKE_CURRENT_BINARY_DIR}/script.cmake
)

And then in script.cmake.in:
execute_process(COMMAND process param1 RESULT_VARIABLE res_var)
if(NOT "${res_var}" STREQUAL "0")
  # do something here about the failed "process" call...
  message(FATAL_ERROR "process failed res_var='${res_var}'")
endif()

Comment: Always with the `configure_file` :-)
Comment: If its useful, use it... :-)
Comment: so @Max, did you "test it tomorrow"?


How should I deal with a vocabulary with many terms?

Question: I'm trying to use Drupal 8, but if Drupal 7 is better for that, I'm ready to go back to Drupal 7.
I have a vocabulary that must contain at least 10,000 terms, but they can also become more than 100,000.  For the sake of simplicity, I chose to make only one vocabulary, without hierarchy.
I quickly reached the limits of my server, and I regularly get WSODs,  especially when I try to edit the vocabulary.
I tried to increase the limits of memory (I am under MAMP), but I still have errors. Here is the error:

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 20480 bytes) in /core/lib/Drupal/Core/Entity/Sql/Sq

How can I avoid these problems?
Is it preferable to split the vocabulary?
Comment: Is it just a matter of loading the taxonomy overview page? Replace it with a paged view for better results? Not really a lot of other information here.
Comment: Way too broad. Many sites out there have thousands of terms or millions of nodes. Sounds more like a server tuning problem?
Comment: It's strange. I'm using MAMP yet, with the default settings. I pushed the limit of the memory to 512M ... Are there any other settings to be made?
Comment: Please post the error message from Apache logs or from Drupal error log when you get a white screen. Also, enabling error display in php.ini can help a lot in this matter
Comment: PHP memory limit over 256MB isn't going to be any more beneficial to you.
Comment: @IsmailCherri Here is the error: Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 20480 bytes) in /core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php on line 588 E_ERROR Error in file SqlContentEntityStorage.php at line 588
Comment: @Kevin Thanks Kevin for this solution. Otherwise, there is no other setting that would help? To cut the taxonomy in several is not preferable from a performance point of view?
Comment: @Hgfdsoiu of course if it can be cut, it will be preferable, but if not due to some business reasons, the suggestion of Kevin may be your best option
Answer: Since i can't answer it in comment. i'll try to answer here. I've solve similar problem, my solution is using redis caching and entity cache module
Since then, my site going well with 256MB RAM configuration in php.ini.


Let $U$ be an open connected subset and $f : U \to \Bbb R$ be a diff function then $f$ is a constant function.

Question: Let $U$ be an open connected subset of $\Bbb R^n$ and $f : U \to \Bbb R$ be a differentiable function such that $D f (p) = 0$ for all $p \in U$ then $f$ is a constant function.
If we can prove that $f$ is constant about each point in $U$ i.e., let if $x \in U$, there exists $B(x, r_x) \subset U$. Then if we can show that $f$ is constant on the nbd  $B(x, r_x)$ then we are done. I think we have to use MVT.
Help Needed!
Answer: Pick any two points $u$ and $v$ from $U$, and apply the MVT to the segment $[u,v]$ that connects them: this is possible provided that $u$ and $v$ are sufficiently close, since $U$ is open and open balls in $\mathbb{R}^n$ are convex. You will find in the end that $f(u)=f(v)$.
You can conclude in a standard way.
Answer: Pick $x_0 \in U$ and let $C=\{x \in U| f(x) = f(x_0)\}$. It is easy to see that
$C$ is closed since $f$ is continuous. Since $U$ is open, you can use the mean value theorem to show that $C$ is open. Since $U$ is connected we have $C = U$.


Coefficients of a series expansion under modular arithmetic

Question: I am reading a paper by Ramanujan on partitions and need help understanding an intermediate step he uses in a proof. He writes:

... all the coefficients in $(1-x)^{-5}$ are multiples of 5, except those of $1$,  $x^5$, $x^{10}$, $...$, which are congruent to 1: that is to say
  $$
\dfrac{1}{(1-x)^5} \equiv \dfrac{1}{1-x^5} \pmod 5
$$
  or$$
\dfrac{1-x^5}{(1-x)^5} \equiv 1 \pmod 5
$$

The coefficients can easily be verified to have this property, we have the series expansion:
$$
(1-x)^{-5} = 1 + 5x + 15x^2 + 35x^3 +70x^4 + 126x^5 + \dots
$$
Here's how I would approach it. For the series expansion I can write:
$$
\begin{align}
(1-x)^{-5} &= \sum_{k=0}^\infty \binom{k+4}{4}x^k\\
&= \sum_{k=0}^\infty \dfrac{(k+4)!}{4!k!} x^k\\
&= \sum_{k=0}^\infty \dfrac{(k+4)(k+3)(k+2)(k+1)}{4!}x^k\\
&= \sum_{k=0}^\infty \dfrac{24 + 50 k + 35 k^2 + 10 k^3 + k^4}{24}x^k
\end{align}
$$
and looking at the coefficients modulo 5:
$$
\dfrac{24 + 50 k + 35 k^2 + 10 k^3 + k^4}{24} \equiv 1-k^4 \pmod 5
$$
and I can see that $k \equiv 0$ gives the coefficient congruent to 1 while any other value of k results in the coefficient being congruent to 0, the desired result. Still, I'm confused at the relevance/meaning of the congruences that Ramanujan wrote. Can someone help me understand what he meant? I feel like I'm missing something.
Comment: The congruences values happen to be the description of the coefficients of $\frac{1}{1-x^5}=1+x^5+x^{10}+...$. Namely, they are all zero except for exponents divisible by $5$, which are $1$. He can then conclude that $\frac{1}{(1-x)^5}\equiv\frac{1}{1-x^5}$.
Comment: You may be interested in [OEIS sequence A004006](https://oeis.org/A004006): 0, 1, 3, 7, 14, 25,... .
Comment: @MoonLightSyzygy that very much helps to clarify. Thank you!
Comment: @MoonLightSyzygy Your argument works even if $5$ is replaced by $6$ but the corresponding result $$\frac{1}{(1-x)^{6}}\equiv\frac{1}{1-x^6}\pmod{6}$$ is false. The fact that $5$ is prime is key here.
Comment: @ParamanandSingh No, it doesn't work because the starting premise is not satisfied. You just didn't understand neither the question nor what I said. The question is 'Why the congruences of the coefficients of $(1-x)^{-5}$ imply that this is congruent to $(1-x^5)^{-1}$?'. What I said is that the congruences simply describe the coefficients of $(1-x^5)^{-1}$. Now revisit your example. Do you know that the coefficients of $(1-x)^{-6}$ are divisible by $6$ for all exponents except the multiples of $6$ in which case they are congruent to $1$? No, you don't have that. So, nothing I said implies ...
Comment: ... the congruence that you wrote.
Comment: @MoonLightSyzygy: Ok I thought that the statement in your first comment is the reason for the congruence. Your comment is actually a description of the given congruence rather than a justification for it.
Comment: @ParamanandSingh It is a justification of the congruence between the power series, given the congruences of the coefficients. The congruences of the coefficients is given and also computed already in the question. They don't need help with that. They are asking why from these it follows the congruence of the power series.
Answer: I hope you know the following

Theorem: If $p$ is a prime number then $p$ divides the binomial coefficients $\binom{p}{a}$ for $a=1,2,\dots, (p-1)$.

Therefore we have $$(1-x)^{5}\equiv 1-x^5\pmod{5}$$ and taking reciprocals $$\frac{1}{(1-x)^{5}}\equiv \frac{1}{1-x^5}\pmod {5}$$
The key here is the congruence of formal power series with integer coefficients. Let $\sum_{n=0}^{\infty} a_nx^n, \sum_{n=0}^{\infty} b_nx^n$ be two formal power series with integer coefficients. Then we say that $$\sum_{n=0}^{\infty} a_nx^n\equiv \sum_{n=0}^{\infty} b_nx^n\pmod{m} $$ if $a_n\equiv b_n\pmod {m} $ for all $n$.
Such congruences follow usual rules like one can add / subtract same formal series to each side of a congruence or multiply both sides of a congruence by same formal series and the resulting congruence remains valid.
Similarly we can take reciprocals of both sides of a congruence if resulting formal series have integer coefficients (prove it!). Note that this requires the formal series involved have their constant terms equal to $1$ so that taking reciprocals leads to integer coefficients.

Ramanujan was a master of such manipulation with formal series and products and he used this approach extensively. My guess here is that you encountered this technique in proving partition congruence $$p(5n+4)\equiv 0\pmod{5}$$
Comment: @Sirch You can avoid having to invert the series and re-proving that their corresponding coefficients are congruent, if as you did in your question, you expand $(1-x)^{-p}$ in series directly. The coefficients are $(-1)^n\binom{-p}{n}$, which give you directly the congruence. No need to do the same work twice.
Comment: @MoonLightSyzygy: the proof for inverting the series is almost trivial by induction. Once the rules for congruence of power series are established this itself becomes an effective technique.
Comment: Thank you for your help, this makes things much more clear! You are correct that I am reading about congruences of the partition function.
Comment: @Sirch: you may also have a look at [this](https://paramanands.blogspot.com/p/archives.html?m=0). Search for "congruence" in the linked page.


Stable marriage problem with all men having the same preference

Question: Does a Stable marriage matching exist when all men have the same preferences for women, but the women do not have the same preferences when it comes to men?
One example case is:
Man 1 pref.: Woman 1, Woman 2
Man 2 pref.: Woman 1, Woman 2
Woman 1 pref.: Man 1, Man 2
Woman 2 pref.: Man 2, Man 1
TIA!
Answer: By the stable marriage theorem, there is always a stable marriage no matter what the preferences are.
In your example, a stable marriage would M1-W1 and M2-W2.  This is stable because each woman is matched with her most preferred man.
Comment: Thanks! Had misunderstood the definition of stability. M1 - W1 and M2 - W2 does provide a matching where "there is no pair of people that prefer each other to their spouses"


How project structure is displayed in eclipse, how manage it?

Question: I have Spring-MVC application. Files like: .project, .classpath, I dont keep in repository, I generate it by eclipse during import (eclipse import maven project).
Sometimes in Project Explorer View, project looks like:

And sometimes like below:

Can I manage this, how? I prefere second view, how convert first to second view? On screens are Eclipse Juno and Kepler, both have the same plugins installed (mostly).
Answer: In the first screenshot, the SRC/  folder is not a source folder, whereas in the second the folders SRC/main/Java, SRC/main/resources...  are sources folder and not the SRC/.A right click on the SRC/ and then Build path, set a source folder should
fix that in the first image. In the second, remove from build path SRC/* and then do as above.


Why did Verratti get a card for this back pass?

Question: During the match between PSG and Nantes, Marco Verratti was cautioned (received a yellow card) for this pass to the goalkeeper, which was headed back rather than kicked.
I believe the referee has interpreted the behavior as unsportsmanlike, but do the rules confirm this?
Comment: If could add a description of the incident to the question, it would be better - since Youtube video are prone to being taken down.
Comment: [Please do not use codeblocks for emphasis or highlighting](http://meta.workplace.stackexchange.com/a/3942/53718). It interferes with screen-readers, and is inappropriate usage, especially where *emphasis* or **strong emphasis/bold** should be used. In particular @jamauss should know better.
Comment: @Nij I'll stop using codeblocks for emphasis in comments when inline blockquotes are introduced. Until then, I'm going to follow [enderland's answer to that meta question](http://meta.workplace.stackexchange.com/a/3943/29620), as there is no better tool. Italics and bold don't have the desired effect.
Comment: But there's no point to an inline blockquote. Either you want the quote separate, so use the > markup, or you want it inline but emphasised, so use the emph/stremph with * around "".
Answer: The offence committed by Marco Verratti is mentioned under Law 12 - Fouls and Misconduct, Section 3: Disciplinary Action.

Cautions for unsporting behaviour
There are different circumstances when a player must be cautioned for
  unsporting behaviour including if a player:
...

uses a deliberate trick to pass the ball (including from a free kick) to the goalkeeper with the head, chest, knee etc. to circumvent the Law, whether or not the goalkeeper touches the ball with the hands.

Going down under no pressure to head the ball to the keeper certainly fits the act that this rule aims to punish and although the referee has drawn flak for brandishing the yellow card, he has followed the rule and taken appropriate action for Verratti's offence.


What happens when a site goes in maintenance mode while a user is editing an node content?

Question: Let's imagine a user is editing a node content. In the mean time, a Drupal administrator puts the site in maintenance mode.

Does the user have a chance to save his work (assuming it does
not have the "Use the site in maintenance mode" priviledge)?
Is there a way to send them a warning, like 'maintenance in 5 mins'?

Thanks.
Answer: Unless you notify the editors about that, they will lose their work on that node. You can do that either by using some contrib modules or by creating your own custom module. Either way, I think you definitely need some kind of ajax solution so they can be notified even when they are on the node edit page.
You can check Privatemsg and Private Message Growl modules. I'm not quite sure how they work but they look promising.
Comment: You can also use something like http://drupal.org/project/autosave to make sure their work is not completely lost, if this situation arises.


css (box-shadow) transition on page load

Question: Is there a way to make a transition happen for a box-shadow on page load instead of with a hover or click effect?
The transition I want on page load, or as an event:
.item:hover{
margin:0 auto;
box-shadow: 1px 1px 20px  grey;
transition: 0.7s;
max-width: 940px;
color: dimgrey;
padding-top: 10px;
padding-bottom: 10px;
border-radius: 10px 10px 10px 10px;
}

Comment: have you seen this https://stackoverflow.com/questions/11679567/using-css-for-a-fade-in-effect-on-page-load
Comment: yes, i was a bit tired and think i thought the keyframes was only for movement and colour change, not for like creating a box-shadow onpageyoffset = 900 etc.
Answer:

you can name keyframes a name and provide the time you need, I have provided4sec in the example.
It says change the background color from red to yellow and increase the height by 200px and animate this for 4 seconds.

.item {
  height: 100px;
  width: 100px;
  background-color: blue;
  animation-name: animate;
  animation-duration: 4s;
  border-radius: 10px;
}

@keyframes animate {
  from {
    background-color: red;
  }
  to {
    background-color: yellow;
    height: 200px;
  }
}

Comment: how do you make it so that it stays with the end result after finishing?
Comment: I got it,

animation: animate 1s forwards

the fill node of forwards did it


CSS - Links moving on hover

Question: I'm having a slight issue with some CSS I'm working on.
Links in the footer moves a little when on hover, but only after I refresh the page, on first load all looks good but after I refresh the page the links are sitting tight to each other and when hovered they go back to their proper position, tried few tricks found on Stack, but they didn't help.
Here is the code:
.f-links {
    clear:both;
float:right;
    position:relative;
    left:-50%;
    text-align:left;
}

.f-links ul {
    list-style:none;
    position:relative;
    left:45%;
}

.f-links li {
    float:left;
    position:relative;
}

.f-links a {
font-size:12px;
margin-top: 0;
margin-bottom: 0;
    text-align: center;
text-decoration: underline;
    color: black;
    float:left;
    padding:2px 10%;
    white-space:nowrap;
}

.f-links a:hover,
.f-links a:visited {
    color: black;
}

.f-links a:hover {
    text-decoration: underline;
}

and the HTML:

About Us

Contact Us

Terms & Conditions

Thanks in advance for any help.
Comment: why do you float the `a` s?
Comment: That's taken from one solution I found on here, I wanted to position the links right in the center.
Answer: if you only want to center the links you better use following css (inline-block is well supported so no worries)
.f-links {
    text-align: center;
}

.f-links ul {
    list-style:none;
}

.f-links li {
    display: inline-block;
}

Answer: You should remove the float left  and the percentage from padding in the .f-link a styles:
.f-links a {
font-size:12px;
margin-top: 0;
margin-bottom: 0;
text-align: center;
text-decoration: underline;
color: black;
padding:2px 10px;
white-space:nowrap;
}

Comment: I removed them, but that didn't fix the problem.

CSS - Links moving on hover


Variável não recebe novo valor

Question: Tenho um objeto que deve ficar "caindo" sobre a tela várias vezes, e isso funciona.
O que estou tentando fazer é com que uma variável chamada x receba mais 1 sempre que este objeto passar pela tela. Quando x receber mais 5, quero que outra variável chamada y receba menos 1.
Para isso declarei ambas variáveis e atribuí um valor a elas: x = 0 e y = 5.
PROBLEMA:
x deveria receber mais 1 quando o objeto passasse pela tela, e isto acontece, porém apenas uma vez. Quando o objeto passa pela primeira vez pela tela, x recebe mais 1, mas após isso, x para no 1 e não recebe mais nada.

Para y receber menos 1, x deve receber 5, então creio que esse é o motivo para que y não mude o valor, já que x não passa de 1.
Nenhuma mensagem de erro é exibida durante a execução do jogo.
Por que o valor da variável x não muda?
CÓDIGO:
<code>private int x, y;

void Start() {
    x = 0;
    y = 5;
}

void OnBecameInvisible() {
    // quando o objeto passar pela tela
    x += 1;
    Debug.Log("Valor de x: " + x);

    if ((x % 5) == 0)
    {
        // sempre que x receber mais 5
        y -= 1;
        Debug.Log("Valor de y: " + y);
    }
}
</code>
Observação: não coloquei todo o código porque o restante dele é sobre a velocidade que o objeto irá cair, posição e coisas do tipo.
Comment: Nós precisamos entender o que está acontecendo.  Pra mim tá tudo certo aí, não vejo problemas. Você tem que mostrar o problema acontecendo. Leia como fazer um [mcve]
Comment: Como eu disse na pergunta, o problema é que o valor de ambas variáveis não mudam. Em OnBecameInvisible(), depois de x receber mais 1 a variável tem o seu valor imprimido, e como pode ver no código, a mesma coisa acontece com a variável y. Não é exibido nenhuma mensagem de erro durante a execução do jogo, então é difícil saber o porque disso!
Comment: Vou editar a pergunta e tentar deixar isso mais claro.
Answer: Tente alterar o nome do objeto que está passando sobre a tela toda vez que ativar a função OnBecame. Pode ser uma possível solução. Poderá fazer o teste jogando dois objetos na tela e observando se a variavel X recebe uma soma.

Variável não recebe novo valor


Por que dá erro quando tento atribuir um valor na variável dentro de um operador condicional?

Question: Eu tenho o seguinte código que deve receber 4 números e dizer qual deles é o maior.
#include <stdio.h>

int max_of_four(int x, int z, int y, int w);

int main() {
    int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = max_of_four(a, b, c, d);
    printf("%d", ans);

    return 0;
}

int max_of_four(int x, int z, int y, int w){
    int max1, max2;

    x > z ? max1 = x : max1 == z;
    y > w ? max2 = y : max2 == w;

    return max1 > max2 ? max1: max2;
}

A minha dúvida está na função max_of_four. Eu comparo dois números duas vezes e o maior deve ser atribuído à sua respectiva variável. Na parte do else (... : max1 == z; / ... : max2 == w;) em vez de == deveria ser =, porém se eu colocar o = o código dá o erro:

lvalue required as left operand of assignment

Por outro lado, se eu deixo o == o código não roda direito, não imprimindo o valor mais alto caso ele esteja na segunda ou quarta posição.
Eu sei que poderia fazer o seguinte:
 int max1 = x > z ? x : z;
 int max2 = y > w ? y : w;

Porém gostaria de saber se meu código é incorrigível ou se estou deixando algo passar.
Comment: Tente: (x > z) ? (max1 = x) : (max1 = z); ,que aqui funcionou, pois você especifica sem dúvidas quais são as expressões.
Comment: @MauryDeveloper A função está no final, porém eu a declarei no topo antes da função principal. A dica de colocar entre parênteses os termos funcionou e o Luiz Augusto explicou direitinho o que acontece. Muito obrigado a todos!
Comment: Não tem muito sentido este == pois o resultado será verdadeiro ou falso e não uma atribuição. O correto é o que você colocou no final.
Comment: Função foi criada depois. Eu já tive esse problema. Sempre deixe main nas ultimas linhas
Answer: Você consegue fazer o que deseja, só a sintaxe estava um pouco errada, veja só que dá pra ser até mais simples:
#include <stdio.h>

int max_of_four(int x, int z, int y, int w) {
    int max1 = x > z ? x : z;
    int max2 = y > w ? y : w;
    return max1 > max2 ? max1 : max2;
}

int main() {
    int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = max_of_four(a, b, c, d);
    printf("%d", ans);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Ah, mas você quer fazer de outro jeito, então sim, seu código é incorrigível. Seu gosto não pode se sobrepor ao mais correto.
Você está misturando statement com expressão. O operador condicional existe para simplificar quando você tem expressões. Você está querendo transformar um código de statement em expressão e isto é errado, mesmo que funcione. Você está tornando o código mais ilegível, então não faça, simples assim.
Uma atribuição gera um efeito colateral e este tipo de cóisa é o que mais causa bugs, por isso deve estar muito visível, deve ser  no início da linha pra ficar óbvio. Você está usando um operador para substituir uma construção de linguagem e "encurtar", isso não é legal. Por que não usar o operador do jeito certo de forma que encurta mais ainda?
Comment: Entendi. Então eu devo apenas usar um Operador Ternário quando eu quiser atribuir um valor a uma variável sob uma condição? Achei que era uma forma mais curta de escrever, não sabia que tinha certas condições sintáticas para o Op. Ternário. Muito obrigado pela correção teórica!
Answer: Verifiquei seu código com operador ternário e não compila, porém usando a estrutura de seleção if/else o mesmo compila.
#include <stdio.h>

int max_of_four(int x, int z, int y, int w);

int max_of_four(int x, int z, int y, int w){
    int max1, max2;

    if (x > z)
    max1 = x;
    else
    max1 = z;

    if (y > w)
     max2 = y;
     else
      max2 = w;

    return (max1 > max2 ? max1 : max2);
}
int main() {
    int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = max_of_four(a, b, c, d);
    printf("%d", ans);

    return 0;
}

Colocando a busca no google: lvalue required as left operand of assignment ternary operator
Encontro as seguintes perguntas:

"lvalue required as left operand of assignment" error - ternary
operator
Error: lvalue required in this simple C code? (Ternary with
assignment?)

Traduzindo, via google translate, a resposta:
Na linguagem C, a gramática e a semântica do operador condicional são diferentes de C ++. Seu código seria compilado em C ++, já que em C ++ a expressão
 <condition> ? a = b : c = d

seria analisado como
 <condition> ? (a = b) : (c = d)

Porém em C, a mesma expressão é analisada como
 (<condition> ? (a = b) : c) = d

que é uma história completamente diferente. O resultado de ?: em C nunca é um lvalue, e é por isso que a última análise não é compilada.


Receiving data from a USB device in C or C++

Question: I need a list of all plugged in USB devices and have the user select one to let the console application receive any data the USB device sends.
I can then start playing around with the data in my program.
I don't want to use library's, only standard C++ functions, and the program should work in Windows 98.
Comment: I want to know the background of it and write own code.
Comment: There are no Standard C++ functions to do this.
Comment: I'm not sure... Can you please tell me how it can be done then.
Comment: why don't you want to use libraries?
Comment: You will have to use Windows API.  Also check out the USB protocol.
Comment: Yes, I need to do it using the Windows API, but I don't know how.
Comment: Then, perhaps, start with something simpler...
Answer: This is a very persistent question in forums and programming Q+A sites.  Never with a happy ending.  The B in USB means bus.  That is a term in computer hardware design to describe an electrical interface for electronic devices to exchange data.  It plays the exact same role as, say, the PCI (express) bus inside your machine.  Since it is an electrical specification first and foremost, USB supports a very large number of types of devices.  Anything from a wireless network adapter, modem, flash memory card to a teapot warmer.  Just about the only kinds of devices that it doesn't handle well are ones that require a very large bandwidth, like a video adapter.
The USB specification has a very elegant protocol specification that describes how devices can share the bus and how they can exchange data.  That protocol spec however does not describe the format of the data at all, it merely defines the notion of being able to deliver chunks of bytes.  It is up to the device itself to give a meaning to those bytes.
On the machine end, you need software to interpret those bytes and make the machine do something interesting with them.  That requires a device driver.  Just like your video card and your network interface card require a device driver.  Obviously a video driver is very different from a NIC driver.  The same is true for USB drivers, there is little commonality.
If you want to write software that treats USB devices similar then you need to write that at the level where they still have something in common.  That's at the USB controller level, you could write a filter driver that injects itself in the USB driver stack and peeks at the I/O request packets between the controller and the device driver.  Similar to, say, the winpcap filter driver that spies on TCP/IP traffic.  There isn't much of anything interesting to see though, you'd be staring at the blobs of bytes that pass back and forth.  It is a much bigger problem than winpcap, at least it sees bytes fly by whose meaning is documented somewhere in an RFC.  That's not the case for USB, the company that makes the USB device is also usually the device driver supplier.  They keep the internal format undocumented.
Writing filter drivers requires pretty advanced skills, there are lots of pain points.  Like crashing the operating system when you make a simple mistake.  There has also been considerable flux in the Windows Driver Model lately, USB drivers have been getting moved into ring 3 (user mode) to keep the operating system stable.
To get started, download the Windows WDK (aka "DDK") and read Walter Oney's books.  Preferably all of them.
Comment: Yes, that would be a problem.  Amazon.com delivers to Belgium afaik.  You probably don't want to spend too much money on it, happy ending and all that.  I know you've got good libraries available in university towns.
Comment: @Hans: My dad isn't very much interested in what I do on my PC. I didn't ever write my own program. I know other languages very well, like PHP and JavaScript. I know, a lot of fun, but what I have in my mind to realize in C++ is much more interesting and fun than a Freecell game. I think this is a very basic thing to do (finding out which USB devices are connected and receive data), and I don't see why it won't be possible with C++.
Comment: Thanks, but I don't really want to make a driver. Is that a problem? And are you sure the book is good for me? I live in Belgium and I can't buy it here.
Comment: I still don't know. I just want to make a program, not a driver. :/
Answer: Here's something to get you started:

Universal Serial Bus Revision 3.2 Specification - it's a bit long, but a good read if you want to get into USB. It explains everything about how USB works.
The USB section at MSDN

And for crying out loud update to an OS that's not from the last millenium. I hear Linux has great support for USB.
Comment: +1 for the update - Windows 98 is ancient. (+1 for the implied Linux recommendation.) If people would update, we'd get cool stuff faster.
Comment: I read a lot today without any result and I don't feel to read a whole book only about USB specifications. Can you maybe give me an example code of what I want to do? It can be very basic.
Comment: @Midas: Low-level stuff is not simple. I, for one, have spent a lot of time just reading the specs to get a better idea about how USB works. If you're looking for learn about things, it's sometimes better to read the docs instead of jumping into example code.
Comment: OK, I'll read it, but then I still don't know how to program for USB in C++.
Answer: How can one write a program for USB, wanting to understand the background of it, while not wanting to read much about it, not wanting to use a library, all in the same time?
Anyway. there is a project "libUSB Win32" from Stefan Meyer not under heavy development at the moment, but written in C maybe this could be something for you, it has also the ability to run under ancient windows versions ;)
you can find it here:
http://sourceforge.net/apps/trac/libusb-win32/wiki
a while ago i have written this in VB6 that makes use of "libUSB Win32" don't know if it can be useful for you:
http://www.activevb.de/cgi-bin/upload/download.pl?id=3061
Comment: libUSB is based on standard C++ code, isn't it? I could write this myself, adapted to my program.
I could maybe take a look at the source.
Comment: The URL seems to have changed. Your's doesn't work anymore.
But using Google I found this link to be working: https://sourceforge.net/projects/libusb-win32/
Comment: Also the wiki mentiions the following:
"libusb-win32 is now in Bug-Fix-Only maintenance mode. It is recommended new project[s] should migrate to libusb-1.0 API and use libusb Windows (http://libusb.info) instead."
Answer:
I simply need a list of all plugged in USB devices and have the user select one to let the console application receive any data the USB device sends.

Getting the list isn't the big problem, it's receiving the data.
I know you don't want to write a driver, but this is what drivers do: receive data from a device.
Answer: The advice you're getting here is on the mark; USB is not easy, believe me... I'm working on a USB project but from the back-end.  Seems to me that you need to be looking at the back-end too, that's where you really don't have to deal with libraries and all that, but you won't be able to get around the reading whatever you do.
Don't get discouraged yet, but you do need to wet you feet before you jump in and drown.  USB2.0 and USB3.0 are quite dry, but I found OSDev Wiki and usbmadesimple to be useful stepping stones.
If you still need to be in the PC, then you should consider trying to get a hold of some open source usb code for maybe a USB sniffer if you can find it.
Comment: Please don't add signatures to your posts. (As per the "Do not use signature, taglines, or greetings." section of [the help content](http://stackoverflow.com/help/behavior).)


Como faço um javascript que atualiza dados de um formulario?

Question: Estou começando a aprender javascript agora, e tenho de preencher um formulário com alguns dados que tenho em um banco.
Ao realizar a consulta no banco (através do php), u tenho um array multidimensional assim:
    Array ( [0] => Array ( [evento_id] => 2 [celebracao] => 3 [eventoNome] => ANIVERSÁRIO ARTHUR 2 ANOS [primeiroNome] => ARTHUR HENRIQUE [segundoNome] => [data] => 2018-04-08 [observacoes] => ) [1] => Array ( [evento_id] => 3 [celebracao] => 3 [eventoNome] => ANIVERSÁRIO DO ANDERSON [primeiroNome] => ANDERSON MOREIRA [segundoNome] => [data] => 2017-10-21 [observacoes] => ) )

O formulário é feito a partir de um select, como do código abaixo:

Evento: <select id="evento" name="evento" onchange="atualiza(this.value)">
       <?php foreach ($evento as $row) {
           echo "<option value=".$row['evento_id'].">".$row['eventoNome']." </option>";}?>
           </select>

Data: <input type="date" data-format="dd-mm-yyyy" name="data" id="data" disabled/>

         <?php
         if ($evento == null) {
            echo "
Noivo: <input type='text' name='primeiroNome' id='primeiroNome' disabled/>
";
            echo "
Noiva: <input type='text' name='segundoNome' id='segundoNome' disabled/>
";
           } else {
               echo "
Nome: <input type='text' name='primeiroNome' id='primeiroNome' disabled/>
";}

Eu sei que preciso dos ids dentro dos inputs para receber os dados do javascript, mas não estou sabendo como pegar o array que está em php, o value do select onde já vai estar com o nome do evento escolhido (ANIVERSÁRIO ARTHUR 2 ANOS value 2 ou ANIVERSÁRIO DO ANDERSON value 3) e atualizar os campos nome e data do form abaixo do select.
O script que eu fiz para isso é este:
    function atualiza(valor) {

        var eventoid = valor;
        var eventos = <?php echo json_encode($evento);?>;
        for(i=0; i<= eventos.length; i++){
            for (j=0; j<=eventos.length; j++){
                if (eventos.evento_id = eventoid){
                    document.getElementById('primeiroNome').innerHTML=(eventos.primeiroNome);
                    document.getElementById('segundoNome').value=(eventos.segundoNome);
                    document.getElementById('data').value=(eventos.data);
                    document.getElementById('evento_id').value=(eventos.evento_id);
                }
            }
        }
    }

Mas não está ocorrendo esta atualização, o que posso estar fazendo.
Qualquer ajuda é bem vinda.
Answer: Ok, vamos fazer algumas alterações no seu código:
Adicione uma propriedade data-row na tag option
echo "<option data-row='". json_encode($row) . "' value=".$row['evento_id'].">".$row['eventoNome']." </option>"

Depois mude o parâmetro passado para a função atualiza para this
<select id="evento" name="evento" onchange="atualiza(this)">

Agora mude sua função atualiza
function atualiza(select) {
    var selectedOption = select.querySelector('option:checked');
    var data = JSON.parse(selectedOption.getAttribute('data-row'));

    console.log(data);

    document.getElementById('primeiroNome').value=(data.primeiroNome);
    document.getElementById('segundoNome').value=(data.segundoNome);
    document.getElementById('data').value=(data.data);
    document.getElementById('evento_id').value=(data.evento_id);
}

Código completo no pastebin.
Answer: Suponho (sem testar tudo) que o problema esteja na função em javascript. Você não deve usar o json_encode nessa situação (ele vai simplesmente colocar uma string na variavel em questão). Deixe assim:
function atualiza(valor) {
    var eventoid = valor;
    var eventos = <?php echo $evento;?>;
    for(i=0; i<= eventos.length; i++){
        for (j=0; j<=eventos.length; j++){
            if (eventos.evento_id = eventoid){
                document.getElementById('primeiroNome').innerHTML=(eventos.primeiroNome);
                document.getElementById('segundoNome').value=(eventos.segundoNome);
                document.getElementById('data').value=(eventos.data);
                document.getElementById('evento_id').value=(eventos.evento_id);
            }
        }
    }
}

No mais use as ferramentas de depuração do navegador para ver tem algum erro em javascrit.
Comment: O problema que os dados que eu preciso estão em um array multidimensional, e são neles que estão as informações que eu preciso. Fazendo desta forma, o echo não imprimiu a variável $evento, e usando o print_r, apenas mostrou o array completo.


How does SGD come in the picture for Sequence to Sequence models?

Question: I was learning that seq2seq models (from the deeplearning.ai course) try to maximize:
$$ \max_{y} P_{\theta}(y_1 \dots y_{T'} \mid x_1 \dots x_T ) $$
I learned that one way they do it is via beam search. However, what I don't understand is where SGD comes in the picture. I will explain the way I think it comes in the picture and the true objective I think we are trying to optimize. I think we are actually trying to optimize:
$$ \max_{\theta,y} P_{\theta}(y_1 \dots y_{T'} \mid x_1 \dots x_T ) = \max_{\theta,y} J(\theta,y) $$
we want to optimize the most likely sequence but we also want to improve the RNN parameters (or at least that's what I would have thought, specially since in normal supervised learning thats what we do).
So according to that I believe this is the way it would be done:

at iteration $t$ we have model $\theta^{(t)}$
we get it's most likely sequence with beam search $\hat y = y_1 \dots y_{T'} := BeamSearch(x_1...x_T,\theta^{(t)})$
the using that most likely sequence we do SGD on the parameters according to the (normalized log likelihood)
$$\theta^{(t+1)} := \theta^{(t)} - \eta_t J(\theta^{(t)},\hat y)$$
which basically makes the current most likely sequence even more likely with SGD
repeat

I think this is probably wrong because it would seem this algorithm reinforces a specific sentence. If the first guess wasn't right I'd assume it would be some sort of horrible confirmation bias algorithm...but I can't see how SGD comes in the picture according to the descriptions I've read in Coursera's deeplearning.ai!
Answer: A sequence to sequence model produces a probability distribution over sequences $Y$ conditioned on another sequence $X$.
At test time, you may want to find the mode of that distribution: $\max_Y P(Y|X;\theta)$ -- the sequence which is most likely. For example if you have a translation model, you want to find the translation which has the highest probability under the model. This maximization must be done with beam search.
At training time, you already have $X,Y$ pairs from the data and you are simply trying to maximize the (log) likelihood of the model: $\max_\theta E[\log P(Y|X;\theta)]$. This is a completely different task from test time, and doesn't require beam search, and is done with SGD.
Comment: @Pinocchio in this context -- yes
Comment: So beam search is only during test time?


Python 3: RuntimeWarning with numpy.power

Question: When using numpy.power(2,N), where N is an integer, I encounter the following issue:
In[1] np.power(2,63)
Out[1] -9223372036854775808
RuntimeWarning: invalid value encountered in power

and even more strangely,
In[2] np.power(2,63)*2
Out[2] 0

This happens for all exponents greater than or equal to 63. I thought that large integer are not an issue in Python - what's wrong here, then?
Comment: You aren't dealing with Python integers here, you are dealing with NumPy integers which are of a fixed size (64 bits in this case), which is a prerequisite for the fast vectorized math operations that NumPy provides.  If you want to use Python ints, write `2**63` or `pow(2, 63)`.
Answer: Large integers are not a problem with Python because Python only has one integer type and that is of arbitrary precision. But NumPy uses normal "C" data types and these have limited precision:
>>> 2 ** 63              # Python
9223372036854775808

>>> np.int64(2) ** 63    # NumPy
-9223372036854775808

On most systems 64bit is the highest precision integer type available with plain NumPy. So if you're dealing with larger numbers you could use float dtypes or simply use Python integers with normal lists or NumPy object arrays (not really recommended).


Find matrix $P$ such that $P^{-1}AP=B$

Question:
Given $$A = \begin{bmatrix}
1 & 0 & 0 \\
0 & 2 & -3 \\
1 & 3 & 2 \end{bmatrix}$$ $$B= \begin{bmatrix}
1 & 0 & 0 \\
0 & 2 & -3 \\
0 & 3 & 2 \end{bmatrix}$$ find $P$ such that $P^{-1} A P = B$.

Firstly I said that $AP=PB$
Solved the 9 equations in 9 unknowns. and got that:
$$P= \left( \begin{array}{ccc}
-10x & 0 & 0 \\
3x & y & z \\
x & -z & y \end{array} \right)$$
Then I used computer to find $P^{-1}$ in terms of those unknowns and plugged it back in to
$P^{-1}AP=B$
Compared the coefficients and i end up with
$B= \left( \begin{array}{ccc}
1 & 0 & 0 \\
-z/10x & 2 & -3 \\
1-y/10x & 3 & 2 \end{array} \right) $
Set $x=1$, $y=10$, $z=0$ and indeed $P^{-1}AP=B$
The doubts I am having is the fact that P is not unique. I could set x,y,z to different numbers.
Can anyone explain this? Thank you.
Comment: Suppose that $P$ solves your problem, then $\alpha P$ will also solve it for any $\alpha \neq 0$ so the solution is never unique.
Comment: Left multiply both sides by $P$? Is there a better method?
Comment: That is very true. Thank you. I believe it won't change anything no matter which way i do it?
Answer: The computation is correct, and we cannot expect that $P$ is unique in general. A somewhat extreme case is $A=B=0$, where any invertible $P$ will do.
Answer: Using SymPy:
<code>>>> from sympy import *
>>> X = MatrixSymbol('X',3,3)
>>> A = Matrix([[ 1, 0, 0],
                [ 0, 2,-3],
                [ 1, 3, 2]])
>>> B = Matrix([[ 1, 0, 0],
                [ 0, 2,-3],
                [ 0, 3, 2]])
>>> simplify(Matrix(A*X - X*B))
Matrix([
[                            0,            -X[0, 1] - 3*X[0, 2],             3*X[0, 1] - X[0, 2]],
[          X[1, 0] - 3*X[2, 0],          -3*(X[1, 2] + X[2, 1]),           3*(X[1, 1] - X[2, 2])],
[X[0, 0] + 3*X[1, 0] + X[2, 0], X[0, 1] + 3*X[1, 1] - 3*X[2, 2], X[0, 2] + 3*X[1, 2] + 3*X[2, 1]]])
</code>
If $\rm A X - X B = O_3$, we have an underdetermined homogeneous system of $3^2 - 1$ linear equations in $3^2$ unknowns. Thus, we have at least $1$ degree of freedom. We vectorize the matrix equation
$$\left( \mathrm I_3 \otimes \mathrm A - \mathrm B^{\top} \otimes \mathrm I_3 \right) \mbox{vec} (\mathrm X) = 0_9$$
and let $\mathrm M := \mathrm I_3 \otimes \mathrm A - \mathrm B^{\top} \otimes \mathrm I_3$. Using SymPy:
<code>>>> I3 = Identity(3)
>>> O3 = ZeroMatrix(3,3)
>>> M = BlockMatrix([[A - I3,       O3,       O3],
                     [    O3, A - 2*I3,    -3*I3],
                     [    O3,     3*I3, A - 2*I3]])
>>> Matrix(M)
Matrix([
[0, 0,  0,  0, 0,  0,  0,  0,  0],
[0, 1, -3,  0, 0,  0,  0,  0,  0],
[1, 3,  1,  0, 0,  0,  0,  0,  0],
[0, 0,  0, -1, 0,  0, -3,  0,  0],
[0, 0,  0,  0, 0, -3,  0, -3,  0],
[0, 0,  0,  1, 3,  0,  0,  0, -3],
[0, 0,  0,  3, 0,  0, -1,  0,  0],
[0, 0,  0,  0, 3,  0,  0,  0, -3],
[0, 0,  0,  0, 0,  3,  1,  3,  0]])
>>> Matrix(M).rank()
6
</code>
Hence, we have $3^2 - 6 = 3$ degrees of freedom.
Comment: Yes I know realised that the answer I posted only works for PAP^-1

P^-1AP allows you to set all three unknowns, as long as resulting P is invertible.

Find matrix $P$ such that $P^{-1}AP=B$


NSInternalInconsistencyException - Could not load NIB in bundle:

Question: I am trying to bundle all my .xib resources into a "ViewController.bundle" to ship along with "MyLibrary.framework". If I just place all the .xib files in the framework project, everything is working fine, but if I put them inside "ViewController.bundle", everything break apart
<code>*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'Could not load NIB in bundle:
'NSBundle </Users/administrator/Library/Application Support/iPhone Simulator/5.0/
Applications/8AD68FD1-158E-4926-AE03-8FEF870E7012/ios.app/ViewController.bundle>
(not yet loaded)' with name 'FirstViewController_iPhone''
*** First throw call stack:
(0x160e052 0x1071d0a 0x15b6a78 0x15b69e9 0x3ff838 0x2a6e2c 0x2a73a9 0x2a75cb 0x2c2b89 0x2c29bd
0x2c0f8a 0x2c0d7e 0x2c0a22 0x2bfd88 0x5e3ac 0x2df8 0x2e34 0x160fec9 0x1e45c2 0x1e455a 0x289b76
0x28a03f 0x2892fe 0x209a30 0x209c56 0x1f0384 0x1e3aa9 0x1eedfa9 0x15e21c5 0x1547022 0x154590a
0x1544db4 0x1544ccb 0x1eec879 0x1eec93e 0x1e1a9b 0x2452 0x2385)
</code>
I have tried various ways:
1. Creating the "ViewController.bundle" in Finder, place all the .xib there, and drag to xcode
2. Create a new Target for the framework project, choose "Bundle" under "Framework & Library" in "OS X" section (Note: it has to be OSX since I am using xcode 4.6 which do not have "Bundle" under its "Framework & Library" - it used to have, and I used to create bundle that contains .png resources using this wizard)
Under both circumstances, I have made sure that the "ViewController.bundle" exist in "Build Phase" >> "Copy Bundle Resources" in my target app.
I also tried including "ViewController.bundle" under "Target Dependencies" of my Framework project, but all my efforts resulted in the same crash.
I also tried various ways to load the .xib, to no avail. However, the following code that load a .png resource from the same "ViewController.bundle" works perfectly:
<code>// Loading .png resource works perfectly
//  UIImage* closeImage = [UIImage imageNamed:@"ViewController.bundle/first.png"];
//  NSString *szBundlePath = [[NSBundle mainBundle] pathForResource:@"ViewController" ofType:@"Bundle"];
//  UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"showView" message:szBundlePath delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
//  UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(220, 10, 40, 40)];
//  [imageView setImage:closeImage];
//  [alertView addSubview:imageView];
//  [alertView show];
//  return;
</code>
Using the same code to load the xib failed:
<code>NSBundle *bViewController = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"ViewController" withExtension:@"bundle"]];
if ( [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone ) {
    self.m_pFirstViewController = [[[FirstViewController alloc] initWithNibName:@"FirstViewController_iPhone" bundle:bViewController] autorelease];
    self.m_pSecondViewController = [[[SecondViewController alloc] initWithNibName:@"SecondViewController_iPhone" bundle:bViewController] autorelease];
} else {
    self.m_pFirstViewController = [[[FirstViewController alloc] initWithNibName:@"ViewController.bundle/FirstViewController_iPad" bundle:nil] autorelease];
    self.m_pSecondViewController = [[[SecondViewController alloc] initWithNibName:@"ViewController.bundle/SecondViewController_iPad" bundle:nil] autorelease];
}

    /** It crash in this line!! Note however, both m_pFirstViewController and m_pSecondViewController is allocated and not nil */
self.viewControllers = @[self.m_pFirstViewController, self.m_pSecondViewController];

    /** never reach here already crash */
[[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:self animated:YES completion:^{
    NSLog( @"presented!" );
}];
</code>
I have spent the last 8 hours debugging this, googling and tried various suggestions from SO, but to no avail... any help is greatly appreciated! Thanks!
Comment: my be some control deleted from xib and it maped with xib.
Comment: no, all the .xib are included, however, I checked the .bundle inside the .app, they are all included as is. ie: .xib, but the error seems like it is expecting the compiled version (.nib)
Answer: The 2nd way that I tried is the closest... Then modify the OSX bundle to iOS bundle in the Build Settings. Apparently, there are several steps that I missed. I followed the tutorial and sample project by Matt Galloway here:
http://www.galloway.me.uk/tutorials/ios-library-with-resources/
and now everything works as intended.
Thanks everyone for your help!
Comment: Thank you! Added note: if your png files are being turned into tiffs, add this  "User-Defined" build setting:
`COMBINE_HIDPI_IMAGES = NO`


Bootstrap 4.0 dropdown menu not using the full height of the nav bar

Question: Im looking for some help, im a bit new to programming and I have tried to google my way to a solution, but can´t figure it out.
how can i get the dropmenu to use the full height of the nav bar?
I have tried to do it with CSS but can´t get it the work. I have added a picture
showing the problem.
enter image description here
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Heima</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

  <link rel="stylesheet" href="static/landing/styles.css">

    .navbar-dark:hover .navbar-nav:hover .nav-link:hover
{
color: #fff;
width: 100%;
}

.bg-color{
background-color: #18191a;
}

.dropdown:hover{
background-color: #2f2f30;
height: 10%;
}

a:hover{
link-color: #fff;
color: #fff;
}

a{
link-color: #fff;
color: grey;
}

.nav-item dropdown
{
width: 100%;
}

    Logo

        Akfør

        Link 1
        Link 2
        Link 3

        Dropdown link

        Link 1
        Link 2
        Link 3

        Dropdown link

        Link 1
        Link 2
        Link 3

Comment: Your ``'s should be placed inside a `` element and you probably need to remove the vertical default padding of the `.navbar` by adding class `.py-0` to it
Comment: I did just try that, and it removed almost all of the spacing, but there is still a bit for space between the dropdown menu and the bottom/top of the navbar
Answer: From what I understand your issue is the padding of the navbar.
Try adding the following to your css:
.navbar {
padding: 0px 1rem;
}

Or add the following class to your navbar:
py-0

This will remove the padding and therefore the dropdown shadow will use the full height of the navbar.