Spring boot - Embedded Tomcat - Connector Customizer - fail to add parseBodyMethods attributes

Question: The original problem is when I sent a http request with method 'DELETE', the body part couldn't be sent to the server.
After googling, I found this article that suggests modifying the server.xml file and adding 'parseBodyMethods' to the Connector part can solve the problem:
<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           parseBodyMethods="POST,PUT,DELETE"
           redirectPort="8443" />

However, because I'm using spring's embedded tomcat, I have to find a way to do the same in spring's way. So, I found this article that seems to allow me to add ConnectorCustomizer and add additional attribute to the Connector. The following is my code:
    public class MyTomcatConnectorCustomizer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer factory) {
        if(factory instanceof TomcatEmbeddedServletContainerFactory) {
            customizeTomcat((TomcatEmbeddedServletContainerFactory) factory);
        }
    }

    public void customizeTomcat(TomcatEmbeddedServletContainerFactory factory) {
        TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) factory;
        tomcat.addConnectorCustomizers(connector -> {
            connector.setAttribute("parseBodyMethods", "POST,PUT,DELETE");
        });
    }

}

@Bean
MyTomcatConnectorCustomizer myTomcatConnectorCustomizer() {
    MyTomcatConnectorCustomizer myTomcatConnectorCustomizer = new MyTomcatConnectorCustomizer();
    return myTomcatConnectorCustomizer;
}

But still, the same issue exists. the body is still empty when I send a 'DELETE' request to the server. Does anyone have encountered the same issue before? Help appreciated!
Answer: change
connector.setAttribute("parseBodyMethods", "POST,PUT,DELETE");

to
connector.setParseBodyMethods("POST,PUT,DELETE")

or just
@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
    return new TomcatEmbeddedServletContainerFactory(){
        @Override
        protected void customizeConnector(Connector connector) {
            super.customizeConnector(connector);
            connector.setParseBodyMethods("POST,PUT,DELETE");
        }
    };
}

Answer: Yes, I know this is a bit old question but I stumbled upon this issue and found that SO don't have a solution for Spring Boot version 2.0.0 and later.
I had found this article on Baeldung which describes the changes in SB 2 versus SB 1.
Quoting the article (code emphasis is mine):

In Spring Boot 2, the EmbeddedServletContainerCustomizer interface is replaced by WebServerFactoryCustomizer, while the ConfigurableEmbeddedServletContainer class is replaced with ConfigurableServletWebServerFactory.

So to fix your issue you need to implement interface WebServerFactoryCustomizer from package org.springframework.boot.web.server and parametrize it with TomcatServletWebServerFactory and override it's customize method.
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

@Component
public class MyTomcatConnectorCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

  @Override
  public void customize(TomcatServletWebServerFactory factory) {
    TomcatConnectorCustomizer parseBodyMethodCustomizer = connector -> {
      connector.setParseBodyMethods("POST,PUT,DELETE");
    };
    factory.addConnectorCustomizers(parseBodyMethodCustomizer);
  }
}


Função empty retorna true (verdade) quando valor é 0

Question: Olá, estou usando o código abaixo para gravar o status ($status_prod) do botão (Habilitado? Sim ou Não), e gravar também o endereço ($link_prod) de destino do botão quando habilitado. Mas ele só esta gravando a opção SIM, e não estou conseguindo descobrir como fazer com que ele grave a opção NÃO quando selecionada.
Reparei que quando insiro esta linha }else if(isset($_POST['status_prod'])){, eu consigo gravar o opção NÃO.
E quando troco para esta linha if(!empty($status_prod)) {, gravo a opção SIM.
Estou postando os endereços para que os amigos possam verificar o problema que esta ocorrendo.
Endereço do painel onde trocasse o status do botão: http://www.simuleseusite.com/admin/
Acesso com (Login - usuario) e (Senha - 123)
Entre em (menu/habilitar botão) Faça o teste trocando de Sim Para Não, e tente destroca-lo, e verá que não esta gravando a opção Sim.
Endereço do Resultado da Habilitação do botão ou não: http://www.simuleseusite.com/
Segue  código usado abaixo:
<?php
//pega o valor do botao
        if(isset($_POST['status_prod'])){ // só entra aqui, se gale_status tiver sido postado
                $link_prod = null;
                $status_prod = 'Não';

// se a pessoa marcar a opção sim:
        if($_POST['status_prod'] == "1") {
                $link_prod = '
'.$bot_prod.'

';
                $status_prod = 'Sim';

        //}else if(isset($_POST['status_prod'])){ // Com essa linha funciona a opção NÃO
        if(!empty($status_prod)) {              // Com essa linha funciona a opção SIM

// Se existir sessão, eu crio aqui
        $_SESSION['hab_prod']['status_prod']=$status_prod;
        $_SESSION['hab_prod']['link_prod']=$link_prod;

        //header("location:menu_halitar_link.php");

        echo "<meta http-equiv='refresh' content='0; URL= menu_halitar_link.php'>
        ";
        }}} // Retirar uma Chave se for usar a opção NÃO
?>
        <form method="post">
            Habilitar o Link <?php echo $bot_prod ?>?

            <input type='radio' name='status_prod' value='1' checked="checked"/>Sim
            <input type='radio' name='status_prod' value='0'>Não
            <input type="submit" value="Atualizar">
        </form>

Se os amigos puderem me dar uma ajuda para descobrir onde estou errando ficarei muito agradecido.
Brigadão à todos, e grande abraço.
Answer: Estive a fazer uns testes e a tomar isto em consideração:
Cheguei à conlusão que o valor inteiro 0 e a string "0" são considerados vazios para o método empty(), retorna true. Neste exemplo em baixo caso escolha "não" (value="0") não vai entrar na primeira condição, enquanto que se escolher o "sim" (value="1") entra nas duas
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(!empty($_POST['status_prod'])) {
        echo 'Não está vazio: ' .$_POST['status_prod'];
    }
    if(isset($_POST['status_prod'])) {
        echo 'Existe: ' .$_POST['status_prod'];
    }
}
?>
<form method="post">
    Habilitar o Link

    <input type='radio' name='status_prod' value='1' checked="checked"/>Sim
    <input type='radio' name='status_prod' value='0'>Não
    <input type="submit" value="Atualizar">
</form>

Podemos conferir isto se:
var_dump(empty(0)); // bool(true)
var_dump(empty("0")); // bool(true)
var_dump(empty(1)); // bool(false)
...

Pelo HTML algum valor do botão radio vai ser sempre enviado, pois sim vai começar sempre checked, você pode contornar isto da seguinte maneira:
if(isset($_POST['status_prod']) && $_POST['status_prod'] == 0) {
    // input "Não", $_POST['status_prod'] = 0
}
else {
    // input é sim
    $_POST['status_prod'] = 1; // inserir esta linha por segurança
}

PS: Em príncipio vai ser sempre enviado um dos valores, pois o seu "Sim" começa com checked, mas temos SEMPRE fazer as verificações do lado servidor
Answer: Com a ajuda do amigo Miguel que me deu uma luz para que conseguisse chegar ao meu objetivo, que é poder gravar o Status do botão e habilita-lo de acordo com a seleção SIM ou NÃO.
Acesse os endereços mencionados acima para efetuar o teste e verificar o resultado.
Abaixo código funcionando perfeito.
<?php
if(isset($_POST['status_prod'])) {

if(isset($_POST['status_prod']) && ($_POST['status_prod']) == 0) { // Desabilita o Botão.
    $link_prod = null;
    $status_prod = 'Não';
}else{
    $_POST['status_prod'] == 1; // Habilita o Botão com o Link de destino.
        $link_prod = '
'.$bot_prod.'

';
        $status_prod = 'Sim';
        }
        $_SESSION['hab_prod']['status_prod'] = $status_prod;
        $_SESSION['hab_prod']['link_prod'] = $link_prod;

        echo "<meta http-equiv='refresh' content='0; URL= menu_halitar_link.php'>
        ";
        }
?>
        <form method="post">
            Habilitar o Link <?php echo $bot_prod ?>?

            <input type='radio' name='status_prod' value='1' checked="checked"/>Sim
            <input type='radio' name='status_prod' value='0'/>Não
            <input type="submit" value="Atualizar">
        </form>

Agradeço a atenção de todos os amigos ao meu problema, que com o auxilio do amigo Miguel foi solucionado.
Abraços à todos.
Comment: Ainda bem que resolveu
Answer: O método empty que é um método nativo do PHP, retorna true sempre que um valor de uma variável for vazia, no entanto, é importante sabermos em que situações, no PHP esse método interpretará como vazio. São eles:

' ' ,uma string vazia
0 ,um inteiro zero
0.0 ,flutuante zero
null ,variável nula
array(), um array vazio
false, um booleano falso
$valor, uma variável que não possui ainda uma atribuição.

Em todos esses casos, o empty sempre retornará como true.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


How can I avoid the output of my module is cached?

Question: I have a module I wrote that prints dynamic data for JavaScript variables.
function javascript_api_page_attachments(array &$page) {
$page['#attached']['html_head'][] = [
        // The data.
    [
        '#type' => 'html_tag',
        // The HTML tag to add, in this case a  tag.
        '#tag' => 'script',
        // The value of the HTML tag, here we want to end up with alert("Hello world!");.
        '#value' => javascript_api_print_parameters(),

    ],
    // A key, to make it possible to recognize this HTML  element when altering.
    'hello-world'
];}

My problem is when Drupal caches the page.Need to stop caching my pages in drupal.
How can I avoid the output of my module is cached?
Comment: You have drupalSettings to pass variables.
Comment: Why are you adding JavaScript like this?
Comment: Because all the variables are created by the module.
Answer: As Eyal mentioned, you can pass the variables from your module to jQuery like this:
mymodule.module
function mymodule_page_attachments(array &$attachments) {
    $attachments['#attached']['library'][] = 'mymodule/auto';
    $attachments['#attached']['drupalSettings']['cool'] = 'hello world';
  }
}

mymodule.libraries.yml
auto:
  version: 1.0
  js:
    js/auto.js: {}
  dependencies:
      - core/jquery

auto.js
(function($, Drupal, drupalSettings) {

    $( document ).ready(function() {
      alert(drupalSettings.cool);
    });

})(jQuery, Drupal, drupalSettings);

This will show a js alert message saying "hello world".
Comment: Hi my problem is not in the way i am adding the js to the page .
my problem is this function: javascript_api_print_parameters()
collect all the module the implement the hook and create a dynamic parameters .
because drupal caching is enabled the first time you hit the page the parameters are sticky to this page .
Comment: @HanielBitton is this a custom page created by your module? or is this a content type node page?
Comment: its a regular node page.
Comment: @HanielBitton what data are you grabbing from the node page? or Exactly how does your dynamic data get created?
Answer: I suggest  you first create a Js file, put your Js function there then pass desire variable ( or object) to it with using drupalSettings and try to get variable(s)  in your js files. ( I guess you are know how attach js libraries to page if not take a took at Helper1 and Helper2
$page['#attached']['drupalSettings']['myvars'] = $myvars;

Then Drupal.drupalSettings.myvar will be exists (it's will be dynamic and not cached) in your Js file.
Answer: To disable the page cache for anonymous users try the first method:
// Deny any page caching on the current request.
\Drupal::service('page_cache_kill_switch')->trigger();

Else, you need to set max-age 0 in e.g. hook_node_view().
function yourmodule_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
  if ($node->getType() == 'yourtype' && $view_mode == 'full') {
    $build['#cache']['max-age'] = 0;
  }
}

OR, if you like to remove cache from route, provide no_cache in routing.yml of your module.
newsletter.signup:
  path: '/abc'
  defaults:
    _controller: '\Drupal\your_module\Controller\your_controller::render'
  requirements:
    _permission: 'access content'
  options:
    no_cache: TRUE

Answer: Thanks for the help i came up to create a new page with a controller and this page will be attached to the page .
<?php

namespace Drupal\javascript_api\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

/**
 * An example controller.
 */
class PageParamsController extends ControllerBase {
    public function build(){
        $result = javascript_api_print_parameters();
        return new Response($result , 200 , array('Content-Type'=> 'application/javascript'));
    }}

pageparams:
  # Block the page from being loaded until Modernizr is initialized.
  header: true
  version: "v1"
  js:
    /javascript_api/pageparms.js: { preprocess: 0, weight: -21, minified: true }

Now i have a dyanmic js that i can put on the page and to use my Variable in the global area.
Thanks All :)
Comment: I don't think that the hook_page_attachments method will be cached. And it is always better to go with the framework than against it.
Comment: It actually been cached tried that when added the JavaScript to the head section.


Best way to store configuration in MySQL

Question: I have a scenario where i need to store configurations in mysql table having three columns namely VendorID,ServiceID and ModeID . Configuration for a vendor can be done with three overriding cases as follows.

One column VendorID having non-NULL value with ServiceID ,ModeID having NULL value.

VendorID,ServiceID,ModeID -- >  1,NULL,NULL

Two columns VendorID,ServiceID having non-NULL values with ModeID having NULL value.

VendorID,ServiceID,ModeID -- >  1,1,NULL

All three columns having non NULL values.

VendorID,ServiceID,ModeID -- >  1,1,1
When case 1,2,3 are defined and in the MySQL query WHERE clause vendorid,servideid and modeid are passed, then case 3 overrides case 2 and case 1.
When case 3 is not defined and case 1,2 are defined and  in the MySQL query WHERE clause vendorid,servideid and modeid are passed, then case 2 overrides case 1.
When case 3 and case 2 are not defined and case 1 is defined and  in the MySQL query WHERE clause vendorid,servideid and modeid are passed, then case 1 is returned.
Now my question is, how can i query the table to get the configuration returned when vendorid,servideid and modeid are passed in the query in one go without having to query 3 times separately.
Any other good approach for the above problem is also welcome.
Comment: Are you using Oracle or MySQL?
Comment: I am using MySQL
Comment: You said it yourself in post already more or less by using the word case all the time but you can use CASE END flowcontrol in SQL.. If you want better help you could provide a [example](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query)
Answer: You may want this:
where (VendorID, ServiceID, ModelID) = ($VendorID, $ServiceID, $ModelID) or
      ( (VendorID, ServiceID) = ($VendorID, $ServiceID) and ModelId is null) or
      ( VendorID = $VendorID and ServiceID is null and ModelId is null)

Alternatively you may want:
select t.*
from t
where VendorId = $VendorId and
      (ServiceId = $ServiceId or ServiceId is null) and
      (ModelId = $ModelId or ModelId is null)
order by ( ServiceId is not null ) desc,
         ( ModelId is not null ) desc
limit 1;

This returns one row with the best match.


I can't filter the child view based on a value from the parent view

Question: I have read many of the questions asked on this site, but none of them suited my problem. What is the need to make a Users view that shows below its created contents.
I have a website with 3 roles. Each role has the permission to create a content type. Users of the "Truckers" role can create nodes whose type is Trucks. The Username value is automatically added to a field, in order to identify which truck driver that truck belongs to. That field is an entity reference.
I need to create a view that shows users of the Truckers role and the trucks which belong to them. I created 2 views. One of them, based on the Trucks content type, lists the trucks, and among other fields, shows the Username of the truck driver who created it; the other one, based on Users, lists the users who have the Truckers role.
Using Views field view, I added the Trucks view as a field inside the Truckers view. However, I didn't find any combination of contextual filters, relationships, etc. that gives the desired result.
In the second image, you can see that the Trucks view is shown below each user of the Truckers role, but it shows all trucks, not just those created by the trucker.

I am not a programmer. How could I achieve the result I need? Is there a contextual filter, relationship, that I need to set? They have many options and I do not understand all of them correctly and in depth.
I am using Drupal 8.9.13 and Views field view 8.x-1.0-beta3.
Answer: You should be able to accomplish this with one view.  I don't think views field view is necessary.
Add a view that shows Users
In the Filter Criteria section filter it by role (trucker).
Under Advanced use the Relationships dropdown to add the relationship Content Authored.
In the Fields section add a field to show whatever field of the trucks content type you want to show for each trucker (e.g. truck name).  You could also use title.  This field setting will use the "node" relationship which is available as a result of adding Content Authored in the relationships dropdown in the advanced section.
If you do use title instead of something like truck name, or any field that appears in multiple content types, in the Filter Criteria section be sure to add a "content type" filter in order to restrict results to the trucks content type.
Format the results as you like (e.g. table, etc.).
Comment: Thanks, it works!
Just a clarification: I only made it work by setting the output format as table, and grouping by a field, in this case Username.


Rails with Yummly Gem works fine locally, but fails on Heroku

Question: I am a novice to Ruby on Rails and am following Michael Hartl's 3.2 tutorial book as a reference.  I got my app running and deployed onto Heroku fine until I try to add the unofficial yummly gem.
http://rubygems.org/gems/yummly/versions/0.0.7
I get it to work locally (makes and fetches the api fine), but when I push it to Heroku, the app crashes and says it can't find Yummly.rb in the helper files on line 5.
Other than including

require Yummly

in my controller class and

gem "yummly"

(and running bundle install) in my Gemfile, what could I be missing?  Perhaps I need to specify that the gem needs to be the latest version 0.0.9 (I couldn't get it to install so I didn't try to change it)?
Does this have to do with Heroku specifically? or does it have to do with the Yummly Gem specifically?
Heroku logs as follows
State changed from crashed to starting
Starting process with command `bundle exec thin start -R config.ru -e $RAILS_ENV -p 51790`
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /app/config/environment.rb:5)
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /app/config/environment.rb:5)
/app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:317:in `rescue in depend_on': Missing helper file helpers/Yummly.rb (LoadError)
from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/action_controller/metal/helpers.rb:92:in `modules_for_helpers'
from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:131:in `modules_for_helpers'
from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:131:in `map!'
from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:135:in `block in modules_for_helpers'
from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:312:in `depend_on'
from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:225:in `require_dependency'
from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:159:in `default_helper_module!'
from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/action_controller/metal/params_wrapper.rb:135:in `inherited'
from /app/app/controllers/application_controller.rb:1:in `<top (required)>'
from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:95:in `helper'
from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `block in require'
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/engine.rb:439:in `block (2 levels) in eager_load!'
from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/railties/routes_helpers.rb:7:in `block (2 levels) in with'
from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/action_controller/railties/paths.rb:7:in `block (2 levels) in with'
from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:22:in `block in inherited'
rom /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:22:in `class_eval'
from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/abstract_controller/helpers.rb:22:in `inherited'
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/engine.rb:436:in `ea

Answer: require takes a file or gem name to require so the classes and modules it defines are accessible in the current file.
Therefore, you should do the following :
require 'yummly'

Note the fact that it's a string and not a constant.
It is also completely downcased, as per convention, filenames in ruby never takes any uppercase.
However, since you're using bundler, you should know that is manages requiring your dependencies automatically. Therefore, you don't need to require your dependency at all.
Comment: Actually that did fix it.  I had a 'require Yummly' in another helper I forgot.  Thanks so much!
Comment: Thanks for the info.  It still works locally when I take out the require.  Sadly, it still doesn't fix the problem when I deploy it to Heroku.


How can I handle$~\exp(\ln|x|)~$to solve 1st order linear DE?

Question: RHS and LHS are same.
$$\exp\left(\ln\left(x\right)\right)=\exp\left(\ln\left(x\right)\right)\tag{1}$$
Taking log.
$$\ln\left(\exp\left(\ln\left(x\right)\right)\right)=\ln\left(\exp\left(\ln\left(x\right)\right)\right)\tag{2}$$
$$\ln\left(x\right)=\ln\left(\exp\left(\ln\left(x\right)\right)\right)\tag{3}$$
$$\therefore~~x=\exp\left(\ln\left(x\right)\right)\tag{4}$$
Then what about$~\ln\left|x\right|~$?
This problem is a sub-problem of below ODE.
$$\frac{\mathrm dy}{\mathrm dx}-\frac{2}{x}y=x^6\tag{5}$$
My thoughts are as below.
$$P\left(x\right):=-\frac{2}{x}\tag{6}$$
$$Q\left(x\right):=x^6\tag{7}$$
$$\underbrace{\frac{\mathrm dy}{\mathrm dx}+P\left(x\right)y=Q\left(x\right)}_{\text{1st order linear DE}}\tag{8}$$
$$\text{Integrating factor}=\exp\left(\int P\left(x\right)\mathrm{dx}\right)\tag{9}$$
$$\exp\left(\int-\frac{2}{x}\mathrm{dx}\right)\tag{10}$$
$$=\exp\left(-2\int\frac{1}{x}\mathrm{dx}\right)\tag{11}$$
$$=\exp\left(-2\ln\left|x\right|+\text{const}\right)\tag{12}$$
$$=\exp\left(-2\ln\left|x\right|\right)\exp\left(\text{const}\right)\tag{13}$$
$$=\exp\left(\color{red}{\ln\left|x\right|}\right)^{-2}\exp\left(\text{const}\right)\tag{14}$$
$$\exp\left(\ln\left|x\right|\right)=\exp\left(\ln\left|x\right|\right)\tag{15}$$
ADD
I got the following general solution as I forcefully assumed$~x=\exp\left(\ln\left|x\right|\right)~$
$$y=\frac{1}{5}x^7+\text{const}_{1}x^2\tag{16}$$
Comment: Note that when finding the integrating factor you can disregard the constant of integration in step (12). And there is no reason to assume that $x=\exp\left(\ln\left|x\right|\right)$ since the integrating factor is simply $\exp\left({\ln\left|x\right|}\right)^{-2}=\dfrac{1}{|x|^2}=\dfrac{1}{x^2}$.
Answer: I think I solved the problem by advice from @John Wayland Bales
$$\exp\left(\ln\left|x\right|\right)^{-2}\tag{1}$$
$$=\frac{1}{\exp\left(\ln\left|x\right|\right)^{2}}\tag{2}$$
$$=\frac{1}{\exp\left(2\ln\left|x\right|\right)}\tag{3}$$
$$=\frac{1}{\exp\left(\ln\left(\left|x\right|^2\right)\right)}\tag{4}$$
$$=\frac{1}{\exp\left(\ln\left(x^2\right)\right)}\tag{5}$$
$$=\frac{1}{\exp\left(2\ln\left(x\right)\right)}\tag{6}$$
$$=\frac{1}{\exp\left(\ln\left(x\right)\right)^{2}}\tag{7}$$
$$=\frac{1}{\left(x\right)^{2}}\tag{8}$$
Answer: Firstly, on your equations for $\exp$ and $\ln,$ $$x=\exp[\ln(x)]$$ only holds for $x\gt0.$ Secondly, the integrating factor for the equation $$y'(x)-\frac2{x}y(x)=x^6$$ is given by the function $$\mu(x)=\begin{cases}C_0\exp[-2\ln(-x)]&x\lt0\\C_1\exp[-2\ln(x)]&x\gt0\end{cases}=\begin{cases}-\frac{C_0}{x^2}&x\lt0\\\frac{C_1}{x^2}&x\gt0\end{cases}$$ with $C_0,C_1\gt0.$ What this means is that if $$f(x)=\frac1{x^2},$$ then $$(fy)'(x)=f(x)x^6=x^4.$$ Since $0$ is a singularity, we have that $$f(x)y(x)=\frac{x^5}5+C_0=\frac{y(x)}{x^2},\;\;\;\;x\lt0$$ $$f(x)y(x)=\frac{x^5}5+C_1=\frac{y(x)}{x^2},\;\;\;\;x\gt0.$$ What this implies is that $$y(x)=\begin{cases}\frac{x^7}5+C_0&x\lt0\\\frac{x^7}5+C_1&x\gt0\end{cases}.$$


Exim 4.63 - temporarily freeze outgoing emails from specific user sent by horde/roundcube

Question: I am following this solution
Exim4 - temporarily freeze outgoing emails from specific user (Exim4 - temporarily freeze outgoing emails from specific user)
I am able to get email freeze from specific sender, but only when I send it from console through "telnet xxx.xxx.xxx.xxx 25". Solution is not working when I send emails from Horde/Roundcube and any Desktop Client.
Please guide me where I am doing wrong ?
Answer: You need to add the acl_not_smtp acl
acl_not_smtp = acl_not_smtp

Then create the rule under that acl
acl_not_smtp:
   accept   condition = ${lookup{$sender_address}lsearch{/etc/exim/freezelist_sender_addresses}{1}{0}}
         control   = freeze/no_tell
   accept


Does $\int_{x_1}^{x_2}\frac{1}{f^{-1}(x)}dx=\int_{f^{-1}(x_1)}^{f^{-1}(x_2)}\frac{f^{\prime}(y)}{y}dy$ hold?

Question: Consider a differentiable function $f$ that is strictly increasing and positive. Numerical examples seem to show that:
\begin{equation}
\int_{x_1}^{x_2}\frac{1}{f^{-1}(x)}dx=\int_{f^{-1}(x_1)}^{f^{-1}(x_2)}\frac{f^{\prime}(y)}{y}dy,
\end{equation}
where $f^{-1}$ denotes the inverse function of $f$ and $f^{\prime}(x)=\frac{\partial}{\partial x}f(x)$.
I was unable to show this and could not find any reference, so that by now I wonder whether this equality holds at all or if the examples I checked were just lucky coincidences.
Any hints would be appreciated. Thank you very much in advance.
Comment: Hint. Substitution: $y=f^{-1}(x)$
Answer: Yes, the given formula holds. As regards your last comment, the answer is no, making the substitution $y=f^{-1}(x)$, we don't find
$$\int_{x_1}^{x_2}\frac{1}{f^{-1}(x)}dx=\int_{f^{-1}(x_1)}^{f^{-1}(x_2)}\frac{y}{f^{\prime}(y)}dy.$$
By letting $y=f^{-1}(x)$ then $f(y)=x$ and $f'(y)\,dy=dx$. Moreover, since $f$ is increasing, the same holds for $f^{-1}$ and $[x_1,x_2]=[f^{-1}(x_1),f^{-1}(x_2)]$. Hence
$$\int_{x_1}^{x_2}\frac{1}{f^{-1}(x)}dx=\int_{f^{-1}(x_1)}^{f^{-1}(x_2)}\frac{1}{y}(f'(y)\,dy).$$
You may also obtain the same result by using the substitution rule
$$\int_{x_1}^{x_2}g(\varphi(x)) \varphi'(x)\,dx=\int_{\varphi(x_1)}^{\varphi(x_1)}g(y)\,dy$$
where
$$g(x)=\frac{f'(x)}{x}=\frac{1}{x\cdot (f^{-1})'(f(x))}\quad\text{and}\quad\varphi(x)=f^{-1}(x).$$
Comment: You're absolutely right. I simply mixed it up completely...


Problem with poker chips

Question: Dave has $10$ poker chips, $5$ of which are red and the other $5$ of which are white. Dave likes to stack his chips and flip them over as he plays. How many different $10$-chip stacks can Dave make if two stacks are not consider distinct if one can be flipped to appear identical to the other?
Can someone please help me answer this, I know there is a similar problem out there but it was with $6$ and $4$ instead of $5$ and $5$ so I was unsure how to solve it using odd numbers.
Thanks appreciate the help.
Answer: So the total way of arranging the chips is 10!/5!5!. Now consider this, if we say let red chips be denoted by 1 and white chips be denoted by 0, then all the palindromes formed will be considered identical as if you flip them you get the same order (eg 1000110001 ). Now all the non palindromic sequences are considered twice in the 10!/5!5! (as 10!/5!5! counts 110010001,100010011, but as a rule these are identical) Thus we need to divide the whole thing by 2, But in doing so we divide number of palindromic sequences which aren't counted twice by 2, hence we first add the number of palindromic sequence to the total way and divide the whole by 2 to get the answer the the should be : {[10!/5!5!]+no of palindromic sequence}/2. But here we understand the the palindrome should be using 5 ones and 5 zeros which isn't possible since 10 is even and you need even numbers of ones and zeros adding to 10 (like 6 and 4 as suggested), thus no of palindromic sequence = 0 thus the final ans : {10!/5!5!}/2.
Answer: There a $10!$ ways to arrange $10$ pieces. But this number includes every single possibility.
Since you have $5$ reds, you can swap a red chip with any other red one and you will get the exact same arrangement. There are  $5!$ to arrange the $5$ red chips therefore you divide $10!$ by $5!$.
The same is valid for the whites: divide again $\frac {10!}{5!}$ by $5!$.
Finally you get that the total number of arrangements is $\frac {10!}{5!\times5!}$.
The general formula for the number of different arrangements of $N$ elements, of which $m_1, m_2,...,m_n$ are the same, is $\frac{N!}{m_1!\times m_2!\times...\times m_n!}$
Now, note that every single stack arrangement when flipped has a corresponding arrangement, which is different from it. This is true, save for the symmetric arrangements - they are flipped onto themselves, not a different stack arrangement. Therefore, you are left to calculate how many of the possible stack arrangements are symmetric, divide the rest by $2$, since they are identical when flipped, and you will get the answer. Luckily, there are no symmetric arrangements since you have even number of positions and odd number of chips of the same color.
So you answer would be $\frac {10!}{2\times5!\times5!}$.

Problem with poker chips


Getting the node object in hook_form_FORM_ID_alter

Question: Follow up to this question  but I don't have enough reputation to ask clarification in a comment.
I am porting a contributed module to Drupal 8.
The sugested code on the above mentioned CR and post is not working:
$node = $form_state->getFormObject()->getEntity();

Nothing is loaded into the $node variable.
My PHPStorm IDE gives a warning for getEntity():
Method 'getEntity' not found in class Drupal\Core\Form\FormInterface less...
Referenced method is not found in subject class.
It is also not presenting this method for code completion.
In the use cause I am referencing:
use Drupal\Core\Entity;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Entity\Node;
use Drupal\Core\Render\Element;

Answer: PhpStorm doesn't know as the type of form object is dynamic but it's fine.
If you want to make it happy, wrap it in a condition like:
if ($form_state->getFormObject() instanceof EntityForm) {
  ...
}

Either way, it should definitely work if you implement the correct form alter. If you don't, you should end up with a fatal error not just without a node object.
You need to share your exact code if you want a more specific answer, that's all I can tell you.
Comment: Thanks Berdir. I was not aware $node is not the node object like in D7. So $node->nid does not work, but $node->Id () does.
Answer: Though the correct answer has been chosen, I feel there's need to explain some things:

The method getFormObject() is only available on forms of type EntityForm.
If you're doing hook_form_node_form_alter(), you know that the form is always a node form, so you're safe calling getEntity() on the form object.
However, if you're doing a general hook_form_alter() hook, you might want to check for the correct $form_id or check if the form object is actually a NodeForm or an EntityForm. This will prevent PHP errors if the form is not an entity / node form.
As for your IDE and code completion, you can tell your IDE that the $form_object you're dealing with is a NodeForm or an EntityForm. This will make it show more appropriate hints.

/** @var \Drupal\Core\Entity\EntityForm $form_object */
$form_object = $form_state->getFormObject();
if ($form_object instanceof EntityForm) {
  $entity = $form_object->getEntity();
  // Do something with the entity.
}

Comment: best of them all, thanks for the clarification!
Answer: For your IDE to know what the variable type is and what is available to it, you need to type hint your variables.
The type hint is the variable type added before the parameter variable name (in the example below array and FormStateInterFace).
Example:
/**
 * On form submit, do something.
 *
 * @param array
 *   The form array.
 *
 * @param \Drupal\Core\Form\FormStateInterface
 *   The form state array.
 */
function _submit_hook_name(array $form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject();
  // Do something...
}

For submit hooks, you should be using the Drupal\Core\Form\FormStateInterface type... therefore at the top of the file ensure you use that class use Drupal\Core\Form\FormStateInterface;.
Drupal coding standards states that you should type cast as well as explain the type in the docblock.  The extra effort helps in future. ;)


Lagrange multipliers or KKT problem

Question: Consider the following: find the absolute max and absolute min of $f(x, y, z) = yz + xz$ over $V = \{(x, y, z) \in\mathbb{R}^3; 2x + y + z \leq 1; x \geq 0, y \geq 0, z \geq 0\}$
Attempts
So first of all, $V$ is bounded and closed, hence it's compact. This means there do exist max and min (global). Even without starting any kind of calculation, I can smell the global min is at $(0, 0, 0)$, since we have a restriction over the three variables but they all can start from zero. The function cannot be negative, due to the conditions over $(x, y, z)$ so this "proves" the origin is the global minimum.
Yet I am having troubles in finding the global max. Also I wonder if there is a suitable way to find the global min too, without intuition.
The Lagrangian reads
$$L = yz + xz - \lambda(2x + y + z - 1)$$
And the associated system of equations (gradient plus constraint) reads
$$\begin{cases}
z - 2\lambda = 0 \\\\
z - \lambda = 0 \\\\
y + x - \lambda = 0
\\\\
\lambda(2x + y + z - 1) = 0 \\\\
2x + y + z - 1 \leq 0
\end{cases}
$$
I avoided to write also the positive conditions on $(x, y, z)$.
Now from the first two equations it's obvious that $z = 0$. But then from the third and from the constraint I get $x = 1$, which turns into $y = -1$.
The point $(1, -1, 0)$ is not valid though.
I don't really know how to continue here, because I cannot say "suppose $\lambda \neq 0$ and then reason on the constraint for the first two equations implies $\lambda = 0$ and $z = 0$.
I am not capable to use KKT here, have no clue on how I would proceed with this.
Any help? Also $(0, 0, 0)$ does not emerge from here.
Comment: Are you sure you've used KKT correctly? The version I know of needs one support variable per (in-)equality constraint
Comment: @Sudix You mean like adding $\sigma x \geq 0$, $\rho y \geq 0$ and $\tau z \geq 0$ in addition to $\sigma x$, $\rho y$ and $\tau z$ in the Lagrangian? I tried but it becomes just a mess, and the solutions do not change, I think...
Comment: Without the inequalities $x,y,z\ge 0$ the problem has neither minimum or maximum, so they're strictly necessary. It becomes a mess in the sense that you get a case distinction into $2^4$ cases. That's more or less how it is expected to go, though - without anything we can make use of, each inequality constraint doubles the number of cases to handle. However, for your case, each resulting case is a linear program, so while the process may be tedious, it should give you a result.
Comment: If you want to save some work, you can (for the maximizer at least) first look only at $2x+y+z\le 1$ and argue that for any maximizer with $2x+y+z<1$ we can find a maximizer with $2x+y+z=1$ that is at least as good if not better.
Answer: Considering the Lagrangian
$$
L(x,y,z,\lambda,s) = x z+y z+b x+\lambda _1 \left(s_1^2+2 x+y+z-1\right)+\lambda _2 \left(x-s_2^2\right)+\lambda _3 \left(y-s_3^2\right)+\lambda _4 \left(z-s_4^2\right)
$$
The stationary conditions gives
$$
\nabla L = 0 = \cases{
b+2 \lambda _1+\lambda _2+z\\
\lambda _1+\lambda _3+z\\
\lambda _1+\lambda _4+x+y\\
s_1^2+2 x+y+z-1\\
x-s_2^2\\
y-s_3^2\\
z-s_4^2\\
\lambda _1 s_1\\
\lambda _2s_2\\
\lambda _3 s_3\\
\lambda _4 s_4}
$$
after substitution of $b = 0$ into the formal solutions, we have
$$
\left[
\begin{array}{cccccccccccc}
f & x & z & y & \lambda_1 & \lambda_2 & \lambda_3 & \lambda_4 & s_1^2 & s_2^2 & s_3^2 & s_4^2\\
 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
 0 & 0 & 0 & 1 & 0 & -1 & -1 & 0 & 0 & 0 & 0 & 1 \\
 0 & 0 & 1 & 0 & 0 & 0 & 0 & -1 & 0 & 0 & 1 & 0 \\
 0 & \frac{1}{2} & 0 & 0 & 0 & 0 & 0 & -\frac{1}{2} & 0 & \frac{1}{2} & 0 & 0 \\
 \frac{1}{8} & \frac{1}{4} & 0 & \frac{1}{2} & -\frac{1}{4} & 0 & -\frac{1}{4} & 0 & 0 & \frac{1}{4} & 0 & \frac{1}{2} \\
 \frac{1}{4} & 0 & \frac{1}{2} & \frac{1}{2} & -\frac{1}{2} & \frac{1}{2} & 0 & 0 & 0 & 0 & \frac{1}{2} & \frac{1}{2} \\
\end{array}
\right]
$$
Here $s_i = 0$ means that the $i$-th constraint is active and $s_i > 0$ means that the solution point is internal to the corresponding constraint. The problem here is to administrate the $2^4$ possibilities of $\lambda_is_i = 0$

Lagrange multipliers or KKT problem


Is there a $(6,9,3)_2$ code?

Question: Does there exist a $1$-error-correcting binary code with block length $6$ and $9$ codewords?

The Hamming bound says that for any code $C$ with those parameters, $|C| \le \frac{2^6}{1+6} \approx 9.14$. So, we can't rule out the existence of such a code using the Hamming bound.
The Singleton bound says that for any code $C$ with those parameters, $|C| \le 2^{6-3+1} = 16$, so we can't rule out the existence of such a code using the Singleton bound.
Also, this can't be a linear code, since $\log_2 9$ isn't an integer. That rules out the possibility of just enumerating the possible generator matrices.

I feel a bit silly asking this, but the direct approach (assume $000\ 000$ is in the code, then all others must have Hamming weight $\ge 3$, ...) becomes unmanageable quickly. How else can I go about this?
Answer: By adding a parity bit / puncturing in any non-constant coordinate (i.e. in this coordinate, both symbols $0$ and $1$ appear in some codeword), a $(6,9,3)_2$ code exists if and only if a $(7,9,4)_2$ code exists.
For a $(7,9,4)_2$-code, the Plotkin bound yields the contradiction $$4 = d \leq \frac{n\cdot \left|C\right| \cdot (q-1)}{(\left|C\right|-1)\cdot q} = \frac{7 \cdot 9\cdot 1}{8\cdot 2} \approx 3.94.$$
So there is no $(7,9,4)_2$ code and no $(6,9,3)_2$ code.
A convenient tool on questions like this is the internet table for small binary block codes. According to it, the maximum size for a binary code of length $7$ and distance $4$ is $8$, so again, there is no $(7,9,4)_2$ code.
In fact there is only a single isomorphism class of a $(6,8,3)_2$ code, and moreover it is linear (if translated such that the zero word is in the code). The code of joriki has the generator matrix $$\begin{pmatrix}1 & 0 & 0 & 1 & 1 & 0 \\ 0 & 1 & 0 & 1 & 0 & 1 \\ 0 & 0 & 1 & 0 & 1 & 1\end{pmatrix}.$$
Comment: Thank you. Yes, you are right, "removing a parity bit" is a bit misleading. I'll edit my answer. What I mean is: You puncture the code in the $i$-th coordinate (i.e. remove the $i$-th coordinate from all codewords). The only condition is that not all codewords are zero in this coordinate (if $C$ has more than 1 codeword, there is always such a coordinate; for good codes typically each single coordinate is fine).
Comment: Nice solution; more insightful than mine :-) When you say "adding / removing a parity bit", I suppose you mean "adding a parity bit or removing an arbitrary bit"? At least I don't see why the $(7,9,4)_2$ code should have a parity bit.
Comment: Whence that condition? Wouldn't you also get a $(6,9,3)_2$ code by removing a coordinate with all zeros?
Comment: You get a $(6,9,4)_2$ code then. Of course, you could immediately "worsen" it to a $(6,9,3)_2$ code by flipping some bit in a minimum weight codeword (assuming that the zero-word is in the code.
Comment: Interesting -- I hadn't realized that I was slightly misusing the notation and calling anything a $(6,9,3)_2$ code that has distance *at least* $3$.
Comment: Yeah, in some situations this would be quite convenient. But as far as I know, $(n,A,d)_q$ means minimum distance *exactly* $d$. For the "at least" version one could use the notation $(n,a,\geq d)_q$, though.
Comment: Thanks! That extending/puncturing trick is clever. By the way, your use of $(n,A,d)_q$ and $(n,A,\ge d)_q$ matches what I was taught.
Answer: Here's code that performs an exhaustive search for such a code and doesn't find one. It does find a $(6,8,3)_2$ code:
<code>000000
111000
100110
011110
010101
101101
110011
001011
</code>
Answer: For a binary codeword of length $6$, there are $4$ choices for the last two coordinates: $00,01,10$ or $11$. Now assume that, there is a binary code with nine codewords. But then, at least three of the codewords must have the same the last two coordinates by pigeonhole principle. However, three codewords having the same last two coordinates cannot satisfy the given minimum distance since they must satisfy the same minimum distance for length $4$. Hence, there is no $(6,9,3)_2$ code.

Is there a $(6,9,3)_2$ code?


I have my data set, now what?

Question: I have a basic understanding of basic statistics, but I believe I've gotten myself out of my depth.
I have a data set with a dependent variable (time span) and three quantitative independent variables. There is also a qualitative independent variable (a type flag) but I think I can quantify it if I must. The quantitative independent variables all seem to be inversely proportional to the dependent variable.
I want to see if I can determine which of these independent variables has the most influence over the dependent. I ran all data through regression tests using statsmodels for Python (ordinary least squares) but I get warnings indicating multicollinearity and $R^2 = 0.002$. I've also tried univariate linear regression of each independent but am not getting something that looks usable.
Finally, I also have this problem of the qualitative independent.
Again, I'd really like to know how these independents work together to influence the dependent, and I'd also like to know the degrees to which they influence but I'm clearly lost as to the methodology.
EDIT

Warnings:
1 The condition number is large, 5.65e+06. This might indicate that there are
  strong multicollinearity or other numerical problems.

Screenshot of full output from .fit().summary()

Data Profile:

I should also note that two of these independent variables (maxtransfersize and buffercount) repeat for every combination of stripes and diskconfig (<- this is the qualitative variable, and I think I have a way of quantifying that now). backup_time_ms is the dependent variable.
Comment: Post your warning text in full.  Can you display a snapshot of the data set (Probably just a few observations).  Post the output of statsmodel that shows the $R^2R
Answer: The problem that you're running into is the multi-collinearity in the input matrix for your regression.  the matrix is 'ill-conditioned', meaning that small errors in the input lead to large errors in the ouput.  The calculation for the condition number of a matrix is $\frac{\lambda_{max}}{\lambda_{min}}$ (that might only be for symmetric matricies), or the ratio of the largest to the smallest eigenvalue of the matrix..  I think that the general formula is $||A|| ||A^{-1}||$  The normal equations (the equation used to solve for the betas of the regression) are $\beta = (A^TA)^{-1}Ay$.  So as you can see, if you have a matrix with a large condition number (which your program is telling you that you do), it becomes worse from the normal equations since you basically multiply the A matrix together three times.  This problem (the multi-collinearity) is what's causing your $R^2$ and your betas to have "messed up" values.  (remember that small errors in the inputs lead to large errors in the output).  Now, what can you do about this?  This large condition number comes up also on very high dimensional data.  For you, it seems to be coming from the fact that your predictor variables are strongly related.  What can you do about this?
(1) You can figure out which of your variables is causing the problem and remove it from the model.
(2) You can consider methods like ridge regression.
What does ridge regression do?  They add a small perturbation to your matrix ($\lambda I)$ where $\lambda$ is the perturbation, and I is an identity matrix (matrix with zeroes everywhere, but ones in the diagonal).  This reduces your problem with multi-collinearity, but at the expense of adding some bias to the model.  I'd suggest on reading up on ridge regression or lasso before just jumping in.  I've always found "The Elements of Statistical Learning" to be a good reference.  It's free as a pdf online.  Good luck.
Comment: Hi there. Thanks for the feedback. I apologize for the delay. I'm no good at these advanced statistical methods and am really just trying to determine which of x1, x2, and x3 holds the most influence over the outcome. I'm trying to understand the methods you've described (thanks for the paper) but I think that I am just having a hard time conceptualizing how to analyze my data set.
Comment: (1) The r-squared is low. This is secondary to collinearity? (2) the lasso performs well in the setting of collinearity? (3) Lasso is a traditional way to manage colinearity? Usually one (a) removing variable (b) combines variables (c) orthogolonizing (sp?) http://stats.stackexchange.com/questions/25611/how-to-deal-with-multicollinearity-when-performing-variable-selection
Comment: (c) yes, i think it's called gram-schmidt.
Answer: There is a lot to comment on here. Not sure what is the most useful.
(0) I've also tried univariate linear regression of each independent but am not getting something that looks usable  If there isn't a strong association, statistics won't solve that. Exploratory data analysis with graphs can be useful here.
(1) dependent variable (time span) Time variables: these can be tricky. They are often not normally distributed. You may want to examine this assumption
(2) quantitative qualitative independent variable This isn't useful terminology. Continuous or categorical. And if you think that there isn't a linear relationship for continuous variables (as discovered in exploratory analysis), how you plan to accommodate that would be a better start
(3) X2 and X3 appear to be correlated based on regression. Are they? Exploratory analysis with X2 vs X3 plot would be useful.
Comment: Thanks for your feedback and I apologize for the delay. As for (3), I don't know how to answer that because they were both controlled by me when creating the test. I established the test such that x2 and x3 were held constant while x1 was changed. Then I held x1 and x3 constant while x2 was changed. Finally, I held x1 and x2 constant while x3 was changed. As I said, I'm really not particularly good with statistics, but what I'd really like to know is which of these variable holds the most influence over the result and I just don't know how to achieve that.

I have my data set, now what?


What is this chord (B-E-A-D#-F#)?

Question: We have the successive notes :  B-E-A-D#-F#
I know that it is not B11. I have no idea of the name.
Comment: You seem to know enough to state it's *not* B11. What lead you to that conclusion?
Comment: @AndrewT. - please do not believe all you read on websites. There's a lot of dross and inaccuracies contained therein.
Comment: @Tim it's just to push OP to explain the reasoning why they believed it's not B11...
Comment: According to [Scales Chords](https://www.scales-chords.com/chord-namer/?notes=D%23;E;F%23;A;B&key=&bass=), it's B11. On the other hand, it'd be interesting to know why you thought it's not B11.
Comment: @AndrewT. http://scottdavies.net/chords_and_scales/music.html according to this website there is a C#
Comment: Does this answer your question? [What fingerings are used for the minor and major blues scales?](https://music.stackexchange.com/questions/32109/what-fingerings-are-used-for-the-minor-and-major-blues-scales)
Comment: @DaveJacoby Not clear the relationship between your comment and this question. Did you intend your comment for another post?
Comment: @DaveJacoby - I think the answer is no.
Answer: The order of the notes in a chord rarely affect its name. B D# F# make B major. Adding A (b7) makes it dominant 7th. The E is the 4th, which could be a sus 4 but since there is the maj 3 (D#) that can't be sus. E becomes the 11th. but since there is no 9th (C#)  it must be B7 add 11.
Comment: This is known as a "quartal" voicing, which need not be strictly quartal for the designation. If only the D# was a D, it would be the chord and voicing used by Bill Evans on Miles Davis's [original "So What" recording](https://www.youtube.com/watch?v=ylXk1LBvIqU&t=36s).
Answer: It's is a B11. First off, exact voicing do not matter for naming the chord. The bass note is the only thing that affects the naming. Extend chords in general imply the lower extensions, but are not required in the chord. In a similar vein of thought, the 5th in general in any chord can be implied so 4 sets of notes can represent a B11 and they are as follows:
B11 (All notes): B-D♯-F♯-A-C♯-E
X:1
L:1/1
K:C
M:None
V:1 clef=treble
"B11"[B, ^D ^F A ^C' E']

B11 (Omitted 9th): B-D♯-F♯-A-E
X:1
L:1/1
K:C
M:None
V:1 clef=treble
"B11"[B, ^D ^F A E']

B11 (Omitted 5th): B-D♯-A-C♯-E
X:1
L:1/1
K:C
M:None
V:1 clef=treble
"B11"[B, ^D A ^C' E']

B11 (Omitted 5th & 9th): B-D♯-A-E
X:1
L:1/1
K:C
M:None
V:1 clef=treble
"B11"[B, ^D A E']

Answer: B probably isn't the root of this chord, because it would be very dissonant and very bad for voice leading for a chord with the root of B to contain both a D# and an E. You would end up with the (silly but nonetheless correct) chord named B7susAdd10.
When you've got a collection of notes like this, you are not really looking at a chord per se, but rather a voicing of a chord. Chord voicings don't necessarily have to contain every note of the chord, just the ones that the composer/performer considers pertinent for the occasion. As you can imagine, that means there's a lot of flexibility and room for interpretation about what the chord actually is, since the root doesn't have to be at the bottom, the inversion doesn't really have to make much sense outside of the context that it's used, and the chord could be missing notes that would otherwise make it much easier to spell!
Nonetheless, I have some theories about what this chord might be.
My first guess (and the answer that I'd say is most likely) is F#Mi13/B. This collection of notes contains every note key to this chord; it's only missing the fifth, which is a common candidate for removal in chord voicings that contain the root. This is a particularly likely candidate if the next chord is B7 or F7, but it wouldn't necessarily be either of those.
Due to the nature of the question, it's also possible that it's something different. It could be a rather unusual voicing of EMiMaj9 or a somewhat less unusual voicing for AMaj7#11. It's also possible that the connection to a triad is only incidental and that this chord that mostly consists of stacked fourths derives its properties from those stacked fourths. The point is that if you find F#Mi13/B to be an insufficient answer then no specific answer anyone here gives you is going to be particularly good and you need to investigate the context that the chord lies in and use that to spell it; because we don't have that we can only give you a best guess answer.
Comment: Here we go again, inventing crazy names for simple chords! Sheesh, even in the 16th century people used to write dominant chords (E) in A minor with F natural and G natural in one part, and F# and G# simultaneously in another, without getting hung up about "dissonance"! It's not dissonant at all - just nice and "crunchy!"
Comment: Brad Mehldau fairly often uses voicings with the major 3rd and the 11th. One good example that comes to mind is his solo version of My Favorite Things. This can be heard on the live recordings available from searching YouTube, and [here's a nice video tutorial](https://m.youtube.com/watch?v=ZO7WkrsW6Ag) that shows it in bar 8.
Comment: Yep.  To me this chord sounds like a B7 plus the fourth, sort of a crunchy suspension.  No way that F# can be construed as the root, unless it is strongly implied by the voice leading.
Comment: The question says he knows it's not a B, so what's your next best candidate? F#. I would say as a rule that any chord declared a suspension with the major 3rd (or 10th) in it has been misspelled by definition as it betrays the meaning of "suspension". Also @alephzero F, F#, G and G# being played simultaneously in A minor has never not been dissonant.

What is this chord (B-E-A-D#-F#)?


How to statistically analyze significance with 7-point Likert scale data?

Question: I am working on a business research paper. The hypothesis is that the sales rep influences the customer's decisions. Independent variables consist of the sales rep's: knowledge, pushiness, friendliness, etc. Dependent variable is the customer's willingess to buy.
In all, I have 12 questions that I asked on a Likert scale ranging from 1 (not important at all) to 7 (extremely important).
At this point, I have all the means and standard deviations calculated but am not sure how to proceed to evaluate whether the whole set of independent variables proves my hypothesis that the rep's qualities does influence the customer to buy.
I've done some reading on regression, ANOVA and chi squared but would really like to understand how I can apply them to this situation.
Additionally, I want to know if I compute the composite score of the subgroups, i.e. men versus women, how can I compare them statistically?
Thanks for any and all suggestions!
Comment: Is the dependent variable also on a 7-item Likert scale?
Comment: Just to clarify: Do all data come from the customer? They rate the sales rep's knowledge, etc., then you ask them if they are willing to buy?
Comment: Hi Jason - Yes, in the sense that I first asked "how important are the following sales rep's features in your decision to buy", then followed by the respondent answering the following questions based on 1-7.  Is that what you mean?
Comment: Hi Jason - Yes they do all come from the customer. However I indirectly ask if they are willing to buy based on how they rate the questions. So the summation of the answers would indicate they are feel strongly to buy.
Comment: There's a problem with the underlying hypothesis: if the sales rep is really great, the customer will never notice it was not her own decision. Non-response rates are going to be significant, as well. Multinomial logit is (superficially) what you are probably after. Please be aware there's a lot more for you to read to avoid the hidden reefs...
Comment: Deer Hunter - that is very true. I will make a mention of that in my research but I think this is the best I can go on. Thank you very much!
Comment: The discussion is very confusing. Do you have 11 Likert-type 7-points ratings as independent variables and one willingness-to-buy rating as dependent variable?
Answer: As you have already identified dependent and independent variables, you can use correlation and regression analysis. If you have qualitative variables you can also conducted comparison tests such as t-test for two groups and ANOVA for more than two group qualitative variable.
Answer: You can group your data and perform either a 2-proportion test or a Chi-square test.
Ho: Sales Rep knowledge has no impact on customer buying criteria
Ha: Knowledgable Sales Rep has a positive impact on customer buying criteria
A simple grouping:
Divide your data into 2 groups (low sales rep knowledge and high sales rep knowledge).
Divide your results into 2 groups (will likely buy and will not buy).
Once you have this grouped data then you can perform a 2-proportion test.
If you have more than 2 groups, then a Chi-square test would be appropriate.
Comment: Dividing your individuals into two groups is a bad idea as it discards information and reduces power.


Ιnitial Value Problem $y'=(x-y)^{1/2}$, $y(2)=2$

Question:
Let the initial value problem :
  $$y'=(x-y)^{1/2}, y(2)=2$$
  Study the existence of solutions in a domain around the initial value and study its uniqueness too.

Attempt :
In order to show the uniqueness, I'll work around the function $f(x,y) = (x-y)^{1/2}$ and it's Lipschitz condition with respect to $y$ :
$$|f(x,y_2) - f(x,y_1)| = |(x-y_2)^{1/2} - (x-y_1)^{1/2}|$$
For the function $g(y) = (x-y)^{1/2}$, we can use the Mean Value Theorem since it's continuous and differentiable for $x-y \geq 0 \Leftrightarrow x \geq y$, for some $ξ \in (y_1,y_2) $ :
$$\big((x-y)^{1/2}\big)'|_{y=ξ} = \frac{(x-y_2)^{1/2} - (x-y_1)^{1/2}}{y_2 - y_1}$$
$$\Leftrightarrow$$
$$-\frac{1}{2\sqrt{x-ξ}}(y_2-y_1) = (x-y_2)^{1/2}-(x-y_1)^{1/2}$$
$$\Leftrightarrow$$
$$\bigg|-\frac{1}{2\sqrt{x-ξ}}\bigg|\bigg|y_2-y_1\bigg| = \bigg| (x-y_2)^{1/2}-(x-y_1)^{1/2}\bigg|$$
Now, I am not sure if I can make an assumption about a constant $L$ with respect to $y$. I observe that $k=\bigg|-\frac{1}{2\sqrt{x-ξ}}\bigg|$ is independent of $y_2,y_1$ but I cannot see how to make an inequality out of this, since it's value would change for any different $x$. Can you give me some help regarding how to show that there exists a Lipschitz constant or not ?
Also, regarding the solution, how would I study the existence of solutions in a domain around $y(2) = 2$ ? Can you please explain thoroughly with a complete solution regarding this, because it's an issue I have in a lot of similar problems.
Comment: At $y=x$ you have a vertical tangent in direction $y$ and thus no Lipschitz constant.
Comment: @LutzL ty for the reply. What about the existence of solution though around the domain of the initial value ?
Comment: @LutzL By the way, I suppose you mean a vertical tangent at $x=ξ$ ?
Comment: At any point $(x,y)$ where $y=x$, so also at the given initial point. However, contrary to $y'=\sqrt{y}$ the zero curve of the radicant is not a solution itself, so that the possibilities for multiple solutions are reduced.
Answer: Let $z(x)=x-y(x)$, then $z'(x)=1-y'(x)$ hence $$z'(x)=F(z(x))\qquad z(2)=0$$ with $$F:u\mapsto1-\sqrt{u}$$
This is an autonomous differential equation with $F(z(2))\ne0$ hence, for every $x\geqslant2$, $$\int_0^{z(x)}\frac{du}{1-\sqrt{u}}=x-2$$ that is, using the change of variable $v=\sqrt u$, $$x-2=\int_0^{\sqrt{z(x)}}\frac{2vdv}{1-v}=\left.-2\log(1-v)-2v\right|_0^{\sqrt{z(x)}}=-2\log(1-\sqrt{z(x)})-2\sqrt{z(x)}$$ or, equivalently, $$(1-\sqrt{z(x)})\,e^{\sqrt{z(x)}}=e^{1-x/2}$$ One sees that $z(x)$ increases from $z(2)=0$ to $z(+\infty)=1$, and that, for every $x\geqslant2$, $y(x)$ is the unique solution of the identity $$(1-\sqrt{x-y(x)})\,e^{\sqrt{x-y(x)}}=e^{1-x/2}$$
On the other hand, again using $F(z(2))>0$, one sees that the solution is not defined on $x<2$.
Nota: The fact that $F(z(2))>0$ implies that every solution $z(x)$ is instantaneously positive, that is, that $z(x)>0$ for every $x>2$, and then Cauchy-Lipschitz uniqueness and existence criterion applies. However, a rigorous argument showing uniqueness and existence starting at $z(2)=0$ is lacking (Cauchy-Peano-Arzelà provides existence, confirmed by the explicit computations above, but the hypotheses of Osgood's criterion, for example, are not met).


É possivel converter pdf para png sem usar o imagick?

Question: Eu estou gerando um documento em pdf e queria converte ele para png, mas a hospedagem do cliente não aceita extensões do php como o imagick, procurei bastante na net mas só acho opções que usa o imagick, alguém tem alguma ideia se é possível fazer sem e como?
Answer: Algumas hospedagens podem possuir o ImageMagick instalado, mesmo sem ter a extensão do PHP. Nestes casos, pode-se invocar o programa diretamente do sistema através do "exec()" do PHP:
<code><?php
$location   = "/usr/local/bin/convert"; // Localização do "convert" do imagick
$name       = "original.pdf";
$nameto     = "covertido.png";
$convert    = $location . " " . $name . " ".$nameto; // Comando
exec ($convert); // Executa o comando

echo "PDF convertido para PNG!!";
</code>


AWS SAM: An error occurred (ValidationError) when calling the CreateChangeSet operation: Parameter 'MaxAllowedPacket' must be a number

Question: I am adding a new parameter to my AWS RDS aurora-mysql CloudFormation template. But I am getting following error when running sam deploy.
sam deploy \
          --region us-west-2 \
          --stack-name xxxx \
          --template-file build/product.yaml \
          --capabilities CAPABILITY_IAM \
          --capabilities CAPABILITY_NAMED_IAM \
          --parameter-overrides \
            VpcId=vpc-123456789 \
      LambdaCodeBucket=artifacts-123456789

        Deploying with following values
        ===============================
        Stack name                   : xxxx
        Region                       : us-west-2
        Confirm changeset            : False
        Deployment s3 bucket         : None
        Capabilities                 : ["CAPABILITY_NAMED_IAM"]
        Parameter overrides          : {"VpcId": "vpc-123456789", "LambdaCodeBucket": "artifacts-123456789"}
        Signing Profiles             : {}

Initiating deployment
=====================
Error: Failed to create changeset for the stack: xxxx, An error occurred (ValidationError) when calling the CreateChangeSet operation: Parameter 'MaxAllowedPacket' must be a number.
make: *** [deploy] Error 1

product.yaml snippet:
  MaxAllowedPacket:
    Description: >-
      This parameter indicates the maximum size of packet in bytes. Allowed values are between 1024 to 1073741824.
      The default value is 4194304 (4 MB).
    Type: Number
    MinValue: 1024
    MaxValue: 1073741824
    Default: 4194304

....
Resources:
  ...
  DBParameterGroup:
    Type: AWS::RDS::DBParameterGroup
    Properties:
      Description: !Ref AWS::StackName
      Family: aurora-mysql5.7
      Parameters:
        max_allowed_packet: !Ref MaxAllowedPacket

I have set the type for MaxAllowedPacket as Number with a numeric min and max and the default value is also numeric. So not clear why is it throwing this error: Error: Failed to create changeset for the stack: xxxx, An error occurred (ValidationError) when calling the CreateChangeSet operation: Parameter 'MaxAllowedPacket' must be a number. make: *** [deploy] Error 1
I did look at other similar post on SO such as this, but it did not help.
Answer: I found the issue. This was happening because I had earlier defined MaxAllowedPacket as String and had created the resource with that.
Old Code:
  MaxAllowedPacket:
    AllowedPattern: ^(Auto|102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-9][0-9]{4,8}|10[0-6][0-9]{7}|107[0-2][0-9]{6}|1073[0-6][0-9]{5}|10737[0-3][0-9]{4}|1073740[0-9]{3}|1073741[0-7][0-9]{2}|10737418[01][0-9]|107374182[0-4])$
    Default: Auto
    Description: >-
      This parameter indicates the maximum size of packet in bytes. The default value is 4194304 (4 MB).
      Allowed values are between 1024 to 1073741824, or "Auto" to use the default value
    Type: String

After changing it to Number, it was failing when trying to update the same CloudFormation Stack because that Stack was having MaxAllowedPacket as String.
To ensure this was the issue, I created a new CF Stack (and hence new resource) with my new code (as shown on the question here) and it worked fine.


Criar título para duas colunas

Question: Tenho este código para criar as seguintes tabelas lado a lado:
echo '

';
echo '

Total de Refeições Creche I Utentes
	 ';
echo $tabela1;
echo '

Total de Refeições Creche II Utentes
	 ';
echo $tabela2;

echo "	";

echo '

Total de Refeições Infância Utentes
	 ';
echo $tabela3;
echo '

Total de Refeições Infância Colaboradores
	 ';
echo $tabela4;

echo "	";

echo '

Total de Refeições Centro de Dia Utentes
	 ';
echo $tabela5;
echo '

Total de Refeições Centro de Dia Colaboradores
	 ';
echo $tabela6;

echo "	";

echo '

Total de Refeições Lar Utentes
	 ';
echo $tabela7;
echo '

Total de Refeições Lar Colaboradores
	 ';
echo $tabela8;

echo '

';

Resultado:

Agora pretendo criar um título para as duas primeiras tabelas lado a lado e outro para as outras duas, como mostro na imagem:
Answer: Para fazer uma célula da tabela ocupar mais que uma coluna, pode usar o atributo colspan. Caso queira que ocupe mais que uma linha, também pode usar o rowspan, como mostra o exemplo abaixo.

    Senior

    A
    B

    C

Criar título para duas colunas


Spring Data JPA: How to fix NullPointerException in findById method of CrudRepository?

Question: Collegues, istill can't solve problem with CrudRepository when select data from MSSQL Db.
Repository looks like:
@Repository
public interface MarketInfoRepository extends CrudRepository<MarketInfoEntity, MarketInfoEntityPK> {

   // MarketInfoEntity findById(Integer id);
     MarketInfoEntity findById(MarketInfoEntityPK marketInfoEntityPK);

}

MarketInfoEntity entity is:
@Entity
@Table(name = "MarketInfo", schema = "dbo", catalog = "")
@IdClass(MarketInfoEntityPK.class)
public class MarketInfoEntity {
    private int id;
    /*other fields*/

    @Basic
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

@Id
@Column(name = "Asset_ID")
public double getAssetId() {
    return assetId;
}

public void setAssetId(double assetId) {
    this.assetId = assetId;
}

@Id
@Column(name = "TSSection_ID")
public double getTsSectionId() {
    return tsSectionId;
}

public void setTsSectionId(double tsSectionId) {
    this.tsSectionId = tsSectionId;
}

    /*equals and hashcode*/
}

When I run test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {OlmeCapConfig.class} , loader = AnnotationConfigContextLoader.class)
public class MarketInfoCapRepositoryTest {

    @Autowired
    MarketInfoCapRepository marketInfoCapRepository;

    @Test
    public void findById() throws Exception {

        try {
            marketInfoCapRepository.findById(82524);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

the next stacktrace follows:
java.lang.NullPointerException
    at org.hibernate.internal.util.StringHelper.root(StringHelper.java:379)
    at org.hibernate.persister.entity.AbstractEntityPersister.getSubclassPropertyTableNumber(AbstractEntityPersister.java:1884)
    at org.hibernate.persister.entity.BasicEntityPropertyMapping.toColumns(BasicEntityPropertyMapping.java:46)
    at org.hibernate.persister.entity.AbstractEntityPersister.toColumns(AbstractEntityPersister.java:1827)
    at org.hibernate.hql.internal.ast.tree.FromElement.getIdentityColumns(FromElement.java:354)
    at org.hibernate.hql.internal.ast.tree.IdentNode.resolveAsAlias(IdentNode.java:198)
    at org.hibernate.hql.internal.ast.tree.IdentNode.resolve(IdentNode.java:124)
    at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:109)
    at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:104)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:1013)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.propertyRef(HqlSqlBaseWalker.java:1165)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2287)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2228)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1499)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:583)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:311)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:259)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:261)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
    at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:545)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:654)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:3307)
    at org.hibernate.query.criteria.internal.CriteriaQueryImpl$1.buildCompiledQuery(CriteriaQueryImpl.java:318)
    at org.hibernate.query.criteria.internal.compile.CriteriaCompiler.compile(CriteriaCompiler.java:127)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:3600)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:203)
    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:498)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347)
    at com.sun.proxy.$Proxy44.createQuery(Unknown Source)
    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:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy44.createQuery(Unknown Source)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.createQuery(PartTreeJpaQuery.java:198)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.createQuery(PartTreeJpaQuery.java:148)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.doCreateQuery(PartTreeJpaQuery.java:79)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:206)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy64.findById(Unknown Source)
    at com.pivotal.olme.jpa.dao.cap.MarketInfoCapRepositoryTest.findById(MarketInfoCapRepositoryTest.java:46)
    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:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    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:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Could you help me to fix this NPE?
P.s.

May be problem is in Unknown Source (look into stacktrace)
Also i have one more method which extends CrudRepository with the same DataSource and it works fine.

Sorry once again for yesterday post with incorrect stacktrace.
Comment: `extends CrudRepository` ?
Answer: There are multiple issues with your code.
Why do you have a custom findById method when CrudRepository provides a findOne method. The Id class of your entity is not Integer but MarketInfoEntityPK so your findById should accept that (findOne uses that automatically).
Also, you don't have any fields annotated with @Id.
Comment: thank you. The problem was in incorrect method naming. Why idea offer to name method like `findBy...`, `getAfter` etc?


O que é uma virtual table?

Question: Vi que algumas linguagens usam essa tal de vtable na sua implementação. O que é e para que serve?
Todas as linguagens são iguais no uso dela?
Em que parte da memória ela fica?
Answer: A vtable, como costuma ser chamada, é uma tabela dos métodos virtuais a serem invocados quando um objeto está em uso. Portanto é algo de orientação a objeto, mais especificamente de polimorfismo.
Também chamada de tabela de funções/métodos virtuais, tabela de despacho ou tabela de chamada virtual
O v de virtual é sobre os métodos virtuais que essas linguagens têm. Então vtable é uma tabela de métodos virtuais, ou seja, é uma lista (pode ser algo muito próximo ou ser um array de referências (ponteiros) para o código das funções que servem como métodos).
Quando há polimorfismo é necessário ter uma forma de decidir qual código será executado de acordo com o tipo do objeto que está sendo manipulado. Existem algumas formas de realizar polimorfismo, uma delas é dinâmico, é usando late biding e precisa de um mecanismo para controlar isso.
Embora possa fazer de formas diferentes na prática a virtual table costuma ser a mais adequada.
O termo vtable é muito usado no contexto de C++, mas mecanismos parecidos existem em outras linguagens. Porém "nunca" é igual.
C++ só tem essa estrutura de dados chamada vtable para tipos que possuem métodos virtuais, ou seja, que fazem polimorfismo. A filosofia da linguagem é pagar só pelo que usa.
C# tem essa estrutura sempre e está atrelada ao tipo, tendo métodos virtuais ou não, a única otimização é não usá-la quando não é necessário.
Java não é diferente, só que usa a vtable do tipo sempre, mesmo sem necessidade, a não ser que o JITter faça alguma otimização quando ele percebe ser desnecessário, mas não é algo determinado pela linguagem.
Linguagens com características mais dinâmicas têm uma forma de vtable, usam sempre, e mais, costumam ter até uma vtable por objeto e não apenas uma por tipo.
Isso dá grande flexibilidade para os objetos, mas cobra o preço da performance e consumo de memória.
O uso em linguagens dinâmicas, talvez especialmente JavaScript, ajude entender a vtable, porque sabemos que um objeto nesta e outras linguagens de mesma filosofia na verdade possuem protótipos, que nada mais são que arrays associativos com os membros do objeto. Sendo que pode ter alguns membros que guardam valores, que são os campos, e outros membros que são os métodos, que não deixa de ser um valor guardado com o ponteiro para qual função deve executar. Cada objeto pode mudar completamente. Dá até pra trocar a função de uma hora para outra. Já respondido com mais detalhes em outras respostas.
Em linguagens mais estáticas não tem essa flexibilidade, só é necessário, potencialmente, mudar qual é o método a ser chamado se o tipo for mais específico, mas não a cada objeto. Então a estrutura de dados não fica junto do objeto, fica junto ao tipo, sendo que C++ não tem maiores informações sobre o tipo, tipicamente, e a vtable fica sozinha.
Estritamente falando as linguagens mais dinâmicas não têm exatamente uma vtable, tem algo mais poderoso, e ineficiente. Mas tem algo muito parecido. A vtable seria auxiliar e não parte do objeto. O mecanismo de indireção do polimorfismo é idêntico, mas feito diretamente no objeto.
Então todo objeto que tem uma forma de polimorfismo, usado efetivamente ou não, precisa estar ligado a uma estrutura de dados com a lista de métodos virtuais que ele tem para ser chamado. Pode ser a própria estrutura do objeto, ou pode ser algo separado em algum ponto da memória dedicado a isto, provavelmente em memória estática que o compilador disponibiliza. Obviamente que se estiver atrelado ao objeto então fica na memória dinâmica (muito eventualmente na automática).
A referência para a vtable costuma ficar em um preâmbulo do objeto, conforme já relatado em várias respostas aqui (exemplo em C#).
Bem grosso modo, nas linguagens estáticas, pode entender que ela é algo assim:
List<Function> vtable_Animal = { Animal_Come(), Animal_Anda() };
List<Function> vtable_Gato = { Gato_Come(), Gato_Anda() };

Obviamente que Gato é o tipo que herda de Animal.
Então cada objeto precisa ter uma referência para vtable_Animal se ele for do tipo Animal, e para vtable_Gato se for do tipo Gato.
Aí, quando for chamar o método Come() de um objeto, ele vai descobrir qual método deve chamar consultado a tabela em vez de chamar a função de forma direta. Isso é chamado indireção. Se o objeto foi declarado com o tipo Animal então chamará o Animal_Come(), mas se o tipo do objeto for Gato chamará Gato_Come(). Então a chamada do método é para um ponteiro para a vtable que tem um ponteiro para o método. A chamada já considera o elemento da lista, no exemplo Come() é o primeiro elemento.
Claro que tudo isso depende de implementação, a não ser que alguma linguagem especifique que só pode ser de um jeito por alguma razão. Cada detalhe tem que ser procurado onde está usando. De qualquer forma por ser um detalhe de implementação não costuma ser extensivamente documentado. Você não precisa saber para usar.
Então essa forma seria até mais simplificada em C++ e só teria a estrutura se realmente esses dois métodos demonstrados são virtuais (a tabela existiria se existisse um só método virtual).
Em C# a tabela seria muito maior, e complexa, com todos os métodos. Mas a tabela só seria consultada quando o método for declarado como virtual. Em Java ela seria sempre consultada, a não ser que o JITter otimize.
A consulta seria justamente pegar o ponteiro da tabela e aí consultar o ponteiro do método contido nela para chamar a execução adequada, diferente do método não virtual que já tem o ponteiro que deve ser usado para chamar a execução, não tem que selecionar qual método é o adequado.
Para dar uma ideia mais próxima de como é de fato em C++ (mas ainda não é a forma real):
struct Foo { virtual ~Foo(); virtual int a() { return 1; } };
struct Bar: public Foo { int a() { return 2; } };
void f(Foo& arg) {
  Foo x; x.a(); // non-virtual: always calls Foo::a()
  Bar y; y.a(); // non-virtual: always calls Bar::a()
  arg.a();      // virtual: must dispatch via vtable
  Foo z = arg;  // copy constructor Foo::Foo(const Foo&) will convert to Foo
  z.a();        // non-virtual Foo::a, since z is a Foo, even if arg was not
}

Se transforma em (note o uso de struct para formar a estrutura com  lista de métodos):
typedef struct Foo_t Foo;   // forward declaration
struct slotsFoo {           // list all virtual functions of Foo
  const void *parentVtable; // (single) inheritance
  void (*destructor)(Foo*); // virtual destructor Foo::~Foo
  int (*a)(Foo*);           // virtual function Foo::a
};
struct Foo_t {                      // class Foo
  const struct slotsFoo* vtable;    // each instance points to vtable
};
void destructFoo(Foo* self) { }     // Foo::~Foo
int aFoo(Foo* self) { return 1; }   // Foo::a()
const struct slotsFoo vtableFoo = { // only one constant table
  0,                                // no parent class
  destructFoo,
  aFoo
};
void constructFoo(Foo* self) {      // Foo::Foo()
  self->vtable = &vtableFoo;        // object points to class vtable
}
void copyConstructFoo(Foo* self,
                      Foo* other) { // Foo::Foo(const Foo&)
  self->vtable = &vtableFoo;        // don't copy from other!
}

typedef struct Bar_t {              // class Bar
  Foo base;                         // inherit all members of Foo
} Bar;
void destructBar(Bar* self) { }     // Bar::~Bar
int aBar(Bar* self) { return 2; }   // Bar::a()
const struct slotsFoo vtableBar = { // one more constant table
  &vtableFoo,                       // can dynamic_cast to Foo
  (void(*)(Foo*)) destructBar,      // must cast type to avoid errors
  (int(*)(Foo*)) aBar
};
void constructBar(Bar* self) {      // Bar::Bar()
  self->base.vtable = &vtableBar;   // point to Bar vtable
}

Usando:
void f(Foo* arg) {                  // same functionality as above
  Foo x; constructFoo(&x); aFoo(&x);
  Bar y; constructBar(&y); aBar(&y);
  arg->vtable->a(arg);              // virtual function call
  Foo z; copyConstructFoo(&z, arg);
  aFoo(&z);
  destructFoo(&z);
  destructBar(&y);
  destructFoo(&x);
}

Fonte.
Detalhe que você pode usar uma vtable em praticamente qualquer linguagem de programação, talvez todas de alguma forma, até mesmo em C. Sempre que o polimorfismo dinâmico for útil, se a linguagem não fornece o recurso, o programador cria e usa manualmente sem ajuda do compilador.
Eventualmente pode usar indireção de campos também, especialmente em múltipla herança.
Para múltipla herança é necessária uma técnica um pouco mais sofisticada para lidar com dois ou mais ramos de herança, eventualmente até acessando mais de uma vtable.
Esta técnica não é suficiente em linguagens que precisam fazer despachos múltiplos.
Geralmente isto faz parte da ABI.
Coloquei no GitHub para referência futura.

O que é uma virtual table?


How can I convert date in unix epoch format to ruby datetime for a datetime column

Question: The date is coming from an imported xml that gives a 13 digit string (unix epoch time format).
The following snippet causes the resulting column value to be set to 1970-01-01
  seconds=msg.time_stamp_long.to_i/1000
  time=Time.at(seconds).utc.to_s
  msg.time_stamp=time
  msg.save

How to get the correct format for a DateTime column?
Comment: Do You want to save in db `1970-01-01` ? can you up more ex: msg fields, ... you use format `strftime`. ex: `msg.created_at.strftime('%F')`
Comment: My problem is that 1970-01-01 isn't right It should be a real date derived from a 13 digit string from xml import It seems the data was originally in unix time format and needed to be converted to ruby datetime format first and being a string was problematic also
Comment: Thanks, it's a 13 digit string meaning it's a string but it's all numbers
Comment: What DBMS? Can you give and actual example? What is the DB schema for that column? Are you sure it's what you expected? "...a real date..."  give an example of what you expect to see. Don't describe it, give us exactly what you are seeing and what you want to see.
Comment: Sorry but this is a collosal XY question - you're asking about a solution which isn't even needed in the first place instead of just asking how to parse a unix epoch. `DateTime` is a Ruby class. Not an actual database column format. When you use `add_column :foo, :bar, :date_time` the database adapter will create the column with the appropriate format for your RBDMS.
Comment: You don't have actually care about the format - just pass input to your model that it understands like an instance of Date, DateTime, TimeWithZone or even ISO string. Then when you persist the model the database adapter will handle any conversion for you.
Answer: Time.at(1663681609392 / 1000).to_datetime

or if it's a string
Time.at("1663681609392".to_i / 1000).to_datetime

Be aware that unix time is epoch UTC time. Time and DateTime can get tricky in Ruby and in Rails. Make sure you are getting the time you expect. You may need to look into methods like .in_time_zone
To use your variables from the question:
msg.update(time_stamp: Time.at(msg.time_stamp_long / 1000))

is all you really need. As Max pointed out the DB adapter will handle the rest. But when you go to display or manipulate dates/times in Rails you might want to look into Date, Time, TimeWithZone, DateTime, etc. to understand the options that are out there and how they apply to your use case.
Comment: Also I see you are converting to a string before saving as the date-time column. Not sure why you would do that. That is why I asked for the schema.
Comment: I can't remember why I used to_s This became so difficult I'm now trying to solve it in mysql without using ruby or ror Mysql has a from_unixtime function that returns null when applied to the 13 digit numbers I have in time_stamp_long The schemas not really relevant I don't think because the data source is xml
Comment: to_datetime is a function that converts strings to datetimes, not integers to datetimes
Comment: Here's an example of one of the values of time_stamp_long 1663681609392 What date would you translate that into, how would you do it, how would you store that in a mysql datetime column? That's all I wanna know
Comment: Did you even read or try my answer? `to_datetime` is a method on both`String` and `Time` classes.
Comment: Here's the value I need to store as datetime (i think) 1663681609392
Comment: Also, you are missing something in your data format. Your time_stamp_long translates to `Fri Dec 20 20:23:12 PST 54689`. So unless you are looking for the year 54689, something is missing. My answer works. It's your data (or what you know about it) that is incorrect.
Comment: Oh, it's in milliseconds. So I need to divide by 1000 in my answer.
Comment: The answer should work. As Max pointed out to your question, the DB adapter will handle putting it into the DB. You just hand it something that Rails understands as a date_time, date, or time object.
Comment: Beartech: You're right, just needed to add to_i to enable division


app.UseMvc routes in asp.net doesn't exists

Question: I'm learning asp.net and I have a issue using routes in the startup file.
I need to change the url to do something like this
app.UseMvc(routes => {
routes.MapRoute(
name: "pagination",
template: "Products/Page{productPage}",
defaults: new { Controller = "Product", action = "List" });

But it said template parameter does not exists. I'm using Endpoints so how to do it with endpoints?
My actual code looks like this
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Product}/{action=List}/{id?}");

    });

Thanks
Answer: I suggest an easier way by declaring your route above the action itself.
[Route("Products/Page/{productPage?}")]
public async Task<IActionResult> Products(string productPage) {
    return View();
}


accessing variable in a method to another method in same class

Question: Hi i have used to a input dialog using a material design library to get a value.
inside the save button i have put my input dialog
saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new MaterialDialog.Builder(getActivity())
                        .title("Please enter your playlist name")
                        .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_DATETIME_VARIATION_NORMAL)
                        .input("", "", new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {

                                new BackgroundTask().execute();
                            }
                        }).show();

            }
        });

here i want to get the 'input' variable in
 public void onInput(MaterialDialog dialog, CharSequence input) {

to use in another method. How can i access this variable?
Comment: Can't you pass 'input' as a parameter to the other method?
Answer: If I understood your question well, you could get the input value like this:
private inputVal;

....
@Override
public void onInput(MaterialDialog dialog, CharSequence input) {
   //save the input variable to a global variable to be able to use it later
   inputVal = input.toString();
   new BackgroundTask().execute();
}

And then you could easily use the input variable in other methods
Answer: You can pass the variable directly to the method or save it into a class variable and then use that