A conjecture about big prime numbers

Question: The fact that each prime number (greater than $9$) ends with one of the four digits $1,3,7,9$, allows us to classify the tens in which the primes are found according to which of these four digits, added to the tens, yields to a prime number.
For example, for the first ten we have $1 \rightarrow \{1,3,7,9\}$. In fact, $10+1$, $10+3$, $10+7$ and $10+9$ are all primes. Conversely, for the twentieth ten the association reads $20 \rightarrow \{\}$, since there are no primes between $200$ and $209$.
It is easy to see that each ten is associated to one (and only one) group of symbols, chosen among the following $16$ distinct alternatives: $\{\}$, $\{1\}$, $\{3\}$, $\{7\}$, $\{9\}$, $\{1,3\}$, $\{1,7\}$, $\{1,9\}$,  $\{3,7\}$, $\{3,9\}$, $\{7,9\}$, $\{1,3,7\}$, $\{1,3,9\}$, $\{1,7,9\}$, $\{3,7,9\}$, $\{1,3,7,9\}$.
For the sake of simplicity, we can identify each of these $16$ distinct groups of symbols  with a single symbol, or with a single color, as illustrated below:

Arranging the tens in a Pascal's triangle, we find (*) the following structure (omitting the first ten on the edges of the triangle):

(*) I hope that my code is correct! It would be great if someone, more skilled than me, could confirm the emergence of such structure. In case you are interested in double-checking, please have a look to this post for details.
However, assuming that I did not mess up too much with the code, my conjecture is that

For very big tens, there cannot be colored squares other than on the outer diagonal of the triangle.

In other words, big primes $p$ must be in the form $p=10^{\binom{n}{k}}+1$, or $p=10^{\binom{n}{k}}+3$, or $p=10^{\binom{n}{k}}+7$, or $p=10^{\binom{n}{k}}+9$, and $k=1$. Clearly, a weaker version of such conjecture is that $k$ can oscillate among some little integer $2,3,4,5\ldots$ (which ones?).
This is probably an obvious result for the experts (I apologize, in case), nevertheless I would be glad to understand the connections between this approach and others, and also to know if there is some technique to attack  such problem.
Sorry for possible naivety, and thank you very much for your comments and suggestions!
EDIT: The conjecture was based on the assumption that the plot of the triangle was correct. But, as Ross has shown, that was not the case. An improved version of the code producing that plot, in fact, results in this picture:
Comment: Sorry...you think that sufficiently large primes must be all be of the form $10^N+d$ where $d\in \{1,3,7,9\}$?  But this is clearly false.  I expect I have misunderstood what you have written...can you clarify?
Comment: Another problem with your claim (and, I think, with any natural weakening of it) is that $\sum \frac 1p$ diverges...where the sum is taken over the primes...but $\sum \frac 1{10^n}$ converges as does any fixed multiple of it.
Comment: +1 Nice question.
Comment: The top square looks to be one of the blues. I don't understand what you mean be omitting the first ten on the edges.  Should the top square be ${5 \choose 2}={5\choose 3}=10?$  Why are the next two purple?  I don't understand how you came up with your picture.  Does the big white area in the middle claim that if I take a binomial coefficient in that region and replace the ones digit with $1,3,7,9$ I will not get a prime?  It would be helpful to have only the top ten rows in a larger picture with the coefficients shown in colored squares.
Comment: @lulu That's definitely possible. There can be some mistake in the code, and the triangle I obtained is an artifact. However, there is still the weaker version of the conjecture. Your observation is anyway very interesting. Why this is false? Thanks!
Comment: Well, for one thing, Dirichlet tells us that, given any $M$ prime to $10$ there are infinitely many primes congruent to $M\pmod {10}$.  Thus, for example, there are infinitely many primes that end with a million $1's$.
Comment: @RossMillikan I omit the first ten $\binom{1}{0}$ on the edges because they do not add much to the picture. The top blue is green, the second ten. Please, have a look here  https://math.stackexchange.com/q/289614/559615 for more details. Yes, the big area should not contain primes, if my code is correct.
Comment: @lulu Then probably the conjecture is false. I didn't know about the Dirichlet observation. Thanks.
Comment: Here is a discussion of [Dirichlet's Theorem](https://en.wikipedia.org/wiki/Dirichlet%27s_theorem_on_arithmetic_progressions).
Comment: @lulu Should the weaker version hold with Dirichlet argument? Thanks for the link!
Comment: I tried to follow your link, but it is to an unrelated question.  Is the top one green because it comes from ${6 \choose 3}=20$ and the primes in $[20,29]$ are $23,29$?  Then the two purples below come from ${7 \choose 3,4}=35$ and $31,37$ are prime?  Which row is the last one has colored squares going all the way across?  I strongly suspect your algorithm is failing when the numbers get too large.
Comment: @RossMillikan Sorry Ross for the awful picture. If you take this picture representing the position of the squares https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/PascalsTriangleCoefficient.svg/220px-PascalsTriangleCoefficient.svg.png I just removed the outer edge. Give me some minutes, and I tell you the row.
Comment: @RossMillikan It is the ten 34 (i.e. row 34 in Pascal's Triangle).
Comment: (+1) Love your posts. How do you come up with these things?
Comment: @TheSimpliFire Thanks! It is just the natural development from this idea https://math.stackexchange.com/questions/2886024/a-conjecture-involving-prime-numbers-and-circles
Comment: But ${36 \choose 13}=1251677700,$ the first one I tried, and $1251677701$ is prime.  That square should not be white
Comment: @RossMillikan 36 gives you the _position_ in the triangle, but it represents a ten, therefore we should check if $1251677700\cdot 10$+1, +3, +7 or +9 are prime. However, now I check again.
Comment: So your claim is that if I take any entry $N$ in the middle of Pascal's triangle then $10N+1, 10N+3, 10N+7,$ and $10N+9$ are all prime?  It would have helped to make that clear.  All the talk about $10$s does not do so.
Comment: ${37 \choose 13}=3562467300$ and $35624673001$ is prime
Comment: I checked the code many times, but maybe there is a mistake. I am checking it again.
Answer: The large white area in the middle claims that if $N$ is any number in that area of the triangle then none of $10N+1, 10N+3, 10N+7, 10N+9$ are prime.  The claim is false as ${37 \choose 13}=3562467300$ and $35624673001$ is prime.
Comment: There are a few prime repositories mentioned in [this question](https://math.stackexchange.com/questions/1270957/where-can-i-find-a-list-of-large-prime-numbers).
Comment: You can't hope to look up numbers in a list to see if they are prime.  There are just too many primes, even small ones like only $15$ digits as mentioned in the linked question, for anybody to have bothered listing them.  For your purposes you only need to check some thousands or maybe millions of numbers,  That can be quite quick.  You need to use a package that works with arbitrarily large integers, but there are many of those.  The Fermat pseudoprime test will be good enough for what you need.  It is quick to code.
Comment: Yes. I understood the problem. Please, can you suggest me a way to efficiently code this structure?
Comment: You just need to compute $n \choose k$, which you can just do by summing the two entries above, then check the four numbers for being prime.  Clearly one of these steps is not working properly.  I suspect it is your primality test.  Maybe you are getting overflow of the integers you are using, because that region of the triangle has reasonably large numbers in it.
Comment: Yes, This is the problem. Also, do you know a good repository for primes? Thanks, Ross! I should delete this post, but I can't.
Comment: [Wikipedia](https://en.wikipedia.org/wiki/Primality_test) has a start on how to do primality testing.
Comment: Thanks a lot for your observations and suggestions. Useful and neat (as always, btw).

A conjecture about big prime numbers


"$\dfrac{x}{\sqrt{2}}$" is neglected so it proves neither A or B, how to fix my proof?

Question: How to prove
A)$$F(\mu+n \sigma)-F(\mu-n \sigma)=\Phi(n)-\Phi(-n)=\operatorname{erf}\left(\frac{n}{\sqrt{2}}\right)$$
B) $$F(x)=\Phi\left(\frac{x-\mu}{\sigma}\right)=\frac{1}{2}\left[1+\operatorname{erf}\left(\frac{x-\mu}{\sigma \sqrt{2}}\right)\right]$$

A CDF for a normal standard is the following:

$$N(x) = \frac{1}{\sqrt{2\pi}} \int_{-\infty}^x e^{-\phi^2/2} d\phi$$
I have the following relation in my notes which I am not very sure how they arrived at:
$$N(x) = \frac{1}{2}+\frac{1}{2}\text{erf}(x/\sqrt{2})$$
The following neglects the term "$\dfrac{x}{\sqrt{2}}$" so it proves nothing:
Not sure how they can have $x$ value in $N(\cdot)$ and $x/\sqrt{2}$ in $\text{erf}(\cdot)$. Here is what I got:
$$N(x) = \frac{1}{\sqrt{2\pi}}\left(  \int_{-\infty}^0 e^{-x^2/2} dx + \int_0^x  e^{-\phi^2/2} d\phi \right)$$
I reasoned that since $$\int_{-\infty}^{\infty}e^{-x^2/2}dx=\sqrt{2\pi}$$
then
$$\int_{-\infty}^0 e^{-x^2/2} dx = \frac{\sqrt{2\pi}}{2}$$
Therefore:
$$N(x) = \frac{1}{\sqrt{2\pi}}\left(  \frac{\sqrt{2\pi}}{2} + \frac{\sqrt{\pi}}{2}\text{erf}(x) \right)$$
Which is:
$$N(x) = \frac{1}{2} + \frac{1}{2\sqrt{2}}\text{erf}(x)$$
And not quite what I have in notes (due to $\text{erf}(x)$) instead of $erf(x/\sqrt(2))$
Answer: The definition of the error function is a slightly different integral from the CDF of a standard normal: $$\operatorname{erf}(x) = \frac2{\sqrt\pi} \int_{t=0}^x e^{-t^2}\,\mathrm dt.$$
Inside this integral, we can make the substitution $u = t \sqrt 2$, so that in the exponent we get $t^2 = (u/\sqrt 2)^2 = u^2/2$. But $\mathrm du = \sqrt2 \,\mathrm dt$, so when we make this substitution, we get
$$
  \operatorname{erf}(x) = \frac{2}{\sqrt{2\pi}} \int_{u=0}^{x \sqrt 2} e^{-u^2/2}\,\mathrm du.
$$
To get from here to the standard normal CDF, we replace $x$ by $x/\sqrt2$ (to make the upper bound on the integral correct), and divide by $2$:
$$
   \frac12 \operatorname{erf}(x/\sqrt 2) = \frac1{\sqrt{2\pi}} \int_{u=0}^x e^{-u^2/2}\,\mathrm du = N(x) - N(0).
$$
Since $N(0) = \frac12$ by symmetry, we get
$$
    N(x) = N(0) +  \frac12 \operatorname{erf}(x/\sqrt2) = \frac12 +  \frac12 \operatorname{erf}(x/\sqrt2).
$$


Who invented modal Jazz?

Question: Can anyone be said to have done so? Or was it just a movement that emerged from the various people playing at the time? I believe that Kind of Blue was the first album to popularize it but can Miles actually be said to have invented modal Jazz? Surely other contemporary musicians were doing similar things.
Wikipedia is not very clear on this. It states

Originating in the late 1950s and 1960s, modal jazz is epitomized by Miles Davis's "Milestones" (1958), Kind of Blue (1959), and John Coltrane's classic quartet from 1960–64.

And then goes on to say

Mercer Ellington has stated that Juan Tizol invented the melody to "Caravan" in 1936 as a result of his days studying music in Puerto Rico, where they couldn't afford much sheet music so the teacher would turn the music upside down after they had learned to play it right-side up.

So, if Caravan is indeed the first modal jazz piece, should Juan Tizol be credited with inventing it? Or should it be Russel? Or everyone who was playing at the time or what?
Comment: It is rare that movements in music get attributed to a single player. Usually there is a group of musicians that further some concepts, and then in hindsight it is made into a genre, or sub genre. I can't think of any other genre or sub genre that is attributed to a single musician, so I doubt a clear cut answer exists.
Comment: [Wikipeda sums it up nice](http://en.wikipedia.org/wiki/Modal_jazz)
Comment: @Dom that's just it, it doesn't really. I did read it before posting (though I should have made that clearer in my question, I have edited to make this clearer). All the wikipedia page says is that in the 50s, musicians began experimenting on it "spurred by [...] George Russell", yet it also mentions Caravan as a 1936 recording. So, if Caravan is indeed the first modal jazz piece, should  Juan Tizol be credited with inventing it? Or should it be Russel? Or everyone who was playing at the time or what?
Comment: My understanding is that Davis was the first to strictly compose modally in jazz, and he certainly helped popularize it via making albums of almost entirely modal music. That being said I'd imagine that Davis was himself influenced by early modal composition, such as Caravan, so really the emergence is a result of years of musicians doing the same thing and eventually that thing turned into what we know as modal jazz.
Answer: All modal jazz means is that the harmony is deliberately static so that the players can stretch out against it as well as with it in a more elastic fashion. It's not really something you could even say was "invented". While "Kind of Blue", put it on the map, there are boat loads of tunes preceding that album that are modal in at least sections. "Dark Eyes" is another early example that is very modal. The practice preceded the term and the movement.
Comment: That said, most people would consider "So What" to be the first *entirely modal* side recorded. I have no idea if it actually is, but it's considered to be. ;-)
Comment: Also, lots of Gypsy jazz could be considered modal.
Answer: There's no specific name as to who exactly invented modal jazz but the elements of modal play have always been there in jazz. Jazz borrows a lot of influences from different traditions including classical music and it is from this classical music that history shows the extensive use of modes around the 19th century - but make no mistake, "modal theory" has always been there, even the legendary Saint Yared from the ancient Ethiopian church in Africa utilized his "own" modes.
Coming back to jazz, a modal approach can be heard in many recordings from the 1940s like Benny Goodman's "Sing, sing, sing". Elements of modal jazz can also be heard in earlier jazz solos when musicians wanted to create linear/horizontal melody lines as opposed to vertical lines. I would like to believe that "modal jazz" is a word that was coined and popularized by critics to describe the type of jazz that the musicians of the 1950s were mostly playing; Miles Davis, John Coltrane, Bill Evans, Gil Evans, Cannonball Adderley, etc not that modal jazz was invented by any single person.
We should also be cognizant of the fact that most of the music originated from the human voice (singing, humming, clapping, tapping, etc) long before musical instruments were created, hence modes have always been there since the days of the caveman and the cavewoman.

Who invented modal Jazz?


Fetch Contact Details - Infusionsoft API

Question: I am using Infusionsoft API to fetch the details of the contact. I have the email address and using that email address I am fetching other details. I have used,
<code>// $app->findByEmail($email, $retrunfields);
$contact_details = $app->findByEmail("firstname.lastname@example.com", "Id");
var_dump($contact_details);
</code>
And also I am using the second method,
<code>$contact_data = $app->dsQuery('Contact' , 1 , 0 , array('Email' => 'email@example.com') , array('Id'));
var_dump($contact_details);
</code>
Both the scripts are working fine, but they are taking longer than usual. It takes more than 15 seconds to fetch the result and display.
Am I making any mistake or there is another better way to do this ?
Comment: This looks correct to me...
Comment: @mevius, this is correct but it takes way to long to execute.
Comment: Wow...how many records are in that database?
Comment: @mevius more than 20000 records in IS.. Is there any better way to fetch the contact details ??
Answer: this is most likely due to one of three factors.

Your Infusionsoft Contacts table is huge (millions of records)
Your Infusionsoft app is being overtaxed (lots of Users, opt-ins, queries, etc..)
Your Infusionsoft API usage is being throttled.

The best thing to do is to reach out to Infusionsoft support and ask them what the cause of the slowness might be for your app. They can look at your database size, app usage, and api throttling and let you know what's up.
Comment: Great points from @Jeremy -- InfusionSoft API is notoriously slow and subjected to frequent throttling, I experience that a lot, too.
Answer: You are doing the API call correctly. I would suggest to use the first one if you are searching only by email.
Slowness can be either caused by Infusionsoft API or by your server.
I don't think Infusionsoft's API will cause this as I've worked with a client before with hundreds of thousands of contacts but fetching contact took only few seconds.
Answer: It's important in cases like this to rule out as many potential sources of slowness as you can.  When anything in PHP takes a long time, there are any number of things that could cause it, from your server configuration, to the remote system just being slow.
Have you already tried running this query from another server, or from your own local machine? Try to find some common factors, isolate the problem and see if it doesn't help narrow down the problem.
Infusionsoft's performance has been very spotty in my experience.  Sometimes it would work perfectly for months on end, but usually not. Whenever we had a problem--some code that suddenly stops working when it had worked for years before or a process that once took less than a second suddenly slowing to a crawl--more often than not we could traced it back to something on their end.  And very often it was something that speaks of terrible QA-- Just this week we had an issue where queries on saved searches were returning entirely random information, and if we hadn't validated the entries before doing anything we might have ended up causing some serious issues for our clients.  Your issue doesn't sound all that exceptional, sadly. You may have to consider, if the same problem occurs under different test cases that it's something on their end that you can't remedy.
Regarding the API, you are using an older, deprecated version.  I'd recommend transitioning from it, since it had all kinds of problems--it would work, mind you, and should still work indefinitely barring a few easily remedied issues regarding HTTP certificates, but its code quality is poor.
Infusionsoft has provided a replacement API which they're just calling infusionsoft-php.  Novak Solutions also provides an excellent object-oriented version as well, which they, confusingly enough, call infusionsoft-php-sdk.  There's an option to use their XMLHTTP gateway as well,


How do I repeat / spread background image depending on number of divs on the page?

Question: I'm aware of the css properties background-size: cover; and background-size: contain; however despite of description of its usage I can't seem get it to work the way I need.
At the moment I'm adjusting coverage of the background image manually which is very impractical as you can imagine. How can I adjust coverage or repetition based on how many divs are on a page ?
On the mobile viewport its particularly desired. When I scroll down on the phone I want to see all divs covered to the footer. If I add another div (think a comment) background image would be extended.
body {
    background-image: url("bg.jpg");
    background-repeat: repeat;
    background-size: contain;
    height: 1000px;  /* <-- impractical way of adjusting coverage */
  }

I'm considering a javascript solution but it wouldn't be elegant but rather cumbersome. Is there "built-in" solution to this ?
Comment: Why do you need to set the size of a background that is repeating anyway? Questions like this should come with a proper [mre] that illustrates the actual issue.
Answer: All I needed to do is to replace lines:
background-size: contain;
height: 1000px;

with:
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;

works like a charm.
Comment: you said you are aware about `cover` so your answer doens't make a lot of sense plus we no more need to use prefixes with background-size


Magento adding actions In orders

Question: I'm using Magento Community 1.7. When I go to Sales-->Orders I see all the orders. Currently I can tick certain orders and, using the action dropdown, I can print invoices, cancel, hold etc. I'm wondering if there is anyway that I can add actions like "Requires Refund", "Fraud". The actions wouldn't neccessarily have to do anything just change the status so I can see clearly for later the status of these orders. Any ideas?
Answer: In order to add more actions you need to override this method Mage_Adminhtml_Block_Sales_Order_Grid::_prepareMassaction().
For each action you add, you will need a method in the controller you send it to.
Take for example the action Cancel. It is added to the mass action block like this:
$this->getMassactionBlock()->addItem('cancel_order', array(
     'label'=> Mage::helper('sales')->__('Cancel'),
     'url'  => $this->getUrl('*/sales_order/massCancel'),
));

and the corresponding method is Mage_Adminhtml_Sales_OrderController::massCancelAction()

Magento adding actions In orders


Creating a dynamic URL in node--resource.tpl.php

Question: I'm trying to create a URL in my node--resource.tpl.php file that contains fields from the resource in question in the URL. The following code is what I've been playing with, but when the user clicks the link it just shows as follows:
http://pf.dev/content/specific-resource-feedback?nid=&title=

Ie. The nid and title are not being filled out correctly. So here's the code I'm using (incorrectly) to create the URL:

    <a href="/content/specific-resource-feedback?nid=
<?php $content['nid']) ?>&title= <?php $content['title']) ?>">
Trouble with this resource? Let us know.

Any ideas why this might not be working as intended?
Comment: Because $content['nid'] and $content['title'] are empty... Install devel and use dpm($content); to see what's inside $content
Answer: The title is defined for a node.tpl.php file as $title, and the node id can be retrieved with: <?php print $node->nid; ?>  therefore, it should read something like this:

  <a href="/content/specific-resource-feedback?nid=<?php print $node->nid; ?>&title= <?php print $title; ?>">
  Trouble with this resource? Let us know.

Comment: That works, much obliged!


Why do I get "Command 'drupal-update' is not defined" when I run "composer drupal-update"?

Question: I'm using Drupal 8.2.7 on XAMPP, on Windows 10. I am installing AMP via Composer, but I received an error  when I run composer drupal-update.
I ran the command from the Drupal root folder.

[Symfony\Component\Console\Exception\CommandNotFoundException]
      Command "drupal-update" is not defined.

What happened?
Answer: Neither Drupal core nor Composer define that command. It's the Composer Manager module that defines it.
Be sure to read carefully the instructions to properly install the module, and the following note the project page gives.

Drupal 8
The Drupal 8 version of this module is deprecated and no longer needed, due to improvements in Drupal 8.1. Use Composer directly to get the needed modules, which will also download their required libraries.

The installation instructions are the following.

Installation

Install the Composer Manager module.
Run the module's init.php script on the command line
  (php scripts/init.php from inside the composer_manager module directory).
  This registers the module's Composer command for Drupal core.
Run composer drupal-update from the root of your Drupal directory.

If you are wondering why you don't see the Drupal 8 version in the project page, that is because, as the project page says, the Drupal 8 version is deprecated. The last Drupal 8 version is 8.x-1.0-rc2, visible in the releases page.


Store into variable a string that changes dynamically

Question: I'm quite new unix in shell scripting so I assume I need help regarding the following issue:
I want to store into a variable a string of a log text that changes dynamically. E.x one time you run the program that creates this log, this string may be server1 and the next time server238. I have found ways to find the first occurrence of this string through sed or grep and cut. However since the log file that this software creates may differ from version to version I can't count on a specific line that contains this string. E.x one version may log "The server you are using is server98" and the next one to "Used server is server98". Is there a way through sed or awk that this string may be retrieved regardless of the log layout.
Thanks in advance.
Comment: Oh, you seem to be fond of [Camus](https://en.wikipedia.org/wiki/Albert_Camus)!  Good.
Comment: That is cruel, mr @devnull :-)
Comment: @MarkSetchell What's cruel about that?  [The Myth of Sisyphus](https://en.wikipedia.org/wiki/The_Myth_of_Sisyphus) is an excellent read.
Answer: I'd go with:
server=$(grep -Eo 'server[0-9]+' file | head -n 1)

to find any occurrence of the word server followed by some digits, e.g. server3, server98
-E means to use Extended regular expressions (i.e. \d+ for multiple digits)
-o means only output the matching part of the string - not the whole line that contains it.
Here it is in action on OSX:
cat file
server9
fred server98 fred
3

/usr/bin/grep -Eo 'server[0-9]+' file
server9
server98

Comment: Thanks for your quick response. I tried but the variable was empty.Could you explain what the argument -Eo stands for because I haven't found it in any reference. I tried also with grep -E but the variable was also empty.
Comment: I have explained the switches I used. They are the ones on a Mac under OSX but you should be able to find the equivalent on any Unix/Linux if you do `man grep` and then `/xtended`. Actually, I think Linux uses GNU grep which does Extended Regexes anyway, so you can probably omit it on Linux.
Comment: Hi again I tried it both in Ubuntu and OSx but I had the same result.
I also tried with only grep -o but the same. I may have misconceived something.
Comment: This worked but it stored all the occurrences of server91. How can this be minimized to just one?
Comment: I have modified my answer to just grab the first occurrence, by using `head -n 1`
Answer: Try this:
MY_VAR="$(sed -n 's/^.*\(server[0-9][0-9]*\).*$/\1/p' my_file.log | sort -u)"

Comment: Thanks for the answer. The echo of the variable showed that it stored all the occurrences but only with numbers. So it stored the following
91 91 91 91 91 91 91 91 91 91 91
I may be misunderstood but I would like only one occurrence with the whole alphanumeric "server91" to be stored in the variable.


Verificar as respostas certas nas checkbox

Question: Estou tentando fazer que a menssagem window.alert('A certou') só aparecer quando as três checkbox com o name="certo" forem marcadas.
HTML5
<input type="checkbox"  class="resposta" name="certo">
Abrir portas para um futro promissor.

<input type="checkbox"  class="resposta" >
Ganhar dinheiro.

<input type="checkbox"  class="resposta" name="certo">
Expandir minha rede de contatos profissional.

<input type="checkbox"  class="resposta">
Diminuir o desmatamento.

<input type="checkbox"  class="resposta" name="certo">
Promover meu trabalho.

<input type="button"  value="Verificar" onclick="verificar()">

Javascript
function verificar(){
    let resposta = document.querySelector('.resposta')
    let correto = document.getElementsByName('certo')

    for (var marcado in resposta) {
        if(resposta[marcado].checked){
            window.alert('Marcada')
            if(correto == true){
               return window.alert('A certou')
            }else{
                return window.alert('Errou')
            }
        }
        else
        return window.alert('Em branco')
    }
}

Answer: vc pode criar uma função que percorra os input certos e so retorne verdadeiro se todos tiverem checados. assim:
    function verificar() {
        console.log(verificarCheckbox())
        if (verificarCheckbox()) {
            alert("Acertou")
        } else {
            alert("Errou")
        }
    }

    function verificarCheckbox() {
        let correto = document.getElementsByName('certo')
        let isValid = true
        correto.forEach(function (el) {
            if (!el.checked) {
                isValid = false
            }
        })
        return isValid
    }

Comment: Obrigado hiago-buzz, nem tinha pensado em fazer uma function separada para percorra os input certos. :)


How to create own jar file and import it?

Question: Suppose I have a java class file which can be used in many projects. So, I want to create a jar file and it can be used in any other projects as needed. How to achieve this ?
I am using eclipse IDE.
Comment: You need to include your build environment/IDE or this is a meaningless question.
Comment: http://stackoverflow.com/questions/2591092/how-can-i-create-a-jar-file?rq=1
Comment: @Brain Roach, I tried using commands but it is so irritating and now I  need easy steps...
Answer: I found the solution as below:
First create your java file as you require. Right click your project -> click on export -> select option jar, follow the dialog box. Now, you have created your own java jar file.
Create your new project as you require, import that jar file as you are importing other jar files. Now, you can import that created jar file's methods or anything as you required...
Comment: Is that jar file stored somewhere?
Answer: You can find all necessary steps to create a JAR in Eclipse here


Locus of centre of circle

Question: Question: A circle passes through the origin and has four distinct intersections with the parabola $y=x^2$. Describe the possible positions of the centre of the circle.
I believe that the centre cannot be below or on the parabola, since that would result in at most two intersections. Therefore, the centre must be within the interior of the parabola. I also tried thinking along the lines of $$(x-h)^2+(x^2-k)^2=r^2$$ and finding the conditions on $h$ and $k$ such that this equation has 4 distinct real roots. Would using the discriminant for quartic equations be the correct approach?
Comment: why the downvote? the question shows effort, it is clear and is useful.
Answer: First, I'm assuming that whenever you say an intersection, you're talking about a real intersection.  Otherwise, there are always four intersections (counting multiplicity).
Second, since a circle and a parabola are bout quadrics, the number of intersections of these two varieties is at most $4$.  Therefore, this question is asking for all the zeros to be real.
We'll start by writing the circle as $(x-h)^2+(y-k)^2=r^2$ or that
$$
x^2-2hx+h^2+y^2-2ky+k^2=r^2.
$$
Since the circle passes through the origin, we can substitute $(0,0)$ to get that $h^2+k^2=r^2$.  Hence, the equation for the circle simplifies to
$$
x^2-2hx+y^2-2ky=0.
$$
Now, let's look for the other intersection points.  These points must satisfy $y=x^2$, so, after substitution, the $x$-coordinates of the intersection points are zeros of
$$
x^2-2hx+x^4-2kx^2=0.
$$
We already know that $x=0$ is a solution, so we can factor that $x$ out to get
$$
x(x^3+(1-2k)x-2h)=0.
$$
We focus on the cubic part.  This is a depressed cubic with a simple discriminant.
The discriminant in this case is
$$
-4(1-2k)^3-27(-2h)^2.
$$
The discriminant is positive if and only if all the solutions are real and distinct.
Therefore, the condition for all the roots of the cubic to be real and distinct (with $r^2=h^2+k^2$) is that
$$
32k^3-48k^2+24k-4-108h^2>0.
$$
Now, we finally want the roots to be distinct.  While the roots of the cubic are distinct when the condition above holds, it might be that one of the roots of the cubic is zero, which matches the $x$ that we factored out.
Therefore, we, in addition, need that $h\not=0$ in the cubic so that the cubic has a nonzero constant term, and does not have $0$ as a zero.
Summary: There are three conditions which are necessary and sufficient:

$r^2=k^2+h^2$
$h\not=0$
$(2k-1)^3>27h^2$.

Thanks to @Servaes for suggesting a cleaner form for the summary.
Comment: +1 Excellent answer! You could take out the common factor $4$ from the last inequality, and perhaps even express it more cleanly as
$$(2k-1)^3>27h^2.$$
This also shows that necessarily $k>\frac12$.
Comment: Thank you for your help! Really appreciate your time in answering this.

Locus of centre of circle


Incorrect "Mailbox Store" in Active Directory

Question: I recently had to restore our primary domain controller from a backup, but the backup was taken before a mailbox was moved (from mail1 to mail2). The user now has the problem that they cannot access their email. This appears to be because Outlook is looking for the emails on mail1.domain.com, whereas the actual emails are on mail2.domain.com.
In AD, the users "Mailbox Store" attribute is set to "MAIL1/First Storage Group/Mailbox Store (MAIL1)".
In event viewer on MAIl1 (which is also our PDC), the following event is logged :
<code>Event Type: Error
Event Source:   MSExchangeIS Mailbox Store
Event Category: General
Event ID:   1205
Date:       26/10/2009
Time:       09:30:49
User:       N/A
Computer:   MAIL1
Description:
Failed to create the mailbox of
/o=DOMAIN/ou=first administrative group/cn=Recipients/cn=<user> with error 0x50c.
</code>
How can I tell AD where the mailbox is correctly located?
Comment: There are no "primary domain controller" or "PDC" computers in Active Directory. There are only "domain controllers" some of which might hold unique FSMO roles. Otherwise, they're all the same. None is "primary".
Answer: Fixed the problem with this article.


Importance of studying the curvature of a covariant derivative on a vector bundle

Question: Let $\mathcal{E}$ be a vector bundle over $M$. Let $\nabla : \Gamma (M,\mathcal{E}) \rightarrow \Gamma(M,T^*M \otimes \mathcal{E})$ be a covariant derivative on M. I read that the choice of a covariant derivative $\nabla$ on $\mathcal{E}$ allows us to split the tangent bundle $T \mathcal{E}$ into the vertical bundle and a horizontal bundle.
Denote $\mathcal{R}$ the curvature of $\nabla$, which is defined by
$$\mathcal{R}(X,Y) =[\nabla_X, \nabla_Y]- \nabla_{[X,Y]},$$
Where $X$ and $Y$ are two vector fields.
I'm wondering why it is useful to consider the curvature of a covariant derivative on a vector bundle?
Answer: Developing @Wyatt's second point ("The curvature is exactly how much the connection fails to be flat.") a bit further:
Curvature provides a useful tool to topologically classify vector bundles in terms of Chern-Weil theory.
Think of vector bundles over compact manifolds, for simplicity a line bundle over the torus, the latter thought as a square obtained as quotient of $\mathbb{R}^2$ by a lattice. For the vector bundle to be smooth, the fibers need to be periodic in a suitable sense and this claim restricts the freedom in choosing how they "twist over the torus". A good notion of a quantitative measure of "how they twist" is the curvature.
In fact, integrating the curvature over the torus gives you a topological invariant, that is, an integer number (up to some constant) which only depends on the topology of the bundle and is the same for whichever covariant derivative you have chosen. Moreover, if two vector bundles can be smoothly deformed into one another, then these numbers must be same, or conversely, if they are not the same, then the bundles cannot be smoothly deformed into one another. (Google for Chern numbers if you are interested). So "how much curvature there must be in total" is a topological property of the bundle, where by choosing different covariant derivatives, you can "distribute the curvature" in different ways over the manifold.
Going on from there, you can study Chern-Weil theory which provides a large class of such topological invariants by (up to some details) integrating suitable polynomials of the curvature (which become non-trivial if the base manifold has a higher dimension than 2). You can of course pretend to forget the notion of curvature and express these polynomials of the curvature as polynomials of the covariant derivative, but this makes it much harder to characterize these polynomials and would not be the usual way of mathematics in general to structurize theories as good as possible.
Comment: Okay, maybe that was a bit too handwavey... Take a line bundle $\pi:E\to\mathbb{T}^2$ over the 2-torus and define the quotient projection $$p:\mathbb{R}^2\to\mathbb{R}^2/\mathbb{Z}^2=\mathbb{T}^2.$$ Then $p^*E$ is a line bundle over $\mathbb{R}^2$ for which you define the fiber over a point $x\in\mathbb{R}^2$ to be the space $E_{p(x)}$. Since $p$ is $\mathbb{Z}^2$-periodic, so is $p^*E$, in the sense that for $x\in\mathbb{R}^2$ and $\gamma\in\mathbb{Z}^2$ you have $(p^*E)_{x+\gamma}=(p^*E)_x$.
Comment: Via $p$ you can think of the torus as the unit square in $\mathbb{R}^2$ with the boundary pieces identified appropriately. If you want to define something on $\mathbb{T}^2$ by defining it on the unit square it has to be periodic in the sense of "it has to coincide on the left and right and on the lower and upper boundary piece of the unit square".
Comment: "For the vector bundle to be smooth, the fibers need to be periodic in a suitable sense and this claim restricts the freedom in choosing how they "twist over the torus". @nicrot000 could you please elaborate further in this statement, I didn't understand it ? For example what do you mean by " periodic" in this context  and by "twist over the torus" ?
Answer:
One very important example is general relativity, where the curvature is related to the stress-energy tensor on spacetime. Look up "Einstein Equation". There are other examples in gauge theory where the curvature corresponds to the field strength.

The curvature is exactly how much the connection fails to be flat. Flat connections also give integrable systems of differential equations. Curved connections do not, so we can view curvature as an obstruction to integrability. Look up "Maurer-Cartan Equation".


Not getting fieldset as a option while adding new fields in content type

Question: I am adding new field in content type and I want that field's Field type to be Fieldset but there is no such option in Field type column.
Can anyone know how can I add new field's Field type as Fieldset
Thanks
Answer: There's no 'fieldset' field type as such.
If you want to wrap entity fields in fieldsets, install the Field Group module:

Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
Comment: At the bottom of the manage fields form you'll see **Add new group**; fill in a name for the group, choose a type, add it, then once it's added you'll be able to drag 'proper' fields underneath it. When you view the form, the changes you've made will show up
Comment: I have already installed Field Group module.Which option i need to select while adding field group as fieldset in adding content type?


Gitlab CI/CD deploy to aws via aws-azure-cli authentication

Question: When deploying to AWS from gitlab-ci.yml file, you usually use aws-cli commands as scripts. At my current workplace, before I can use the aws-cli normally, I have to login via aws-azure-cli, authenticate via 2FA, then my workstation is given a secret key than expires after 8 hours.
Gitlab has CI/CD variables where I would usually put the AWS_ACCESS_KEY and AWS_SECRET_KEY, but I can't create IAM role to get these. So I can't use aws-cli commands in the script, which means I can't deploy.
Is there anyway to authenticate Gitlab other than this? I can reach out to our cloud services team, but that will take a week.
Comment: Posted an answer, how did it go? did it worked?
Answer:
You can configure OpenID to retrieve temporary credentials from AWS without needing to store secrets.

In my view it's actually a best practice too, to use OopenID roles instead of storing actual credentials.

Add the identity provider for GitLab in AWS
Configure the role and trust
Retrieve a temporary credential

follow this https://docs.gitlab.com/ee/ci/cloud_services/aws/ or a more detailed version https://oblcc.com/blog/configure-openid-connect-for-gitlab-and-aws/


Interpretation of a linear regression

Question: I have some problems in understanding the results of two linear regressions on the same data.
I have 2 variables and I want to know if there is a linear correlation between the two. Let's say velocity of a car and perceived velocity of the conductor.
Let's say I have 4 velocities and 2 evaluations of the perceived velocities performed in 2 trials by 15 participants, on a 7 points Likert scale where 1 is very slow and 7 = very fast.
Now if I take the AVERAGE values of the evaluations given by the 15 participants for the 4 velocities I get a clear linear relationship with $R^2$ = 0.7.
However if I perform the analysis on the raw data (i.e. 15 participants * 2 trials = 30 values for each velocity) I get a $R^2$ = 0.2. Plotting the graph of the velocity data vs perceived velocity I get a mess of points very widely distributed.
Why do I get this behavior?
Which of the two analyses should I use? The first or the second?
How can I interpret my values?
Please let me know
Thanks in advance
Comment: You are getting the conclusions that different individuals often describe their speed differently, but that overall they often notice when their speed changes.
Comment: Hi, could you clarify a few things.  Which is your response variable (on the vertical axis) - perceived velocity or actual velocity?  What is the scale of actual velocity (is it the same seven point scale as perceived, or is it a four point scale - one interpretation of what you mean by "I have 4 velocities"). What *do* you mean by "I have 4 velocities" - is this 4 possible velocities?  In the first regression, do you have 60 points or 15? And in the second are there 120 or 30?
Comment: Hi, can you show us the scatterplot of your two velocity variables?
Comment: Hello everybody thanks for your reply. On the vertical axis there is the perceived velocity. On the horizontal axis I have the velocities, on a 4 point scale. Just velocity 1, 2 , 3 and 4. It is a general case, I don't care about the differences between the velocities (Please note: this velocity example is just a generalization of the real problem that I am trying to solve...). In the first regression I just have 4 points (the average perceived velocity for the 4 velocities). In the second regression I have 120 points (15 participants * 2 trials * 4 estimate of the velocities).
Comment: It would help if you edited your question to show the first couple of rows of your data, and put up a scatterplot.
Answer: I agree with @PeterEllis & @Michelle that it is hard to follow your question exactly, and more information (such as they request) would probably be very helpful in getting an answer that is useful for you.  I can make a guess at what is going on here based on what I can glean, however: I suspect what you are seeing is just the resolving power of the mean.  The strength of correlations are influenced by the amount of noise present.  Take a variable that has a correlation, $\rho$, with another variable and add additional variability to it, and you will decrease the estimated value, $r$.  You don't have to change the underlying trend; that is, the random noise you add can be centered on 0.  Looking at the formula for the product-moment correlation makes this more apparent:
$$
r=\frac{{cov}(x,y)}{s_xs_y}
$$
As the SD for one of the variables gets larger, the product will get larger, leading to a larger denominator, and a smaller $r$.  On the other hand, using means instead of raw data will shrink the variability by a factor of $1/\sqrt{n}$.  As for which one of these is 'right', I don't know how to answer that.  They are answers to different questions.
With more information, I may update this answer, but this may be what's going on.
Answer: Now that I understand your data I would certainly use the original set in your analysis rather than the four averages.  The "noise" that you describe is actually a crucial part of your data.  The higher $R^2$ in the model with fewer data points is because you have taken out the variation around the means.
First, which of your two plots and regressions to use?
By using a technique like linear regression on your original data (the 120 points) you can simultaneously look at the average perceived velocity for each of your four levels of actual velocity, and conduct inference based on a full understanding of the level of variation in the data.
If you conduct it on just the four means, you have split your analysis into two phases.  The first phase finds the average for each level of actual velocity; then the second (where you conduct regression) tries to do inference to the general population.  You can't really do what you want to in this second phase because you have lost all the information about the randomness in your first phase.
You might want to come back to your picture of the four averages as part of a result-reporting summary of your data, but all inference should be based on a model fitted to the original set.
Second, what analysis to do
Because you have repeated observations with characteristics in common (eg different trials; and each observer with different goes) you can't just fit a regression to all 120 points.  You need to somehow control for observer effects.  I would fit a model like
perceived ~ actual * observer

while hoping that can be reduced to
perceived ~ actual + observer

For this to work properly actual needs to be an ordered factor.   R will then automatically apply the correct contrasts to it in fitting a model (sorry I don't have time to explain that better but there would be material on the web about what that means).
However, there are lots of potential fishhooks.  Can perceived velocity really be treated as continuous?  Does it have an approximately normal distribution (obviously not really, but it may be close enough)?  Is the variance independent of the mean?  Evading these will be tricky and you should use R's graphic capabilities fully in exploring your data.  If the assumptions behind linear regression do not hold, you may be able to use the polr() function from library(MASS) to fit an ordinal response regression instead.

Interpretation of a linear regression


Using Spark Scala in EMR to get S3 Object size (folder, files)

Question: I am trying to get the folder size for some S3 folders with scala  from my command line EMR.
I have JSON data stored as GZ files in S3. I find I can count the number of JSON records within my files:
spark.read.json("s3://mybucket/subfolder/subsubfolder/").count

But now I need to know how much GB that data accounts for.
I am finding options to get the size for distinct files, but not for a whole folder all up.
Comment: @DenisMakarenko : He wanted to print distinct file sizes rather than folder
Comment: I've closed it too fast. The title is misleading.
Answer:
I am finding options to get the size for distinct files, but not for a
  whole folder all up.

Solution :

Option1:
Get the s3 access by FileSystem
    val fs = FileSystem.get(new URI(ipPath), spark.sparkContext.hadoopConfiguration)

Note :

1)  new URI is important other wise it will connect to
  hadoop file system path instread of s3 file system(object store :-)) path . using new URI you are giving scheme s3://
  here.
2) org.apache.commons.io.FileUtils.byteCountToDisplaySize will
  give display sizes of file system in GB MB etc...

      /**
    * recursively print file sizes
    *
    * @param filePath
    * @param fs
    * @return
    */
@throws[FileNotFoundException]
@throws[IOException]
  def getDisplaysizesOfS3Files(filePath: org.apache.hadoop.fs.Path, fs: org.apache.hadoop.fs.FileSystem): scala.collection.mutable.ListBuffer[String] = {
    val fileList = new scala.collection.mutable.ListBuffer[String]
    val fileStatus = fs.listStatus(filePath)
    for (fileStat <- fileStatus) {
      println(s"file path Name : ${fileStat.getPath.toString} length is  ${fileStat.getLen}")
      if (fileStat.isDirectory) fileList ++= (getDisplaysizesOfS3Files(fileStat.getPath, fs))
      else if (fileStat.getLen > 0 && !fileStat.getPath.toString.isEmpty) {
        println("fileStat.getPath.toString" + fileStat.getPath.toString)
        fileList += fileStat.getPath.toString
        val size = fileStat.getLen
        val display = org.apache.commons.io.FileUtils.byteCountToDisplaySize(size)
        println(" length zero files \n " + fileStat)
        println("Name    = " + fileStat.getPath().getName());
        println("Size    = " + size);
        println("Display = " + display);
      } else if (fileStat.getLen == 0) {
        println(" length zero files \n " + fileStat)

      }
    }
    fileList
  }

based on your requirement, you can modify the code... you can sum up all the distinct files.
Option 2 : Simple and crispy using getContentSummary
implicit val spark = SparkSession.builder().appName("ObjectSummary").getOrCreate()
  /**
    * getDisplaysizesOfS3Files
    * @param path
    * @param spark [[org.apache.spark.sql.SparkSession]]
    */
  def getDisplaysizesOfS3Files(path: String)( implicit spark: org.apache.spark.sql.SparkSession): Unit = {
    val filePath = new org.apache.hadoop.fs.Path(path)
    val fileSystem = filePath.getFileSystem(spark.sparkContext.hadoopConfiguration)
    val size = fileSystem.getContentSummary(filePath).getLength
    val display = org.apache.commons.io.FileUtils.byteCountToDisplaySize(size)
    println("path    = " + path);
    println("Size    = " + size);
    println("Display = " + display);
  }

Note : Any option showed above will work for
local or
hdfs or
s3
as well


Kibana /etc/init.d scripts

Question: I am having a hard time adapting the init.d start up scripts I have found for Kibana on the internet.
I am experienced with RedHat/Centos but we have standardized on Suse Enterpise Linux here at work. So I need to port the init.d scripts I have been using to work with SLES.
I don't have access to the machine with the scripts, and they aren't throwing any errors; at least not any that I can figure out how to detect. But they also don't start up Kibana and keep it running.
I can start Kibana from the command line manually, but that won't work in a production environment. I would rather use the blessed kibana-daemon.rb script and a proper init.d script to kick that off.
I wanted to go ahead and reach out to see if anyone had a working script for SLES.
As soon as I get back to my other machine I will update this question with the specific scripts and any errors I can find.
Answer: In my experience, it is much easier to use mod_passenger and rely on the httpd init scripts, instead.
This is a working example from an older Kibana version, you might need to adapt it to your needs:
# vim:fdm=marker:syn=apache:ts=2
# VHOST KIBANA {{{
Listen 8080

<VirtualHost _default_:8080>
  ServerAdmin "firstname.lastname@example.com"
  ServerName "kibana.crapsteak.org"
  DocumentRoot "/opt/org/kibana/Kibana-x.y.z/public/"
  ErrorLog "|/usr/sbin/rotatelogs -f ${APACHE_LOG_DIR}/kibana/error.log.%Y%m%d 86400"
  CustomLog "|/usr/sbin/rotatelogs -f ${APACHE_LOG_DIR}/kibana/access.log.%Y%m%d 86400" logstash_json
  HostnameLookups Off
  UseCanonicalName Off
  ServerSignature On
  RackBaseURI /
  <Directory "/opt/org/kibana/Kibana-0.2.0/public">
    Options FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from 127.0.0.1 10.0.0 x.y.z.0/24
  </Directory>
</VirtualHost>
# }}}

Comment: I don't have Apache on this machine and Ruby is the one language out of all the mainstream languages that I know that I don't *"do"*; so I had not considered this. Good advice.

Kibana /etc/init.d scripts


Add new array values to existing array position

Question: I have array which is presenting like this:
<code>        $array = array (
        "list" => array(
            "serwer-1" => 3
        ),
        "servers" => array(
            3 => array(
                "msg" => "{'some data': 123123121313}",
                "status" => 200
            ),
        ),
    );
</code>
I want add new items to $array['list'] for example:
<code>        array (
        "list" => array(
            "serwer-1" => 3
            //NEW DATA HERE
            "serwer-2" => 7,
        ),
        "servers" => array(
            3 => array(
                "msg" => "{'some data': 123123121313}",
                "status" => 200
            ),
        ),
    );
</code>
Maybe it's trivial, but I haven't any idea how to do this - I have bad day today :(
Comment: `$array['list']['serwer-2'] = 7;`
Answer: In order to add a key-value pair to an existing array just do it like the key exists there.
<code>$array["list"]["serwer-2"] = 7;
</code>
Then you will get desired result.


Pegando Evento Collapsing Toolbar Android

Question: Existe alguma forma de identificar o evento de collapsing da CollapsingToolbar?
Tipo um onChangeCollapsingListener
O que preciso fazer é setar a visibilidade de alguns componentes da tela quando a CollapsingToolbar da um expand ou um collapsing.
Desde já agradeço.
Answer: O AppBarLayout tem um listener para ser notificado de mudanças de offset.
Acredito que seja possível ser notificado quando ele está completamente colapsado ou expandido da seguinte maneira:
AppBarLayout.OnOffsetChangedListener  listener = new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if(collapsingToolbar.getHeight() + verticalOffset < 2 * ViewCompat.getMinimumHeight(collapsingToolbar)) {
            // CollapsingToolbar esta colapsado
        } else {
            // CollapsingToolbar esta expandindo
        }
    }
};

appBar.addOnOffsetChangedListener(listener);

Fonte: https://stackoverflow.com/questions/31595741/show-view-when-toolbar-collapses


switch loop doesnt recognize zero "0" php

Question: I have this simple function to convert the number of comments of an user to types of members.
function checkMemberN($numMessages){
    $n= $numMessages;

    switch ($n) {
        case ($n<50): $type="New"; break;
        case ($n>=50 && $n<250):$type="Frequent";break;
        case ($n>=250 && $n<1000): $type="Master";break;
        default: $type="undefinded";
    }

    return $type;
}

echo checkMemberN(0);

It looks like it doesn't recognize zero (0), because when I put 1 or a higher number it retrieves the correct user type. What am I doing wrong?
Comment: I think you want `switch(true)`. That being said, this is a terrible use-case for `switch`. Just use `if..else if..else`
Comment: Change it to `switch (true) {` and it works. Basically you're chasing a falsy value and that second condition is the first one to evaluate to false.
Comment: do $n=intval($numMessages);
Comment: Phil. haha. why a terrible use? I think it suits...how can I make it work?
Comment: @ItayMoav-Malimovka it doesnt work.
Comment: the funny thing is that it was working good a couple of days ago. now it doesnt work anymore...
Comment: @JohnConde you are a genius. thank you +1 haha.
Answer: When you use switch, the first case which returns a value equal to the given one is selected. In this case, your argument (zero) is a false-y value. That's why the first case that returns false is chosen: "Frequent".
To fix it, you can do this:
if ($n<50) {
  $type = "New";
} else if ($n>=50 && $n<250) {
  $type = "Frequent";
} else if ($n>=250 && $n<1000) {
  $type = "Master";
} else {
 $type = "undefined";
}

If you still want to use switch, you can change the argument to true:
switch (true) {
    case ($n<50): $type="New"; break;
    case ($n>=50 && $n<250):$type="Frequent";break;
    case ($n>=250 && $n<1000): $type="Master";break;
    default: $type="undefinded";
}

Here, the first case which returns true will be used.


Como pegar a última venda de cada cliente

Question: Eu tenho uma tabela de clientes:
----------------------------------------------------
codigocliente || razao        || cidade   || estado
----------------------------------------------------
0001          || Sup. Mercado || Londrina || PR
----------------------------------------------------
0002          || Super Pão    || Arapongas|| PR
----------------------------------------------------
0003          || Loja Comer.  || Cambé    || PR
----------------------------------------------------

e uma tabela de nota fiscal:
----------------------------------------------------
n_nota || valor_nota || dt_emissao || codigocliente
----------------------------------------------------
0001   || 1000,00    || 2021-01-01 || 0001
----------------------------------------------------
0002   || 2500,00    || 2021-02-13 || 0002
----------------------------------------------------
0003   || 800,00     || 2021-02-27 || 0001
----------------------------------------------------
0004   || 1500,00    || 2021-03-20 || 0003
----------------------------------------------------

SELECT
    c.codigocliente,
    c.razao,
    c.cidade,
    c.estado,
    MAX(nf.dt_emissao),
    nf.valor_nota
FROM clientes c
LEFT JOIN nota_fiscal nf ON nf.codigocliente = c.codigocliente
GROUP BY c.codigocliente;

Como pegar o valor da ultima compra referente a ultima data?
Comment: Qual a versão do seu MySQL?
Comment: Versão do banco 10.4.6-MariaDB
Comment: Consegue adicionar os scripts de criação e dados?
Comment: http://sqlfiddle.com/#!9/541c882/12
Answer: Para fazer isso pode quebrar isso em duas queries.
A primeira vai retornar o n_nota da data mais recente agrupada por cliente:
SELECT MAX(n_nota) n_nota
  FROM nota_fiscal nf1
 GROUP BY codigocliente

Dai basta adicionar essa subquery e fazer o JOIN de nota_fiscal com essa query, para garantir que pega os dados da nota_fiscal correta:
SELECT
    c.codigocliente,
    c.razao,
    c.cidade,
    c.estado,
    nf.dt_emissao,
    nf.valor_nota
FROM clientes c
LEFT JOIN nota_fiscal nf ON nf.codigocliente = c.codigocliente
INNER JOIN
    (SELECT MAX(n_nota) n_nota
       FROM nota_fiscal nf1
      GROUP BY codigocliente) AS aux
      ON nf.n_nota = aux.n_nota
GROUP BY c.codigocliente;

Repare que, no SELECT principal, está pegando diretamente a data e valor, isso porque o último JOIN (nf.n_nota = aux.n_nota) garante que o registro em "nota_fiscal" é o mais atual, que é o n_nota retornado na subquery.
Pode ver funcionando aqui: http://sqlfiddle.com/#!9/541c882/11
UPDATE: após os comentários, ao testar a query acima para trazer os clientes sem venda, ao substituir o INNER JOIN por LEFT JOIN retorna os dados do cliente, porém não traz corretamene o registro da venda, por causa do SELECT que faz o cálculo do MAX(n_nota). Para resolver isso, adicionei mais um nível na query, para o LEFT JOIN com "clientes" ser o único JOIN no "primeiro nível" da query, assim:
SELECT
    c.codigocliente,
    c.razao,
    c.cidade,
    c.estado,
    nf.dt_emissao,
    nf.valor_nota
FROM clientes c
LEFT JOIN (
  -- dados da nf mais recente
  SELECT codigocliente,
         dt_emissao,
         valor_nota
   FROM nota_fiscal nf1
  INNER JOIN
        -- nf mais recente
        (SELECT MAX(n_nota) n_nota
           FROM nota_fiscal
          GROUP BY codigocliente) AS aux ON nf1.n_nota = aux.n_nota
        ) AS nf ON nf.codigocliente = c.codigocliente
GROUP BY c.codigocliente;

Comment: Certo, mas eu preciso que os clientes sem venda apareça nesta consulta também, como fazer?
Comment: basta mudar o INNER JOIN para LEFT JOIN, que vai trazer os registros que existam em clientes em não na subquery, assim com o outro JOIN :)
Comment: Usei o left Join, mas não trouxe o valor correto referente a data.
Comment: então precisa olhar os seus dados, acabei de fazer essa change que te falei, adicionei outro cliente sem venda e retorna, veja aqui: http://sqlfiddle.com/#!9/83c41b/1
Comment: No próprio exemplo que vc me passou, quando uso INNER JOIN me traz o valor da ultima data, quando uso LEFT ele me traz o valor da primeira data,
Comment: edite o script e coloque os dados que tem, eu montei esse baseado no que tem na pergunta e pode estar diferente
Comment: Blz, vou tentando aqui, Obrigado!
Comment: @MarcosVinicius fiz um teste e consegui replicar o problema, fiz uma alteração na query e coloquei da pergunta, veja lá


How do elements of $\mathbb{R}(xy,x+y)$ look like?

Question: I have problems with determining what are typical elements of such field $\mathbb{R}(xy,x+y)$
In one indeterminate it is easier as
$\mathbb{R}(x)=\Bigl\{\frac{f(x)}{g(x)}, g(x)\neq 0, f(x),g(x)\in\mathbb{R}[x]\Bigr\} $
where
$f(x)=a_{0}+a_{1}x+a_{2}x^2+\dots+a_{n}x^{n}$
$g(x)={b_{0}+b_{1}x+b_{2}x^2+\dots+b_{n}x^{n}}$
and by translating the above case, we get something like this
$\mathbb{R}(xy,x+y)=\Bigl\{\frac{f(xy,x+y)}{g(xy,x+y)}, g(xy,x+y)\neq 0, f(xy,x+y),g(xy,x+y)\in\mathbb{R}[xy,x+y]\Bigr\} $
but does $f(xy,x+y)$ really mean? Can we take for example
$f(xy,x+y)=5xy-3(x+y)$?
Can someone give me example of non trivial elements belonging to the above field?
For example is it true that  $(xy)^2=x^2y^2\in \mathbb{R}(xy,x+y) $?
Comment: You need to define what $\mathbb{R}(xy, x+y)$ really is. Is it the field of fractions in two indeterminates, called for some reason "$xy$" and "$x+y$"? Is it the subfield of $\mathbb{R}(x,y)$ generated by $xy$ and $x+y$?
Answer: This is the field of all rational functions symmetric in $x$ and $y$. So for example it contains
$x^3+y^3+5x^2y+5xy^2 -x-y$ since this is symmetric in $x$ and $y$.
$x+y$ and $xy$ are the elementary symmetric functions and a basic theorem of algebra is the every symmetric rational functions is a rational function of the elementary symmetric functions.
Comment: Dear Rene: You wrote: "This is the *field* of all *polynomials* symmetric in x and y". But there is no such *field*. The polynomials symmetric in x and y form a *ring*.
Comment: @Pierre-YvesGaillard oh sorry I meant rational functions.
Comment: Great answer! +1
Answer: HINT
You can "build these up". Notice that $\mathbb{R}(xy,x+y) = \mathbb{R}(xy)(x+y)$.
This is similar to $\mathbb{R}(x+y)$ but instead of having coefficients in $\mathbb{R}$, the coefficients are in $\mathbb{R}(xy)$.


Example of two atlases on a manifold $M$ which give rise to different sets of smooth functions on $M$.

Question: Lee states that there will be many possible atlases that give rise to the same smooth structures on a manifold $M$; that is they determine the same collection of smooth functions on $M$.
Unfortunately, I don't see how different atlases will give rise to different collections of smooth functions in the first place.
For example, I'm struggling to think of two atlases on $\mathbb{R}$ which would not give the same collection of smooth functions; namely the ones in the sense of ordinary calculus.
Could someone provide me with an example of a manifold and two atlases on this manifold such that the collection of smooth functions determined by the atlases are not equivalent?
Answer: Let $\{(U_\alpha,\phi_\alpha)\}_{\alpha\in\mathcal{A}}$ and $\{(U_\beta,\phi_\beta)\}_{\beta\in\mathcal{B}}$ be two smooth (that is $\mathcal{C}^{\infty}$) atlases on a topological manifold $M$. By definition the  $\mathcal{C}^{\infty}$-structures defined by these two atlases are equivalent if their union $\{(U_\alpha,\phi_\alpha)\}_{\alpha\in\mathcal{A}\cup\mathcal{B}}$ is also a smooth atlas, that is, the transition maps between the charts of different atlases are smooth. It can be shown, that this definition, is equivalent to saying that two $\mathcal{C}^{\infty}$-structures are equivalent if they determine the same set of smooth functions $f:M\rightarrow\mathbb{R}$.
Here is an example of two non-equivalent $\mathcal{C}^{\infty}$-structures:
Consider the topological manifold $\mathcal{N} = \mathbb{R}$ equipped with the $\mathcal{C}^{\infty}$-structure determined by the $\mathcal{C}^{\infty}$-atlas consisting of the single chart $(\mathbb{R}, Id)$.
Next consider $\mathbb{R}$ equipped with the $\mathcal{C}^{\infty}$-structure determined by the $\mathcal{C}^{\infty}$-atlas consisting of the single chart $(\mathbb{R}, \phi)$ where $\phi(x) = x^{3}$.
We can now show, that each one of the above $\mathcal{C}^{\infty}$-atlases (and thus: their  $\mathcal{C}^{\infty}$-structures) are non-equivalent (because,  for example, the change of coordinates: $[Id\circ\phi^{-1}](x)=x^{1/3}$ is not smoothly differentiable at $0$), therefore, the $\mathcal{C}^{\infty}$-structures determined by them are different.
Comment: Ok. So atlas 1 givesthe collection of all smooth functions on $\mathbb{R}$ as in calculus, while atlas 2 gives the collection of functions which are smooth when composed with $x^{\frac13}$, so for example $x^3$.
Comment: Yes, this is what I had in mind.


Thread is created but not executed

Question: I have a DLL which is used by an ATL-COM component. Inside my DLL, a method StartMonitoring gets called from FinalConstruct. I want to create background thread inside StartMonitoring(), but the thread is created and a valid handle is returned yet the code inside the thread never gets executed. Does this have to do something with the way ATL components work? Please excuse me if its a dumb question but i do not have any ATL/COM understanding.
Here i believe it has something to with the way COM works. In my case i need StartMonitoring to start a background thread and when StopMonitoring is called from FinalRelease() will signal this background thread to quit and then Wait for it to quit. Now because the Thread is not started but have given a valid handle, StopMonitoring will signal and wait for ever. If i forcibly end StopMonitoring by bypassing Wait and return to FinalRelease(), MonitorThreadProc then starts execution.
<code>unsigned int WINAPI CMonitor::MonitorThreadProc(LPVOID lpvParam)
{
    std::cout << "Enter MonitorThreadProc" << endl;   //Never hits this
    if (lpvParam == nullptr)
        return 1;

    CMonitor *pMonitor = static_cast<CMonitor*>(lpvParam);
    return (unsigned int)pMonitor->Run();
}

void CMonitor::StopMonitoring()
{

    if(m_EvtReg)
    {
        m_EvtStopMonitoring.Set();
        DWORD dwResult = ::WaitForSingleObject(m_hThread, INFINITE);
        if(dwResult == WAIT_OBJECT_0)
        {
            cout<<"Thread terminated"<<endl;
        }

    }
    m_EvtReg.Close();
    m_EvtStopMonitoring.Close();
    HANDLE h = m_hThread.Detach();
    CloseHandle(h);
}

bool CMonitor::StartMonitoring()
{

    int num = 0;
    unsigned int nThreadId = 0;
    HANDLE hThread = (HANDLE)_beginthreadex(nullptr, 0, MonitorThreadProc, (LPVOID)this, 0, &nThreadId);
    if(hThread == nullptr)
    {
        return false;
    }
    //I get a valid handle from _beginthreadex, but the thread never gets executed.
    m_hThread.Attach(hThread);
    return true;
}
</code>
Comment: Any chance `StartMonitoring` is called from `DllMain`
Comment: @rustyx Problem is not with the _beginthreadex, i have used it in plenty of code and not a new thing. Here i believe it has something to with the way COM works. In my case i need StartMonitoring to start a background thread and when StopMonitoring is called it will signal this background thread to quit and then Wait for it to quit. Now because the Thread is not started but have given a valid handle, StopMonitoring will signal and wait for ever. If i forcibly end StopMonitoring by bypassing Wait, then the MonitorThreadProc executes, which is totally out of sink
Comment: When you are expecting that `MonitorThreadProc` starts and it does not, I think you could break in with debugger and check threads. Perhaps something there suggests what exactly is locked and prevents from new thread to start.
Comment: If the COM server calls it while itself being loaded (i.e. from its DllMain), thread creation will fail.
Comment: @RomanR.The thread just is created and thats it, the callstack shows just ntdll.dll!78d820c kind of frame. And it only starts working after FinalRelease is done which is pointless in my case
Comment: @rustyx StartMonitoring is called from FinalConstruct(). So its not DLLMain
Comment: The odds that you can see std::cout output from an ATL component are rather low.  It is not obvious why you use cout at all, you of course favor using a debugger breakpoint instead.
Comment: @HansPassant I'm able to see cout working on main thread. Anyways, have debugger connected and never seen the BG thread being executed until the Main thread is done with its work, Only after that BG starts execution.
Answer: The odd behaviour was due to the loader lock held during the DLL load . Until the loader lock is held , thread is never scheduled and hence I was not seeing the code execution.

Thread is created but not executed


JavaScript interpreters on older Debian installations (sarge)

Question: I am goign to write a few scripts for managing tasks via command line on the servers.
I will use the NodeJS Debian package in servers that support it, but I have a few servers still in Debian 3.1 (sarge).
I know that these servers have the Rhino package, the scripts I write may still run the same way on Rhino? (considering I do not use new JavaScript features that may not be available)
If not, what interpreter can I use for JS command line scripting on older Debians that will be compatible with the scripts I run via NodeJS on the newer Debians?
Answer: I don't think it would be possible to write anything non-trivial that would work on both new Node.js and old Rhino.
But if you are able to install packages on those old systems then you are presumably also able to install software from source (at least you have to if you want to install your own software there).
Installing Node from source is not difficult - see my recent answer about installing Node from source (see the Update part). You can even install Node specifically along your own scripts to not clobber the file system.
For example, let's say that you want to install your scripts in /opt/X (substitute a better name for X), you might do it like this:
# create a directory:
mkdir -p /opt/X/node-src

# change dir:
cd /opt/X/node-src

# download the Node source:
curl -O https://nodejs.org/dist/v4.4.5/node-v4.4.5.tar.gz

# extract the archive:
tar xzvf node-v4.4.5.tar.gz

# go into the extracted dir:
cd node-v4.4.5

# configure for installation:
./configure --prefix=/opt/X/node-v4.4.5

# build and test:
make && make test

# install:
sudo make install

# make a symlink to that version:
sudo ln -svf /opt/X/node-v4.4.5 /opt/X/node

# create a directory for your scripts:
mkdir /opt/X/scripts

And now put your scripts in /opt/X/scripts and remember to start them with a line:
#!/opt/X/node-v4.4.5/bin/node

(for a given version)
or:
#!/opt/X/node/bin/node

(using your symlink)
Adding /opt/X/scripts to your PATH by using something like:
PATH="/opt/X/scripts:$PATH"

somewhere where you set up the PATH (like .profile or .bashrc) will make it easy to execute your scripts. If you want both your scripts and node/npm binaries easily executable you can set the PATH like this instead:
PATH="/opt/X/scripts:/opt/X/node/bin:$PATH"

Of course you can change the "X" to a better name, or install node in /opt/node like I described here or anywhere else if you want (of course remember to put your own paths in the commands above).
That way you can have a modern, secure and consistent version of Node on your machines. This is what I would recommend in this situation because writing that code that would work on new and old Node and on Rhino (and do anything useful) doesn't seem easy or even possible. Node is not only JavaScript but also a complicated I/O system, libuv and the entire ecosystem of npm modules.
As the old saying goes, "It's easier to port a shell than a shell script" (Larry Wall) so in your case it may be actually easier to install Node along with your scripts than to write your scripts in a way that would work without Node (though if you manage to do it then please post a comment here, I would certainly want to know how you did it).


ASP.NET MVC input number

Question: Estou tentando usar um input com type=number, porém no Chrome está dando que o valor informado deve ser um número.
O problema está no model state que está retornando inválido, pois ao dar o post, está entrando no Create.
Já implementei o globalize como nessa resposta, porém não resolveu o caso.
Minha view
@model WebApplication24.Models.Produto

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Produto

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Descricao, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Descricao, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Descricao, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Valor, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Valor, new { htmlAttributes = new { @class = "form-control", @type = "number", @step = "any" } })
                @Html.ValidationMessageFor(model => model.Valor, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Quantidade, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Quantidade, new { htmlAttributes = new { @class = "form-control", @type = "number", @step = "any" } })
                @Html.ValidationMessageFor(model => model.Quantidade, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.ValorCusto, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.ValorCusto, new { htmlAttributes = new { @class = "form-control", @type = "number", @step = "any" } })
                @Html.ValidationMessageFor(model => model.ValorCusto, "", new { @class = "text-danger" })

                <input type="submit" value="Create" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

}

Meu bundle
 var bundle = new ScriptBundle("~/bundles/jqueryval") { Orderer = new AsIsBundleOrderer() };

            bundle
                .Include("~/Scripts/jquery.validate.js")
                .Include("~/Scripts/jquery.validate.unobtrusive.js")
                .Include("~/Scripts/globalize.js")
                .Include("~/Scripts/jquery.validate.globalize.js")
                .Include("~/Scripts/methods_pt.js");
            bundles.Add(bundle);

methods_pt
jQuery.extend(jQuery.validator.methods, {
    number: function (value, element) {
        return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
    }
});

Pacotes instalados

Microsoft.AspNet.Mvc.pt-br version="5.2.3"
jQuery.Validation.Globalize version="1.1.0"
jquery-globalize" version="1.1.1"

--

Editei o código da view realizando as sugestões do Márcio, mas mesmo assim continua dizendo que o valor informado não é válido

Adicionei os códigos do exemplo ao meu GitHub
Answer: Dei uma olhada no seu código, para corrigir altere seu arquivo methods_pt.js para o seguinte código.
$.validator.methods.range = function (value, element, param) {
  var globalizedValue = value.replace(".", "");
  globalizedValue = globalizedValue.replace(",", ".");
  return this.optional(element) ||
    (globalizedValue >= param[0] &&
     globalizedValue <= param[1]);
};

$.validator.methods.number = function (value, element) {
  return this.optional(element) ||
    /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/
        .test(value);
};

Espero ter ajudado.
Answer: Acredito que você não tenha colocado um atributo necessário (acredito que só no chrome) do comportamento dos passos (step). Como terá numeros decimais, o chrome entende que 1 não é igual a 0.1, obviamente. então coloque como atributo o step="any" para todos os campos number
@Html.EditorFor(model => model.number_value, new { htmlAttributes = new { @class = "form-control", @type = "number", @step = "any" } })

e se necessário um MIN e um MAX;
Answer: Acho que você precisa mudar a configuração do Globalization no web.config da aplicação, para que o modelBinder funcione corretamente, procure pela tag
<configuration>
...
   <system.web>
   ...
      <globalization culture="pt-BR" uiCulture="pt-BR" />

Fonte
Fonte 2
Comment: já está dessa forma o meu web.config
Comment: No seu modelo, os campos são Double?
Comment: São decimal, postei na pergunta o link pra download do projeto
Comment: @PabloVargas, olhei o projeto e não achei nenhum problema. Acho que então você vai precisar implementar O Binder, e adicionar ele no Global.asax, segue um link de exemplo: http://www.devmedia.com.br/asp-net-mvc-manipulando-valores-monetarios/28907
Answer: Crie um arquivo .js com o seguinte trecho de código.
(function ($) {
    $.validator.methods.range = function (value, element, param) {
        var globalizedValue = value.replace(",", ".");
        return this.optional(element) || (globalizedValue >= param[0] &&
        globalizedValue <= param[1]);
};

$.validator.methods.number = function (value, element) {
    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:
    [\.,]\d+)?$/.test(value);
};

//Date dd/MM/yyyy
$.validator.methods.date = function (value, element) {
    var date = value.split("/");
    return this.optional(element) || !/Invalid|NaN/.test(new Date(date[2], date[1], date[0]).toString());
    };
})(jQuery);

Referencie este arquivo depois do arquivo jqueryvalidate.js, assim sobre escrevendo o método original.

ASP.NET MVC input number


Store custom checkout pane data to order

Question: I've created a custom checkout pane according to documentation. When I submit my Order and go to admin page, where all my orders are listed, I can't see this custom pane field there. I've already tried to add $this->order->save(); at the end of submitPaneForm function but that seems to make no difference. I've already created field with machine name "field_test_me" in my Order type and also have added this field to enabled fields on "Manage display" tab, but the field seems to be empty.
Is there anything I'm missing to get my custom pane fields to be displayed on the "Order detail" page, please?
This is how my buildPaneForm function looks like:
public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form)
{
$pane_form['billing_info'] = [
  '#type' => 'fieldset',
  '#title' => $this->t('@title', ['@title' => $this->configuration['title']]),
];

$pane_form['billing_info']['field_test_me'] = [
  '#type' => 'textfield',
  '#title' => 'Test me',
  '#wrapper_attributes' => [
    'class' => ['col-md-6']
  ],
  '#default_value' => 'MY CUSTOM STRING'
];
return $pane_form;

}
And this is how my submitPaneForm function looks like:
public function submitPaneForm(array &$pane_form, FormStateInterface $form_state, array &$complete_form)
{
    $values = $form_state->getValue($pane_form['#parents']);
    $this->order->setData('field_test_me', $values['billing_info']['field_test_me']);
}

I'm using other functions for displaying value on "Review" page, but those are not part of my issue.
Answer: I found a solution. With my custom field called "Test me" and machine name "field_test_me" created in my Order Type entity I could save the data from Custom Checkout Pane with $this->order->set() function instead of $this->order->setData(). Of course I needed to change $this->order->getData() to $this->order->get() everywhere where used.
I don't understand what's the difference between set() and setData(), but it seems to store my Custom Checkout Pane values to my custom fields created in my Order type entity.
Comment: Thanks I'm working on the same thing. I believe setData() is a way to set miscellaneous "extra" data (just as a key/value pair), but I can't figure out how to get that data to show up on the admin orders page.

So setting the value of an existing field seems like the way to go. It's already being output in the twig template for the admin order page.

I was going to try to use the twig file 'commerce-order--admin.html.twig' and output the extra data, but of course I'm not using my custom theme on the admin area. So that twig template is kind of useless for me.
Answer: I'm doing it this way:
public function submitPaneForm(array &$pane_form, FormStateInterface $form_state, &$complete_form) {
     // save the data
    $values = $form_state->getValue($pane_form['#parents']);
    $this->order->setData('send_gift_to_recipient', $values['send_gift_recipient']);
    $this->order->setData('gift_recipient_address', $values['gift_recipient_address']);
    $this->order->save();
}

Then I copied the twig file: commerce-order--admin.html.twig from /modules/contrib/commerce/modules/order/templates into my custom module templates directory (uslhs_checkout_pane/templates).
In my checkout pane module file: uslhs_checkout_pane.module I've added this code to override the Commerce Orders twig file and use mine instead:
/**
 * Implements hook_theme().
 */
function uslhs_checkout_pane_theme($existing, $type, $theme, $path) {
  return [
    'commerce_order__admin' => [
      'base hook' => 'commerce_order',
      'render element' => 'elements',
    ],
  ];
}

function uslhs_checkout_pane_preprocess_commerce_order(array &$variables) {
  $order = $variables['elements']['#commerce_order'];
  $variables['send_gift_to_recipient'] = ($order->getData('send_gift_to_recipient') == 1) ? 'Yes':'No';
  $variables['gift_recipient_address'] = $order->getData('gift_recipient_address');
}

Clear the cache to have it read the new twig file. I had to use Drush to clear it, when I used the Drupal UI my template still wasn't taking effect. But doing a Drush cr did the trick.
And then finally in my twig file I've added these lines:

{{ 'Send gift to recipient'|t}}: {{ send_gift_to_recipient }}

{{ 'Gift recipient address'|t}}: {{ gift_recipient_address }}


jQuery image src change every 8 seconds

Question: I have a div with the ID of header, what id like is the first image found in this id to change every 8 seconds. The image name is image1.jpg and after 8 seconds id like it to change image1 to image2 then after another 8 seconds revert back to image1 and so forth.
Is the route of finding the first image in the div etc a bit long winded and how would i go about the rest? For instance getting the src to change every 8 seconds? Help much appreciated
Comment: What have you tried so far? Getting the first image element is simply `$('#header img').first()`. As for changing the image: http://stackoverflow.com/questions/10415932/change-jquery-image-src-dynamically/10416038.
Comment: http://mattgemmell.com/2008/12/08/what-have-you-tried/
Comment: to get the src you can do `var src = $('#header').attr('src');` then change it at will so only thing left would be to have a timeout function that runs every 8 seconds that pulls the next image src, maybe store all src's in an array or something
Comment: do u want to use a slider ?
Answer: You can try
var $img = $('div#header img').first();
var flag = false;
setInterval(function(){
    $img.attr('src', 'image' + (flag ? 1 : 2) + '.jpeg' );
    flag = !flag;
}, 8000);

Functional Demo: Fiddle (Note: This does not work with image, but just a demo for the technique used. Check the console to see the src value)
Comment: @JeffersonHenriqueC.Soares updated to support the change back
Comment: @EnterJQ This is the ternary operator http://en.wikipedia.org/wiki/%3F:#JavaScript / http://msdn.microsoft.com/en-us/library/ie/be21c7hw(v=vs.94).aspx
Comment: You should use setInterval, @John wanna image `src` changed back
Comment: @JeffersonHenriqueC.Soares Yes you are right, will make the correction
Comment: @ArunPJohny in that idea it would be easier to use a boolean and do `(flag)?1:2` and to invert the it you do `flag = !flag` instead of doing another if
Comment: Please any one can tell , what going on here ?  (flag == 0 ? 1 : 2)
Comment: @EnterJQ i thing that line is wrong it should be `((flag == 0)? 1:2)`
Comment: @EnterJQ its the same as `flag = if(flag ==0) 1 else 2` but more nice to read
Comment: @HugoAlves Yes you are right, it would be easier to a boolean flag
Comment: @ArunPJohny if i later add a third image (being image3) would i just change flag ? 1 : 2 to flag ? 1 : 2 : 3 ?
Other than that this works perfectly. Thank you!
Comment: @John No, it won't work like that. I've an updated solution at http://jsfiddle.net/uxZfq/3/ . Here you can decide where to reset the counter based on the iteration you want
Answer: assuming the first image is image1.jpeg then at the first run you what it to be 2 so use ++i to increment first then use the var in the string
var i = 0;
setInterval(function() {
     if(i == 2) i=0;

     $('#imageID').attr('src', 'image' + (++i) + '.jpeg' );
}, 8000);

jQuery image src change every 8 seconds


Beginning counterpoint above or below a cantus firmus

Question: I have more questions on the Study of Counterpoint:

Must the cantus firmus always start on the tonic?
If the cantus firmus is in the bass then can the counterpoint start with something other than a tonic like a third or dominant?
If the cantus firmus is in the top voice then should the counterpoint start with the tonic,
why can't it start with the fifth?
Answer:
Yes.
Strictly speaking the counterpoint must begin on either the fifth, octave, or unison - the last being the least common.
If the counterpoint is below the cantus firmus then it must begin with the octave or unison.  It cannot start with the fifth degree of the scale because when a perfect-fifth is inverted, it becomes a fourth, which Fux and others categorize as a dissonant interval. Since you cannot begin counterpoint, much less begin a downbeat with a dissonant interval, starting with the fifth is not allowed.  In addition, the counterpoint must be written in the some mode as the cantus firmus.  To begin the counterpoint on the fifth degree of the mode would be to imply a different modal sonority and would be therefore incorrect as well.

Hope that helps.


purpose of background dataset for shap library deep explainer?

Question: I was going through a tutorial for Deep Learning Model Interpretation Using SHAP when I came across this code block:
# select backgroud for shap
background = x_train[np.random.choice(x_train.shape[0], 1000, replace=False)]

# DeepExplainer to explain predictions of the model
explainer = shap.DeepExplainer(model, background)

# compute shap values
shap_values = explainer.shap_values(x_test_each_class)

What is the purpose of this background dataset?
Comment: Background is training dataset for the SHAP exercise.  You set background sample as your trained model which you then use to pass your data point(s) of interest to pass through and average for missing features. You'll change background and you may get different Shapley values
Comment: You don't retrain model. You use background dataset to learn Shapley values the SHAP way.
Comment: Can you elaborate on the sentence "you set background sample as your trained model"? I thought the `model` variable already held all the information for my trained model. Why does SHAP need the background dataset to train again?
Answer: Consider a scenario involving four features: A, B, C, and D.
For an individual i, their respective feature values are 4, 6, 7, and -1.
In the context of calculating the "average marginal contribution" of the C feature when it is introduced to a combination of features A and B for individual i (a key step in calculating the Shapley value), the following procedure is employed:

Maintain the values of features A, B, and C fixed for individual "i" (A = 4, B = 6, C = 7).

Create an artificial individual j, who has equal values of A and B as individual i.

Randomly select a donor.

Utilize the donor's value of feature D as the value for feature D of both individual i and j (e.g. donor has a D value of 3).

Use the donor's value of feature C as the value for feature C of individual j (e,g.donor has a C value of 9).

Ultimately, calculate the disparity between:
a. For individual "i": f(A = 4, B = 5, C = 7, D = 3)
b. For individual "j": f(A = 4, B = 5, C = 9, D = 3)
Repeat the steps from 2 to 5 iteratively. This iterative process effectively mitigates the effects of feature D, allowing the determination of the isolated influence of feature C while assuming A = 4 and B = 5.
These donors are randomly drawn from backgroud distribution.
Answer: To get SHAP values, we need to compute the difference between two expectations (ref. https://arxiv.org/pdf/1705.07874.pdf - equations (8) and (9)).
We cannot compute these expectations analytically and, thus, use Monte-Carlo estimates. Background dataset is used to generate samples which are used to calculate these estimates.
And, of course, if the background dataset changes, the estimates would change and thus SHAP values would change.


Add Header and Footer on all the pages except the first page?

Question: Is there a way with the python-docx library to insert the header and footer on the whole document except on the first page?
Answer: Yes:
section = document.sections[0]
section.different_first_page_header_footer = True
header = section.header

This setting is section-specific, so if you have more than one section in your document (most probably don't) then you'll need to set .different_first_page_header_footer to each section on which you want that behavior.
You can also access a distinct first-page header or footer after this using:
first_page_header = section.first_page_header
first_page_footer = section.first_page_footer


what's the theory foundation of the giant component strategy?

Question: could anyone plz let me know what's the theoretical foundation of the giant component strategy?
I have used this technique to get the giant components of a not fully connected graph but i need the theory foundation of this strategy.
I appreciate any help!
Comment: Dear @F.caren, can you clarify your question? Are you wondering why giant component arise in graphs? Or about which algorithms to use to find giant components in graphs?
Comment: @Antoine Vernet thanks for your response and i mean the second one.
 If you have any further details about this strategy plz let me know?? Appreciate your help!
Answer: I am not sure what you mean by giant component strategy but as per your comment on your question, I assume that you are wondering why giant components arise in graphs.
The first thing to realise is that giant components do not arise in every graph and that a set of conditions are necessary for a giant component to arise.
In Erdos-Renyi random networks, a common type of random network, there is a high likelihood of a giant component emerging if the probability of a tie between two nodes is $p \geq \frac{1 + \epsilon}{n}$ where $n$ is the number of nodes and the constant $\epsilon \geq 0$.
For random graphs more generally, Molloy and Reed (1995) showed that a random graph is very likely to have a giant component if $\sum i(i -2)\lambda_i > 0$, where $\lambda$ is the proportion of node of degree $i$ in the graph.


How to dismiss a ProgressDialog after a specific time

Question: As shown in the code below, if a Progressdialoge exists, I want to set a new message to it, and dismiss it after 3 seconds.
In the run-time, what happens is, the old message remains set to the progressdialog and lasts for 3 seconds and then the progressdialog dismisses without the new message is set. Any suggestions?
Code:
if ( (location != null) && (mProgreeDialoge != null) ){
            mProgreeDialoge.setMessage(PROGRESS_DIALOGUE_MSG01);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

Update:
if ( (location != null) && (mProgreeDialoge != null) ){
            mProgreeDialoge.setMessage(PROGRESS_DIALOGUE_MSG01);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    mProgreeDialoge.dismiss();
                }
            }, FREEZE_PROGRESS_DIALOGUE_TIME);

Comment: Possible duplicate : http://stackoverflow.com/questions/3947080/progressdialog-does-not-want-to-update-the-message
Answer: I would use a Handler for this, and have it post the message delayed with 3000 milliseconds.
Below is a simple Handler implementation, you can extend/customize it with int arguments and the obj member too:
private final Handler mHandler = new Handler()
{
    @Override
    public void handleMessage(Message msg)
    {
        super.handleMessage(msg);
        if (mProgreeDialoge.isShowing())
            mProgreeDialoge.dismiss();
    }
};

Then after showing the progress dialog, just send a message to the handler with a delay of 3 seconds:
mProgreeDialoge.setMessage(PROGRESS_DIALOGUE_MSG01);
mHandler.sendMessageDelayed(new Message(), 3000);

Comment: In concept of using handlers, it worked now for me, but in a bit different way than yours. please have a look at the update
Comment: @Amr, sure, if you don't want to reuse the handler, or examine it's members (`arg1`, `arg2`, `obj`), it's simpler to not extend it (though you need to create a `Runnable` to run on a different thread. Glad you made it!


Confidence interval for GLM or the maximum of a function?

Question: Imagine I have a set of (xi,yi) measures.
I can show it on a scatter plot

I want to choose the value of x that maximizes  y,
or I could fit a function and find the values of the parameters that maximize that function.
To put it simple I decide to fit a general linear regression model  (quadratic on the variable)
Y=a+bx+cx^2.
I can do it with R, using the glm()  funtcion.
And I would get the values of a, b, c their standard errors  SE(a), SE(b), SE(c), R2 and more things.
And the max would be located at x=-b/2c
My question is,  How can I calculate the confidence interval for that x, the predictor?
Is it just the typical formula   x+-Z·S/sqrt(n)?
and using some result provided by R for that S?
or do I need to calculate that standard using a more complex methods, such as the square root of the sum of derivatives squared...?
Or it's something completly different?
How would you do it with a simulation with x ?
maybe calculate "y" for different values of x with perturbation.
then choose the 95% max values of y (??) and calculate the confidence interval for the associated x's ?
How would you do it?
Comment: If you want to stay frequentist you could look up the delta method which will provide a way to get standard errors for transformations of your parameters
Comment: Your first question doesn't make any sense to me. And you would need to get the full covariance matrix for the predictors. You can't just use the standard errors of the estimates themselves because they are correlated. In R you would use the vcov function to get the covariance matrix from the model.
Comment: So do you think the delta method (what I called the square root of the sum of derivatives squared...) would be appropiate to calculate the predictor's confidence interval ? And what if I prefer the likelihood methodology? Do you know of any link with examples o further information?
Comment: R glm shows the standard errors for the coefficient estimates.
Should I use them or the standard deviations instead?
And I also need to know the error for the Y, How can I get it? From the residuals deviance, using the "confint" or how?
Comment: Thanks, that was going to be related my next question,  vcov solves it. The question aboout how to get the error associated to "y" still remains.
If you create an answer joinning all your comments I could vote you.
Comment: I'm thinking that the simplest method, calculating the error of x with the errors of b and c, doesn't take into account the errors of y.
And I should do a weighted glm  in order to weight the data with its experimental error.
Comment: And my last question.  When I have already calculated the deviation of x I wanted to use the  x+-Z·S/sqrt(n) formula but this assumes normality.  What should I use instead?
Comment: Maybe it's easier to run a small simulation with pertubation.  I've added this idea as a second option.
Answer: In the comments there are good proposals, like the traditional delta method. A newer method which might be more exact, is constructing a profile likelihood confidence interval, which today is quite easy.
I will show below with an simulated example, in R. First write the linear regression (polynomial) model as
$$ Y_i = a + b x_i + c x_i^2 + \epsilon_i $$
Now, assuming $c<0$ so as to have a maximum ... (If $c>0$ the same methods will give a confidence interval for the minimum), the maximum is at
$$ M=-\frac{b}{2c} $$
$M$ is our interest (or focus) parameter, so reparametrize the regression model as
$$ Y_i = a + b x_i\left( 1-\frac{x_i}{2M}\right) +\epsilon_i $$
This is now no longer linear in the parameters, but we can fit it as a nonlinear regression model:
a <- 1
b <- 1
c <- -1/2
x <- seq(from=-5,  to=5,  by=1/3)

set.seed(7*11*13) # My public seed
Y <- a + b*x  +  c*x^2  +  rnorm(length(x), 0, 2)

mydata <- data.frame(Y, x)

mod0 <- nls(Y ~ a  + b*x*(1-x/(2*M)), data=mydata,
            start=list(a=0, b=0.5, M=2))

 summary(mod0)

Formula: Y ~ a + b * x * (1 - x/(2 * M))

Parameters:
  Estimate Std. Error t value Pr(>|t|)
a   1.2778     0.6284   2.033   0.0516 .
b   0.9671     0.1404   6.888 1.74e-07 ***
M   0.8975     0.1571   5.711 3.99e-06 ***
  ...

Now we call the confint function, which calls the profile function , doing likelihood profiling, and constructs the confidence interval from there:
 confint(mod0, 3)
Waiting for profiling to be done...
     2.5%     97.5%
0.6044179 1.2658407

We can also plot the likelihood profile for M:

Now, as an exercise readers can compare this with the delta method ...