Diferença entre função construtora e função que retorna objeto literal

Question: Qual a diferença prática entre eu criar uma função construtora desta forma:
function construtora (nome, sobrenome) {
    this.nome = nome
    this.sobrenome = sobrenome
}

Ou desta forma:
function construtora (nome, sobrenome) {
    let obj = {}

    obj.nome = nome
    obj.sobrenom = sobrenome

    return obj
}

Comment: Isto responde à sua pergunta? [Qual é a diferença entre criar um objeto a partir da forma literal ou a partir de uma função construtora?](https://pt.stackoverflow.com/questions/445939/qual-%c3%a9-a-diferen%c3%a7a-entre-criar-um-objeto-a-partir-da-forma-literal-ou-a-partir-d)
Answer: No seu primeiro exemplo, você têm uma função que funciona como construtura (constructor function), que retorna uma nova instância de objeto se você chamá-la utilizando o operador new. Assim:

function construtora(nome, sobrenome) {
  this.nome = nome;
  this.sobrenome = sobrenome;
}

const instance = new construtora('John', 'Doe');
console.log(instance);

Como você não especificou na resposta se está usando o new ou não, acho pertinente falar que se você simplesmente invocar a função, sem utilizar o operador new, um objeto não será retornado. A chamada simplesmente retornará undefined:

function construtora(nome, sobrenome) {
  this.nome = nome;
  this.sobrenome = sobrenome;
}

const instance = construtora('John', 'Doe');
console.log(instance); // undefined

A partir do ECMAScript 2015 (vulgo ES6), esse padrão "prototípico" clássico para atingir um certo tipo de "orientação a objetos" no JavaScript foi sendo menos usado, uma vez que a construção class foi introduzida. Mas não se engane, pois class não passa de mero açúcar sintático para essa antiga abordagem prototípica.

Já no seu segundo exemplo, não diria que a função (construtora) é, de fato, uma função construtora. Você está criando um tipo de função fábrica (factory function), por que você cria um objeto literal e o retorna. Vale dizer que nos dois casos um objeto está sendo criado, mas há uma sutil diferença a qual eu entro em mais detalhes nesta outra resposta.
De forma resumida (leia a pergunta referida para saber mais), nesse segundo exemplo, você está criando um objeto literal (o que não é o caso no primeiro exemplo). Desse modo, se você verificar, a forma como os objetos foram construídas é diferente e, nesse caso, os construtores também. Veja:

function construtora1(nome, sobrenome) {
  this.nome = nome;
  this.sobrenome = sobrenome;
}

function construtora2(nome, sobrenome) {
  let obj = {};
  obj.nome = nome;
  obj.sobrenom = sobrenome;
  return obj;
}

const instance = new construtora1('John', 'Doe');
const obj = construtora2('Luiz', 'Felipe');

console.log(instance);
console.log(obj);

console.log(instance.constructor.name); // "construtora1"
console.log(obj.constructor.name); // "Object"

Note que, apesar das propriedade próprias (own properties) dos objetos instance e obj serem as mesmas, os construtores são diferentes, o que também indica uma diferente cadeia de protótipos.

A título de preferência, eu pessoalmente considero o nome da função do primeiro exemplo construtora correto, já que a função está construindo um objeto (contrutora é o construtor do objeto se este tiver sido criado através do operador new).
No entanto, o nome da função (construtora) do segundo exemplo não me parece tão preciso, já que não é a função (construtora) que constrói o objeto, mas sim Object. Vale lembrar que, internamente, quando você cria objetos literais, eles são construídos a partir de Object.
Do ponto e vista semântico e interno da linguagem, há a diferença de que, quando se chama uma função sem o operador new, a propriedade interna [[Call]] é invocada. Quando a função é chamada utilizando o operador new, a propriedade interna [[Construct]] é chamada. Consulte esta tabela para saber mais.
A própria especificação (na tabela referida) refere-se às funções que implementam [[Call]] como "callable" e às funções que implementam [[Construct]] como "constructors". Vale salientar que toda constructor function é, também, callable.

Não tem a ver com a pergunta, mas note que coloquei ponto e vírgula no final de cada statement. Pode parecer "frescura", mas criei esse hábito para evitar algumas situações bizarras que podem ocorrer se você não utilizar o ponto e vírgula em todas as linhas (veja mais sobre o assunto aqui).


Migrating a PhoneGap iOS app to Android - experiencing terrible performance issues

Question: We have been working for several months on a fairly substantial iOS app using PhoneGap 1.8.1 and Kendo UI from Telerik. I would say the iOS app is about 90% as fast as its native equivalent which is perfectly acceptable for us. We took the same exact codebase and substituted in the Android equivalent javascript files, booted up our device (Motorola Xoom running 4.0.3), and performance is just awful. The worst of it is the page transitions - which should take maybe 0.3 seconds - take 2-5 seconds. Performance is same if not worse on the emulators (no surprise there).
If there is helpful code I could post, please let me know. Otherwise I guess we are looking for other people who have run into this situation and/or suggestions for performance improvements. At this point PhoneGap is a complete non-starter for Android development for us.
Answer: We do some cross-platform mobile development using Sencha Touch 2 (no experience with Kendo UI).  The last time I looked into performance in detail, Sencha Touch 2 was the best performing of the full-featured/mature cross-platform mobile frameworks (Jquery Mobile, Kendo UI, etc.).  Our experience is that the performance on Android is considerably slower than iOS (even though Sencha Touch 2 is considered kinda fast).  Scrolling lists, screen transitions, etc. are all sub-par.  I was rather astounded at the performance difference.  The Android performance is better on my Galaxy Nexus running 4.0, but still noticeably slower than iOS devices.
Unfortunately, I don't see a way for you to get your apps to perform the same on Android as on iOS.  This is the unfortunate reality that I came to a while back.  The issue you're seeing is due to performance of the browsers on the different platforms; phonegap just uses UIWebView and WebView to load the html and javascript pages inside a native app wrapper.  Can you load the Kendo UI app in the browser on the devices?  I'm assuming the performance would be the same as the native-wrapped apps.
Our "solution" has been to develop for Android first and get the apps to a point where they perform decently.  Then we know they'll be great on iOS devices.
I'm not very familiar with Kendo UI, but as far as recommendations or tweaks, we try to keep as little in the DOM as possible.  When the app starts, we create as little in the DOM as possible, then create/destroy objects as the app needs them.  Also, just general optimization of the javascript helps.
I think this is a dirty little secret of these mobile frameworks.  When you approach them about it, their answer is that the Android browser performance is slow, so the apps are going to be slow.  I.e. "not our fault", yet they continue to portray a framework that works great on all platforms.
For us, Sencha Touch 2 is fast enough where it gives our users a decent experience on Android devices, so it's worth the enormous time savings vs. developing natives apps for each platform.
Just to clarify, the performance issue you're seeing likely has nothing to do with PhoneGap, it's the browser performance on the devices.  PhoneGap essentially just wraps a WebView in a native app wrapper.  We have seen the performance issues on Android when using both PhoneGap and the Sencha Touch native packaging.


How many boundary values determine an automorphism of unit disk?

Question: How many boundary values are needed to uniquely determine an automorphism of unit disk?
More precisely, find the $n \in \mathbb{N} $ such that for any two sets $ \{ x_1, x_2, ..., x_n \} $ and $ \{ y_1, y_2, ..., y_n \} $ of $n$ distinct points on $ \mathbb{S}^1 $, there exists a unique automorphism $ f: \mathbb{D} \rightarrow \mathbb{D} $ with $ f(x_i) = y_i $ for all $i$.
Clearly, $n=2$ is not enough: there are many automorphisms $ \mathbb{D} \rightarrow \mathbb{D} $ fixing the two points $1$ and $-1$ on $ \mathbb{S}^1 $.
My guess is $n=3$, since any automorphism $ \mathbb{D} \rightarrow \mathbb{D} $ is of the form $ f_{e^{i\theta},a} (z) = e^{i\theta} \frac{z-a}{1-\bar{a}z} $, where $ (e^{i\theta},a) \in \mathbb{S}^1 \times \mathbb{D} $. The dimension of the parameter space $ \mathbb{S}^1 \times \mathbb{D} $ suggests that we need three boundary values.
However, when I plug in $ f_{e^{i\theta},a} (x_i) = y_i, $ $ i=1,2,3 $, I can't solve $ (e^{i\theta},a) $ explicitly in terms of $x_i$ and $y_i$. Any suggestion?
Comment: Note that you should be a little bit more precise about what domain you're looking for an automorphism in - from your context it's clear that you want complex analytic functions, but the question makes perfect sense if you consider $f: \mathbb{R}^2\mapsto\mathbb{R}^2$ instead of $f:\mathbb{C}\mapsto\mathbb{C}$ (in which case the answer is that there are still many such functions even with the entire boundary fixed).
Answer: I realize I am perhaps a little late to answer this question, but I was wondering about the same thing and it took me quite some time to figure it out. So I hope other people might find this solution in the future.
I find the question easier to answer in the upper half plane model $\mathbb{H}$. Using for example
$$
\phi\colon \mathbb{D} \rightarrow \mathbb{H}, z \mapsto \frac{z-i}{1-iz}
$$
and extending it to $\partial \mathbb{D}$, we see that $\phi(\partial \mathbb{D}) = \mathbb{R} \cup \{\infty\}$ holds.
Furthermore you can check that the automorphism group of $\mathbb{H}$ is given by $\operatorname{PSL}(2,\mathbb{R})$.
What we want to prove next is, that given any two triplebs of boundary points of $\mathbb{H}$ (i.e. $\mathbb{R} \cup \{\infty\}$), we find a unique element in the automorphism group of $\mathbb{H}$ converting the one into the other.
To see that we consider the complex cross-ratio given by
$$
(z; z_1, z_2, z_3) \mapsto \frac{(z - z_2)(z_1 -z_3)}{(z_1 - z_2)(z - z_3)},
$$
where we kill a term, if one of the variables is $\infty$ and the $z_i$ are distinct and fixed. Then we get a Möbius transformation which we denote by $\phi$. We see the following:
$$
\phi(z_1) = 1, \quad \phi(z_2) = 0 \text{ and } \phi(z_3) = \infty.
$$
From that we get the following observation: if the $z_i$ are in $\mathbb{R} \cup \infty$, then $\phi$ is represented by a real matrix and we can find a representative in $\operatorname{PSL}(2, \mathbb{R})$. So we can map any $\mathbb{H}$ boundary triple to the triple $(1,0, \infty)$, which is also a $\mathbb{H}$ boundary triple. Concatenation with an inverse of another cross-ratio yields our assertion.
The uniqueness of the tranfsormation is given by the fact, that any Möbius transformation is uniquely determined by three points (which is actually a consequence of the cross-ratio, we used).
Now, going back to $\mathbb{D}$, we get that any automorphism of it, is uniquely determined by three boundary values.
Answer: Your guess based on dimension is correct.
To come up with a proof, it helps to recognize that your formula for an automorphism of the disc generalizes to the concept of a fractional linear transformation
$$T(z) = \frac{az+b}{cz+d}
$$
where $a,b,c,d \in \mathbb{C}$ and $ad-bc \ne 0$. Furthermore, after a normalization you may assume $ad-bc=1$. Normalized fractional linear transformations form a group under composition; this group is isomorphic to $SL(2,\mathbb{C})$.
Just to put this in context, each normalized fractional linear transformation is an automorphism of the entire Riemann sphere $\mathbb{C} \cup \{\infty\}$, and these are exactly all of the automorphisms of $\mathbb{C} \cup \{\infty\}$, so every automorphism of $\mathbb{D}$ extends to the whole of $\mathbb{C} \cup \{\infty\}$. Thus, if you know something about automorphisms of $\mathbb{C} \cup \{\infty\}$ then perhaps you can apply it to gain knowledge about automorphisms of $\mathbb{D}$.
The uniqueness property you want then follows from a lemma which says that for any two triples of distinct points $z_1,z_2,z_3$ and $w_1,w_2,w_3$ in $\mathbb{C} \cup \{\infty\}$ (assuming the three $z$'s are all different, as are the three $w$'s) there exists a unique normalized fractional linear transformation $T$ such that $w_1 = T(z_1)$, $w_2 = T(z_2)$, $w_3 = T(z_3)$. It is easiest to prove this lemma first in a special case $w_1=0$, $w_2=1$, $w_3=\infty$, and then use that to prove the general case.


JSONP post data to other domain

Question: I have tried to find the answer to this by searching for a while now but I'm not finding what I need.
So I have these input boxes.

  Kontaktuppgifter

  <input class="double" type="text" name="customer_firstName" placeholder="Förnamn" />
  <input class="double" type="text" name="customer_surName" placeholder="Efternamn" />
  <input class="double" type="email" name="customer_email" placeholder="Epost" />
  <input class="double" type="tel" name="customer_cellnr" placeholder="Mobilnummer" />

  Adressuppgifter

  <input type="text" name="customer_adress" placeholder="BostadsAdress" />
  <input type="text" name="customer_zipcode" placeholder="{{postal_code_label}}" />
  <input type="text" name="customer_city" placeholder="Ort" />
  <input type="text" name="customer_country" placeholder="Land" />

  Garantispecifika uppgfiter

  <input type="text" name="customer_housenr" placeholder="Fastighetsbeteckning" />
  <input type="text" name="customer_persnumber" placeholder="Personnummer" />

  Företagsspecifika uppgifter - Fylls bara i av företag

  <input type="text" name="customer_companyName" placeholder="Företagsnamn" />
  <input type="text" name="customer_Orgnr" placeholder="Organisationsnummer" />
  <input id="send_message" class="button secondary" type="submit" value="Registrera Garanti" onclick="postFrom(this)"/>

Now I want to send all data via JSONP.
I got it to work with one, attribute 'customer_name=json'
How should I concatenate everything to I can send it to my handler?
Is data: the only tag i can use or how should I structure the call?
$.ajax({
   type: 'GET',
   url: 'http://www.mypage.com/offerthandler.ashx',
   crossDomain: true,
   data: 'customer_name=json',
   dataType: 'jsonp',
   success: function(responseData, jsonobj) {
   alert('POST Successfull.');

},
error: function (responseData, textStatus, errorThrown) {
    alert('POST failed.');
}
 });

Should I go for a
 data: 'customer_firstName=$('[name="customer_firstName"]').val() +
        customer_surName=$('[name="customer_surName"]').val()

and so on or how am I to do this?
Answer: An easy way to do this would be so insert  tags give the form an id and serialize the form.
Example
 <form id="myform">

 Kontaktuppgifter

 <input class="double" type="text" name="customer_firstName" placeholder="Förnamn" />
 <input class="double" type="text" name="customer_surName" placeholder="Efternamn" />
 <input class="double" type="email" name="customer_email" placeholder="Epost" />
 <input class="double" type="tel" name="customer_cellnr" placeholder="Mobilnummer" />
 </from>

And now javascript!
   var datavariable = $("#myform").serialize();

$.ajax({
type: 'GET',
url: 'http://yoururl.com',
crossDomain: true,
data: datavariable ,
dataType: 'jsonp',
success: function(responseData, jsonobj) {
    alert('POST Successfull.');

},

JSONP post data to other domain


Difficulties with MapReduce on Ruby Mongoid

Question: I'm having difficulty creating a MapReduce function in Ruby with MongoDB and mongoid. I'm using the Ruby and MongoDB Web Development Guide, and the content doesn't seem to be written for Mongoid (even though it was written post-rails 3.2).
Here is a sample JSON document:
> db.books.find()
{ "_id" : ObjectId("50ceb8551d41c8ade7000041"),
"author_id" : ObjectId("50ceb72c1d41c8ade700003d"),
"category_ids" : [ ], "name" : "Great Expectations",
"votes" : [
  {     "username" : "Gautam",  "rating" : 9 },
  {     "username" : "Tom",     "rating" : 3 },
  {     "username" : "Dick",    "rating" : 7 }
]
}

Anyway, I'm having trouble with the mongoid MapReduce. I can run this fine in MongoDB:
> var reduce = function(key, values) {
  var result = {rating: 0};
  values.forEach(function(value) {
    result.rating += value.rating;
  });
  return result;
  };
> var map = function() {
  this.votes.forEach(function(x) {
    emit(x.username, {rating: x.rating});
  });
  };
> var results = db.books.mapReduce(map, reduce, {out: "mr_results"});
> results
{
    "result" : "mr_results",
    "timeMillis" : 28,
    "counts" : {
        "input" : 2,
        "emit" : 6,
        "reduce" : 3,
        "output" : 3
    },
    "ok" : 1,
}
> results.find()
{ "_id" : "Dick", "value" : { "rating" : 10 } }
{ "_id" : "Gautam", "value" : { "rating" : 15 } }
{ "_id" : "Tom", "value" : { "rating" : 10 } }

But when I run the following in the Rails Console, I get this:
1.9.3-p327 :292 > map = "function() {
1.9.3-p327 :293"> this.votes.forEach(function(x) {
1.9.3-p327 :294"> emit(x.username, {x.rating});
1.9.3-p327 :295"> });
1.9.3-p327 :296"> }
1.9.3-p327 :297"> "
 => "function() {\nthis.votes.forEach(function(x) {\nemit(x.username, {x.rating});\n});\n}\n"
1.9.3-p327 :298 > reduce = "function(key, values) {
1.9.3-p327 :299"> var result = {rating: 0};
1.9.3-p327 :300"> values.forEach(function(value) {
1.9.3-p327 :301"> result.rating += value.rating;
1.9.3-p327 :302"> });
1.9.3-p327 :303"> return result;
1.9.3-p327 :304"> }
1.9.3-p327 :305"> "
 => "function(key, values) {\nvar result = {rating: 0};\nvalues.forEach(function(value) {\nresult.rating += value.rating;\n});\nreturn result;\n}\n"
1.9.3-p327 :306 > results = Book.where(votes: 1).map_reduce(map,reduce).out(inline: 1)
 => #<Mongoid::Contextual::MapReduce
  selector: {"votes"=>1}
  class:    Book
  map:      function() {
this.votes.forEach(function(x) {
emit(x.username, {x.rating});
});
}

  reduce:   function(key, values) {
var result = {rating: 0};
values.forEach(function(value) {
result.rating += value.rating;
});
return result;
}

  finalize:
  out:      {:inline=>1}>

1.9.3-p327 :307 > results.find()
 => #<Enumerator: #<Mongoid::Contextual::MapReduce
  selector: {"votes"=>1}
  class:    Book
  map:      function() {
this.votes.forEach(function(x) {
emit(x.username, {x.rating});
});
}

  reduce:   function(key, values) {
var result = {rating: 0};
values.forEach(function(value) {
result.rating += value.rating;
});
return result;
}

  finalize:
  out:      {:inline=>1}>
:find>

Or, if I change the out result to "mr_results" this is what happens:
1.9.3-p327 :383 > results = Book.map_reduce(map,reduce).out("mr_results")
NoMethodError: undefined method `update_values' for "mr_results":String
        from /home/BSP/.rvm/gems/ruby-1.9.3-p327/gems/mongoid-3.0.14/lib/mongoid/contextual/map_reduce.rb:134:in `out'
        from (irb):383
        from /home/BSP/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.9/lib/rails/commands/console.rb:47:in `start'
        from /home/BSP/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.9/lib/rails/commands/console.rb:8:in `start'
        from /home/BSP/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.9/lib/rails/commands.rb:41:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `'

How can I make this output the expected results from the book votes?
Answer: The out function expects a Hash, not a string:
results = Book.map_reduce(map,reduce).out(:replace => "mr_results")

Comment: Yes - @robbrit is right. you need to use replace: "mr_results" to get the same results as in the book. Mongoid 3.0 was released a few weeks after my book was released, so the syntax changed a bit.
Comment: Thanks! After seeing this and finding that Mongoid is "lazily evaluated" I am able to return what I need to see with results.find().to_a or results.find().entries, where Mongo does not require that method appended.


Is the elbow in the forehand tennis strike meant to be totally direct or little bit in angle?

Question: I played my first serious match against a player in tennis who strikes over 200km/h. I got a little feeling of pain to my elbow when I passed balls back with a little angle in the elbow. Later I changed my elbow to totally direct the point when I hit the ball so I experienced no pain anymore. I asked my experienced friend about this pain and he said that the pain may be due to poor technique and I should still continue with my old angular forehand strike and improve swing of the whole body. I am uncertain about this so:

During the time of hit in the forehand strike, is the elbow meant to be angular or direct?
Answer: No, your elbow should absolutely not be locked when you make contact with the ball. Your arm should be nearly straight but with a slight bend at the point of contact, never completely locked. This will allow for your arm to move fluidly through the stroke and will enable you to brush up on the ball, creating topspin. You can see in this video that Federer's arm is almost straight, but his elbow is not locked when he makes contact with the ball, which allows his arm to turn over after contact (this motion makes the racquet move up as well as through the ball, creating topspin).
The pain you are feeling is most likely tennis elbow, which is a strain in the tendons in your elbow from overuse. In other words, your body simply isn't used to hitting balls that are coming at you with such high speeds, causing strain. Locking your elbow, however, brings your joint against your bones, so when you hit the ball, instead of relying on your muscles and tendons for structural support, the impact is going straight to your bones and elbow joint. Repeated impacts will wear down the cartilage in your elbow joint. Instead, keep a slight bend in your elbow at contact and strengthen your muscles. As far as the pain goes, there are plenty of braces out there to help with tennis elbow, but the Band It is the one that has given me the best results. Other than that, rest and ice your elbow and it should start to feel better.
Source: I've been playing tennis since I could barely walk, and playing competitively since middle school. I used to teach classes with students ages 5-16 at a private club.
Comment: Tennis elbow shows up on the backhand, not on the forehand. It's an injury to the tendon that extends the middle finger, which is not being extended on the forehand.
Answer: At the point when you are making contact with the ball, your arm should be straight with your elbow locked. Your wrist is what generally moves or 'rolls over' as you swing the racquet to hit the ball. Your elbow should only bend after contact during your follow-through. See this video of Roger hitting forehands to see what I mean.
https://www.youtube.com/watch?v=el_y4QqIpNY#t=59
Comment: Yes, that's what I said. At the point when your strings meet the ball (contact) your arm should be straight, not bent. It may only be straight like that for a very short moment, but it should be straight. It's your shoulders and hips that rotate and bring your arm through the hitting zone - not your arm itself.
Comment: It is very hard to see this thing in videos but the locked during the hit feels correct way of doing it -- I get far more accurate shots and no pain. Hitting the ball with even a small angle causes a little shock to the elbow which irritates the joint.
Comment: I found this explanation useful [here](https://www.youtube.com/watch?v=-QDWF6pmf0M&feature=youtube_gdata_player), it tries to explain that the arm need to be aligned well before the strike so that the shot is in front of your body. If it is not well aligned, then arm may not have enough time to get aligned to the proper position.


How to build and organize menus with rich taxonomies and complex view-based menus

Question: I would like to hear your insights about strategies on organizing menus. I mean two main approaches: having each menu header as an individual Drupal menu vs. having all menus grouped as one big menu, perhaps named "Main menu".
I built quite a large site where I had to use such modules as OM Maximenu, Taxonomy menu/Taxonomy menu trails, Menu Block, Sitemap, DHTML Menu. Without much knowledge about Drupal and the consequences of my choice, just to keep my progress on, I took my liberty to sometimes put a group of menu items as individual menus, sometimes I grouped them together (this was the case of Taxonomy menu and Menu Block where I could define the level at which menu starts).
Then, when I installed Sitemap I saw that my menu organization revealed to public. This was also a lesson.
Although everything works OK, I don't feel alright with this kind of mess. Especially, after some time I know I will have to do a repetitive research on how a particular menu is built, rather than have it intuitively solved right away.
My question: What is your preferred way to build and organize menus with rich taxonomies and complex view-based menus (OM Maximenu)?
Answer: Typically, we put all of the site sections in the main menu.
Each site section will get its own Drupal menu.  How items get into menus varies widely project-to-project, but we will rely on path-alias define section organization as much as possible.
Each section will have its own Panels pages, where the site section gets used as the context / selection rule (typically by path matching), and the menu is placed in a content area.
Occasionally, we will have a site section taxonomy, which gets used inside a custom block to display the proper menu.


Sorting an array in c is deleting values

Question: I am programming a genetic algorithm so that this solves problems of linear programming, I am using C language, when I calculate the limit of the variables I keep the values in a float type array, I need to order that array but it deletes a data that I need to moment of ordering: I have used a shell_sort pogramed by me and the qsort that is implemented in the standard librarian and with both gives me the same result, I append the code of the algorithm that I use to order and the comparator function that I use for the qsort () :
    void shell_sort(float *A, int n){
    int gap = n/2;  //Se obtiene el gap dividiendo el tamaño de arreglo entre dos
    int inner, outer, swap; //Variables auxiliares

    while (gap > 0) { //Mientras gap sea mayor que zero entonces:
        for(outer = gap; outer < n; outer++){ // Para outer igual a gap, siempre que outer sea menor a n, outer aumentara su valor en uno
            inner = outer; // inner se iguala al valor de outer
            swap = A[inner]; // Swap se iguala a la posiscion inner de A
            while (inner > gap - 1 && A[inner - gap] > swap ) {  // Mientras inner sea mayor que gap menos 1 y que A en su posicion inner menos gap sea mayor a Swap
                A[inner] = A[inner - gap]; //La posicion inner de A tomara como nuevo valor la posicion inner menos  gap de A
                inner -= gap; //inner decrementa su valor en gap veces
            }
            A[inner] = swap; //La posicion inner de A tomo como nuevo valor swap
        }
        gap /=2; // se divide a gap entre dos
    }
}

Comparer function:
int comp(const void * a, const void * b){
    if(*(float*)a < *(float*)b) return -1;
    if(*(float*)a == *(float*)b) return 0;
    if(*(float*)a > *(float*)b) return 1;
}

Output:
Output
I think when I sort the array the result will be 0,26,37 but the result is 26,37 and I need that zero I don't really know why is this happen.
Hope someone can help me.
This is the piece of code when I use the sorting.
    Limites obtenerValoresLimites(lista *l,char var){
        //This code works
Limites lim;
        restriccion r;
        int i,j;
        float *aux = (float*)malloc(sizeof(float));
        for (i = 0; i < Size(l); i++)
        {
            r = Element(l,i+1);
            for (j = 0; j < strlen(r.variables); j++)
            {
                if(r.variables[j] == var){
                    aux[i] = (r.limite/r.coeficientes[j]);
                    }
            }
        }
    //First print of the output that confirms the zero originally exist

        //for (i = 0; i < sizeof(aux)/sizeof(*aux) ;i++)
            //printf("%f\n",aux[i]);

    //Sorting
        //qsort(aux,sizeof(aux)/sizeof(*aux)+1,sizeof(float),comp);
        shell_sort(aux,sizeof(aux)/sizeof(*aux));

        //printf("\n");
    //Second print of the output now the zero is no longer in the array
        //for (i = 0; i < sizeof(aux)/sizeof(*aux) ;i++)
        //{
        //  printf("%f\n",aux[i]);
        //}

        lim.inferior = 0;
        lim.superior = aux[(sizeof(aux)/sizeof(*aux))-1];
        lim.variable = var;

        return lim;
    }

Thanks for answer and read.
I think the code is a little bit difficult to read, its because we are using some data structures to modelete the problem so if you are interested in we leave the gitHub repo below.
Complete code if you are interesed in: https://github.com/JoelRomero97/Metodos-Cuantitativos.git
Comment: Time to [learn how to debug your program](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Also please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), and learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve).
Comment: If you say that your sort and qsort of the standard library both return the same result, then I think the problem is somewhere else, perhaps you think you have a 0 in your array, or you are passing the incorrect size to both sort functions. Show us how you call the sort functions. Better still post a [mcve]
Comment: @Pable, either that or he is saying `qsort` is broken too...
Comment: @DavidC.Rankin yes, I know, but the likelihood that `qsort` is broken and not the OP's code, is very very small. It is not as if `qsort` was written yesterday by the friend of the maintainer of the the glibc (or any other well tested libc implementation). Funny note: when I was a beginner, I often though that I had found a bug in the libc, because some standard function didn't work as expected and it was always me who just used it incorrectly.
Comment: @Pablo In my school student from first year was yelling at me (I was a assistant) because `read()` was "bugged" ;) I still laugh when I see them even after 4 years. They keep saying that for 6 hours before finally understand the behavior of `read()` ;) The real fun was keep saying "read the man you miss a vital information". the bug was "read do not read n byte as I request but less" they was reading standard input...
Answer: Like I suspected, the problem is in how you call the sorting function.
shell_sort(aux,sizeof(aux)/sizeof(*aux));

The sizeof(aux)/sizeof(*aux) construct works only for pure arrays, not for pointers (and also not for pointers that point to allocated memory).
When you allocate memory with malloc & friends, you know beforehand the size,
store it in a variable and use that variable for when you call the sorting
function or any other function that expects the size of the array.
Because sizeof(aux)/sizeof(*aux) is wrong, your are accessing memory beyond the limits, so this yields undefined behaviour.
And that is also true before you even call the sorting function. You are are
doing
aux[i] = (r.limite/r.coeficientes[j]);

for values of i larger than 1 (assuming that Size(l) is larger than 1).
You have to allocate the proper amount of memory, base on your code, I presume
you need Size(l) spaces. So the correct allocation should be
size_t len = Size(l);
float *aux = malloc(len * sizeof *aux);
if(aux == NULL)
{
    fprintf(stderr, "Not enough memory\n");
    return SOME_ERROR_VALUE;
}

for (i = 0; i < len; i++)
{
    ...
}

shell_sort(aux, len);

...

lim.inferior = 0;
lim.superior = aux[len-1];
lim.variable = var;

Also, don't cast malloc
Comment: "pure arrays" XD
Comment: @Stargateur I use the word "pure" to emphasize that I mean `int arr[10]`. We often use the term array interchangeably when it comes to talking about contiguous blocks of memory allocations with `malloc`, and that's fine when you know the difference between an array and a pointer.


Attaching an image to a randomly generated number between 1-10?

Question: I'm fairly new to HTML and I'm able to successfully generate the random numbers, but I want to attach an image to a specific number E.G  a card game (11 =jack =12=queen ..etc)
This is what I have
function numbers() {
    var x = Math.floor((Math.random() * 10) + 1);
    var img = document.createElement("img");
    if(x ==1||2||3||4||5||6||7) {
        img.src = "ace.jpg";
    }
    document.getElementById("num").innerHTML = "Rule " + x;
}

Comment: `if(x == 1 || x == 2|| x == 3|| x == 4|| x == 5|| x == 6|| x == 7) {` This would do it, you have to check every single value.
Comment: possible duplicate of [Concise way to compare against multiple values](http://stackoverflow.com/questions/13737091/concise-way-to-compare-against-multiple-values)
Answer: You could use switch...case.
something like
switch(x) {
case 1:
    img.src = "king.jpg";
    break;
case 2:
    img.src = "queen.jpg"
    break;
...
default:
    img.src = "ace.jpg"

}
where the "..." is just replaced by more cases (how many you need).
the default case is run when no other cases match x.
If you were interested in why the break keyword is necessary, information about it can be found in the link i provided. basically

When the JavaScript code interpreter reaches a break keyword, it
  breaks out of the switch block.
This will stop the execution of more code and case testing inside the
  block.

meaning the whole switch(x){...} is a "block" where x is compared to each case. If there is a match, the code there is executed, but if theres nothing telling it to stop, it'll just keep running code! So the break keyword exits the whole block, keeping other cases from running!
Comment: this introduces the `break` keyword, which is hardly intuitive to someone just learning to program (especially combined with the "fall-through" behavior of a `switch`), but it is still the best way to solve this problem, so +1.
Answer: imgArr = ['jack.png', 'queen.png','tree.png','man.png','ace.png','king.png','yellow.png','green.png','black.png','white.png'],
      randomNumber = 0,
      numImgMap = {}; // map between image and random number.

function randomNumberGenerator(){
 return Math.floor((Math.random() * 10) + 1);
}

for(var k = 0; k < 10; k++ ){
   randomNumber = randomNumberGenerator();
   numImgMap[randomNumber] = imgArr[randomNumber];

}
// numImgMap is now your map(object) with random number associated with random images.


How's the seasonal adjusted series calculated in Holt Winters method?

Question: In the text book Forecasting: Principles and Practice in Exponential Smoothing chapter there is this part
*

".. With the additive method, the seasonal component is expressed in
absolute terms in the scale of the observed series, and in the level
equation the series is seasonally adjusted by subtracting the
seasonal component."

I'd like to know what method is used to calculate the seasonal component in order to get the seasonaly adjusted series for the level equation.
Different methods are discussed in the book like: classical decompositon, STL.. but there is no details about how it's done in the Holt-Winters forecasting method.
Answer: All flavors of Exponential Smoothing (Holt-Winters is one special case) work in the same way. You work with fixed smoothing parameters (typically denoted with Greek letters, $\alpha$, $\beta$ and $\gamma$) and different components (e.g., a level components $\ell$, a trend component $b$ and a set of seasonal components $s$).
How you initially set these values is not fixed, there are various methods. You could fix the smoothing parameters irrespective of the data, or estimate them, and/or estimate the initial component values, e.g., using MLE or minimizing some sum of squares.
In any case, once you have the smoothing parameters and the initial components, you walk through your time series and update the components based on the actual observations. Each Exponential Smoothing model will have its own set of updating formulas. On the FPP2 page you linked, it's right under the heading "Holt-Winters' additive method". You first update $\ell_t$ based on the actual observation $y_t$, the relevant seasonal index $s_{t-m}$ from one seasonal cycle back, and the previous level $\ell_{t-1}$ and the previous trend $\b_{t-1}$. Then you update the trend component $b_t$ and finally the seasonal component $s_t$.
When you have thus walked through your time series, you have these component time series. Table 73 actually goes through exactly this exercise. Try recreating it yourself, taking the first four rows as given (these have been estimated by minimizing  the RMSE), and starting the updating at the row for 2005Q1.
If you then want a deseasonalized series, you just subtract $s_t$ from $y_t$.


Access node fields in hook_node_grants

Question: In hook_node_grants() I want to check if user ID is equal to a node's field value, But there is only two arguments: $account and $op
How can I access the node object that is being checked for grants?
Answer: A better approach to this would be to implement hook_node_api that checks the current $user's permissions to the loaded field then does something.
function custom_module_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  //get the current user
  global $user;

  switch ($op) {
    case 'load':
      //do some logic with $node and with the current $user's roles
    break;

    //(optional)add other cases for other operations

    default:
    break;
  }
}

alternatively you can try template_preprocess_node
function theme_name_preprocess_node(&$variables) {
  global $user;
  $node = $variables['node'];

  //do some stuff with $node and $user
}

Comment: Unfortunately these don't allow to prevent a node from listing and denying access to node before loading
Comment: This doesn't solve the problem.  It won't control access to the node.

Access node fields in hook_node_grants


Divisão em URL AMIGAVEL sem criar pasta

Question: Ola, estou cirando um site e começando a trabalhar com URls amigáveis, com essa estrutura consigo realizar o procedimento normalmente e resgatar os valores.
Agora gostaria de criar divisões na URL, por exemplo:
tenho hoje que funciona: site.com/contato e site.com/empresa
mas queria criar tipo: site.com/planos/fibra e site.com/cliente/cadastro.
O 1° exemplo esta funcionando corretamente porem não estou conseguindo aplicar divisões sem usar pastas.
minha estrutura é .htaccess
<code>RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1
</code>
meu index.php
<code> <?php

 $getUrl = strip_tags(trim(filter_input(INPUT_GET, 'url', FILTER_DEFAULT)));
 $setUrl =(empty($getUrl)) ? 'index' : $getUrl;
 $Url = explode('/', $setUrl);

$Url[0] = (!empty($Url[0]) ? $Url[0] : null);
$Url[1] = (!empty($Url[1]) ? $Url[1] : null);
$Url[2] = (!empty($Url[2]) ? $Url[2] : null);

       if (file_exists(REQUIRE_PATH_INC . $Url[0] . '.php')):
            require REQUIRE_PATH_INC . $Url[0] . '.php';
        elseif (file_exists(REQUIRE_PATH_INC . $Url[0] . '/' . $Url[1] . '.php')):
            require REQUIRE_PATH_INC . $Url[0] . '/' . $Url[1] . '.php';
        else:
            require REQUIRE_PATH_INC . '404.php';
        endif;
        ?>
</code>
Answer: Você precisa especificar regras em seu htaccess dessa forma:

RewriteRule  ^contato$        index.php?area=contato [L]

E em seu arquivo index efetuar uma rotina para carregar os dados por área.
Explicando a regra acima: estou dizendo que qualquer url dentro desse dominio começada com contato deve redirecionar para a página index.php passando como argumento da url a variavel GET area.

cliente/cadastro e /planos/fibra

Outros exemplos:

RewriteRule  ^cliente/cadastro$   index.php?area=cadastro_clientes [L]
RewriteRule  ^planos/fibra$       index.php?area=planos [L]

Dentro do seu php é que vai criar um switch com a variável $_GET['area'] e efetuar a separação de conteúdo.
Comment: No código da pergunta, no case do `/cliente/cadastro`, o valor em `url` será `cliente/cadastro`, que na *index.php* é separado em `$Url[0]` e `$Url[1]`. Qual o motivo disso não funcionar?

Divisão em URL AMIGAVEL sem criar pasta


Passar variável query buider Laravel

Question: Eu estou tentando fazer esta função com Laravel Query Builder
public function getEstudantesCargaHoraria(Request $request)
{
    $ano_letivo = $request->ano_letivo;
    $turma_id  = $request->id;

    $ano_letivo = 2017;
    $turma_id   = 528;

    $estudantes = DB::table('turmas_has_estudantes')
        ->leftJoin('estudantes_identificacao', 'estudantes_identificacao.id', '=', 'turmas_has_estudantes.estudantes_identificacao_id')
        ->leftJoin('estudantes_carga_horaria', function ($join) {
            $join->on('estudantes_carga_horaria.estudantes_identificacao_id', '=', 'turmas_has_estudantes.estudantes_identificacao_id')
                ->where(function ($query)  use ($ano_letivo) {
                    $query
                    ->whereNull('estudantes_carga_horaria.ano_letivo')
                    ->orWhere('estudantes_carga_horaria.ano_letivo', '=', $ano_letivo);
                });
        })

        ->select(
            'turmas_has_estudantes.id AS turmas_has_estudantes_id',
            'turmas_has_estudantes.numero',
            'estudantes_identificacao.nome_completo',

            'estudantes_carga_horaria.id AS estudantes_carga_horaria_id',
            'estudantes_carga_horaria.estudantes_identificacao_id',
            'estudantes_carga_horaria.ano_letivo',
        )
        ->where('turmas_has_estudantes.turmas_id',     $turma_id)
        ->orderBy('turmas_has_estudantes.numero')
        ->orderBy('estudantes_identificacao.nome_completo')
        ->get();

    return $estudantes;
}

Aparece mensagem de erro: Undefined variable: ano_letivo
Eu pesquisei na Internet e recomendavam colocar: use ($ano_letivo) mas, não funcionou. Continua não reconhecendo a variável
Answer: Você está usando uma Closure dentro de outra. Para isso, você precisa passar a variável para o escopo da segunda Closure através de use.
O seu código está assim:
->leftJoin('estudantes_carga_horaria', function ($join) {
    $join->on('estudantes_carga_horaria.estudantes_identificacao_id', '=', 'turmas_has_estudantes.estudantes_identificacao_id')
        ->where(function ($query)  use ($ano_letivo) {
            $query
            ->whereNull('estudantes_carga_horaria.ano_letivo')
            ->orWhere('estudantes_carga_horaria.ano_letivo', '=', $ano_letivo);
        });
})

Deveria estar assim:
->leftJoin('estudantes_carga_horaria', function ($join) use($ano_letivo) { // preste atenção nessa linha

    $join->on('estudantes_carga_horaria.estudantes_identificacao_id', '=', 'turmas_has_estudantes.estudantes_identificacao_id')
        ->where(function ($query)  use ($ano_letivo) {
            $query
            ->whereNull('estudantes_carga_horaria.ano_letivo')
            ->orWhere('estudantes_carga_horaria.ano_letivo', '=', $ano_letivo);
        });
})

Ou seja, toda vez que você usar uma Closure dentro de outra e quiser usar a variavel do escopo principal, é necessário "repetir" o use pra cada uma delas.
Vou dar um exemplo fictício
$a = "valor";

call(function () use($a) {

    return function () use($a) {

        return function () use ($a) {
            echo $a;
        };
    };
})

Comment: Que coisa estranha!! rsrs Funcionou perfeitamente! Muito Obrgado!!

Passar variável query buider Laravel


Android Google Map Fragment 1:1 ratio (Same height and width)

Question: I am trying to create a google maps with aspect ratio 1:1 so the height is the same as the width. This is my current code:
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@drawable/border"
        android:orientation="vertical"
        android:paddingBottom="15dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingTop="5dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Locatiegegevens"
            android:textStyle="bold" />

        ...

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Woonplaats:" />

        <fragment xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:map="http://schemas.android.com/apk/res-auto"
            android:id="@+id/mapPreview"
            android:name="com.google.android.gms.maps.MapFragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            map:cameraZoom="13"
            map:liteMode="true"

            map:mapType="normal" />

    </LinearLayout>

The fragment class:
public class CaseFragment extends Fragment implements OnMapReadyCallback {

private GoogleMap mMap;
private Case caseObj;

private TextView title;

public CaseFragment() {
    // Required empty public constructor
}

public static CaseFragment newInstance(Case caseObj) {
    CaseFragment caseFragment = new CaseFragment();

    Bundle args = new Bundle();
    args.putSerializable("case", caseObj);
    caseFragment.setArguments(args);
    return caseFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle args = getArguments();
    caseObj = (Case) args.getSerializable("case");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_case, container, false);

    title = (TextView) view.findViewById(R.id.txtTitle);
    title.setText(caseObj.getId());

    MapFragment mapFragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.mapPreview);
    mapFragment.getMapAsync(this);

    return view;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    LatLng sydney = new LatLng(-33.852, 151.211);
    googleMap.addMarker(new MarkerOptions().position(sydney)
            .title("Marker in Sydney"));
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}

I already tried to use LayoutParams but that made the width the same as the height for some reason:
ViewGroup.LayoutParams params = mMapFragment.getView().getLayoutParams();
params.height = params.width;
mMapFragment.getView().setLayoutParams(params);

It currently looks like this:
Answer: Use Custom View class extended MapView instead of fragment
then, Override onMeasure as below
   @Override
    protected void onMeasure(int width, int height) {
        // note we are applying the width value as the height
        super.onMeasure(width, width);
    }

It will solve your issue.


what kind of chord progession is this?

Question: im quite new in music theory and i really dont understand what he is doing here.
is he changing the key after every chord?
he talks about c minor being the root note. after that he switches to c# which would be off the key?
what kind of chord progession is this? does it have a name? i have a really hard time figuring out what is happening here :( it sounds so good tho!

thanks for helping!
Answer: He is doing this:
Cm Db => Fm Gb => Bbm Cb => Ebm Fb => ...
What I hear is a continuous modulation up in perfect fourths. The chords Cm Db Fm can be heard in the key of F minor. The F minor chord is then re-interpreted as the Vm chord of the next key (Bbm) etc. So what you have is

key
Fm:  Cm Db Fm
Bbm:       Fm Gb Bbm
Ebm:             Bbm Cb Ebm
...
Answer: @MattL already pointed out the three chord pattern.
With Roman numerals the basic harmonic template is v VI i. That's a minor v. The chords are diatonic, but technically non-functional. I only mention this as a kind of progression. When chords are treated non-functionally you can use unconventional root progressions that aren't like familiar patterns such as ii V I, and they can sound pretty cool with a more drifting feel.
Then a harmonic pattern is repeat by transposing you can call it a harmonic sequence. Sequences can be either diatonic or chromatic. In this case the sequence is chromatic and shifts into different modes.
Instead of having a more common name like turnaround ii V I or substitution ii bII I you could call this kind of progression...
A diatonic, non-functional, sequential progression.
That is a mouthful, but it really does describe the kind of progression.

what kind of chord progession is this?


disable scrolling on webpage and allow it only on page sections

Question: I'm working onepage website, what i'm trying to do is to disable scorlling on webpage and only and make transitions between sections using the navbar links to id. for that i have use this jquery code
$(document).ready(function() {
    $('.js-scrollTo').on('click', function() {
        var page = $(this).attr('href');
        var speed = 1000;
        $('html, body').animate( { scrollTop: $(page).offset().top }, speed );
        return false;
    });
});

and this on CSS
html, body {margin: 0; height: 100%; overflow: hidden}

everything work fine except one issue is that when im in a specific section that have a big content i can't scroll within in, what im trying to figure out is: how to enable scrolling within section itself without scrolling all the webpage
Answer: If I've understood your question correctly, what you can do in this case is add an overflow-y:scroll to the wrapping div of the content you wish to be scrollable.
For example, say we have a div#test with some content:

   ... Some content

We can then simply apply the styles:
#test {
  height: 300px;
  width: 300px;
  overflow-y: scroll;
  background: #ff1000;
}

Here is it in action: http://codepen.io/anon/pen/RRYERR
Comment: thank you for your answer but i have tried that before and it didnt work for me, it only show the scroll bar but it dont really scroll beside its ugly, im looking for something in jquery for a slim scroll bar
Comment: For this to work, you'll need to ensure that the div itself is bounded at some height (i.e. set a height on it) so the content actually overflows. Also, for the custom scrollbar, there are a number of libraries you could use to change the look of it, such as [this](https://github.com/gromo/jquery.scrollbar)
Answer: You can add css to your div :-
yourDiv:hover { overflow: auto; height:desired height }


PCA variances pattern changed greatly after data cleaning

Question: I have data, when I normalize it and then performed PCA, I calculated the variance of PC components, I found that, the first component is 72% and seconed component is 8% (total 72+8=80%) and so on.
Now I used to the same data and performed some data cleaning function and then normalize it and then performed PCA, calculated variance of the PCA components I found that, first component gives 40% and second component gives 20% (40+20=60%).
What does this mean? Which one is better? I found that, after data cleaning operation, the classifier gives highest accuracy. I am unable to have a sense what is happening exactly and why? Would anyone explain?
Comment: That very likely means that your uncleaned data had some outliers and that your initial PCA solution was much driven by those outliers (they pulled the first component towards them; or, because you did z-standardizing which changes the shape of the data cloud, they might have pulled the component away from them).
Answer: This situation is typically conspicuous when you perform data cleaning, you must be clear about the data structure (highly balanced or unbalanced) before performing it. After all, it means that using the PCA before data cleaning tend to explain more variability of the data with less dimension.
To answer your question more precisely, could you tell me what classifier(s) are you using?
By the way, the formula of variance captured by component k is:
$$\frac{\lambda_k}{\sum_{i=1}^n \lambda_i}$$
,where $\lambda_1 \ge \lambda_2 \ge......\ge \lambda_n \ge 0$ is the variance captured by each component.
Comment: I am using SVM classifier.
Answer: For classifiers the critical issue is the ratio of variance within groups to variance between group means. With SVM the shape of the groups can be more complex than a simple linear discriminant analysis but the same principle holds (SVM can be viewed as remapping a complex group shape into a simple one).
What this means is that overall variance across the dataset can't predict performance in a classifier. If the data cleanup has removed irrelevant variations then the classifier should work better. If the variations removed by the cleanup are relevant to the classier it will be worse.


How to distinguish numerical categorical (Ex: White = 1, Latino = 2 etc) from numerical continuous or discrete variables on a dataset?

Question: I am currently working on a project that involves a data processing pipeline, and in it I might come across all sorts of data. I would like to know if there are any references on an automatic way to detect if a numerical column is actually a category (e.g. store ids, ZIP codes, etc...) and to not mistake it for a continuous variable.
Is there any way in which we could look at the numbers on a particular column and solely based on the number tell if it's categorical or numerical? I myself have already read a couple of other posts regarding this problem here but most of the answers either don't have any references to scientific studies or simply say it's impossible.
Comment: Could you explain why this might matter for your processing pipeline?
Comment: We want to automate everything. We want to have a machine that automatically identifies the variable type (categorical etc) without having to do it all manually because at times we might receive dozens of datasets with hundreds of columns and we won't have the time to anayse column by column.
Comment: That isn't what I was asking.  What is the point of characterizing columns as categorical or numerical?  How is that relevant for data processing?
Comment: Should I use one hot encoding on them or not? maybe using one hot encoding for numerical variables might reduce the accuracy significantly...
Comment: That's not a data processing decision, nor is it wise to automate it: it's a *statistical modeling* decision.  Using one-hot encoding for numerical variables will *increase* the accuracy of any prediction based on them but potentially at a cost of (severe) overfitting.  Using that coding for a *response* variable will usually not work at all and will always create a complicated model.
Answer: I found this helpful
A key distinction between ordinal categorical variables and discrete quantitative variables is that there is a uniform degree of difference within discrete quantitative variables.
It's from resource
https://www.codecademy.com/learn/stats-variable-types/modules/stats-variable-types/cheatsheet
Hope it helps.
Comment: My question was more on the lines of: if I have many datasets with a large amount of columns, is there any strategy I could use to figure out which columns are categorical ordinal, categorical nominal, or quantitative if all the columns are already being represented in numbers? Like correlation, number of unique values, or anything else?
Comment: This will mistakenly identify ZIP codes as not being discrete.  And with small datasets it will be often mistaken, no matter what the variables may be.  The question really is unanswerable because it's predicated on a fallacy: neither "categorical" or "numerical" refer to inherent properties of data.  They reflect a combination of the measurement process and how the data are modeled.
Comment: Found something similar here, they used python. to identify categorical variables in dataset. https://stackoverflow.com/q/29803093
Comment: That's a solution to a different problem.  There, "categorical" refers to how data are represented in a computer.
Comment: okay.  thanks @whuber


AngularJS consumir RESTful em dominios diferentes

Question: Boa tarde, estou tentando fazer um cliente que indexa as informações de vários webservices (sobre cotações de bitcoin de várias corretoras) porém ao tentar acessar o webservice os valores importados do json não são exibidos, e ao apertar o F12 no chrome retorna a seguinte mensagem de erro:

XMLHttpRequest cannot load https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

já dei uma pesquisada sobre o erro, o mesmo tbm ocorre no meu servidor de testes remoto (hostinger), eu sei que o erro ocorre porque o servidor não retorna a header "Access-Control-Allow-Origin = *" porém são muitos servidores diferentes de terceiros que eu irei buscar e todos me retornam este mesmo erro...
segue o código utilizado para acessar o WS:
(serviço)

app.factory('foxbit', ['$http',
function($http){
 return $http.get('https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC')
 .success(function(data) {
   return data;
 })
 .error(function(err) {
   return err;
 });
}]);

Controller:

app.controller('MainController', ['$scope', 'foxbit', function($scope, foxbit) {
  foxbit.success(function(data) {
    $scope.cotacaofox = data;
  });

}]);

Então, se os ninjas daqui puderem me indicar um meio de contornar este erro, eu ficarei muito grato.
Obrigado.
Comment: já tentou criar um virtual host pra ver se você contorna o problema?
Dica: Não deixe o 'succes' e o 'error' na factory. Você deve tratar isso no controller. E ao invés de usar essas funções para tratar o retorno, use 'then'. As duas anteriores parecem que estão 'deprecated'.
Comment: O problema do virtual host é que eu vou colocar a página em um servidor remoto que não tenho acesso a essa customização no servidor remoto, e quanto ao success e ao error, eu coloquei só pq fica mais fácil, mais pretendo arrumar antes de colocar em produção..
Answer: Essa é uma limitação imposta pelo CORS. Duas possibilidades:

Solicite aos mantenedores do serviço blinktrade.com que incluam o seu domínio de origem na lista de domínios autorizados, ou
Implemente um serviço de proxy local, eliminando a avaliação do CORS.

Um exemplo de proxy em C#/WebApi 2 vem a seguir:
[RoutePrefix("stack/proxy")]
public class ProxyController : ApiController
{
    [Route("")]
    [HttpGet]
    public object Search([FromUri] string url)
    {
        try
        {
            var client = new HttpClient();
            var result = client.GetStringAsync(url).Result;

            var resp = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain")
            };

            return resp;
        }
        catch (Exception e)
        {
            throw;
        }
    }
}

Uso:

http://localhost:49801/stack/proxy/?url=https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC

Resultado:
{
"high":1693.88,
"vol":248.24057349,
"buy":1623.55,
"last":1623.54,
"low":1551.01,
"pair":"BTCBRL",
"sell":1625.11,
"vol_brl":403631.3524226
}

Código-fonte para controller WebApi retirado do projeto Nyan (gitHub).
Comment: Por isso a sugestão de implementar um proxy service local, Dennis. CORS só influencia requisições XHR entre domínios. Uma chamada via proxy funciona como uma requisição direta.
Comment: Igual eu falei acima, não tenho como pedir para os mantenedores do WS adicionar o tratamento ao header do response pq são vários WS que eu vou buscar informações...
Comment: @Dennis Uma alternativa é fazer as requisicoes utilizando jsonp. Essa funcionalidade se aplica apenas para Get e internamente cria um elemento script que pode referenciar outro dominio. Um parâmetro a mais será necessario para possibilitar a injeçao de callback. Favor pesquisar a documentacao. $Http.jsonp
Comment: O problema do JSONP é que nos WS que eu estou consumindo nenhum deles retorna os dados em JSONP somente em JSON.


Best way to practice difficult runs

Question: Runs are very common in music; a typical run is a sequence of quick, short, slurred (not always) notes that either ascend or descend and often involve multiple shifts.
The approaches
I've learned a few ways to tackle runs, but I want to know if there are more than the ones I will describe below.

Add-A-Note

Add-A-Note is when one takes out slurs from the run (if any) and starts with the first note. After practicing one note, add a second note, and practice the group of 2 notes with separate bows. Continue this sequence until every note in the run can be played in separate bows. I also recommend starting with a slower speed than increasing the speed until the desirable tempo is reached.

Backwards Add-A-Note

This method is essentially the same as Add-A-Note, but backward, starting from the last note of the run. This is especially helpful in runs that ascend to an especially high note or involve many shifts.

Isolating shifts

This is something I frequently do, where I isolate the shift by practicing the note before the shift to the note after the shift.

Groupings

This is similar to Add-A-Note, but with groupings instead of individual notes. I found this especially helpful if the run is written in rhythmic notes, such as a sequence of sixteenth notes (groupings of 4) or triplets (groupings of 3).
The problem
These approaches work very well for me, but I am wondering whether there are any better methods. These methods are all very tedious and involve a lot of repetition, sometimes when it seems unnecessary to do so. I have tried simply slowing down the run, in separate bows, and then speeding it back up. However, the result is never as clean as if I did the same thing with Add-A-Note. Any suggestions or practice tips would be appreciated.
Comment: https://theviolinlessons.com/shifting-on-violin/
Comment: Please define run and shift.
Comment: A run is a rapid sequence of ascending or descending notes, and a shift is when you move your finger up the fingerboard to play a higher note on the same string.
Comment: Thanks, but how can you concile "higher note" and "same string" ? Same string implies same note doesn't it ?
Comment: No... you can play multiple tones on one string with the same finger by moving up the fingerboard.
Comment: Sorry, I understood it was on the piano. Indeed.
Answer: Sure, I can think of a few other formulaic approaches to practicing passagework. But the very best approach is not a formula at all, but to engage your mind analytically as you practice. You're probably doing this already and are just looking for some extra tools to have in your bag, but it's worth emphasizing. The most efficient practicing is not when we simply put ourselves through some process or ritual, expecting it to have an expected effect on our playing, but when we let our brain talk to our muscles and ears. "I do this. It sounds like that. Why? Oh, because I went like that. So I'll try going like this instead. It changed the sound in this way." This happens all the time unconsciously, but when we make it conscious we learn faster (and can apply our learning to other passages and pieces!).
With that disclaimer: I find that your "add-a-note" and "backwards-add-a-note" are very effective when in the early stages of "getting to know" a passage, helping to actually parse it and become familiar with the notes. Yes, practicing shifts in isolation is very important (though so is re-contextualizing them. Sometimes what makes a shift challenging might be what happened two or three notes earlier.)
One favorite, for passages that are all notes of equal duration (like, say, several measures of 16th notes) is to project a rhythm pattern onto them. To convert those 16ths into pairs of dotted 16ths and 32nds (long-short-long-short), and then to do the opposite (short-long-short-long). Those two combined do something great: If I were to apply it to, say, Paganini's 5th caprice:

... then with the first pattern (long-short), I'd have a "long time" between the A and the C (in which I shift), and a "short time" between the C and the E. As I move from the third beat into the fourth, I'd have a shortened time for the shift back to first position. When I switch to the short-long pattern, I'd have a "short time" between the initial A and C and a "long time" between C and E. By practicing both patterns, I will at some point have played every pair of notes, every shift and string crossing, at double my metronome speed (as if they were 32nds), but I give my mind time to process what I'm doing. You can then apply other rhythm patterns as well; Galamian's scale system has a whole section devoted to rhythm patterns (one 8th followed by three 16ths? A 16th, two 8ths, a 16th?).
Another simple trick is to change the bowing style. For a spiccato passage, the shortness of each tone gives your left hand fingers extra milliseconds to move into position, and a broad, connected legato forces them to switch places more quickly. For a fortissimo passage, there's much to be gained by calming the heck down and practicing it mezzo forte until it's comfortable. Sometimes for passages that have challenging left-hand work and bowing, it can be helpful to separate them. Put the bow down and just move your fingers on the strings. Then pick up the bow, keep your left hand still, and play open strings in the exact pattern of rhythm and bow directions that you would. For instance, in these measures of the Paganini...

... I find that the second measure is much more challenging than the previous ones, and is one of the measures that really impedes my ability to crank the tempo up. In that measure (starting with the F) I would play: D D A A | D A A A | D A A A | D A A A etc. I think it's those isolated D string notes, the string crossing from A down to D and back again, that's harder than a string crossing to an isolated higher string. That's partly because the Ds fall on down-bows. Try reversing the bow directions of the passage! If it started down-bow, start up-bow.
Many of these gimmicks do little more than shake up my routine and make me more aware of what I'm doing, but at their best, they cause me to stare at my bow arm as I slowly pivot from A to D and back, and contemplate the mechanics of how my elbow opens and closes as my forearm pivots, and consider whether it might be made easier if I bend my wrist like that, or if I bend my fingers like this on the up-bow to help curve the bow towards the lower string. And then I can internalize those physical findings and know why that measure is hard, and as I approach it think "Ok, bend the wrist and squeeze the fingers," and even apply the same lesson to a similar string crossing in another piece.
Answer:
These methods are all very tedious and involve a lot of repetition, sometimes when it seems unnecessary to do so

Indeed. A large part of the repetitions is going to be repeating something which is no problem for you and only a small part practicing the bit that is actually difficult.
Therefore what I do is try and isolate the difficult part and practice that. Identifying the difficult part is normally easy. Try the run and see where your fingers stumble and fall over, so to speak.
For me that usually happens with string crossings involving the 4th finger and another finger. For instance 1-2-3-4 on the D slurred with 3 on the A. The difficult part is the 3-4-3 string crossing from D to A. So, I extract that and repeat that. In order to solve similar future problems on other strings I construct my own mini etude 3-4-3-4-3-4-3-4 starting on the G string and working up to the E string and practice that until it is smooth and up to speed.

Best way to practice difficult runs


How does Gdim7 fit in C# minor?

Question: I'm pretty new to music theory. This song is actually the reason why I even started reading about theory, but I still can't comprehend this chord progression.

I think this is in C# minor, and this is the chord progression: C#m7 Gdim7 F#m7 B7sus4 C#m7
What I don't understand is the Gdim7 chord. Key of C#m doesn't have  a G chord, but it fits in the chord progression somehow. What's the technical reason behind the flow of this chord?
Also, I'm looking at this from the composer's point of view, and I'm just very confused as to how he ended up writing this progression in the first place. It doesn't seem to follow the typical "pattern". For example, I've been using hooktheory to recreate this, but it doesn't provide an easy way to get the Gdim7 chord under C#m, where the G is the root note.
Thanks.
Comment: Hi. I've edited the title in your question, as people would want to close it in its original form. You have a specific question, which I believe is in within the scope of the site.
Comment: It's an unfortunate misconception you have to use chords that are diatonic to a key. There's a saying that 'a little knowledge is a dangerous thing'... and there seems to be a problem with the way theory is taught - students are taught about diatonic chords and modulation between keys,  but then never seem to get on to other kinds of harmony which are equally useful to know about.
Answer: This is a good example of a non-dominant diminished chord with a diatonic function (i.e. resolving to a diatonic chord). Note that often diminished chords function as dominants. This is the case when the root of the diminished chord is the leading tone to the root of the diatonic resolution chord.
However, in your example this is not the case because then the diminished chord preceding the F#m7 chord should be a Fdim7 chord. The non-dominant diminished chord in your example works because - as also pointed out by Patrx2 - it has more than one tone in common with the resolution chord. A diminished chord moving down a half step is a very common device in jazz progressions. If you replace the C#m7 chord by its relative major chord Emaj7, the progression becomes a well-known jazz cliché:
|| Emaj7  |  Gdim7  |  F#m7  |  B7(sus4)  ||
which is analyzed as
||  Imaj7  |  bIIIdim7  |  IIm7  |  V7  ||
with the bIIIdim7 being a non-dominant descending diminished chord.
Comment: @user18822: I was pointing out a very related example, which occurs very often in jazz standards, and there the C#m7 is replaced by an Emaj7 (which doesn't really change that much, because those two chords are very related).
Comment: Shouldn't the Imaj7 be VIm7 to get C#m7, or were you pointing out an example that shares the qualities of the presented chord progression? Also, I didn't realize you could check a key's relative key to dissect the piece. Thanks!
Answer: Maybe because Gdim7 is the same thing as C♯dim7? That means that, between the C♯m7 and the F♯m7, two notes are going to be held from the first chord, mainly C♯ and E, and there is going to be descending chromatic motion in parallel minor thirds between G♯ and B in the C♯m7, and F♯ and A in the F♯m7, because the remaining two notes of the C♯dim 7 are G and B♭.
That's to say that the diminished 7th chord is formed by chromatic passing motion between the first and 3rd chords of the sequence.
Edit: I'll amplify a bit. It's actually quite subtle because C♯ and E are common to all three chords, so the change of root a fifth downwards (from C♯ to F♯) is being handled strictly by the chromatic parallel thirds moving the distance of a whole tone down.
Answer: I wanted to add some information to the already-good answers, about how to properly "spell" this chord.
Because chords are made up of stacked thirds, a seventh chord built on G will have to have some form of the notes G-B?-D?-F? (I'm using '?' to represent a yet-to-be-determined accidental). In the case of a Gdim7, these would become G-B♭-D♭-F♭. But we know that in our key (C♯ minor) we call the D♭ and F♭ C♯ and E. Yes, these pitches are "enharmonically equivalent," but the Gdim7 chord has to call them D♭ and F♭, since it has to have a stack of thirds.
Fortunately, though, dim7 chords are "symmetrical" -- we can start the chord on any one of its four pitches, and it has the same shape. That means we can pick any of its notes as the root. For example, if we pick E as the root (Edim7), then the chord has to contain E-G?-B?-D?, which, in order to make a dim7 chord, works out to E-G-B♭-D♭. That's better, but we've still got that pesky D♭ in there.
You can probably see where we're going next. By starting the chord a third lower, on C♯, the notes in the chord end up being spelled as C♯-E-G?-B?. In order to make this a C♯dim7, we need to make it C♯-E-G-B♭, which is a much better fit in our key. This is why I would recommend (as did Patrx2) calling this chord a C♯dim7, or a i dim7. I haven't used hooktheory before, but perhaps a i dim7 is easier to find than a ♭IIIdim7?
A little trick to remember all of this: regardless of the accidentals and the intervals involved, almost any chord (in western, common practice music) will be built from stacked thirds. That means they have to contain adjacent notes from a sort of "circle of thirds" scheme. Triads will contain three adjacent notes, while seventh chords will contain four adjacent notes.
A? - C? - E? - G? - B? - D? - F? - A?
Note how the circle wraps around on itself (it ends where it begins). Also note how I'm careful to not specify which version of a note I'm using. That will be determined by a number of factors including the key, and the desired quality of the chord.
Answer: G#dim7 is a rootless inversion for G7b9, making it a nice substitution for this type of chord. The b9 is an altered tension that goes well before a minor chord (look for the altered dominants in a minor 2-5-1).
The G#dim7 kind of acts as a G7, which itself is a tritone substitution for a C#7. C#7 is the V7/II - secondary dominant for the II chord, F#m7 - in the key of E major (C# minor). In other words, C#7, G7, G7b9 and G#dim7 are all good, flavored ways to precede a F#m7 chord.
It's also interesting that G7 is the secondary dominant chord resolving to B7, so it reminds something resolving late. The B7, in this case, is actually a Bsus4. The 4th replaces the 3rd of the chord, making it neutral from a major/minor point of view. Good way to keep that major color from messing up with the song's minor color. I believe this minor flavor is a part of the reason why that G# fits the song so well.

How does Gdim7 fit in C# minor?


Finding the amount of numbers less than another number which are multiples of a set

Question: An Example To Illustrate

Find the amount of numbers less than 30 that are multiples of the set of numbers [2,3,5]
Clearly we can find the number of multiples of a number less than another number through this equation:
$$ numberOfMultiplesLessThan =\Big\lceil\frac {numberToFindMultiplessLessThan}{numberToFindMultiplesOf}\Big\rceil - 1 $$
So in this case we have:

Number of Multiples of 2: $\frac {30} 2 - 1 = 15 -1 = 14$
Number of Multiples of 3: $\frac {30} 3 - 1 = 10 -1 = 9$
Number of Multiples of 5: $\frac {30} 5 - 1 = 6 - 1 = 5$

But now we have to check for cases in which a number is a multiple of more than one of these numbers:

Number of Multiples of 2 & 3:  $\frac {30} {2*3} - 1 = 30/6 - 1 = 5 - 1 = 4$
Number of Multiples of 2 & 5:  $\frac {30} {2*5} - 1 = 30/10 - 1 = 3 - 1 = 2 $
Number of Multiples of 3 & 5:  $\frac {30} {3*5} - 1 = 30/15 - 1 = 2 - 1 = 2 $

Luckily,since $2*3*5 = 30$ there is no number less than thirty that is a multiple of all three, so we don't have to check that set. Unfortunately, for larger sets (and depending on the number that is chosen to be less than) there may be many set intersections to check for.
Anyway, we can now find the amount of numbers that are less than 30 and are multiples of either 2, 3, or 5:

$\text{Multiples Less than 30} = \text{Number of Multiples of 2} + \text{Number of Multiples of 3} + \text{Number of Multiples of 5} - \text{Number of Multiples of 2 & 3} - \text{Number of Multiples of 2 & 5} - \text{Number of Multiples of 3 & 5}$
$\text{Multiples Less than 30} = 14 + 9 + 5 - 4 - 2 - 2 = 21$

Notes about the Problem

Though in this case I choose a number (30) which made the results for the multiple equation turn out nicely, in truth the actual chosen number won't be so nice. So, in those cases the ceiling function must be invoked.
It is not a coincidence that the numbers in the set are all prime. My specific application is a bit odd in that it will only select prime numbers and that too, by choosing a prime number it must include all the prime numbers below it (ex: [11,7,5,3,2] is a valid set but [11,5,3,2] is not). I'm not sure how this note will affect the answer, but I thought I'd include it.

My Problem
This algorithm, while relatively simple, becomes a bit tedious with extremely large numbers and extremely large sets. Examining the problem again, I found that there is a huge amount of simplification that can be made with the overall equation. For example:
Consider (again) the case of finding the amount of numbers less than 30 that are Multiples of 2, 3, or 5. The overall equation is this:

$ \text{Multiples Less than 30} = \text{Number of Multiples of 2} + \text{Number of Multiples of 3} + \text{Number of Multiples of 5} - \text{Number of Multiples of 2 & 3} - \text{Number of Multiples of 2 & 5} - \text{Number of Multiples of 3 & 5} $
$\text{Multiples Less Than 30} =  29 - (\frac {30} 2 -1) - (\frac {30} 3 - 1) - (\frac {30} 5 - 1) + (\frac {30}{2*3} - 1) + (\frac{30} {2*5} -1) + (\frac{30} {3*5} - 1) $
$$Multiples Less Than 30 = 29 - (\frac {30} 2) - (3\frac {30} 3) - (\frac {30} 5) + (\frac {30}{2*3}) + (\frac{30} {2*5}) + (\frac{30} {3*5}) + 3 - 3 $$

[Note: It is common but not required that the -1's cancel out]

$$Multiples Less Than 30 = 29 - (\frac {30} 2) - (\frac {30} 3) - (\frac {30} 5) + (\frac {30}{2*3}) + (\frac{30} {2*5}) + (\frac{30} {3*5}) $$
$$Multiples Less Than 30 = 29 - 30*(\frac12 + \frac 13 + \frac 15 - \frac 1 {2*3} - \frac 1 {2*5} - \frac 1 {(3*5)} )$$
$$Multiples Less Than 30 = 29 - 2*3*5*(\frac12 + \frac 13 + \frac 15 - \frac 1 {2*3} - \frac 1 {2*5} - \frac 1 {(3*5)} )$$
$$Multiples Less Than 30 = 29 - (3*5 + 2*5 + 2*3 - 5 - 3 - 2 )$$

[Note: In cases that don't involve the primorial ( 3*2 or  5*3*2 or  7*5*3*2 or 11*7*5*3*2), you'd have to multiple both sides by the primorial to be able to clear those fractions]

$$Multiples Less Than 30 = 29 - (3*5 + 2*5 + 2*3 - 5 - 3 - 2 )$$
$$Multiples Less Than 30 = 29 - (3*4 + 5 + 2*2) $$

[Note: As you can see (Step 9) the relatively long equation turned into something simple. I've done this with a few numbers, and without doing any calculations -- other than factoring and combining like terms -- it always comes down to something relatively simple.]
The Actual Question!
So, my question is: Using the type of simplification shown above (or any other system for that matter), is there any generalized way to find how many multiples of a prime set as discussed above are below a number that is simpler or faster than the algorithm I described?

P.S.
I'm apologize in advance for the formatting and visual look of the question. I've tried to make it as readable as possible, but I still feel that it is both bulky and a bit unorganized. In addition, I couldn't quite figure out how to make the math look nice (like 3*5)
Comment: The simplest idea that comes to my mind is the sieve of Eratosthenes. By the way, a *multiple* of a number and a *factor* of a number are very different. I believe you might want to use the word "multiple(s)" in your question.
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Comment: @Tunococ You are very correct! I've updated the question. Also, since I only find the amount of _multiples_ :)  and not the actual, specific multiples I believe using the Sieve of Eratosthenes might be overkill. If you are saying on the other hand (and I think you are) to use the same methodology (roughly) as the sieve, I think I am currently (roughly), but perhaps I'm incorrect.
Comment: Updated it with some MathJax!
Comment: See "inclusion-exclusion principle".
Answer: You can write what you're after as
$$\lfloor{29\over2} \rfloor+\lfloor{29\over3} \rfloor+\lfloor{29\over5} \rfloor-\lfloor{29\over6} \rfloor-\lfloor{29\over10} \rfloor-\lfloor{29\over15} \rfloor+\lfloor{29\over30} \rfloor=14+9+5-4-2-1+0=21$$
In general, if you have a set of pairwise relatively prime (positive) integers $a_1,a_2,\ldots,a_n$ and want to know how many multiples of one of these there are less than some number $N$, the answer is
$$\lfloor{N-1\over a_1} \rfloor+\cdots+\lfloor{N-1\over a_n} \rfloor-\lfloor{N-1\over a_1a_2} \rfloor-\cdots-\lfloor{N-1\over a_{n-1}a_n} \rfloor+\cdots+(-1)^{n+1}\lfloor{N-1\over a_1\cdots a_n} \rfloor$$
by inclusion-exclusion, as JMac31 mentioned in comments.  In general this gives you $2^n-1$ numbers to compute.  I don't think you can do any better than that if you want to get the exact number.
On the other hand, if (as is the case in the OP's example), the $a_i$'s are distinct primes and $N$ is their product, then the answer is
$$N-1-(a_1-1)(a_2-1)\cdots(a_n-1)$$
This is mainly the multiplicative property of the Euler phi function.
Comment: Awesome! Thanks man. This is exactly the kind of response I was looking for (not implying the other responses were bad or anything-- they were are good--  just that this answered all of my questions).


Qual alternativa para substituir códigos em ASP por JavaScript?

Question: Tenho esse código em asp e javascript.
<%if trim(ind_tipo_proposta_pj) = "S" then%>
                var onum_seq_proposta_pj_ts = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%><%Response.Write nome_campo_cod_ts%>' + txt_sufixo);
            <%else%>
                var onum_seq_proposta_ts    = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%><%Response.Write nome_campo_cod_ts%>' + txt_sufixo);
            <%end if%>

Preciso torná-lo mais limpo, sem as tags asp. O que passa é que eu tenho muita dúvida quando o assunto é asp. Bem, há uns dias atrás o colega TobyMosque me ajudou bastante em fazer algo semelhante. Não estou aqui pedindo que faça para  mim, senão estarei sempre perguntando, mas uma dica ou uma linha a ser seguida. Minha tentativa ficou nisso:
if()
var onum_seq_proposta_pj_ts = "<%= trim(nome_campo_cod_ts) %>" || "";
var onum_seq_proposta_ts    = "<%= trim(nome_campo_cod_ts) %>"

Não consegui terminar o if e também não sei se o ou está correto. Veja que há um if no asp, caso seja jurídico, carrega uma variável senão carrega outra variável. Fico pensando se eu matar o if do asp e colocar um if do js, se vai dar tilt. Também poderia fazer um ternário, mas como fazer isso numa declaração de uma variável. Faria no if, mas na declaração não sei se é possível(acho que não). Como eu faço, ou melhor, qual caminho a seguir?
Fazendo minhas tentativas aqui cheguei a esse código, mas não sei se estar certo, pois para testar terei que alterar muito mais coisas, mas apenas me digam. Esse é o caminho? Não matei 100% o asp, mas deu uma otimizada em relação ao asp.
var onum_seq_proposta_pj_ts = null;
var onum_seq_proposta_ts    = null;
<%if trim(ind_tipo_proposta_pj) = "S" then%>
   onum_seq_proposta_pj_ts = "<%= trim(nome_campo_cod_ts) %>" || onum_seq_proposta_ts = "<%= trim(nome_campo_cod_ts) %>";
<%end if%>

Ok, em realidade as variáveis txt_prefixo e txt_sufixo são variáveis. Elas já sei como tratar. Veja como estão declaradas:
    var txt_prefixo = '';
    var txt_sufixo  = '';

  try{
       txt_prefixo = '.document.form01.';
       txt_sufixo  = '';
       ......

TobyMosque, é dessa forma que eu devo utilizar o object?
var txt_prefixo = '';
var txt_sufixo  = '';
window["objeto"] = null;

        var nome_campo_cod_ts_id = "<%= trim(nome_campo_cod_ts) %>";

        var onum_seq_proposta_pj_ts = null;
        var onum_seq_proposta_ts = null;
        var txt_chamada = "";

        var onum_seq_proposta_pj_ts_id = "<%= trim(ind_tipo_proposta_pj)%>" == "S";

        if(onum_seq_proposta_pj_ts_id)
            window[txt_chamada][txt_prefixo][onum_seq_proposta_pj_ts][txt_sufixo];
        else
            window[txt_chamada][txt_prefixo][onum_seq_proposta_ts][txt_sufixo];

Em realidade estou com grande dificuldade de eliminar esse try..catch, ou seja, substituir por um código javascript mais limpo:
try {
            txt_prefixo = '.document.form01.';
            txt_sufixo  = '';
            <%if trim(ind_tipo_proposta_pj) = "S" then%>
                var onum_seq_proposta_pj_ts = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%><%Response.Write nome_campo_cod_ts%>' + txt_sufixo);
            <%else%>
                var onum_seq_proposta_ts    = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%><%Response.Write nome_campo_cod_ts%>' + txt_sufixo);
            <%end if%>
        } catch (e) {
            txt_prefixo = '.document.all[\'';
            txt_sufixo  = '\']';
            <%if ind_tipo_proposta_pj = "S" then%>
                var onum_seq_proposta_pj_ts = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%><%Response.Write nome_campo_cod_ts%>' + txt_sufixo);
            <%else%>
                var onum_seq_proposta_ts    = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%><%Response.Write nome_campo_cod_ts%>' + txt_sufixo);
            <%end if%>
        }

Esse try..catch está dentro desse if em ASP:
<%if trim(nome_campo_cod_ts)<> "" then%>
        try {
            txt_prefixo = '.document.form01.';
            txt_sufixo  = '';
            <%if trim(ind_tipo_proposta_pj) = "S" then%>
                var onum_seq_proposta_pj_ts = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%><%Response.Write nome_campo_cod_ts%>' + txt_sufixo);
            <%else%>
                var onum_seq_proposta_ts    = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%><%Response.Write nome_campo_cod_ts%>' + txt_sufixo);
            <%end if%>
        } catch (e) {
            txt_prefixo = '.document.all[\'';
            txt_sufixo  = '\']';
            <%if ind_tipo_proposta_pj = "S" then%>
                var onum_seq_proposta_pj_ts = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%><%Response.Write nome_campo_cod_ts%>' + txt_sufixo);
            <%else%>
                var onum_seq_proposta_ts    = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%><%Response.Write nome_campo_cod_ts%>' + txt_sufixo);
            <%end if%>
        }
    <% else %>
        try {
            txt_prefixo = '.document.form01.';
            txt_sufixo  = '';
            <%if ind_tipo_proposta_pj = "S" then%>
                var onum_seq_proposta_pj_ts = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%>num_seq_proposta_pj_ts' + txt_sufixo);
            <%else%>
                var onum_seq_proposta_ts    = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%>num_seq_proposta_ts' + txt_sufixo);
            <%end if%>
        } catch (e) {
            txt_prefixo = '.document.all[\'';
            txt_sufixo  = '\']';
            <%if ind_tipo_proposta_pj = "S" then%>
                var onum_seq_proposta_pj_ts = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%>num_seq_proposta_pj_ts' + txt_sufixo);
            <%else%>
                var onum_seq_proposta_ts    = eval(txt_chamada + txt_prefixo + '<%Response.Write prefixo%>num_seq_proposta_ts' + txt_sufixo);
            <%end if%>
        }
    <%end if%>

Answer: Por que você não escreve os valores das variáveis ind_tipo_proposta_pj nome_campo_cod_ts e prefixo  em campos HTML do tipo hidden, assim que o ASP é executado, aí você pode manipular com o javascript. Lembre-se de colocar os campos antes do código JavaScript pois assim o servidor já "escreveu" os campos com os valores e você vai poder manipulá-los em seguida com JavaScript:
<input type="hidden" name="ind_tipo_proposta_pj" id="ind_tipo_proposta_pj" value="<%= trim(VARIAVEL_DO_ASP_TIPO_PROPOSTA) %>"/>
<input type="hidden" name="nome_campo_cod_ts" id="nome_campo_cod_ts" value="<%= trim(VARIAVEL_DO_ASP_NOME_CAMPO_COD_TS) %>"/>
<input type="hidden" name="prefixo" id="prefixo" value="<%= trim(VARIAVEL_DO_ASP_PREFIXO) %>"/>

Aí sim você usa tudo em JavaScript:

var onum_seq_proposta_pj_ts = null;
var onum_seq_proposta_ts = null;
var txt_chamada = "";
var txt_prefixo = "";
var txt_sufixo = "";

var campo_ind_tipo_proposta_pj_que_veio_do_asp = document.getElementById('ind_tipo_proposta_pj').value;
var campo_nome_campo_cod_ts_que_veio_do_asp = document.getElementById('nome_campo_cod_ts').value;
var campo_prefixo_que_veio_do_asp = document.getElementById('prefixo').value;
var prefixo_do_banco_de_dados = (campo_prefixo_que_veio_do_asp + "" + campo_nome_campo_cod_ts_que_veio_do_asp)

if (campo_ind_tipo_proposta_pj_que_veio_do_asp == "S") {
  eval(txt_chamada + txt_prefixo + prefixo_do_banco_de_dados + txt_sufixo);

} else {
  eval(txt_chamada + txt_prefixo + prefixo_do_banco_de_dados + txt_sufixo);
}
<input type="hidden" name="ind_tipo_proposta_pj" id="ind_tipo_proposta_pj" value="S" />
<input type="hidden" name="nome_campo_cod_ts" id="nome_campo_cod_ts" value="" />
<input type="hidden" name="prefixo" id="prefixo" value="document.write('ok');" />

O problema aí meu amigo é que tanto para pessoa física, como para pessoa jurídica a variável onum_seq_proposta_pj_ts  e onum_seq_proposta_ts    serão iguais. Porque se você olhar o código correspondente no script ASP original, as variáveis são as mesmas <%Response.Write prefixo%><%Response.Write nome_campo_cod_ts%>
Comment: Não pensei nisto. Pode ser uma boa saída sim, fica bem mais legível. Pode ser um caminho ou uma linha a ser seguida. Caso seja uma proposta PF, esse campo deverá vir com "N". Se eu coloco na página o value como "S", como ficaria caso seja uma proposta PF?
Comment: Na verdade se você olhar mais a cima o certo é colocar o `value` com a impressão do conteúdo da variável que está no `ASP`. Essa variável do tipo da proposta está no `ASP` (você leu do banco de dados ou um arquivo de texto, por exemplo, utilizando `ASP`), ou está em um campo `HTML` e essa página recebe essa variável ?
Comment: Vem do banco. O problema é que o site é muito grande, esse é apenas um módulo pelo que fomos contratados para dar manutenção. O site é bem antigo. Essa dúvida eu tenho. Se fixo o value como "S" e entra "N", ele muda o value, certo?
Comment: Acho que não estás entendendo @pnet. Eu só fixei o campo no código de exemplo, para que você possa testá-lo. Mas no seu aí, na sua página, você vai imprimir o valor do resultado da variável que veio do banco de dados, vou chamar ela de `TIPO_DE_PROPOSTA` e fazer o seguinte: ``
Comment: Ok, entendi agora. Nesse caso ele mesmo vem do BD(ind_tipo_proposta_pj)
Comment: Ok editei o código, pois entendi o que o seu código original propunha. Ele além de verificar se o valor da variável `ind_tipo_proposta_pj` é pessoa jurídica "S", o código `JavaScript` das condições `if` e `else` executa o aglomerado de outras variáveis, algumas do banco (entendendo que o que vem do seu `ASP` veio do banco) e são elas `nome_campo_cod_ts` e `prefixo`, e outras do próprio `JavaScript` e são elas `txt_chamada`, `txt_prefixo` e `txt_sufixo`.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/26947/discussion-between-maicon-herverton-and-pnet).
Answer: pnet, aproveitando a ideia do Maicom, você pode colocar as variáveis dentro de uma tag script na sua pagina ASP:

Porem fazendo desta forma, você vai enfrentar o mesmo problema que colocando em input:hidden, o usuario poderá alterar o valor vindos do ASP.
Então você pode fazer o seguinte para travar estes valores:

Agora que você tem todas estas variaveis em memoria, você pode trabalhar em um *.js separado.
var onum_seq_proposta_pj_ts = null;
var onum_seq_proposta_ts = null;
if (asp.ind_tipo_proposta_pj.trim() === "S")
    onum_seq_proposta_pj_ts = eval(txt_chamada + txt_prefixo + asp.prefixo + asp.nome_campo_cod_ts + txt_sufixo);
else
    onum_seq_proposta_ts = eval(txt_chamada + txt_prefixo + asp.prefixo + asp.nome_campo_cod_ts + txt_sufixo);

O problema do código acima é o uso do eval, eu particularmente não gosto de montar javaScript dinamicamente desta forma, então vamos abordar uma alternativa.
Quando falamos de javaScript no browser, todas as variáveis/funções globais são na verdade propriedades do objeto window.
Então todas as declarações abaixo são equivalentes:
var objeto = null;
window.objeto = null;
window["objeto"] = null;

no caso de uma chamada dinâmica, as duas primeiras formas não nos interessa, mas note a terceira, posso passar o nome da variável como uma objeto.
então no lugar de fazer algo assim:
var prefixo1 = "teste1.";
var prefixo2 = "teste2.";
var propriedade = "teste3";
var valor = eval(prefixo1 + prefixo2 + propriedade);

podemos ter algo assim:
var prefixo1 = "teste1";
var prefixo2 = "teste2";
var propriedade = "teste3";
var valor = window[prefixo][prefixo2][propriedade];

sendo que desta forma você pode avaliar o valor desta propriedade através do watch do browser (no caso do chrome/opera o "Chrome" DevTools [F12]).
Comment: Ok Toby, estou realmente fazendo avaliações e testes. tenho seguido o modelo anterior que você me ajudou(montou). Essa abordagem, meu líder gostou muito e disse que seguisse esse padrão. O Maicon não está fora dessa abordagem. Essa função é muito grande, eu postei uma pequena parte apenas, pois eu tenho que entender, aprender e fazer, por isso não postei tudo. Vou seguir a abordagem de ambos, fazer minhas devidas alterações e testar.
Comment: Apenas corrigindo uma informação anterior. Respondi que as chamadas asp vêm do banco, mas não, elas estão vindo do formulário chamador, dos campos, como uma CheckBox e etc... Apenas como subsídio.


MySQL concatenate based on field content

Question: I have a MySQL table with a structure like the following:

I'm looking for a select statement which will concatenate the last four fields as follows:
ID    Source
1     Search engine
2     Email
3     Coupon mailout
4     Relative of owner

I can think of a way to do this by using subqueries to choose the relevant fields to concatenate based on Type, nested subqueries to select values that are not NULL or 'Other', followed by JOINs, CONCAT()s and a UNION, but that seems a very complicated approach to the problem.
Am I overthinking this? Is there a simpler way?
Answer: If you can't fix your data, you can simply use IF() function. In my example, I'm using simple column names to make it a bit clearer:
mysql> SELECT IF(c1 IS NOT NULL AND c1 != 'Other', c1,
        IF(c2 IS NOT NULL AND c2 != 'Other', c2,
        IF(c3 IS NOT NULL AND c3 != 'Other', c3, c4))) FROM t1;

The above was tested.
You could make a Stored Function out of it if you need to use it often.
But, if you can, fix the table structure?
Comment: Thanks! I'd love to fix the structure, but sadly I'm stuck with it for the time being.
Answer: I reckon you'll need a few IFs and IFNULLs in there, something like:
SELECT ID, IF(Type='Online', IFNULL(OnlineSourceOther, OnlineSource), IFNULL(OfflineSourceOther, OfflineSource)) AS Source FROM referrals

Totally untested, YMMV, good luck, let us know how it goes.


How can I send an e-mail to the admin when use of a view results in an error?

Question: I have a large number of complicated views on a site, some of which, when searched with certain options or by certain users, give the following error:

An illegal choice has been detected. Please contact the site
  administrator.

Is it possible to somehow catch this error and email the admin?  Ideally, I would be able to include the URL of the view causing the problem and the UID of the user accessing the view for troubleshooting purposes.
Answer: You are describing hook_watchdog(array $log_entry):

This hook allows modules to route log events to custom destinations, such as SMS, Email, pager, syslog, ...etc.

emphasis mine.
Inside it, you can use $log_entry array to get UID and request URL, and you can also use global $user, and you can call current_path(), so both your requirements seems doable.
$log_entry array is defined as:

$log_entry: An associative array containing the following keys:

type: The type of message for this entry.
user: The user object for the user who was logged in when the event happened.
uid: The user ID for the user who was logged in when the event happened.
request_uri: The request URI for the page the event happened in.
referer: The page that referred the user to the page where the event occurred.
ip: The IP address where the request for the page came from.
timestamp: The UNIX timestamp of the date/time the event occurred.
severity: The severity of the message; one of the following values as defined in RFC 3164:

WATCHDOG_EMERGENCY: Emergency, system is unusable.
WATCHDOG_ALERT: Alert, action must be taken immediately.
WATCHDOG_CRITICAL: Critical conditions.
WATCHDOG_ERROR: Error conditions.
WATCHDOG_WARNING: Warning conditions.
WATCHDOG_NOTICE: Normal but significant conditions.
WATCHDOG_INFO: Informational messages.
WATCHDOG_DEBUG: Debug-level messages.

link: An optional link provided by the module that called the watchdog() function.
message: The text of the message to be logged. Variables in the message are indicated by using placeholder strings alongside the variables argument to declare the value of the placeholders. See t() for documentation on how the message and variable parameters interact.
variables: An array of variables to be inserted into the message on display. Will be NULL or missing if a message is already translated or if the message is not possible to translate.

There is no way I know to get form ID of a form that created your error, I don't think it is in ['variables'], so the best you can do is to parse ['message'] for "illegal choice", and test ['request_uri'] and ['referer'] for pages that are your suspects.
Comment: Thanks.  It looks like there's a lot of different possible causes for this error message.  Is there an efficient way to isolate causes of this specific error message?
Comment: @PatrickKenny answer updated