Insert string/source command after #!/bin/bash line in a bash file

Question: I'm trying to insert a certain string after the #!/bin/bash line in a separate bash file but I'm running into issues with my sed statement not parsing through the characters correctly. I'm basing my example off of solutions here https://unix.stackexchange.com/questions/121161/how-to-insert-text-after-a-certain-string-in-a-file
So for example, I have a sed statement that is trying to write a source command to scriptOne.sh:
sed '/#!/bin/bash/a source /root/documents/folder/scriptTwo.sh' /root/home/scriptOne.sh

I would like scriptOne.sh to go from this:
#!/bin/bash

to this after running my script:
#!/bin/bash

source /root/documents/folder/scriptTwo.sh

The sed command doesn't seem to work I think because of the extra slashes and characters it's having trouble separating from an actual string vs regex characters. Ideally I would also like to insert an extra blank line between the #!/bin/bash and source command, but my main goal is just to insert that source command under the #!/bin/bash.
Update:
I tried this in my script (just another random script located in /home/student/Desktop):
#!/bin/bash

sed '\~#!/bin/bash~ a\
\
source /root/documents/folder/scriptTwo.sh' /root/home/scriptOne.sh

but when I run it, scriptOne.sh does not get altered.
Answer: You may use sed like this:
sed -i.bak '\~#!/bin/bash~ a\
\
source /root/documents/folder/scriptTwo.sh' /root/home/scriptOne.sh

Comment: Check my updated answer. You just needed `-i` flag
Comment: Hello, my script looks like this:

#!/bin/bash

sed '\~#!/bin/bash~ a\
\
source /root/documents/folder/scriptTwo.sh' /root/home/scriptOne.sh

And when I run the script, scriptOne.sh doesn't seem to change - it only has the bin/bash line with no source command being added after that.
Comment: Sorry for the formatting, I described my problem in my updated post


How to do download from html grid to excel or CVS file in my c# code

Question: I am writing a windows service that is supposed to act as a robot.
it should go to a webpage and does some acitvities like logging on, and then pressing a button to take some records from other side.
now I am almost done with everything and records has been take from server.
but I don't know to download the records from HTML grid to a excel or CVS local file with c# and .net framework.
the question is: how to download from html grid to local file with .net framework
I am not using asp.net, it is just a windows service
Comment: actually records are available on my html document
Comment: What framework are you using to connect to the website?  Is there a button on the site to download the values in another format?
Comment: I am using awsoemium, there is button to export and there is a radio button that allows to choose between cvs and excel, but I am new and have no idea how i can find out what to do
Answer: <code>****on click of the button you can dowload the excel****

 protected void btn_download_template(object sender, EventArgs e)
        {
            string str_FolderPath = "c:/Budget_Sample.xlsx";
            Response.ContentType = ContentType;
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(str_FolderPath));
            Response.WriteFile(str_FolderPath);
            Response.End();
        }
</code>


How to get innerHTML of this element in javascript?

Question: Pretty simple question. I have an element (a tag) which has an onclick to call a javascript function. Amoung other things, I want this function to echo the innerHTML of the element that called it. So, in this case, the innerHTML of the atag.
How do I do this?
Answer: <element onClick="alert(this.innerHTML);"> ... </element>

Comment: +1 Nothing wrong with inline handlers. They can be very useful, and solve or simplify some problems.
Comment: `this.innerHTML` is the important part, so it's a valid answer.
Comment: "It works" isn't enough. The reason that went out of fashion is because it is poor practise.
Comment: Nice try, but It kind of dismisses the fact that I said call a javascript function
Comment: +1 for an excellently efficient suggestion that doesn't require you to build a function outside of the element to call to reference back to the element itself to handle its own content
Answer: markup:
<element id="foo"> ... </element>

js:
document.getElementById('foo').addEventListener('click', fn);

function fn(){ alert(this.innerHTML); }

http://jsfiddle.net/g7Bau/2/
The important thing to note here, which essentially answers your question, is that the event listener when called has binds this to the DOM node that caused the event to fire. So we can use this in the function and it's generic. You could add another element, and bind a click listener also using fn and the one function would work for both elements.
Comment: @Raynos, you're right. The trend in all major browsers is to make it optional though, as per the HTML5 spec. This clearly isn't a cross-browser solution, since <IE9 this won't even work...


List not being saved

Question: I'm trying to save a list of question options but its not being saved. Only the last row is being save.
Below is the code.
<code>@Transactional
public void addQuestionOptions(QuestionOptionsRequest questionOptionsRequest, int questionId) {
    List<QuestionOption> optionList = new ArrayList<>();
    QuestionOption options = new QuestionOption();

    Question question = questionRepository.findByQuestionId(questionId);
    if(question != null) {
        questionOptionsRequest.getQuestionOptions()
                .stream()
                .forEach(option -> {
                    options.setQuestionOption(option.getQuestionOption());
                    options.setQuestion(question);
                    options.setQuestionOptionNumber(option.getQuestionOptionNumber());
                    optionList.add(options);
                });
        questionOptionRepository.saveAll(optionList);
    }
}
</code>
QuestionOption
<code>@Entity
@JsonIgnoreProperties({"question"})
public class QuestionOption {

    @Id
    @GeneratedValue
    private int questionOptionId;

    private int questionOptionNumber;

    private String questionOption;

    public Question getQuestion() {
        return question;
    }

    public void setQuestion(Question question) {
        this.question = question;
    }

    @ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
    private Question question;

    public void setQuestionOptionNumber(int questionOptionNumber)
    {
        this.questionOptionNumber = questionOptionNumber;
    }

    public void setQuestionOption(String questionOption)
    {
        this.questionOption = questionOption;
    }

    public String getQuestionOption()
    {
        return this.questionOption;
    }

    public int getQuestionOptionNumber()
    {
        return this.questionOptionNumber;
    }

    public int getQuestionOptionId() {
        return questionOptionId;
    }

    public void setQuestionOptionId(int questionOptionId) {
        this.questionOptionId = questionOptionId;
    }
}
</code>
Question
<code>@Entity
@Getter
@Setter
public class Question {

    @Id
    @GeneratedValue
    private int questionId;

    private int assessmentId;

    private QuestionTypes questionType;

    private String questionText;

    private String questionURL;

    private QuestionStatus questionStatus;

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="question")
    private List<QuestionOption> questionOptions;

    public void setQuestionId(int queId)
    {
        this.questionId = queId;
    }

    public void setQuestionText(String queTxt)
    {
        this.questionText = queTxt;
    }

    public void setQuestionType(QuestionTypes queType)
    {
        this.questionType = queType;
    }

    public void setQuestionURL(String queURL)
    {
        this.questionURL = queURL;
    }

    public int getQuestionId() {
        return questionId;
    }

    public String getQuestionText() {
        return questionText;
    }

    public QuestionStatus getQuestionStatus() {
        return questionStatus;
    }

    public void setQuestionStatus(QuestionStatus questionStatus) {
        this.questionStatus = questionStatus;
    }

    public QuestionTypes getQuestionTypes() {
        return this.questionType;
    }

    public String getQuestionURL() {
        return this.questionURL;
    }

    public int getAssessmentId() {
        return this.assessmentId;
    }

    public void setAssessmentId(int assessmentId) {
        this.assessmentId = assessmentId;
    }

    public QuestionTypes getQuestionType() {
        return questionType;
    }
}
</code>
Answer: You are creating only one object of QuestionOption
QuestionOption options = new QuestionOption();
Create this object inside for each.
Comment: I tried that but I'm getting a constraint violation exception. com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'PRIMARY'

List not being saved


What's wrong with the function multiplyTwoMatrices() in this C code for finding fibonacci using matrix multiplication?

Question: #include<stdio.h>

void multiplyTwoMatrices(int (*)[2], int[][2], int[][2]);
void copyMatrix(int[][2], int[][2]);
void powerAMatrix(int[][2], int[][2], int);

int main()
{
    int num;
    scanf("%d", &num);

    int i;
    for(i = -1; i <= num; i++)
    {
        printf("\n%d", fib(i));
    }
}

int fib(int num)
{
    if(num <= 0)
    {
        return 0;
    }
    else
    {
        int matrix[2][2] = {{1, 1}, {1, 0}};
        //int fibMatrix[2][2] = powerAMatrix(matrix[2][2], num);
        int fibMatrix[2][2];
        powerAMatrix(fibMatrix, matrix, num);
        return getFibNum(fibMatrix);
    }
}

void powerAMatrix(int fibMatrix[2][2], int matrix[2][2], int num)
{
    //fibMatrix = matrix;
    copyMatrix(fibMatrix, matrix);
    int i = 0;
    for(i = 1; i < num; i++)
    {
        //fibMatrix = fibMatrix * matrix;
        multiplyTwoMatrices(fibMatrix, fibMatrix, matrix);
    }
}

void copyMatrix(int destinationMatrix[2][2], int sourceMatrix[2][2])
{
    int i = 0; int j = 0;
    for(i = 0; i < 2; i++)
        for(j = 0; j < 2; j++)
            destinationMatrix[i][j] = sourceMatrix[i][j];
}

void multiplyTwoMatrices(int multipliedMatrix[2][2], int matrixA[2][2], int matrixB[2][2])
{

    int i = 0; int j = 0; int k = 0;
    for(i = 0; i < 2; i++)
    {
        for(j = 0; j < 2; j++)
        {
            multipliedMatrix[i][j] = 0;     //or just initialize it as a zero matrix.
            for(k = 0; k < 2; k++)
            {
                multipliedMatrix[i][j] += (matrixA[i][k] * matrixB[k][j]);
            }
        }
    }
                    //working alternative
    /*
    int x =  matrixA[0][0]*matrixB[0][0] + matrixA[0][1]*matrixB[1][0];
    int y =  matrixA[0][0]*matrixB[0][1] + matrixA[0][1]*matrixB[1][1];
    int z =  matrixA[1][0]*matrixB[0][0] + matrixA[1][1]*matrixB[1][0];
    int w =  matrixA[1][0]*matrixB[0][1] + matrixA[1][1]*matrixB[1][1];

    multipliedMatrix[0][0] = x;
    multipliedMatrix[0][1] = y;
    multipliedMatrix[1][0] = z;
    multipliedMatrix[1][1] = w;
    */
}

int getFibNum(int fibMatrix[2][2])
{
    return fibMatrix[0][1];
}

The function multiplyTwoMatrices() seems to work only if "working alternative" (code closed in comments inside this function) is used instead of the one used currently. I'm unable to understand what is going wrong with this code. A little help is appreciated.
Output expected: 0 0 1 1 2 3 5 8 ...
Output coming:   0 0 1 1 1 1 1 1 ...
Answer: while your multiplication function is correct, it doesn't work correctly when the destination is one of the operands; if it is, the operand is changed there while the calculation is underway.
Either require that multipliedMatrix is distinct from both matrixA and matrixB (that'd be preferred), or have a temporary matrix there and copy it into the result!

P.S. it would be much easier wrapping the matrix class into a struct:
struct intmatrix2x2 {
    int values[2][2];
};

this would make implicit copies when calling functions; and instead of copyMatrix you can say:
struct intmatrix2x2 b = a;

and your multiplication could read as
struct intmatrix2x2 multiply(struct intmatrix2x2 a, struct intmatrix2x2 b)
{
    struct intmatrix2x2 result;
    int i = 0; int j = 0; int k = 0;
    for(i = 0; i < 2; i++)
    {
        for(j = 0; j < 2; j++)
        {
            result.values[i][j] = 0;     //or just initialize it as a zero matrix.
            for(k = 0; k < 2; k++)
            {
                result.values[i][j] += a.values[i][k] * b.values[k][j]);
            }
        }
    }
    return result;
}

and you could use it as
struct intmatrix2x2 result = multiply(a, b);


Always prompt for a shipping address even if there are no shippable products with Ubercart

Question: I manage a site selling online classes. Some classes include shipped items (books, posters, etc); for these classes, the cost of shipping is included in the class price.
Ubercart products are configured as non-shippable, as automated shipping quotes through UPS should not add any additional cost.
I'd like to configure Ubercart (6.x-2.4) to always prompt users to enter a shipping address, without returning an error message when products in the order are not flagged as shippable.
At present, Ubercart will always prompt the user for a shipping address if "Hide shipping information when possible for carts with no shippable items" is unchecked in "Checkout settings." However, it looks like the UPS module will always try to calculate a shipping quote if shipping details are prompted for, regardless of whether items are shippable or not. If this is the case, an error message is displayed informing the user that a shipping could not be calculated.
Is it possible to configure shipping settings to still prompt for a shipping address, while preventing shipping modules such as UPS from returning an error message if no shippable products are configured?
For example:

    Order A: (works with UPS shipping module)
         Shippable_product_A  $10 (shipping $5)
         Shippable_product_B  $20 (shipping $8)
         --------------------------------------
         Total order cost: $30 + $13 => $43

    Order B: (does NOT work with UPS)
         Shippable_product_A    $10 (shipping $5)
         Non-Shipped_product    $15
         ---------------------------------------
         Total order cost: $25 + $5 = $30

Comment: I don't understand your approach. Why not to set items with shippable elements as shippable products, and set free shipping on them? If UPS module does not work with [free shipping as described](http://www.ubercart.org/docs/user/30515/how_setup_free_shipping), you should file a bugreport, or check issue queue for patches that may already be available.
Comment: This is a very, very old question. Modules have changed since then. The question was asked regarding a situation in Ubercart for Drupal 6. The link you gave is for Drupal 7 and an updated version of Ubercart.
Answer: The only work around for this is to alter the UPS module yourself or report it as bug, (because in my opinion, this is a bug.)
You could probably write a module that would override the UPS module to circumvent the above suggestions. You have pretty clearly hit the nail on the head though. The problem is not Ubercart but the modules that are interacting with it inappropriately. I know the FedEx module takes into account shipable products, if my memory serves me correctly.
The entire shipping pane should be hidden if there are no shipable items. (That is the point of having that option in the products.)


For a Variational Autoencoder (VAE) couldn't we just sample from a standard normal distribution without the encoder at training?

Question: Normally when training a VAE, we have an encoder and a decoder. The encoder maps the input to a series of values that represent the mean and variance of a distribution (the size of this output tensor is 2 * latent_size). After that, we sample from this (using the reparametrization trick) and the decoder uses these values to generate an output. The loss tries to both minimize the distance between the generated output and the input and to move the means and stds from the encoder close to 0 and 1 (standard distr.)
Considering the fact that at "inference" / generation, we are sampling directly from a standard normal distribution, couldn't we have just trained the decoder with samples like this and not use the encoder, which ultimately only learns to map the input to the 0, 1 pairs (from my experience by the end of the training they get quite close to these values)? We will still have the latent space regularization we need for generating coherent outputs.
Also because the KL loss part uses directly the outputs from the encoder, there is no gradient to somehow affect the decoder, so the decoder only learns from the reconstruction loss. (I might be wrong here)
A quick reference implementation of what I was thinking:
<code>import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Load MNIST dataset
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
mnist = torchvision.datasets.MNIST(root='./data', download=True, transform=transform)

batch_size = 128
train_dataset = torch.utils.data.DataLoader(mnist, batch_size=batch_size, shuffle=True, pin_memory=True, num_workers=4)

class VAE(nn.Module):
    def __init__(self, input_size, hidden_size, latent_size):
        super(VAE, self).__init__()
        self.latent_size = latent_size
        self.input_size = input_size
        self.hidden_size = hidden_size

        self.fc1 = nn.Linear(input_size, hidden_size)
        self.fc2 = nn.Linear(hidden_size, latent_size * 2)
        self.fc3 = nn.Linear(latent_size, hidden_size)
        self.fc4 = nn.Linear(hidden_size, input_size)

    def encoder(self, x):
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

    def reparameterize(self, mu, log_var):
        std = torch.exp(0.5 * log_var)
        eps = torch.randn_like(std)
        return eps.mul(std).add_(mu)

    def decoder(self, z):
        z = F.relu(self.fc3(z))
        z = torch.sigmoid(self.fc4(z))
        return z

    def forward(self, x, z):
        # mu, log_var = self.encoder(x).split(self.latent_size, dim=1)
        # z = self.reparameterize(mu, log_var)
        recon_x = self.decoder(z)
        return recon_x

def loss_fn(recon_x, x):
    BCE = F.binary_cross_entropy(recon_x, x, reduction='sum')
    # KLD = -torch.mean(-0.5 * torch.sum(1 + log_var - mu ** 2 - log_var.exp(), dim = 1), dim = 0)
    return BCE

# Initialize VAE model
input_size = 784
hidden_size = 512
latent_size = 32
model = VAE(input_size, hidden_size, latent_size)
model = model.to(device)

# Choose optimizer and loss function
optimizer = torch.optim.Adam(model.parameters(), lr=1e-5)

# Train loop
num_epochs = 10
for epoch in range(num_epochs):
    train_loss = 0
    for x, _ in train_dataset:
        x = x.view(-1, 784).to(device)
        z = torch.randn(x.shape[0], latent_size)
        z = z.to(device)
        recon_x = model(x, z)
        loss = loss_fn(recon_x, x)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        train_loss += loss.item()

    print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {train_loss / len(train_dataset.dataset)}')

</code>
Any reviews or improvements are more than welcome!
Answer: If you want to use the decoder as a generative model, you can theoretically input random vectors and force it to generate an image (this is what the generator in a GAN does). But that would cause, in the best case, that the model will only work for specific random vectors.
If you just not use the encoder you're basically generating 2 random vectors which output two different images. What happens if you take 2 very similar images in the training set, the same image rotated by 1 degree for example, and randomly generate two random vectors that are very far apart?
Also think of the inverse case where you generate 2 infinitesimally close random vectors, but force them to generate very different images ( a white plane over blue skies and a black sheep in a green meadow).
You are basically forcing the generative model to learn contradictory information and therefore hurting performance.
The clever solution for that was the encoder. It allows the model to automatically constrain the random vectors so that similar inputs generate similar random vectors, thus allowing the decoder to learn much better. It also makes the latent space continuous so that for every random vector you get a pretty valid output.
Hope it helps somewhat.
Comment: Hi, thank you for your answer! The two examples with similar vectors - different images and different vectors - similar images were quite helpful for creating an intuition. Also yeah, I guess the question was quite similar to a GAN generator. Great answer!


como faço pra imprimir a linha que está o menor elemento de uma matriz?

Question: #include <iostream>

using namespace std;

int main()
{
    int m[4][4],i,j,menor;
    for(i=0;i<4;i++){
        for(j=0;j<4;j++){
           cin>>m[i][j];
           if (i == 0 and j == 0){
               menor=m[0][0];
           }
           if(m[i][j]<menor){
            menor=m[i][j];
           }
        }
    }

    cout<<"O menor numero e:"<<menor<<endl;
    return 0;
}

Answer: Se entendi corretamente sua pergunta, você quer o número da linha do valor inserido e não da matriz. Para ambas as formas, você pode monitorar as inserções (variável insercoes) e guardar o valor da inserção menor em uma variável (nesse caso linhaDoMenorNumero) ou atualizar a variável com o índice da linha atual da sua matriz (variável i):
int m[4][4], i, j, menor, linhaDoMenorNumero, insercoes = 0;

for (i = 0; i < 4; i++) {
    for (j = 0; j < 4; j++) {
       cin >> m[i][j];
       insercoes++;

       if (i == 0 and j == 0) {
           menor = m[0][0];
       }

       if(m[i][j] < menor) {
        // para encontrar a linha da matriz, basta substituir "insercoes" por "i"
        linhaDoMenorNumero = insercoes;
        menor = m[i][j];
       }
    }
}

cout << "O menor numero e: " << menor << endl;
cout << "Na linha: " << linhaDoMenorNumero << endl;
return 0;

Espero ter ajudado de alguma forma.
Comment: muito obrigada!


Confused about the visual explanation of eigenvectors: how can visually different datasets have the same eigenvectors?

Question: A lot of statistics textbooks provide an intuitive illustration of what the eigenvectors of a covariance matrix are:

The vectors u and z form the eigenvectors (well, eigenaxes). This makes sense. But the one thing that confuses me is that we extract eigenvectors from the correlation matrix, not the raw data. Furthermore, raw datasets that are quite different can have identical correlation matrices. For example, the following both have correlation matrices of:
$$\left[\begin{array}{} 1 & 0.97 \\ 0.97 &1\end{array}\right]$$

As such they have eigenvectors pointing in the same direction:
$$\left[\begin{array}{} .71 & -.71 \\ .71 & .71\end{array}\right]$$
But if you were to apply the same visual interpretation of which directions the eigenvectors were in the raw data, you would get vectors pointing in different directions.
Can someone please tell me where I have gone wrong?
Second Edit: If I may be so bold, with the excellent answers below I was able to make sense of the confusion and have illustrated it.

The visual explanation coheres with the fact that the eigenvectors extracted from the covariance matrix are distinct.
Covariances and Eigenvectors (Red):
$$\left[\begin{array}{} 1 & 1 \\ 1 & 1\end{array}\right] \left[\begin{array}{} .7 & -.72 \\ .72 & .7\end{array}\right]$$
Covariances and Eigenvectors (Blue):
$$\left[\begin{array}{} .25 & .5 \\ .5 & 1\end{array}\right] \left[\begin{array}{} .43 & -.9 \\ .9 & .43\end{array}\right]$$
Correlation matrices reflect the covariance matrices of the standardized variables. Visual inspection of the standardized variables demonstrate why identical eigenvectors are extracted in my example:
Comment: If you wish to evaluate *correlation*, then you must draw your scatterplots with scales in which the standard deviations of the components are equal. That is not the case in any of your images (except perhaps for the red dots in the second one), which may be one reason you find this confusing.
Comment: I appreciate your having illustrated your question. That helps people understand it & adds to the value of the thread for future reference. Be aware, however, that ~10% of men are red-green colorblind. With 2 colors, red & blue may be safer.
Comment: No problem, @SueDohNimh. Thank you for making it intelligible for all. On a different note, I would keep the `[PCA]` tag. If you want to re-focus the question, or ask a new (related) question & link to this one, that seems fine, but I think this question is PCA-ish enough to merit the tag.
Comment: Many thanks, I have corrected the colors as you suggested
Comment: Nice job, @SueDohNimh. You could also add that as an answer to your own question instead of an edit, if you wanted to.
Answer: You don't have to do PCA over the correlation matrix; you can decompose the covariance matrix as well.  Note that these will typically yield different solutions.  (For more on this, see: PCA on correlation or covariance?)
In your second figure, the correlations are the same, but the groups look different.  They look different because they have different covariances.  However, the variances are also different (e.g., the red group varies over a wider range of X1), and the correlation is the covariance divided by the standard deviations (${\rm Cov}_{xy} / {\rm SD}_x{\rm SD}_y$).  As a result, the correlations can be the same.
Again, if you perform PCA with these groups using the covariance matrices, you will get a different result than if you use the correlation matrices.
Comment: +1 You have probably also noticed that with two variables the correlation matrix always has the same two eigenvectors, $(1,1)$ and $(1,-1)$, *no matter what value the correlation has.*
Comment: +1 to what @whuber wrote, but note that the corresponding eigenvalues do depend on the correlation value.
Comment: Hi guys, many thanks. I was aware that distinct eigenvectors arise from using the covariance matrices instead; this was a further source of concern as I made me worry that by using correlation matrices instead I was reducing the information being used and therefore being less accurate.

Would it be sensible to conclude based on your responses that the visual interpretation provided is only really applicable to eigenvectors of the covariance matrix of the raw data rather than the correelation matrix?
Comment: Not really, @SueDohNimh. You can use the visual interpretation, just standardize your variables first if you want to use the correlation matrix.
Comment: This is true, but the eigenvectors of the Cov matrix can vary based on the correlation.
Comment: And another thread http://stats.stackexchange.com/q/62677/3277


Spring Data JPA: Como fazer projeção de dados?

Question: Estou seguindo um tutorial para fazer projeção com base neste link. Porém, parece que a aplicação esta gerando um erro na serialização dos dados emitidos pela reflexão do Jackson.
Segue erro gerado:
<code>"message": "No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.ae1.domain.profile.dtos.PersonalInformationDto]",
    "trace": "org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.ae1.domain.profile.dtos.PersonalInformationDto]\r\n\tat org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321)\r\n\tat org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194)\r\n\tat org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:174)\r\n\tat org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:297)\r\n\tat org.springframework.data.repository.query.ResultProcessor$ChainingConverter.lambda$and$0(ResultProcessor.java:217)\r\n\tat org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:228)\r\n\tat org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:156)\r\n\tat org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:157)\r\n\tat org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:142)\r\n\tat org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:618)\r\n\tat org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:605)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)\r\n\tat org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:149)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)\r\n\tat com.sun.proxy.$Proxy130.findAllCustom(Unknown Source)\r\n\tat com.ae1.business.profile.services.implementations.PersonalInformationServiceImpl.findAll(PersonalInformationServiceImpl.java:21)\r\n\tat com.ae1.application.profile.controllers.PersonalInformationController.findAll(PersonalInformationController.java:24)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:567)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:634)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:113)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)\r\n\tat org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)\r\n\tat org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat com.ae1.domain.security.filters.JwtAuthenticationTokenFilter.doFilterInternal(JwtAuthenticationTokenFilter.java:48)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)\r\n\tat org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)\r\n\tat org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)\r\n\tat org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)\r\n\tat org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.base/java.lang.Thread.run(Thread.java:830)\r\n",
</code>
Segue implementação da minha classe DTO:
<code>@Getter @Setter @NoArgsConstructor
public class PersonalInformationDto {
    private Integer id;
    private String name;
    private String fatherName;
    private String motherName;
    private Genrer genrer;
    private MaritalStatus maritalStatus;
    private LocalDate birthDate;
    private ProfessionDto profession;
    private String about;

    public PersonalInformationDto(Integer id, String name, String fatherName, String motherName, Genrer genrer, MaritalStatus maritalStatus, LocalDate birthDate, ProfessionDto profession, String about) {
        this.id = id;
        this.name = name;
        this.fatherName = fatherName;
        this.motherName = motherName;
        this.genrer = genrer;
        this.maritalStatus = maritalStatus;
        this.birthDate = birthDate;
        this.profession = profession;
        this.about = about;
    }
}
</code>
Segue meu prepositório:
<code>@Repository
public interface PersonalInformationRepository extends JpaRepository<ProfileEntity, Integer> {

    @Query("select person.name, person.fatherName, person.motherName, person.genrer, person.maritalStatus, person.birthDate, person.profession, profile.about from Person person join Profile profile on profile.person = person")
    List<PersonalInformationDto> findAllCustom();

}
</code>
Answer: Esta quase certo, você deve construir a instância diretamente na <code>@Query</code>:
<code>@Repository
public interface PersonalInformationRepository extends JpaRepository<ProfileEntity, Integer> {

    @Query("select new com.ae1.domain.profile.dtos.PersonalInformationDto(person.name, person.fatherName, person.motherName, person.genrer, person.maritalStatus, person.birthDate, person.profession, profile.about) from Person person join Profile profile on profile.person = person")
    List<PersonalInformationDto> findAllCustom();

}
</code>
Se atente ao fato da necessidade de um construtor que corresponda aos parâmetros utilizados na montagem da query, caso contrário não haverá como construir a instância.
Comment: Neste contexto, tenho profession sendo também um DTO. Como converter de entidade para dto usando a própria reflexão... pois o erro esta nele.
Comment: Eu fiz usando uma projeção fechada. E também usando a sua forma, mas existem problemas na serialização de outros objetos, que precisam estar como DTO.
Comment: @ThiagoCunha, conseguiu descobrir?


CSS para styled-components

Question: Olá, queria saber se tem como usar a tag para selecionar todos os elementos, que em css é * mas no styled-components.
EX:
*{
 box-sizing: border-box;
 background-color: #fff;
}

Aqui ele adiciona border-box e a cor de fundo para branco a todos os elementos da pagina. E eu quero fazer igual mas com styled-components.
Comment: você pode usar o createGlobalStyle pra esse caso.

https://styled-components.com/docs/api#createglobalstyle
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: para isso, existe uma função do pŕoprio styled-components para a criação de estados globais da aplicação. A createGlobalStyle.
// globalStyles.js
import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  * {
     box-sizing: border-box;
     background-color: #fff;
   }
`;

export default GlobalStyle;

A função retorna um componente que deve ser utilizado na sua aplicação, geralmente no componente mais global possível. Ou seja, no  (caso tenha utilizado o Create React App, é claro).
// App.js
import React from 'react';
import GlobalStyle from './ui/globalStyle';
import Content from './components/Content';

function App() {
    return (
      <>
        <GlobalStyle />
        <Content />
      </>
  );
}

export default App;

Ao utilizar esse "estilo global", o css será aplicado em sua aplicação.

CSS para styled-components


Find $\int \frac{x^2}{(x \cos x - \sin x)(x \sin x + \cos x)}dx $

Question: Find $$\int \frac{x^2}{(x \cos x - \sin x)(x \sin x + \cos x)}dx $$
Any hints please?
Could'nt think of any approach till now...
Comment: Partial fraction
Comment: @KennyLau Thanks.Its done !
Answer: When I have a rational function I usually start by making a part of the denominator "appear" in the numerator, and since we're dealing with trigonometric function, the following identity is quite handy:
$$\frac{x^2}{(x \cos x - \sin x)(x \sin x + \cos x)}=\frac{x^2\cos^2x+x^2\sin^2x}{(x \cos x - \sin x )(x \sin x + \cos x)} $$
$$\frac{x^2\cos^2x-x\sin x\cos x+x\sin x\cos x+x^2\sin^2x}{(x \cos x - \sin x )(x \sin x + \cos x)}=\frac{x\cos x(x\cos x-\sin x)+x\sin x(\cos x+x\sin x)}{(x \cos x - \sin x )(x \sin x + \cos x)} $$
$$ = \frac{x \cos x}{ x \sin x  + \cos x } + \frac{x \sin x}{x \cos x - \sin x} $$
Let's treat each part separately:
$$I_1=\int \frac{x \cos x}{ x \sin x  + \cos x }dx$$
Let $u=x \sin x  + \cos x$ then $du=x \cos xdx$ then
$$I_1\int \frac {du}u=\ln(u)+c_1$$
Acting similarly on the second term, yields:
$$\int \frac{x^2}{(x \cos x - \sin x)(x \sin x + \cos x)}dx=\ln( x \sin x  + \cos x)-\ln(x \cos x - \sin x)+c$$
Answer: $$ \frac{x^2}{(x \cos x - \sin x)(x \sin x + \cos x)} = \frac{x \cos x}{ x \sin x  + \cos x } + \frac{x \sin x}{x \ cos x - \sin x} $$
Why I get this:
$$\frac{x^2}{(x \cos x - \sin x)(x \sin x + \cos x)}  = \frac{A(x)}{ x \sin x  + \cos x } + \frac{B(x)}{x \ cos x - \sin x} \\\ \implies A(x)( x \cos(x)- \sin(x))+ B(x) (x \sin x + \cos x) = x^2$$
So $ A(x) = ax+b, B(x) = cx + d$.
$(ax+b)(x \cos(x) - \sin(x)) + (cx+d) ( x \sin x + \cos x) = x^2\\\ \implies ax^2 \cos(x) - ax \sin(x) -b\sin(x) + bx \cos(x) + cx ^2 \sin(x) +\\ cx \cos(x) + dx \sin(x) +d \cos(x) = x^2 \implies$
$$ a\cos(x) +c\sin(x) = 1 \tag{1}$$
$$d \cos(x) - b\sin(x) = 0 \tag{2}$$
$$ -a\sin(x)+b\cos(x)+c \cos(x)+ d \sin(x) = 0 \tag{3}$$
$\forall x \in R$
By $(2)$, $d = b = 0$,By $(1)$ and (3), $\cos(x) = a, c = \sin(x)$
Comment: @SanchayanDutta "forall" statement, let cos(x) = 1, sin(x) =0, then d = 0, let sin(x) = 1, cos(x) = 0, then b = 0. One can also try the $wsin(x)+vcos(x) = \sqrt{} \text{blah blah blah}$ formula.
Comment: I found this using Kenny's comment at the same moment you posted this answer :-)!However I did the partial fraction by just guesswork.Did you use any formal method?
Comment: @SanchayanDutta Look what I added.
Comment: Some doubts.How did you know b=d=0?
Answer: $$ \begin{aligned}
\int\frac{x^{2}}{(x\cos x - \sin x)(x\sin x + \cos x)}\,\mathrm{d}x&=\int\left(\frac{x\sin x + \cos x}{x\cos x - \sin x}\right)^{-1}\frac{x^{2}}{(x\cos x - \sin x)^{2}}\,\mathrm{d}x\\&=\int\left(\frac{x\sin x + \cos x}{x\cos x - \sin x}\right)^{-1}\,\mathrm{d}\!\left(\frac{x\sin x + \cos x}{x\cos x - \sin x}\right)\\
&=\log\left|\frac{x\sin x + \cos x}{x\cos x - \sin x}\right|+C.
\end{aligned} $$
Comment: I think, it is the best answer. +1
Answer: Let $$I = \int\frac{x^2}{(x\sin x+\cos x)\cdot (x\cos x-\sin x)}dx$$
$\displaystyle \bullet\;\;  x\sin x+1\cdot \cos x = \sqrt{x^2+1}\left[\sin x\cdot \frac{x}{\sqrt{1+x^2}}+\cos x\cdot \frac{1}{\sqrt{1+x^2}}\right]$
$$=\sqrt{x^2+1}\sin \left(x+\alpha\right)$$
Where $\displaystyle \cot \alpha = x\Rightarrow \alpha = \cot^{-1}(x) = \frac{\pi}{2}-\tan^{-1}(x)$
$\displaystyle \bullet\;\;  x\cos x-1\cdot \sin x = -\sqrt{x^2+1}\left[\sin x\cdot \frac{1}{\sqrt{1+x^2}}-\cos x\cdot \frac{x}{\sqrt{1+x^2}}\right]$
$$=-\sqrt{x^2+1}\sin \left(x-\beta\right)$$
Where $\tan \beta = x\Rightarrow \beta = \tan^{-1}(x)$
So $$I = -\int\frac{1}{1\cos(x- \tan^{-1}{x})\cdot \sin (x-\tan^{-1}(x))}\cdot \frac{1}{1+x^2}dx$$
Now Put $x-\tan^{-}(x)=t\;,$ Then $\displaystyle \frac{1}{1+x^2}dx = dt$
So $$I = -\int\frac{\sin^2 t+\cos^2 t}{\sin t \cdot \cos t }dt = -\int \tan t dt-\int \cot t dt$$
So $$I = \ln |\cos t|-\ln |\sin t|+\mathcal{C} = -\ln |\tan t|+\mathcal{C}$$
So $$I =-\ln \left|\tan \left(x-\tan^{-x}(x)\right)\right|+\mathcal{C} = -\ln \left|\frac{\tan x-x}{1+x\tan x}\right|+\mathcal{C}$$
So $$I = \ln \left|\frac{\cos x+x\sin x}{\sin x-x\cos x}\right|+\mathcal{C}$$
Comment: Very nice, when I first see it, I also try this. This strategy is similar to this problem:http://math.stackexchange.com/questions/1698591/evaluation-of-int-frac1x22x2x-cos-x-sin-x4dx ^-^
Comment: you don't need to say thanks. I really appreciate the method.
Comment: @juantheron Great as usual.Could you try this http://math.stackexchange.com/questions/1878682/find-int-fracax2-bx-sqrtc2x2-ax2b2dx  if you are free?
Comment: http://math.stackexchange.com/questions/1878682/find-int-fracax2-bx-sqrtc2x2-ax2b2dx
Answer: Let $$I = \int\frac{x^2}{(x\sin x+\cos x)(x\cos x-\sin x)}dx$$
Now Put $x=2y\;,$ Then $dx = 2dy$
So $$I = \int \frac{2y^2}{(2y\sin 2y+\cos 2y)(2y\cos 2y-\sin 2y)}dy$$
So $$I = \int\frac{2y^2}{(y^2-1)\sin 2y+2y \cos 2y}dy$$
$$\bullet\; (y^2-1)\sin 2y+2y\cos 2y = (y^2+1)\left[\cos 2y\cdot \frac{2y}{1+y^2}+\sin 2y\cdot \frac{y^2-1}{1+y^2}\right]$$
$$\displaystyle = (y^2+1)\cos \left(2y-\alpha\right) = (y^2+1)\cos \left(2y-\tan^{-1}\left(\frac{y^2-1}{2y}\right)\right)$$
So $$I = \int \sec \left(2y-\tan^{-1}\left(\frac{y^2-1}{2y}\right)\right)\cdot \frac{2y^2}{1+y^2}dy$$
Now Put $\displaystyle \left(2y-\tan^{-1}\left(\frac{y^2-1}{2y}\right)\right)=z\;,$ Then $\displaystyle \frac{2y^2}{y^2+1}dy = dz$
So $$I = \int \sec z dz = \ln \left|\sec z+\tan z\right|+\mathcal{C} = \ln \left|\tan \left(\frac{\pi}{4}+\frac{z}{2}\right)\right|+\mathcal{C}$$


Number of paths through a grid

Question: I am attempting to solve Project Euler prob. 204 by hand, and I decided that this method should help a lot.
I have the following grid:

The numbers indicate the total number of paths from a node at the base to all the nodes on the top. Conditions below apply.
The width and height can go up to infinity. A node can only connect to one that is above its row, and that is either directly above or anywhere to the right of the node (If it was not understood by the first restriction, a node cannot connect to one that is directly to the right. Must be 1 above.).
Is there a formula that can show the number of paths through the grid above, with any given width and height? If so, please explain.
Comment: Have you learnt graph theory?
Comment: Sorry, but none at the moment.
Answer: Hint.  Suppose you want to get from a starting node to a node at most $n$ steps to the right and $m$ steps above.  You will have to visit exactly one node at each level above the start; say the node visited at level $k$ is $a_k$ steps to the right of the start.  Then we have
$$0\le a_1\le a_2\le\cdots\le a_{m-1}\le a_m\le n\ ,\tag{$*$}$$
and conversely, each $m$-tuple $(a_1,\ldots,a_m)$ will give a possible path.  So, you need to count the number of $m$-tuples satisfying $(*)$.
One way to do this: let $b_k=a_k+k$ for each $k$.  Then we need
$$0<b_1<b_2<\cdots<b_{m-1}<b_m\le n+m\ .$$
Can you take it from here?
Comment: user3373311, see slight revision and additional hint.  @PatrickDaSilva FYI ;-)
Comment: Yup, that's the good place to start ; +1, that was a good hint.
Comment: May by a silly question, but what does the (*) represent? I'm a bit confused on what exactly a (m-1)-tuple should satisfy.
Comment: E.g, if $m=4$, $n=6$, $a_1=3$, $a_2=3$, $a_3=4$ it represents the path $$(0,0)\to(1,3)\to(2,3)\to(3,4)\to(4,6)\ .$$
Comment: It finally got to me that the $(*)$ stands for the condition you listed. Truly, I knew that this condition applied when I was searching for a pattern. Unless I'm missing what I'm looking for, this doesn't seem to answer the question. My question is _how_ to get the number of tuples satisfying the condition.
Comment: @user3373311 : Count! This answer gives you a hint as to *how* to count it. If you want a full answer, then ask for it.
Comment: Thank you for your patience with this question. While I have not used your hint _entirely_ in my solution, your answer has got me to illustrate some further examples, and realize that the number of paths is associated with Pascal's triangle. Once again, thanks for the help. I have marked this as answered.

Number of paths through a grid


Strapi: React: Cannot read property 'associations' of undefined

Question: Currently trying to upload an image and connect it to an existing entry.
The schema of the existing entry is
{
      "name": "page rows",
      "description": "",
      "connection": "default",
      "kind": "collectionType",
      "collectionName": "page_rows",
      "attributes": {
        "row": {
          "type": "json"
        },
        "images": {
          "type": "media",
          "multiple": true,
          "required": false,
          "allowedTypes": [
            "images"
          ]
        }
      }
    },

and I upload an image using
export const formatEntryUpload = (file, entryModel, entryID, entryField, entryPlugin = null) => {
  const entryUpload = new FormData();
  entryUpload.append('files', file);
  entryUpload.append('ref', entryModel);
  entryUpload.append('refId', entryID);
  entryUpload.append('field', entryField);
  if(entryPlugin) {
    entryUpload.append('source', entryPlugin);
  }
  return entryUpload;
};

where I fill call the function by
formatEntryUpload ( file, "page_rows", id, "images", "users-permissions");

however when I do I get the following error.
[2021-02-07T21:01:35.334Z] error TypeError: Cannot read property 'associations' of undefined
at /srv/app/node_modules/strapi-connector-mongoose/lib/relations.js:250:43
at Array.forEach (<anonymous>)
at /srv/app/node_modules/strapi-connector-mongoose/lib/relations.js:235:20
at Array.reduce (<anonymous>)
at Function.update [as updateRelations] (/srv/app/node_modules/strapi-connector-mongoose/lib/relations.js:97:68)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Object.add (/srv/app/node_modules/strapi-plugin-upload/services/Upload.js:253:17)
at async Promise.all (index 0)
at async Object.upload (/srv/app/node_modules/strapi-plugin-upload/services/Upload.js:105:12)
at async Object.upload (/srv/app/node_modules/strapi-plugin-upload/controllers/Upload.js:82:18)
at async /srv/app/node_modules/strapi/lib/middlewares/router/utils/routerChecker.js:70:22
at async module.exports (/srv/app/node_modules/strapi-plugin-users-permissions/config/policies/permissions.js:97:3)
at async /srv/app/node_modules/strapi-utils/lib/policy.js:52:5
[2021-02-07T21:01:35.334Z] debug POST /upload (564 ms) 500

The image is successfully uploaded however it is not associated with the entry. What do I need to change to associate the image with the entry?
Answer: change "page_rows" to "page_row"
it helped me
formatEntryUpload ( file, "page_rows", id, "images", "users-permissions") =>
formatEntryUpload ( file, "page_row", id, "images", "users-permissions");


How do I define the limits of a double integral in polar coordinates over an annulus?

Question:
Evaluate the double integral by re-writing them in polar coordinates:
$\displaystyle\iint\limits_{R}\frac{y^2}{x^2}\ dA$, where $R$ is part of the annulus (ring) $9\leq x^2+y^2\leq 25$ lying in the first quadrant and below the line $y=x$.

So from this, I gather (assuming I understood correctly) that $R=\{(x,y)\mid9\leq x^2+y^2\leq 25,\ 0\leq y\leq x\}$.

There are two circles, one where $r=5$ and one where $r=3$. I would guess that what I'm looking for is the larger circle minus the smaller circle, but doing that the only way I can think of yields the following:
\begin{gather}
(x^2+y^2)-(x^2+y^2)=25-9\\
0=16
\end{gather}
I'm clearly way off track here; how do I look at this so I can define the bounds of the double integral in polar coordinates?
Answer: You can use polar coordinates, then you have
$$ 9\leq x^2+y^2\leq 25 \implies  3\leq r\leq 5, $$
and
$$ 0\leq \theta \leq \frac{\pi}{4},\quad \rm{since}\quad y=x. $$
$$ \displaystyle\iint\limits_{R}\frac{y^2}{x^2}\ dA = \int_{0}^{\pi/4}\int_{3}^{5}\frac{\sin^{2}(\theta)}{\cos^2(\theta)}rdrd\theta $$
Comment: Ah; it had not crossed my mind to specify $3\leq r\leq 5$. That makes perfect sense. All of my questions to date were about solid circles, not rings.


Can't get true/false value from command line in python 2.7

Question: I'm trying to incorporate a flag in to a program:
python2.7 hello.py --showxy

and argparse is giving me trouble.
this is my example test code:
import os
import sys
import argparse

print (os.getcwd())
print ("___________________________________________________")
print ("A: " + sys.argv[0])
print ("B: " + sys.argv[1])
print ("C: " + sys.argv[2])
print ("___________________________________________________")

parser = argparse.ArgumentParser()
parser.add_argument('--showxy', action='store_true')
args = argparse.Namespace()
d = vars(args)

print Namespace()

And while I should be getting:
Namespace(showxy=True)

I am actually getting an error:
A: hello.py
B: haarcascade_frontalface_default.xml
C: euromil.jpg
___________________________________________________
Traceback (most recent call last):
  File "hello.py", line 19, in <module>
    print Namespace()

NameError: name 'Namespace' is not defined

How should I be formatting this?
Comment: Why do you think you *should* be getting that? `Namespace` is under `argparse` and you accessed it already as `argparse.Namespace()`. Why do you think calling `Namespace` would work?
Comment: You didn't even call `parser.parse_args()`. Why are you trying to call `Namespace` directly?
Answer: You are missing the parsing step
args = parser.parse_args()

args = argparse.Namespace() just creates an new empty Namespace object.
argparse is the module.  parser is the ArgumentParser object.  Namespace is a class defined in that module.  parse_args creates a Namespace, fills it with values that that it parses from sys.argv, and returns it as args.
Defining the parser by itself does not do any parsing.

The very first example in the docs is:
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

Some claim this is too advanced for beginners, but the key pieces are there.
parser = ...
parser.add_argument...
args = parser.parse_args()
# look at args, print it, access attributes, etc.

argparse.Namespace isn't mentioned until section https://docs.python.org/3/library/argparse.html#the-namespace-object
Comment: You don't normally need to create a `Namespace` yourself.  `parse_args` does that for you. (you can create a Namespace and pass it to the parse_args, but that's advanced usage).   You may need to review the `argparse` docs, and/or tutorial.
Comment: Correction, I should have written `parser.parse_args()`.  `parse_args` is a method of the parser, not a function of the module.  Please go read the docs and try some of the examples.
Comment: Got it. Is that before or after the namespace?
Comment: Ok, now I got: `"AttributeError: 'module' object has no attribute 'parse_args'`


Filter grouped DataFrame in Julia

Question: I have a DataFrame
df = DataFrame(a = [1,1,2,2,2])

5×1 DataFrame
 Row │ a
     │ Int64
─────┼───────
   1 │     1
   2 │     1
   3 │     2
   4 │     2
   5 │     2

and I want to filter for the groups with let's say 2 rows - ideally with using Chain und potentially using DataFramesMeta - and I cannot get it to work.
It does work when first creating a separate column for this like so
@chain df begin
    groupby(:a)
    @transform(:rows = length(:a))
    @subset(:rows .== 2)
end

2×2 DataFrame
 Row │ a      rows
     │ Int64  Int64
─────┼──────────────
   1 │     1      2
   2 │     1      2

But it doesn't work when doing the same calculating it within @subset(). Anyone got a clever solution?
Answer: Instead of subset, use filter for this:
julia> @chain df begin
           groupby(:a)
           filter(:a => a -> length(a) == 2, _)
       end
GroupedDataFrame with 1 group based on key: a
First Group (2 rows): a = 1
 Row │ a
     │ Int64
─────┼───────
   1 │     1
   2 │     1

julia> # OR:

julia> @chain df begin
           groupby(:a)
           filter(_) do subdf
               length(subdf.a) == 2
           end
       end
GroupedDataFrame with 1 group based on key: a
First Group (2 rows): a = 1
 Row │ a
     │ Int64
─────┼───────
   1 │     1
   2 │     1

Comment: This solution is, without a doubt, worth an up-vote. Unfortunately `filter()` is so hideous in chains, because it puts the object to filter last, that I have a hard time calling this a good solution. But this is, of course, not about you. Thanks for the answer.
Comment: @Georgery Yeah, `filter` does stand out weirdly in an otherwise nice chain of operations. I've added another version of it, which still *kind of* breaks the flow of the chain, but is at least less hideous in my eyes.
Comment: (Although, I've found that most real world use cases end up with some custom function in the chain that breaks the flow to some extent anyway. Still, it's good to minimize those where we can.)
Answer: In my recent blog post I have explained why we decided that this particular case should not be easily supported (in short: users were confused by pseudo-broadcasting in other cases; however, feel free to open an issue if you disagree with the logic explained there).
The solution is either to use filter as Sundar R suggests (in 1.4 release we will add ungroup kwarg to it to make it more convenient, see this issue) or to write:
julia> @chain df begin
           groupby(:a)
           @subset(fill(length(:a) == 2, length(:a)))
       end
2×1 DataFrame
 Row │ a
     │ Int64
─────┼───────
   1 │     1
   2 │     1

Comment: Thanks. I don't want to open an issue. I think that DataFrames and DataFramesMeta are making an amazing effort. It's just hard to like this syntax.

Filter grouped DataFrame in Julia


Low variance components in PCA, are they really just noise? Is there any way to test for it?

Question: I'm trying to decide if a component of a PCA shall be retained, or not. There are a gazillion of criteria based on the magnitude of the eigenvalue,  described and compared e.g. here or here.
However, in my application I know that the small(est) eigenvalue will be small compared to the large(st) eigenvalue and the criteria based on magnitude would all reject the small(est) one. This is not what I want. What I am interested in: is there any method known that takes the actual corresponding component of the small eigenvalue into account, in the sense: is it really "just" noise as implied in all the textbooks, or is there "something" of potential interest left? If it is really noise, remove it, otherwise keep it, regardless of the magnitude of the eigenvalue.
Is there some kind of established randomness or distribution test for components in PCA that I am unable to find? Or does anyone know of a reason that this would be a silly idea?
Update
Histograms (green) and normal approximations (blue) of components in two use cases: once probably really noise, once probably not "just" noise (yes, the values are small, but probably not random). The largest singular value is ~160 in both cases, the smallest, i.e. this singular value, is 0.0xx - way too small for any of the cut-off methods.
What I'm looking for is a way to formalize this ...
Comment: Many of the tests you refer to have exactly the property you ask for: they attempt to distinguish "noise" from "signal."
Comment: I have recently been interested in a similar question, but in a specific situation when you have multiple measurements for each data point. See [Choosing number of PCA components when multiple samples for each data point are available](http://stats.stackexchange.com/questions/83789/choosing-number-of-pca-components-when-multiple-samples-for-each-data-point-are). Maybe it applies to your case as well?
Comment: Using distributional tests on PCs to decide on their randomness sounds as a very interesting idea (that I have never seen applied); something similar is done in ICA, that specifically looks for maximally non-Gaussian components. Doing PCA and then discarding components that are "too Gaussian" has ICA flavour to it and might actually work!
Comment: They are not necessarily just noise, look at some of the images in [my answer here](https://stats.stackexchange.com/questions/177102/what-is-the-intuition-behind-svd)
Answer: One way of testing the randomness of a small principal component (PC) is to treat it like a signal instead of noise: i.e., try to predict another variable of interest with it. This is essentially principal components regression (PCR).
In the predictive context of PCR, Lott (1973) recommends selecting PCs in a way that maximizes $R^2$; Gunst and Mason (1977) focus on $MSE$. PCs with small eigenvalues (even the smallest!) can improve predictions (Hotelling, 1957; Massy, 1965; Hawkins, 1973; Hadi & Ling, 1998; Jackson, 1991), and have proven very interesting in some published, predictive applications (Jolliffe, 1982, 2010). These include:

A chemical engineering model using PCs 1, 3, 4, 6, 7, and 8 of 9 total (Smith & Campbell, 1980)
A monsoon model using PCs 8, 2, and 10 (in order of importance) out of 10 (Kung & Sharif, 1980)
An economic model using PCs 4 and 5 out of 6 (Hill, Fomby, & Johnson, 1977)

The PCs in the examples listed above are numbered according to their eigenvalues' ranked sizes. Jolliffe (1982) describes a cloud model in which the last component contributes most. He concludes:

The above examples have shown that it is not necessary to find obscure or bizarre data in order for the last few principal components to be important in principal component regression. Rather it seems that such examples may be rather common in practice. Hill et al. (1977) give a thorough and useful discussion of strategies for selecting principal components which should have buried forever the idea of selection based solely on size of variance. Unfortunately this does not seem to have happened, and the idea is perhaps more widespread now than 20 years ago.

Furthermore, excluding small-eigenvalue PCs can introduce bias (Mason & Gunst, 1985).  Hadi and Ling (1998) recommend considering regression $SS$ as well; they summarize their article thus:

The basic conclusion of this article is that, in general, the PCs may fail to account for the regression fit. As stated in Theorem 1, it is theoretically possible that the first $(p-1)$ PCs, which can have almost 100% of the variance, contribute nothing to the fit, while the response variable $\text{Y}$ may fit perfectly the last PC which is always ignored by the PCR methodology.
The reason for the failure of the PCR in accounting for the variation of the response variable is that the PCs are chosen based on the PCD [principal components decomposition] which depends only on $\text{X}$. Thus, if PCR is to be used, it should be used with caution and the selection of the PCs to keep should be guided not only by the variance decomposition but also by the contribution of each principal component to the regression sum of squares.

I owe this answer to @Scortchi, who corrected my own misconceptions about PC selection in PCR with some very helpful comments, including: "Jolliffe (2010) reviews other ways of selecting PCs." This reference may be a good place to look for further ideas.
References

- Gunst, R. F., & Mason, R. L. (1977). Biased estimation in regression: an evaluation using mean squared error. Journal of the American Statistical Association, 72(359), 616–628.
- Hadi, A. S., & Ling, R. F. (1998). Some cautionary notes on the use of principal components regression. The American Statistician, 52(1), 15–19. Retrieved from http://www.uvm.edu/~rsingle/stat380/F04/possible/Hadi+Ling-AmStat-1998_PCRegression.pdf.
- Hawkins, D. M. (1973). On the investigation of alternative regressions by principal component analysis. Applied Statistics, 22(3), 275–286.
- Hill, R. C., Fomby, T. B., & Johnson, S. R. (1977). Component selection norms for principal components regression. Communications in Statistics – Theory and Methods, 6(4), 309–334.
- Hotelling, H. (1957). The relations of the newer multivariate statistical methods to factor analysis. British Journal of Statistical Psychology, 10(2), 69–79.
- Jackson, E. (1991). A user's guide to principal components. New York: Wiley.
- Jolliffe, I. T. (1982). Note on the use of principal components in regression. Applied Statistics, 31(3), 300–303. Retrieved from http://automatica.dei.unipd.it/public/Schenato/PSC/2010_2011/gruppo4-Building_termo_identification/IdentificazioneTermodinamica20072008/Biblio/Articoli/PCR%20vecchio%2082.pdf.
- Jolliffe, I. T. (2010). Principal components analysis (2nd ed.). Springer.
- Kung, E. C., & Sharif, T. A. (1980). Regression forecasting of the onset of the Indian summer monsoon with antecedent upper air conditions. Journal of Applied Meteorology, 19(4), 370–380. Retrieved from http://iri.columbia.edu/~ousmane/print/Onset/ErnestSharif80_JAS.pdf.
- Lott, W. F. (1973). The optimal set of principal component restrictions on a least-squares regression. Communications in Statistics – Theory and Methods, 2(5), 449–464.
- Mason, R. L., & Gunst, R. F. (1985). Selecting principal components in regression. Statistics & Probability Letters, 3(6), 299–301.
- Massy, W. F. (1965). Principal components regression in exploratory statistical research. Journal of the American Statistical Association, 60(309), 234–256. Retrieved from http://automatica.dei.unipd.it/public/Schenato/PSC/2010_2011/gruppo4-Building_termo_identification/IdentificazioneTermodinamica20072008/Biblio/Articoli/PCR%20vecchio%2065.pdf.
- Smith, G., & Campbell, F. (1980). A critique of some ridge regression methods. Journal of the American Statistical Association, 75(369), 74–81. Retrieved from https://cowles.econ.yale.edu/P/cp/p04b/p0496.pdf.
Comment: ... and there is no whatsoever guarantee that the effect you need to solve your problem is larger than other effects which are just noise wrt. the problem at hand. I've seen data where 95% of the variance was noise due to some physical effects...
Comment: Very nice review, but (sorry to quibble again) *pace* Hadi & Ling, selecting the PCs to retain in a regression based on their strong relationship to the response, is as dangerous as selecting the original predictors based on their strong relationship to the response. Cross-validation is essential & shrinkage preferable. Personally I'd prefer a judicious use of PCA together with subject-matter knowledge to guide data reduction on predictors, blind to the response, e.g. using the first PC of groups of predictors measuring much the same thing, or determined by variable clustering.
Comment: +1 (long time ago) to this answer, but after reviewing this thread now, I must say that this answer does not answer the original question almost at all: OP was asking about whether one can use any distributional tests on components to judge on their randomness. See also my last comment to the OP.
Answer: Adding to @Nick Stauner's answer, when you're dealing with subspace clustering, PCA is often a poor solution.
When using PCA, one is mostly concerned about the eigenvectors with the highest eigenvalues, which represent the directions towards which the data is 'stretched' the most. If your data is comprised of small subspaces, PCA will solemnly ignore them since they don't contribute much to the overall data variance.
So, small eigenvectors are not always pure noise.


Como contar palavras repetidas em uma string e achar sua posição?

Question: Imagine o Alfabeto, nesse alfabeto tem palavras de A-Z, mas de repente surge várias letras A, como:
A-B-C-D-E-F-G-H-I-A-J-K-L-A-M-A-N-O-P-Q-A
A variável nomes abaixo, é esse alfabeto. A variável procurar só vai servir para mim escolher qual palavra repetida eu quero ver na variável nomes.
Neste modelo:
string procurar = "cachorro";
string nomes = "vaca cachorro vaca cachorro gato cavalo";
int index = ??
int total = ??

Alguém pode ajudar?
Comment: Mas contar todas as palavras repetidas ou apenas a palavra que está na variável `procurar` ?
Comment: contar as palavras que está na variável `nomes`. A variável `procurar` serve para eu procurar o nome repetido na variável `nomes`.
Answer: Vê se te ajuda:
string procurar = "cachorro";
string nomes = "vaca cachorro vaca cachorro gato cavalo";
MatchCollection matches = Regex.Matches(nomes, procurar);
foreach (Match item in matches)
{
    Console.WriteLine(string.Format("{0} = {1}", procurar, item.Index));
}
Console.WriteLine(string.Format("achado {0} nomes ", matches.Count));

Funcionando no https://dotnetfiddle.net/dqjc8B


How to change the colour of a button when clicked on? (Vue)

Question: I'm trying to get a button that changes its color when pressed on it. When it is pressed again, it should change back to its original color. What am I doing wrong?
The Button in my template:
<Button v-bind:class="{'white': !clicked, 'blue': clicked}" v-on:click ="!clicked" ></Button>

Comment: This is unrelated to your issue, but you should always make sure your data field is a function that returns an object. See [here](https://vuejs.org/v2/guide/components.html)
Answer: You should set clicked property explicitly by @click="clicked = !clicked":

  <Button
    v-bind:class="{'white': !clicked, 'blue': clicked}"
    v-on:click ="clicked = !clicked"
  />

Comment: Also, you can use ternary expression for setting a class dynamically:

`v-bind:class="clicked ? 'blue' : 'white'"`


Laplace transform using 2nd shifting Theorem

Question: $$\mathcal{L}(U(t-5)e^{t-5} )$$
I've been taught this method and im not sure of and whether it will be correct, so I came here to ask.
$\mathcal{L}(U(t-5)e^{t-5} = \mathcal{L} (U(t-a) f(t-a) ) = e^{-as}F(s) $
a = 5,
Therefore, $f(t-5) = e^{t-5} $
since $\mathcal{L} (f(t)) = F(s) $
$f(t) = e^t $
and $\mathcal{L} (f(t)) = \frac{1}{s-1} $
Therefore the answer is - $e^{-5s} \frac{1}{s-1} $
Am I correct ?
Answer: Yes, you have applied $$\mathcal{L}(U(t-5)e^{t-5} = \mathcal{L} (U(t-a) f(t-a) ) = e^{-as}F(s) =  e^{-5s} \frac{1}{s-1}$$
correctly to get your answer $e^{-5s} \frac{1}{s-1}$


boost threadpool using boost::asio

Question: I am trying to create boost threadpool using boost asio with a work queue. But I am stuck at one point, I need a monitoring function which should keep running and keep track of queue. I am not sure how I can write that, currently I put it in my thread pool class. I am also trying to write seprate thread with global function. Can someone suggest any way?
#include <boost/thread/thread.hpp>
#include <boost/asio.hpp>
#include<memory>
#include<vector>
#include<list>

using namespace std;

class threadWork
{
public:
virtual void run()=0;
};

class thread_pool
{
private:
  boost::asio::io_service io_service_;
  boost::asio::io_service::work work_;
  boost::thread_group threads_;
  std::size_t available_;
  boost::mutex mutex_;

  list<shared_ptr<threadWork>> workQueue;

public:

  thread_pool( std::size_t pool_size ) : work_( io_service_ ), available_( pool_size )
  {
    for ( std::size_t i = 0; i < pool_size; ++i )
    {
      threads_.create_thread( boost::bind( &boost::asio::io_service::run, &io_service_ ) );
    }
  }

  ~thread_pool()
  {

    io_service_.stop();

try
    {
      threads_.join_all();
    }
    catch ( ... ) {}
  }

  void enqueue(shared_ptr<threadWork> work)
  {
  workQueue.push_back(work);
  }

  void keepRunning() // how to call this ?
  {
  while(true)
  {
      boost::unique_lock< boost::mutex > lock( mutex_ );

      if ( 0 == available_ ) // If no threads are available, then sleep.
      {
          boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
      }
      else
      {

          if(workQueue.empty() != true)
          {
               --available_;
               io_service_.post( boost::bin(&thread_pool::wrap_task,this , workQueue));
               workQueue.pop_front();
          }
      }
  }
  }

 private:

  void wrap_task(list<shared_ptr<threadWork>>& workQueue )
  {
    try
    {
    workQueue.front()->run(); // Run the user supplied task.
    }

catch ( ... )  // Suppress all exceptions.
{

}

boost::unique_lock< boost::mutex > lock( mutex_ );
    ++available_;
  }
};

class someWork:public threadWork
{
public:
virtual void run()
{
    cout<<"some long task \n";
     boost::this_thread::sleep(boost::posix_time::milliseconds(5000));
}
};

int main()
{

thread_pool pool(10);

pool.keepRunning(); // this stuck code so where to start this ?

shared_ptr<threadWork> w(new someWork);

pool.enqueue(w);

return 0;
}

Comment: I think boost already has threadpool http://threadpool.sourceforge.net/
Comment: Have a look at this: http://think-async.com/Asio/Recipes an ASIO Threadpool....
Comment: thanks , i am considuring using threadpool from threadpool.sourceforge.net
Comment: this example code does not compile, there are several errors, an example `io_service_.post( boost::bin(&thread_pool::wrap_task,this , workQueue));` should be `boost::bind`
Comment: this example code does not compile , ssorry for that i will check and update soon. as of now i am using think-async.com/Asio/Recipes link by mark , it works up to some extend. thanks to all of you.
Comment: threadpool has the problem that it doesn't queue at all - if all threads are busy adding a task fails. So to be useful you need to add a (threadsafe) queue to it.
Answer: You could use boost::asio::deadline_timer to periodically have your io_service update an atomic variable representing the queue length. A class member function could return the queue length on demand (by value).

boost threadpool using boost::asio


Convert comma separated binary string to byte[] for Registry insertion

Question: This is really getting the better of me. I need to convert this:
string data = "4,0,0,0,1,0,0,0,16,0,0,0,100,58,82,80,162,77,200,183,178,32"

into a byte array so that I can use it here:
polKey.SetValue("Blob", data, RegistryValueKind.Binary);

I've tried data.Split(',') to split it into an array and use that, but I can't get my head around it.
Comment: @Logerfo casting isn't going to work.  You have to parse the values, so instead of `.Cast()` you need `.Select(byte.Parse)`.
Comment: You mean that the first byte is 4, the second is 0, etc.?
Comment: I guess you could do that using LINQ: `data.Split(',').Cast().ToArray();`
Comment: @juharr you're right, thanks!
Answer: I'm assuming your byte array needs the parsed values (e.g. 4, 0, 1, 100, etc.) and not the ASCII values of each string.
First convert to an array of strings:
string[] strings = data.Split(',');

then convert each string to a byte:
byte[] bytes = strings.Select(s => byte.Parse(s)).ToArray();

Answer: You can use Linq
string data = "4,0,0,0,1,0,0,0,16,0,0,0,100,58,82,80,162,77,200,183,178,32";
var buf = data.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
              .Select(x => byte.Parse(x))
              .ToArray();

A regex solution is also possible
var buf = Regex.Matches(data,@"\d+").Cast<Match>()
               .Select(x => byte.Parse(x.Value))
               .ToArray();


Remove Chapter title from header on all pages, latex book class

Question: Edited to include a reproducible example.
So, I've found a number of people asking about how to add the chapter title from the header of subsequent pages but I need the opposite. I'm using fancy header but need everything except the page number removed from the header (the page needs to be at the top right of every page). The code I'm using removes the header from the first page of each chapter, but every subsequent page has the chapter name in the header on the left. I'm using \documentclass[12pt,oneside]{book}.
Below is the header code:
\documentclass[12pt,oneside]{book}
\usepackage{fancyhdr}            % Permits header customization. See header section below.
\fancypagestyle{plain}{
    \lhead{}
    \fancyhead[R]{\thepage}
    \fancyhead[L]{}
    \renewcommand{\headrulewidth}{0pt}
    \fancyfoot{}
}

\begin{document}
\chapter{Starting Here}
Some stuff
\newpage
New stuff

\end{document}

I have to submit this document with specific formatting requirements and want to continue using the fancyhdr package. Any help is much appreciated.
Comment: https://tex.stackexchange.com/questions/117328/fancyhdr-does-not-apply-same-header-footer-on-chapter-and-non-chapter-pages
Answer: While your MWE loads the fancyhdr package, you don't actually use it for normal pages as there is no  \pagestyle{fancy} or similar. This means your code only customises plain pages like they are used for the first page of a chapter.
If you want to customise normal pages as well:
\documentclass[12pt,oneside]{book}
\usepackage{fancyhdr}            % Permits header customization. See header section below.
\fancypagestyle{plain}{
    \lhead{}
    \fancyhead[R]{\thepage}
    \fancyhead[L]{}
    \renewcommand{\headrulewidth}{0pt}
    \fancyfoot{}
}

\pagestyle{fancy}
\fancyhead[R]{\thepage}
\fancyhead[L]{}
\renewcommand{\headrulewidth}{0pt}
\fancyfoot{}

\begin{document}
\chapter{Starting Here}
Some stuff
\newpage
New stuff

\end{document}

Comment: Thank you so much! That is really helpful to understand latex better!
Answer: from the .cls file, I commented \pagestyle and added following code before /begin{document}.
\usepackage{fancyhdr}            % Permits header customization. See header section below.
\fancypagestyle{plain}{
    \lhead{}
    \fancyhead[R]{\thepage}
    \fancyhead[L]{}
    \renewcommand{\headrulewidth}{0pt}
    \fancyfoot{}
}

\pagestyle{fancy}
\fancyhead[R]{\thepage}
\fancyhead[L]{}
\renewcommand{\headrulewidth}{0pt}
\fancyfoot{}


How do I figure out what module is using drupal_set_message()?

Question: Some module is using drupal_set_message() to show a message at the top of the administrative pages.
I would like to figure out from where it is coming from. Is there any way to determine what module is creating it? How do I remove it?
Comment: Install Devel and stick `dpm(debug_backtrace());` in `drupal_set_message()` temporarily - that'll tell you where it comes from. Actually no, don't do that, you'll get a recursive loop...you can play around with a static var to short the recursion though
Comment: Try doing a **grep** on your project source folder for **drupal_set_message**  . Something like : `grep -r --include "*.php" drupal_set_message .`  or `grep -r drupal_set_message .`
Comment: @Clive : please apply some kind of undo/rollback of the title of this question, which originally was about a "green area" related to drupal_set_message() ... That's different from "using drupal_set_message()" ... and seems like editing the question to make it fit an answer ... which is not what one should do, right?
Answer: Are there any messages in your error log? You should be able to see a module name there.
drupal_set_message has no parameter to add a module name to the message so there is no straight forward method of finding the module. You could copy the string from the message and search in the translation page (if you have the locale module enabled. Or throw the string at Google and see what you find. That usually helps!
Answer: Is the node the only thing that it's logging out? If that's the case then it may be hard to find out which module is outputting it. If not then I would suggest what rtome says in the comment, although slightly modified.
If you SSH into the root of your drupal install, and run "find . -exec grep 'yourtexthere' {} \; -print" then it will search every file for that line of text and print out which files have it.
If the node is the only thing being printed, however, then you may do better to disable the modules one by one (or several at a time) until the message goes away.
(btw watchdog and drupal_set_message are not the same thing. Watchdog is what is logged to through the command watchdog() and which you can find in admin/reports/dblog)
Comment: I'm not sure if it's rather answer or request for clarification :(
Comment: To clarify it's drupal_set_message I think, it shows up in green ... I suppose I can turn them off one at a time but I thought perhaps there was an easier solution
Answer: If you are asking to edit out the code calling drupal_set_message() from that module, I would rather suggest not doing it.
Disabling some messages is easy as installing the Disable Messages module, and setting it up. The module is described as follows:

Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal_set_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.
Features

Filter out messages that match a full text string exactly.
Filter out messages that match a regular expression.
Permissions to specifically hide all messages of a given type from any role.
Disable all filtering for specific users.
Disable all filtering for specific paths.
Apply filtering only for specific paths.
Debug system to get messages in the HTML without showing it to the end users.


Can't load MSMQ COM Object on Windows Server 2012

Question: My VBScript tries to load MSMQ COM Object
<code>Set MSMQQueueInfo = CreateObject("MSMQ.MSMQQueueInfo")
</code>
I enabled Messaging DCOM Proxy

Script can't load COM object:
Answer: You need to specify the machine you are creating the queue on.
Using Message Queuing over DCOM
Comment: The error I'm getting happens before there's a chance to worry about machine name. I couldn't create the COM object.
Comment: The object is created using the machine name, not before you specify the machine name.
Set qinfo = CreateObject("MSMQ.MSMQQueueInfo", "MyServer.MyDomain.com")
Comment: As I posted in the question, I'm creating without the name `CreateObject("MSMQ.MSMQQueueInfo")`
Comment: My assumption (as I can't test it at the moment) is that the proxy needs to know the queue manager to talk to for object creation. If you don't specify then the QM would have to be local.
Answer: Even though I am not running MSMQ on this server, I still had to install the messaging server to load the COM object:


Ways to filter drupal search results

Question: I'm running into some trouble to setup a search in Drupal between some related nodes with some decent filters.
I've tried to use search_api, search_api_db & the facet_api, it work's like a charm except that there doesn't seem to be a functionality to select multiple options to filter on. (or functionality).
For example when you've got a list with some options:

Option 1 (10)
Option 2 (2)
Option 3 (8)

When you click Option 1, facet_api will only show:

x Option 1 (10)

I'd like the possibility to select multiple options, and extend my filter.

x Option 1 (10)
Option 2 (2)
x Option 3 (8)

While searching I ran into some issues posted at drupal.org that state that it's possible with search_api_solr but not with search_api_db.
http://drupal.org/node/1390586 (Implement support for search_api_facets_operator_or  - search_api_db)
http://drupal.org/node/1679974 (Allow multiple checkboxes to be selected in a facet - FacetAPI )
My question is: Is it possible with the search_api, search_api_db and facet_api to let this work, or are there other solutions out there that will provide the functionality described above?
It needs to work with multiple facets and update the number of results behind the options.
Comment: do you know in advance what these facets are going to be? or is it random texts with in the content spread across content types and taxonomies?
Comment: Hi, at this moment i use the content of select fields from the node like color and type of a product for the facets.
Comment: why dont you use views filter then?
Comment: I tried to use the view filter and expose it to the users. But it doesn't show the number of items that met that criteria. For example, if someone selects a option, and there is only 1 item with the color blue it needs to show (1) behind blue. If is select another option that could be another number.
Comment: let me know if this is how you want it. http://openoman.com/search/results/shipping
Comment: Hi Mohammed, no that restricts the search results to only that category. I'm looking for something like the languages at the following page: http://www.amazon.com/s/ref=lp_283155_nr_n_3?rh=n%3A283155%2Cn%3A!1000%2Cn%3A3248857011&bbn=1000&ie=UTF8&qid=1359964825&rnid=1000 the possibility to select multiple options.
Comment: Very long question just to ask how to allow multiple facets. If you would reduce the length of the question I believe you'd attract more answers.
Answer: I think you can change your facets to using the facetapi to use checkboxes instead of links. I believe you can go into your index and then edit the facet and choose under Display Widget: Links with checkboxes.
Comment: This really isn't much of an answer. Can you provide any more information?
Comment: I edited my answer above.
Answer: The answer to your question is as follows:
1) Within that facets filters - un-check "Do not display active items"

2) Within that facets display - select "Or" - N.B. This option will only be available on Solr driven servers!

I hope that helps!

Originally found here: Allow multiple check-boxes to be selected on a facet
Thanks goes to: deggertsen
Answer: You could achieve multiple facet selections with Apachesolr module:

This module integrates Drupal with the Apache Solr search platform.
  Solr search can be used as a replacement for core content search and
  boasts both extra features and better performance. If you're looking
  for Apache Solr integration, this is possibly the best option
  available.
Comment: The OP already has search setup with Search API and simply wants to change the facets. Facets for both Search API and Apachesolr module are provided by Facet API, so switching Solr module is irrelevant.

Ways to filter drupal search results


Nomenclature for modulations

Question: I have noticed that sometimes the music plays a tone, goes up a few semitones with it and then that last tone in the walk is treated like the fifth in the new key it modulates to. Sometimes the tone was the fifth in the old key before it started walking, so to speak, so it is kind of like the key was transposed up a few semitones. This kind of thing seem to happen in (some versions of) Bränd-Pers vals for example.
Other times the last note in the walk is the old key's leading tone, but in the new key it would be the third or something like that. This kind of thing seems to happen in Carmen by Sarasate Op. 25 for example, although it might be numbered differently because I guess it might not be the usual major key and that seems to affect what number or name you give the notes.
I am wondering if there is some established nomenclature about these kind of things. I can imagine the number of possibilities growing quite chaotically so I don't expect every possibility to have a name.
Comment: Are you asking about a name for the key change, or a name for the process or getting there? A concrete example would help.
Comment: I guess I am asking if I can say a 7-to-3 key change or if noone will understand me then because the usual name is ???. And I thought the buildup might affect the name. Not sure what you mean with concrete. Do you mean song and bar or what.
Comment: Your comment provides helpful clarification. By concrete, I mean a specific example in a piece of music where the kind of modulation you're asking about happens.
Comment: That edit is very helpful. If you could say where in Sarasate's "Carmen" such a modulation occurs, that would save everyone the time of searching through the score or a recording to try to find an example of what you're describing.
Comment: Usually some of them happens in songs I don't have sheet music in so I don't know for sure what happens. I just notice the seven notes I am playing sound like crap suddenly :-)
Comment: One kind is the [Truck Drivers Gear Change](https://tvtropes.org/pmwiki/pmwiki.php/Main/TruckDriversGearChange) (TV tropes link warning).  This is humorous, and probably not worth an answer, but it's recognized nomenclature...
Answer: There isn't a special name for this type of modulation, but there are some terms relevant to it.

mediant relationship: A mediant relationship is a relationship by thirds. So a modulation from I to III or I to VI is either a diatonic mediant modulation (if it's the III or VI of the originating key/mode) or a chromatic mediant modulation (if the III or VI comes a different key/mode).
secondary dominant: When the arrival in the new key is preceding by a dominant chord from that key, that preceding chord is called a secondary dominant. For example, if a modulation to III is preceded by a dominant seventh chord built on ^7 (i.e., VII[#,7]), then a secondary dominant (labeled V7/III [read: "five-seven of three"]) is in use.
pivot chord: When the dominant chord of the new key is also a diatonic chord in the old key, it's known as a pivot chord. An example here would be the VII7 chord in minor. One might have a walk-up progression like V - VI - VII in a minor key, which then resolves to III of that key. The VII chord is simultaneously operating in both the originating key (as VII) and the new key (as V). Note that pivot chords are not uniquely dominant chords relative to the new key. Any chord that functions simultaneously in both the originating key and in the target key can be a pivot chord.
Comment: @Emil `I` is the key before the modulation, `III` is the key after modulation, relative to the original key. In other words, in a modulation from C major to E minor, C would be `I` and E minor would be `III`.
Comment: When you say from I to III, which key are they respectively in?
Comment: I understand you correct that with III you are talking about the tonic of the new key relative to the original key? So it could be the tonic of some kind of mode?
Comment: @Emil Yes, though typically it will either be major or minor.
Comment: Just one more thing, the default is to talk about where the tonic is moved or...? So one can think of it as two steps, move tonic,(optionally) change mode...
Comment: @Emil I'm not sure I understand what you're asking.
Comment: I am just trying to fit it into my conceptual image of a key change, where the pitchclasses look like a 3x3 template, the mode is like the pin/anchor point and the tonic is like the application point. Sorry if I am being confusing, but in my head "modulation to III" would mean like the pin and the template should comove, while "modulating to minor" would mean the pin should stay but the template should move.
Comment: Or maybe it is more like first move pin, then move template according to mode.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/146080/discussion-between-aaron-and-emil).

Nomenclature for modulations


Error while using fs.readFileSync

Question: I'm trying to convert an uploaded image to base 64
       var file = e.target.files[0];
       var imageFile = fs.readFileSync(file);
       var encoded = new Buffer(imageFile).toString('base64');

I get an error saying :
TypeError: __WEBPACK_IMPORTED_MODULE_4_fs___default.a.readFileSync is not a function.
Answer: The mention of __WEBPACK_IMPORTED_MODULE_4_fs___ and the use of e.target.files suggests you are not running this code under Node.js but are bundling it up with WebPack and trying to run it in the browser.
The fs module requires Node.js.
You need to find a different approach if you want to do this in a browser.
See How to convert file to base64 in JavaScript?.

Error while using fs.readFileSync


Showing non-monotonicity (and unimodality) of particular function

Question: I want to show that
$$f(x) = \mu \frac{e^{r(x - \mu)}}{s^2 + e^{r(x - \mu)}} + x \frac{s^2}{s^2 + e^{r(x - \mu)}}$$
where $x > \mu > 0 $, $s^2 > 0$ and $r > 0$ is non-monotonic or, even better, unimodal with respect to the distance between $x$ and $\mu$. More precisely, that the function at first increases as $x$ grows, but that the marginal effect eventually becomes negative.
The approach I have taken is to show that the marginal effect $\frac{df}{dx}$ can be both positive and negative. First, taking the derivative with respect to $x$ we get
$$\frac{df}{dx} = \frac{s^2 e^{r \mu}(s^2e^{r\mu} + \mu re^{rx} + e^{rx} - rxe^{rx})}{(s^2e^{r \mu} + e^{rx})^2}. $$
Since the denominator is never negative, the sign of the derivative only depends on the difference
$$s^2e^{r\mu} + \mu re^{rx} + e^{rx} - rxe^{rx}.$$
First, the derivative must initially be positive. To show this, I set $x = \mu$ (implying no distance between $x$ and $\mu$) yielding
$$s^2e^{r \mu} + e^{r \mu} > 0.$$
However, I am bit unsure about how to prove that the derivative eventually will become negative. Rewriting the above expression, we get
$$\frac{s^2 e^{r \mu}}{e^{rx}} + r \mu + 1 - rx.$$
As $x$ grows, the first term will decrease in size, the two middle terms are constant and the third term increases in size. But how do I show that it will for sure be negative at some point? Is it enough to show that the marginal effect tends to 0 as $x \rightarrow \infty$ since it is a continuous function?
Many thanks,
Comment: What is known about the parameter $r$? In some contexts the word *unimodal* is used to describe a function that increases to a unique "peak" and thereafter decreases.  This might help improve your Question, since you are interested in showing more than merely the function is *not* monotonic.
Comment: Thanks for the clarification question! I should have added that $r > 0$. And showing that it is unimodal would be even better than merely showing that it is not monotonic.
Answer: Your last expression can be written as
$$s^2e^{r(\mu-x)} + r(\mu-x) + 1$$
and if $\mu$ is constant then as $x\to\infty$ the expression goes to $-\infty$.

Let $t = \mu - x$, and notice that $x > \mu > 0$ implies $t < 0$.
The derivative equals $0$ if and only if
$$s^2e^{rt} + rt + 1 = 0.$$
When $t\to0$, the expression approaches $s^2 + 1 > 0$.
On the other hand, because $s^2, r > 0$ the expression is easily seen to be monotonically strictly increasing on $t$.
It follows that, as $t$ decreases along the negative axis, the expression too strictly decreases monotonically, and hence it equals $0$ for a single value of $t$ and then becomes negative for all values afterwards.
Comment: Check the edit.
Comment: Thank you. This is probably the easiest way. Do you have any suggestions to show that it is unimodal?