Pizzicato notation

Question: I'm trying to figure out what (if any) norms apply to notation for pizzicato.  As explained here, we have:

Do we not have any symbols used to indicate right-hand pizzicato?  I have only seen it written out with the abbreviation "pizz" which, to avoid ambiguity, then requires a subsequent abbreviation "arco" to indicate a return to bowing!  (Not to mention the semantic ambiguity in assuming that "pizz" is right-hand pizzicato, and not any other variant.)
ETA: Given that we have symbols for virtually every other string attack and ornamentation, it would seem exceedingly odd to have no symbol for this most-common form of pizzicato.  Using the word abbreviations produces score kludges like the following. (pizz. arco, pizz. arco, ad libitum....  Heaven help us if anything unusual should happen!)

Another point of confusion: I have also seen an open circle used to indicate left-hand pizzicato, but only in scores for Paganini, like this:

Is this notation unique to Paganini?  Generally I believe/assume that notation is used to indicate the note should be played as a harmonic.
Comment: One might well ask why bother *requiring* left-hand pizz!  It's dangerously close to "composer wanking."  Typically pizz is played LH only when it's easier or faster than trying to adjust the bow-hand from bowing to pizz position or vice versa.  -- or of course when there's a pizzicato note simultaneous with bowed notes.
Comment: @CarlWitthoft that sounds like a good answer: I.e., we can say that "+" is *the* symbol for pizzicato, and it's up to the performer to decide whether to pluck with the left or right hand.  Just like it's ultimately up to the performer to choose fingering.
Comment: Only a guess - but isn't r.h.pizz the 'norm'? The main alternative in most cases to arco? Sort of datum point for bowing or not? And, whatever the sign or symbol may be, a return to arco will inevitably need a sign or symbol to direct that.
Comment: @Tim: Yes, it's arguable that right-hand pizz is the default *pizzicato*.  But no: Wherever there is a symbol that applies to each note – as is the case for every other type of pizz, as well as the more common symbols indicating martelé, détaché, tenuto, accent, harmonics, turns – no notation is needed to indicate a subsequent note is played "normally."  In all of those cases the absence of a symbol (or special instruction) means "none of the above."
Answer: @feetwet Right hand pizzicato is, as you wrote, indicated with "pizz.". There is no reason to make any other symbol for that; you can say that the word "pizz." has become the symbol. Any different symbol will just be confusing.
Using an open circle to indicate left-hand pizzicato is a really bad idea since an open circle normally means a harmonic as you wrote. So a publisher should apply the symbols in the standard way they are known to violin players when he/she publishes violin music.
New symbols are only relevant when new playing techniques are invented.
Edit 17th July 2022:
I forgot to mention that an open circle can also mean an open string. It is easy to see from the context whether it means an open string or a harmonic since there are only 4 strings and they can not be played as harmonics and any other note can not be played as an open string.
Comment: My naïve guess is that the symbol is slightly clumsy because the act of switching between bowing and pizzicato is similarly clumsy. While a single left-hand pizz can be played simultaneously or fluidly within an arco passage, with right-hand pizz you are actually switching between two mutually exclusive modes, and the use of text reflects that.
Comment: Fair enough: I just edited the question to suggest why one would expect a more concise "symbol" for right-hand pizz.
Answer: I dropped in to say "Indicating LH pizz with an open circle? Baloney! I've never seen that," but I thought I'd do my homework first. Indeed, it looks like Paganini did that himself in the 9th variation of the 24th Caprice:

... and so did the first printed edition:

It seems that, from the beginning of the notated history of left-hand pizzicato, the "o" and "+" were both present (see pages 12 and following of this very convenient dissertation); in fact de Tremais used both.
That said, common modern use has certainly settled on "+" and any use of "o" would no doubt confuse modern players.
Comment: That dissertation is an excellent reference, and well worth the read!
Answer: I believe in the Paganini the circle indicates a specific type of LH pizz., like a pull off on a guitar.
While the original question of why not a symbol instead of writing "pizz." and "arco" is an interesting one, pizzicato sections often go on for lengthy passages, and it would be inelegant to writing a pizz symbol on every note for say, an entire movement (Tchaikovsky 4th Symphony, 3rd mvt.). In a similar way, if one of the articulations indicated by a symbol continues on for a lengthy passage, the composer will usually indicate the articulation with the word rather than placing symbols on all of the notes. this then, would as with the arco indication require a norm. to indicate the end of the articulated section.
Answer: The reason right-hand pizzicato does not need a specific symbol rather than just "pizz." is that it cannot be done simultaneously with bowing other notes.  In contrast, left-hand pizzicato can be interspersed with bowing or even done simultaneously with bowing other notes.  That is its main point, actually.  So you want to have something that can be applied to single noteheads.
Comment: Well, not simultaneously, but it is certainly possible to quickly switch back and forth between pizz and arco, and then it does get a bit cluttered.
Comment: If you are at the frog you could probably squeeze in a bit of pizz.

Pizzicato notation


Why is this the $L(M)$ of this DFA?

Question: Why is this the $L(M)$ of this DFA? Can someone please explain it? I am new to this course. When I tried alone answering the question of "What is special about the words that get accepted by this DFA?" I answered that "any word that ends with a while the letter before it is not a ($\epsilon a$ for example or $ba$ or...."
Answer: First of all note that your DFA accepts the string $\newcommand{\aa}{\mathtt{a}}\newcommand{\bb}{\mathtt{b}}\aa\aa\aa$, so your characterisation of the language it accepts is a bit off.
Hint.  An inspection of the DFA reveals the following simple facts:

Reading an $\aa$ from either $q_1$ or $q_3$ brings you to the accepting state.
Reading a $\bb$ from either $q_1$ or $q_3$ brings you to the opposite state.
Reading either an $\aa$ or a $\bb$ from the accepting state $q_2$ brings you to one of $q_1$ or $q_3$.

Concentrate first on the ways you can get from the accepting state back to itself (in particular by only reading consecutive $\aa$s), and then note that the only way to get from a non-accepting state to the accepting state is to read an $\aa$.
Answer: Hint.  Your automaton is deterministic but it is not minimal. First compute its equivalent  minimal DFA and your problem will become much simpler.
Comment: Oh, we haven't learned about how to make DFA's minimal, I will look it up, thank you.
Answer: Language of automaton is just list of transitions (from where to where by each input character as we read), You've listed the list as a Regular Expression (RE). RE is just showing what should be accepted by this particular automaton not showing what the actual implementation is.
The Language is SUM of transitions:
<code>Start State : q1

End State   : q2
</code>
$\delta (q1,a) = q2$
$\delta (q1,b) = q3$
$\delta (q2,a) = q1$
$\delta (q2,b) = q3$
$\delta (q3,b) = q1$
$\delta (q3,a) = q2$

This is the basic of Theory of Computation course, I highly recommend watch tutorials or read more to concretely understand this basics.

Why is this the $L(M)$ of this DFA?


I have an error code in my getBody() function and I dont know why

Question: So I'm creating this code where the template is selected through a series of If statements.  so it is a changing variable.  I am simply trying to now replace text in the selected template and I keep getting the same error that getBody() is not a function.  Any help is greatly appreciated!
var doc = DriveApp.getFileById(templateId);
var copy = doc.makeCopy();
var destination = DriveApp.getFolderById('1mGCx4yXX_NnLHsHsGWBGkzwAVhG-cTrc');
destination.addFile(copy);
copy.setName(regno + ' statistical analysis');
var copiedTemplateId = copy.getId();

var body = doc.getBody();
var header = doc.getHeader();

Comment: What is the type for `doc`?  Where is the `getBody` method defined?  Basically, can you clarify why specifically you *expect* `getBody()` to be a function here?
Comment: The getBody() is intended to be used to replace text in the template in subsequent code after this.   the doc and getBody types i guess would be visible in the code somehow... I'm really trying to learn from scratch, so I'm not fully understanding exactly what you are asking.  this is the first time that they are mentioned in the code up until this point.
Comment: Well, the point of what I'm asking is why you expect that function to exist and what you expect it to do?  What documentation or example are you referencing?  What documentation have you looked up?
Comment: I would like that function to be able to allow me to retrieve set text within the template and replace them with data from a spreadsheet for automatic report generation.  the document is a google doc template.
Comment: Try this instead  `var doc = DocumentApp.getById(templateId)`;
Comment: this does not work either.... I really dont know what is going on.  :(
Answer: DriveApp.getFileById returns a File.
So, doc is of type File.
There is no "getBody" function for a File, at least it doesn't exist in the documentation: https://developers.google.com/apps-script/reference/drive/file
Comment: is there a way of making a file a document?
Comment: You might want to take a look at this instead: https://developers.google.com/apps-script/reference/document/document-app#openbyidid
Search "DocumentApp.openById", that returns a Document, and then you can use getBody() on that document. Good luck!
Answer: This works:
function myfunk() {
  const regno = "test";
  var file = DriveApp.getFileById("fileid");
  var destination = DriveApp.getFolderById("folderid");
  let name = regno + ' statistical analysis';
  var copy = file.makeCopy(name, destination);
  var copiedTemplateId = copy.getId();
  let doc = DocumentApp.openById(copiedTemplateId);
  var body = doc.getBody();
  var header = doc.getHeader();
  Logger.log('id: %s, body: %s, header: %s',copiedTemplateId,body,header);
}

File was a Google Document and a copied was created in the appropriate directory and renamed correctly.


How to create temporary select field?

Question: I added a field:
$form['field_brand_selector']['#type'] = "select";
$form['field_brand_selector']['#title'] = "Brand";
$form['field_brand_selector']['#required'] = false;

This field is populated dynamically using Javascript. However, if I try to save the form, I get:
Illegal choice 49124 in Brand element.

I suspect that this is because I don't have this:
$form['field_brand_selector']['#options'] = $options;

So Drupal doesn't know which values are allowed for this Dropdown Selector. But seeing as this dropdown selector is not actually a field that must be saved, is there a way to "ignore" it's submission when I press save, so that I don't get the illegal Brand element error?
Comment: "This field is populated dynamically using Javascript" - not possible. Drupal has to have all values available. You could use hidden instead.
Comment: If you don't need the select box to actually be apart of the Drupal form and you are already altering the select with javascript you could you insert the whole select item via javascript. That should stop Drupal trying to validate it.

Or if not you could probably use the form API's ajax functionality to populate the options. That is the Drupal way to have dynamic selects.
Answer: Probably a hack, but this is how I solved it:
$form['field_brand_selector'] = array(
    '#type' => 'inline_template',
    '#template' => '{{ somecontent | raw }}',
    '#context' => [ 'somecontent' =>
    '
        Brand
        <select class="" id="edit-field-brand-selector" name="field_brand_selector" readonly="readonly"></select>
    '],
    '#weight' => 8,
);

This way Drupal doesn't validate the field I added.

How to create temporary select field?


If $B$ is continuous, then there exists $T \in BL(\mathcal{H})$ so that $B(x,y)=\langle Tx,y\rangle $

Question: Let $B:H \times H \to \mathbb C$ continuous and sesquilinear where $H$ is a Hilbert space.
Show that there exists a $T \in BL(\mathcal{H})$ so that $B(x,y)=\langle Tx,y\rangle $ for all $x,y \in H$.
My ideas on $T$:
since $B$ is continuous, we know that $x \mapsto B(x,y)$ is continuous on $H$. I am shooting in the dark here, I do not see how we can define $T$ appropriately without knowing more about $B$. If $y$ were fixed, it would be simple to define $Tx=B(x,y)\frac{y}{\vert \vert y \vert \vert}$ and then we get $B(x,y)=\langle Tx,y\rangle $ for all $x,y \in H$. But, as stated, this only works for a fixed $y$, but in our case $y$ is variable.
Comment: Do we know whether $B$ is symmetric?
Comment: No we do not know
Comment: I've fixed my hint, I think it should work now. Feel free to ask any further questions (but give it a try before reading the spoilers!).
Answer: Hint: it is well known that when $H$ is a Hilbert space, the map
$$
v \in H \mapsto (-,v) \in H^*
$$
is an isomorphism. That is, for any linear continuous functional $\varphi : H \to \mathbb{k}$ (= $\mathbb{R}$ or $\mathbb{C}$) there exists a unique $v \in H$ such that $\varphi(x) = (x,v)$ for all $x \in H$.
Now, following your idea, fix $x \in H$ and consider the function $f_x(y) := \overline{B(x,y)}$. Does it have any special properties you could use?

 Note that $f_x(y)$ is linear and continuous, since $B$ is continuous and sesquilinear. Hence there has to exist a unique vector which I will define as $Tx$ for which we have $f_x(y) = (y,Tx)$ for all $y \in H$. You are left to show that $T$ is linear and continuous: this follows from the uniqueness of each $Tx$ and the continuity of $B$.


Marcar todos os checkbox de uma tabela DataTable?

Question: Tenho um ckeckbox que tem intenção de marca todas as opções disponíveis em uma tabela Jquery-DaTaTabeles, mas após á paginação os próximos Checkbox não foram marcados, ou seja, na segunda página eles já não estão mais marcados.
VEJAM:

$(document).ready(function() {
    $('#example').DataTable();

    //JQUERY PARA MARCAR O CHECKBOX
    $('#ckTodos').click(function() {
        var check = $(this).is(':checked');
        $('.marcar').each(function() {
            $(this).prop("checked", check);
        });
    });
});

<link href='https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css' rel='stylesheet' type='text/css'>

         <input type='checkbox' id='ckTodos'/>

         Name
         Position
         Office
         Age
         Start date
         Salary

         Name
         Position
         Office
         Age
         Start date
         Salary

         <input type='checkbox' class='marcar'/>

         Tiger Nixon
         System Architect
         Edinburgh
         61
         2011/04/25
         $320,800

         <input type='checkbox' class='marcar'/>

         Garrett Winters
         Accountant
         Tokyo
         63
         2011/07/25
         $170,750

         <input type='checkbox' class='marcar'/>

         Ashton Cox
         Junior Technical Author
         San Francisco
         66
         2009/01/12
         $86,000

         <input type='checkbox' class='marcar'/>

         Cedric Kelly
         Senior Javascript Developer
         Edinburgh
         22
         2012/03/29
         $433,060

         <input type='checkbox' class='marcar'/>

         Airi Satou
         Accountant
         Tokyo
         33
         2008/11/28
         $162,700

         <input type='checkbox' class='marcar'/>

         Brielle Williamson
         Integration Specialist
         New York
         61
         2012/12/02
         $372,000

         <input type='checkbox' class='marcar'/>

         Herrod Chandler
         Sales Assistant
         San Francisco
         59
         2012/08/06
         $137,500

         <input type='checkbox' class='marcar'/>

         Rhona Davidson
         Integration Specialist
         Tokyo
         55
         2010/10/14
         $327,900

         <input type='checkbox' class='marcar'/>

         Colleen Hurst
         Javascript Developer
         San Francisco
         39
         2009/09/15
         $205,500

         <input type='checkbox' class='marcar'/>

         Sonya Frost
         Software Engineer
         Edinburgh
         23
         2008/12/13
         $103,600

         <input type='checkbox' class='marcar'/>

         Jena Gaines
         Office Manager
         London
         30
         2008/12/19
         $90,560

         <input type='checkbox' class='marcar'/>

         Quinn Flynn
         Support Lead
         Edinburgh
         22
         2013/03/03
         $342,000

         <input type='checkbox' class='marcar'/>

         Charde Marshall
         Regional Director
         San Francisco
         36
         2008/10/16
         $470,600

         <input type='checkbox' class='marcar'/>

         Haley Kennedy
         Senior Marketing Designer
         London
         43
         2012/12/18
         $313,500

         <input type='checkbox' class='marcar'/>

         Tatyana Fitzpatrick
         Regional Director
         London
         19
         2010/03/17
         $385,750

         <input type='checkbox' class='marcar'/>

         Michael Silva
         Marketing Designer
         London
         66
         2012/11/27
         $198,500

         <input type='checkbox' class='marcar'/>

         Paul Byrd
         Chief Financial Officer (CFO)
         New York
         64
         2010/06/09
         $725,000

         <input type='checkbox' class='marcar'/>

         Gloria Little
         Systems Administrator
         New York
         59
         2009/04/10
         $237,500

         <input type='checkbox' class='marcar'/>

         Bradley Greer
         Software Engineer
         London
         41
         2012/10/13
         $132,000

Comment: Sugiro que você poste o HTML que é gerado, desta forma o pessoal conseguirá te ajudar melhor. Do jeito que você postou teríamos que adivinhar o que seu servidor processa.
Answer: Recomendo usar o evento de paginação: page.dt, que é disparado sempre que alguma paginação é feita.
Obs: Se sua tabela tiver ordenação ou filtro, a tabela é refeita, logo é preciso refazer as marcações. Para isso usei o evento de order.dt e search.dt.
Com esse evento é possível marcar todos os elementos caso o seu check "mestre" (marcar todos) esteja marcado.
O codigo seria:
function toggleMarcarTodos(event) {
    var $tabela = $("#example");
    var check = $("#ctl00_ContentPlaceHolder1_rptComunicado_ctl00_ckTodos", $tabela).is(':checked');
    var $checks = $('.marcar', $tabela);

    // Se a sua coluna tiver ordenacao, tem que prevenir de ordenar ao clicar no checkbox!
    event && event.stopPropagation();

    $checks.each(function () {
        $(this).prop("checked", check);
   });
}

// Se houver o evento de paginação ou ordenação ou filtro, é preciso marcar todos novamente.
$('#example').on('page.dt, order.dt, search.dt', function () {
    setTimeout(toggleMarcarTodos, 1);
});

O uso do setTimeout(..., 1) faz com que a execução da função toggleMarcarTodos seja "escalonada" para depois de todo processamento que o DataTable faz para reconstruir a tabela com os novos dados.
Coloquei um pequeno exemplo nesse JSFiddle, caso queira observar o comportamento.
Answer: Neste código todas checkbox que tiverem a class='marcar' irá receber o checked, isto irá acontecer no momento em que o script for chamado, no caso você condicionou no evento click de um outro elemento, quando a "próxima pagina" for chamada, se o evento click acontecer irá marcar todos novamente, caso o evento não aconteça ou na nova pagina os elementos não tiverem a class='marcar' isso não irá acontecer. ( Se não me engano esse script de marcar precisa ser escrito novamente após um elemento seja inserido de forma dinamica na pagina)
$('.marcar').each(function () {
   $(this).prop("checked", check);
});


How should I alter forms shown in a block?

Question: I want to alter the login form to display only the @username and @password inputs.

Is it mandatory to write another module to overwrite the user module? Can it be done from  my PHP block by using these 2 variables? If yes, how can I find the name of the variables?
What is the Drupal recommended way for doing this?
Answer: There are two ways to display only some fields:

Get the original form, and remove unneeded fields. This can be done 2 ways, in hook_form_alter() or by calling drupal_get_form() and working on outputted array. This way is risky - save handler might be unable to save if some fields it expects are missing.
Create your own form, with your own inputs, validators and save handlers. Copy strings from form you are copying to keep using any translations already available. This is safer, but requires a bit more work.

In theory you can handle form in a block with php filter. I would not recommend it. It's way more manageable to keep code in files. And if you have APC, it's also way faster. Thus, modules are the way to go.


Determining if difference is significant

Question: I work on an ecommerce site, and I'm trying to determine a feature's impact on conversion.
This is not an AB test; rather, 100% of customers had access to the feature- whether or not they used the feature is indicated in "Segment" below.
In the past 12 months:

Segment
Converted
Didn't convert
Total

Used feature
629
20,570
21,097

Didn't use feature
243,273
8,131,398
8,374,671

Plain English: Of 21,097 customers who used feature, 629 or 2.98% converted. Of 8,374,671 who didn't use feature, 243,273 or 2.90% converted.
At first glance "Used feature" has higher conversion, but I'm wondering what other calculations I need to make a statistically sound conclusion.
New to stats.stackexchange so apologies if formatting is improper!
Answer: You can do the chi-squared test and get a p-value. (I haven't done the test, so I don't know what the p-value is.)
What you cannot do — without making a big assumption — is to claim that the feature increases the probability of conversion. It may be the case that users who were more likely to convert were also more likely to use the feature. In other words, the population of customers who use and don't use the feature may not the same.
This conundrum illustrates why A/B tests are useful: by randomizing customers to use the feature or not, we make sure that those who have access to the feature are comparable (exchangeable) with those who do not and so we can draw conclusions about the feature's effectiveness to increase conversion.
Comment: Good answer. The extra information about inferences is super helpful!
Answer: If all the customers are independent (e.g. you don't have data on the same customer multiple encounters) then this is the classic 2 by 2 table that can be analyzed using a Chi-Squared test: https://en.wikipedia.org/wiki/Chi-squared_test.
Answer: Normally, testing involving two samples requires more complicated analysis than testing with one sample. But in this case, the sizes are so unbalanced that it's a reasonable approximation to just do an analysis on the smaller sample. We can take a null hypothesis that the smaller sample is from a Poisson distribution whose $\lambda$ is equal to the percentage of the large sample times the size of the small sample. That gives $0.029*20570=596.53$. This gives a p-value of 8.9%, which is not significant. You could also use a binomial distribution, which gives a p-value of 8.6%.


How to derive differential of a variable

Question: Could you please explain the following two questions relating to differential of a variable.

In the method of integration by parts using substitution, we have $u = f(x)$, $v = g(x)$, $du = f'(x)dx$, and $dv = g'(x)dx$. Is it just a definition to assign those values to the differentials $du$ and $dv$ or is it based on some logics?
How could the highlighted differentials $dt$ $du$ in the below text be derived? I tried to use the method in (1) above but it didn't work out as I got $sin\theta cos\theta (1 - r^2) + r(cos^2\theta - sin^2\theta)$.
Answer: The point is that when you do substitution, you have
$$
\int g(f(x))\,f'(x)\,dx=\int g(v)\,dv
$$
by taking $v=f(x)$. Then the formula suggest that $f'(x)\,dx=dv$. The formula for integration by parts, that comes from the derivative of a product, is
$$
\int f(x)\,g'(x)\,dx = f(x)g(x)-\int g(x)\,f'(x)\,dx.
$$
With the above convention, and taking $u=g(x)$, you get
$$
\int u\,dv=uv-\int v\,du.
$$
The second case has nothing to do with the above. The situation is that now you have a double integral. When you do substitution in a double integral, taking
$$
t=g(r,\theta),\ \ u=h(r,\theta),
$$
the change of variable is given by
$$
dt\,du=\begin{vmatrix} \frac{\partial g}{\partial r}&\frac{\partial g}{\partial \theta}\\
\frac{\partial h}{\partial r}&\frac{\partial h}{\partial \theta}\end{vmatrix}\,dr\,d\theta.
$$
For the particular choice of polar coordinates in your example, the above determinant (called the Jacobian) is $r$.
Comment: Wow! First time ever I've seen differential of a variable involving determinant. Thanks, Martin. Just a quick clarification: did you mean $\int g(f(x))\,f'(x)\,dx=\int g(v)\,dv$ instead of $\int g(f(x))\,f'(x)\,dx=\int f(v)\,dv$?
Comment: Indeed; edited.
Answer: Both t and u are functions of r and $ \theta $. Form the matrix J whose first row is
$ \nabla t $ and whose second row is $ \nabla u $. Then when we change the variables, we have the formalism of replacing the symbol $ dt du $ by the symbol $ |\det(J)| dr d\theta $ You can easily check that $ |\det(J)$ $ is r.
Comment: Thanks for your answer, @P. Lawrence. Without Martin spelling out, I don't think I could visualise your explanation.


Why the set $ \mathcal{S} = \left\{x\in\mathbb{Q} : x>0 , x^2<2 \right\} $ doesn't have the least-upper-bound in $\mathbb{Q}$?

Question: Why this set $$
\mathcal{S} = \left\{x\in\mathbb{Q} :x>0 , x^2<2 \right\}
$$
does not have a least upper bound in $\mathbb{Q}$ ?
I am not seeking for a proof, but rather want to get a clear sense that this set has no least upper bound. I know that $\sqrt2$ would the lub if the set we are working on was real numbers. But if we consider the set of rational numbers it has no lub because $\sqrt2$ is irrational? How can it be explained more clearly?
And also can you give me a nice source that explains this argument ?
Answer: Let $a$ be a rational upper bound of $S$. Prove that
$$b=\frac12\left(a+\frac2a\right)$$
is also a rational upper bound of $S$ and that $a>b$.
Answer: Hint: Let $s$ be the supremum of $S$, assuming it exists.
If $s>\sqrt2$, then we can find another upper bound between $s$ and $\sqrt 2$ (why)?
If $s< \sqrt2$, then we can find some $z\in S $ such that $z>s$. (Again why?)
Answer: If you are working in a context where the basic facts about the real numbers are already known, then you can simply apply those; given any rational upper bound $u$ to $S$, there exists another rational number $u'$ satisfying $\sqrt{2} < u' < u$, and thus $u'$ is a smaller upper bound.
Since $u$ was arbitrary, no rational upper bound can be a least upper bound.

When not working in such a context, coming up with a well-motivated proof isn't particularly enlightening (better to learn the ideas in the context of doing real analysis rather than when working under restricted conditions); the following trick derived from Newton's method to find a root of $x^2 - 2$ is instead used:
Define a function on nonzero rationals
$$ f(x) = \frac{x + \frac{2}{x}}{2} $$
If $x^ 2> 2$, then it's pretty easy to see that $f(x) < x$. Furthermore, $f$ has the distinctive property that
$$ f(x)^2 - 2 = \frac{(x^2-2)^2}{(2x)^2} $$
which, among other things, shows that you always have $f(x)^2 > 2$ when $x$ is a nonzero rational.
Note, given my comment above, this argument is meant to be one that is easily verified; it is not intended to be particularly enlightening, to be a demonstration of the tools you'll be learning, or to be something you'd be expected to be able to come up with on your own.
Comment: Aside: I wish the order of operations were universally understood, so that I could use the more legible $x+2/x$ in that numerator.
Comment: I have just come across with a definition that says:  An ordered set $S$ is said to have the least upper-bound-property if the following is true: If $E$ $\subset S$ , $E$ is not empty, and $E$ is bounded above, then sup$E$ exists in S. In my question, can we use this definition to prove that the set S has no lub because there exists no such a set $E$ ?
Answer: You got it right. Because $\sqrt{2}$ is the infimum of $\mathcal{S}$ but it doesn't belong to $\mathcal{S}$, so $\mathcal{S}$ has no least-upper-bound.
More precise, you can assume that $A$ is the least-upper-bound of $\mathcal{S}$. So $x < A$ for all $x\in \mathcal{S}$ and $A\in \mathcal{S}$, i.e A is rational . But you always can take $A'$ is rational and $A^2 < A'^2 < 2$.


Ratio of PC to Mac support hours?

Question: For purposes of a purchase of laptops for everyone in my small (15 people) organization, I have compiled a spreadsheet containing what I think is an apples to apples comparison of the cost of, among other things, supporting those seats.
I am trying to put values into fields that represent a) the number of hours per mac per week, and b) the number of hours per PC per week, that I will be spending supporting users and machines.
If you've had experience with both, I'd be curious to hear your estimate of the ratio of those two numbers (0.75? 1.5?).
I do realize that all other things are never equal, of course, so I'd be curious to hear your reasoning, and/or particulars of your environment, users, skillset, staff capacity, etc, as well.
Comment: A clearer question without all the irrelevant greek stuff would be preferred.
Comment: This is far too subjective. Not because you're comparing Macs to PCs but because you've said absolutely nothing about the applications or what these machines will be used for. That's where the real support will be.
Comment: It's actually not subjective; it's dependent on lots of variables. Regardless, I recognize that there's no one right answer, but rather a question that's likely to elicit a range of answers (Hence the title of the question). Seems like a valid query, doesn't it?
Comment: edited to try to save the question -- a bit too whimsical
Comment: Shouldn't you be comparing Apples to PCs, instead of Apples to Apples?
Answer: The hours you'll spend per machine on support will have far less to do with the platform than the user so make a decision that is sensitive to the preferences and skills of your users and proceed.
Answer: Depends also on the infrastructure you have to control things. If you have a Windows domain with 15 desktops and need to change a setting on all of them you'll have a much easier time than 15 separate Macs, likewise with AV configuration, password syncing and such. The same in reverse applies though so if you don't have a domain but do have a snow leopard/samba server you might find the Macs easier.
We support a number of Macs and by and large they require less time except where parallels/VMware is involved. There are always users that want to run PC apps and tend to use one of the above to do so. At which point your admin overhead just quadrupled. Personally I like the idea of setting up a dedicated Windows Terminal server for those users.
On average I've found Mac's do throw less grief but are harder to centrally manage. So there is a magic number in there somewhere where PCs will be easier to manage, personally I'd guess it to be around the 20 mark. Will say I haven't had much to do with Mac's enterprise config stuff (does it exist?).
and I second Niels comment about most of support going to users, regardless of platform there is always someone that unplugs their mouse.
Comment: Excellent points. We do have a Windows domain, but it seems like overkill in our case, actually.
Answer: From lots of experience in supporting organizations that had roughly equal numbers of Unix-based and Windows-based end users, the tasks and category of the end user is more important than the platform in determining end user support requirements.  Most of the end user support is typically  "would you please reset my password," reconnecting loose cables, and ensuring switches are in the ON position.  For servers support, new rollouts, updates, troubleshooting, adding features or capabilities, etc., there was roughly a 10:1 ratio between the number of technical support people required per thousand supported seats.  That is, Windows server and technical support required 10x the amount of labor hours than Unix based systems.
I don't know how that plays out for your particular organization, but in my experience the typical crossover point is at about seven to ten users.  Of course, this assumes that you do not require Windows application (typically Microsoft Office) file import/export for your task customer base.
Answer: Depends entirely on the applications involved, the tasks involved, the caliber and experience of the users, the caliber and experience of the IT staff, and a couple hundred other things. Hell, the ratio wouldn't even be the same in different departments in my own company, let alone someone else's company with zero indication of what they do...
Comment: Granted. In your experience, then, in one department? As for us, we use Google Apps and MS Office. It's an office environment, basically, with people who travel a fair amount, write, communicate and present to groups.
Comment: Office will likely be your biggest sticking point. If they're used to Windows Office it'll be a nasty transition to Mac Office, and vice versa. Significant differences in UI.
Answer: Yes, it's not an aphrodite to athena   apples to oranges comparison. (mind the pun)
What you're really asking is: Do Mac's have a lower Total Cost of Ownership (TCO) when compared to PC running Windows?
There was a whitepaper a few years back that tried to do a comparison, although all links to it seem dead! (maybe someone elses search skills are better then mine & can link a copy here). Here's a review of the whitepaper from a someone user who trashes it.  Here's a discussion of it on a Microsoft blog.
IMHO apple mac's these days are appliances (unless your doing objective-c dev work).  If  your user are only ever going use is a browser, productivity apps like word, excel do some presentations then macs are probably the way to go.
The reality is, this will not describe every user in your organization.  Most accounting & other LOB application packages are mostly Windows based.  You may be able to get away with having some users on Mac's, but not the whole business.
Answer: There are a few factors which will influence the ratio:

experience of the sysadmin on both systems: if the person is a skilled Mac user, he/she will spend much less time to resolve problems.
variety of applications used on the machines
how "computer-savvy" are the users?

I have to support both PCs and Macs in my network. I can't say that Macs (users) have fewer problems, maybe it's true that there are other kind of problems. For example, simple incompatibility problems ("emails don't look like in Outlook", VPN configuration is different).
I think in the end the ratio is near 1. Off topic: Having a heterous environment is a huge challenge and dangerous, if sysadmins lack personal experience with the different systems. But on the other hand it helps in understanding some underlying concepts, because you have multiple perspectives on the topics.
Answer: From my experience (Having supported a combination of Win95, WinNT4 and Linux from '98-'04) the time of managing the 'computers' can be automated for all platforms (dunno about mac). When fully automated the cost of supporting can drop dramatically. For Linux (and most likely MAC) you as an admin can login remotely and install/reconfigure things in a (semi) automated way.
What is important to realize is that the tools on a system is dependend on the role of the person. A 15 person company implicitly means "only 1 or 2 people peer role" so you'll have a a lot of diversity in usage patterns of those systems.
So if you can have a 'one size fits all' your cost will be much lower than a single platform (win, mac, linux,...) with different applications on each instance.
BTW: The most time is spent supporting users, regardless of the platform.

Ratio of PC to Mac support hours?


Language selector Drupal 8

Question: I can't seem to get a Language Selector to appear on my page.html.twig (or in a block). I must be doing something wrong, I can perfectly translate my content by I can't switch language (unless I change the URL myself).
Comment: Add some code bits please?
Comment: I just couldn't find any blocks but I looked in the wrong place...
Answer: This guide shows how to create a multi-lingual content.
https://www.ostraining.com/blog/drupal/d8-multi-lingual/
If not success please post some code you're trying to do. Remember to clear the cache.
Comment: Wow... I just had to press the "place block" and the Language Switcher block was there. Guess I'm still used to D7. Thanks.

Language selector Drupal 8


Pyephem localtime issue

Question: I have a time lapse python script that works fine in the uk,  it now I live in France it's still calculating on standard GMT time. How can I change the code so it represents my actual location?
<code>import sys
import os
import time
import ephem

#find time of sun rise and sunset
sun = ephem.Sun()
home = ephem.Observer()
home.lat, home.lon = '45.226691', '0.013133' #your lat long
sun.compute(home)
sunrise, sunset = (home.next_rising(sun),
                   home.next_setting(sun))
daylightminutes = (sunset - sunrise) * 1440 # find howmany minutes of daylight there are
daylightminutes = (round(daylightminutes))
sunriselessonemin = ephem.date(sunrise + 1*ephem.minute)

print "prog started at(home.date) =  %s" %(home.date)
print "datetime = %s" % time.strftime("%Y/%-m/%-d %H:%M:%S")
print "sunrise = %s" %sunrise
print "sunset = %s" %sunset
print "daylight mins = %s" %(daylightminutes)

....

while ephem.now() <= sunrise:
                time.sleep(1)
                dostuff()
</code>
The code is assuming it's sunrize/sunset at gmt time rather than my local time despite knowing my actual lat/long.
So at the present in France we are 2 hours ahead of gmt, which is no use of course.
Answer: PyEphem could not translate lat/lon into a timezone without having a built-in map of world time zone boundaries, which, alas, it does not.
But your computer operating system knows your timezone if you've set it, and PyEphem has a "localtime()" function that will ask the operating system for the time zone to use for printing a time:
https://rhodesmill.org/pyephem/date.html#time-zones
Comment: Thanks! I've found a nice example here that works nicely too - https://gist.github.com/scivision/228cad3ee5efe74dd5230ddb19bf36fe

Pyephem localtime issue


How to analyse count data

Question: I have count data on bird abundance obtained from 12 locations. I have summed the abundance for each site as I have been sampling each location twice and there is no significant difference between them (I used the Wilcoxon rank-sum test). The next variable I have is the percentage of the urban landscape at each location. I want to know whether the amount of urban landscape influences abundance. I have looked into Poisson regression, but I am new to stats and I am not sure if that is the correct test, nor how to interpret its results.
Comment: Wilcoxon comes up often when you Google "tests for non-normal data". But if the data aren't normal, what are they? Ignoring structure completely is rarely a good idea. Wilcoxon's results are hard to interpret. it's only a test of means when distributions are symmetric - counts are often heavily skewed, and so if not a test of means what is it?
That's asked somewhat rhetorically - it's a mean *rank* difference - but honestly what would one do with that kind of information?
Answer:
Poisson regression sounds fine
summing the abundance is fine, but I wouldn't use a Wilcoxon test to decide whether or not to do it; I would decide a priori whether or not I was interested in within-site variation over time, or whether there were covariates that changed over time within sites that I wanted to account for (if you don't aggregate, then you probably need to use a mixed model with a random effect of site)
in R (for example) you would use fitted_model <- glm(count ~ urban, data = ..., family = poisson) to run the Poisson model. anova(fitted_model) and the coefficient estimate in summary(fitted_model) will give you p-values for the effect of urban landscape (they're slightly different tests, the anova() result is slightly more reliable).
technically both of those tests assume you have a large data set (12 is not particularly large), so you might want to use bootstrapping or a permutation test to double-check whether your results are robust
you should definitely check for overdispersion/consider whether a negative binomial [MASS::glm.nb] (or quasi-Poisson [family = "quasipoisson"]) rather than a Poisson regression is appropriate (you might want to assume that you have overdispersion)
the coefficient for urban gives the expected increase in the natural logarithm of the number of counts for a one-unit increase in the proportion of urban landscape. If the coefficient is small, it can be interpreted as approximately a proportional change.
the DHARMa and performance::check_model() packages/functions are very useful for diagnostic checks.
Comment: Would you advise quasipoisson over poisson to account for the possibly uneven denominators (for instance, how is % urban defined, are all sampled locations really alike even if the same sq. kms, etc.)?
Comment: We didn't get much information. If the sampling effort/area/etc. is different for different sites that would typically be handled by adding an `offset(log(effort))` term to the model (to make the response effectively "counts per unit effort"). Negative binomial and quasi-Poisson approaches handle the same problem (overdispersion - one source would be additional unmeasured variation, but if you *know* the variation is from sampling effort it's better to include it directly).
Comment: `family = quasipoisson` makes some things (like checking model fit via LRT rather than Wald test) awkward
Comment: But we favor quasiX methods precisely because they're a bit robust to those usual model-based assessments, and of course they don't prevent you from using simple box plots, smoothers, and scatterplots, to basically assess distributions and trends.
Comment: I'm just saying there are tradeoffs.

How to analyse count data


WL.Server.getActiveUser returns Null

Question: I need the ability to get a users login userid/password in a java adapter. After reading lots of articles, the best way seems to be to call
WL.Server.getActiveUser from a javascript function that gets called from the java adapter. So, I added a getIdentity function to the http adapter that authenticates our app. I have verified that getActiveUser works in the authentication function that the login pages calls...
When I call the getIdentity function, getActiveUser returns null using The same authentication realm. I have set the realm in the application_descriptor file. Not sure what else I have to do. Any ideas?
function performAuthentication(username, password) {
       WL.Logger.info("In performAuthentication: username = " + username + " password = " + password + "Time = " + new Date(new Date().getTime()).toLocaleString());

        var invocationData = {
            adapter : 'BluePages',
            procedure : 'authenticate',
            parameters  : [username, password]
        };
        var invocationResult = WL.Server.invokeProcedure(invocationData);

        var fullName = invocationResult.result.fullName;
       if (invocationResult.result.success == false) {
            return {
                authRequired: true,
                loginPassed: false
            };
        }
        else {
            userIdentity = {
                userId: username,
                credentials: password,
                displayName: username,
                attributes: {
                    foo: "bar"
                }
        };

        WL.Server.setActiveUser("AuthRealm", null);
        WL.Server.setActiveUser("AuthRealm", userIdentity);
        var activeUser = WL.Server.getActiveUser("AuthRealm");
        WL.Logger.info("activeUser = " + activeUser);

        if(activeUser && activeUser.userId == username){
            WL.Logger.info("Active userId = " + activeUser.userId + " password = "    + activeUser.credentials);
            WL.Logger.info("User has been logged in!");
            return {
                loginPassed: true,
                authRequired: false,
                fullName: fullName,
                result: invocationResult.result
            };
        }
        else {
            WL.Logger.info("Else Clause...");
            if(activeUser != null)
                WL.Server.setActiveUser("AuthRealm", null);
            WL.Server.setActiveUser("AuthRealm", userIdentity);
        }

         return {
            authRequired: false,
            loginPassed: true,
            fullName: fullName
        };
    }

 }

function getIdentity() {
        WL.Logger.info("AuthAdapter: In getIdentity: Time = " + new Date(new Date().getTime()).toLocaleString());

        WL.Logger.info("AuthAdapter: userIdentity = " + userIdentity);

        var activeUser = WL.Server.getActiveUser("AuthRealm");

        WL.Logger.info("AuthAdapter: getIdentity: getActiveUser returned = " + activeUser);

        if (activeUser) {

                WL.Logger.info("AuthAdapter: getIdentity userId = " + activeUser.userId);

                return {
                    userId: activeUser.userId,
                    credentials: activeUser.credentials,
        };
     }
 }

Answer: There could be 2 reasons to get null when using WL.Server.getActiveUser:
1)If no realm is defined on the adapter, the method returns null (active user is unknown)
2)If a realm is defined on the adapter:
If there is no strong identity associated with the user (the user was authenticated in this session or in a previous session), the method returns null.
In your case you said the realm is exist so I suggest to try #2
You can find more information here:
https://www.ibm.com/support/knowledgecenter/SSZH4A_6.0.0/com.ibm.worklight.help.doc/apiref/r_method_wl_server_getactiveuser.html

WL.Server.getActiveUser returns Null


Is Harmonica Mugig 10-hole 20-tone Blues Harp similar to the others in view of blows and draws?

Question: I've just started learning to play (diatonic) harmonica, and here is my Mugig 10-hole 20-tone Blues Harp:

Its instruction manual illustrates the note pattern as the following:

But it actually contradicts the blow-draw pattern explained in most of the books including this one that says:

For example, books often say that the first hole's notes are C and D in the case of blowing and drawing, respectively; however, my harmonica instruction claims something completely reversed!
When I try simple songs based on what the instruction says, the sound is not exactly what it should be; however, I'm a beginner and my solfege skills are poor, so I can not exactly find out whether the instruction manual is correct or not.
Does anybody have any experience to use such kind of harmonica?
Update 1:
Here are some tests:

Blow hole 1
Draw hole 1
Blow hole 2
Draw hole 2
Answer: This seems to be Richter tuning, where the bottom octave is designed to provide two triads - I blowing, and V drawing. The middle and top part provide full diatonic scale notes, but missing the B draw at the very top. All this provides a simple triad of C in this case when blowing anywhere, with a G9 sound sucking above the bottom octave. So, apart from the bottom octave and the top two notes, it's just like an ordinary mouth organ.
Comment: Tim, you might want to take another look at this one, you've missed the mark entirely
Answer: That is odd!
I've never seen that before in my life.  According to your booklet, it is exactly the same as a normal harmonica, except completely backwards.
My guess would be the arrows in the book are wrong rather than the harmonica, but who knows.
Could you post a recording of simply playing a chord, blowing, and then drawing?  Doesn't have to be accurate or single notes or anything, just picking it up and blowing then inhaling will be enough to tell.
Update: I can tell from your recording that this is indeed correct: the booklet is just printed wrong and the harmonica has the normal layout.  That being said, it's also not perfectly in tune and probably is never going to sound 100% right.  If you have fun with this harmonica, then buy yourself a proper instrument, they're not crazy expensive, and you'll be able to enjoy something that will sound in tune.
For example, hohner special 20s are fantastic.  A hohner big river is fine, and suzuki/lee oskar both make decent affordable harmonicas. Easttop now makes very affordable chinese-made harmonicas: they are the first Chinese company to make a decent blues harp, and in fact they're very good.  What you have, unfortunately, is more of a toy than an instrument.
Comment: Can you please check the applied update? I recorded four tests corresponding to the first two holes of the instrument.
Comment: @Roboticist can you use soundcloud or vocaroo or something?
 The website you've linked to is err... well it's unique I'll give it that... Soundcloud is better because it doesn't expire, but vocaroo.com is very quick and easy
Comment: Sorry for the inconveniences. I just uploaded them in vocaroo. Please check the updated links.
Comment: @Roboticist in case you haven't seen, I updated my answer


Can't figure out how sum(1) is working in this query

Question: So I am trying to combine to query's and to do that I need to figure out what is going on in this one. I'm still relatively new to sql server and I am forced to dive right into some complicated qrys and sometimes I get stuck on simple things like this. My problem is that the Sum(1) function is used and I'm not entirely sure how. Meaning I believe it is counting duplicates but I cannot tell based on what information it is doing so.
this is the query
SELECT
qryReinsuranceDPA1.POLICY_NO,
qryReinsuranceDPA1.PHASE_CODE,
qryReinsuranceDPA1.SUB_PHASE_CODE,
qryReinsuranceDPA1.ProdType,
TotalDPA = Sum(case when [SumOfNetDefExtraAdj] Is Null then [SumOfNetDefPremiumAdj] else [SumOfNetDefPremiumAdj] + SumOfNetDefExtraAdj end),
Sum(1) AS Expr1
FROM qryPolicyListforNYDefPRemAsset_Re RIGHT JOIN qryReinsuranceDPA1
ON
qryReinsuranceDPA1.POLICY_NO = qryPolicyListforNYDefPRemAsset_Re.POLICY_NO AND
qryReinsuranceDPA1.PHASE_CODE= qryPolicyListforNYDefPRemAsset_Re.PHASE_CODE AND
qryReinsuranceDPA1.SUB_PHASE_CODE = qryPolicyListforNYDefPRemAsset_Re.SUB_PHASE_CODE
GROUP BY qryReinsuranceDPA1.POLICY_NO,
qryReinsuranceDPA1.PHASE_CODE,
qryReinsuranceDPA1.SUB_PHASE_CODE,
qryReinsuranceDPA1.ProdType
--HAVING (((Sum(1))<>1))

GO

And this is a small sample of what it produces (the actually results number around 77,000)
POLICY_NO    PHASE_CODE    SUB_PHASE_CODE    ProdType   TotalDPA       Expr1
228433800    0             1                 TERM       282.324223     1
228439200    0             1                 PERM       53.17048634    1
228439200    6             1                 PERM       10.3805065     1
228441500    0             1                 PERM       526.6883742    1
228441500    0             2                 PERM       10.63320899    1
228441700    0             1                 PERM       20.86247317    1
228448100    0             1                 PERM       345.2117169    1
228460200    0             1                 TERM       302.7574933    1
228464900    0             1                 TERM       191.2597906    1
228468000    0             1                 PERM       8445.190912    1
228473600    0             1                 TERM       339.8413682    **2**
228473800    0             1                 TERM       686.1766864    **2**
228477200    0             1                 TERM       583.7580207    1
228481200    0             1                 TERM       362.9472595    1
228481200    0             2                 PERM       4.217792443    1
228482500    0             1                 PERM       1894.303507    1
228482500    1             1                 TERM       1312.183889    1
228491600    0             1                 TERM       325.0796843    **2**
228494400    0             1                 PERM       748.2710255    1
228501000    0             1                 TERM       47.78070676    1
228501100    0             1                 TERM       47.78070676    1
228501300    0             1                 PERM       365.5651862    1
228501300    0             2                 PERM       12.20547324    1
228501300    1             1                 TERM       706.0961491    1
228501300    1             2                 PERM       12.46769547    1
228502000    0             1                 PERM       6562.164879    1
228502000    0             2                 PERM       184.7741277    1

The right most column is the result of the Sum(1) and what I want to know is when and why does it produce a 2.
Comment: thank you for editing it i couldn't figure out how to do that
Answer: sum(1) is exactly equivalent to count(*) - it returns a count of all the rows within the group.
It will therefore return a value of 2 when, for a given value for each of POLICY_NO, PHASE_CODE, SUB_PHASE_CODE and ProdType there are two rows in the selected dataset (before grouping).
Comment: SUM(1) = "someone"   SUM(1) forgot about COUNT(*).
Comment: Yes, but when you say "Sum(1) will provide the count" it sounds like part of a "Who's on first?" IT routine.
Comment: @HABO: Errm, what? I didn't say "Sum(1) will provide the count" and I don't know what a "Who's on first?" IT routine is.


Check if Internet access is available on Android

Question: How can i check that internet has or not. But i found this code but when wifi connected it return true, but i know that there is not internet. No internet access.
<code> public boolean chechInternet_con(){
    ConnectivityManager connec = (ConnectivityManager)
    context.getSystemService(Context.CONNECTIVITY_SERVICE);
    android.net.NetworkInfo wifi =connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    // Here if condition check for wifi and mobile network is available or not.
    // If anyone of them is available or connected then it will return true, otherwise false;

    if (wifi.isConnected() || mobile.isConnected()) {
        return true;
    }
    return false;

}
</code>
Comment: Have you tested your code in device?
Comment: This has been answered please check this link
http://stackoverflow.com/questions/11096987/check-real-internet-connection
Answer: Try this,
<code>public boolean isInternetOn(Context ctx) {
        this.mContext = ctx;
        ConnectivityManager Connect_Manager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        State connected = NetworkInfo.State.CONNECTED;
        State connecting = NetworkInfo.State.CONNECTING;
        State disconnected = NetworkInfo.State.DISCONNECTED;

        State info0 = Connect_Manager.getNetworkInfo(0).getState();
        State info1 = Connect_Manager.getNetworkInfo(1).getState();

        // ARE WE CONNECTED TO THE NET
        if (info0 == connected || info0 == connecting || info1 == connecting
                || info1 == connected) {

            Log.d("Internet", "Connected");
            return true;
        } else if (info0 == disconnected || info1 == disconnected) {
            Log.d("Internet", "DisConnected");
            return false;
        }
        return false;
    }
</code>
Comment: my device connected to wifi but no internet access, i can not enter sites:(
Comment: Can you remove this  info0 == connecting || info1 == connecting condition from the "if" and then check?
Answer: See below code
<code>    public static boolean checkConnection(Context context) {

    final ConnectivityManager mConnectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    final NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else
        return false;
}
</code>
Comment: Thank But you only are checking connected or connecting but my device connected to wifi but no internet access. i mean i can not enter any sites:(
Answer: So, its connected to wi-fi network but no internet access. Right?
Try to ping 220.127.116.11 or google.com to know whether there is internet access.
 This will help you.


Feedback form slider

Question: I have used some code for feedback form that slides up.It placed in bottom.
I want to fix it in bottom like if i am scrolling page it will fix there.
Code for it i have used :
Div Code :

  Feedback

Please Send Us Your Feedback

    <textarea id="feedback_text"></textarea>
    <input type="button" value="Send" id="submit_form" />

CSS :
.feedback{
    position:absolute;
    left:0;
    bottom:0;
}
.feedback a {
    display:block;
    height:20px;
    width:100px;
    text-align:center;
    background:red;
    border:2px solid #fff;
    outline:1px solid #a1a1a1;
    padding:5px;
    float:left;
    cursor:pointer;

    /*Font*/
    color:#FFF;
    font-weight:bold;
    font-size:18px;
}

.feedback .form{
    clear:both;
    height:300px;
    width:450px;
    border:1px solid #000;
    background:#fff;
    padding:15px;
    display: none;
}
.feedback .form textarea{
    height:170px;
    width:400px;
    padding:5px;
}
.feedback .status{
    font-size:16px;
}

jquery :
(function ($j) {

  feedback_button = {

    onReady: function () {
      this.feedback_button_click();
      this.send_feedback();
    },

    feedback_button_click: function(){
        $("#feedback_button").click(function(){
            $('.form').slideToggle();
        });
    },

    send_feedback: function(){
        $('#submit_form').click(function(){
            if($('#feedback_text').val() != ""){

                $('.status').text("");

                $.ajax({
                    type: "POST",
                    url: "./process_email.php",
                    data: 'feedback=' + $('#feedback_text').val(),
                    success: function(result,status) {
                        //email sent successfully displays a success message
                        if(result == 'Message Sent'){
                            $('.status').text("Feedback Sent");
                        } else {
                            $('.status').text("Feedback Failed to Send");
                        }
                    },
                    error: function(result,status){
                        $('.status').text("Feedback Failed to Send");
                    }
                });
            }
        });
    },

  };

  $j().ready(function () {
      feedback_button.onReady();
  });

})(jQuery);

Tell me how can i fix it in bottom.
Answer: Try this:
.feedback{
    position:fixed;
    //left:0;
    bottom:0%;
    z-index: 99;
}

Comment: Its works.But in image slider it will goes behind image .How can i take it in front ?

Feedback form slider


Is my time series stationary?

Question: I am using R and have found that both KPSS ( Kwiatkowski-Phillips-Schmidt-Shin ) and the adf (Dickey-Fuller) tests indicate stationarity, having a p-value of 0.01.
Here is a plot of the original data:

However, when I plot the correlogram, it looks as though the data are non-stationary.

So what do you think? Is the data stationary or non-stationary?
Comment: Naturally, the question still remains how strong the trend is and how much difference it makes. I am puzzled that you are in doubt about seasonality. The seasonality is evident from the graph and fits with what we know from everyday life. Learning  statistics doesn't mean that we have to test whether day and night are statistically different, although there are problems where tests really are needed. By the way, don't take me for a time series expert. I'd suspect that you got those test results the wrong way round; I don't use those tests in my practice but that's my guess.
Comment: You have trend and seasonality. Neither should be surprising. Statistics would be different without tests, but judgment is needed too!
Comment: Stationary means the distribution does not change over time. So informally if you recorded all hits on the y-axis as counts in an interval and drew a histogram of those then if you repeated this exercise you should get the same if you shift your interval by a finite amount. Non-stationarity is for example a Wiener process (random walk) where you literally can't predict where it's going next. What you plotted looks stationary to me with a tiny trend and as remarked before seasonality. Your correlogram gives you informal evidence for autocorrelation, so try and fit 3 lags and a trend.
Comment: Thanks, so the answer is: non-stationarity. Yeah? I am pretty new to stats :)
Comment: @Hirek "stationary ... with a tiny trend"; would you talk about "stationary with a large trend"? I think I know what you mean, but using terms in this way is really likely to confuse those new to the field.
Comment: A way to get which way these tests work is to create sandbox series with enormous trends and no trend at all and see which way the P-values fall. Here as elsewhere the R documentation may assume that you know exactly what you are doing.
Comment: @NickCox "I am puzzled that you are in doubt about seasonality. The seasonality is evident from the graph and fits with what we know from everyday life." Thanks, but I am not asking about seasonality. I am asking about stationarity.
Comment: Forgive for imagining otherwise. The main reason for the correlogram pattern, which you took as implying non-stationarity, is seasonality. You will find differences in the literature on whether stationarity implies lack of seasonality (so seasonality is a deviation from it) or stationarity is consistent with seasonality. If the definition of stationarity includes (e.g.) the expected value being the same everywhere, that's incorrect here in so far as the expected value is not constant at all but varies with the time of year. So, supply your exact definitions and the matter can be discussed.
Comment: Does "having a p-value of 0.01" refer to `adf.test`, to `kpss.test` or to both? Note that these have *different* null hypotheses: the null for `adf.test` is that your time series has a unit root (i.e., is non-stationary), whereas the null for `kpss.test` is that the time series is level or trend stationary.
Comment: Oh I mean the trend is clearly upward meaning a positive coefficient but it would be very small. So beta times t is your trend and beta would be a small number if you did a fit. If you want to play around a little look for OxMetrics which has a good help file.
Answer: Tests for stationarity are notorious for having weak power so keep that in mind. As mentioned in the comments, it helps to use judgement as well. A weakly stationary process by definition has a constant mean and variance.
While your correlogram (which I'm assuming is the autocorrelation function) shows significant autocorrelation, this does not necessarily mean the series is non-stationary - its telling us that the observations are not independent.
By just looking at your plot, the series does look stationary but highly seasonal.
Another diagnostic you can try, which is pretty much analogous to the ADF test, is to fit an AR(1) model to the data. If the AR(1) coefficient estimate is (significantly) less than 1, then we have evidence of a stationary process. If the AR(1) coefficient is approximately 1, the process is more likely to contain a unit-root and is non-stationary.
Comment: "the series does look stationary but highly seasonal"
Aren't seasonal series considered non-stationary because the mean varies with time?
Comment: @infinitesimal you are correct. A series with seasonality cannot be stationary as we can use the seasonal pattern to inform our predictions based on the time.
Answer: I agree with all the points regarding seasonality and visual inspection above.
One additional thing: ADF tests the null of a unit root whereas KPSS tests the null of a stationary process. So if both have a p-value of .01, you actually have conflicting results (which may happen, tests being capable of type I and II errors, of course) at conventionel levels.
Answer: The declining wave pattern in the ACF and the ACF(1) > .9 indicates nonstationarity.  If shown, the PACF would reveal a spike at PACF(1).
Transform the data to (1 - B), then examine the ACF and PACF.  If a statistically significant spike occurs at PACF(12), then the series may be seasonally non-stationary, thus requiring the series to be transformed (1 - B) (1 - B)^12 prior to modeling the residuals.
Seasonal non-stationarity is a bit tricky to identify. The guiding rule is do NOT over difference in an attempt to achieve stationarity.

Is my time series stationary?


Calculating an integral using Laplace transform

Question: I need to find:
$\int_0^\infty e^{-2t}tcos(t)dt$
Using Laplace transform.
The theorem that I'm supposed to use (I wasn't able to find the correct term in English):
Suppose $L[f(t)]=F(s).$ If $\frac{f(t)}{t}$ is an original, then $L[\frac{f(t)}{t}]=\int_s^\infty F(s)ds$.
I'm not sure how this applies here. The problems I've solved so far (and unfortunately haven't fully understood) had a distinct form of $\frac{f(t)}{t}$.
I'd be grateful if anyone could help point me to the right direction here.
Answer: $${\cal L}(\cos t)=\int_0^\infty e^{-st}\cos t\ dt=\dfrac{s}{s^2+1}$$
$${\cal L}(t\cos t)=\int_0^\infty e^{-st}t\cos t\ dt=-\left(\dfrac{s}{s^2+1}\right)'$$
then set $s=2$.
Comment: With integration by parts prove ${\cal L}(tf)=-F'$.
Comment: Forgot about that approach, I find it a bit strange that it wasn't mentioned anywhere in my book.


JOIN de 3 tabelas (LEFT JOIN)

Question: Estou com um dúvida referente a melhor forma (referente a performance e execução) de fazer o seguinte select...
Inicialmente eu pensei em utilizar o LEFT JOIN, porém me deparo com algumas restrições na sua característica do LEFT JOIN.
Tendo 3 tabelas seguintes:
SERVICO
- S_ID
- S_CODIGO
- S_STATUS

ENTREGA
- E_ID
- E_CODIGO
- E_INFO
- D_FK_ID (FK com a tabela DIARIO, coluna D_ID)

DIARIO
- D_ID
- D_DATA

S_CODIGO (tabela SERVICO) e E_CODIGO (tabela ENTREGA) são incomuns e S_CODIGO possui mais dados e a Tabela de ENTREGA pertence a uma parte desses CODIGOS (por esse motivo pensei no LEFT JOIN).
SELECT
    s.S_CODIGO AS CODIGO,
    s.S_STATUS AS STATUS,
    e.E_INFO AS INFORMACAO,
    d.D_DATA_INSERT AS DATA_CADASTRO
FROM
    SERVICO s
LEFT JOIN
    ENTREGA e
    ON e.E_CODIGO  = s.S_CODIGO

a partir desse select eu queria fazer mais um join para da Tabela ENTREGA (coluna D_FK_ID) com a Tabela DIARIO (D_ID) para buscar a coluna D_DATA_INSERT.
para retornar algo dessa forma:
CODIGO - STATUS      - INFORMACAO - DATA_CADASTRO
200    - CONCLUIDO   - DIURNO...  - 2018-11-05
201    - ANDAMENTO   - DIURNO...  - 2018-11-05
203    - CONCUIDO    - DIURNO...  - 2018-11-05
205    - CONCUIDO    - null       - null
210    - CONCUIDO    - null       - null

Answer: Basta incluir um novo join e adicionar a tabela "DIARIO":
SELECT
    s.S_CODIGO AS CODIGO,
    s.S_STATUS AS STATUS,
    e.E_INFO AS INFORMACAO,
    d.D_DATA_INSERT AS DATA_CADASTRO
FROM
    SERVICO s
LEFT JOIN
    ENTREGA e
    ON e.E_CODIGO  = s.S_CODIGO
LEFT JOIN DIARIO d
    ON e.D_FK_ID = d.D_ID

Pode adicionar quantos join forem necessários. Copiei seu exemplo e fiz um LEFT JOIN, mas poderia ser qualquer outro tipo de join.
Aqui outra pergunta similar: SQL JOIN múltiplas tabelas

JOIN de 3 tabelas (LEFT JOIN)


Logistic Regression Failed in statsmodel but works in sklearn; Breast Cancer dataset

Question: I am learning about both the statsmodel library and sklearn. I am trying to construct a logistic model for both libraries trained on the same dataset.
In sklearn, the following works:
# import the data
from sklearn.datasets import load_breast_cancer

data = load_breast_cancer()

X_df = pd.DataFrame(data.data, columns=data.feature_names)
y_df = pd.DataFrame(data.target, columns=['target'])

# split into train and test datasets
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X_df, y_df, test_size=0.2, random_state=42)

print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)

# fit the model and make a prediction
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
Xscaled  = scaler.fit_transform(X_train)

clf1     = LogisticRegression()
clf1.fit(Xscaled, y_train.values.ravel())

y_pred = clf1.predict(scaler.fit_transform(X_test))

accuracy_score(y_test.values.ravel(), y_pred)*100)

This works and gives a result of

98.24561403508771

Now I want to do something similar in the statsmodel library
I do the following (continuing in the same notebook):
import statsmodels.api as sm

Xs = sm.add_constant(Xscaled)
res = sm.Logit(y_train, Xs).fit()

But this gives an error:

LinAlgError: Singular matrix

What is causing the discrpancy between sklearn and statsmodel?
Answer: I suspect the reason is that in scikit-learn the default logistic regression is not exactly logistic regression, but rather a penalized logistic regression (by default ridge-regresion i.e. with a L2-penalty). This has the result that it can provide estimates etc. even in case of perfect separation (e.g. some predictors have all 1 or all 0) or situations where some combination of predictors results in "perfect" prediction, while standard non-penalized logistic regression runs into problems (either you think this is a legitimate infite estimate, e.g. 100% of stones thrown into the air fall to the ground, or think of this as a problem e.g. 100% of 10 people that fell out of plane died, but occasionally people will survive).
Answer: In statsmodels, GLM may be more well developed than Logit.  If you fit the model as below with GLM, it fails with a perfect separation error, which is exactly as it should.  It is also possible to use fit_regularized to do L1 and/or L2 penalization to get parameter estimates in spite of the perfect separation.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import statsmodels.api as sm
import pandas as pd

data = load_breast_cancer()

X_df = pd.DataFrame(data.data, columns=data.feature_names)
y_df = pd.DataFrame(data.target, columns=['target'])

X_train, X_test, y_train, y_test = train_test_split(X_df, y_df, test_size=0.2, random_state=42)

scaler = StandardScaler()
Xscaled = scaler.fit_transform(X_train)

Xs = sm.add_constant(Xscaled)

# Below will fail with a perfect separation error
#res = sm.GLM(y_train, Xs, family=sm.families.Binomial()).fit()

res2 = sm.GLM(y_train, Xs, family=sm.families.Binomial()).fit_regularized(L1_wt=0.0, alpha=0.1)
params = res2.params

Answer: In your data, the reason statsmodel crashes is due to highly correlated variables. If you look at your predictors:
import seaborn as sns
sns.clustermap(X_train.corr())

You can see this bunch of variables on diagonal left, perimeter,mean radius etc that is highly correlated. So if we include all of them into the fit, it is going to be hard to estimate these coefficients. We can remove these first, and fit:
import statsmodels.api as sm
excl = ['mean radius','mean perimeter','mean area',
        'worst area','worst perimeter','worst radius',
        'radius error','perimeter error','area error']
Xs = scaler.fit_transform(X_train.drop(excl,axis=1))
res = sm.Logit(y_train, Xs).fit()

Optimization terminated successfully.
         Current function value: 0.073780
         Iterations 12

This fits ok, we can check the accuracy and it's lower than what you have with scikit-learn, and I tried adding back the area, perimeter variables using PCA but it doesn't get much better:
y_scores = res.predict(scaler.fit_transform(X_test.drop(excl,axis=1)))
y_pred = (y_scores >0.5).astype(int)
accuracy_score(y_test.values.ravel(), y_pred)

0.9210526315789473

So fitting a model via maximum likelihood like in statsmodel is going to be highly unstable with high degree of collinearity. As @Björn pointed out, scikit-learn's logistic regression works because it by default uses a L2 penalty.


Identificar um clique longo com jquery

Question: Galera montei um context menu que funciona assim, quando o usuário clica com o botão direito do mouse em uma 'tr' da tabela ele se abre.
Faço assim usando jQuery:
// Verifica se abre o menu
$("tr").mousedown(function (e) {
  //AQUI FICA AS FUNÇÕES DO MENU
});

Bom, o problema é que, quando ele é aberto em um celular, não se tem o mouse.
Queria saber se tem alguma forma de identificar um clique por 2 segundos, e abrir o menu.
Então ele deverá se abrir tanto com o botão direito ou com um clique longo.
Answer: Ou você pode utilizar o evento taphold do jQuery Mobile API:

O evento jQuery Mobile taphold desencadeia-se após um evento de toque
  completo e sustentado (também conhecido como pressão longa).

Para seu caso ficaria mais ou menos:
$("tr").on( "taphold", function( event ) {
  //AQUI FICA AS FUNÇÕES DO MENU
});

Somente com jQuery, é possível calcular o tempo entre o mousedown e mouseup:

var tempo;

$("div").mouseup(function(){

  // diferença entre clicar e soltar
  var total = new Date().getTime() - tempo;
  var segundos = ((total % 60000) / 1000).toFixed(0);
  console.log(total); // total se millis
  console.log(segundos); // total em segundos

  if (segundos > 0){
    console.log("Oi");
  }

}).mousedown(function(){

  // set tempo ao clicar
  tempo = new Date().getTime();

});

  Teste

Comment: Muito com, era isso mesmo que eu precisava, mas como vou chamar a função '$("tr").on( "taphold", function( event ) {' quando o segundos for maior que 2?
Comment: Justamente, ele trata sozinho isso @HugoBorges. Por isso editei colocando o tempo em segundo somente com jQuery :)
Comment: estou tentando fazer essa verificação, 'if (segundos > 0) {console.log("oi");}' mas não funciona, vc sabe porque?
Comment: Precisava inverter os operadores para não ficar negativo @HugoBorges. Editei a resposta :)
Comment: não estou conseguindo fazer o menu abrir com um clique longo (e tenhas mais de 1 segundo), poderia me ajudar? segue meu código https://jsfiddle.net/hugoborges/50bh9t1a/2/
Comment: @HugoBorges, notei que ele está entrando na condição normalmente, mas não acontece nada na tela. Visto que é outro assunto, sugiro que abra outra pergunta se o problema for com o menu, para não ramificar essa sua pergunta.

Identificar um clique longo com jquery


Is this a held ball (which should have led to a jump ball)?

Question: Please see: https://www.youtube.com/watch?v=WxY47I-pc-Q
Greg Anthony (the commentator) is quite insistent that this should have been a jump ball.  But it looks to me that the ball was not in Hibbert's "continuous possession" (as required by the rules, see below).
Instead, it looks like Hibbert went up, Millsap blocked it, ball completely left Hibbert's hands, Hibbert rebounded the blocked shot (albeit while still in the air), and came back down with it (just like you would when getting any rebound). So this shouldn't be a jump ball (and the officials got it right with their no-call). Is my interpretation of the rules correct?

A held ball occurs when two opponents have one or both hands firmly
  on the ball or anytime a defensive player touches the ball causing the
  offensive player to return to the floor with the ball in his
  continuous possession. (p. 19 of this PDF)
Comment: Im wondering if Greg doesn't have an angle there to see that Hibbert released the ball before coming back down.
Comment: Yes but he was continuing to say the same thing even as he (and the viewers) were looking at the replay, where we could clearly see that.
Answer: Yes your interpretation of the rules is correct. The commentators get real decisive one way or another. They will argue something and not always be right. They do it so people will watch them because they actually get into the game. I dislike the commentators that just say "He shot the ball" or "Did you see that pass?" And they have no real excitement behind it.


dataframe pivot based on 3 columns

Question: I have a data frame like shown below

customer
organization
currency
volume
revenue
Duration

Peter
XYZ Ltd
CNY, INR
20
3,000
01-Oct-2022

John
abc Ltd
INR
7
184
01-Oct-2022

Mary
aaa Ltd
USD
3
43
03-Oct-2022

John
bbb Ltd
THB
17
2,300
04-Oct-2022

Dany
ccc Ltd
CNY, INR , KRW
45
15,100
04-Oct-2022

If I pivot as shown below
df = pd.pivot_table(df, values=['runs', 'volume','revenue'],
                        index=['customer', 'organization', 'currency'],
                        columns=['Duration'],
                        aggfunc=sum,
                        fill_value=0
                  )

level = 0 becomes volume for all Duration (level 1) revenue for all Duration duration for all Duration.
I would like to pivot by Duration as level 0 and volume, revenue as level 2.
How to achieve it?
Current output:

I would like to have date as level 0 and volume, revenue and runs under it.
Comment: Can you add the expected output to your post/question ?
Answer: You can use swaplevel like below in your current pivot code; try this;
df1 = df.pivot_table(index=['customer', 'organization', 'currency'],
                        columns=['Duration'],
                        aggfunc=sum,
                        fill_value=0).swaplevel(0,1, axis=1).sort_index(axis=1)

Hope this Helps...

dataframe pivot based on 3 columns


What is the reason for the many manuals on a pipe organ?

Question: Pipe organs may have as many as five "manuals", each of them almost the size of piano keyboard, and if would not be enough may even feature the feet keyboard. And my 88 key piano keyboard already covers the majority of the hear-able sound range, probably no more than 20 or about keys could be added to the sides, unless to play ultrasound for bats and whales.
Is it so that organ has multiple keys for the same note? How common is to play same note using different keys/pipes on the same piece of organ music?
Comment: I don't think the manuals are always as extensive as a pianoforte keyboard. Apart from that I believe the manuals are wired to a different set of organ pipes, and hence have a different tone color. I think this wiki entry may be of some use: http://en.wikipedia.org/wiki/Organ_console
Comment: This is regional thing. European keyboards now typically extend to 4 1/2 octaves (5 in France), while in America much wider manuals occur, but fewer aliquot stops.
Comment: @KilianFoth I've never seen an organ manual with more than 61 keys, nor a modern one with fewer than 61 keys.  All of the modern ones I've seen up close have been in the US, so I'm perfectly prepared to believe that there are builders still making smaller ones.  Can you name an actual American organ with larger manuals?  All those for which I've found descriptions or photographs online have 61 keys.
Answer: The different manuals are assigned to different stop combinations. By pulling out different stops, different sets of pipes sound when you press a key (or pedal). Having more than two manuals allows the performer to rapidly switch from stop-combination to another, or to make the left and right hands sound different.  In addition, the different manuals can be linked to one another, i.e. depressing a key on a given manual also causes the corresponding key on a different manual to be depressed. Since this linkage can be achieved by pulling a single lever, it is an easy way to significantly modify the sound produced by the organ.
Answer: Important addition to Daves answer: Note, that an organ does not support touch dynamics. As soon as you press the key you get the sound, no matter how soft you touch. To achieve different dynamic levels you need another, weaker or stronger registered manual. By the way, this is also the reason for harpsichords having more than one manual.
Comment: A well made organ with mechanical action allows you to influence the velocity of the valve opening and closing. This lets you modify the "attack", i. e. the development of a stationary sound can be delayed and a softer sound can be achieved. But this is already high art. Also electric and pneumatic action prohibits it entirely.
Answer: In addition to what everyone else said, having more manuals making it easier for the organist to change sounds quickly but, also, each manual is called a division and all the pipes for that manual are generally in its own location.  Here is a recording I made utilizing all the divisions rapidly.
This isn't a good recording in that the camera which also recorded the audio was placed near the console and you can't hear the room.  The lowest manual (Choir) sounds from the balcony.  The second one (Great) sounds behind me RIGHT IN MY EAR.  The third (Swell) sounds across the chancel.  The fourth (Solo) is across the chancel up above the Swell.  The people in the pews can hear the sound coming from and bouncing about different locations.
Toccata et Fugue in D Minor
Answer: Some pieces call for distinctly different sounds for the melody and accompaniment. This is often a requirement for trumpet voluntary type of music. The right hand usually plays the melody on the Swell with a reed, and the left hand plays with Diapason stops on the Great. On slower pieces, you might want just the melody to have a tremolo, and be able to open/shut the swell box for dynamics, but those effects would not be applied to the Great manual.
Comment: Modern 'popular' music instrumentalists also often use multiple keyboards (see many current music videos of stadium concerts). The different keyboards play different "instruments" - not a piano keyboard five times as long, or five times as loud.
Answer: I wish to mention that many baroque-era organ pieces have "contrapunctus" or "stretto" sections in them and playing those on a single manual would inevitably cause the musician's hands to collide. In case of double contrapunct (which was trivial matter for the genius of J. S. Bach) one needs maybe 3 or 4 keyboards to avoid trouble.
Comment: Did you intend a question mark at the end of your post?


Book recommendation on statistical computing?

Question: Topics on importance sampling, Monte Carlo, MCMC etc.
Comment: Please try a little harder to make this precise. Are you looking for a book that tells you how to use software or one that tells you how to write original programs? What background in computing/statistics/mathematics are you expecting to be assumed? Any language or package or environment or specific software assumed? etc.
Comment: You should edit your question to be more precise. Are you interested in books on Monte Carlo methods in statistical computing (as I assumed)? If so edit your question and its title to be more precise.
Answer: This one is a "must read" position and also very readable:

Robert, C. & Casella, G. (2004). Monte Carlo Statistical Methods. Springer.

This two introduce the topic with examples of code in R what I personally found very helpful:

Robert, C. & Casella, G. (2009). Introducing Monte Carlo
Methods with R. Springer.
Suess, E.A. & Trumbo, B.E. (2010).
Introduction to Probability Simulation and Gibbs Sampling with R. Springer.


Implementation independent way to see if a map contains null key

Question: I have an API that receives a parameter which implements the Map interface. I need to check to see if this Map contains any null key. The problem is there are certain implementations of Map, such as ConcurrentHashMap which throw NPE if you call contains(null) on them.
What is a good, implementation independent way to see if an object that adheres to the Map interface contains a null key or not?
Note that I can't use keySet and check to see if that contains a null, because ConcurrentHashMap actually just wraps the keySet onto itself and ends up calling contains again underneath.
Any ideas would be much appreciated. I would rather not use instanceOf since that tends to look ugly when you have to corner case so many different types of Maps
Answer: I think this would do the trick:
private static Map<String, String> m = new ConcurrentHashMap<>();

public static void main(String[] args) {
    boolean hasNullKey = false;
    try {
        if (m != null && m.containsKey(null)) {
            hasNullKey = true;
        }
    } catch (NullPointerException npe) {
         // Relies on the fact that you can't add null keys to Map
         // implementations that will throw when you check for one.
         // Add logging etc.
    }
    System.out.println("Does map have null key? " + hasNullKey);
}

Comment: I'm surprised there's no `Collection#isAllowNull()` or some such, but apparently there's not.  Yay for APIs that force you to use try/catch to test their capabilities and state.
Comment: I really hate catching an NPE like this. I'll wait a bit longer to see if there are better alternatives before I accept this.
Comment: @AbuZubair I agree, as Kevin says, a nice API method would be preferable but we're dealing with an interface here, so given no implementation specifics, nothing springs to mind. It would be nice if `ConcurrentHashMap` etc. looked for the null in `containsKey` and returned false.
Answer: new HashSet<K>(map.keySet()).contains(null);

or if you don't want to copy all the keys:
boolean containsNull = false;
for (K k : map.keySet()) {
    if (k == null) {
        containsNull = true;
        break;
    }
}

Comment: I agree. I think all 3 solutions are ridiculous. The fact that you're forced to do any of these things is absurd. Why does `map.containsKey(null)` throw a NPE?!
Comment: This will certainly do the trick but has the overhead of  creating the new `HashSet`.
Comment: Yes I like this quite a bit but I can't take the perf hit of a new `HashSet`.
Comment: It's quite a big oversight. The whole point of interfaces is that you're supposed to be able to use different implementations. For the record I would accept your answer if I were the OP. It avoids the iteration if the implementation doesn't allow `null`, and uses the quickest solution (`containsKey()`) if it does. You're not going to get any better than that.
Comment: @pbabcdefp dependent upon the keyset implementation, you may now have an iteration overhead over my solution. If the keyset is a `HashSet` your implementation is O(n/2) rather than O(1).
Comment: @pbabcdefp seems like an oversight in the `ConcurrentHashMap` implementation. `containsKey` should return false for `null`.


how to add nested add fields by using angular js?

Question: When I click on the add-field button, I need to get another add-2nd-field button. If I click on the add-2nd-field button, I should get 3 text boxes this should repeat for 10 times upon clicking those buttons. Presently I'm getting only for the add-field button this buttons working properly. Inner add-2nd-field button is not working.
Please help me out.
script code
$(document).ready(function() {
var max_fields      = 10; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID
var y=1;
var x = 1;//initlal text box count
$(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max input box allowed
        x++; //text box increment
      $(wrapper).append('
<button class="add_field_button" id="secondclick">2nd add field</button>
');

    }
});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text                                                                              e.preventDefault(); $(this).parent('div').remove(); x--;
})});

html code

<button class="add_field_button">Add More Fields</button>

thanks in advance
Comment: where is angular code?
Comment: you have tagged `angularjs` with `jquery` code written :D
Answer: I've modified your code.
JS code:
var max_fields      = 10; //maximum input boxes allowed
var add_button      = jQuery(".add_field_button"); //Add button ID
var x = 1;//initlal text box count
jQuery('.add_field_button').on( "click", function(e) {
   if(x <= max_fields) {
        jQuery(this).html('Add Field '+(x+1));
        jQuery('.input_fields_wrap').prepend('
Field '+x+' added
');
        x++;
   } else {
    jQuery(this).addClass('hide');
    alert('Maximum limit reached');
   }
});

HTML code is mostly same as yours

<button class="add_field_button">Add 1st Field</button>

CSS code
.hide {display: none;}

You can edit prepend element to your desired html. Hope it helps


flexsurvreg - shape and scale proportional hazard model

Question: Please see below codes and plot for fitted curves to Kaplan-Meier data (weibull in this example) using the ovarian data. Based on the estimates, the shape and scale of the fitted Weibull distribution for rx A are 1.13e+00 and 4.50e-04 respectively. How do I find/calculate the shape and scale for rx B fitted curve based on this output?
Thanks for your help in advance!
> library(survival)
> library(survminer)
> library(dplyr)
> library("flexsurv")
> ovarian$rx <- factor(ovarian$rx,
+                      levels = c("1", "2"),
+                      labels = c("A", "B"))
> surv_object <- Surv(time = ovarian$futime, event = ovarian$fustat)
> fit1 <- survfit(surv_object ~ rx, data = ovarian)
> fitw <- flexsurvreg(formula = Surv(futime, fustat) ~ rx, data = ovarian, dist="weibullPH")
> fitw
Call:
flexsurvreg(formula = Surv(futime, fustat) ~ rx, data = ovarian,
    dist = "weibullPH")

Estimates:
       data mean  est        L95%       U95%       se         exp(est)   L95%       U95%
shape         NA   1.13e+00   6.90e-01   1.85e+00   2.84e-01         NA         NA         NA
scale         NA   4.50e-04   1.12e-05   1.82e-02   8.49e-04         NA         NA         NA
rxB     5.00e-01  -6.31e-01  -1.78e+00   5.19e-01   5.87e-01   5.32e-01   1.68e-01   1.68e+00

N = 26,  Events: 12,  Censored: 14
Total time at risk: 15588
Log-likelihood = -97.36415, df = 3
AIC = 200.7283
> plot(fit1)
> lines(fitw)

See comment re: "dist=weibull"
> fitww <- flexsurvreg(formula = Surv(futime, fustat) ~ rx, data = ovarian, dist="weibull")
> fitww
Call:
flexsurvreg(formula = Surv(futime, fustat) ~ rx, data = ovarian,
    dist = "weibull")

Estimates:
       data mean  est       L95%      U95%      se        exp(est)  L95%      U95%
shape        NA      1.129     0.690     1.848     0.284        NA        NA        NA
scale        NA    920.128   468.868  1805.704   316.508        NA        NA        NA
rxB       0.500      0.559    -0.478     1.597     0.529     1.749     0.620     4.936

N = 26,  Events: 12,  Censored: 14
Total time at risk: 15588
Log-likelihood = -97.36415, df = 3
AIC = 200.7283

Answer: The Weibull distribution has several parameterizations. The parameterization used in the standard R function definition is called the "standard" parameterization in Wikipedia. Using that terminology from R (also adopted in the flexsurv package):

The Weibull distribution with shape parameter $a$ and scale parameter $b$ has density given by
$$\frac{a}{b}\left(\frac{x}{b}\right)^{a-1} \exp\left({-\left(\frac{x}{b}\right)^{a}}\right)$$
for $x$ > 0.

Survival modeling with Weibull is generally done with covariate values affecting the scale parameter $b$, not the shape parameter.* In that parameterization, the survival as a function of time $x$ is:
$$S(x) = \exp \left({-\left(\frac{x}{b}\right)^a}\right) $$
Those are the shape ($a$) and scale ($b$) values for which you got estimates when you chose dist="weibull" in your model in an edit to your question.
With $x$ representing time, differences in the scale parameter $b$ can be thought of as changing the time scale, an accelerated failure time (AFT) interpretation. Dividing the time $x$ by the scale parameter $b$ means that a larger value of $b$ corresponds to a longer time to get to any particular fractional survival.
In this parameterization, a regression coefficient represents an additive linear effect on the log of the scale parameter; see for example page 4 of the flexsurv vignette. The exponential of a regression coefficient thus represents a multiplicative effect on the scale parameter. In your example with this parameterization, that means that the scale value of 920 for group rxA becomes a value of 1609 for group rxB. The larger scale value means a longer lifetime for that group.
You first, however, chose dist="weibullPH".** That changes the output to display the first of the alternative parameterizations in Wikipedia. In that form, differences in covariate values are thought of as representing differences in the hazard of an event. The page for "WeibullPH" in the flexsurv documentation notes that the "scale" parameter is then called $m$, with $m=b^{-a}$ in terms of the "standard" parameterization.  The "shape" parameter $a$, however, is unchanged. In the PH parameterization, the survival function is:
$$S(x) = \exp ({-mx^a} )$$
That value $m$ is what you show reported as scale.
The next source of confusion is a difference between how the parameter estimates are handled internally and how they are reported, depending on the report for which you ask. The estimates for shape and scale in your display are the values for $a$ and $m$ in the PH parameterization for the reference category of rxA. You can verify that by adding the following line to your survival plot, using the formula for the Weibull survival function:
> curve(exp(-4.50e-04*x^1.13),from=0,to=1200,add=TRUE,col="blue",lty=2)

It lines up right along the lower smooth curve, representing the rxA group.
The problem you face is that the coefficient reported for rxB is the change in the log hazard between the reference rxA and the rxB group. That's useful for interpretation in terms of log hazards and hazard ratios, but it's not the form in which your display shows the scale parameter $m$.
To accomplish what you want, it's simplest to interrogate your model instead with the coef() function, which reports regression coefficients in the (natural) log units in which they are used internally:
> coef(fitw)
     shape      scale        rxB
 0.1214247 -7.7055872 -0.6314782

The coefficient for rxB is unchanged from the display you show, while shape and scale are now log-transformed. In these log units the rxB coefficient is simply an additive change to the reference-condition scale value, giving a scale value in log units for the rxB group of -8.337. You then exponentiate to get that scale value back into a form that you can compare against the display you show or plug back into the survival function.
If you add to your survival plot the following:
> curve(exp(-exp(-8.337)*x^1.13),from=0,to=1200,add=TRUE,col="black",lty=2)

you will see that you have reproduced the smooth curve shown in your original survival plot for the rxB group.

*The flexsurv package allows for more complicated models in which covariates can affect "ancillary" parameters like shape and variance. Otherwise, it just models, as a function of the covariates, a parameter that "governs the mean or location of the distribution," according to the package vignette. Table 1 in that vignette shows that this "location" parameter for Weibull is the Weibull "scale" parameter in the above parameterizations. Note that the above parameterizations differ from that used for Weibull models in the standard survreg() function, as explained for example here, providing even more opportunity for confusion.
**Only a Weibull distribution allows for parameterizations as functions of covariate values that maintain the same distribution family for both accelerated failure times and proportional hazards interpretations. See, for example, these course notes.
Comment: @user2310 I expanded the description of the standard parameterization in the middle of the answer. The confusion is that in the standard parameterization an increase in the `scale` parameter $b$ (parameter divides time) means a _longer_ lifetime , while in the PH parameterization an increase in the `scale` parameter $m$ (parameter multiplies a function of time) means an increased hazard and shorter lifetime.
Comment: @user2310 With `dist=weibull` coefficients don't describe changes in hazard ratios. They describe changes in apparent time scales. The value of 1.749 is **NOT** a hazard ratio! It's the factor by which you multiply the baseline `scale` factor $b$ when you move from group `rxA` to group `rxB`. With `dist=weibull`, a larger value of $b$ means you need a larger value of time $x$ to get down to the same survival fraction. So the larger `scale` factor then means _improved_ survival with `rxB`. Depending on parameterization, `scale` in Weibull can mean 3 different things. Be very careful.
Comment: Thank you so much for this - is extremely helpful! Using `dist=weibullPH` the HR is 0.532. However, using `dist=weibull` the HR is 1.749 (which doesn't makes sense since B is better than A). Could you please advise the discrepancy (see edits in original post above the graph)?
Comment: Thanks @EdM. Does that mean that based on the same data (i.e. ovarian), using the "dist=weibullPH" resulted in B being better than A (HR 0.532), but B is worse than A when using the "dist=weibull" (HR 1.749)? I would have thought regardless of the type of distribution fitted, the original conclusion would remain the same (i.e. B better than A based on KM plot).