Pitch perception: What allows us to uniquely identify a musical note?

Question: If I start on a musical note on the piano and play out the folllowing harmonics/overtones I can find all the notes in the chromatic scale via the harmonic series eventually. Does that mean that every note on the piano contains all the other notes via its overtones? If so what makes a note unique?
Edit: Lets say A2 (110hz) for a refrence to the musical note.
Im more curious about the difference of pitch than timbre. Incredible grateful for all comments that help clear up the issue
Comment: @topomorto Yes, there is much more to say but it was already a heavy comment.  I did not attempt an answer since it was not entirely clear whether I was answering the right question.  Another interesting aspect is why some instruments, e.g. a lot of percussion, do not have exact pitches.  The stretched tape story was real, with the constancy of pitch removed, it no longer sounded at all like a piano even though the harmonic structure was probably maintained.
Comment: Do you mean why does the same note played by different instruments sound different?  Harmonics are part of the answer but not all of it.  For example, a clarinet produces only odd harmonics.  If you simulate this with a synthesiser then it will sound rather clarinet like.  However, there are many other factors such as attack, decay, and vibrato that distinguish instruments.  In the days of tape, I had a badly stretch tape of piano music.  It no longer sounded like a piano.  A piano has a stable pitch.  The stretched tape version sounded like a musical saw.
Comment: Related on Physics: https://physics.stackexchange.com/q/78827
Comment: @badjohn harmonics (or, to use a more general word, partials) can themselves be thought of as varying in pitch and amplitude over the course of a note. So though you're absolutely right that a static harmonic structure can't tell the full story, it is possible to analyse all aspects of a note in terms of a changing harmonic structure (though it can be clumsy when the sound becomes less periodic and more noisy).
Answer:
If I start on a musical note on the piano and play out the folllowing harmonics/overtones I can find all the notes in the chromatic scale via the harmonic series eventually.

That's true in one sense of the word 'note', but not in the sense that's relevant to your reasoning. The harmonic series contains harmonics whose pitches correspond to all the note names in the chromatic scale. So in that sense, yes, it "contains all the notes". However, it does not contain all the notes in the sense of containing all the pitches in the chromatic scale (e.g. over a range of octaves).
Have a look at the table here. That's a list of all the notes in the chromatic scale (within some range, using some reference pitch, and some particular temperament).
Does the harmonic series based on any fundamental contain all those pitches? No, it doesn't.

Does that mean that every note on the piano contains all the other notes via its overtones?

No. The harmonic series will contain notes of all the different names. It doesn't contain "all the notes", in the sense of all the actual pitches that correspond to notes in the chromatic scale.

what makes a note unique?

Simplistically speaking, and assuming that you are interested only in pitch and not timbre, the thing that makes a note unique is its fundamental frequency. If you're talking about timbre, I refer you to Dave's answer :)

EDIT: OK, so... pitch perception, simplified version.
A sound is a variation in the pressure of the air.
That variation in pressure can be depicted as a waveform.
Not all sounds have a particular 'pitch'. A sound that has a pitch is one whose waveform repeats, like this:

https://swphonetics.com/praat/tutorials/understanding-waveforms/
We can see that the "one cycle" marked by the arrow repeats again and again.
Now, the pitch of the sound that we hear depends on how frequently the waveform repeats - we call this the frequency.
In the diagram above, the cycle is about 0.0033... seconds long. So the frequency is 1/0.0033 - Which is 300 Hz.
And that frequency of the sound is is, simply speaking, the answer to your question - that's the thing that governs the pitch that we hear.
You might be confused as to why I haven't mentioned harmonics at all. But actually, to understand the idea of frequency, you don't need to understand the idea of harmonics. You only need to know that a sound wave that repeats a certain number of times a second has a certain unique pitch.

So why do people talk about the harmonics of a note, if they have nothing to do with the pitch?
One reason is that the harmonics are important in how the ear recognises frequency. Our ear can't look at a graph, the way we just have.
What the ear does is make use of a different way of representing a sound - not as a pressure waveform changing over time ("time domain"), but as a set of different frequency components ("frequency domain").
The best way to understand this is to try it yourself. Go to https://meettechniek.info/additional/additive-synthesis.html and play with this:

The above shows a wave that has only the fundamental frequency - no harmonics (this shape is called a sine wave).
If we add more harmonics, the timbre of the wave changes, AND the shape of the wave changes:

In these pictures, the graph at the top is a time-domain view of the shape of the waveform, while the sliders at the bottom show the frequency domain view - how much energy is in each harmonic. An important thing to notice is that the harmonics are all multiples of the fundamental frequency. H1 is 440 Hz, so H2 is 880 Hz, H3 is 1320 Hz, and so on.
The ear can measure these different harmonics as there is a special structure called the Basilar membrane allowing it to do this:

https://www.britannica.com/science/basilar-membrane
So how does the ear know what the fundamental frequency of the note is from the harmonics?
What it does is look at the frequencies of all the harmonics, and then works out the highest common factor of the harmonics. So if it hears harmonics at 125, 250, 500, and 625Hz, it will guess that the frequency of the note is 125 Hz.
Because of this, notes with very different harmonic structures can still have the same pitch:

Those two arrangements of the harmonics sound very different, because the relative strengths of the harmonics change the timbre of the sound, but the pitch is still the same.
One things those diagrams don't show very well is the change in frequency (the X-axis in those diagrams is phase, not time).
This video shows much better how the pitch of the sound we hear depends on the frequency of the wave (how quickly it repeats):

So, putting this all together:
Let's say the ear hears these harmonics (all Hz):
440, 880, 1320, 1760, 2200
What frequency will the ear hear?
It will hear 440Hz - or A4.
What about 880, 1760, 2640, 3520, 4400?
It will hear 880 Hz - or A5. (Note that's still A, but a different 'A').
And what about 98, 196, 294, 392, 490?
The ear will hear 98 Hz, or G2.
So I don't think it's really useful to think that a note 'contains' other notes because of its harmonics - that's not how the ear works. It groups the harmonics into sets related by frequency that we then hear as single notes.
Comment: I think your answer is on the right path but it may benefit from a little more on the fundamental frequency, perhaps referring to how we perceive different frequencies based upon the fundamental.  I only really say this because the meat of your answer is dealing with the peripheral subject matter.  +1 either way
Comment: Steven sandoval  - as @Basstickler suggests, I'm happy to add more detail about pitch perception if you think I have indeed understood your question correctly :)
Comment: @Stevensandoval added. I hope I haven't made it even more confusing, but please ask if you have any questions!
Comment: @topomorto - Wow! Very thoroughly expanded upon!  Well done!  Particularly I hadn't heard of the concept of the ear/brain calculating the perceived pitch based on the set of overtones provided.  Very informative.
Comment: @Basstickler I started to hit the endstops of my own knowledge there, but I believe that various psychological experiments (with missing fundamentals, resultant tone phenomena, etc) suggest that's roughly how it works. At that point I'd like to know more details about *how* myself, though...
Answer: To me this is akin to asking "if all of images on our screens are just red, green and blue phosphors, how are there different colors?" (the same kind of question can be asked in terms of mixing pigments). It is in the fact that there are different mixtures of the different components.  So, in terms of the harmonic content, it is the relative amplitudes (and phase) of the different harmonics that affect the perception of pitch and timbre.
In principle, it is the entire wave train that makes a sound unique.  Although there is a 1-to-1 correspondence between the wave train and the harmonic content I like to start in the time domain; aspects like onset transients, the how a note decays and whatnot are easier to think about in terms of when they occur and how they last in time.  The percussive attack of a piano is distinct from a slow onset violin note of the same pitch.   Other kinds of differences, especially the perception of "texture" in sustained notes are more obviously reflected in differences in the harmonic content of the note, c.f. this video for a comparison of some idealized waveforms.


CSS display e visibility - Efeitos no SEO

Question: Estou fazendo um website e aplicando algumas técnicas de SEO, porém tenho uma div que necessita ficar oculta (propriedade display:none; e visibility:hidden;). Qual é o efeito nos mecanismos de busca para este elemento DIV? Funcionaria da mesma forma nas tags
 e
?
Answer: Isso causará um impacto ruim no SEO se esta tag em questão for uma tag que você deseja usar para propósitos de entregar conteúdo para os buscadores (pode ser confundido com cloacking).
O ideal é você não esconder tags que contém conteúdo que possa ser usada como palavra-chave no buscador, as tags h1 por exemplo costumam ser péssimas opções para se esconder.
Dê uma olhada no conteúdo dessas tags e pondere se vale apena alterar sua visibilidade nos motores de busca.
Teve uma discussão parecida aqui:
https://webmasters.stackexchange.com/questions/54892/can-i-hide-h1-tag-will-it-hurt-seo


Natural language processing API for iOS 5

Question: I am looking for NLP capable library or API which will be able to identify number, date, person, place name, and parts of speech from a given sentence.
Answer: NSLinguisticTagger will do this. Introduced in iOS 5.
Comment: later on i used this, but i forgot to post it as an answer. Thanks it will really help others
Answer: You should try Nuance SDK for iOS. You also can try CMU (open source) but quality is pretty low, especially for conditions with noisy environments.
Comment: http://cmusphinx.sourceforge.net/wiki/
Comment: i think that sdk is for proccesing voice dictation not for natural language processing
Comment: http://dragonmobile.nuancemobiledeveloper.com/public/index.php?task=home
Comment: From your question tt seems like you need speech recognition.
Comment: If I had more time I would write one! This would actually be a worthwhile effort on someone's part.
Answer: It seems like you're looking for named entity recognition. You could use Boost Spirit for parsing.


Referencing objects in Javascript

Question: When you have a multi-tiered object like a json object that say has 3 tiers
i = {'id':1{'name':'austin', 'lives':'college'{'name':'eckerd', 'major':'compsci'}}}

To reference the object is it better to reference it like so
for (x in i)
    i[x]['lives']['name']
//or
    i[x].lives.name

I think that gets my idea across.  Pretty much use Associative arrays or the 'dot' method and why?
Answer: i[x].lives.name is equivalent to i[x]["lives"]["name"].
i[x][lives][name] means that you have variables called lives and name that you want to reference:
There's no real benefit to using one form over the other; imho it's clearest to use the dot notation unless you need the variable property names.
Comment: err sorry those are supposed to be in quotes in the question
Comment: It's really just whatever you prefer. The two syntactical representations refer to the exact same objects in the exact same way. The method you choose will have no effect on your code besides the way it looks.

Personally I use the . syntax to separate standard "objects" from what I consider to be "arrays" although to JS they are exactly the same thing.
Comment: @austinbv Looks good.  Guess it's only the last line of this answer that's relevant then. :)
Comment: I'm tempted to downvote this as JSON keys (which are strings) should only be accessed accordingly as strings, not object parameters.
Answer: "Values can be retrieved from an object by wrapping a string expression in a [ ] suffix. If the string expression is a string literal, and if it is a legal JavaScript name and not a reserved word, then the . notation can be used instead. The . notation is preferred because it is more compact and reads better."

Crockford, D. (2008), JavaScript: The Good Parts. (pp. 21). Sebastopol, CA, U.S.A.: O'Reilly.

Referencing objects in Javascript


What does "finitely many" mean here? "$B$ is a collection of sets that are the intersection of finitely many sets in [a set of sets]"

Question: Take a set of sets $C$. What does it mean when we say

"$B$ is a collection of sets that are the intersection of finitely many sets in $C$?"

Does "finitely many" mean "from 1 to n"?
With $1$, I mean the intersection of a set with itself.
Comment: It means that the number is not infinite.
Comment: "Every natural number has only finitely many divisors", how do you understand this statement?
Answer: It means that for every set $D\in B$ there is a natural number $n\in \mathbb{N}$ and a collection of sets $\lbrace C_1,\dots, C_n\rbrace\subset C$ so that $D=\bigcap_{j=1}^n C_j$
Comment: Yes, of course, thanks
Comment: Then, n can be equal to 1 in your definition
Comment: @VahidM.SafarZadeh Yes. So any element of $C$ is a valid element of $B$.
Answer: Let it be that $X$ is a set and that $\mathcal C\subseteq\wp(X)$, i.e. $\mathcal C$ is a collection of subsets of $X$.
Then we can define $\mathcal B$ as the collection of sets that can can all be written as an intersection of finitely many sets.
In mathematical notation:$$\mathcal{B}:=\left\{ \bigcap\mathcal{D}\mid\mathcal{D}\subseteq\mathcal{C}\text{ and }\mathcal{D}\text{ is finite}\right\}$$
Here: $$x\in\bigcap\mathcal{D}\iff\forall D\;\left[D\in\mathcal{D}\implies x\in D\right]$$
or more shortly: $$x\in\bigcap\mathcal{D}\iff\forall D\in\mathcal{D}\;\left[x\in D\right]\tag1$$

Special case $1$: $\mathcal{D}\subseteq\mathcal{C}$ and $\mathcal{D}$
a singleton.
That means that $D=\left\{ D\right\} $ for some $D\in\mathcal{C}$
and applying $\left(1\right)$ we find easily that $\bigcap\left\{ D\right\} =D$.
This actually tells us that:$$\mathcal C\subseteq\mathcal B$$because for every $D\in\mathcal C$ we have $D=\bigcap\left\{ D\right\}\in\mathcal B$.

Special case $2$: $\mathcal{D}=\varnothing$
For every $x$ it
is vacuously true that $\forall D\in\varnothing\;\left[x\in D\right]$.
Also if $x\notin X$ so it is somehow "running out of hand".
In this case often a convention is applied that says that we only
restrict to elements in the original set $X$ leading to:$$\bigcap\varnothing=X$$
So under this definition of $\mathcal B$ and this convention we always have: $$X\in\mathcal{B}$$


Date input format problem

Question: I need to import a large dataset (over 300,000 records) into a Drupal 8 site. I have figured out how to do this with feeds on a small test dataset.
The dates in the records are in the format June 8, 2018. I do not see a way to use a Drupal 8 Date field to input dates in this format.
I need to be able to create a view that displays records based on a date range.
What is the best way to get the data into Drupal in a format that a view can use? Would it be to maybe use computed field to transform the data while it is being imported? Or would it be better to maybe execute a SQL query after the data is imported?
Answer: Rather than using Feeds, I suggest using the core Migrate module.  There is also a core plugin for converting dates during migration, FormatDate.  This will allow you do specific the input format and the output format.  I believe, this process configuration would work in your case:
process:
  field_date:
    plugin: format_date
    from_format: 'F j, Y'
    to_format: 'Y-m-d'
    source: event_date

If Feeds is your preferred method, then you can try the Feeds Tamper module.  Based on the plugin list for Drupal 8, I think you would need to do a "String to Unix timestamp" tamper on the field, followed by a "Unix timestamp to Date" tamper, using 'Y-m-d' as the format string. However, I haven't used Feeds and Feeds Tamper in a long time, and would typically write custom tampers for something like this.
Comment: Thanks mpdonadio. I haven't used the Migrate module yet, but now may be the time to try it.

Date input format problem


How do I Express this PHP in Ruby?

Question: I need a neat and tidy and elegant way to do this in Ruby. It is a simple get what is on the page and out put it to the screen.

Answer: You can use net/http like this:
require 'net/http'
puts Net::HTTP.get('google.com', '/')

You can also use get_print, like this:
Net::HTTP.get_print('google.com', '/')

Answer: require 'net/http'
uri = URI('http://google.com')
p Net::HTTP.get(uri)

You can read more on this topis in documentation here.

How do I Express this PHP in Ruby?


refresh svelte select component after adding an option

Question: I am trying to make a select component update itself after adding an option but I can't. Here is my code:

  <select bind:value={options} on:change={doSomething}>
    {#if options}
      {#each options as option}
        <option value={option}>{option}</option>
      {/each}
    {/if}
  </select>
  <button type="button" on:click={addEventSignal}>Add Signal</button>

If I reload the component it shows the new option but I would like to have the new option in the select list as soon as the input dialog is gone.
Answer: Svelte doesn't detect the mutation of your options object:
options.push(option)

It only tracks assignments, with =. A very common solution to make the compiler aware of the modification is this kind of situation is self-assigment:
// you'd also have to make it a `let`, of course
options.push(option)

// this, Svelte will see!
options = options

You can call that a Sveltism.
Reactivity will ensue, and your select's options should be updated immediately. See details in this section of the tutorial.


Rota parou de funcionar somente na versão release

Question: Tenho um software aqui na empresa, e ele funcionava perfeitamente. Porém, fiz uma pequena alteração de layout e na minha máquina funciona perfeitamente. Quando publico a aplicação, a rota (/Configuracoes) retorna erro 404, como se a rota não existisse.
Criei uma outra rota (/Config), com o mesmo conteúdo e ela não funciona também.
Alguma ideia do que pode estar causando isso?
Comment: E qual é a diferença entre os dois ambientes? em produção ele está publicado em um subdomínio ou diretório virtual?
Comment: Não há diferença, fora o ip de acesso. É um servidor na rede. Não faz sentido não abrir a rota, pelo menos não para mim...
Comment: Você pode garantir que não é uma exception sendo estourada e tá sendo feito redirect como "not found"?
Comment: Como faço para verificar isso? Não tenho como depurar em release...
Comment: Ele está publicado no IIS? Tem como compartilhar o Startup?
Comment: Consegui resolver. Obrigado.
Answer: Consegui solucionar o problema da seguinte forma:
Voltei até um "commit" que funcionava no git , e fui "comitando"
um por um e publicando. Até que descobri o commit.
O que aconteceu foi que um desenvolvedor criou uma rotina que necessitava
de um arquivo. Esse arquivo, por acaso, existia no repositório, porém,
não era criado pelo C# quando compilada a solução. Isso causava uma exceção
que não era retornada devido às configurações do servidor.
Ao ajustar o sistema para criar o arquivo caso ele não existisse, resolveu o problema.


Tips on refactoring unstructured repetitive code into reusable components

Question: I have searched and searched and could not get any relevant answer. Hopefully someone can help.
I started writing classes as a sort of unit hold data and another util class to populate the class from the database. Well this might not seem to big of a problem for a small code base but looking forward and for me to grow to a competent developer with a solid grasp of object orientated design and development i need to grow this into a proper design
Lets start of with the initial class
public class Foo
{
   public int FooID {get;set;}
   public string FooName {get;set;}
   public string FooDescription {get;set;}
}

public class NotRelatedToFoo
{
   public int SomeID {get;set;}
   public string SomeName {get;set;}
   public string SomeDescription {get;set;}
}

public class Util
{
   public Util(){}

   public List<NotRelatedToFoo> GetNotRelatedToFoos(string SomeName)
   {
     .... DB Code to return Data from DB

     List<NotRelatedToFoo> notfoos = new List<NotRelatedToFoo>()
     (select * from NotRelatedToFoo where SomeName like @SomeName)
     foreach var item in db
     {
       NotRelatedToFoo notfoo = new NotRelatedToFoo ();
       notfoo.SomeID = item.SomeID;
       notfoo.SomeName = item.SomeName
       notfoo.SomeDescription = item.SomeDescription
       notfoos.Add(notfoo);
      }
      return notfoos ;
   }

}

My question is what is the best way to move forward from this design.
Edit
At the moment the Util class is a big mess and i need advice how to extract and group the functions together follow a structured design
This is not going to work, or can it
public class Foo
{
   public int FooID {get;set;}
   public string FooName {get;set;}
   public string FooDescription {get;set;}

   public List<Foo> GetFoos(string FooName)
   {
     .... DB Code to return Data from DB

     List<Foo> foos = new List<Foo>()
     (select * from foo where FooName like @FooName)
     foreach var item in db
     {
       Foo foo = new Foo();
       foo.FooID = item.FoodID;
       foo.FooName = item.FooName
       foo.FooDescription = item.FooDescription
       foos.Add(foo);
      }
      return foos;
   }
}

Thanks
Comment: This question should earn @AntiPatternMax a "Best Title" badge. :)
Comment: That's quite a title, but still hasn't too much to do with the question
Comment: Please edit your question title to something sensible...
Comment: Maybe you couldn't get a relevant answer because you didn't ask a relevant question?
Answer:
My question is what is the best way to move forward from this design.

Classes named Util or Manager or what have you are generally a design smell. You should be able to describe what it is that the class is doing (it should have a single responsibility) and that should be the name of the class. If you have to use generic, vague, catch-all terms to describe what the class is doing then you are doing something wrong and a redesign is in order.
Your Util class is doing too much. It's getting data from a database for two distinct types. By designing your class in this way, you are setting yourself up to violate the open/closed principle (you will have to modify this class every time you add a new type to your model).
At a minimum, you need separate classes to get Foos and NotRelatedToFoos from a database. How about
abstract class Repository<T> {
     IEnumerable<T> GetAll();
}

abstract class SqlRepository<T> : Repository<T> {
    protected readonly SqlConnection connection;
    public SqlRepository(SqlConnection connection) {
        this.connection = connection;
    }
}

class FooRepository : SqlRepository<T> {

    public FooRepository(SqlConnection connection) : base(connection) { }

    public IEnumerable<T> GetAll() {
    }
}

etc. What's really sick is that you can even lift a lot of the repetitive code of hydrating an object from an IDataReader into a common class (hint: a first version would use reflection).
Beyond this, read about SOLID. And if you really want to dive it, try Patterns of Enterprise Application Architecture (Fowler) and Design Patterns (Gamma et al.)
Comment: +1. I hope all the library authors who made me use multiple totally unrelated `Manager` classes in the same program are reading along.
Comment: I like this, i would really appreciate it if you can expand on the code example you provided
Comment: Better yet, get an ORM like NHibernate so you can deal more with the objects in *your* app (and less with the common objects needed in your infrastructure).
Comment: @Berryl: While your comment is correct (everyone should use ORMs), switching to an ORM doesn't help with the fact that the OP is trying to get unconfused about OOP.
Answer: the common way to access the database, is through data access objects. http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
Don't know, if you have other classes for persisting, updating, or deleting data, but I usually do CRUD operations through a DAO.
Answer: Your Util class is responsible for many things (as Jason pointed out earlier).
It appears though that at the crux of it, Util is attempting to be a repository for your Foo and UnrelatedToFoo objects.
I would personally look at abstracting this out into some inheritance structures and introducing generics.
If you're going to be be creating a lot of these POCO objects that map to database tables in repetitive and convention based ways, consider an ORM such as NHibernate with FluentNHibernate mappings.
Comment: Thanks, I have used Linq to SQL and Subsonic but i NEED to know how this all works. I think a lot of developers know how to use the nice add-ons but don't have a clue on how to implement it themselves.
Comment: 'but don't have a clue on how to implement it themselves' - I agree. I have a vague idea how NHibernate works, but not in detail and wouldn't for a second think I could implement it myself.  But thats fine with me, I'm sticking to my knitting. Do you **really** need to know how it works to a level of detail that you could implement it yourself?  If you set out to truly understand everything you use you'll achieve mediocrity at best.  Don't re-invent the wheel, and have faith and trust 3rd party components used by hundreds of other developers world wide.


Do these infinite series converge to a finite limit?

Question: Now, I know that there is that remarkable result which finds that $$\sum_{n=1}^{\infty}n=-\frac{1}{12}$$ for $n\in\mathbb{N}$, under some kind of Cauchy limit.
Are there any such convergences for the following series summations?

$\sum_{n=0}^{\infty} n$;
$\sum_{n=0}^{\infty} n^2$.
Comment: You could call these summability methods, but it's certainly not a case of **convergence**.
Comment: @HarrySmith no, conditional convergence still refers to convergent series (which are just more fragile than absolutely convergent series). These above sums are actually divergent - you can just assign a value to them by somehow writing it as "something" + the infinity we don't care about.
Comment: Good point, @RobertIsrael -- I suppose a more accurate term would be [conditional convergence](http://bit.ly/1T7jYVC), no?
Comment: No, these series are *not* conditionally convergent.
Answer: These are regularized sums. The first one is actually the one that you already wrote in the first line (adding zero doesn't do anything). The second turns out to regularize to zero. Read up on zeta regularization and watch these excellent videos
https://www.youtube.com/watch?v=w-I6XTVZXww
https://www.youtube.com/watch?v=0Oazb7IWzbA
And you can generalize $\sum_{n=0}^\infty n^k = \zeta(-k)$ where $\zeta$ is the Riemann zeta function - you can see from the definition of this function, that all we do is to put in a number outside the convergence domain of original series, so the result is not a true sum of the series (which diverges) but analytic continuation that extends the domain beyond what the series can do.


Rails with Bootstrap Tabs

Question: I have a rails 4 app.
I am trying to incorporate Bootstrap Tabs.
Reading the bootstrap docs, it says one way of doing this does not involve any js. I have tried each of the approaches in the docs but can't get any of them working in my app.
My current attempt is:

 Terms

 Privacy

 Licence

 Trust

 Reliance

 Pricing

<%= render 'pages/legalpolicies/terms' %>

<%= render 'pages/legalpolicies/privacy' %>

<%= render 'pages/legalpolicies/licence' %>

<%= render 'pages/legalpolicies/trust' %>

<%= render 'pages/legalpolicies/reliance' %>

<%= render 'pages/legalpolicies/pricing' %>

The effect is to give me a tab bar across the top of the page. The tabs are clickable.
However all of the content in each of the separate tab content panes just displays in one big long page of text. The links don't work.
Can anyone see what's required to get this to work?
I read this statement in the docs:
You can activate a tab or pill navigation without writing any JavaScript by simply specifying data-toggle="tab" or data-toggle="pill" on an element.
I understand this to mean that no js is required.
Anyway, I tried making a privacy.js file in my javascripts folder and adding:
$('#myTabs a').click(function (e) {
  e.preventDefault()
  $(this).tab('show')
})

That didn't do anything.
I tried moving it to my application.js file. No difference. Is more js required? It's odd to me that this does anything since I don't have anything called #myTabs in the html. Is there something else that's required to get this to work?
Gem file has:
gem 'sass-rails', '~> 5.0'
gem 'bootstrap-sass', '~> 3.3.5'

Style sheets has a file called: framework_and_overrides.css.css, which has:
@import "bootstrap-sprockets";
@import "bootstrap";
@import "font-awesome-sprockets";
@import "font-awesome";

Javascripts folder has a file called application.js, which has:
//= require underscore
//= require gmaps/google
//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require_tree .

So - following advice on the bootstrap-sass gem setup (for Ruby on Rails, I made changes to my stylesheets and js files.
Specifically, that gem says:
Then, remove all the *= require_self and *= require_tree . statements from the sass file. Instead, use @import to import Sass files.

Do not use *= require in Sass or your other stylesheets will not be able to access the Bootstrap mixins or variables.

I changed the name of the application style sheet from application.css.scss to application.scss.
I changed the content of that file to:
 @import "framework_and_overrides.css.scss";
 @import "require_self";
 @import "require_tree .";
 */

I changed the content of my framework_and_overrides.css.scss file to include:
@import "bootstrap-sprockets";
@import "bootstrap";
@import "font-awesome-sprockets";
@import "font-awesome";
@import "bootstrap-slider";

My application.js file has:
//= require underscore
//= require gmaps/google
//= require jquery
//= require bootstrap-sprockets
//= require bootstrap-slider
//= require jquery_ujs
//= require_tree .

This doesn't have a positive impact. It removes all the styling on my pages, removes all the bootstrap styling and generally messes everything up. It doesn't connect the tab links to the tab content.
I'm stuck -really trying to understand how to use Bootstrap Tabs in Rails 4. Any advice would be very much appreciated.
When I change it back, at least the styling is reflected, but the js tabs do not work (in either case).
ANOTHER ATTEMPT:
When I add import bootstrap to the top of my application.js:
@import "bootstrap";
//= require underscore
//= require gmaps/google
//= require jquery
//= require bootstrap
//= require bootstrap-sprockets
//= require bootstrap-slider
//= require jquery_ujs
//= require_tree .

The tabs across the top of the page in this example work so that the page is jumped down to where the start of the relevant text tab is. That's not what I want. I want the partial containing that text to display at the top of the page (and the text in each of the other partials to be hidden) - as is shown in the bootstrap example for tabs.
Comment: your html works for me: https://jsfiddle.net/rg6gkrn0/
Comment: You should only require one Bootstrap JS file, not both. That might help. See [docs](https://github.com/twbs/bootstrap-sass). > bootstrap-sprockets and bootstrap should not both be included in application.js
Comment: Yeah - I only added in '//= require bootstrap' to the application.js file because I was at a loss for what else I should try. I deleted it but still have the same problem
Comment: You need to include Javascript to initialize the tabs: http://getbootstrap.com/javascript/#tabs-usage. This might go into application.js, or into another .js file in your `/javascripts/` directory.
Comment: is this a necessary part of the setup:  @import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');
Comment: I don't have ^^ in my file
Comment: can you show your gemfile?
Comment: Also I noticed a typo `framework_and_overrides.css.css` shouldn't that be scss instead of css? `framework_and_overrides.css.scss`
Comment: It's autocorrect in this platform. the file is called css.scss.
Comment: This post may help you in a better way [How to get Twitter-Bootstrap navigation to show active link?](http://stackoverflow.com/questions/9879169/how-to-get-twitter-bootstrap-navigation-to-show-active-link)
Comment: This may help you in a better way.
http://stackoverflow.com/questions/9879169/how-to-get-twitter-bootstrap-navigation-to-show-active-link
Comment: thanks Sohair, that's not what i want. I want to render static text for each tab in my set. At the moment, the text renders in one long page and the tabs just jump down to the top of the related section. That's not what I want.
Comment: What does the browser console show? Are there any JS errors or resource 404ing?
Answer: I read the following in Bootstrap DOC:

Using navs for tab panels requires JavaScript tabs plugin For tabs
  with tabbable areas, you must use the tabs JavaScript plugin. The
  markup will also require additional role and ARIA attributes – see the
  plugin's example markup for further details.

So you probably need to add to application.js:
//= require bootstrap

Including:
   //= require bootstrap-sprockets

Is not enough:

bootstrap-sprockets provides individual Bootstrap Javascript files
  (alert.js or dropdown.js, for example), while bootstrap provides a
  concatenated file containing all Bootstrap Javascripts
Comment: Not sure which docs you are reading, but the docs say this: Markup
You can activate a tab or pill navigation without writing any JavaScript by simply specifying data-toggle="tab" or data-toggle="pill" on an element. Adding the nav and nav-tabs classes to the tab ul will apply the Bootstrap tab styling, while adding the nav and nav-pills classes will apply pill styling.
Comment: I had previously tried adding both bootstrap and sprockets to application.js. See comments above. It doesn't work. The docs for bootstrap sass say not to do it. I tried again just to check and it does not work
Comment: I copied these quotes from respectively the bootstrap official documentation (getbootstrap.com) and the SASS Bootstrap GEM (on Github).
Comment: Your HTML setup is correct, because that was confirmed by the fiddle of Aguardientico in the comments on your question.. so the only things wrong could be a javascript error elsewhere, the Javascript / CSS not loaded properly, or you are calling the tooltip code wrong. Can you confirm there's a method tab() inside your rendered .js file (when viewing source on localhost en clicking the link)? Also, do you have Firebug or some other Javascript console to check for errros in your code, it could also be caused by some other script as well, rendering jQuery inactive.
Comment: I copied my comment 4 above from bootstrap docs too (same website). I don't have any tooltips. I don't know how to check the inspect element. i can't find anything in the local host inspector. The only js in the privacy.js file is as set out above. I don't have anything anywhere else in the app called 'myTabs'. I don't know what that js is meant to do. It's certainly not doing anything.
Comment: Where I said tooltip I meant tab. To inspect if your .js includes a tab method, open the source code for your localhost (Alt + Cmd + U for chrome for mac, don't know for windows). Look for the file that looks something like: /assets/application-803a4159303d2a2401c2b82c10067bfd2eb0d2dc545e1507081abe2735dfe0f6.js, check that one for the existence of tab() method.
Comment: This should be present in your .js:   `var Tab = function (element) {
    this.element = $(element)
  }` or something comparable depending on your bootstrap version.
Comment: I definitely don't have anything like the js you have typed above. I can't see anything that looks like that in the docs either.  No - I don't have a bootstrap tab section in the js when I inspect that file. I have js for olark and google analytics, but not tabs. I tried moving the myTabs js from a file in my javascripts folder called privacy.js to the bottom of the view page, but that didn't work either.
Comment: If you don't have the Tab method, Tab won't work as it requires Javascript... take a look at the Bootstrap documentation.
Comment: The only method I have is the one set out above. I can't find anything in the docs that looks like the line you set out above.
Comment: Do you know where there are any tutorials for using bootstrap tabs with rails?
Comment: It's has really nothing to do with Rails since Rails is serverside. If you include the correct JS & CSS, have the correct HTML structure (which you have) and call the Tab() function from Bootstrap.js, then you are all set! If you do not have a Tab() method inside your .js you identified your problem! Now you can work on fixing it, by making sure the correct (CSS &) JS is present.
Comment: Please confirm that you understand that you DO need JS to achieve working Tabs in Bootstrap! http://getbootstrap.com/javascript/#tabs
Comment: http://getbootstrap.com/javascript/#tabs says you can use it without js. In any event I have something called myTabs (as above) in my js. I don't know whether that is what you're referring to as the Tab function. I don't know what 'myTabs' means. There is nothing in the file with that id. I don't know how to identify my problem. A tutorial for how to set up bootstrap tabs with rails may help. There is obviously skill involved in interpreting the bootstrap documents and construing them for a rails project. I can't figure it out and would appreciate if there is a tutorial showing how this works.
Comment: You are misunderstanding the documentation, there's no JS involved in toggling the Navigation of the tabs themselves, but there is for hiding / showing the content. That's why this part of the documentation is present in the section JAVASCRIPT. Just make sure your code includes the correct Bootstrap files. Especially //= require bootstrap (and not sprockets!) in application.js
Comment: Do you have a repo in which I can take a look?
Answer: Here's one way with extra styling to make the tabs look like what you would like.
For the rails links to work you will need to modify the javascript that shows hides content to either use turbolinks or similar.

        $(document).ready(function() {
            $(".tabs-menu a").click(function(event) {
                event.preventDefault();
                $(this).parent().addClass("current");
                $(this).parent().siblings().removeClass("current");
                var tab = $(this).attr("href");
                $(".tab-content").not(tab).css("display", "none");
                $(tab).fadeIn();
            });
        });
        body {
        padding: 20px;
        font-family: Arial, Helvetica, sans-serif;
        line-height: 1.5;
        font-size: 14px;
        }
        .tabs-menu {
        height: 30px;
        float: left;
        clear: both;
        }
        .tabs-menu li {
        height: 30px;
        line-height: 30px;
        float: left;
        margin-right: 10px;
        background-color: #ccc;
        border-top: 1px solid #d4d4d1;
        border-right: 1px solid #d4d4d1;
        border-left: 1px solid #d4d4d1;
        }
        .tabs-menu li.current {
        position: relative;
        background-color: #fff;
        border-bottom: 1px solid #fff;
        z-index: 5;
        }
        .tabs-menu li a {
        padding: 10px;
        text-transform: uppercase;
        color: #fff;
        text-decoration: none;
        }
        .tabs-menu .current a {
        color: #2e7da3;
        }
        .tab {
        border: 1px solid #d4d4d1;
        background-color: #fff;
        float: left;
        margin-bottom: 20px;
        width: auto;
        }
        .tab-content {
        width: 660px;
        padding: 20px;
        display: none;
        }
        #tab-1 {
        display: block;
        }

Tab 1

Tab 2

Tab 3

Tab 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sit amet purus urna. Proin dictum fringilla enim, sit amet suscipit dolor dictum in. Maecenas porttitor, est et malesuada congue, ligula elit fermentum massa, sit amet porta odio est at velit. Sed nec turpis neque. Fusce at mi felis, sed interdum tortor. Nullam pretium, est at congue mattis, nibh eros pharetra lectus, nec posuere libero dui consectetur arcu. Quisque convallis facilisis fermentum. Nam tincidunt, diam nec dictum mattis, nunc dolor ultrices ipsum, in mattis justo turpis nec ligula. Curabitur a ante mauris. Integer placerat imperdiet diam, facilisis pretium elit mollis pretium. Sed lobortis, eros non egestas suscipit, dui dui euismod enim, ac ultricies arcu risus at tellus. Donec imperdiet congue ligula, quis vulputate mauris ultrices non. Aliquam rhoncus, arcu a bibendum congue, augue risus tincidunt massa, vel vehicula diam dolor eget felis.

Donec semper dictum sem, quis pretium sem malesuada non. Proin venenatis orci vel nisl porta sollicitudin. Pellentesque sit amet massa et orci malesuada facilisis vel vel lectus. Etiam tristique volutpat auctor. Morbi nec massa eget sem ultricies fermentum id ut ligula. Praesent aliquet adipiscing dictum. Suspendisse dignissim dui tortor. Integer faucibus interdum justo, mattis commodo elit tempor id. Quisque ut orci orci, sit amet mattis nulla. Suspendisse quam diam, feugiat at ullamcorper eget, sagittis sed eros. Proin tortor tellus, pulvinar at imperdiet in, egestas sed nisl. Aenean tempor neque ut felis dignissim ac congue felis viverra.

Duis egestas fermentum ipsum et commodo. Proin bibendum consectetur elit, hendrerit porta mi dictum eu. Vestibulum adipiscing euismod laoreet. Vivamus lobortis tortor a odio consectetur pulvinar. Proin blandit ornare eros dictum fermentum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur laoreet, ante aliquet molestie laoreet, lectus odio fringilla purus, id porttitor erat velit vitae mi. Nullam posuere nunc ut justo sollicitudin interdum. Donec suscipit eros nec leo condimentum fermentum. Nunc quis libero massa. Integer tempus laoreet lectus id interdum. Integer facilisis egestas dui at convallis. Praesent elementum nisl et erat iaculis a blandit ligula mollis. Vestibulum vitae risus dui, nec sagittis arcu. Nullam tortor enim, placerat quis eleifend in, viverra ac lacus. Ut aliquam sapien ut metus hendrerit auctor dapibus justo porta.

Proin sollicitudin tincidunt quam, in egestas dui tincidunt non. Maecenas tempus condimentum mi, sed convallis tortor iaculis eu. Cras dui dui, tempor quis tempor vitae, ullamcorper in justo. Integer et lorem diam. Quisque consequat lectus eget urna molestie pharetra. Cras risus lectus, lobortis sit amet imperdiet sit amet, eleifend a erat. Suspendisse vel luctus lectus. Sed ac arcu nisi, sit amet ornare tellus. Pellentesque nec augue a nibh pharetra scelerisque quis sit amet felis. Nullam at enim at lacus pretium iaculis sit amet vel nunc. Praesent sapien felis, tincidunt vitae blandit ut, mattis at diam. Suspendisse ac sapien eget eros venenatis tempor quis id odio. Donec lacus leo, tincidunt eget molestie at, pharetra cursus odio.

Comment: Hi Abs, no -that's not the styling or format I want. I want the styling I have (when the js does not work properly).
Comment: also - i can't use turbo links because i use olark

Rails with Bootstrap Tabs


Nativescript real device date and time

Question: Is there a way I can get the date and time of device ? The auto one. If the user disables the auto in date and time and chooses his own date and time, it would crash my app. I am also using firebase with it
Answer: It's not possible to detect that info on iOS, but on Android you could do this.
<code>if (application.android) {
        if (android.provider.Settings.Global.getInt(application.android.context.getContentResolver(), android.provider.Settings.Global.AUTO_TIME, 0) !== 1) {
            console.log("Date / Time preference is not set to auto!!!");
        }
    }
</code>
On iOS the only option may be comparing the local date time with the server's date time with a simple api, make sure you include the timezone info.

Nativescript real device date and time


Where have I gone wrong in finding the derivative of $2^{\sin x}$?

Question: I was finding the derivative of $2^{\sin x}$.
My attempt $(1)$-
$$y=2^{\sin x}$$
$$\implies\ln y=\ln2^{\sin x}$$
$$\implies\log_ey=\ln2^{\sin x}$$
$$\displaystyle\implies e^{\ln2^{\sin x}}=y$$
$$\implies\frac{d}{dx}y=\frac{d}{dx}e^{\ln 2^{\sin x}}$$
Now,I know $\frac{d}{dx}e^x=e^x$ but what about $\frac{d}{dx}e^{\ln 2^{\sin x}}$.
How do I simplify it?
My attempt $(2)$-
$$2^{\sin x}=y$$
$$\log_2y=\sin x$$
$$\frac{d}{dx}\log_2y=\frac{d}{dx}\sin x$$
Now,I feel that chain rule can be used some how in the LHS to get $\frac{dy}{dx}$ which is our required derivative,but I am having trouble applying chain rule.
What to do?
Thanks a lot for any help!!
Comment: What you should have done is note that $\ln 2^{\sin x} = \ln 2\cdot\sin x$.
Comment: The first four lines do not help; they are like saying $f(x)=f(x)+3-3$.
Comment: @CameronWilliams How did you get that?
Comment: @tatan From the properties of logarithms.
Comment: @CameronWilliams That was trivial...missed it out...thanks by the way...
Comment: $2^{\sin x}=(e^{\ln 2})^{\sin x}=e^{(\ln 2) \sin x}.$
Answer: I feel like it will be easier to go off of Attempt 1, so I'm going to do that:
$$\frac{dy}{dx}=\frac{d}{dx}e^{\ln 2^{\sin x}}$$
Now, we know that $\ln2^{\sin x}=\sin x\ln 2$, so make the substitution:
$$\frac{dy}{dx}=\frac{d}{dx}e^{\sin x\ln 2}$$
At this point, we have the right-side function in the form of $e^{g(x)}$ where $g(x)=\sin x\ln 2$. This means we can use chain rule:
$$\frac{dy}{dx}=\frac{d}{dg}e^{g(x)}\frac{d}{dx}\left(\sin x \ln 2\right)$$
It is a common identity that $\frac{d}{dg}e^{g(x)}=e^{g(x)}$. Also, it is a common identity that $\frac{d}{dx}\sin x=\cos x$, so we can use constant multiplication rule to get that $\frac{d}{dx}\left(\sin x \ln 2\right)=\ln 2\cdot \cos x$:
$$\frac{dy}{dx}=e^{g(x)}\ln 2\cdot \cos x$$
Finally, substitute back in $g(x)=\sin x\ln 2$:
$$\frac{dy}{dx}=e^{\sin x\ln 2}\ln 2\cdot \cos x$$
Now, to finish it off, we need to simplify. Note that $e^{\sin x \ln 2}=\left(e^{\ln 2}\right)^{\sin x}=2^{\sin x}$:
$$\frac{dy}{dx}=2^{\sin x}\ln 2\cdot \cos x$$
Comment: The way you have written it may appear that $\ln 2\cos x = \ln(2\cos x)$ Better to write it as $\ln 2\cdot \cos x$ or explicitly as $(\ln 2)(\cos x)$.
Comment: @ParamanandSingh Thanks for the suggestion! I'm using $\ln 2\cdot\cos x$ now.
Answer: For this kind of problems, logarithmic differentiation makes life easier $$y=2^{\sin (x)}\implies \log(y)=\sin(x)\log(2)$$ Differentiating both sides $$\frac{y'}y=\cos(x)\log(2)\implies y'=2^{\sin (x)}\cos(x)\log(2)$$


What's next after Windows Server 2008 R2?

Question: Looking at Windows Server 2008 R2 and wondering about the value of Software Assurance. I must be just fumble fingered today because I can't seem to find a roadmap for where we're going from here.

When's the next proposed release date for version next?
Where's currently the best place to purchase with or without SA? Been awhile since I've done direct purchasing.
Comment: I'm just happy that the server and client releases are back in lockstep.  For a while there it was seriously schizophrenic.
Answer: Can't remember an exact url but if I remember correctly, Micrososft has committed to a 3 year release cycle, with interim (R2) releases after 18 months.
Comment: And in the past they committed to a 2 year cycle, but still took 5 years to release. It comes when it comes.
Comment: Agreed. R2/Win7 was actually somewhat on schedule but time will tell.
Answer: The next version Windows Server 8 (my be renamed) out around mid next year.
Comment: This answer would be improved by providing more substance and references to support your information.


#default_value not being displayed in form

Question: Here's a function that returns a form:
function myfunc($str)
{
    $form = array();
    $form['header text'] = array(
        '#markup' => '
blah blah blah
',
    );
    $form['new_str_value'] = array(
         '#type' => 'textfield',
         '#title' => 'New String Value',
         '#size' => 60,
         '#maxlength' => 128,
         '#required' => TRUE,
         '#default_value' => $str,
    );

    return $form;
}

The textfield displays correctly with the right size and label, but it is not populated with an initial value. Any ideas? Should I be rendering or building the form in the function before returning it, or setting the value in $form_state ... or something?
Any help much appreciated!
Comment: How is `$str` being passed to the form function?
Comment: ``myfunc`` is called via a page callback from ``hook_menu`` - it's a page argument passed in from the URL. I've simplified the actual function in this listing - but ``$str`` definitely contains a useful string by the time it is used as ``#default_value``.
Answer: Assuming Drupal 7...
The signature for form functions needs to follow a strict pattern; Drupal will pass along $form and $form_state as the first two args, and anything else as subsequent args.
So assuming $str should be the first custom arg to the form, the signature should look like this:
function myfunc($form, &$form_state, $str) {

Comment: Thanks for this Clive. This gives me a further problem, then - if I need to call this function from ``hook_menu`` by setting ``page callback`` to ``drupal_get_form`` and ``page_arguments`` to ``array('myfunc')``, how do I now pass through the token from the URL? (The path is ``admin/config/foo/bar/%``).
Comment: That would be `'page callback' => 'drupal_get_form', 'page arguments' => array('myfunc', 4)`, where the `4` refers to the zero-based index of the parameter in the URL, when split on the `/` char. I'm always curious whether that particular explanation will mean anything to someone who hasn't seen it before, do let me know if not ;)
Comment: Magic!! That works. BTW the explanation of where '4' comes from does make sense to me, but only because I've figured it out previously - it took me a while to work out how to set those parameter values! Best regards, MB


Hypothesis testing: Why is a null model that fits the data well better than one that doesn't?

Question: Let's say we have two models: a null model, $M_0$, and an alternative model $M_1$.    The only difference between them is that, in $M_0$ one parameter is fixed at $0$ and in $M_1$, that parameter is fixed at the value that maximizes the likelihood of model $M_1$.  This is a typical setup for a likelihood ratio test.
My intuition is that the better $M_0$ describes the data-generating process, and thus the less the residual variation in the fitted model, the better.  By "better", I mean for a given sample size, effect size, and false positive rate, I will have more power to reject the null.
That's a bit hand-wavey.  I'll make a simulation with a linear regression model.
<code>set.seed(27599)

lm_lrs_no_covar <- function(y, x) {
    2*(logLik(lm(formula = y ~ x)) - logLik(lm(formula = y ~ 1)))
}

lm_lrs_yes_covar <- function(y, x, z) {
  2*(logLik(lm(formula = y ~ x + z)) - logLik(lm(formula = y ~ z)))
}

n <- 1e2
num_sims <- 1e4

no_covar <- yes_covar <- rep(NA, num_sims)

for (sim_idx in 1:num_sims) {

  x <- runif(n = n)
  z <- runif(n = n)
  y <- rnorm(n = n, mean = 0.2*x + z, sd = 0.2)

  yes_covar[sim_idx] <- lm_lrs_yes_covar(y = y, x = x, z = z)
  no_covar[sim_idx] <- lm_lrs_no_covar(y = y, x = x)
}

plot(x = sort(no_covar),
     y = sort(yes_covar),
     type = 'l')
abline(a = 0, b = 1)
</code>
This plot shows that the LR statistic from the model with the covariate is pointwise greater than the LR statistic from the model without the covariate.

But, why, from a likelihood perspective is this so?
Answer: The models are dominated by the large residual variability, implicitly set to the default value sd=1 of the rnorm() function. Differences in the covariate structure contributes little to the quality of the model, and the small difference cannot be detected with your simulations. Use sd=0.1 and you get different results that match your intuition.
<code>    set.seed(27599)

lm_lrs_no_covar <- function(y, x) {
    2*(logLik(lm(formula = y ~ x)) - logLik(lm(formula = y ~ 1)))
}

lm_lrs_yes_covar <- function(y, x, z) {
  2*(logLik(lm(formula = y ~ x + z)) - logLik(lm(formula = y ~ z)))
}

n <- 1e2
num_sims <- 1e2

no_covar <- yes_covar <- rep(NA, num_sims)

for (sim_idx in 1:num_sims) {

  x <- runif(n = n)
  z <- runif(n = n)
  y <- rnorm(n = n, mean = 0.2*x + z,sd=0.1)

  yes_covar[sim_idx] <- lm_lrs_yes_covar(y = y, x = x, z = z)
  no_covar[sim_idx] <- lm_lrs_no_covar(y = y, x = x)
}

plot(x = sort(no_covar),
     y = sort(yes_covar),
     type = 'l')
abline(a = 0, b = 1)
</code>
Comment: You explained why my simulation didn't support my intuition.  But you didn't answer the overall question -- why does a null model that fits the data better  perform better?  Said another way, from a likelihood perspective, why is my intuition correct?
Comment: Fraction of explained variability?
Comment: I'm not sure what you're asking.
Answer: I haven't been able to thoroughly crack this one, and it's only gotten one partial answer on SE, but here's what progress I've made.

It's not too surprising, but both the null and the alt models fit better when the covariate is included (blue and purple are above red and green).  But, as reflected in the LR, there's more improvement from null to alt when the covar is modeled (blue->purple has more improvement than red->green).
I guess my read on this is that the more correct the null model is, the more improvement we get from adding in the tested parameter.  In the absence of the covariate, the MLE of the parameter that we add to go from null to alt may be some compromise between explaining the unmodeled effect of the covariate and explaining what that parameter really does in the data-generating process.


Is measure preserving action $\theta_t$ measure preserving with $t$ replaced by a stopping time?

Question: Suppose $\theta:\mathbb{Z}\times \Omega\to \Omega$ is a measure preserving action on a probability space. In particular $E[X] = E[X\circ \theta_t]$ for all $t$. Does the same hold if $t$ is replaced by a stopping time $\tau$ relative to $\{\mathcal{F}_t\}$ if $X$ is $\mathcal{F}_{\infty}$-measurable?
Comment: What is $\mathcal F_t$? You haven't even defined the filtration. This is especially unclear since you're indexing set here is $\Bbb Z$ and not $\Bbb N$.
Answer: No, this is false if I understand the question correctly.
Take $\Omega = \{0,1\}^{\Bbb Z}$ with its product $\sigma$-algebra, and let $\mu$ be the infinite product of Bernoulli$(1/2)$. Let $\mathcal F_t$ be the filtration generated by coordinate maps $\pi_n(\omega)=\omega_n$ for $n \leq t$.
Let $\theta$ be the shift operator, that means that $$\theta(n,\omega) = (\omega_{n+k})_{k \in \Bbb Z}$$
Let $X(\omega)=\pi_1(\omega) = \omega_1$, the first positive coordinate of the infinite sequence $\omega$. Let $T(\omega)$ be the first $n \in \Bbb N$ such that $\omega_n=1$. Then clearly $E[X \circ \theta_T]=1$ whereas $E[X \circ \theta_t] = \frac{1}{2}$ for all fixed times $t$.
Comment: Apologies for my question not being clear. I'm trying to figure out under what conditions $E[X] = E[X \circ \theta_{\tau}]$ ``should'' hold, and I guess my intuition was wrong.


Understanding singular complexes

Question: I'm just getting started on singular homology and I've found that when we compute the singular $q$-simplices of a topological space X (which is the set of all linear mappings $\sigma: \Delta_n \to X$) we only use a few generators, but there'd be more. Let me explain myself:
Suppose we're computing the singular $q$-simplices of a line with vertices $v_1$ and $v_2$. We usually say that the singular 0-simplex is the free abelian group spanned by $\langle\sigma_1, \sigma_2\rangle$, where $\sigma_i: \Delta_0 \mapsto v_i$. However, when we compute the singular 1-simplex we say that it is the free abelian group spanned by $\langle \rho \rangle$, where $\rho: \Delta_2 \mapsto [v_1 v_2]$ (here $[v_1 v_2]$ denotes the line with edges $v_1$ and $v_2$). Wouldn't $\rho': \Delta_2 \mapsto v_1$ be another generator of the singular 1-simplex?
In general, I feel like I can choose infinitely many generators for every singular $q$-simplex.
I'm pretty sure I'm not understanding the point of the theory well enough, so please I'd really appreciate if anyone could answer me.
Comment: It sounds like you are actually talking about simplicial homology, not singular homology.  A **lot** of your terminology is mixed up though so it's hard to tell.  I would suggest that you start by not trying to think about things intuitively and instead working with the precise definitions that are in whatever reference you are learning from.
Answer: You confuse a lot of things. A singular $n$-simplex of $X$ is a continuous map $$\sigma_\alpha\colon \Delta^n \to X$$
The singular $n$-simplices of $X$ are the basis elements of the free abelian (chain) group $C_n(X)$, i.e. they generate $C_n(X)$.
A singular $0$-simplex is not being generated by singular $0$-simplices, but if your space $X$ admits precisely two singular $0$-simplices, then the chaingroup $C_0(X)$ is generated by these two $0$-simplices.
Also, it's certainly not true that you can somehow choose infinitely many generators for a chaingroup, say $C_1(X)$. The free abelian group $C_n(X)$ is a free $\mathbb{Z}$-module and its elements are formal sums $\sum_i n_i\sigma_i$ with $\mathbb{Z}$-coefficients $n_i$. These elements are called $n$-chains.
In summary, $n$-chains of $C_n(X)$ are linear combinations of basis elements the singular $n$-simplices $\sigma_\alpha$ that generate $C_n(X)$.
In order to get a better intuitive picture i would highly suggest you to look up the idea of homology, it's very well illustrated in Hatcher on p.99.
Comment: Thanks to both Eric and Zest! But could you please explain more about why can't we have infinitely many generators? There may exist infinitely many continuous $n$-simplices $\sigma: \Delta_n \to X$, isn't it true?
Comment: The cardinality of the basis of a free abelian group is called its *rank*. Similar to the dimension of a vector space, a free abelian group can indeed have infinite rank (i.e. infinitely many basis elements). But you can't choose infinitely many generators if the rank is finite.

Understanding singular complexes


Merging columns Dataframe

Question: I have the following Dataframe:
df1

startTimeIso
endTimeIso
id

2023-03-07T03:28:56.969000
2023-03-07T03:29:25.396000
5

2023-03-07T03:57:08.734000
2023-03-07T03:59:08.734000
7

2023-03-07T04:18:08.734000
2023-03-07T04:20:10.271000
16

2023-03-07T07:58:08.734000
2023-03-07T07:58:10.271000
21

and the second one:
df2

startTimeIso
endTimeIso
value

2023-03-07T03:28:57.169000
2023-03-07T03:29:25.996000
true

2023-03-07T03:57:08.734000
2023-03-07T03:58:08.734000
true

2023-03-07T05:38:08.734000
2023-03-07T05:40:10.271000
true

2023-03-07T07:58:08.934000
2023-03-07T07:58:10.371000
true

I want to check, if a row from df2 merge with a row from df1. There can be a tolerance from 1 Second. StartTimeIso as well as endTimeIso should be considered.
The result should look like this:
df_merged

startTimeIso
endTimeIso
value
startTimeIso_y
endTimeIso_y
id

2023-03-07T03:28:57.169000
2023-03-07T03:29:25.996000
true
2023-03-07T03:28:56.969000
2023-03-07T03:29:25.396000
5

2023-03-07T03:57:08.734000
2023-03-07T03:58:08.734000
true
None
None
None

2023-03-07T05:38:08.734000
2023-03-07T05:40:10.271000
true
None
None
None

2023-03-07T07:58:08.934000
2023-03-07T07:58:10.371000
true
2023-03-07T07:58:08.734000
2023-03-07T07:58:10.271000
21

Rows_found = 2
Comment: For clarity can you provide an example for which end is considered differently than start? Here a simple merge on start OR end is sufficient
Comment: @mozway Can you modify the code so that the end of the values must match a tolerance of 1 second?
Currently only the startTimeIso is checked, but the end can be as long as you like.
Answer: one-to-one merge using merge_asof
Use a merge_asof with tolerance:
df1[['startTimeIso', 'endTimeIso']] = df1[['startTimeIso', 'endTimeIso']].apply(pd.to_datetime)
df2[['startTimeIso', 'endTimeIso']] = df2[['startTimeIso', 'endTimeIso']].apply(pd.to_datetime)

out = pd.merge_asof(
    df2.sort_values(by='startTimeIso'),
    df1.sort_values(by='startTimeIso')
       .rename(columns={'startTimeIso': 'startTimeIso_y'}),
    left_on='startTimeIso', right_on='startTimeIso_y',
    direction='nearest', tolerance=pd.Timedelta('1s'),
    suffixes=(None, '_y')
)

print(out)

Output:
             startTimeIso              endTimeIso  value            endTimeIso_y    id
0 2023-03-07 03:28:57.169 2023-03-07 03:29:25.996   True 2023-03-07 03:29:25.396   5.0
1 2023-03-07 03:57:08.734 2023-03-07 03:58:08.734   True 2023-03-07 03:58:08.734   7.0
2 2023-03-07 05:38:08.734 2023-03-07 05:40:10.271   True                     NaT   NaN
3 2023-03-07 07:58:08.934 2023-03-07 07:58:10.371   True 2023-03-07 07:58:10.271  21.0

If you want to consider either start or end, perform two merges and combine_first:
out1 = pd.merge_asof(
    df2.sort_values(by='startTimeIso').reset_index(),
    df1.sort_values(by='startTimeIso')
       .rename(columns={'startTimeIso': 'startTimeIso_y'}),
    left_on='startTimeIso', right_on='startTimeIso_y',
    direction='nearest', tolerance=pd.Timedelta('1s'),
    suffixes=(None, '_y')
)

out2 = pd.merge_asof(
    df2.sort_values(by='endTimeIso').reset_index(),
    df1.sort_values(by='endTimeIso')
       .rename(columns={'endTimeIso': 'endTimeIso_y'}),
    left_on='endTimeIso', right_on='endTimeIso_y',
    direction='nearest', tolerance=pd.Timedelta('1s'),
    suffixes=(None, '_y')
)

out = out1.combine_first(out2).set_index('index')

print(out)

many-to-many merge using numpy
s1 = df1['startTimeIso'].to_numpy()[:,None]
s2 = df2['startTimeIso'].to_numpy()
e1 = df1['endTimeIso'].to_numpy()[:,None]
e2 = df2['endTimeIso'].to_numpy()

ms = abs(s1-s2) < pd.Timedelta('1s')
me = abs(e1-e2) < pd.Timedelta('1s')

idx1, idx2 = np.where(ms&me)

out = df2.join(df1.iloc[idx1].set_axis(df2.index[idx2])
                  .rename(columns={'startTimeIso': 'startTimeIso_y',
                                   'endTimeIso': 'endTimeIso_y'}))

Comment: @hubi3012 it depends if you are trying to do a one-to-one or one-to-many or many-to-many merge. `merge_asof` only supports one to one. Can you give more details, eventually updating your example?
Comment: The many-to-many merge solution is exactly what I was looking for. It works perfectly for me. Thank you!
Comment: If I understand correctly, the two columns startTimeIso of the data frames are merged using merge_asof. Is there a way to include the column endTimeIso in the merge, so that the end time is also taken into account?
Because when I tried the first example, only the startTimeIso has to match. The endTimeIso does not play a role.
Comment: When I look at your solution, the 2 line in df2 is matched with the 2 line in df1. Now I have adjusted the times in my df1 so that this should no longer be matched, since startTimeIso in the two dfs matches but endTimeIso in the two dfs does not, since the end time of the two entries is different, even taking into account the tolerance. I hope I can give you more clarity with this. I would like to see if both the startTimeIso and the endTimeIso match during the merge.
Comment: Unfortunately no, that would be a different logic
Comment: can you perhaps give me an example of this?
Comment: You should probably open a new question with specific examples

Merging columns Dataframe


Not enough storage is available to process this command

Question: I've got a number of users who are complaining that IE8 gives the error Not enough storage is available to process this command when printing very large documents (100's of pages). I found a number of articles that talk about the IRPStackSize being too small, but even with that turned up to 50 (the highest it will go), I still see this error happening.
Are there any other possible work around's? Or is it simply that IE is not capable of printing very large documents?
UPDATE
For anyone else looking at this kind of problem:
We have abandoned printing documents directly from the browser, there was a whole litany of problems. We had everything from out of memory errors, images not being displayed and browsers just plain locking up.
Printing large documents from the browser is a plain bad idea. We are currently looking at alternatives.
Comment: I saw this problem and used another browser to print with success. Google Chrome worked when IE did not.
Answer: Your research seems to point to a fairly unavoidable limitation in IE8, and I couldn't find anything to contradict that.
Have you tried printing to PDF, ODI, or other disk-based document format first? This would be my first choice for a workaround.
Comment: +1 I seriously doubt that IE (or any browser) was ever meant to print hundreds of pages.


How to write columns and rows using .map and for loop

Question: I've been trying to solve this all day. It's an exercise for a programming course, but I seem unable to solve it. It's pretty beginner but I would still appreciate any help.
http://repl.it/dfl/1
Basically the exercise is this:
create a function called clearBoard()
This function will go through every cell in checkerboard and set that cell's value to null.
we've been using for loops and .map so that's basically the tools we should use to solve this.
I am kind of lost, so I created a function to see how to write on the columns and how to write on the rows. I can't seem to write on both.
I see that my for loop isn't working, and I don't know why. I think I'm doing everything right. The only thing that works is the .map iterator but it doesn't do rows and columns.
Answer: If you want to use .forEach and .map:
var clearBoard = function (checkerboard) {
    checkerboard.forEach(function (row) {
        row.map(function () {
            return null;
        })
    })
    return checkerBoard;
}

But that's probably slower than:
var clearBoard2 = function (board) {
    // you can use use i < 8 and j < 8, since checkerboards
    // are always 64 squares
    for (var i = 0; i < board.length; i++) {
        for (var j = 0; j < board[i].length; j++) {
            board[i][j] = null;
        }
    }
    // you could also do
    /*
        for (var i = 0; i < 64; i++) {
            checkerboard[Math.floor(i/8)][i % 8] = null;
        }
    */
    // since it's the same thing
    return board;
}

Here's another way you can do it:
var clearBoard3 = function () {
    var board = [];
    for (var i = 0; i < 8; i++) {
        board[i] = Array.apply(null, new Array(8));
    }
    return board;
}


SAT MATH Circle Geometry

Question: How many points may be contained in the intersection of 2 distinct circles?
The answer is 0, 1 and 2 points. I don't get why it could be 0 points when two circles are intersecting.
Comment: The question is not ambiguous.  Take note, it asks:  "How many points *may be* contained in the intersection of $2$ distinct circles?" and **NOT** "How many points may be contained in the intersection of $2$ distinct *intersecting* circles?"
Comment: answer: 2. Draw two intersecting circles .
Comment: @DeepSea: Not necessarily. ... in mathematics the intersection of two things can definitely sometimes be the empty set, so no points in common.
Comment: 2 distinct circles can intersect in 1 or 2 points
Comment: I think the question was too ambiguous, but as Jose answered, concentric circles could be counted for $0$ points.
Comment: The problem is asking how many different amount of points can fit. If you draw 2 circle intersecting, it has an intersecting point, but it doesn't need to be counted. $0$ points could "fit" in this region.
Answer: No points of intersection

One point of intersection

Two points of intersection
Comment: but in case 1 and 2 the the circles are not intersect with each other
Comment: @k.Vijay, please see Ted Shifrin's and Lê Đức Minh's comments above.
Comment: It is possible to give examples from analytic geometry where these cases become apparent and clear.  I will edit those examples into this answer when time permits.
Answer: The problem clearly asks:

"How many points may be contained in the intersection of 2 distinct circles?"

And thus, the assumption that the circles are actually intersecting in all three cases is wrong.

There can be $0$ points in the intersection of two distinct circles, if they are not intersecting. This implies that there is a distance between any point on circle $A$ and any point on circle $B$.
There is $1$ point of intersection, when there is only one point $P$ that is included in both circles.
There are $2$ points of intersection, when only two points are common to both circles.

See the image below for clarifications:

SAT MATH Circle Geometry


How to prevent sessionStorage being inherited when using target="_blank"/window.open() to open a new window/tab?

Question: On a tab with url http://foo.com/ I set a sessionStorage item thus-
sessionStorage.bar="hello";

I then open a new window on any path on the same domain -
window.open("http://foo.com/any/path");

Then on the new window I find that -
sessionStorage.bar === "hello"

Is true. The exact same thing happens if I use a link with target="_blank" attribute to open the new window. The exact same thing also happens when a new tab is opened, and not a new window. Another thing to note is that this is only true for items set on sessionStorage before opening the new window. Adding or changing any item on sessionStorage in either windows after the new window is opened does not effect the other window in any way.
I thought that sessionStorage was supposed to be scoped to a single tab/window, but apparently sessionStorage is extended to new tabs and windows when they are opened from another window.
Is there a way to prevent this? I can probably test for existence of window.opener to detect such a case, but it would be much cleaner if it was possible to prevent it in the first place.
Thanks!
Comment: sessionStorage is scoped to the session, hence the name.  Doesn't matter the tab you have it on.
Comment: @JeremyMiller, thanks for your comment, could you please elaborate? How is the session then defined? [MDN](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage) simply says that "Opening a page in a new tab or window will cause a new session to be initiated."
Comment: Found it.  It's in the spec they link to, but it's a bit to type, so I'll post as an answer.
Comment: hmmm... I must have been mistaken.  Checking in detail now.
Answer: According to the Webstorage Specification, "When a new Document is created in a browsing context which has a top-level browsing context, the user agent must check to see if that top-level browsing context has a session storage area for that document's origin. If it does, then that is the Document's assigned session storage area."
So, my take on this is that if you close the tab, then open a new tab, it will be a new "session" per the specification.  However, if the tab remains open and you then open a new tab, the top-level browsing context matches, so the sessionStorage is referenced.
Comment: it's cloning for me on chrome 62 but not firefox 56
Comment: Thanks! Do you have any suggestion as to how to override or bypass this behavior other than checking window.opener?
Comment: Only by destroying the sessionStorage onLoad.  What's your goal?
Comment: I can't destroy the sessionStorage, so I guess I would work around checking window.opener. Thanks again for your help and insights!
Comment: This "cloning" behaviour seems specific to IE - Firefox and Chrome, at least, seem not to inherit sessionStorage from opening windows, and this post is the only thing I can find referring to sessionStorage inheritance. My take on that quote from the spec is, a "browsing context which has a top-level browsing context" refers to iframes. So an iframe with the same origin as the containing window gets the same sessionStorage - and *exactly* the same sessionStorage, i.e. changes made by one context will be seen by the other - unlike the "cloned" sessionStorage behaviour that only IE exhibits.
Comment: This might not be true.
Answer: You can prevent a new tab or window from inheriting a copy of the original window's sessionStorage by setting the window.open windowFeatures parameter 'noopener' to true:
window.open('http://example.com', '_blank', 'noopener=true');

The parameter 'noreferrer' also works because, if set, the browser will omit the Referer header, as well as set noopener to true.
Mozilla documentation for window.open
Note: this parameter is not a solution when using window.open to open a URL in the same (i.e. current window, with the target set to '_self'). Although the reassigned window will not have a window.opener value, the session storage set by the prior URL may remain--at least if the new URL has the same domain.
Comment: Awesome solution! Hopefully it works in all browsers...?
Comment: I can vouch only for Firefox.
When opening a URL in the same window, you can do this:

`let j = sessionStorage.length - 1;
for (j; j >= 0; j--) {
    sessionStorage.removeItem(sessionStorage.key(j));
}
window.open('http://www.example.com', '_self');`
Comment: To follow up my last comment: This solution does not work in safari on iOS.
Answer: You can using this way:
    const a = document.createElement('a');
    a.href = "http://example.com/any/path";
    a.target = '_blank';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);

Comment: This works like a charm in all browsers I have tested so far. :)
Answer: I solved this by temporary removing the session item while opening the new window.
sessionStorage.removeItem('bar');
window.open('http://example.com/any/path', '_blank');
sessionStorage.setItem('bar', 'hello');

Answer: You can workaround the inheritance behavior by using a separate key per window (or if you have multiple keys, by applying some unique prefix to each key).
That begs the question of how to assign/retain a unique key per window.  Well, SessionStorage is not empty when link opened in new tab in Internet Explorer shows that you can set the name of each window to some unique value, which is retained across reloads.


How do I use block_view_alter for the template file?

Question: I want to alter a view block. I used hook_block_view_alter(), but this is not working in a template theme Drupal 8.
How do I use hook_block_view_alter() in template theme?
Comment: Welcome to Drupal Answers! The only part clear in the question is that you are trying to use `hook_block_view_alter()`. Since you are talking of code you wrote, you should show what code you wrote. _It is not working_ is not much helpful. What did you get from the code you are using, and what is the expected result?
Answer: I think from the *.theme file you should use hook_preprocess_HOOK
Comment: Yes, Drupal doesn't invoke `hook_block_view_alter()` for themes.
Comment: Used hook_preprocess_block which Could not call region of each block for check by handle code !
Comment: @HenryTran Your comment is not clear at all. First, you need to show the code you are using, and tell us exactly what you are trying to achieve; then, we can answer your question. Until then, the only possible answer is this. Drupal doesn't invoke `hook_block_view_alter()` when implemented from a theme.


Ban or Kick when a timer expires (Discord.js)

Question: I have been trying to code a timer set by a mod that is put into a user, when the time is out, the person automatically gets kicked or banned, or it is not able to see nothing from the server. But been really struggling.
Comment: What have you tried so far?  SO is not a code writing service, so you need to show some proof of what you've tried or what you've tried to *find* so we can help.
Answer: <code>// make sure member = the member object
setTimeout(() => member.ban(), MILLISECONDS /* e.g 1000 for 1s */);
</code>


Joint distribution of min(X,Z) and min(Y,Z)

Question: I have three random variables, $X\sim exp(a), Y\sim exp(b), Z \sim exp(c).$ They are all independent. I need to find $P(Min(X,Z)\geq u_1, Min(Y,Z)\geq u_2)$ I.e the joint probability of the two minimum.
I think that I somehow need to break the minimum and have three inqualities. After that Ican use their independece. The problem is that I don't know how to break them up.
Any help would be much helpful.
Answer: Hint:
On base of rule: $$\min(a,b)\geq c\iff a\geq c\text{ and }b\geq c$$ you can find that the event can also be described as: $$\{X\geq u_1,Y\geq u_2,Z\geq\max(u_1,u_2)\}$$Now apply independence.
Comment: @Math1000 in cases like this I always investigate whether the rule mentioned  in my answer might make things more easy.
Comment: Simply brilliant. May I ask how you had the idea to split the event into disjoint elements of $\sigma(X)$, $\sigma(Y)$, and $\sigma(Z)$?


Use the Bisection method to find solutions

Question: Use the Bisection method to find solutions, accurate to within $10^{−5}$ for the following problems.
$$2x\cos(2x)-(x+1)^2=0,$$
for $-3\leq x\leq -2 $, and $-1\leq x\leq 0 $
Help me please. If you can help me please make sure the solution is complete and detailed so that you can understand it so that you can independently solve other examples
Comment: What kind of help do you need? Do you know what the Bisection method is?
Comment: i Know the bisection method
Comment: Then what is stopping you from using it in this example? Again, what kind of help do you need?
Comment: don't know how to implement it, if you can, then please choose, but in detail so that you can solve other examples
Comment: You implement it by doing some calculations about $20$ times for each root. How you do the calculations is up to you.
Comment: You code or copy the general bisection method `bisection(f,a,b,eps)`, then your function `my_f(x) return 2*x*cos(2*x)-pow(x+1,2)` and call `bisection(my_f,-3,2,5e-6)` and call the output your result. You might want to print out step information in the bisection method.
Answer: hint: Use that $$\cos(2x)=\frac{(x+1)^2}{2x}$$ and $$|\cos(2x)|\le 1$$ so $$\frac{(x+1)^2}{2|x|}\le 1$$
Comment: then ... i don't understand what to do, please help me, complete the example, i know that the formula: $\frac{b-a}{2^n}\leq 10^{-5}$
Comment: thats all, finish the problem, @Dr. Sonnhard Graubner


select2: load asynchronous data through promise

Question: What is the best place to load the options for select2 asynchronously. I want the same facility as ajax, but instead of select2 sending an ajax request, it needs to load the values asynchronously from a promise object. Below code works, in which I load the data in query, but which means every keystroke, invocation of select dropdown, it will query the data. so, what is the correct configuration?
code:
var items2 = [
            {
                "Id": 1,
                "Name": "First"
            },
            {
                "Id": 2,
                "Name": "Second"
            },
            {
                "Id": 3,
                "Name": "Third"
            }
        ];

        var names = function () {
            var deferred = $q.defer();

            $timeout(function () {
                deferred.resolve(items2);
            }, 200);

            return deferred.promise;
        };

        var query: function (query) {
                var results = [];

                names().then(function(d){
                    $.each(d, function(index, item){
                        results.push({
                            id: item.Id,
                            text: item.Name
                        });
                    });

                    query.callback({  results: results });
                })
        };

Edit
looking at the source, it looks like it only allows either ajax or local for querying data. It would have been ideal if local takes a function which returns the data. Am I on the right track? is there an easy way to patch it?
thanks
// exports
    window.Select2 = {
        query: {
            ajax: ajax,
            local: local,
            tags: tags
        }, util: {
            debounce: debounce,
            markMatch: markMatch,
            escapeMarkup: defaultEscapeMarkup,
            stripDiacritics: stripDiacritics
        }, "class": {
            "abstract": AbstractSelect2,
            "single": SingleSelect2,
            "multi": MultiSelect2
        }
    };

Edit2:
'local` indeed accepts a function. but it doesn't play nicely with remote data, as the data is received with a delay (async), drop down is not populated with the new data. I have to close and open the drop-down again. This is not intuitive for the user.
Answer: As far I see, select2 invokes an ajax call for each key stroke, and opening the select box. I can get the same behavior using query (with promise) as in the original question. I was expecting select2 loads the data once, then do rest locally (search, and further invocation till any data change). looks like this is not an option. I may just cache my results locally. Better answer welcome.
Comment: how to get it with query (promise)?


Why would $f(x)$ at point $b$ not equal $f(b)$?

Question: In the picture below, I am told that points a and b represent different kinds of discontinuities.
Point a is discontinuous since the point limit of $f(x)$ as $x$ tends to $a$ doesn't exist. That does sound quite cryptic, my interpretation is that since $f(x)$ doesn't tend to $a$ when $x<a$, that point can't be regarded as continuous.
I'm more confused about point $b$ though. The book states that since this point cannot be continiuous since $A\neq f(b)$.
I am having a hard time comprehending this statement, surely at point $b$, the function $f(x)=f(b)$ by definition?
Comment: $f(b)\ne A$ is a gimmick to illustrate a point.
Answer: Yes, obviously $f(x)=f(b)$. However, the limit of the function when $x\to b$ is not $f(b)$. As you can see the values of $f$ near the point $x=b$ (not at the point itself but at its neighborhood) are very far from $f(b)$.
Comment: Right, so this is a hypothetical case where everything infinitly close to $f(b)$ tends to A, but the infinitly small point $f(b)\neq A$?
Comment: Well, yes. The closer $x$ is to $b$, the closer $f(x)$ gets to $A$. And only at the point $x=b$ itself the value is very different.
Answer: The point $f(b)$ is the black dot.
However, it is not equal to $\lim_{x \to b} f(x)=A \ne f(b)$, hence it is not continous at $b$.
The points around $b$ takes values that are closer to $A$ and far from $f(b)$.


Eliminar dado selecionado do array

Question: Na minha função eu insiro um dado informado em um array e em uma box para visualização do usuário. Mas caso ele queira retirar essa informação, ele seleciona ela e é retirada através da function! Porém caso ele informar a mesma informação novamente, ela da erro informando que já existe!
Ex:
variaveis na function
         w_Cont_Qtde = 1;
         w_Qtde_Peri = $arr_w_param[10]; --> $arr_w_param[10] é a quantidade informada em uma tela anterior (ex: 5 / 10 / ...)
         v_patr = new Array (w_Qtde_Peri);

Insere os dados
function move(Origem, Destino)
{
   var w_valor = Origem.value;
 if (w_Cont_Qtde <=  w_Qtde_Peri)
    {
    if ((v_patr.indexOf(w_valor) == -1) && (w_valor != ""))
       {
        var opt = document.createElement("option");
        opt.text = w_valor ;
        opt.value = w_valor ;
        Destino.options.add(opt);
        v_patr[w_Cont_Qtde]= w_valor;
        w_Cont_Qtde = w_Cont_Qtde +1;
        return true;
       }
    else
        {
        alert("Patrimônio OU Serial já existe OU não é válido!");
        return true;
        }
   }
 alert("Quantidade informada ja Incluida !!!");
return true;
}

Retira os dados (só está eliminando da box)
function tira(Destino)
{
    var i;
    for(i = 0; i < Destino.options.length; i++)
    {
        if (Destino.options[i].selected && Destino.options[i].value != "")
        {
            w_valor=Destino.options[i].value;
            w_Cont_Qtde = w_Cont_Qtde - 1;
            Destino.remove(Destino.selectedIndex);
        }
    }
}

Meu problema é: "Eliminar o dado selecionado do array também, pois da box ele já elimina."
Answer: você pode remover itens de um array em javascript utilizando o método splice, você informa no primeiro parametro o índice do item e no segundo parametro a quantidade de itens a remover.

Editado (Exemplo de Utilização)
meuArray.splice(meuArray.indexOf(meuValor), 1);

ou seja, ele irá pegar o índice do item a remover do array e irá passar no primeiro parâmetro, e ele irá remover 1 item após este índice (2º parâmetro)
Comment: da mais preferência para a documentação do mozilla dev https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Comment: Obrigado Willian, para as futuras respostas irei utilizar a documentação da Mozilla.
Comment: @dennis90 se fosse para aplicar seria como?

Eliminar dado selecionado do array


How to find primes between $p$ and $p^2$ where $p$ is arbitrary prime number?

Question: What is the most efficient algorithm for finding prime numbers which belongs to the  interval $(p,p^2)$ , where $p$ is some arbitrary prime number? I have heard for Sieve of Atkin but is there some better way for such specific case which I described?
Comment: That's probably no easier than simply finding all primes below $p^2$.
Comment: Since the primes become (somewhat) sparser as you go, you're probably going to focus on a small interval $[p,p+O(\log p)]$ anyway. So I'm not sure that having such a big range at your disposal is of any help.
Comment: @GerryMyerson,all primes...
Comment: Do you want to find *all* the primes between $p$ and $p^2$? or just one or two? or do you just want to know how many there are?
Comment: I doubt you'll find an algorithm that requires $p$ to be prime.  Is there reason to suspect that the set of primes between $n$ and $n^2$ has some nice property when $n$ is prime that isn't true when $n$ is not prime?
Comment: @ThomasAndrews,Each prime number that is greater than $p$ and less than $p^2$ can be represented as sum of prime powers with bases less or equal to $p$ so that is reason of such boundaries...
Comment: @pedja, that's a very incomplete statement.  How many prime powers?  I don't see that as remotely useful for actually finding such primes, given $p$.
Comment: @ThomasAndrews,number of prime powers =( number of primes less or equal to p )- 1,where exponents are nonnegative integers and coefficients are equal to 1.Such sum can produce any prime number greater than $p$ and less than $p^2$.
Comment: Every positive natural number can be written as the sum of distinct powers of 2, so I don't see how your statement is useful.
Answer: This is essentially the same as asking for the primes below x for arbitrary x.
There are essentially only two practical sieves for the task: Eratosthenes and Atkin-Bernstein. Practically, the sieve of Eratosthenes is fastest; the Atkin-Bernstein sieve might overtake it eventually but I do not know of any implementations that are efficient for large numbers.
Unless your range is very small, it will not fit in memory.  In that case it is critical to use a segmented sieve; both Eratosthenes and Atkin-Bernstein do this naturally.
If you're looking for an existing program, try yafu, primesieve, or primegen.  The first two are modified sieves of Eratosthenes and the last is an Atkin-Bernstein implementation, though efficient only to $2^{32}$ (or p = 65521 in your case).


Is there a rule of thumb on the relationship between the number of instances and the number of features?

Question: If we build a classifier based on a very small number of instances (say, fewer than 300) and the number of features we are using is very large (say, larger than 100k features). If we decide to introduce a feature selection step before building the classifier, is there a rule of thumb on how many features we should choose?
Comment: I would think this problem is too data specific for there to be any rule of thumb.
Answer: It depends on the type of your target variable. Frank Harrell gives some guidelines in his book, "Regression Modeling Strategies". You can find the discussion here (page 61):
Regression Modeling Strategies


Continuous JavaScript Scroller

Question: Continuous JavaScript Scroller
I have below script which is working on next and previous click. There are about 1 to 3 div for which I have added this JavaScript to flow from left to right and vice versa upon the next and previous button action.
I want to make it continuous scrolling. After third div scroller should again navigate to first div. It should not go in a reverse direction. Flow should be continuous again and again.
Please advise on the solution to achieve this.

js
window.onload=init;

function init(){

var arrowLeft=document.querySelector('.arrowLeft');
var arrowRight=document.querySelector('.arrowRight');
arrowRight.addEventListener('click',slideRight,false);
arrowLeft.addEventListener('click',slideLeft,false);

  var flag=1;
  function slideRight(){
    if(flag<3){
    flag++;
    arrowLeft_div.innerHTML="";
    var slider=document.querySelector('.slider');
    slider.style.webkitTransform+='translate(-1024px, 0px)';
   }
    if(flag==3){
    arrowRight_div.innerHTML="";
   }
}

  function slideLeft(){
    if(flag>1){
    flag--;
    arrowRight_div.innerHTML="";
    var slider=document.querySelector('.slider');
    slider.style.webkitTransform+='translate(1024px, 0px)';
   }
   if(flag==1){
   arrowLeft_div.innerHTML="";

  }
 }

}

Comment: What is your question exactly?
Comment: I want to create continuous slider. Suppose, there are three div, one after another.

When hitting on next, it will take to 2 second div, then another hit will take to third div. any click after this on next button, I should able to see 1st div again. Looping the three divs. Like 1,2 then 3 then 1, 2 then 3 repeated process.

The above code work fine till I reached third div, after that I disabled the next click.

But here I want to keep the next button active and want to show 1st div again upon the next click. It should look continuous processes.
Comment: i just added html code as well, just to make every thing clear. Hope this will help.
Comment: please note, code is developed specifically for Ipad.
Comment: @user - How long is the duration of the animation?
Comment: i controlling duration from webkit css. duration is one sec                                                                                here is the code for reference.                                                                                .slider{width:3072px; height:768px; float:left; position:absolute; left:0px; top:0px; -webkit-transition:all 1.0s ease-in-out;
}
Comment: @user - It would be very helpful if you would create a working example using [jsFiddle](http://jsfiddle.net/).
Comment: actually it is very wonderful, but with jquery i am getting some problem in ipad and iphone. That why dont want to use frame works. It would be great if i could do this with out framework
Comment: @user - I'm not talking about using a framework. I mean use jsFiddle to create a working example of your code that we can test. At jsFiddle, you can use the menus on the left to select "No Library" mode. Then create a working example of the code you have so far, click "Save" at the top, and post the link here.
Comment: please find the url. Thanks a lot for the support          http://jsfiddle.net/q9MDx/
Comment: this will specifically run on webkit browser. Chrome and safari.
Answer: Something like this?
var flag=1;
function slideRight(){
    if(flag<3){
    flag++;
    arrowLeft_div.innerHTML="";
    var slider=document.querySelector('.slider');
    slider.style.webkitTransform+='translate(-1024px, 0px)';
}
    if(flag==3){
    arrowLeft_div.innerHTML="";
    var slider=document.querySelector('.slider');
    slider.style.webkitTransform+='translate(2048px, 0px)';
    flag = 1;
}

Comment: actually this script take the slide back to reversed position, but i want to move the div in a continuous direction.  similar to below like. http://cssglobe.com/lab/easyslider1.7/01.html
Comment: Oh. Well then I don't know :)

Continuous JavaScript Scroller


Use a custom template field even if it's excluded from display

Question: In a Views, I have two field :

Link field : With 1 to n links to display (excluded from display)
Body field : Who use the previous link field (via rewrite output and token)

I have created a custom template for display link field like I want.
Here is my problem:
When I render my Views, my custom template isn't used for display my links...
He use the display function defined in the link field settings.
Is there a way to force View to use my template ?
Any suggestions to do this?
Edit : Some screenshot of fields and theme informations
Link field :

Body field :

Theme Infos :
Comment: I'm trying to solve the same problem.  What was your solution? It seems fields used as replacement patterns simply cannot be themed.
Answer: To use the custom template for a particular field you should use the template suggestion from Theme:Information from advance section of your view, Select the suggestion template form the them info as the screenshot for field NID
 . Create that template inside the your_theme/template folder. Don't forgot to clear the drupal cache.
Comment: Thank for your answer but I have already do this solution. Maybe my post is not clear on that point but I have a custom template acccording Theme:Information infos.

I have clean my cache many times... But the problem stay...

Use a custom template on a hidden field seems doesn't work.
Comment: if it is hidden then why you want to theme that, i unable to understand in this point.
Comment: Because I use it in an other field where I rewrite output using this field with a token.
Comment: so you should theme that another field than only it will effect...debug the $output or available templete variables to theme your field
Answer: If you make this field the displayed field it will take the theme adjustments. Do your rewrite and replacement patters on this field, put it at the end of the field list and exclude the others.  If this field is used as a replacement pattern the theme will not be applied.