Calculating Goodness of Fit in Multiple Regression

Question:
I've never even heard the term "Goodness of Fit" in my class. I looked through the textbook and can't find it there either.
What exactly is "goodness of fit"? Is there a formula to calculate it?
Answer: Goodness of fit is, roughly, the ability of a model to generate high quality predictions.
To calculate the goodness of fit, the predicted values are called expected value $E$, and the outcome is called an observed value $O$. There are a number of tests based on comparing the observed values to expected values. They are generally some form of the statistic: $(E-O)^2/variance)$ where $variance$ depends on the type of outcome being modeled. This statistic trends toward a $\chi^2$ random variable with $q-p$ degrees of freedom. The numerator $q$ is the number of parameters needed to give the "observed" quantities in a model" and $p$ is the number of parameters in the candidate model. If the test achieves a $p$-value less than $\alpha$ we conclude that the model has poor fit and that the observed values are too inconsistent with the expected values.
The most commonly used goodness-of-fit test is the Pearson Chi-square test for categorical data which is calculated by:
$$ T = \sum_{i,j} \left( O_{ij} - E_{ij} \right) ^2 / E_{ij} $$
for a contingency table having row/columns indexed by $i$ and $j$. The Wikipedia article has a good discussion of these models. However, a Poisson model has a different goodness of fit metric, like $\sum O_i/E_i$ which Rockhill used to show calibration of a cancer incidence prediction model in 2001.
In an ANOVA with discrete fixed effects, there is a finite number of possible expected values, based on all observed combinations of covariates, so the test statistic of the form $\sum_{i=1}^k (\bar{Y}_k - \hat{Y}_k)^2/(\sigma^2/n_k)$ has an asymptotic $\chi^2_{k-p}$ distribution (please correct me if this is wrong). Here $\bar{Y}_k$ is the sample mean for the $k$-th combination of covariates whereas $\hat{Y}_k$ is the predicted mean and $\sigma^2/n_k$ is the expected variance of the $k$-th sample mean when homoscedasticity holds.
This method has been highly criticized.

Null hypothesis significance testing seems to have limited applicability for evaluating predictive models.
Split sample validation, cross validation, or bootstraps are more promising for evaluating predictive models.
Large samples tend to produce overly precise global "goodness of fit" tests.
High dimensional models can suffer from poor power.
Comment: I have never seen goodness of fit explicated as the ability to make good predictions, for me it mean that the data looks like what you would expect if you simulated from the simulated model. It could well be that the true model cannot make good predictions! But it could still be good-fitting
Comment: @kjetilbhalvorsen I pondered the GOF for some time to think how best to explain in laymen's terms. I agree with your interpretation too. I don't see a disagreement between our explanations. I was careful about the word "good" versus "perfect" to describe predictions: good is relative to the realm of what's possible, a good fitting-model will certainly make good predictions if not perfect ones. A good fitting model may not be a true model.
Comment: @AdamO In the SEM tradition, you can have perfect fit with low R^2. In fact, it's often easier to get good fit when correlations among the original variables are low. But the OP is clearly asking about something different than SEM GOF, because (barring edge cases) a multiple regression model will always have perfect fit, being exactly identified. So apparently a subspecialty jargon difference.
Comment: @PatrickMalone how would one have perfect fit with low R^2 in SEM? There are many fit indices in SEM, they don't all measure the same thing. (Should this just be a separate question?)
Comment: @AdamO You can have a chi-squared of zero, which will be perfect fit by any criterion. The simple example is a saturated model (of which multiple regression is an example). It can reproduce the sample variance-covariance matrix exactly--which is what fit means in SEM--even when the relations are weak, so R^2 is low.

If you want to open a question I can hold forth further!
Comment: @PatrickMalone See related question [here](https://stats.stackexchange.com/questions/340384/how-is-goodness-of-fit-estimated-in-sem-models).
Answer: You need to calculate the coefficient of determination (R square) which is the most common goodness of fit index in multiple regression and (multiplied by 100) denotes the percent of the variation of dependent variable explained by the 4 predictors participating in your model. I guess that you have a textbook to consult. If not then after a simple Google search you will find many excellent sources.


In a classic 12-bar-blues pattern, what are the changes for a "chunka-chunka" rhythm?

Question: The basic 12bb pattern I know, but it's very typically played with a "chunka-chunka" rhythm where it alternates back and forth between two chord variants each beat (Is this also known as a shuffle or is that something else?)
On guitar I can play this on 2 strings and you can get away just be moving one string a tone up/down each strum, but I don't know what the underlying chords are.
Can someone explain the chords/theory?
Comment: I would add I have heard this called a "train" or "chugga-chugga" pattern. Basic to blues and rock and roll. Suggestive of the action (and sound) of the wheels on an old fashioned steam engine.
Answer: I agree with Tim's answer, but I'd like to add that you shouldn't think of it as changing chords. What you're doing (i.e. playing this on two strings) is actually correct and it's not like 'getting away' with something, but that's all that's to it. It's a line imposed over a chord: the chord is a dominant seventh chord (i.e. in a basic blues either the I7, IV7, or V7) and the line goes from the 5th of the chord to the 6th (and it sometimes moves on to the b7th). It happens quite often that the basic harmony is static while some line is moving. See also this answer for the more general concept of a moving line over a static chord.
Comment: @Mr.Boy: No, the basic boogie woogie left hand pattern would be two notes at the same time only.
Comment: So you're saying I'm effectively alternating between different 2-note chords, each a subset of the 'real' chord?
Comment: @Mr.Boy Yes, that's the way it is usually played on the guitar, not only by beginners.
Comment: I only used guitar as the example I know well though - how would it work on a piano for instance?
Comment: @Mr.Boy: Same thing.
Comment: Your left hand would typically just play 2 notes? I assumed it would be different (but related) 3-note chords - with a 7th chord you have 4 notes so you'd be picking a different set of 3, or something :)
Answer: You are playing a root and the 5th above it. That 5th then gets changed to a 6th. It sometimes then goes up one more fret to a m7th note. As in E - E (bottom string open) with 5th string 2nd fret, 4th fret, then, if you want 5th fret, often coming back to fret 4th fret.
So, the underlying chords would be maj (minor also works, but is unusual), 6th, then b7th.


Showing units sold in product page OpenCartv3

Question: I'm trying to show the units sold for each product in Product page in OpenCart v3 but I keep getting the following error

Fatal error: Uncaught Error: Call to a member function getUnitsSold()
  on null in
  /Applications/XAMPP/xamppfiles/htdocs/store/catalog/controller/product/product.php:157
  Stack trace: #0
  /Applications/XAMPP/xamppfiles/htdocs/store/system/engine/action.php(79):
  ControllerProductProduct->index() #1
  /Applications/XAMPP/xamppfiles/htdocs/store/catalog/controller/startup/router.php(25):
  Action->execute(Object(Registry)) #2
  /Applications/XAMPP/xamppfiles/htdocs/store/system/engine/action.php(79):
  ControllerStartupRouter->index() #3
  /Applications/XAMPP/xamppfiles/htdocs/store/system/engine/router.php(67):
  Action->execute(Object(Registry)) #4
  /Applications/XAMPP/xamppfiles/htdocs/store/system/engine/router.php(56):
  Router->execute(Object(Action)) #5
  /Applications/XAMPP/xamppfiles/htdocs/store/system/framework.php(168):
  Router->dispatch(Object(Action), Object(Action)) #6
  /Applications/XAMPP/xamppfiles/htdocs/store/system/startup.php(104):
  require_once('/Applications/X...') #7
  /Applications/XAMPP/xamppfiles/htdocs/store/index.php(19): in
  /Applications/XAMPP/xamppfiles/htdocs/store/catalog/controller/product/product.php
  on line 157

What I have so far is
catalog/model/catalog/product.php
<code>public function getUnitsSold($product_id) {
    $query = $this->db->query("SELECT SUM(op.quantity) AS total FROM `" . DB_PREFIX . "order_product` op LEFT JOIN `" . DB_PREFIX . "order` o ON (op.order_id = o.order_id) WHERE o.order_status_id > '0' AND op.product_id = '" . (int)$product_id . "'");
if ($query->row) {
        return $query->row['total'];
    } else {
        return FALSE;
    }
}
</code>
and in catalog/controller/product/product.php
<code>$data['text_units_sold'] = $this->language->get('text_units_sold');
$this->data['units_sold'] = $this->model_catalog_product->getUnitsSold($product_id);
</code>
Anyone can detect what is the problem and the solution.
Thanks.
Answer: I suspect that in the function where you are calling getUnitsSold, you have not done a
<code>$this->load->model('catalog/product');
</code>
Comment: It works!!! Thanks a lot, I really appreciate it. I have been scratching my brain for hours.


Show that the interior is not empty in $\mathbb R^3$

Question: Show that the interior of the set $M= \{ x \in \mathbb R^3:a_i^tx \le b_i , i=1,...,m\} $, where $a_i$ - vectors in $\mathbb R^3$, $b_i$ - positive numbers is not empty.
I wanted to take a sphere in the centre in point $x \in M$ with radius small enough that every other point in $S$ will be also in $M$. But I'm not sure how to show it, I was thinking about taking the radius $\frac{b_i-a_i^tx}{\lVert a_i \rVert}$, but I can't get any conclusion with that. Can someone help me?
Comment: @geetha290krm Correct, but may be empty.
Comment: $ \{ x \in \mathbb R^3:a_i^tx < b_i , i=1,...,m\} $ is the inverse image of an open set under a  continuous function, so it is open.
Comment: What does $a_i^tx$ mean?
Comment: @AdamRubinson it's the matrix multiplication form of the dot product.
Comment: You mean like ${a_i}^T a_i$ ?
Comment: @geetha290krm My first comment was nonsense. Your hint was essential.
Answer: geetha290krm gave the crucial hint:
The function $f_i : \mathbb  R^3 \to \mathbb R, f_i(x) =a_i^tx$, is continuous, thus $U_i = f_i^{-1}((-\infty,b_i)) = \{ x \in \mathbb R^3 \mid a_i^tx < b_i\}$ is open in $\mathbb R^3$. Thus $U = \bigcap_{i=1}^m U_i$ is open and contained in $M$. Since $b_i > 0 = f_i(0)$, we have $0 \in U \subset M$.
Thus the interior of $M$ is not empty.
Comment: Wait, but how did you get that $x_1+x_2+x_3=1$? We have that $x_1+x_2+x_3 \le 1$ and $x_1+x_2+x_3 \ge -1$
Comment: @delta Oops, you are right. My answer was nonsense. I have rewritten it.


How can I find the limit of the following?

Question: What is the limit of this
$$\lim_{x\to+\infty}\left(1+\frac{4}{2x+3}\right)^x$$
I know that $$\lim_{x\to+\infty}\left(1+\frac{4}{2x}\right)^x$$ will give me $$e^2$$ but the I dont know what to do with the 3.
I have tried bringing them to a common denominator so I got
$$\lim_{x\to+\infty}\left(\frac{2x+7}{2x+3}\right)^x=\lim_{x\to+\infty}\left(e^{x\ln{(\frac{2x+7}{2x+3})}}\right)$$
And then Im stuck again
Comment: Hint:
$$
\left(1+\frac{4}{2x+3}\right)^x
= \left(1+\frac{2}{x+\frac32}\right)^x
= \left(1+\frac{2}{x+\frac32}\right)^{x+\frac32} \left(1+\frac{2}{x+\frac32}\right)^{-\frac32}
$$
Comment: What have you tried? Do you know about the natural logarithm function and its properties?
Comment: Welcome to TeX SX! Simply determine the limit of the log.
Comment: You should show what you have tried to solve it.
Comment: I updated the post to show what I have done
Comment: Hint: $f(x)^x = e^{x \,\cdot\, \ln f(x)}$
Comment: Or also $$\left(1+\frac{4}{2x+3}\right)^x=\left[\left(1+\frac{4}{2x+3}\right)^{\frac{2x+3}{4}}\right]^{\frac{4x}{2x+3}}$$
Comment: @SammyBlack I think that now you can add your answer again since the asker gave some context about its effort.
Answer: Let $f(x) = 1 + \frac{4}{ 2x+3}$
And $g(x) = x $
Your limit is of the form $(1)^{\infty}$ , whose value is equal to $$e^{ \lim_{ x \to {\infty}}  {(f(x) - 1 )}{g(x)}} $$
Therefore , $$L = e^{ \lim_{ x \to {\infty}}  {(\frac{4x}{2x+3} )}} $$
Now $$\frac{4x}{2x+3} = {\frac{4x+6}{2x+3} } - \frac{6}{2x+3} = 2 - \frac{6}{2x+3}$$
Therefore , L becomes
$$ L =  e^{ \lim_{x \to \infty} { 2 - \frac{6}{2x+3}} } = e^2$$


Count duplicate string in array(java) in existing code

Question: <code>public static void main(String[] args) {
    String[] a = {"java","c++","c++","java","c#","bootstrap","java"};
    Set<String> nonDuplicateSet = new HashSet<String>();
    Set<String> duplicateSet = new HashSet<String>();
    for(String abc:a){
        if(!nonDuplicateSet.contains(abc)){
            nonDuplicateSet.add(abc);
        }else{
            duplicateSet.add(abc);
        }
    }
    System.out.println(duplicateSet);
</code>
How to count java is repeating 3 times/c++ is repeating 2 times
Comment: Instead of using `Set`s, you could try using a `Map`, where each `String` is stored along with the number of times it occurs.
Answer: This will help you
<code>`String[] a = {"java","c++","c++","java","c#","bootstrap","java"};
        Map<String, Integer> map = new HashMap<String, Integer>();
        for(String str :a){
            if(map.containsKey(str)){
                map.put(str, map.get(str)+1);
            }else{
                map.put(str, 1);
            }
        }`
</code>
and the for entrySet take the count.


Fix my querySelector to add a specific class to it in javaScript

Question: I have built the navigation bar in my web page dynamically as shown below
NavBuilder = () => {
//to loop from section 1 to 4 and add sections to navigation
for (s = 0; s < sections.length; s++) {
    const liElem = document.createElement('li');
    //const divElem = document.createElement("div");
    const Id = sections[s].id;
    const DataNav = sections[s].dataset.nav;
    liElem.innerHTML = `<a class="menu__link" href="#${Id}">${DataNav}</a>`;
    Menu.appendChild(liElem);
}
}
NavBuilder();

and when I want to scroll the page I want to add a specific class "your-active-class" to the section which I created in my html page, and also add the class "active" to the liElem so whenever I scroll in the page and stop on a specific section the navbar should highlight the section I stopped on int the navbar it and also highlight the section itself.
the javaScript function I created to add the class active:
window.addEventListener('scroll', () => {
sections.forEach(s => {
    const topDistance = s.getBoundingClientRect().top;
    // if the distance to the top is between 0-150px
    if (topDistance >= 0 && topDistance < 150) {
        s.classList.add('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.add("active");

        // otherwise, remove the class
    } else {
        s.classList.remove('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.remove("active");

    }
});

});

I am still caughting this error "Uncaught TypeError: Cannot read property 'id' of undefined" in the line
document.querySelector().classList.add("active");
What is the mistake i am making that prevent me from highlighting my navbar?
the html code:
    <!DOCTYPE>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Manipulating the DOM</title>

<link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">

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

Landing Page

Section 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra
          dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus
          imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget
          bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet
          elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo
          nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie
          semper in tellus. Sed congue et odio sed euismod.

Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel
          luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur
          porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.

Section 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra
          dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus
          imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget
          bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet
          elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo
          nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie
          semper in tellus. Sed congue et odio sed euismod.

Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel
          luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur
          porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.

&copy Udacity

and the active class and your-active-class
.active {
padding: 25px;
background-color: black;
color: white;

}
section.your-active-class {
background: rgb(0, 0, 0);
background: linear-gradient(0deg, rgba(211, 39, 39, 0.356) 0%, rgba(223, 10, 10, 0.548) 100%);

}
Answer: querySelector expects that you pass a valid CSS selector to it, which you aren't doing. You need to change it a little bit and select by the href's value.
In a queryselector you cannot use the -syntax.
document.querySelector(`a[href="#${sections[s].id}"]`)

Comment: I used document.querySelector(`a[href="#${s.id}"]`).classList.add("active"); and it worked fine thanks alot
Comment: Yes, and we also don't use foreach loop like that.
Answer: The basic syntax of foreach loops in JS is: forEach((element) => { /* ... */ } ).
Other syntaxes:
// Arrow function
forEach((element) => { /* ... */ } )
forEach((element, index) => { /* ... */ } )
forEach((element, index, array) => { /* ... */ } )

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function(element) { /* ... */ })
forEach(function(element, index) { /* ... */ })
forEach(function(element, index, array){ /* ... */ })
forEach(function(element, index, array) { /* ... */ }, thisArg)

The variable s in your code is already the element, but not the index(key). Use directly ${s.id} directly instead.
Also, we don't use querySelector() in that way (getting the whole element by typing in their HTML in).
Your code can be replaced by:
document.querySelector(`a[href="#${s.id}"]`)

For more info on querySelector(), please visit https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
P.S. Also, I really wonder if there is really a class in your page called your-active-class, cuz it seems like you copied completely from a website :P
If there is not, you can simply remove the s.classList.add('your-active-class');
Comment: so i got this error Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '' is not a valid selector.


XNA C# 2D Scrolling Background 3 or More

Question: I've trying to create a scrolling background with 3 background, but everything When the 3rd start to come out. It creates a giant blue screen(Default background of the game) infront of the 3rd and after the 3RD it doesn't show any background.  I have no idea how fix this, and I already know it something simple. I've got the 3RD one to work, but .
Code that I'm trying to use.
<code> public void Update(GameTime gameTime)
    {
        bgPos0.Y += speed;
        bgPos1.Y += speed;
        bgPos2.Y += speed;

        if (bgPos0.Y >= 950)
        {
            bgPos1.Y = -950;

            if (bgPos1.Y >= 950) // Doesn't go fully down.
            {
                bgPos2.Y = -950;

                if (bgPos2.Y >= 950)
                {
                    bgPos0.Y = 0; //(Try to change it to -950 still doesn't work. I guest it due to that bgPos0 is set to 0, 0)
                }
            }
        }
    }
</code>
And the Vector2 code for the pos are
<code>        bgPos0 = new Vector2(0, 0);
        bgPos1 = new Vector2(0, -950);
        bgPos2 = new Vector2(0, -1900); // Could be the large -1900 number that destroying the code. To make it not work.
</code>
So how do I fix this? I wish I could fix it right now, but I can't for some reason.
Answer: I don't think you want to have the if-statements nested.  The code you posted constantly moves the second background to -950 for as long as the first is past 950.  Since the first is constantly moved back to -950 it shouldn't ever manage to move past 950, and so it never gets into the last one.  I think what you probably want to do is something more like:
<code>public void Update(GameTime gameTime)
{
    bgPos0.Y += speed;
    if(bgPos0.Y > 950) {
        bgPos0.Y = -950;
    }

    bgPos1.Y += speed;
    if(bgPos1.Y > 950) {
        bgPos1.Y = -950;
    }

    bgPos2.Y += speed;
    if(bgPos1.Y > 950) {
        bgPos1.Y = -950;
    }

}
</code>
[EDIT]: As an aside, the number in question isn't nearly large enough to cause problems.  XNA's Vector2 class stores the x and y components as floats, and the maximum value for a float in C# is somewhere around 3.4e38 or so, and accurate to 7 digits according to MSDN.


Jolt converts JSON array to JSON Object automatically

Question: I have a json which consists a json array 'attrs'. This array contains name/value pairs so the number of objects inside it is dynamic. I know 2 name/value pairs that will always be present and i'm currently using jolt to extract them and bring them to the outermost level.
During this process, I'm seeing three scenarios
Jolt Spec used :
[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "[&1].&",
        "attrs": {
          "*": {
            "name": {
              "*": {
                "@2": "[&5].&4"
              },
              "orderType": {
                "@(2,value)": "[&5].&1"
              },
              "paymentType": {
                "@(2,value)": "[&5].&1"
              }
            }
          }
        }
      }
    }
  }
]

Scenario 1: All name/value pairs in 'attrs' were the ones I was expecting, therefor after using jolt nothing was left inside this 'attrs' and in the transformed json, this 'attrs' was not present. This was expected.
Input JSON :
[
  {
    "requestedStartDate": null,
    "cuDetails": [
      {
        "role": "Customer",
        "value": "ABX"
      },
      {
        "role": "ABC",
        "value": "ABC"
      }
    ],
    "notes": null,
    "attrs": [
      {
        "name": "orderType",
        "value": "PROVPN"
      },
      {
        "name": "paymentType",
        "value": "Upgrade/Downgrade/ChangeContractPeriod"
      }
    ]
  }
]

Output JSON :
[
  {
    "requestedStartDate": null,
    "cuDetails": [
      {
        "role": "Customer",
        "value": "ABX"
      },
      {
        "role": "ABC",
        "value": "ABC"
      }
    ],
    "notes": null,
    "orderType": "PROVPN",
    "paymentType": "Upgrade/Downgrade/ChangeContractPeriod"
  }
]

Scenario 2 : Along with the name/value pairs I was expecting, there was ONE extra name/value pair. After transformation, the expected name/value pairs are in the outermost level but the 'attrs' is transformed as an OBJECT. This was not expected, I was expecting 'attrs' to remain an array.
Input JSON :
[
  {
    "requestedStartDate": null,
    "cuDetails": [
      {
        "role": "Customer",
        "value": "ABX"
      },
      {
        "role": "ABC",
        "value": "ABC"
      }
    ],
    "notes": null,
    "attrs": [
      {
        "name": "orderType",
        "value": "PROVPN"
      },
      {
        "name": "paymentType",
        "value": "Upgrade/Downgrade/ChangeContractPeriod"
      },
      {
        "name": "deliveryType",
        "value": "CRM"
      }
    ]
  }
]

Output JSON :
[
  {
    "requestedStartDate": null,
    "cuDetails": [
      {
        "role": "Customer",
        "value": "ABX"
      },
      {
        "role": "ABC",
        "value": "ABC"
      }
    ],
    "notes": null,
    "orderType": "PROVPN",
    "paymentType": "Upgrade/Downgrade/ChangeContractPeriod",
    "attrs": {
      "name": "deliveryType",
      "value": "CRM"
    }
  }
]

Scenario 3 : Along with the name/value pairs I was expecting, there were multiple extra name/value pair. After transformation, the expected name/value pairs are in the outermost level but the 'attrs' is transformed as an ARRAY. This was expected.
Input JSON :
[
  {
    "requestedStartDate": null,
    "cuDetails": [
      {
        "role": "Customer",
        "value": "ABX"
      },
      {
        "role": "ABC",
        "value": "ABC"
      }
    ],
    "notes": null,
    "attrs": [
      {
        "name": "orderType",
        "value": "PROVPN"
      },
      {
        "name": "paymentType",
        "value": "Upgrade/Downgrade/ChangeContractPeriod"
      },
      {
        "name": "deliveryType",
        "value": "CRM"
      },
      {
        "name": "deliveryAddress",
        "value": "aBC"
      }
    ]
  }
]

Output JSON :
[
  {
    "requestedStartDate": null,
    "cuDetails": [
      {
        "role": "Customer",
        "value": "ABX"
      },
      {
        "role": "ABC",
        "value": "ABC"
      }
    ],
    "notes": null,
    "orderType": "PROVPN",
    "paymentType": "Upgrade/Downgrade/ChangeContractPeriod",
    "attrs": [
      {
        "name": "deliveryType",
        "value": "CRM"
      },
      {
        "name": "deliveryAddress",
        "value": "aBC"
      }
    ]
  }
]

Expected Output in Scenario 2 & 3 : In case that attrs JSON array is displayed, i want it to be displayed as an array not an object .
Answer: In any case the following spec will return an array for extra attrs by adding square brackets [] :
[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "[&1].&",
        "attrs": {
          "*": {
            "name": {
              "*": { // else case for "name" matches
                "@2": "[&5].&4[]"
              },
              "orderType|paymentType": {
                "@2,value": "[&5].&1"
              }
            }
          }
        }
      }
    }
  }
]


Inserir valor de Input como uma Option de um Select

Question: Boa noite!
Sou iniciante com o Vue.js, estava tentando fazer alguns testes e pequenos projetos para treinar e resolvi fazer um programa que simule um Relógio Ponto. Enfim, acabei travando nessa parte do código(logo no início --'), onde quero pegar o valor do Input e inserí-lo como uma Option de um Select, onde posteriormente vou acrescentar um button pra marcar o CheckIn/CheckOut do funcionário selecionado.
Segue o código:

<template>

      <button @click="toggleButton1 = !toggleButton1" class="btn btn-danger" type="button">New Collab</button>

      <button @click="toggleButton2 = !toggleButton2" class="btn btn-danger" type="button">Collabs</button>

    <form v-show="toggleButton1" class="newCollabForm">

        Employee
        <input type="text" class="form-control" placeholder="Collab Name" id="collabName">

        <button @click="submitCollab" class="btn btn-dark" type="submit">Submit</button>

    </form>

    <form v-show="toggleButton2" class="newCollabForm">

        Search Employee
        <select class="form-control" id="namesSelect">

          <option v-for="collab in collabNames" v-bind:key="collab.value" />

        </select>

    </form>

</template>

Os problemas:
1 - Na tag Select, ao inserir um novo valor, acaba saindo um valor em branco antes de cada nome inserido;
2 - É "correto" ou boa prática usar esse v-for na tag option? Fiquei na dúvida se não seria na tag Select;
3 - Quando eu uso a Option sem o v-for, ele só mostra o nome que foi inserido no momento do Input, mas quando eu testo um "alert(array)" pra mostrar o conteúdo da Array, todos os nomes inseridos são mostrados, só nao aparece no Select. e_e
Alguem pode dar uma luz?
Já dei uma lida na documentação (https://br.vuejs.org/v2/guide/forms.html), não achei nada parecido com isso. :/
Agradeço a atenção desde já
Comment: Se fez a parte do código tudo errado
Answer: Vou me focar na parte de adicionar um item na lista para que o seu select seja atualizado com o novo valor, ou seja, a sua lista que carrega o select a partir do momento da sua atualização automaticamente os options também são, exemplo minimo:

var vm = new Vue({
  el: '#app',
  data: {
    value: '',
    items: []
  },
  methods: {
    handleAddItem: function() {
      if (this.value.trim()){
        this.items = [...this.items, this.value];
        this.value = '';
      } else {
        alert('Digite algum valor');
      }
    }
  }
});

        <input type="text" v-model="value" />
        <button v-on:click="handleAddItem">Add Item</button>

      <select size="5" style="width:100%">
        <option
          v-for="(item,index) in items"
          v-bind:key="index">{{item}}</option>
        </select>

nesse exemplo, quando você digitar na caixa de texto algum valor e pressionar o botão o select vai ser atualizado com o novo valor, na verdade a lista criado com o nome de items é que é atualizado e consequentemente o select. Observação: foi adicionado no select um size = "10" para melhore a visualização.

1 - Na tag Select, ao inserir um novo valor, acaba saindo um valor em branco antes de cada nome inserido;

Você fez errado, não se faz programação reativa assim, sempre tem uma variável que atualiza os componentes, não é regra geral, mas, é assim que é feito em sua maioria e também é o famoso depende do seu contexto, nesse atual deve ser feito igual no exemplo acima.

2 - É "correto" ou boa prática usar esse v-for na tag option? Fiquei na dúvida se não seria na tag Select.

Na verdade não tem essa de boa prática é assim mesmo que tem que ser feito olhe um exemplo aqui no próprio site

3 - Quando eu uso a option sem o v-for, ele só mostra o nome que foi inserido no momento do input, mas quando eu testo um alert(array) pra mostrar o conteúdo da array, todos os nomes inseridos são mostrados, só não aparece no Select.

Nesse pergunta fiquei na duvida e também me parece que fez errado, como eu disse e repito sempre na programação reativa trabalhamos com as variáveis porque é assim que deve ser feito e com nessas variáveis tem os valores que necessitamos.

Estude mais, assista alguns videos e tutoriais, aqui mesmo tem bastante material e não use comandos do javascript puro (tem exceção para isso também) use sempre o que a lib vuejs te recomenda.
Comment: Muito obrigado!!


Value of the cell moves to the left after editing in the userform

Question: I have been facing a strange issue lately. So, the user has the ability to change value of the cell from the userform window, however, after apply changes somehow the values go from the right to the left (only ones with decimals) and that creates a problem when the data is read by another software (Matlab) it can not be read. I have tried to reformat it as number or general to see what happens but nothing. The only thing that changes it back to the right is (find & Replace "," with ","). Anyone knows why this happens? Any solutions ? (see picture for demonstration)
Comment: Maybe look in the code for the user form. As I understand it the edit box treats everything as a string. So when the number goes initially from the sheet to the form it is converted into a string. Hence when it is written back, the sheet thinks it's a string. In the code underlying the form you need to intervene and turn the string back to a number (eg using CDbl() ). If you enter a value (or change) a number directly on the sheet, Excel will try and be 'helpful' and convert things that look like numbers into numbers (it does the same with dates).
Comment: My guess is that the ones formatted to the left are strings, and the ones to the right are numbers, right? It's odd that replacing the comma turns it back into a number, while formatting as a number does not. How does the useform aplly the value? Maybe you can change that.
Comment: @DS_London Worked magically. Thank you for this tip.
Answer: Maybe look in the code for the user form. As I understand it the edit box treats everything as a string. So when the number goes initially from the sheet to the form it is converted into a string. Hence when it is written back, the sheet thinks it's a string. In the code underlying the form you need to intervene and turn the string back to a number (eg using CDbl() ). If you enter a value (or change) a number directly on the sheet, Excel will try and be 'helpful' and convert things that look like numbers into numbers (it does the same with dates). – Solution by @DS_London
Comment: It is worth remembering that there is a difference between the value that Excel stores, and the how it is formatted and displayed. Excel (typically) stores values as numbers or strings. Changing the display format of a value does not change its underlying type. Eg there is no underlying Excel type of 'Date' in a spreadsheet: dates are stored as numbers. It is only the formatting that shows the value as a recognizable date. The way to see a value's is to select the cell and hit 'Shift-Ctrl-#'. This removes any formatting of the value.


Theano Ubuntu 12 cuda

Question: my question is the next one:
I use theano on ubuntu 14 and configure theano flags by editing .theanorc. To use cuda, I only have to add:
[cuda]
root=/usr/local/cudaVersion/

And everything goes, theano is capable of finding nvcc, the libs and everything, I do not have to add cudaRoot to the $PATH or the library directory to $LD_LIBRARY_PATH.
In ubuntu 12 this does not happens. If I create the .theanorc in the same way, theano is only capable of finding nvcc but not the library, and I have to add /usr/local/cudaVersion/lib64 to the LD_LIBRARY_PATH enviroment variable.
The problem is that I do not like to use this enviroment variable. Does anyone knows why in ubuntu 14 only editing .theanorc is enough and in ubuntu 12 is not?
Answer: I will try to help you the best i can.
I use Theano and CUDA on Linux.
First, are you sudo in both OS's ? Did you install theano and python environment and cuda as sudo? Because, i suppose that, if the setup of CUDA wasnt done on global library path, then it wont be automatically detected.
Also, according to the official website of theano:
http://deeplearning.net/software/theano/install_ubuntu.html#install-ubuntu
Quoting :

For Ubuntu 11.10 through 14.04:
sudo apt-get install python-numpy python-scipy python-dev python-pip
  python-nose g++ libopenblas-dev git sudo pip install Theano
On 14.04, this will install Python 2 by default. If you want to use
  Python 3:
sudo apt-get install python3-numpy python3-scipy python3-dev
  python3-pip python3-nose g++ libopenblas-dev git sudo pip install
  Theano
For Ubuntu 11.04:
sudo apt-get install python-numpy python-scipy python-dev python-pip
  python-nose g++ git libatlas3gf-base libatlas-dev sudo pip install
  Theano

So did you follow these instructions? They might be the cause.
Also, There is additional instructions to setting up cuda for theano, on the same page:

Ubuntu 11.10/12.04 (probably work on 11.04 too):
sudo apt-add-repository ppa:ubuntu-x-swat/x-updates sudo apt-get
  update sudo apt-get install nvidia-current
Ubuntu 14.04:
sudo apt-get install nvidia-current sudo apt-get install
  nvidia-cuda-toolkit

The questions below might also help if the above didnt solve it.
As described on the references, did you edit .bashrc properly?
How did you install CUDA on both OS's?
Did you try to uninstall CUDA,Theano and python environments and install them again?
Its probably worth to edit the question with more info if these didnt help!
Extra references:
https://groups.google.com/forum/#!topic/theano-users/RRqYTf42YIo
http://dhaneshr.net/2015/09/10/setting-up-cudnn-and-theano-on-ubuntu-14-04-and-15-10/

Theano Ubuntu 12 cuda


Calculating variance of joint pdf.

Question:
I am having problem in settling the domain. I usually draw graph in these type of question but can't.
$0<|x_1|\leq x_2<\infty$
If $x_1$ is greater than zero whats the point of modulus? Plus integral is scary.
Comment: Better brackets:  $V(X_1)=E(X_1^2) - (E(X_1))^{2}$
Comment: I have to follow normal method of calculating Variance no trick here? $V(X_1)=E(X_1)^{2} - (E(X_1))^{2}$
Answer: Hints

$X_2$ is almost surely positive.
$-X_2 \le X_1 \le X_2$ and indeed given $X_2=x_2$, you have $X_1$ conditionally uniformly distributed on $[-x_2,x_2]$
$E[X_1]$ should be obvious
Law of total variance: $\operatorname{Var}(Y)=\operatorname{E}[\operatorname{Var}(Y\mid X)] + \operatorname{Var}(\operatorname{E}[Y\mid X])$
$\int \frac{e^{-x^2/2}}{x}\,dx$ may be horrible, but multiplying by $x^2$ you should find  $\int x e^{-x^2/2}\,dx$ much easier
Comment: To calculate $E(X_1)$ we will be multiplying with $x_1$ how will it cancel denominator $x_2$?
Comment: Ohhh the other formula godammit.I got it now .
Comment: Can you solve it for me I ll have an idea how to these types next time ?

Calculating variance of joint pdf.


Call to undefined function db_set_active()

Question: I sure I have succeed to use these snippets in previous code, but now I get a "Call to undefined function db_set_active()" error. I don't understand why.
public function allUnits() {
  global $dbUtil;

  $list = array();
  $qryStr = "SELECT * FROM unit ORDER BY u_id";

  db_set_active('mpd_pro');
  $rs = db_query($qryStr);

  while ($row = $rs->fetchAssoc()) {
    $list[$row["u_id"]] = $row;
  }

  db_set_active('default');

  return ($list);
}

Comment: You may missing some files during the transfer. Try a new Drupal installation.
Comment: But I have the latest core.
Comment: Is this even Drupal code??? How is this function called?
Answer: The 2 things that come to mind: your installation is  not bootstrapping properly (improperly configured .htaccess or settings.php) , or you installation is corrupt.
I would recheck the apache logs, watchdog logs to see if any errors are mentionned, if all fails I would see if the application works with this module disabled, because this function is defined in core on line 2519 in includes/database/database.inc and should be available from all your custom module code.
Hope this helps, cheers!
Comment: I sure this is not the installation issue. Because I run code A is succeed, but when the code run to code B, I got this error message. so I don't know why.
Comment: I know you are doubtful, but there cannot be many other reasons. Maybe permission errors, this is why I advised you to check the logs. What os are you using?  find the apache error logs and your watchdog logs and check if anything is in there to clue you in.  This is most certainly a configuration / permission problem,  seeing as how this application is installed and running *on millions of sites*, with db_set_active properly defined. Good-luck friend.
Comment: Unfortunately, I only see "PHP Fatal error:  Call to undefined function db_set_active() in D:\xampp\htdocs\drupal\mat\classes\UnitUtil.class.php on line 60" in php_error_log...
Answer: If that code is called from hook_exit(), then it can be called when Drupal bootstrap didn't initialize the database system.
In any case, calling drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE) would assure the database system is initialized.
public function allUnits() {
  global $dbUtil;

  $list = array();
  $qryStr = "SELECT * FROM unit ORDER BY u_id";

  drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
  db_set_active('mpd_pro');
  $rs = db_query($qryStr);

  while ($row = $rs->fetchAssoc()) {
    $list[$row["u_id"]] = $row;
  }

  db_set_active('default');

  return ($list);
}

If that doesn't help, then there is effectively something wrong. As stefgosselin said, it could be a configuration problem, or the database.inc file is corrupted, and db_set_active() is not found there. If the latter were the case, the site would be problems even when you try accessing the front page; the same is true if your site has problem bootstrapping.


Indexing large 2d numpy array by conditions

Question: I have a 2D NumPy array that of shape (1500, 3712). I want to find the indices of the array that have values between -10 and -40. So far I have:
for item in lon_array:
    for value in item:
        if value >= -40 and value <= -10:
            find_index = np.where(lon_array == value)
            index = np.asarray(find_index).T

Since it is a really big array, is there any way to make this faster?
Comment: can u please add 2D array having length may be 5 or 6
Comment: Is it necessarily a numpy array? If so, then add the [tag:numpy] tag. Or is using numpy just an attempt to find the indices of the matching item and your "array" is really an ordinary list of lists?
Answer: Assuming your lon_array is a NumPy array you can use the following methods:
find_index = np.where(np.logical_and(lon_array >= -40, lon_arr <= -10))
index =  np.asarray(find_index).T

Since np.where takes only one condition, you can combine two to get the between condition with np.logical_and.
It can be done as a one-liner too:
>>> lon_arr
array([[ 20, -40],
       [ 30, -30],
       [ 20, -14],
       [ 30, -30]])
>>> np.asarray(np.where(np.logical_and(lon_arr>=-40, lon_arr<=-10))).T
array([[0, 1],
       [1, 1],
       [2, 1],
       [3, 1]])

Answer: If lon_array is a list of lists (built-in basic data type of Python), using enumerate(...)would be the best approach to know the indices of an element:
for y, row in enumerate(lon_array):
    for x, value in enumerate(row):
        if -40 <= value <= -10:
            index = (y, x)
            # do something useful with it...

Answer: With numpy.where, you can extract the indices based on the value of your data, and keep the iterations over your data executed in the optimized c code on to which numpy is built:
import numpy as np

x = np.random.random(10).reshape(2, 5)
print(x)
indices = np.where(x < 0.2)  #<--- this selects the indices based on a filter
print(indices)
x[indices]

output:
[[ 0.11129659  0.33608351  0.07542966  0.44118394  0.14848829]
 [ 0.8475123   0.27994122  0.91797756  0.02662857  0.52820238]]

# These are the indices produced by np.where:
# the first array contains the rows `i` and the second the columns `j`
(array([0, 0, 0, 1]), array([0, 2, 4, 3]))

array([ 0.11129659,  0.07542966,  0.14848829,  0.02662857])

Because you have two conditions in your filter, I suggest you use the following construct that allows to build a more complex boolean expression than what np.where directly accepts:
indices = np.where(np.logical_or(x < 0.2, x > 0.8))

Answer: For completeness, you could use numpy.indices as an alternative to the numpy.where based solution that was proposed in other answers:
In [1245]: lon_array = np.linspace(-70, 20, 10).reshape(2, 5)

In [1246]: lon_array
Out[1246]:
array([[-70., -60., -50., -40., -30.],
       [-20., -10.,   0.,  10.,  20.]])

In [1247]: idx = np.nonzero(np.logical_and(lon_array >= -40, lon_array <= -10))

In [1248]: idx
Out[1248]: (array([0, 0, 1, 1], dtype=int64), array([3, 4, 0, 1], dtype=int64))

In [1249]: lon_array[idx]
Out[1249]: array([-40., -30., -20., -10.])

The demo above shows that NumPy's nonzero returns a tuple of 1D arrays which triggers advanced indexing when used as a selection object.


JavaFX : TableView ToogleButton Column

Question: My TableView has a column with a ToggleButton. All the buttons belong to one group, you can only select one button (one row).
But my TableView has a lot of rows and the ToggleGroup seems to work.
That is until I scroll drown.
When I select one ToggleButton and scroll down no other button should be selected but there is always one that is selected per view.
Is this fixable?
Edit: Here is a SSCCE :
MainApp.java :
package p1;
import java.io.IOException;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

public class MainApp extends Application {

private Stage primaryStage;
private AnchorPane rootLayout;
private ObservableList<Person> personData = FXCollections.observableArrayList();

public MainApp(){
  for(int i=0;i<40;i++){
       personData.add(new Person("person " +i));
  }
}
public ObservableList<Person> getPersonData(){
    return personData;
}
@Override
public void start(Stage primaryStage) throws Exception {
    this.primaryStage = primaryStage;
    try{
        FXMLLoader loader =new FXMLLoader();
        loader.setLocation(MainApp.class.getResource("People.fxml"));
        rootLayout = (AnchorPane)loader.load();
        Scene scene = new Scene(rootLayout);
        primaryStage.setScene(scene);
        primaryStage.show();
        PeopleController controller = loader.getController();
        controller.setMainApp(this);
    } catch(IOException e){
        e.printStackTrace();
    }
}
public Stage getPrimaryStage(){
    return primaryStage;
}
public static void main(String[] args){
    launch(args);
}}

People.fxml :
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="p1.PeopleController">
<children>
<TableView fx:id="personTable" layoutX="160.0" layoutY="49.0"  prefHeight="351.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="49.0">
 <columns>
      <TableColumn fx:id="nameColumn" prefWidth="75.0" text="Name" />
      <TableColumn fx:id="previewColumn" prefWidth="75.0" text="Preview"/>
    </columns>
  </TableView>
  </children>
  </AnchorPane>

PeopleController.java :
package p1;
import com.sun.prism.impl.Disposer;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.util.Callback;

public class PeopleController{

@FXML private TableView<Person> personTable;
@FXML private TableColumn<Person, String> nameColumn;
@FXML private TableColumn previewColumn;
private MainApp mainApp;
final ToggleGroup group = new ToggleGroup();

@FXML
public void initialize() {
    nameColumn.setCellValueFactory(cellData -> cellData.getValue().NameProperty());
    previewColumn.setCellFactory(
            new Callback<TableColumn<Disposer.Record, Boolean>, TableCell<Disposer.Record, Boolean>>() {

        @Override
        public TableCell<Disposer.Record, Boolean> call(TableColumn<Disposer.Record, Boolean> p) {
            ButtonCell cell = new ButtonCell(group);
            cell.setAlignment(Pos.CENTER);
            return cell;
        }
    });
}
public void setMainApp(MainApp mainApp){
    this.mainApp = mainApp;
    personTable.setItems(mainApp.getPersonData());
}
public class ButtonCell extends TableCell<Disposer.Record, Boolean> {

    final ToggleButton cellButton = new ToggleButton("click");

    public ButtonCell(ToggleGroup group){
         cellButton.setToggleGroup(group);
    }
    @Override
    protected void updateItem(Boolean t, boolean empty) {
        super.updateItem(t, empty);
        if(!empty){
            setGraphic(cellButton);
        }
    }}}

Person.java :
package p1;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class Person {
private final StringProperty name;
public Person(){
    this(null);
}
public Person(String name){
this.name = new SimpleStringProperty(name);
}
public String getName(){
    return name.get();
}
public void setName(String name){
    this.name.set(name);
}
public StringProperty NameProperty(){
    return name;
} }

Comment: please show a SSCCE that demonstrates the problem
Comment: I added a SSCCE is this good? @kleopatra
Comment: yeah, thanks - now see what you mean :-) You can't manage the state in the view (aka: ToggleGroup), because the cells are re-used and then don't correspond any longer to the initial row. Instead, keep the state in some data model and update as needed. Unrelated: better stick to javafx naming conventions, should be _nameProperty_
Answer: The reason that the toggle seems to "jump" when scrolling is the re-use of the cells: the selected state sticks to the button, not the item. Consequently, you can't use a toggleGroup (except in the not-so-common and not recommended case that the items in your data implement Toggle) to keep the toggle state. You need to implement the toggle-logic yourself.
One option is a custom SingleSelectionModel and a custom ButtonCell that talks to the model (as do all other collaborators). Unfortunately, FX doesn't have a publicly accessible concrete implementation of the model. As often, the heavy lifting - which in this case is to update itself on modifications to the items - is left to client code (and not done in this example as well ;-)
Something like:
public class ToggleButtonTableExample extends Application {

    public static class DataSelectionModel<S> extends SingleSelectionModel<S> {

        private ListProperty<S> listProperty;

        public DataSelectionModel(Property<ObservableList<S>> items) {
            //listProperty = BugPropertyAdapters.listProperty(items);
            listProperty = new SimpleListProperty<>();
            listProperty.bindBidirectional(items);
            ListChangeListener<S> itemsContentObserver = c -> {
                itemsChanged(c);
            };
            listProperty.addListener(itemsContentObserver);
        }

        protected void itemsChanged(Change<? extends S> c) {
            // TODO need to implement update on modificatins to the underlying list
        }

        @Override
        protected S getModelItem(int index) {
            if (index < 0 || index >= getItemCount()) return null;
            return listProperty.get(index);
        }

        @Override
        protected int getItemCount() {
            return listProperty.getSize();
        }

    }

    public static class ButtonCellX<S, T> extends TableCell<S, T> {

        private ToggleButton cellButton;
        private SingleSelectionModel<S> model;

        public ButtonCellX(SingleSelectionModel<S> group) {
            this.model = group;
            cellButton = new ToggleButton("click");
            cellButton.setOnAction(e -> updateToggle());
            updateToggle();
            setAlignment(Pos.CENTER);
        }

        protected void updateToggle() {
            model.select(cellButton.isSelected()? getIndex() : -1);
        }

        @Override
        protected void updateItem(T t, boolean empty) {
            super.updateItem(t, empty);
            if (empty) {
                setGraphic(null);
            } else {
                cellButton.setSelected(model.isSelected(getIndex()));
                setGraphic(cellButton);
            }
        }
    }

    private Parent getContent() {
        TableView<Person> table = new TableView<>();
        table.setItems(Person.persons());
        TableColumn<Person, String> name = new TableColumn<>("Name");
        name.setCellValueFactory(new PropertyValueFactory<>("lastName"));

        SingleSelectionModel<Person> model = new DataSelectionModel<>(table.itemsProperty());
        TableColumn<Person, Boolean> toggle = new TableColumn<>("Preview");
        toggle.setCellFactory(c -> new ButtonCellX<Person, Boolean>(model));

        toggle.setCellValueFactory(f -> {
            Object value = f.getValue();
            return Bindings.equal(value, model.selectedItemProperty());
        });

        table.getColumns().addAll(name, toggle);

        Button select = new Button("Select 0");
        select.setOnAction(e -> {
            model.select(0);
        });
        VBox content = new VBox(10, table, select);
        return content;
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setScene(new Scene(getContent()));
        //primaryStage.setTitle(FXUtils.version());
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    @SuppressWarnings("unused")
    private static final Logger LOG = Logger
            .getLogger(ChoiceBoxTableCellDynamic.class.getName());

}

JavaFX : TableView ToogleButton Column


OpenSearch return different results when using parenthesis

Question: I am using OpenSearch to make query to documents in my database, currently I am doing this search (I'm using default_operator=AND, and the terms between "" are terms 1 4 and 5 are terms of two words that I'm omitting,i.e: "foo bar"):
"term 1" term2 term3 "term 4" OR "term 5"
but when I look at my result, there are documents that have just "term 1" term2 term3. This changes if I add parentheses, this search returns what I want:
("term 1" term2 term3 "term 4") OR ("term 5")
Is there any sense to have difference between the results of these queries?
I also tried to change the "term 4" position to:
"term 1" "term 4" term2 term3 OR "term 5"
and the results also are differents from the results of the first query, and for me it doesn't make sense.
This is an example of an almost full query:
{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "should": [
              {
                "query_string": {
                  "query": "\"term 1\" term2 term3 \"term 4\" OR \"term 5\"",
                  "fields": [
                    "my_field.analyzed"
                  ],
                  "default_operator": "AND",
                  "boost": 0.1
                }
              },
              {
                "query_string": {
                  "query": "\"term 1\" term2 term3 \"term 4\" OR \"term 5\"",
                  "fields": [
                    "my_field_2",
                    "my_field_3"
                  ],
                  "boost": 0.5
                }
              }
            ]
          }
        },
        {
          "exists": {
            "field": "my_field"
          }
        }
      ],

Answer: It is worth noting that the boolean operators DO NOT follow the usual precedence rules (another example here and some more thoughts here).
If you're a JavaCC afficionado, you can also check the compiler definition for Lucene's query string parser. You'll see that the query is parsed sequentially, i.e. there's no precedence as you would expect, except when properly specifying parenthesis.
The main take away from the last link is that instead of thinking in terms of boolean operations, you need to think in terms of OPTIONAL, REQUIRED (i.e. +), and PROHIBITED (i.e. -)
Using the Validate API, you can see what's executed on the Lucene side. For instance, the first query below
          {
            "query_string": {
              "query": "\"term 1\" term2 term3 \"term 4\" OR \"term 5\"",
              "fields": [
                "my_field.analyzed"
              ],
              "default_operator": "AND",
              "boost": 0.1
            }
          },

is executed as
(
  +my_field.analyzed:term 1
  +my_field.analyzed:term2 term3
  my_field.analyzed:term 4
  my_field.analyzed:term 5
)^0.1

So,

term 1 is required
term2 term3 (both are concatenated together) is required
term 4 and term 5 are optional

Regarding the second query,
          {
            "query_string": {
              "query": "\"term 1\" term2 term3 \"term 4\" OR \"term 5\"",
              "fields": [
                "my_field_2",
                "my_field_3"
              ],
              "boost": 0.5
            }
          }

it is executed as
+(
  +(my_field_2:term 1 | my_field_3:term 1)
  +(my_field_2:term2 term3 | my_field_3:term2 term3)
  (my_field_2:term 4 | my_field_3:term 4)
  (my_field_2:term 5 | my_field_3:term 5)
)^0.1

So:

term 1 must be present in either my_field_2 or my_field_3
term2 term3 must be present in either my_field_2 or my_field_3
term 4 can be present in either my_field_2 or my_field_3
term 5 can be present in either my_field_2 or my_field_3
at least one of the above must match (i.e. the initial + at the very beginning)


Integral of Devil´s staircase in $[0,1]$.

Question: I have a question about the integral in $[0,1]$ of the devil´s staircase function. It seems to me that is going to be $1$ but  i got it more or less intuitive and i cant make up a mathematical argument to prove it. Is it $1$ ? And how do i prove it ? Thanks.
After some thought i got this , let F be the devils staircase,
$\int_{0}^{1}F(x)$ = $lim_{n\to\infty}\int_{0}^{1} g_n(x)$
where $g_n= (3/2)^n\int_{0}^{x}f_n(t) dt$
where $f_n$ is the caratheristic function of a certain $F_n$ when we construct the cantor set has $C(I)=\bigcap{F_n}$
Comment: If $f$ is that function, how is $f(x)$ related to $f(1-x)$?  They have the same integral, and their sum is ...
Comment: Although the function is not piecewise linear, it is the pointwise limit of piecewise functions. Try  integrating each piecewise linear function, and then swapping the integral and the limit using your choice of convergence theorem. Edit: Even better! The convergence is actually uniform.
Comment: The arc length is $2$
Comment: I dont really understand the question.
Comment: Length of the graph is not $1$.
Comment: Ah damn, then what is it ?
Comment: The graph connects $(0,1)$ to $(1,1)$, so its length is **at least** $\sqrt{2}$.  The length would be equal to $\sqrt{2}$ only for the straight line segment.
Comment: Yes but my problem was calculating the integral of each piecewise function cause we get an integral inside an integral and i wasnt finding a good way to deal with it.
Comment: But what is the value of the integral is it 1?
Comment: Are you trying to compute the length of the graph or the area underneath it?
Comment: First i was trying to do the integral but i got stuck and then i tried the lenght of the graph and i also got stuck , so both i guess.
Comment: Ive tried some more calculus for the lenght of the graph and im getting some results, Does anyone know how much it is supossed to give?
Answer: Let $F : [0, 1] \to [0, 1]$ denote the Cantor function.

$F$ is monotone-increasing and satisfies $F(x) + F(1-x) = 1$. So,
$$ \int_{0}^{1} F(x) \, \mathrm{d}x = \frac{1}{2} \int_{0}^{1} [F(x) + F(1-x)] \, \mathrm{d}x = \frac{1}{2}. $$
For any continuous monotone-increasing function $f : [0, 1] \to [0, 1]$ with $f(0) = 0$ and $f(1) = 1$, we have
$$ \sum_{i=1}^{n} \| (x_i, f(x_i)) - (x_{i-1}, f(x_{i-1})) \| \leq \sum_{i=1}^{n} \left[ (x_i - x_{i-1}) + (f(x_i) - f(x_{i-1})) \right] = 2 $$
for any partition $\{0 = x_0 < \cdots < x_n = 1\}$ of $[0, 1]$. Taking supremum over all the partitions of $[0 1]$ shows that the length of the graph of $f$ is $\leq 2$.
For the Cantor's function, this upper bound is actually achieved. Indeed, for each given $n \geq 1$, consider the partition $\{x_k\}_{k=0}^{3^n}$ given by $x_i = i/3^n$. Then
\begin{align*}
\text{[length of $F$]}
&\geq \sum_{i=1}^{3^n} \| (x_i, f(x_i)) - (x_{i-1}, f(x_{i-1})) \| \\
&= 2^n \sqrt{\frac{1}{2^{2n}} + \frac{1}{3^{2n}}} + (3^n - 2^n)\frac{1}{3^n} \\
&\xrightarrow[n\to\infty]{} 2.
\end{align*}
Intuitively, this is because the graph of $F$ consists of 'infinitesimally small stairs', and any increasing stair from $(0, 0)$ to $(1, 1)$ has length $2$.
Comment: Thanks !!!! I didnt know about that first identity, is it easy to prove? Also i dont understand how u make that step in the integral.
Comment: @PedroSantos Under the standard iterative construction (such as your $g_n$'s), all the intermediate functions $g_n$ also satisfy $g_n(x) + g_n(1-x) = 1$. So the identity follows by taking limit as $n\to\infty$. :)
Comment: Alright thank you my friend!


Proof verification : $f$ is continuous at $c$ $\Leftrightarrow$ $f$ has zero-jump at $c$ for increasing $f$

Question: The Problem : Let $J \subseteq \mathbb{R}$ be an interval and $f : J \to \mathbb{R}$ be increasing. Define the jump at the point $c$ as follows:
$j_f(c)=\lim_{x \to c+}f(x)-\lim_{x \to c-}f(x)$ if $c \in J$ is not an end-point of $J.$
$j_f(c)=\lim_{x \to c+}f(x)-f(c)$ if $c \in J$ is the left end-point of $J.$
$j_f(c)=f(c)-\lim_{x \to c-}f(x)$ if $c \in J$ is the right end-point of $J.$
To show that $f$ is continuous at $c \in J$ iff $j_f(c)=0.$
I'm attaching my solution (A few pieces of argument is marked as informal as they are similar to the previous line of argument and hence not elaborated). Please notify if there's any gap/flaws in the arguments, also whether it could be made shorter by any other technique. Any comment/suggestion regarding this proof, or maybe in general context (style of proof-writing etc), would be greatly appreciated. Thank you.
My Solution :
$(\Rightarrow)$ part : Suppose $c$ is not an end-point of $J$. Given $f$ is continuous at $c.$ Fix $\epsilon > 0.$ Then $\exists \delta > 0$ such that $x \in (c-\delta,c+\delta) \cap J \Rightarrow |f(x)-f(c)| < \epsilon.$ Hence $$x \in (c-\delta,c) \cap J \Rightarrow |f(x)-f(c)| < \epsilon \tag 1$$
$$x \in (c,c+\delta) \cap J \Rightarrow |f(x)-f(c)| < \epsilon \tag 2$$ Since $\epsilon > 0$ is arbitrary, we conclude from $(1)$ that $\lim_{x \to c-}f(x)=f(c)$ and from $(2)$ that $\lim_{x \to c+}f(x)=f(c).$ Hence $j_f(c)=\lim_{x \to c+}f(x)-\lim_{x \to c-}f(x)=f(c)-f(c)=0.$
Now suppose $c$ is the left end-point of $J$. Given $f$ is continuous at $c.$ Then $\exists \delta > 0$ such that $x \in (c-\delta,c+\delta) \cap J = [c,c+\delta) \cap J \Rightarrow |f(x)-f(c)| < \epsilon.$ So, $x \in (c,c+\delta) \cap J \Rightarrow |f(x)-f(c)| < \epsilon.$ Thus $\lim_{x \to c+}f(x)=f(c),$ and hence $j_f(c)=0.$
Informal : Similarly, if $c$ is the right-end point of $J,$ we obtain $j_f(c)=0.$
Note : We did not need the fact that $f$ is an increasing function to establish this side of the equivalence.
$(\Leftarrow)$ part : Suppose $c$ is not an end-point of $J.$ Now $j_f(c)=0 \Leftrightarrow \lim_{x \to c-}f(x)=\lim_{x \to c+}f(x)=l$ $($let$).$ Thus $\exists \delta_1>0$ and $\delta_2>0$ such that
$$x \in (c-\delta_1, c) \cap J \setminus \{c\} \Rightarrow |f(x)-l|<\epsilon$$
$$x \in (c, c+\delta_2) \cap J \setminus \{c\} \Rightarrow |f(x)-l|<\epsilon$$
Let $\delta=min\{\delta_1, \delta_2\}>0$. Then
$$x \in (c-\delta, c+\delta) \cap J \setminus \{c\} \Rightarrow |f(x)-l|<\epsilon \tag 3$$
Claim : $l=f(c).$
We prove the claim by contradiction. First we assume $l<f(c).$ Choose $\epsilon = \frac{f(c)-l}{2}>0.$ Then $\exists \delta_3>0$ such that
$x \in (c-\delta_3,c+\delta_3) \cap J \setminus \{c\} \Rightarrow |f(x)-l|<\epsilon,$ in particular $f(c+\frac{\delta_3}{2})<l+\epsilon=\frac{l+f(c)}{2}<f(c),$ which is a contradiction since $f$ is increasing.
Informal : If otherwise, let $l>f(c),$ we similarly choose $\epsilon=\frac{l-f(c)}{2}>0$ and a corresponding $\delta_4>0.$ Check that $f(c-\frac{\delta_4}{2})>f(c),$ contradicting the fact that $f$ is increasing.
Hence we conclude (by trichotomy law of real numbers) that $l=f(c).$ Now, putting $l=f(c)$ in $(3)$ and noting that $x=c \Rightarrow |f(x)-f(c)|=0<\epsilon,$ we obtain
$$x \in (c-\delta, c+\delta) \cap J \Rightarrow |f(x)-f(c)|<\epsilon \tag 4$$
Since $\epsilon>0$ is arbitrary, we conclude that $f$ is continuous at $c.$
Now suppose $c$ is the left end-point of $J.$ Then $j_f(c)=0 \Leftrightarrow \lim_{x \to c+}f(x)=f(c),$ i.e. given $\epsilon>0, \exists \delta > 0,$ such that $x \in (c, c+\delta) \cap J \Rightarrow |f(x)-f(c)|<\epsilon.$ At $x=c,$ obviously $|f(x)-f(c)|=0<\epsilon.$ Thus $x \in (c-\delta, c+\delta) \cap J \Rightarrow |f(x)-f(c)|<\epsilon,$ and hence $f$ is continuous at $c.$
Informal : Similarly if $c$ is the right end-point of $J,$ we have $j_f(c)=0 \Rightarrow$ $f$ is continuous at $c.$
This completes the proof. $\square$
Answer: Your proof seems correct!
Also You could simply say since $f$ is increasing then
$$L(c):= \lim_{x \to c-}f(x) \leq f(c) \leq \lim_{x \to c+}f(x)=R(c)  $$
(for end points one of these two limit is same as $f(c)$)
Now, under the assumption that $f$ is increasing
$$j_f(c)=0  \quad \text{iff}  \quad L(c)=R(c)=f(c) \quad \text{iff} \quad\text{   f is continuous at $c$}$$


org.springframework.beans.BeanUtils.copyProperties(Object source, Object target) throws error Could not copy property 'channel' from source to target

Question: This is the source class:
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
@JsonSerialize(as = RequestContext.class)
public class RequestContext implements Serializable {

    private static final long serialVersionUID = 1L;

    private String statusCode;

    private String statusType;

    private String txnId;

    private int channelId;

    private String channel;

}

These are the target class and its parent classes:
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
@JsonSerialize(as = Transaction.class)
public class Transaction extends TransactionBase implements Serializable {

    private static final long serialVersionUID = 1L;

    private Actors actors = Actors.SENDER;
    private PartnerMaster senderPartner;
    private PartnerMaster receiverPartner;
    private PartnerMaster userPartner;
    private UserMaster senderUser;
    private UserMaster receiverUser;

    private WalletAction adjustmentType;
    private BigDecimal netAmount = BigDecimal.ZERO;
    private BigDecimal amount = BigDecimal.ZERO;
    private BigDecimal rollbackAmount = BigDecimal.ZERO;

    private Charges charges = new Charges();

    private List<SystemWalletMaster> systemWallets = new ArrayList<>();
    private List<SystemCdrBean> systemCdr = new ArrayList<>();

    private List<Items> products;

    /** generic params for dynamic values. **/
    private HashMap<String, Object> genericParams = new HashMap<>();

}

@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
@AllArgsConstructor
public class TransactionBase extends TransactionFlags implements Serializable {

    private static final long serialVersionUID = 1L;

    private int channelId;
    private String channel;
    private String mvnoId;

    private ServiceMaster service = new ServiceMaster();

    private String featureId;

    private String statusCode;
    private String statusCodeReceiver;
    private String statusType;
    private String txnType;
    private String message;

    private String txnId;
    private String requestId;
    private long duration;

    private TransactionCommon transactionCommon;

}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class TransactionFlags implements Serializable {

    private static final long serialVersionUID = 1L;

    /** flags . **/
    private boolean rollback;

    private boolean adjustment;
    private boolean adjustmentSystem;
    private boolean isWhitelisted;
    private boolean adjustCommission;
    private boolean adjustFee;
    private boolean adjustSystemCommission;
    private boolean adjustSystemFee;
    private boolean isLimitExists;
    private boolean isLimitAllServices;
    private boolean isApprovalEnabled;

}

Beans copy:
@Component
@Slf4j
public class RequestInterceptor implements HandlerInterceptor {

    @Autowired
    private Transaction transaction;

    @Autowired
    private RequestContext requestContext;

    @Autowired
    private UserContext userContext;

    @Autowired
    private CopyPropertyUtils copyPropertyUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if (log.isDebugEnabled())
            log.debug("{}Inside MFS Builder, building Transaction request", CONVERTER);

        copyPropertyUtils.copy(requestContext, transaction);

        ..............
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // No implementation is done in post handle of the intercepter
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

        ..................
    }

}

When we try to copy RequestContext to Transaction we get this error
java.lang.IllegalArgumentException: object is not an instance of declaring class
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[?:?]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[?:?]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:352) ~[spring-aop-6.1.1.jar:6.1.1]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:196) ~[spring-aop-6.1.1.jar:6.1.1]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-6.1.1.jar:6.1.1]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:765) ~[spring-aop-6.1.1.jar:6.1.1]
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:137) ~[spring-aop-6.1.1.jar:6.1.1]
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:124) ~[spring-aop-6.1.1.jar:6.1.1]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.1.1.jar:6.1.1]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:765) ~[spring-aop-6.1.1.jar:6.1.1]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:717) ~[spring-aop-6.1.1.jar:6.1.1]
    at com.sixdee.mfs.base.beans.Transaction$$SpringCGLIB$$0.setChannel(<generated>) ~[classes/:?]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[?:?]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[?:?]

Followed by this:
[2m2024-03-08T12:37:20.803+05:30[0;39m [31mERROR[0;39m [35m20264[0;39m [2m---[0;39m [2m${sys:LOGGED_APPLICATION_NAME}[nio-9110-exec-1][0;39m [36mc.s.d.b.e.ResponseErrorHandler          [0;39m [2m:[0;39m Resource Not Found : object is not an instance of declaring class CLASS jdk.internal.reflect.NativeMethodAccessorImpl LINE -2
[2m2024-03-08T12:37:20.836+05:30[0;39m [33m WARN[0;39m [35m20264[0;39m [2m---[0;39m [2m${sys:LOGGED_APPLICATION_NAME}[nio-9110-exec-1][0;39m [36m.m.m.a.ExceptionHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.beans.FatalBeanException: Could not copy property 'channel' from source to target]
[2m2024-03-08T12:37:20.836+05:30[0;39m [32mDEBUG[0;39m [35m20264[0;39m [2m---[0;39m [2m${sys:LOGGED_APPLICATION_NAME}[nio-9110-exec-1][0;39m [36mc.s.m.b.s.e.EventManager                [0;39m [2m:[0;39m Event management is in progress...
[2m2024-03-08T12:37:20.836+05:30[0;39m [31mERROR[0;39m [35m20264[0;39m [2m---[0;39m [2m${sys:LOGGED_APPLICATION_NAME}[nio-9110-exec-1][0;39m [36mo.s.w.s.HandlerExecutionChain           [0;39m [2m:[0;39m HandlerInterceptor.afterCompletion threw exception

org.springframework.aop.AopInvocationException: AOP configuration seems to be invalid: tried calling method [public java.lang.String com.sixdee.mfs.base.beans.Transaction.toString()] on target [RequestContext(statusCode=DFS100, statusType=F, txnId=168421046664246, channelId=1, channel=PORTAL)]

All the properties required in the target (Transaction) are extended from its parent TransactionBase.

If we try to move those properties to Transaction there will be no error.
When we tried to copy new RequestContext() to new Transaction() rather than the autowired beans there was no error.
The copy worked when we removed the @Scope annotation.
We decompiled the .class file of Transaction and found that there were no inherited methods.
We gave all the annotations of Transaction to TransactionBase the error was still occurring.

We are not able to find what is causing this issue, whether it is the issue with the source (Point-3) or the issue with the target (Point-1), all we can understand is one of the object isn't available, also the property names and types are the same. According to the comment by @M. Deinum in this post I believe the issue is with the org.springframework.beans.BeanUtils but the answer says something else.
We are using @Autowired in some scenarios and @AllArgsConstructor in some other scenarios for dependency injection, would that be causing any issues? Also, the RequestContext is a bean in parent maven project and the others are in the child maven project which depends on the parent.
Versions
Java 17
Spring Boot 3.2.0
Comment: As I mentioned ni that answer (or rather comment) don't use `BeanUtils` for copying as the intend is for internal use. Use a proper mapping framework like MapStruct instead. Also `@Scope` will create a proxy for the class, which can (and thus will) lead to interesting side effects as it uses reflection to invoke things rather then direct method calls.
Comment: The root of your problem is the Cglib proxy caused by the `@Scope` as @M. Deinum says.   I think a solution lies in using some kind of Factory Bean pattern where Spring asks your code to generate a new Bean for the Web Request and then you can be in control of the Transaction/Base instantiation
Answer: when you use ScopedProxyMode.TARGET_CLASS it'll use CGLIB to create a class-based proxy. So the objects of type Transaction and RequestContext aren't the real instances, they're proxies to the concrete classes, like Andrew and M.Deinum said in the comment section. You'll need to use the concrete implementation instead of the proxy.


Root of the polynomial $\begin{bmatrix}t-a&-b\\-c&t-d\end{bmatrix}=(t-a)(t-d)-bc$ an eigenvalue

Question:
1.Let $\begin{bmatrix}a&b\\c&d\end{bmatrix}$ be a $2\times 2$ matrix in a field $K$. Show that any eigenvalue $\lambda$ of this matrix is a root of the polynomial
  $\begin{bmatrix}t-a&-b\\-c&t-d\end{bmatrix}=(t-a)(t-d)-bc$.

Conversely, show that any root of the polynomial $\begin{bmatrix}t-a&-b\\-c&t-d\end{bmatrix}=(t-a)(t-d)-bc$ is an eigenvalue of the given matrix.
  Linear Algebra, Serge Lang

It was easy to prove 1), I used $\det(A-\lambda I)=0$ to get the polynomial expression. But I have know ideia how to do the converse.
1.
$\begin{bmatrix}a&b\\c&d\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix}=\begin{bmatrix}ax+by\\cx+dy\end{bmatrix}$
In which  $ax+by=t x$  and $cx+dy=t y$
$\det\begin{bmatrix}t-a&b\\c&t-d\end{bmatrix}=(t-a)(t-d)-ab$
Question:
How do I prove 2.? May I use $\det(A-\lambda I)=0$ again?
Answer: Denote your matrix with $A$. Suppose $\lambda$ is a root of $\chi(t) = \det(tI - A) = (t-a)(t-d)-bc$, then $\det(\lambda I - A) = 0$ and hence $\lambda I - A$ is singular. We therefore have that $\ker(\lambda I - A)$ is nonzero, hence there exist $v \in V$ such that $(\lambda I-A)v = 0$ or $Av = \lambda v$. Hence $\lambda$ is an eigenvalue.


The Banach-Mazur distance is not reached

Question: Let $X,Y$ be isomorphic Banach spaces.
The Banach-Mazur distance:
$$
d(X,Y)=\inf\{\|T\| \cdot \|T^{-1}\|: T:X\longrightarrow Y \ \text{is an isomorphism} \}$$
can be rewritten as:
$$
d(X,Y)=\inf\{\|T^{-1}\|: T:X\longrightarrow Y \ \text{is an isomorphism}, \|T\|=1\}
$$
If $X,Y$ are finite dimensional spaces the infimum is reached.
But if $X,Y$ are infinite dimensional spaces the infimum is reached ?
Any hints would be appreciated.
Comment: Wojtaszczyk offers a hint for exercise II.E.3 of *Banach Spaces for Analysts*, which asks to find  non-isometric spaces $X$ and $Y$ whose Banach-Mazur distance is $1$: "Take $(p_n)_{n=1}^\infty$ and $(q_n)_{n=1}^\infty$ two disjoint sequences, dense in $[1,1.5]$ such that $p_1=1$. Take $X=\bigl(\sum_{n=1}^\infty \ell^5_{p_n}\bigr)_2$ and $Y=\bigl(\sum_{n=1}^\infty  \ell^5_{q_n}\bigr)_2$. Show that $Y$ does not contain $\ell_1^5$ isometrically."
Comment: @DavidMitra is it necessary to have $5$ in the construction? Do you know the solution?
Answer: Let's follow the hint given by Wojtaszczyk.

Take $(p_n)$ and $(q_n)$ two disjoint sequences, dense in $[1,1.5]$ such that $p_1=1$. Take $X=\left(\sum \ell_{p_n}^5\right)_2$ and $Y =\left(\sum \ell_{q_n}^5\right)_2$.

The Banach-Mazur distance is $1$ because for every $\epsilon>0$ the interval $[1,1.5]$ can be partitioned into subintervals of size $\epsilon$, each of which meets both sequences countably many times.
Now, it seems to me that the reason $Y$ does not contain an isometric copy of $\ell_1^5$ is that $Y$ is strictly convex. (If I'm right then neither $1.5$ nor $5$ are of importance; $1.5$ could be any  number in $(1,\infty)$ and $5$ could be an integer $\ge 2$.)
Indeed, suppose that $(y_n)$  and $(z_n)$ are  two nonzero elements of $Y$ such that $\|(y_n+z_n)\|_Y = \|(y_n)\|_Y+\|(z_n)\|_Y$, meaning that
$$\sqrt{\sum \left\| y_n+z_n \right\|_{q_n}^2} =  \sqrt{\sum \left\|y_n\right\|_{q_n}^2} +  \sqrt{\sum \left\|z_n\right\|_{q_n}^2} \tag1$$
By the triangle inequality and Minkowski inequality for $\ell^2$,
$$\sqrt{\sum \left\| y_n+z_n \right\|_{q_n}^2}
\le \sqrt{\sum (\left\| y_n\|_{q^n}+ \|z_n \right\|_{q_n})^2}\le \sqrt{\sum \left\|y_n\right\|_{q_n}^2} +  \sqrt{\sum \left\|z_n\right\|_{q_n}^2} \tag{2}$$
where equality must hold throughout by (1).
Since $\ell_2$ is strictly convex, equality in the second half of (2) implies that there exists $\lambda> 0$ such that  $ \|z_n\|_{q_n}=\lambda \|y_n\|_{q_n}$ for all $n$. Since each $\ell_{q_n}$ is also strictly convex, equality in the first half of (2) implies that $z_n=\lambda y_n$. Thus, $Y$ is strictly convex.
Comment: Ex 5.44 in Banach space theory. The basis for linear and non-linear analysis. M. Fabian, P. Habala, P. Hajek, V. Montesinos, V. Zizler also saves the day.
Comment: Why is $\sum \left( \frac{\|y_n\|_{q_n}+\|z_n\|_{q_n}}{2}\right)^2 \le    \frac14 \sum \left\|y_n\right\|_{q_n}^2 + \frac14 \sum \left\|z_n\right\|_{q_n}^2$ true for the second half of (2)? Should that be $\sum \left( \frac{\|y_n\|_{q_n}+\|z_n\|_{q_n}}{2}\right)^2 \le    \frac12 \sum \left\|y_n\right\|_{q_n}^2 + \frac12 \sum \left\|z_n\right\|_{q_n}^2$?
Answer: For completeness, I add the details of the proof of $d_{BM}(X,Y)=1$ for the example suggested by Wojtaszczyk. The key is the following
Lemma. The identity map $\ell_p^n\to \ell_q^n $ has norm $1$ when $p\le q$, and norm $n^{1/p-1/q}$ when $p\ge q$.
Proof. (a) Suppose $p\le q$. Let $x$ be a vector of unit $p$-norm. Since each coordinate of $x$ has magnitude at most $1$, it follows that $|x_i|^q\le |x_i|^p$. Hence $\|x\|_q\le 1$.
(b) Suppose  $p\ge q$. By Jensen's inequality, applied to the convex function $\phi(t)=t^{p/q}$, implies
$$
\frac{1}{n} \sum (|x_i|^q)^{p/q} \ge \left(\frac{1}{n} \sum |x_i|^q\right)^{p/q}
$$
hence $\|x\|_q \le n^{1/q-1/p}\|x\|_p$.

In the construction considered here, $n=5$ and $p,q\in [1,1.5]$. Divide $[2/3,1]$ into subintervals of length $<\epsilon$, for small $\epsilon$. If $1/p$ and $1/q$ fall into the same subinterval, the Banach-Mazur distance between $\ell_p^5$ and $\ell_q^5$ is at most $5^\epsilon=1+O(\epsilon)$.
Since the sequences $p_k$ and $q_k$ are dense in $[1,1.5]$, each of subintervals mentioned above contains countably many exponents of either kind. Use a bijection between them to define an isomorphism. The norm of this isomorphism is at most $5^\epsilon$ in either direction.


what is the definition of "two parallel copies of a surface S"

Question: As indicated in the title,
suppose $S$ is a surface with genus $g$, then
what is the definition of "two parallel copies of S"?
Answer: If $S$ is embedded in an orientable manifold, then there is a well-defined normal direction. So you can push off a copy of $S$ along this normal direction to get two parallel copies. It is the same as embedding $S\times [0,1]$ in the ambient manifold and considering the restriction $S\times\{0,1\}$.
Comment: thanks, so it is kind of disjoint union, the resulting surface has genus 2g?
Comment: The resulting surface is disconnected. Normally genus is only defined for connected surfaces. But yes, it is a particular kind of disjoint union.


Slot Machine GUI

Question: It's me again. We were tasked in our class to make a Slot Machine with 2 panels. Everything is working great except for the if else conditions. It seemed that the JOptionPane is not working or showing when it met the condition, but it shows no error in the console. I see the alert on the right it says that the JTextField is unrelated to String, but I converted the Random Number Integers to String to show it on the panel since it seemed that only String are accepted in JTextField. Please help! Thank you!
package slotMachineMain;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class slot1 extends JFrame implements ActionListener {

    JButton button1;
    JTextField text1;
    JTextField text2;

    slot1(){

        Image icon = Toolkit.getDefaultToolkit().getImage("D:\\11.png");
        ImageIcon image1 = new ImageIcon("D:\\12.png");
        ImageIcon image2 = new ImageIcon("D:\\13.gif");
        ImageIcon image3 = new ImageIcon("D:\\14.png");

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("Take your Chance Here!");

        JLabel label1 = new JLabel();
        label1.setIcon(image1);
        label1.setBounds(120, 10, 138, 87);

        JLabel label2 = new JLabel();
        label2.setIcon(image2);
        label2.setBounds(0, 0, 400, 290);

        text1 = new JTextField();
        text1.setPreferredSize(new Dimension(80,80));
        text1.setFont(new Font("Elephant", Font.BOLD, 35));
        text1.setForeground(Color.white);
        text1.setBackground(Color.black);
        text1.setHorizontalAlignment(JLabel.CENTER);
        text1.setEditable(false);

        text2 = new JTextField();
        text2.setPreferredSize(new Dimension(80,80));
        text2.setFont(new Font("Elephant", Font.BOLD, 35));
        text2.setForeground(Color.white);
        text2.setBackground(Color.black);
        text2.setHorizontalAlignment(JLabel.CENTER);
        text2.setEditable(false);

        JPanel panel1 = new JPanel();
        panel1.setBackground(Color.white);
        panel1.setBorder(BorderFactory.createLineBorder(Color.black));
        panel1.setBounds(83, 100, 90, 90);
        panel1.add(text1, BorderLayout.CENTER);

        JPanel panel2 = new JPanel();
        panel2.setBackground(Color.white);
        panel2.setBorder(BorderFactory.createLineBorder(Color.black));
        panel2.setBounds(207, 100, 90, 90);
        panel2.add(text2, BorderLayout.CENTER);

        button1 = new JButton();
        button1.setBounds(152, 200, 75, 25);
        button1.setIcon(image3);
        button1.addActionListener(this);

        this.setResizable(false);
        this.setSize(400, 290);
        this.setLayout(null);
        this.setIconImage(icon);
        this.add(panel1);
        this.add(panel2);
        this.add(button1);
        this.add(label1);
        this.add(label2);
        this.setVisible(true);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Random rn = new Random();
        if(e.getSource()==button1) {
            text1.setText(Integer.toString(rn.nextInt((10-8))+8));
            text2.setText(Integer.toString(rn.nextInt((10))));

            if (text1.equals("8") & text2.equals("9")) {
                JOptionPane.showMessageDialog(null, "YOU WIN A TOKEN!", null, JOptionPane.PLAIN_MESSAGE);

                }
            if (text1.equals("9") & text2.equals("9")) {
                JOptionPane.showMessageDialog(null, "JACKPOT YEHEY!", null, JOptionPane.PLAIN_MESSAGE);
                }

        }
}

}

Comment: 1) *"..it says that the JTextField is unrelated to String"* I'll bet it doesn't! Always copy/paste error and exception output! 2) *"It's me again."* .. again? Your profile only shows one question, no answers. Have you deleted previous questions, or had them deleted for you? 3) Java GUIs have to work on different OS', screen size, screen resolution etc.  using different PLAFs in different locales.  As such, they are not conducive to pixel perfect layout.  Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with ..
Comment: .. layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556).
Answer: You are comparing a JTextField with a String by typing
text1.equals("8")

and so on...
You should instead do
text1.getText().equals("8")

(To extract the String from the JTextField) and get the desired functionality.

Slot Machine GUI


Monit's second "Does not exist" overrides first one

Question: I have a process which I am monitoring using Monit. If process dies for some reason, I want to send a Slack notification using a shell script and also restart it. This behaviour though does not work with "does not exist" directive. The last one is executed and previous one ignored. For example code below:
check process xyz with pidfile /var/run/xyz.pid
  start program = "/etc/init.d/xyz start" with timeout 60 seconds
  stop program = "/etc/init.d/xyz stop"
  if does not exist then restart
  if does not exist then exec "/opt/somescript.sh"

It executes script but does not restart. it also looks like from documentation that this is how it will behave. Any other way to get this working. Documentation reference (Not exactly clear but resembles the actual behaviour):
If not defined, it defaults to a restart action.
You can override the default action with the following statement:

Answer: My guess is the default action is already to restart the process, as per the documentation, and you are overriding that with an exec action
Cleaner way is to add the restart script inside your somescript.sh.
If you don't want to do that, you can also combine the two actions in one, like this:
if does not exist then exec "/etc/init.d/xyz restart && /opt/somescript.sh"

Comment: Sorry but that's just typo from my side while typing the question, corrected now
Comment: Oh I see. I updated the answer, probably best to put the restart and the script into 1 action instead.
Comment: for some strange reason even if I call two commands in exec, separated by && - it calls only the first one. I tested this by changing the places but always only one command is called!
Answer: I believe monit doesn't allow you to have the same statements twice. You would have to write your script on restarting the process in your somescript.sh.


Non Diatonic Harmonization?

Question: First of all, I'm a self taught musician.  I have a basic understanding of music, and I can play piano too.  I understand the theory behind diatonic scales and how the harmony works.  I have learned the major, minor, diminished, and augmented chords, and inversions too, as well as the basic 7th and 9th chords.
Now I want to compose music for a short film.  I have already planned to get what plugins I needed for my DAW, and I have even come up with some tunes which I'm really happy with.
But because I'm composing for a film in the thriller genre (sort of), some of the tunes don't fit in the normal major/minor scales.  I understand that's how film music works sometimes, but I'm still scratching my head (maybe because of my OCD lol).
For example:

the melody notes (C, E, D#, C#),
with the chords (C minor, D# Major, C# minor)

A second example:

the melody notes (G, F#, D#, D),
with the chords (G minor, C minor)

These are just some simple examples to clarify.
When I play all that, for me it sounds good and flows well with the scene, but my mind really overthinks about it: "What scale is this even?".  The melody notes are relatable to the chords at least, and  most of it and sounds good too — nothing felt off or unrelated.
So I'm really worried, am I doing something wrong? or is there no rules as long it sounds good together?
Comment: Music theory is but a tool to analyse music and to help you create stuff. Not every melody needs to stem from a specific scale.
Answer: Put very simply, the 'rules' have developed from what sounds good, not vice versa!
Those 'rules' have been manufactured by musicians over many centuries to guide other musos and make their composing easier. But, making 'rules' for every situation or genre would be virtually impossible, and they would (and do) get broken every day.
Your ears are far better judges than following any 'rules' - some of which your ears will actually agree with, a lot they'll disagree with though.
Use those 'rules' as a datum point for what you're doing, and if you're happy with the end result, so be it.
Answer:
or there is no rules as long it sounds good together...

This is essentially true, there are no rules. But there are tools!
I can make several suggestions:

Secondary dominants. E.g. in the key of C major one could harmonize C and E notes with C chord, and then D# with B7 chord, which would be a secondary dominant for E chord, but resolving deceptively to C#- instead (edit: after playing this example I realized D# in B7 is a leading tone that is expected to resolve upwards, to E, so that's not really a textbook example. Perhaps this is what earned me a downvote?)

Other scales than the most common major and minor scales. E.g. you could base the motif C E D# Db on C altered scale, or C half-whole scale, and use a chord or chords using appropriate extension. E.g. the whole motif could be harmonized with Calt chord.

Modal substitution. In the key of C there is no D# (or Eb) note. But there is Eb note in C minor. You could harmonize that note with some chord from C-minor, e.g. using Ab chord. Similarly C# (or rather Db) is present in C phrygian and C locrian modes.

Chromatic scale. You can simply treat the notes as intentionally dissonant and not belonging to the scale, and not suggesting any underlying harmony.

Modulation. At some point your composition may simply move to another key entirely. You may then come back to the original key – or not.

It's a good idea to experiment by your own, and in the end you always need to follow your ears, but there is also plenty of theory that can help you with the process. Definitely you don't have to limit yourself to chords using diatonic notes.
Comment: Thank you so much for your time... All this tools really helpful... So the main point is we can do whatever we want as long its sounds good? I mean rules meant to break? Just like using D maj chord in C major scale as long it works well
Comment: @Narresnair for sure sounding good is the most important thing, but I also encourage you to study harmony, otherwise you will loose lot's of time on finding by ear what's already discovered and well described by other people.
Comment: @CreativeMind27 that really should not be the take away. Just to put it bluntly, you listed D major chord in a C major scale which is almost always acting as a secondary dominant. That's why it works 99.9% of the time. Knowing this you can also use it in a way that's not typical and get a different effect. Just like when you write a story, you can do whatever but that doesn't make the story stronger. You have to understand what you are going for.
Answer:
"What scale is this even?"

The first example could be a segment of a diminished scale. There is a lot of ambiguity in diminished scales, because you can select various scale steps to create minor, major, and diminished chords.
The second example is a harmonic tetrachord and could be the top tetrachord of a G harmonic minor scale. Both chords Cm and Gm fit very comfortably in that scale.
Both tone collections offer lots of possibilities for eerie or dramatic music.
In film scores a lot has to do with orchestration. Tempo/dynamics/rhythm will have a huge impact too.
If the film were a musical (like The Sound of Music) or required a traditional instrumental theme (like Star Wars), then you would need a solid understanding of the theory behind melody, harmonizing a tune, form, etc. The kind of stuff you would get from a college music theory textbook. You would need to know how to write things like 32 bar songs and symphonic type themes.
If the film doesn't require that kind of traditional music, a lot of expression can come from just orchestration. Unless that orchestration were purely percussive, you will obviously need some kind of pitch material, but you don't necessarily need full songs and themes. Your two example pitch collections would seem to be enough. Tempo/dynamics/rhythm would become critically important in the absence of traditional melody and harmony.
You mentioned thriller genre. That makes me think the Mission Impossible theme. I think it's a good example of the non-traditional approach. Rhythm is really important and the the 5/4 time signature is iconic. Listen to the orchestration. In terms of traditional melody and harmony it's very basic: minor pentatonic in bass with a chromatic descent in the top line, chord wise it essentially elaborates only an A minor chord the whole time except for a short diversion transposing to Dm. This isn't song writing, it's groove and riff with dazzling orchestration.
Compare that with song based in a similar film genre, something like the song Goldfinger.

Non Diatonic Harmonization?...So I'm really worried, am I doing something wrong? or is there no rules as long it sounds good together?

You're the composer, so you need to know what your working toward. It doesn't need to be traditional song or symphonic writing. If you're aiming for a theme like Goldfinger your harmonic material is probably lacking. But if your trying to just set a mood/emotion, the harmonic material seems like enough and harmonization, in the sense of a song like Goldfinger, is not really a concern.
Comment: Yes sir for the short film which I'm working.. there is a scene which i felt like i need some strings and violins so i tried with Kontakt's patch... I come up with a short melody to give sort of uneasy, unpleasant mood then i tried harmonize it... Bcs of my little theory knowledge i can harmonize the melody quickly to set the mood.. It worked well i even try to change the chords but nothing makes me feel satisfied as the C#m Am Em chords.. Then there is my confusion about being in scale came in
Answer:
So I'm really worried, am I doing something wrong? or is there no
rules as long it sounds good together?

If it sounds good to you, then you applied some "rules" i.e. internal logic. Every style has its own set of rules, rules are style-specific. But you can make music in a style without being able to explicate the rules, just like you can speak a language without having studied the syntax or grammar of that language. You know the rules even if you don't know them. Music is a language, and languages are best learned through examples and repetition, not through abstract theory.
If your music doesn't follow the rules of some particular style, it doesn't mean that there are no rules in your music. It can help you work with your music if you can explicate a clear set of rules for it, but it's not a requirement. You can make music by ear. If you keep making music, you may gradually identify some rules like "with this melody note I always use this chord before this", and that will be your own theory and your own rules.

Non Diatonic Harmonization?