javasript invoking custom module to update user response

Question: I have created Multiple choice questions in drupal . One node (page ) has one mcq . The answers are displayed by simple radio buttons and javascript .
Now  I am planing to give some dynamic behavior to users . When a user click the wrong option , I want to capture the response in a custom table in drupal , having userid , nodeid .
can I invoke a custom module by the present javascript  which gets the userid and nid and update the table . I did some  research , and found that form hook is the way to do such things ,But i have hard time understanding this. Can someone please give me right direction .
Thanks a ton !
Comment: I don't understand what you mean by ...answers are displayed by simple radio buttons and javascript. What is the role of the javascript exactly, and how are you navigating from one page or question to the next? And most importantly, are you capturing answers through the node add/edit form? If so you are going down the wrong path and should rather look at the [Webform](https://www.drupal.org/project/webform) module which can properly capture and collate surveys and questionaires.
Comment: I have just looked at your previous post in this forum and am now convinced more than ever that you need to give webform a look. Look at this page which gives a list of modules which supoort and enhance webform. [Webform Related Projects](https://www.drupal.org/node/1526208)
Comment: Hi Reynolds , each node has a mcq ( and the navigation is thorugh Book module) . The anwer for mcq is validated by javascript . if a user selects the wrong option , A message is displayed  right there , with simple javascript validation . now  i want to store the rseponse , for example for an incorrect option , i want to trigger something which can capture the userid, nodeid , timestamp and 'correct/incorrect' response in a table , so that i can display back the statistics to user later .
Answer: So, lets start from the top.
You have a table with userid, nodeid, responseid declared in a hook_schema. This will create the table.
Then, you declare with hook_menu a callback to capture incorrect values and db_insert them into the table.
Then, on the form page with the multiple choice, you extend the behaviour that if the answer is incorrect upon click, it makes an ajax request with the item selected and the node id to the callback, and the callback will determine the user from the current user session, and store it in the table.
So for the content type, you will probably have a multifield for the potential answers, and a single field with the relative id for the correct answer. So if the content creator creates five answers, and the first item is the correct item, a hook form alter will need to extract and #attach the correct answer so that the behaviour on the page can pick it up, use it to determine which of the items is the correct one, extract the field id of the incorrect items and then ping it to the server.
Comment: Thanks Craig ! This is the right pointers for me to proceed further . Thanks a lot !!


Relacionamento entre tabelas

Question: Tenho determinada tabela já criada e populada:
CREATE TABLE `formulario` (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `nome` varbinary(50) DEFAULT NULL,
  `carteira` varchar(30) NOT NULL,
  `tipo_ocorrencia` varchar(13) NOT NULL,
  `contato` varchar(20) DEFAULT NULL,
  `tel` varchar(50) DEFAULT NULL,
  `mensagem` text NOT NULL,
  `data` varchar(10) NOT NULL,
  `hora` varchar(8) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3744 DEFAULT CHARSET=utf8;

Estou criando esta tabela agora:
CREATE TABLE `preformulario` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`r1` VARCHAR( 3 ) NOT NULL ,
`r2` VARCHAR( 160 ) NOT NULL ,
`r3` VARCHAR( 160 ) NOT NULL ,
`r4` VARCHAR( 160 ) NOT NULL ) ENGINE = MYISAM;

Preciso exportar uma tabela que concilie as duas tabelas acima!
O usuário irá informar os dados da tabela preformulario e então começará a informar os dados da tabela formulario.
Conforme expliquei, a tabela formulario já está populada... Sua ID está no 3744.Tenho pouca... Quase nada, experiência com MySQL. Preciso saber se preciso criar uma terceira tabela conciliando as duas que citei ou se existe uma solução no meu PHP que já concilia estes dados?
Answer: voce não precisa de uma terceira table , criei um view ou uma proc ou mesmo um select que liste os dados que voce deseja mostrar para o usuário
no insert pege o id da tabela formulário e insira na outra tabela. Isso é um relacionamento de muitos para muitos
Comment: Olá, @Regis Faria. Não entendi muito bem, meu caro! O que quis dizer com "insert pege"?
Da forma como explicou eu consigo vincular o mesmo usuário? Tipo, se o cara preencher a primeira tabela e preencher a segunda, como faço pra vincular as duas inserções... Exibir as duas em um único SELECT?
Answer: list dados das duas tabelas relacionadas atráves de um select, view ou procudure isso para exibir para o usuario. Nesse select voce trará o id da tabela formulario que é o que voce precisa para fazer o insert na tabela preformulario`
Geralmente é assim que se faz.
Comment: Não é isso.. Não esclareci a dúvida. Não dependo tabela `formulário` para fazer insert na `preformulario`. Eu só preciso conciliar o que foi inserido na `preformulario` ao que for inserido na `formulário`. O mesmo usuário irá inserir dados nas duas.

Relacionamento entre tabelas


Set up SPF: Facing an error for MX and TXT record

Question: Our DNS is managed through Microsoft. I need to set up a new record to allow a new website to send email. Here is what I did.
enter image description here
Kindly assist. I face the same issue with the TXT record as well.
Answer: I'm not familiar with Plesk, but I guess you'll need to leave "Mail domain" field empty, as "@.domain.com." doesn't make any sense.
The correct form of the DNS record name would be "domain.com." or "@" (which means "the current DNS zone"). Your Plesk seems to already provide the zone name as suffix so leave it blank.
Also, don't forget to push the last "." (dot) on the Mail Exchange server field. If you omit the last dot (so you put "xxxxx.mail.protection.outlook.com"), it will be translated as "xxxxx.mail.protection.outlook.com.domain.com" and will not work as expected.
The last "." will tell that the hostname is not relative to the current DNS zone.
To check if your DNS configuration is correct, you'll need to use dig command (in Unix-like system, Google any alternative for Windows):
$ dig MX domain.com @your-domain-nameserver.com
$ dig TXT domain.com @your-domain-nameserver.com

Don't forget to replace "your-domain-nameserver.com" by one of your domain's DNS nameserver set at your registrar.
Comment: Thanks @Manoa I will try that and will let you know if it worked.


How to get notified when a server started with gcloud is completely up

Question: Is there a way to detect when a server is completely up (i.e. finished all the kernel startup tasks)? This is a Google Compute Engine Instance.
Nov 18 10:58:51 image-name google: No startup script found in metadata.
Nov 18 10:58:53 image-name kernel: [   27.491829] aufs au_opts_verify:1570:docker[2414]: dirperm1 breaks the protection by the permission bits on the lower branch
Nov 18 10:58:53 image-name kernel: [   27.703142] aufs au_opts_verify:1570:docker[2414]: dirperm1 breaks the protection by the permission bits on the lower branch
Nov 18 10:58:53 image-name kernel: [   27.735867] aufs au_opts_verify:1570:docker[2414]: dirperm1 breaks the protection by the permission bits on the lower branch
Nov 18 10:58:53 image-name kernel: [   27.771732] aufs au_opts_verify:1570:docker[2260]: dirperm1 breaks the protection by the permission bits on the lower branch
Nov 18 10:58:53 image-name kernel: [   27.797540] device vethfa3ab85 entered promiscuous mode
Nov 18 10:58:53 image-name kernel: [   27.804420] IPv6: ADDRCONF(NETDEV_UP): vethfa3ab85: link is not ready
Nov 18 10:58:53 image-name kernel: [   28.028306] IPv6: ADDRCONF(NETDEV_CHANGE): vethfa3ab85: link becomes ready
Nov 18 10:58:53 image-name kernel: [   28.035505] docker0: port 1(vethfa3ab85) entered forwarding state
Nov 18 10:58:53 image-name kernel: [   28.041963] docker0: port 1(vethfa3ab85) entered forwarding state
Nov 18 10:58:53 image-name kernel: [   28.048532] IPv6: ADDRCONF(NETDEV_CHANGE): docker0: link becomes ready
Nov 18 10:58:54 image-name kernel: [   28.980082] IPv6: eth0: IPv6 duplicate address fe80::42:acff:fe11:1 detected!
Nov 18 10:59:08 image-name kernel: [   43.068094] docker0: port 1(vethfa3ab85) entered forwarding state
Nov 18 10:59:53 image-name kernel: [   87.944452] aufs au_opts_verify:1570:docker[2864]: dirperm1 breaks the protection by the permission bits on the lower branch
Nov 18 10:59:53 image-name kernel: [   88.001012] aufs au_opts_verify:1570:docker[2864]: dirperm1 breaks the protection by the permission bits on the lower branch
Nov 18 10:59:53 image-name kernel: [   88.049510] aufs au_opts_verify:1570:docker[2815]: dirperm1 breaks the protection by the permission bits on the lower branch

My problem is that I can connect to it using SSH when kernel progress is below 30% and some processes are not yet started. I want to detect somehow if the server has completed startup.
Answer: You can create your own script to call the following command frequently:
gcloud compute instances get-serial-port-output INSTANCE_NAME

The serial port output will provide you with all the logs on your instance including the services that started as well.
Comment: Interesting command. I will try it!


Determine partial derivative of function

Question: How to determine first partial derivative of ln function
ex:
Determine first partial derivative of following function
$$f(x,y,z)=\ln(x+2y+3z)$$
I've been tried,but i stuck on ln derivative. Thanks for your answer.
Comment: You wanna do that by using the rules or using the definition?
Comment: Using rules @B.S
Answer: The derivative of a function $f=\ln g$ is $f'=g'/g$. Let $f(x,y,z)\equiv\ln g(x,y,z)\equiv\ln(x+2y+3z)$, so that $g(x,y,z)=x+2y+3z$. Then: $$f_x(x,y,z)=\frac{1}{x+2y+3z}.$$ We treat all variables other than $x$ as constants. Similarly, $$f_y(x,y,z)=\frac{2}{x+2y+3z},$$ and $$f_z(x,y,z)=\frac{3}{x+2y+3z}.$$
Comment: This is a complete source. +1
Answer: Hint: $f_z=\frac{1}{x+2y+3z}\cdot3$.
Answer: Partial derivative of $f$ with respect to $x$ is $f_x=\frac{1}{x+2y+3z}\times \dfrac{d}{dx}(x+2y+3z)$ and similarly the others.
Answer: To find the partial derivative  $\frac{\delta f}{\delta x_i}$ of a function $f(x_1,x_2,...x_n)$, we differentiate $f$ with respect to the variable $x_i$ assuming that $f$ is a function of one variable only, namely $x_i$ and all the other variables are constants.


Receber mensagens IRC CLIENT VB

Question: Ola, estou com uma dificuldade para receber as mensagens de uma conexão IRC feita em VB,
Aqui o Codigo:

Ja foi adicionado a biblioteca como referencia IrcClient.dll.
Esta falando que o irc_ChannelMessage não pode manipular o evento, peocurei a respeito mas não tive sucesso.

Aqui esta o Projeto com o metodo "sender As Object, e As ChannelMessageEventArgs"
Porém ao chamar "Message" não reconhece como sendo do IRC

Dim WithEvents irc As IrcClient
Public Sub Conectar()
  irc = New IrcClient("chat.freenode.net:6665")
  irc.Nick = txtNick.Text
  irc.JoinChannel("##C++")
  irc.Connect()
  lblStatos.Text = "Conectado Servidor Irc."
  End Sub
Public Sub ircChannelMessage(sender As Object, e As ChannelMessageEventArgs) Handles irc.ChannelMessage
  txtMensagens.AppendText(Message & vbNewLine)
  txtMensagens.ScrollToCaret()
  lblMensagens.Text = "Lendo Mensagens."
  End Sub

https://github.com/MrDeppy/deppy
Answer: Os parâmetros do método irc_ChannelMessage não estão corretos.
Pela mensagem de erro, parece que o correto seria colocar a seguinte assinatura:
Private Sub irc_ChannelMessage(sender As Object, e As ChannelMessageEventArgs) Handles irc.ChannelMessage
End Sub

Comment: A mensagem de erro desapareceu, porém não consigo chamar as respostas do servidor.
Vou enviar o projeto.
Comment: Aqui esta o projeto

https://github.com/MrDeppy/deppy

Fiz a correção, porém não consigo chamar a "Message" para a TextBox.
preciso receber as resposta do servidor.

Receber mensagens IRC CLIENT VB


How to customize the user login form?

Question: I'm trying to customize user login form in /user/login page and I want to use a hook_form_alter function to add some awesome style and placeholder to each of user login form fields and remove or hide: "Enter your admin username" and "Enter the password that accompanies your username" description expressions under each of theme.
To resolve this issue I added something like below code to my ThemeName.theme:
function ThemeName_form_alter(&$form, $form_state, $form_id) {
  if ( $form['#form_id'] == 'user_login_form' ) {
    $form['actions']['submit']['#attributes']['class'][] = 'button glow button-primary expanded';
    $form['keys']['#attributes']['placeholder']['name'] = t('User name');
    $form['keys']['#attributes']['placeholder']['password'] = t('Password');
  }
}

I try out many different ways but I can't get any result.
in finally I want to achieve something like below image:

I read this pages but seems none work in Drupal 8:
How to modify the fields of user registration form and user login form?
Modifying the default user registration page
Customize user login block
Comment: I'd hazard a guess that `user-login-form` should be `user_login_form` in your function.
Comment: See what Jeff Burnz has said in the answer below.
Comment: Why not just do it with CSS? `.user-login-form .description { display: none; }`
Comment: The actual strings that you are trying to remove are in UserLoginForm.php - it will be helpful for you to read that code to see how the form is constructed.
Comment: I presume you can add a placeholder attribute when doing the `form_alter()` stuff
Answer: You can add placeholders in hook_form_alter().
/**
 * Implements hook_form_alter().
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function ThemeName_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_login_form' ) {
    // Add placeholders.
    $form['name']['#attributes']['placeholder'] = t('User name');
    $form['pass']['#attributes']['placeholder'] = t('Password');
  }
}

Use the Devel module functions to print out the form using kint, this way you can visibly see the entire structure of the $form array.
Comment: It seems that `User Name` should be `Username` or `User name` to t() function work's correctly.
Comment: The problem is not of the function, but of the string within the function, I used what you used because I have to assume you may rely on that string in your translations.
Answer: SimpleLogin
https://www.drupal.org/project/simplelogin
It is a simple module for Customize Drupal Login, Password and Register pages with Background images.
Administrators can provide the ability to allow users to attach their own background images/ own background color to user login, password, registration pages. Better features including customize background color, image settings.
Features:
Clean & Sleek Design,
Customize background color, link color, submit button color,
Customize image settings,
Background image Opacity,
Remove unwanted Css files from simplelogin pages,
Login pages wrapper width,
Mobile responsive,

How to customize the user login form?


An isomorphism between $\mathbb F_2(\alpha )$ and $\mathbb F_2(\beta )$.

Question: We know that $f(x)=x^3+x+1$ and $g(x)=x^3+x^2+1$ are irreducible over $\mathbb F_2$. Let $\alpha $ a root of $f$ and $\beta $ a root of $g$. Let $K=\mathbb F_2(\alpha )$ and $L=\mathbb F_2(\beta )$. Find explicitely an isomorphism between $K$ and $L$.
Attempts
Does $\alpha \longmapsto \beta $ work ? It look to easy. If not, how can I do ?
Comment: Look for generators of the multiplicative group of each field.
Comment: No it doesn't work. Note that $\mathbb{F}_2(\alpha) \cong \mathbb{F}_{2^{3}}$
Comment: @Joppy In general there are $\phi(p^k-1)$ generators. I think there is a better way, using the Galois group maybe.
Comment: @user1952009: you're right, that was a silly suggestion, my apologies.
Comment: You can easily show that $1/\alpha$ is a zero of $g(x)$ because
$$g(x)=x^3 f(\frac1x).$$ This exact question has been handled on our site before, but I don't have the time to search for an earlier incarnation now. Using *reciprocal polynomial* as a buzzword probably gives you some hits :-)
Answer: Not quite. You have to find all roots of the polynomials over $\mathbb{F}_2(\alpha)$. In fact, for $x^3+x+1$ all roots are given by $\alpha$, $\alpha^2,\alpha^2+\alpha$.
Comment: Thank your for your link, it really help. But I don't understand why we need the roots of $x^3+x^2+1$ over $\mathbb F_2(\alpha )$... To me $\mathbb F_2(\alpha )$ and $\mathbb F_2[x]/(x^3+x^2+1)$ are two finite field of same cardinal, so we just need to associate to each element of $\mathbb F_2(\alpha )$ an element of $\mathbb F_2[x]/(x^3+x^2+1)$... I'm sorry, but I don't see the subtlety here.
Answer: You have to map $\alpha$ to a root of the polynomial $x^3 + x + 1$ in $\Bbb F(\beta)$.
You can just try them all: $\Bbb F(\beta)$ has $8$ elements, $0, 1, \beta$ are not a root, so there are $5$ candidates left and $3$ of them are a root.
Answer: Hint: check that $\beta+1$ satisfies the polynomial $f(x)$ for $\alpha$.


In JAGS, how can I fix a parameter to a distribution, as opposed to just a constant?

Question: The first code chunk below (model1) is a JAGS script designed to estimate a two-group Gaussian mixture model with unequal variances. I am looking for a way to fix one of the parameters (say $\mu_2$) to a particular distribution (e.g., dnorm(0,0.0001)). I know how to fix $\mu_2$ to a constant (e.g., see model2 in code chunk 2), though I cannot find a way to fix $\mu_2$ to my prior belief(e.g., see model3 in code chunk 3, which shows conceptually what I am trying to do).
Thanks in advance!
Code chunk 1
model1 = "
model {

for (i in 1:n1){
y1[i] ~ dnorm (mu1 , phi1)
}

for (i in 1:n2){
y2[i] ~ dnorm (mu2 , phi2)
}

# Priors
phi1 ~ dgamma(.001,.001)
phi2 ~ dgamma(.001,.001)
sigma2.1 <- 1/phi1
sigma2.2 <- 1/phi2
mu1 ~ dnorm (0,0.0001)
mu2 ~ dnorm (0,0.0001)

# Create a variable for the mean difference

delta <- mu1 - mu2

}
"

Code chunk 2
model2 = "
model {

for (i in 1:n1){
y1[i] ~ dnorm (mu1 , phi1)
}

for (i in 1:n2){
y2[i] ~ dnorm (mu2 , phi2)
}

# Priors
phi1 ~ dgamma(.001,.001)
phi2 ~ dgamma(.001,.001)
sigma2.1 <- 1/phi1
sigma2.2 <- 1/phi2
mu1 ~ dnorm (0,0.0001)
mu2 <- 1.27

# Create a variable for the mean difference

delta <- mu1 - mu2

}
"

Code chunk 3
model3 = "
model {

for (i in 1:n1){
y1[i] ~ dnorm (mu1 , phi1)
}

for (i in 1:n2){
y2[i] ~ dnorm (mu2 , phi2)
}

# Priors
phi1 ~ dgamma(.001,.001)
phi2 ~ dgamma(.001,.001)
sigma2.1 <- 1/phi1
sigma2.2 <- 1/phi2
mu1 ~ dnorm (0,0.0001)
mu2 <- dnorm (0,0.0001)

# Create a variable for the mean difference

delta <- mu1 - mu2

}
"
```

Comment: Why not use the distributional operator instead of the assignment operator in model 3. That is, why not use `mu2 ~ dnorm(...)` instead of `mu2 <- dnorm(...)`?
Comment: Because that would tell JAGS I wanted to freely estimate mu2. I want to fix mu2.
Comment: `mu2 <- dnorm(0,0.0001)` makes no sense to me.
Answer: There are at least two ways to express my prior belief of mu2:

I believe very strongly that mu2 can only be a single value, 1.27 say, in which case I can use the assignment operator as shown in chunk2.
I believe that mu2 is most probably some value, 0 say, but with ~95% probability I think it could be between -0.0002 and 0.0002. In that case I can specify a prior distribution on mu2 as is shown in chunk1.

I think 2. is the answer to the title of the OP.


how to separate sentence[i] (string) into words(string) in c++

Question: I have a problem. In my project, I take sentence line by line from dataset file which has one sentence each line. Then , I should separate sentences into words. But I couldn't find this how can I do.
This are the codes of class which will read from dataset:
class Input{
...
public:
string *word;
string *sentence;
Couple *couple;    // int x , int y  order of sentence and word
int number;
int line;
...
void readInput(string input);
}

This are the codes of read method:
void Input::readInput(string input)
{
cout << "Reading the " << input <<endl;

ifstream infile;
infile.open(input.c_str());

    if(!infile.is_open()){
    cerr << "Unable to open file: " << input << endl << endl;
    exit(-1);
}

for(int i=0; i<line ; i++){
    getline(infile, sentence[i]);
    //infile >> sentence[i];
}

for(int j=0;j<line ;j++){
// I want to separate sentences into words
}

infile.close();
cout << "Finished Reading the " << input <<endl;

}
Comment: Are you asking us to do the programming task?
Comment: How can I separate sentences (string) into words(string)?
Answer: for(int j=0; j<line; ++j)
{
    std::istringstream iss(sentence[j]);
    for (std::string w; iss >> w; )
    {
        word[number] = w;
        ++number;
    }
}

You'll need to do something about punctuation though, if you don't want those attached to your words.  Simple enough I think.
Comment: `for(int j=0;j> word[number];
        number++;
    } while (iss);

    }`
Comment: `for(int j=0;j> word[number];
number++;
} while (iss);
}`
Thanks it worked but after sentences program makes a space (as word), what can I do?
Comment: for example
`From
fairest
creatures
we
desire
increase,
// should not be space here
That
thereby
beauty's
rose
might
never
die,
// should not be space here
But
as
the
riper
should
by
time
decease,
// should not be space here
`
Comment: @BurakDağlı: You re-arranged it in such a way that it adds a word even after the input fails.  See my update for a more correct version for your case.
Answer: If it were me in the method where you have:
for(int j=0;j<line ;j++){
    // I want to separate sentences into words
}

I would use a regex to match all words in sentence[j] boost regex is a library I have used with great success in the past.
Answer: You can try to loop through the std::string representing each line by looking for end-of-word markers using std::string::find_first_of(). The parameter to find_first_of would the set of characters that are used to separate words in your text file(could be space, period etc.).


How do I edit and commit a single file from a Subversion repository?

Question: Using TortoiseSVN (a command line solution is OK too), without creating a folder on the repository side, what are the steps to checkout a single file, edit and check back in with comments?
Comment: If thats the case, duplicate http://stackoverflow.com/questions/122107/checkout-one-file-from-subversion
Comment: I think you meant to say "without creating a folder on client side"
Answer: AFAIK you cannot get a copy of a single file from SVN, a working copy is always a directory. So you will need to check out a whole folder in order to edit the file in question and then commit.
This was the case some time back (less than 3 months) and I doubt it has changed since then.
Answer:
Right click in Windows Explorer where you want a working copy.
Choose Check Out. It might be in TortoiseSVN's menu.
Enter the URL and accept to get a working copy.
Make the change to the file.
Right click in the working copy. Choose commit.

OR
Refer to Stack Overflow question Checkout one file from Subversion.
Comment: AFAIK, you mus check out the entire folder (to get the .svn file), which means you CAN NOT just check out one file. If that is correct, then this is NOT a helpful answer. The URL is helpful, however. I'd remove the top portion of this answer and just keep the OR.
Answer: To check out a single file, you'll still need to check out its parent directory. From the command line, to check out https://svn.example.com/trunk/myfolder/index.html:
svn co https://svn.example.com/trunk/myfolder/ --depth empty
svn up myfolder/index.html

Now, you can edit and commit this file as usual, without checking out anything else.
TortoiseSVN also includes "checkout depth" in its svn checkout menu option; however, I don't know of a way to make Tortoise do svn up filename on a file that doesn't exist.
Answer: This is possible with TortoiseSVN, but you must checkout the parent directory as well:

Create a working copy of the directory with no contents (use checkout depth "Only this item")
Click on the new working copy and right click to select the repository browser (TortoiseSVN -> Repo-browser)
Right click the file of choice in the repository browser and select "Update item to revision"
Answer: You have a file single.txt you want to commit.
The right procedure is :
cd /path/destination_directory
svn up
svn commit single.txt -m "Insert here a commit message"

Hope this will help.


Janela modal (Boostrap) não fica visível

Question:

<!doctype html>

    <title>Teste</title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

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

    <link rel="stylesheet" type="text/css" href="css/estilos.css">

                     casa

                 carro

Informe o ano de pesquisa

                    Informe o ano:
                    <input type="text" class="form-control" id="ano">

                    <button type="button" class="btn btn-primary">Buscar</button>

Boa tarde, pessoal.
Estou começando a estudar desenvolvimento web e estou com dificuldades para fazer uma modal (Bootstrap) ficar visível. Depois que eu aciono o link que mostrará a modal, eu até percebo que ela está presente na página (os links por trás ficam "desabilitado" quando passo o mouse por cima), mas os componentes não aparecem. O que posso estar fazendo de errado?
Comment: Acho que sei qual o problema. O que é informado no console quando executa a página?
Comment: @wmsouza, não era este o caso (já havia testado isso). Quando eu removia o atributo "href" o link deixa de ser um link, ficava desabilitado.
Comment: Por padrão o Bootstrap previne o evento padrão de elementos com `data-toggle="modal"`. Logo, independente do link possuir `href="pagina.php"` ou `href="#"`, o que vai prevalecer é o evento de toggle do modal.
Answer: O seu problema pode estar relacionado com o javascript que está utilizando.
O Bootstrap possui versões específicas. Para utilizar o Bootstrap 4.0.0, vai precisar do css e do javascript na mesma versão.
Como você está utilizando a BootstrapCDN para incluir o CSS, aconselho a puxar o JavaScript também de lá:

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

Só isso parece resolver o seu problema.
Lembrando que é recomendável carregar todos os scripts imediatamente antes do fechamento da tag <boby>.
Alguns erros encontrados no seu código:

Duplo carregamento do jQuery
Scripts carregados no head da página

Posso estar enganado, mas acho que você está carregando o FontAwesome de forma errada. O correto seria carregar um arquivo CSS que pode ser encontrado aqui.
Comment: E se não for esse o problema? Creio que deveria esperar o **AP** da um parecer!
Comment: @wmsouza Fiz o teste em minha máquina, e foi esse o único problema encontrado. Creio que deveria esperar um parecer do autor da pergunta antes de downvotar algo totalmente relacionado à pergunta.
Comment: Resolveu, @DanielBonifácio. Segui suas considerações e, por via das dúvidas, removi os carregamentos que tinha e peguei todos no site do Bootstrap para trabalhar via CDN. Foi colar os links retirados da página principal (https://getbootstrap.com) que o modal apareceu corretamente.

Obrigado, gente!!
Comment: @GenivaldoSilva Fico feliz em ter ajudado! :D


How to programmatically create a custom panel pane

Question: I created a custom panel layout with Panels 3 (following this excellent link) and my layout is ready. Now I have my static markup ready for a node (I can use it on the article or a custom content type) and I want to find out how to create a custom panel pane programmatically. I don't won't to do it through the UI as I want to totally control the dynamic markup of a node.
to make things specific (but keeping a certain level of generality), imagine

       !!php dynamic day of the date!!
       !!php dynamic month of the date!!

     !!php dynamic title of the node!!

 !!php dynamic content(body) of the node!!

       !!php dynamic read more text!!

How can I achieve to manage the above dynamic node (and let's suppose I want to achieve an exact, specific markup)?
Comment: Would it be an option to export the panel to code, using features module, and then edit the code as you wish? Why can't you do dynamic stuff with custom views(written in code) that will be integrated into the panel?
Comment: I don't want extra code in my site. I want it to produce the markup I want and not 20 divs more :) Moreover I have already done the (not so simple) styling for the markup and I don't want it(the markup) to change :)
Answer: Ok my question maybe was not the best but at least I hope the following will help new themers get on track.

I created a custom content type called: seminar
I created this node--seminar.tpl.php and placed it inside /sites/all/themes/awesome (the name of my theme)
Inside this file I copy pasted the code found in /modules/system/node/node.tpl.php and I tweaked the code as follows.
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> post clearfix"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
  <?php if (!$page): ?>

         <?php print $date_day; ?>
         <?php print $date_month;?>

      <a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <div class="content"<?php print $content_attributes; ?>>
    <?php
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>

      <?php print render($content['links']); ?>

Keep in mind that in order to achieve this
 <?php print $date_day; ?>
 <?php print $date_month;?>

so that $date_day and $date_month correspond to sth meaningful, I had to go through this. Othewise by default drupal outputs sth like  Apr 30  and we can't target Apr and 30 seperately for CSS styling.


Given the graph of $y=f(x)$ on the left, and $f(x)=(x-2)^2-7$ graph the function

Question:
Given the graph of $y=f(x)$ on the left, and $f(x)=(x-2)^2-7$ graph the fucntion that would represent
Answer: Hint: Domain represents all $x$ points on the graph. And the range is all $y$ points. So for the $y=f(x)$ case the Domain would be all $x$ while the range would be all $y$ $\ge$ $-7$
And when trying to find the invariant points you can set your function $f(x) = x$ solving for $x$ values gives you your invariant points
Comment: what about the secound question? :(
Comment: no I still don't understand for the 2 question is it all reall numbers x>0 and range x<-7


How can I access the default JDT completion proposals in a custom Eclipse plugin?

Question: I'm writing an Eclipse plugin, that has the functionallity of auto completion (the thing when you press Ctrl+Space).
Generally, I know how it works, I made a completion for my own proposals.
But the problem is, that my boss want me to make a completion the same as is in eclipse already. For example if I type "Str", or "org" and press Ctrl+Space, I want to have a completion lists from Java, for example for "Str" a "String", for "org" "org.eclipse...." + a long list. So I need to compute proposals for packages and for classes, just like in Eclipse's JDT editor.
I know that may sound stupid, making it the same as already is, but I need this solution.
Has anyone done a similar thing earlier? Which class do I need to implement?  What changes do I need to make (plugin.xml?)?
Comment: Is your problem showing the proposals, or generating them?
Comment: I can show my proposals which I compute. I know how it works, but i can't generate/display default Java proposals. I simply donno how, but I know this is somehow possible :)
Comment: I don't know any details, but I suppose you somehow can look how the JDT does this, and access the same methods (or copy them, if you don't want to be dependent on the JDT plugins). (I edited the question title, by the way.)
Answer: Try org.eclipse.jdt.ui.text.java.CompletionProposalCollector. There's an example on how to use it in the class' Javadoc.


Salvar $_POST com var_export depois gerar Variável novamente

Question: Eu precisei gerar alguns dados pegando o conteúdo de um $_POST e salvando em um arquivo para processá-lo posteriormente.
Fiz da seguinte forma:
$dados = $_POST;
$dados = var_export($dados, true);
$handle = fopen('posttemp.txt', 'a');
fwrite($handle, $dados);
fclose($handle);

Até aqui esta tudo bem, se abro o arquivo posttemp.txt este é o seu conteúdo.
array (
  'id' => '1832007',
  'post' =>
  array (
    'codigo' => '39063',
    'autor' => 'Christiano',
  ),
  'conteudo' =>
  array (
    'id' => '2526167',
    'dataInicio' => '2017-08-03 21:30:43',
    'dataFinalizada' => '2017-08-03 21:30:47',
    'status' => 'Publicado',
  ),
  'autor' =>
  array (
    'codigo' => '37276',
    'email' => 'email@example.com',
    'nome' => '1 Lift Gold',
    'quantidade' => '1',
  )
)

Agora preciso pegar o conteúdo que foi salvo em posttemp.txt e transformar novamente em uma variável para que possa enviar novamente via POST.
Comment: Por quê não usa o `serialize` e `unserialize`?
Answer: O var_export não tem um caminho reverso, o intuito dele é criar um array válido para o PHP, por exemplo se você deseja editar arquivos .php de configurações dinamicamente.
Um exemplo bem simplório seria isto:
Salva:
<?php
$arr = array(
    'a' => 1,
    'b' => 2,
    'c' => 3
);

$str = var_export($arr, true);
$str = '<?php' . PHP_EOL . 'return ' . $str . ';';

file_put_contents('config.php', $str);

Vai gerar o seguinte conteudo:

 <?php
 return array (
   'a' => 1,
   'b' => 2,
   'c' => 3,
 );

Usa os dados posteriormente:
<?php

$arr = include 'config.php'; //O return em includes retorna o valor

print_r($arr);

Isto pode ser um exemplo de uso que você deseja, pois o config.php irá carregar os dados na várivel $arr pelo include.
No entanto se deseja mesmo usar um arquivo .txt e se os dados não são sensíveis (como senhas ou códigos secretos), você pode usar funções como serialize e unserialize, por exemplo:
gravar.php
file_put_contents('posttemp.txt', serialize($_POST));

ler.php
$dados = file_get_contents('posttemp.txt'); // Lê o arquivo

$post_recuperado = unserialize($dados); //recria os valores

var_dump($post_recuperado); //Exibe com var_dump

Nota:

file_get_contents lê o conteúdo do arquivo
file_put_contents grava o conteúdo no arquivo
Comment: Não seria melhor usar `json_decode` e `json_encode`? Segundo a própria documentação do `unserialize`: "Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes.".


Conversion from char[] to String using toString()

Question: I have a char [].
StringBuffer x = new StringBuffer(name.toString());
StringBuffer y = new StringBuffer();
y.append(name);
String s1 = new String(name);

print x -> [C@42b3b079
print y -> metafactory
print s1 -> metafactory

Could you please tell me why the difference?
When I read the javadoc:
String java.lang.Object.toString()
Returns a string representation of the object. In general, the toString method
returns    a string that "textually represents" this object. The result should be a
concise but informative representation that is easy for a person to read. It is
recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the
class of which the object is an instance, the at-sign character `@', and the unsigned
hexadecimal representation of the hash code of the object. In other words, this method
returns a string equal to the value of:

                 getClass().getName() + '@' + Integer.toHexString(hashCode())

Looks like it depends on implementation. Shouldn't it be advisable to return a
readable string instead with the toString() API.
Thanks
Comment: what type of object is name?
Comment: I don't think you should question language design. I'm afraid "answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise."
Comment: @javaseeker `char[]`, it seems
Comment: @Java Seeker: name is char[]

I am sorry. I am not questioning language design. I am starting out on Java.
Comment: you can not call toString on char[] because char[] is primitive type again about toString() it is a method of base--super class Object. in java each class inherit Object class so by default each class inherit toString() method. it is he reposibility of derived class how they represent toString() method.
Answer: The code:
StringBuffer x = new StringBuffer(name.toString());

behaves the same as:
String name2str = name.toString(); //here the value of name2str is "[C@42b3b079"
StringBuffer x = new StringBuffer(name2str);

That's why print x -> [C@42b3b079.
If you construct the StringBuffer as:
StringBuffer x = new StringBuffer(name);

Then print x -> metafactory.
The reason Object.toString() implemented like this is that, as the base of the inheritance chain, it really doesn't know what information of the subclasses should be added to the return value of toString(). So it just output the class name and the hashcode of the object, which can identify the instance, and it's readable in my opinion.
If you want to output every element of the array, just use the utility method java.util.Arrays.toString(name).


How can I run a post-deploy script (e.g. automate migrations) on flex google app engine?

Question: I am trying to automate deployment to a Google Flex App Engine in a bitbucket pipeline.
If I'm deploying via the CLI I can run something like this to run migrations after deployment:
gcloud app instances ssh --quiet --project <MYPROJECT> --version v0-0-1 --container=gaeapp --service <MYSERVICE> -- do-something-after-deploy.sh

However, this prompts me for this:
ED25519 key fingerprint is SHA256:....................
Are you sure you want to continue connecting (yes/no/[fingerprint])?

It doesn't look like I can use ssh-keyscan to accept the host key.  Is there a way to automate the execution of a script on google app engine after deployment?
Comment: I don't think this is possible currently.  It *is* available with `gcloud compute ssh`, though: https://cloud.google.com/sdk/gcloud/reference/compute/ssh#--strict-host-key-checking.

I set this up to migrate via the cloud sql proxy instead.
Answer: If you don't want to be prompted when running a Cloud SDK command you can use the --quiet flag. As shown in the documentation:
--quiet, -q
Disable all interactive prompts when running gcloud commands. If input is required,
defaults will be used, or an error will be raised. Overrides the default
core/disable_prompts property value for this command invocation. This is equivalent to
setting the environment variable CLOUDSDK_CORE_DISABLE_PROMPTS to 1.

Comment: I think `--quiet` removes the prompts on the gcloud command, but not the ssh command that it executes on the intermediate shell.
Comment: But he has already used `--quiet`!
Comment: Hi Mike, I missed that. I believe you are right. However I am not sure that your approach is recommended since ssh the instance is meant for [debugging purposes](https://cloud.google.com/appengine/docs/flexible/python/debugging-an-instance)


How does one create their own finger-style guitar music?

Question: I understand that fingerstyle guitar is something that is very opinion based (some artists love to accentuate the bass line of the song, while others prefer to highlight the melody)
How does one go about doing it?
Answer: This is very broad, but I think I can break down some introductory steps:

Step 1: Play chords with the fretting hand, as if strumming. Learn some rolls - that is, right-hand picking sequences. There are plenty of rolls in books and on the internet.
Step 2: Learn to adapt the rolls depending on the chord, so that root notes are played when you want them, etc.
Step 3: Elaborate the rolls by making more left-hand movements, for example pull-off or hammer-on to add a seventh.
Step 4: Extend how melodic you can be, by making chord shapes only on a few strings, picking only those, and moving up and down the fretboard.
Step 5: Learn the fretboard, scales and chords well enough that you can play what you hear in your head!

Trying out tabs of other people's songs -- or trying to copy them without the aid of a tab -- or trying to transcribe a tab yourself -- will teach you a lot of this. When following a tab, don't just play the notes without thinking how they relate to chord shapes and scales.
Answer: @Slim's answer is great. A couple of things to add.
After you learn some rolls (picking patterns), you'll be able to arpeggiate chords and play chord melody solos.
Now learn to play the melody fingerstyle, concentrating on your picking hand.
First learn to play the melody and/or bassline with just your thumb and index finger.  Rev. Gary Davis was an expert at this.  Then add the remaining fingers on your picking hand to play chords while you play the melody with your thumb and forefinger.  Now you're playing the guitar like a piano--it sounds much less "guitaristic".
Finish off by learning to play the single-note melody line with all of your picking fingers.
By mixing all of these techniques, you will have a rich palette to paint your musical pictures with.


Consequences for not estimating autocorrelated residuals in a growth curve model

Question: I am fitting a second order growth model with 7 time points on Mplus.
When I estimate the model with autocorrelated residuals in it
the model will not run because of identification issues.
(when I remove the code for autocorrelated residuals it runs,
so it is about sample size, I suppose)
I want to know how not accounting for autocorrelated residuals
will affect the estimation.
Thanks everyone in advance.
Comment: Greetings and welcome to CV! It would be helpful to provide a lot more information about what is going on. Giving answerers information about the nature of the data, output from the model, etc. will ensure a higher likelihood of this question getting answered.
Comment: Thank you so much for this advice. I was not sure what would be useful information that will help me get informed answers. I'll educate myself more next time.
Answer: It depends on how many indicators per time point you have and how many error covariances you allow (e.g., only between the error terms for corresponding indicators and adjacent time points vs. all error correlations for the same variable over time). In my opinion, a better way to account for indicator-specific effects is to include method (indicator-specific) factors; specifically, one residual method factor less than there are indicators. This often leads to a more parsimonious specification and a clearer interpretation of the results. See Figure 2 in the following paper:
Eid, M., Schneider, C., & Schwenkmezger, P. (1999). Do you feel better or worse? The validity of perceived deviations of mood states from mood traits. European Journal of Personality, 13(4), 283-306.
Or (perhaps even better) use indicator-specific growth factors (and no error covariances or method factors at all). See
Bishop, J., Geiser, C., & Cole, D. A. (2015). Modeling latent growth with multiple indicators: A comparison of three approaches. Psychological Methods, 20(1), 43-62.
Eid, M., Courvoisier, D. S., & Lischetzke, T. (2012). Structural equation modeling of ambulatory assessment data. In M. R. Mehl & T. S. Connor (Eds.), Handbook of research methods for studying daily life (pp. 384–406). New York, NY: Guilford Press.
Comment: Thank you Mr. Geiser for answering my question in great detail! You answer helped me understand my question and at the same time educated me as to what kind of information to include when asking questions on CrossValidated next time! I'll read through the articles you have provided me. Thanks again. It really helped.


When to use AWS CloudfrontWebDistribution and when to use AWS Cloudfront Distribution

Question: I see in aws-cdk there are two constructs:

CloudFrontWebDistribution
Distribution

Each have different props that do not look compatible with each other.
I'm wondering which one to use?
Comment: Welcome to SO! In order to help your, you should ensure that we can replicate/understand your problem. What are you trying to do?
Answer: The AWS CloudFrontWebDistribution is the original method for working with CloudFront distributions. But now, they had implemented a new method that is provided by Distribution. You can use both CloudFrontWebDistribution as well as Distribution for working with CloudFront distributions, but Distribution has a simpler interface and they receive new features faster. So, it is recommended to use Distribution instead of CloudFrontWebDistribution.
Comment: To support this argument, here is an implementation of Cache Policies in CloudFront Distribution.
CloudFrontWebDistribution is pending implementation since Oct 2020 but Distribution got it already implemented and merged.

https://github.com/aws/aws-cdk/pull/10656
Comment: Good to know. Maybe they should mention it in the CDK API documentation.
Answer: You can use CloudFrontWebDistribution unless you're looking to have RTMP (streaming) distribution then you can configure the Distribution


Replace wildcard certificate on multiple sites at once (using command line) on IIS 7.5

Question: I have 3 websites: aaa.my-domain.com, bbb.my-domain.com and ccc.my-domain.com all using a single wildcard certificate *.my-domain.com on IIS 7.5 Windows Server 2008R2 64-bit. That certificate expires in a month and I have a new wildcard certificate *.my-domain.com on my server ready.
I want all those domains to use the new wildcard certificate without noticeable downtime.
I tried the usual through the UI starting with replacing the certificate for aaa.my-domain.com:

But when I press OK, I get the following error:

--------------------------- Edit Site Binding ---------------------------
At least one other site is using the same HTTPS binding and the binding is configured with a different certificate. Are you sure that you want to reuse this HTTPS binding and reassign the other site or sites to use the new certificate?
--------------------------- Yes   No ---------------------------

When I click Yes, I get the following message:

--------------------------- Edit Site Binding ---------------------------
The certificate associated with this binding is also assigned to another site's binding. Editing this binding will cause the HTTPS binding of the other site to be unusable. Do you still want to continue?
--------------------------- Yes   No ---------------------------

This message tells me that https://bbb.my-domain.com and https://ccc.my-domain.com will become unusable. And I will have downtime for those at least until I'm done replacing the certificate for those 2 domains too, right?
I was thinking that there must be a smarter way of doing this. Possibly through the command line that replaces the wildcard certificate with a new one for all website at once. I couldn't find any resources online as to how to do that. Any ideas?
Sites related to wildcard and binding:

http://www.diaryofaninja.com/blog/2010/09/01/binding-multiple-domains-to-a-wildcard-ssl-on-a-single-ip-in-iis-75
http://www.computer-howto.com/2011/08/running-multiple-ssl-iis-sites-iis7-75/
https://stackoverflow.com/questions/3895675/how-to-install-wildcard-ssl-cert-on-iis-7-5
http://blogs.msdn.com/b/asiatech/archive/2010/12/27/setting-up-a-wildcard-certificate-in-iis-7-how-to-avoid-those-certificate-mismatch-errors.aspx

Sites related to binding certificates from the command line:

IIS7 add certificate to site from command line
https://stackoverflow.com/questions/591597/how-to-assign-a-ssl-certificate-to-iis7-site-from-command-prompt
Comment: Hm, you're right.  Sorry about that.  Reverted.
Answer: The context of the answer is that IIS 7 doesn't actually care about the certificate binding. IIS 7 only ties websites to one or more sockets. Each socket being a combination of IP + port. Source: IIS7 add certificate to site from command line
So, what we want to do is do certificate re-binding on the OS layer. The OS layer takes control of the SSL part, so you use netsh to associate a certificate with a particular socket. This is done through netsh using netsh http add sslcert.
When we bind a (new) certificate to a socket (ip + port), all sites using that socket will use the new certificate.
The command to bind a certificate to a socket is:
netsh http add sslcert ipport=10.100.0.12:443 certhash=1234567890123456789012345678901234567890 appid={12345678-1234-1234-1234-999999999999}
How to
This part explains how to proceed step-by-step. It assumes you have some websites (aaa.my-domain.com, bbb.my-domain.com) running a *.my-domain.com certificate that is about to expire. You already have a new certificate that you already installed on the server but not yet applied to the websites on IIS.
First, we need to find out 2 things. The certhash of your new certificate and the appid.

certhash Specifies the SHA hash of the certificate. This hash is 20 bytes long and specified as a hexadecimal string.
appid Specifies the GUID to identify the owning application, which is IIS itself.

Find the certhash
Execute the certutil command to get all certificates on the machine:
certutil -store My
I need not all information so I do:
certutil -store My | findstr /R "sha1 my-domain.com ===="
Among the output you should find your new certificate ready on your server:
================ Certificate 5 ================
Subject: CN=*.my-domain.com, OU=PositiveSSL Wildcard, OU=Domain Control Validated
Cert Hash(sha1): 12 34 56 78 90 12 34 56 78 90 12 34 56 78 90 12 34 56 78 90

1234567890123456789012345678901234567890 is the certhash we were looking for. it's the Cert Hash(sha1) without the spaces.
Find the appid
Let's start of by looking at all certificate-socket bindings:
netsh http show sslcert
Or one socket in particular
netsh http show sslcert ipport=10.100.0.12:443
Output:
SSL Certificate bindings:
----------------------
IP:port                 : 10.100.0.12:443
Certificate Hash        : 1111111111111111111111111111111111111111
Application ID          : {12345678-1234-1234-1234-123456789012}
Certificate Store Name  : MY
Verify Client Certificate Revocation    : Enabled
Verify Revocation Using Cached Client Certificate Only    : Disabled
Usage Check    : Enabled
Revocation Freshness Time : 0
URL Retrieval Timeout   : 0
Ctl Identifier          : (null)
Ctl Store Name          : (null)
DS Mapper Usage    : Disabled
Negotiate Client Certificate    : Disabled

{12345678-1234-1234-1234-123456789012} is the appid we were looking for. It's the Application ID of IIS itself. Here you see the socket 10.100.0.12:443 is currently still bound to the old certificate (Hash 111111111...)
bind a (new) certificate to a socket
Open a command prompt and run it as a administrator. If you don't run it as administrator, you'll get an error like: "The requested operation requires elevation (Run as administrator)."
First remove the current certificate-socket binding using this command
netsh http delete sslcert ipport=10.100.0.12:443
You should get:
SSL Certificate successfully deleted
Then use this command (found here) to add the new certificate-socket binding with the appid and the certhash (without spaces) that you found earlier using this command
netsh http add sslcert ipport=10.100.0.12:443 certhash=1234567890123456789012345678901234567890 appid={12345678-1234-1234-1234-123456789012}
You should get:
SSL Certificate successfully added
DONE. You just replaced the certificate of all websites that are binded to this IP + port (socket).


Find the total number of sections

Question: A cube is sectioned by $33$ of planes parallel with faces of cube in many  parallelipipeds. If the number of parallelipipeds with faces that coincide with the faces of cubes is half of the total number.  Find the total number.
My idea: Let $a, b, c $  the number of the three types of planes.
Then there are $(a+1)(b+1)(c+1) $ parallelipipeds.
Also, there are $(a-1)(b-1)(c-1) $ parallelipipeds that hasn't the same faces as cube.
So
$(a+1)(b+1)(c+1)=2 (a-1)(b-1)(c-1) $
Now I am stuck.
Answer: If you set $x=a-1$, $y=b-1$, $z=c-1$, your equation can be rewritten as
$$
(x+2)(y+2)(z+2)=2xyz
$$
and substituting here $z=30-x-y$ we get
$$
128+60(x+y)-2(x^2+y^2)-32xy+(x+y)xy=0.
$$
Make now the change of variables: $u=xy$, $v=x+y$: the above equation becomes
$$
128-28u+60v+uv-2v^2=0,
$$
which can be solved for $u$ to give
$$
u=2{64+30v-v^2\over28-v}.
$$
It is now tedious but straightforward to check all the possible integer solutions, for $0\le v\le27$, which in turn give integer values of $x$, $y$, $z$. It turns out that there are two possible solutions for $(x,y,z)$:
$$
(4,12,14),\quad\hbox{or}\quad(5,7,18).
$$

Find the total number of sections


How much must be taken from each slice of a pie cut into 3rds to be able to share equally between 4 people

Question: Theoretically, if $3$ people were to split a pie evenly amongst themselves, only to have a $4$th person join them, how much or what fraction of each of their $\frac{1}{3}$ slices must be taken and given to the $4$th person, so that everyone has an equal amount of pie. I know it's possible to split each $\frac{1}{3}$ slice into quarters and divide the $12$ resulting slices evenly, but I don't want that answer. I'm wondering what fraction would be needed from each $\frac{1}{3}$ slice, ie, what fraction of $\frac{1}{3}$?
Answer: 3 people each would have 4/12 of the pie while 4 people would each have 3/12 of the pie.  3/12 is 3/4 of 4/12, and that's the amount each of the original three people gets to keep, which means each of the original three people must give the fourth person 1/12 of the pie.  1/12 is 1/4 of 4/12, so each of the original three people must give away 1/4 of their original share of the pie to the new person.
Comment: Thanks! Makes sense now


Erro ao integrar Spring 4 + Hibernate 5 + JPA 2 e Glassfish

Question: Não estou conseguindo iniciar a transação do Spring, é alguma configuração que fiz errado quem poder me ajudar. segue os códigos:

java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()
 at org.hibernate.internal.AbstractSharedSessionContract.getTransaction(AbstractSharedSessionContract.java:382)
 at org.hibernate.internal.AbstractSessionImpl.getTransaction(AbstractSessionImpl.java:23)
 at org.springframework.orm.jpa.DefaultJpaDialect.beginTransaction(DefaultJpaDialect.java:67)
 at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
 at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
 at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
 at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
 at com.sun.proxy.$Proxy221.list(Unknown Source)
 at com.boraji.tutorial.spring.controller.BookController.list(BookController.java:41)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:497)
 at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
 at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
 at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
 at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
 at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
 at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
 at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
 at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
 at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
 at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
 at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
 at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
 at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
 at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
 at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
 at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
 at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
 at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
 at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
 at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
 at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
 at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
 at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
 at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
 at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
 at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
 at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
 at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
 at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
 at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
 at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
 at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
 at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
 at java.lang.Thread.run(Thread.java:745)

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
 xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
 <persistence-unit name="LOCAL_PERSISTENCE"  transaction-type="JTA">
  <description> Spring Hibernate JPA Configuration Example</description>
  <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
  <jta-data-source>jdbc/_scdweb</jta-data-source>
  <class>com.boraji.tutorial.spring.model.Book</class>
  <properties>
      <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
   <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
   <property name="hibernate.show_sql" value="true" />
   <property name="hibernate.hbm2ddl.auto" value="update" />
  </properties>

 </persistence-unit>
</persistence>

AppConfig.java

package com.boraji.tutorial.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.boraji.tutorial.spring.dao"),
      @ComponentScan("com.boraji.tutorial.spring.service") })
public class AppConfig {

   @Bean
   public LocalEntityManagerFactoryBean geEntityManagerFactoryBean() {
      LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
      factoryBean.setPersistenceUnitName("LOCAL_PERSISTENCE");
      return factoryBean;
   }

   @Bean
   public PlatformTransactionManager transactionManager(){
      JpaTransactionManager transactionManager
        = new JpaTransactionManager();
      transactionManager.setEntityManagerFactory(
              geEntityManagerFactoryBean().getObject() );
      return transactionManager;
   }
}

WebConfig.java

package com.boraji.tutorial.spring.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.boraji.tutorial.spring.controller" })
public class WebConfig extends WebMvcConfigurerAdapter {

}

MyWebAppInitializer.java

package com.boraji.tutorial.spring.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

   @Override
   protected Class<?>[] getRootConfigClasses() {
      return new Class[] { AppConfig.class };
   }

   @Override
   protected Class<?>[] getServletConfigClasses() {
      return new Class[] { WebConfig.class };
   }

   @Override
   protected String[] getServletMappings() {
      return new String[] { "/" };
   }
}
Answer: vamos ver se posso lhe ajudar.

substitua o persistence.xml por um arquivo de configuração.
crie o repositorio como interface expandindo JpaRepository

@Repository
public interface Cervejas extends JpaRepository<ClasseJpa, TipoChaveId>{
}

Na Classe de Serviço anote o método com @Transactional do org.springframework.transaction.annotation.Transactional
Caso seja do seu interesse tem no meu github um projeto que fiz no curso da algaworks com esses conceitos.
https://github.com/marcelosartor/curso-spring-mvc-expert

Alias, não sei o seu nivel de conhecimento em spring mas esse curso da algawoks é muito bom, recomendo.


How to hide comments below the node, but not close them?

Question: Аctually I want to list comments for nodes myself (by Views, for example), so I need to hide standard comments list from core comment module.
I can do it like that:
  unset($node['comments']['comments']);

But it will not prevent DB query for comments.
So I found some crazy ways to trick the comments module. For example, to set fake $node->preview property, or to create new view mode and overwrite standard node/%node callback.
Is it really so difficult to hide comments below the node but still allow to add new comment, or I missed something?
Update about "Hidden" option
What about "Hidden" value for the content type:
I need close/open behaviour for my comments. But if I set "Hidden" for my content type, my new content pieces are set to "Comments closed" instead of hidden (here is the code).
Another problem is that user with permission to "post comments" can't add a comment, if comments are hidden (here is the code).
So I can't get the idea.
Answer
Solution found with hook_module_implements_alter(). Thanks a lot!
Comment: its easy... edit the content type, under comment settings select "Hidden". this will hide your comments
Comment: @subhojit777 OP want to prevent DB query i think.
Answer: In modules/comment/comment.module we can see that hook_node_view() (comment_node_view()) is running on line 614. This is where the functions are firing to load all comments and attach them to the node. The first 2 sets of if () { ... } appear to be handling the add comment form and action link. Then the final block of code is finally adding the comments, which I believe is what you're actually most concerned about hiding, and I assume you want this skipped for performance reasons:
// Only append comments when we are building a node on its own node detail
// page. We compare $node and $page_node to ensure that comments are not
// appended to other nodes shown on the page, for example a node_reference
// displayed in 'full' view mode within another node.
if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
  $node->content['comments'] = comment_node_page_additions($node);
}

I think this code is silly, because comment module should not be dependent on any particular hardcoded view mode. Hopefully this will change and become a setting in the UI.
Regardless, I've found a similar post that might interest you: Is there a way to stop comment_node_view from firing?
Basically you're wanting to use hook_module_implements_alter() to stop the comment module from being able to fire off hook_node_view(). Here is what you need to add to your custom module:
function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_view') {
    unset($implementations['comment']);
  }
}

Comment: Thank you very much! Especially for `hook_module_implements_alter`!
Answer: Just try to use hide() in your template file, or hook_preprocess_node():
hide($content['comments']);

Comment: http://drupal.stackexchange.com/questions/28428/how-to-hide-comments-below-the-node-but-not-close-them/51061#comment27749_28428


Play framework 2.2: How to get current controller and action in java

Question: In my application authentication scheme is based on user and role. users with particular role have access to particular action method.
To implement this I have done following
1.Write custom action
public class Authorization extends play.mvc.Action.Simple {
    public Promise<Result> call(Context ctx) throws Throwable {
        //check access
        return delegate.call(ctx);
    }
}

2.Annotate controller with action
@With(actions.Authorization.class)
public class Upload extends Controller {
    ....
}

In my action I have access to user which is in session. I want to get current controller and action so that I can authenticate user. Is there any way to this?
I have read about creating custom annotation with params and in each controller pass parameters to identify the action. But it seems to much work and error prone if by mistake i write wrong action name while copy paste.
Thanks
Comment: Are you looking for a reference to a controller object or just an identifier (i.e. String) of which controller underlies the action?
Comment: Both will work. I was looking for controller and method, String and object both are ok.
Comment: Then are you going to have a big `if...else` structure in your `Authorization` class ? You really should define at controller or method level the role(s) required to execute the method and check it in your `Authorization` class. It will be really less error prone.
Comment: Thanks it was indeed error prone. So I have created custom annotation for each type of access an put it in each controller method.
Answer: You can use context.request().path() to get a string with the path used. This will not include any query parameters, so if you want them you can use getQueryParameter or uri (full url) methods of the same object.
If you need more information than this you can use context.args. This will give you a map with the following keys (in Play 2.2 atleast):
ROUTE_VERB          -> The HTTP verb used (ex: GET)
ROUTE_ACTION_METHOD -> The method called (ex: getUserFavorites)
ROUTE_CONTROLLER    -> Controller class (ex: controllers.api.UsersController)
ROUTE_COMMENTS      -> ???
ROUTE_PATTERN       -> THE URL used (ex: users/favorites)

Comment: Thanks! ROUTE_CONTROLLER and ROUTE_ACTION_METHOD gave the desired result.


Windows 7 EXE filename starts with "Patch", won't run

Question:
Possible Duplicate:
How to prevent Vista from requiring elevation on patch.exe?

One of my programs is called "PatchCompiler.exe". It runs in the console. Or rather, it doesn't run, because Windows 7 treats an EXE file differently if it has "Patch" anywhere in its name, requiring elevated permission ("Do you want to allow the following program from an unknown publisher to make changes to this computer?"). Even if I grant this permission, it runs in an ephemeral console that disappears before I can see its output.
Yes, I know I could fix this problem by renaming my program. But it compiles patches...
Does anybody know how to change this annoying behaviour?
Edited to add: Just to make myself clear: I don't want my program to run with elevated status! Who knows what bugs I left in it?
Comment: I was having a similar problem with a program called "DynamicDispatchTest.exe". Not that big a deal since it's obviously (from the name) just a quick program I created to test something, but I never would have guessed that the filename of all things was the culprit!
Answer: Attach an application manifest that includes
<requestedExecutionLevel level="asInvoker" uiAccess="true"/>

Comment: How do I do that with g++ under MinGW?
Comment: @TonyK See http://www.transmissionzero.co.uk/computing/win32-apps-with-mingw/ for a detailed explanation.
Comment: That worked (after a little massaging). Thank you! I have put the details into a new answer. (I would accept your answer, but I originally posted this on superuser.com as another `TonyK`...)
Comment: contact a mod, and get them to merge the users.
Comment: @TonyK: Sorry, I can't merge an account that doesn't exist.  You have to log into SU and SO with the same credentials for the migration of a question to retain your identity.
Answer: OK, I got it working, thanks to phihag's answer. It didn't work straight from the box, so here's what I did:

Create a file Manifest.xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel level="asInvoker" uiAccess="false"/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>

Create a resource file, Manifest.rc:
#include "winuser.h"
CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST Manifest.xml

Compile the resource file to create Manifest.res:
windres --input Manifest.rc --output Manifest.res --output-format=coff

Add Manifest.res to the link:
g++ -Wall -oPatchCompiler PatchCompiler.cpp Manifest.res

And that's it!
Answer: As far as I know, that's a feature, not a bug. The idea is to make sure that you really really want to run a patch on your computer.
Also, as far as I know, there isn't a nice way to solve the problem. You could disable the UAC or rename the program.
As far as the console is concerned, that's a programming question and there's not enough information to help you. You should simply add a check which will wait until you do something before closing the program. A typical example of that is reading a character from terminal at the end.
You could start an elevated command prompt which shouldn't bring the UAC warning when starting the program and should stay on after the program is completed.
Comment: Feature or Bug ... Trust Windows to base a file's contents on the NAME, giving rise to the FUN.JPG.EXE viruses... Magic Numbers for the win!  This weird thing with Windows means that I can take a GOOD program and make it seem evil by simply renaming it... and conversely, make an evil patcher program good in the same manner.   Good Job MicroSoft.  You'd think it would be better to determine privileges based on what a program DOES... if it opens an .exe/.dll for read/write versus exec... THAT'S a problem needing elevated privs.
Comment: It's a bug; the name of a file has nothing to do with what the file *is*.
Comment: @David X It's a feature according to [this](http://social.msdn.microsoft.com/Forums/en-US/windowsgeneraldevelopmentissues/thread/bf4f7dfa-5553-41d3-9c8e-311ee4a88599/). I won't comment on how smart it is. Also there's [this](http://technet.microsoft.com/en-us/library/cc709628%28WS.10%29.aspx) under `Installer Detection Technology`
Comment: An operating system that bases its behaviour on whether the character sequence "patch" occurs in the name of an executable file? Really, only morons could have designed that. It's such a stupid feature that it's a bug.
Comment: **It's a feature whose existence is a bug.** All happy? ;)
A proper implementation of a design based on an idea that is massively flawed in that it fails to offer actual protection. AND violates the requirement of not being too inconvenient in legitimate uses.


split one fields into multi columns based value in other field

Question: My data is stored in mysql.
My Table data is as follows
3   credit  500.00
3   debit   500.00
4   credit  300.00
4   debit   300.00
5   credit  300.00
5   debit   300.00
6   credit  300.00
6   debit   300.00

I want to write a query to write data as
customer id, credit, debit,final_amount
where as final amount = credit-debit
Can someone please help me with query?
Comment: Go on. Try something.
Comment: Welcome to Stack Overflow! We are a community of volunteers offering aid to programmers stuck on a
particular task. We are not a service to write free code for you. Please read
[What topics can I ask about here?](http://stackoverflow.com/help/on-topic) and
[How do I ask a good question?](http://stackoverflow.com/help/how-to-ask)
Comment: I know that I have to use inner join. somehow not able to figure how.
Comment: Or just sit around while GL does everything for you, as usual.
Comment: @Strawberry Gordon needs those points.  Unless its actually an AI program created by Stack Overflow.
Comment: @Strawberry: LOL. Must be final exam time. Seen the same 5 or 6 questions (st least the task they're trying to do) fairly frequently lately.
Comment: :) LOL. last time i appeared for exam was 20 years ago.
Answer: You can use conditional aggregation:
select customerid,
       sum(case when type = 'credit' then amount else 0 end) as credit,
       sum(case when type = 'debit' then amount else 0 end) as debit,
       sum(case when type = 'credit' then amount
                when type = 'debit' then - amount
                else 0
           end) as credit
from t
group by customerid;


Django get all foreign key names of a model

Question: I need to get all foreign key names of a single model. For example if a model name is UserProfile and it has user, customer, and comment as foreign keys means by single code I want to get all foreign key names of the UserProfile model.
Comment: @Zeeker I tried [k.name for k in obj._meta._field_name_cache if 'foreign_related_fields' in dir(k)]
Comment: @Zeeker I tried this too [k.name for k in obj._meta._field_name_cache if k.__class__.__name__ == "ForeignKey"]
Answer: You can find relations like so: UserProfile._meta.get_all_related_objects()
You can iterate through fields on the model directly via UserProfile._meta.fields
You can determine the field type via field.get_internal_type()
for field in UserProfile._meta.fields:
    if field.get_internal_type() == 'ForeignKey':
        print 'found a foreign key'

Comment: `get_all_related_objects` has been deprecated and is no longer present starting with Django 1.10 https://docs.djangoproject.com/en/1.10/ref/models/meta/#migrating-from-the-old-api
Comment: You can store the fields with this 1 liner `fields = [field for field in YourModel._meta.fields if field.get_internal_type() == 'ForeignKey']`
Comment: @radtek nice one liner. One liners are not always the most communicative/easy to read, so I tend to avoid them. It's not wrong, but it's not right either.


How to selfhost .net core 3.1 web api

Question: Can any one suggest with example how to selfhost core web API without IIS. I have hosted in the IIS but i want to perfome self hosting and also i want to enable HTTPS for the selfhost web API
Comment: ASP.NET Core Web API project you create using VS (VS code or command) is self hosted. The code can run both on IIS and outside of IIS.
Answer:
To Self host web api you should refer to official documentation
To enable https

On an elevated console ("Run as administrator"), execute
netsh http add urlacl url=https://+:4443/ user=<your user name>
to allow the running user to listen on port 4443 using HTTPS (note the use of https instead of http in the above command).
Also on an elevated console, register the server certificate by running
netsh http add sslcert ipport=0.0.0.0:port certhash=thumbprint appid={
    app-guid
}

where,
port is the listening port (e.g. 4443); the special IP address 0.0.0.0 matches any IP address for the local machine;
thumbprint is the certificate's SHA-1 hash, represented in hexadecimal;
app-guid is any GUID (e.g. {00000000-0000-0000-0000-000000000000}) , used to identity the owning application.
Write self host configuration like
class MyHttpsSelfHostConfiguration : HttpSelfHostConfiguration
{
    public MyHttpsSelfHostConfiguration(string baseAddress): base(baseAddress){}
    public MyHttpsSelfHostConfiguration(Uri baseAddress) : base(baseAddress){}
    protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
    {
        httpBinding.Security.Mode = HttpBindingSecurityMode.Transport;
        return base.OnConfigureBinding(httpBinding);
    }
}

then Change the base address passed to the MyHttpsSelfHostConfiguration constructor: var config = new MyHttpsSelfHostConfiguration("https://localhost:4443");
Comment: I think this is for .net frame work , can i use the same for .net core web APi also ?

How to selfhost .net core 3.1 web api


Alternatives to least-Chi-square to fit a straight line,

Question: as stated in the title I am looking for alternative ways to fit my data to a straight line. My current approach is a least Chi-Square Fitting, but the predicted relative errors for the slope exceed 100%.
In my view there are to reasons for that:
a) I only have five data points to fit.
b) These five data points have very large errors (relative error is about 20%).
To clarify the issue I attached the data at the end of this post.
Do you know of other methods to fit data by a linear function, which are better suited to this ill-posed problem?
Since this is my first post here and especially my first post regarding science ever, I hope that I stated my question correctly. Thank you in advance!
Data (x, y, error of y)
$0.025 \qquad 0.66 \qquad 0.14$
$0.099 \qquad 0.72 \qquad 0.14$
$0.220  \qquad 0.78 \qquad 0.14$
$0.390 \qquad 0.75 \qquad 0.14$
$0.620 \qquad 0.83 \qquad 0.14$
Comment: Hi Christian, welcome to the site. By "leas-Chi-square fit" do you possibly mean [least squares](http://en.wikipedia.org/wiki/Least_squares), which is a normal linear regression? An what do you mean by saying that "the predicted relative errors for the slope exceed 100%"? A bit more information what x and y is would be helpful.
Comment: @COOLSerdash The OP may mean fitting by *minimum chi-square*; usually it's used with Poisson or binomial sampling situations but also applies if you know the variance of the observations and assume normality, when it's equivalent to WLS (except all your t's are Z's and all your F's are chi-square).
Comment: As stated by Glen_b I meant "least squares" with least-Chi-square-fit.
Comment: The variable x corresponds to a momentum squared and the y is an observable. The functional dependence is:  $y(x)=b + m*x$  and I am interested in the slope $m$ of this function.
Comment: @COOLSerdash Exceeding 100% means that the error for the slope computed by these least squares fit is much larger than the slope $m$: $m=.23$ and the error $\delta m=.29$
Comment: @Glen_b thanks for clarifying. I was unaware of this method. Thanks.
Answer: It's not clear to me exactly what you want, but if we plot these points (e.g. in R)
x <- c(0.025, 0.099, 0.22, 0.39, 0.62)
y <- c(0.66, 0.72, 0.78, 0.75, 0.83)

plot(x,y,type = 'p')

we can add a least squares fit line
abline(lsfit(x,y))

which (as least square lines often do) looks pretty good, intuitively.
Comment: I agree, but as should be clear this is a small dataset. Note that quantile regression (L_1 norm) yields a loosely similar but not identical line.
Comment: Sorry, that I did not clealy state my point. I would like to extract the slope of the fitted function $y(x)=b+mx$.  Doing this for the given data set with the least squares method I obtain something like: $m=0.23$ with an error of $\delta m=0.29$. My problem is that the error is larger than the result. Is there another method to fit a straight line, which maybe gives smaller errors?
Comment: @PeterFlom Sorry, I realized too late that I should mention you. Please see the post above.
Comment: Hi @NickCox yes, and other norms would probably be similar lines too, as would smoothing methods. But the questioner seems to think (although it's hard to tell) that the least squares line isn't very good here, so I just wanted to show that it is.
Comment: I agree completely.


how can I read old varnish logs?

Question: In /var/log/varnish/ I have some old varnish logs, produced by varnishlog which, due to logrotated, are now in gz format:
-rw-r--r--  1 varnishlog varnish 143068514 Aug 10 23:59 varnish.log.2017-08-10.gz
-rw-r--r--  1 varnishlog varnish 156373518 Aug 11 23:59 varnish.log.2017-08-11.gz
-rw-r--r--  1 varnishlog varnish 134255825 Aug 12 23:59 varnish.log.2017-08-12.gz
-rw-r--r--  1 varnishlog varnish 156992529 Aug 13 23:59 varnish.log.2017-08-13.gz
-rw-r--r--  1 varnishlog varnish 176751837 Aug 14 23:59 varnish.log.2017-08-14.gz
-rw-r--r--  1 varnishlog varnish 155948012 Aug 16 00:01 varnish.log.2017-08-15.gz
-rw-r--r--  1 varnishlog varnish 169977134 Aug 17 00:01 varnish.log.2017-08-16.gz

I've extracted those in another location and tried to view them via head/more but they look binary.
So I then tried opening them with varnishlog using either of the following parameters:
[-N filename]             VSM filename
[-r filename]             Binary file input

But that didn't work giving me:
Can't open log - retrying for 5 seconds

and:
Can't open log file (Not a VSL file:

Any idea on how can I inspect those historical logs from varnish?
p.s I use varnish-4.1.1
Comment: Are these log files produced with varnishncsa? http://go2linux.garron.me/linux/2011/05/configure-varnish-logs-varnishnsca-logrotate-and-awstats-1014/
Comment: @bgtvfr: No. `varnishncsa` produces ncsa log format https://en.wikipedia.org/wiki/Common_Log_Format which is human readable, and by looking at `ps -axu` I see that it's `varnishlog` that produces those logs in my question.
Answer: The error you see is due to lack of privileges. Try:
sudo varnishlog -N <file.vsm> -d

Comment: Whether I do it via `sudo` or as being `root` the result is: `Can't open log - retrying for 5 seconds`. Maybe it's not in the expected format.
Comment: What happen if you try to read the varnishlog file currently being written?  I mean something like: `sudo varnishlog -N /var/lib/varnish/hostname/_.vsm -d`
Comment: Yes, that works, but that file doesn't seem to relate to those large daily archived varnishlog generated files I have in `/var/log/varnish`.
Answer: The correct way was indeed using -r but my files were corrupted due to an improper way of rotating them in a customized /etc/logrotate.d/varnish. Reverting to the default rotate method worked.
Answer: You can read the log by unzipping it with
gunzip -c <filename.log.gz>

Then you can read it with
varnishlog -r  <filename.log>

how can I read old varnish logs?


Bott and Tu page 19 - Exercise 1.7

Question: Bott and Tu page 19 - Exercise 1.7
Compute $H^*_{DR}(\Bbb R^2 - P-Q)$ where $P$ and $Q$ are two points in $\Bbb R^2$. Find the closed forms that represent the cohomology classes.

So first of all, we write that we have:
$$0\longleftarrow\Omega^2(\Bbb R^2-P-Q)\longleftarrow\Omega^1(\Bbb R^2-P-Q)\longleftarrow\Omega^0(\Bbb R^2-P-Q)\longleftarrow0$$
So we consider the closed $0$-forms, and they are given by $d(f(x,y))=0=\frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy$
So $\frac{\partial f}{\partial x}=0=\frac{\partial f}{\partial y}$ so that $f$ is constant. So $H^0(\Bbb R^2-P-Q)=\Bbb R$.
Now we want to find closed $1$-forms, and thus $$d(f(x,y) dx+ g(x,y)dy)=0=\frac{\partial f}{\partial y} dydx+ \frac{\partial g}{\partial x}dxdy=(\frac{\partial g}{\partial x} - \frac{\partial f}{\partial y})dxdy=0$$
So we find that:
$$\frac{\partial f}{\partial y} = \frac{\partial g}{\partial x},$$
Then I want to quotient by all exact $1$-forms, which are those $1$-forms that are equal to $df$ for some $f\in \Omega^0(\Bbb R^2-P-Q)$ and hence are of the form $\frac{\partial f}{\partial x} dx+ \frac{\partial f}{\partial y} dy\ne 0$, so these partials cannot be simultaneously zero.
How do I then find $H^1(\Bbb R^2-P-Q)$?
Answer: This question has been posted for long but I post my solution here since I'm currently reading Bott&Tu and dealing with the same exercise.
Note that moving $P$ and $Q$ around is an diffeomorphism, we may assume that $P=(0,0)$ and $Q=(2,0)$.
Let $\gamma_1$ be the unit circle and $\gamma_2$ be the unit circle centered at $Q=(2,0)$ and we claim that the linear map $H_{DR}^1(\mathbb{R}^2-P-Q)\to \mathbb{R}^2:[\omega]\mapsto (\int_{\gamma_1}\omega ,\int_{\gamma_2}\omega ) $ is an isomorphism. This map is well-defined, vanishing on exact forms by stoke's theorem as loops do not have boundary. Also there clearly exist forms such that $\int_{\gamma_1}\omega\neq \int_{\gamma_2}\omega$, so by a reflection along $x=1$ we see the surjectivity of the linear map. If we uses the argument principle in complex analysis then we can find easily that the closed form that represents $(1,0)\in \mathbb{R}^2$ is $\frac{1}{2\pi} \frac{xdy-ydx}{x^2+y^2}$ and its translation from $(0,0)$ to $(2,0)$ represents $(0,1)\in \mathbb{R}^2$.
For injectivity, given a closed $1$-form $\omega$ such that $\int_{\gamma_1}\omega =\int_{\gamma_2}\omega =0$, we note firstly that the integration of $\omega$ on any loop $\ell$ must be zero by Stoke's theorem. By Jordan curve theorem a loop must encircle a bounded region in $\mathbb{R}^2$. If the loop does not encircle either $P$ or $Q$, then seeing the loop along with the region it encircles as a submanifold $N$ of $\mathbb{R}^2-P-Q$ and we apply Stokes' theorem, getting $0=\int_N d\omega= \int_\ell \omega$. A same argument shows for any circle $C$ centered at $P$ we have $\int_C\omega=0$ on considering $N$ to be the region between $C$ and $\gamma_1$ along with $C$ and $\gamma_1$; the same result holds for $Q$. So for any loop that encircles $P$ or $Q$ (or both of them) we take sufficiently small circles around $P$ or $Q$ and apply Stoke's theorem with $N$ being the region between the circles and the loop along with the circles and the loop. Now we can define a smooth function $f$ on $\mathbb{R}^2-P-Q$ by integrate $\omega$ along a path $\gamma_x\subset \mathbb{R}^2-P-Q$ from a base-point $x_0$ to another point $x$. This $f$ is well-defined, being independent of the choice of the path $\gamma_x$ by the above result on loops. Apply the mean-value property of integration and we see that $df=\omega$ as desired.
Answer: If $P=(0,0)$ consider
the 1-form $$\frac{y\,dx-x\,dy}{x^2+y^2}.$$
This represents a generator of $H^1(\Bbb R^2-(0,0))$. It's also
nontrivial in $H^1(\Bbb R^2-(0,0)-Q)$. But you need to also find
a corresponding 1-form "centred" at $Q$.

Bott and Tu page 19 - Exercise 1.7


How to install mod_fastcgi.so into apache

Question: How do I get the mod_fastcgi.so module and load it into apache2? I need it for a deployment of trac. Thanks!
Answer: <code>yum whatprovides mod_fastcgi.so # will tell you what package contains mod_fastcgi.so
yum install the_package
</code>
Comment: apt-cache search fastcgi
Comment: Actually I'm using Ubuntu 10.4, I probably should I have mentioned that.
Comment: thanks. I think I found it. I'm going to install the 'libapache2-mod-fcgid' package.


Proving the density theorem without assuming that $x>0$.

Question: I want to prove this theorem:

"If $x$ and $y$ are real numbers with $x < y$, then there exists an irrational number $z$ such that $x < z <y$."

I have to do the proof without assuming $x > 0$. My question is, if $x < 0$ can I just take $-x$ and apply the same proof as the book?
The proof in the book is something like this:
It is no loss of generality to assume that $x > 0$. Since $y - x > 0$, it follows from Corollary 2.4.5 that there exists $n \in \mathbb{N}$ such that $1/n < y - x$. Therefore, we have $nx + 1 < ny$. If we apply Corollary 2.4.6 to $nx > 0$, we obtain $m \in \mathbb{N}$ with $m - 1 ≤ nx < m$. Therefore, $m ≤ nx + 1 < ny$, whence $nx < m < ny$. Thus, the rational number $r := m/n$ satisfies $x < r < y$.
Comment: The statement you've written asks for an *ir*rational number! Is this a typo?
Answer: Yes. The application of Corollary $2.4.6$ is the only place where this sign of $x$ is directly exploited. Following the same argument:
Suppose $x<y$ and $x<0$. Then $y-x >0$ is still true. So by Corollary $2.4.5$ there exists $n \in \mathbb{N}$ with $\frac{1}{n} < y-x$ or equivalently $nx+1<ny$. Now applying Corollary $2.4.6$ to $-nx > 0$ gives us the existence of $m \in \mathbb{N}$ such that $m-1 \le -nx < m$. This directly implies that $-m \le nx < -m+1$. Also observe from this inequality that $-m+1 \le nx+1 < ny$.  All in all have that $nx < -m+1  <ny$. So $r:= \frac{-m+1}{n}$ is the rational number you are looking for.


Fechar um modal BOOSTRAP e abrir outra em seguida?

Question: 1: Gostaria que, na minha modal de cadastro, ao clicar no link "Já possui conta? FAÇA LOGIN" a modal de cadastro se fechasse e abrisse a de login, já que o bootstrap não permite 2 modals abertas. Há algum comando pra fazer isso ? (img)

2: Ao clicar no botao "logar", há uma pesquisa no banco e, caso haja o usuario, aparece a div de configuração (dados, endereço, etc), porem a div de login continua aberta, o que fazer? (img2)
Comment: Eu usei a função "$("#login").modal('hide')", porem a modal sumiu, mas a tela continuou escura e o body desativado, como mostra a imagem: https://i.imgur.com/R80iTlL.png
Comment: utilizei a função "$("#login").modal('hide');" seguida de "$('.modal-backdrop').css('display', 'none');" e funcionou, porem a animação é muito lenta,
Comment: Olha, não teria que fechar a primeira e abrir a segunda em sequencia?
Comment: Vc quer que se clicar em "Fazer Login" dentro do modal "Faça seu Cadastro"  esse modal se feche? Não deu para entender direito...
Comment: Edward é o que estou tentando fazer
Comment: Hugo na primeira imagem eu disse que quando clicar em "ja possui conta? Faça login" fechasse a modal cadastro e abrisse a modal Login.

Na segunda imagem eu disse que após eu clicar em "Entre", gostaria que a div em questao se fechasse, porem ela continua aberta.
Answer: Ao fechar a modal com $("#login").modal('hide'), use o callback do evento hidden.bs.modal para abrir a outra com $("#cadastro").modal('show');.

Atente-se de que o Bootstrap 3 só funciona com jQuery a partir da
  versão 1.9.1 e menor que 3.0.

Veja um exemplo:

$("#fazer_cadastro").on("click", function(e){
   e.preventDefault();
   $("#login").modal('hide').on('hidden.bs.modal', function(){
      $("#cadastro").modal('show');
   })
});

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

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#login">Login</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Login

        Fazer cadastro

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Cadastro

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Comment: Sam, primeiramente obrigado pela ajuda. Eu criei um html novo, um JS novo, so pra testar o seu código, e não funcionou, porém no seu exemplo está funcionando perfeitamente. Note: eu copiei exatamente o seu código, e a unica mudança foi inserir o meu javascript. Voce sabe qual pode ser o problema?