Why is the formula for the area of a cardioid $ \int_a^b \frac{1}{2} r^2 d \theta$

Question: I've seen this expression in many places :$\int_a^b \frac{1}{2} r^2 d \theta$ and was wondering if someone can explain where this came from? I've noticed that it's sometimes explained in conjunction with double integrals but I'm not very familiar with double integrals (as in what it means using a picture).
Comment: This formula is not just for the area for a cardioid, but a formula in general to calculate area of a polar equation. The derivation of this formula is based on adding up thinly sliced circle sectors drawn from the Origin to the curve, in the form of a Riemann sum. Look up the formula of the sector of a circle, where the sector spans a central angle measured in radians, and see the similarity between both formulas
Comment: your explanation makes sense
Comment: The area of a "pie wedge" of radius $r$ and angle $d\theta$ is exactly $\tfrac12 r^2 d\theta$.
Answer: There are at least two way to look at this formula. The simplest, in my opinion, is approximating the area inside the arc into small circular arcs.
$\hspace{3.5cm}$
The area inside each arc of radius $r$ and angle $\Delta\theta$ is $\frac12r^2\Delta\theta$ (this is proportional to $\pi r^2$ for the entire circle). Summing these approximations as $\Delta\theta\to0$ yields
$$
\int\frac12r^2\mathrm{d}\theta
$$

Another approach is to look at the Jacobian of the conversion from rectangular to polar coordinates.
$$
\mbox{
$\begin{align}
x&=r\cos(\theta)\\
y&=r\sin(\theta)
\end{align}
$}
\quad\text{and}\quad
\mbox{$
\begin{align}
\mathrm{d}x&=\cos(\theta)\,\mathrm{d}r-r\sin(\theta)\,\mathrm{d}\theta\\
\mathrm{d}y&=\sin(\theta)\,\mathrm{d}r+r\cos(\theta)\,\mathrm{d}\theta
\end{align}
$}
$$
That is
$$
\begin{bmatrix}\mathrm{d}x\\\mathrm{d}y\end{bmatrix}
=\begin{bmatrix}\cos(\theta)&-r\sin(\theta)\\\sin(\theta)&r\cos(\theta)\end{bmatrix}
\begin{bmatrix}\mathrm{d}r\\\mathrm{d}\theta\end{bmatrix}
$$
The determinant of the Jacobian yields
$$
\begin{align}
\mathrm{d}x\,\mathrm{d}y
&=r(\cos^2(\theta)+\sin^2(\theta))\,\mathrm{d}r\,\mathrm{d}\theta\\
&=r\,\mathrm{d}r\,\mathrm{d}\theta
\end{align}
$$
if we integrate in $r$ from the origin first, this yields the area to be
$$
\int\frac12r^2\,\mathrm{d}\theta
$$
Answer: Answer based on my answer to the question Explain $\iint \mathrm dx\,\mathrm dy = \iint r \,\mathrm \,d\alpha\,\mathrm dr$.
1. Area in Cartesian and in polar coordinates. Let $T$ be a bounded closed region of the $xy$-plane. If we decompose $T$ into $n$ rectangular cells the area $A$ of $R$ is the limit
$$ A=\lim_{n\to\infty}\; \sum_{i=1}^{n }\Delta A_{i}$$
which by definition of a double integral is equal to
$$A=\iint_T \mathrm{d}x\;\mathrm{d}y,\tag{1}$$
where $\Delta A_{i}$ is the area of a generic rectangular cell. The limits of integration are to be found in terms of $x,y$.

Figure 1: Generic $i^{th}$-cell in polar coordinates with the shape of a circle sector
Let's compute the same area using polar coordinates $r,\theta$. If we decompose $T$ into cells with a shape of sectors of a circle defined by two radii whose difference is $\Delta r_{i}$ for the generic $i^{th}$ cell and two rays making an angle $\Delta \theta _{i}$ with each other, the area of the  cell (see figure 1 above), using the formula of a circle sector, is
$$\frac{1}{2}\left[ \left( r_{i}+\frac{1}{2}\Delta r_{i}\right) ^{2}-\left(
r_{i}-\frac{1}{2}\Delta r_{i}\right) ^{2}\right] \Delta \theta
_{i}=r_{i}\Delta r_{i}\Delta \theta _{i},$$
where $r_{i}$ is the radius of the middle point of the cell. The same area $A$ can be expressed as the limit
$$A=\lim_{n\to\infty}\;\sum_{i=1}^{n }r_{i}\Delta r_{i}\Delta \theta _{i},$$
which by definition of a double integral is equal to
$$A=\iint_T r\;\mathrm{d}r\;\mathrm{d}\theta. \tag{2}$$
The limits of integration of $T$ are expressed in terms of $r$ and $\theta$. The relation between Cartesian and polar coordinates is
$$x=r\cos\theta,\qquad y=r\sin\theta.$$
In 2. and 3. we evaluate $(2)$ when $T$ is a circle and a cardioid.
2. Example. Area of a circle with radius $R$.  Observing that $r\in [0,R]$ and $\theta\in[0,2\pi]$ the integral $(2)$ reduces to
$$\begin{eqnarray*}A_{\text{circle}}=\int_{0}^{2\pi }\left( \int_{0}^{R}r\ \mathrm{d}r\right) \mathrm{d}\theta
&=&\int_{0}^{2\pi }\frac{R^{2}}{2}\ \mathrm{d}\theta\tag{$\ast$}\\ &=&\pi R^{2}.\end{eqnarray*}$$
Equation $(\ast)$ corresponds to the formula in the question. In this case $R$ is a constant.
3. Area of a Cardioid. To compute the area of a cardioid with equation $r=4a\cos ^{2}\frac{\theta }{2}$ (see figure 2 below) we need to find the limits of integration. From the figure we see that $r\in [0,4a\cos ^{2}\frac{\theta }{2}]$ and $\theta\in[0,2\pi]$. The integral $(2)$ reduces to
$$\begin{eqnarray*}
A_{\text{cardioid}}=\int_{0}^{2\pi }\left( \int_{0}^{4a\cos ^{2}\frac{\theta }{2}}r\ \mathrm{d}
r\right)\ \mathrm{d}\theta  &=&\int_{0}^{2\pi }\left( \left. \frac{r^{2}}{2}\right\vert _{0}^{4a\cos ^{2}\frac{\theta }{2}}\right)\ \mathrm{d}\theta\tag{$\ast\ast$} \\
&=&\int_{0}^{2\pi }\left( 8a^{2}\cos ^{4}\frac{\theta}{2} \right)\ \mathrm{d}\theta  \\
&=&6\pi a^{2}.
\end{eqnarray*}$$
Equation $(\ast\ast)$ corresponds to the formula in the question. Now $r$ is not constant, rather a function of $\theta$.

$$\text{Figure 2: cardioid }r=4a\cos ^{2}\frac{\theta }{2}$$
--
Added: The factor $r$ in $(2)$ is the Jacobian of the transformation. Here is an  evaluation:
$$\begin{eqnarray*}
\frac{\partial \left( x,y\right) }{\partial \left( r,\theta \right) }
&=&\det
\begin{pmatrix}
\partial x/\partial r & \partial x/\partial \theta  \\
\partial y/\partial r & \partial y/\partial \theta
\end{pmatrix}
\\
&=&\det
\begin{pmatrix}
\cos \theta  & -r\sin \theta  \\
\sin \theta  & r\cos \theta
\end{pmatrix}
\\
&=&r\cos ^{2}\theta +r\sin ^{2}\theta  \\
&=&r.
\end{eqnarray*}$$
Answer: All area calculations are double integrals. However, when we are given a curve that bounds our area we can make simplify our integral and convert it into a single integral.
In rectangular coordinates we do this when we calculate an area under a curve. Technically, we start with $$\int_{a}^{b}\int_{0}^{f(x)}dydx$$  and then do the integral in the $y$ direction to get $$\int_{a}^{b}f(x)dx$$
We can do the same thing in polar coordinates. We start with $$\int_{a}^{b}\int_{0}^{r(\theta)}\rho d\rho d\theta$$ and then we integrate in the $\rho$ direction to get $$\int_{a}^{b}\frac{r^2(\theta)}{2}d\theta $$
Comment: I just have an issue with the geometry of a double integral. What is $\rho d\rho$? I need a solid picture in my head to see what you're saying and what does it mean to integrate over two variables pictorially?
Comment: Look at [this](http://www.math.oregonstate.edu/home/programs/undergrad/CalculusQuestStudyGuides/vcalc/255pol/255pol.html) They use $r$ instead of $\rho$. I used $\rho$ so not to confuse it with the $r$ in the final answer.
Comment: It's may be best to group up $\rho \, d\theta$ together; this is the length of the circular arc spanning an angle $d\theta$.


Node.js - Como ler input do usuário pelo console?

Question: Em Java:
System.out.println("Diga algo: ");
Scanner leitor = new Scanner(System.in);
String resp = leitor.nextLine(); //ou nextInt, nextDouble, etc

Em C++
cout << "Diga algo: ";
string name;
cin >> name;

Como ler input pelo console no Node.js?
Answer: Usando o módulo readline:
var readline = require('readline');
var resp = "";

var leitor = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

leitor.question("Qual módulo pra ler dados no node.js?\n", function(answer) {
    var resp = answer;
    console.log("\nSua resposta '" + resp + "' foi grava com sucesso numa variável inútil");
    leitor.close();
});

Comment: Para o exemplo que tem que apenas precisa de saber o modulo a ler dados seria provavelmente melhor obter essa informação através de argumentos de entrada do programa.
Answer:

process.stdin.on('readable', ()=>{
  // reads what is being typed.
  let variable = process.stdin.read();
  // trying to read
  variable = variable.toString().replace(/\n/, "");
  variable = variable.replace(/\r/, ""); });

// Hope this helps


Module for getting what is visible from user's webcam

Question: I need a module that allows users to show what is visible from their webcam.
Is there a module that can do this?
Comment: I've done the best I can with the English, but for me this question still makes no sense.  Can you expand on what you are trying to achieve?  It sounds to me like you want to show the user the output from his/her webcam in the node body?
Comment: yes i want to registered user to open his camera (output in a node) to let the other users to show him.
Answer: I don't think there is exactly what you want at the moment, but the following module might help you on your way:
Webcam field - This is still in development

Webcam field provides dynamically updating webcam image fields. This
  module is compatible with Colorbox.

Videochat - Has no recommended release, although seems to have a full 3.6 version

The Video Chat module adds a fully hosted free video chat to a Drupal
  website. The chat application and video hosting are courtesy of
  Camamba and ad-supported. We hope it provides an alternative to all
  the payware chat modules out there.

Media: Webcam - This is in beta

This project (still under active development) will add a Webcam
  capture tool for video and images to FileField. Video requires a Red5
  or Flash Media server to also be available; documentation for this
  coming soon enough.

Video conference - This requires some further set up of server components, but if you want live video streaming I should imagine you're aware that you will most likely need a RTMP protocol set up.

VideoWhisper Video Conference is a modern web based multiple way video
  chat and real time file sharing tool. It can be used stand alone or
  integrated as extra feature to existing sites. Internet based video
  conference software is great for bringing physically distant people
  together in meetings, trainings, conferences, live events, recruiting,
  consultations, coaching and of course casual community chat.

Paid solution
AVChat
This comes at a price of $285 plus $49 for the Drupal module
Comment: This seems like a great answer. Just one extra item worth mentioning that you could incorporate into your answer: https://www.drupal.org/sandbox/mdryan/2096387 which uses modern javascript/html to create a new file field input formatter.


Fender Rhodes - cable confusion

Question: I have disassembled and reassembled my Fender Rhodes piano. Sadly there is one cable for which I have forgotton to note where I have to plug it in.
Here is a photo.

Its not the cable which connects the input jack to the harp. Its coming from the backside of the jack of the harp.
It looks like it is going to be used like a washer. Maybe it is some sort of grounding.
Can someone help me with this?
Comment: Looks like an earth or ground wire. If the mains plug already has an earth attached to it, there's probably no need to put it anywhere. If the piano works and sounds fine without it, leave it. You may want to touch it onto metal on the piano, listening for hum (or lack of hum). Screwing it onto the frame would maybe mean it doesn't short anything out. - or put it into a plastic sleeve.
Answer: You do need to put it somewhere. It's designed to trap into a screw or nut/bolt on the main frame, so it's properly grounded. The patterning is to prevent vibration from shaking it loose, so if you find any screw without a similar washer, that's probably the one.
The only nut I can see in the image looks like a nylock, or similar 'self-trapping' design which should also stay where it's put, so you're looking for one without that design, a plain screw or nut/bolt that would need that washer type to prevent shaking loose.

Fender Rhodes - cable confusion


Looking for advice on programs to open huge text files

Question: I have several files which I need to examine I'm currently using ultra edit and it works but I'm looking for something that can deal with a really big file a little better than ultra edit.  It is entirely too slow and crashes a lot.  The sizes of the files are 10+ GB.  I've tried hex editor but it gives me the information in the wrong format. Any suggestions>?
Comment: I think this belongs more on http://programmers.stackexchange.com/ than here. I think you're more likely to get the answer you want.
Answer: I use Vim and the LargeFile plugin for big files I need to edit.
Answer: You can try Sublime Text to open file.


username.domain profile in AD environment

Question: Environment: an AD domain (level W2K8) with Vista desktops and W2K8 servers and an AD domain (level W2K3) with XP desktops on W2K3 servers.
Every now and again, I notice a user that has his local profile located under C:\Users\username.domain instead of C:\Users\username
I know that can happen when the users logs in on domain A from a workstation located in domain B, but I've seen this happen a bunch of times where the .domain is the same as the workstation's domain.
When this becomes a problem, we usualy remove the local profile and have the user log on again, after which the profile is loaded correctly.
I've checked the eventviewer multiple times but have not found any entries relating to this.
The question: what is causing this behavior?
Comment: Why is this a problem anyway? If you're referencing the path in scripts, you should be referencing `%userprofile%` instead of the full path.
Comment: We have a couple of applications that don't play nice with this...It's not always a problem, I just would like know what's causing this.
Comment: You've got good background info here, but what exactly is your question?
Answer: If a user profile is created at C:\Users\username.domain (or C:\users\username.domain001) then its because there was already a folder or profile at C:\users\username (or at least windows thinks so).
Answer: The most common reason in my environment is that network connectivity was interrupted (in most cases, the user power cycles the PC) while loading a roaming profile, and critical files (namely the registry) became corrupt, rendering the profile unable to load on subsequent attempts.
An ACL will do it, if the user is unable to load the profile in that directory (access denied).
IMO, corruption is the most likely candidate.
In any case: this should not be a problem. If you have scripts or applications that rely on the user profile residing at a specific location, they are broken, and need to be fixed. I understand implementing a workaround, but still, try to fix the problem.


Loading content alone for each page from drupal to other site?

Question: How to load only content in a page (exclude header & footer) from once specific drupal site to another non-drupal site page.
Like, if I click on link on non-drupal site it should open up drupal content of respective link page without header and footer in a new popup.
I know Iframe and webservice are options to do.
Is there any other way to load content for specific page in drupal to non-drupal site ? Thanks in advance.
Answer: You could create a custom HTML template that would remove the HTML tags but that would render on a certain URL. However, that would make that URL every time it rendered. Web services are your best bet rendering the information an XML format. Below is the services module for Drupal 7
https://www.drupal.org/project/services
Answer: In your theme's page.tpl.php, you could do this.
<?php if (isset($_GET['embed'])) {
    print render($page['content']);
} ?>

<?php (!isset($_GET['embed'])): ?>

    the contents of your page.tpl.php file

<?php endif; ?>

That means you can add ?embed=true (or just ?embed) to a url and only the content blocks / node etc. will show.
I do similar to this for some node edit forms that I load in an iFrame inside a modal, like below.
page--node--article--edit.tpl.php
// just an example file path.

<?php

if (isset($_GET['modal'])) {
    print render($page['content']);
} else {
    include(drupal_get_path('theme', 'mytheme').'/page.tpl.php');
}
?>


Change colors based on value

Question: I am currently creating a grade management system and i need your help with a forEach function.
This is my code and i am trying to change the color based on the grade. As you may guessed it's not working. The error that i get is gradeid.forEach is not a function

let gradeid = document.querySelector(".gradeid");
 console.log(gradeid);

  gradeid.forEach(function() {
    if ({{grades.0.grade}} >= 5) {
      gradeid.style.color = "#00d629";
    }
  else if ({{grades.0.grade}} < 5 && {{grades.0.grade}} >= 4) {
    gradeid.style.color = "#ffce00";
  } else {
    gradeid.style.color = "#D50000";
  }
  });

Thank you for helping
PS: Dedadline is tomorrow
I tried a lot but failed.
Answer: You're using document.querySelector() which returns a single element, that's why you're getting that error. You can't use forEach on a single element.
Try using querySelectorAll() to select multiple elements and get a list which can be iterated.
{{grades.0.grade}} This should be an error too.
You access it like this: grades[0].grade
Comment: Thank you for your help!

Unfortunately it doesn't work.

The error is:

5:51 Uncaught TypeError: Cannot set properties of undefined (setting 'color')
    at 5:51:25
    at NodeList.forEach ()
    at 5:44:11

I added a value to each grade to then access it in the script but it's still undefined
How can i access multiple values of a html document?
Answer: You can change your code as below.
let gradeids = document.getElementsByClassName("gradeid");
 console.log(gradeids );

Array.prototype.forEach.call(gradeids, function(gradeid) {
 if ({{grades.0.grade}} >= 5) {
  gradeid.style.color = "#00d629";
 }
 else if ({{grades.0.grade}} < 5 && {{grades.0.grade}} >= 4) {
  gradeid.style.color = "#ffce00";
 } else {
  gradeid.style.color = "#D50000";
 }
});

Comment: Thank you for your work.

It almost works perfectly. However it's just taking the first grade and colors the other based on the first one.
Comment: Can you share the grades data structure?

Change colors based on value


Webform tokens for submitted images

Question: I'm theming the email that a webform submission generates, and I want to create fqdn'd links to the images that the submitter has uploaded.
I used [submission:values:photo:nolabel], but that generates a url which links to http://sites/default/files/webform/index1_7.jpg. Obviously that URL is broken. Because it's a token string, I can't manipulate it with php string manipulation functions, to take off the http:// part.
The same thing happens with [submission:values:photo_2].
I want to get just the path part, so that I can construct a proper link. I've looked in "Available Tokens" under the webform configuration, but that just lists what I've already tried.
What token gives me just the path to the image on the site?
Answer: It turns out that there is some later template processing, or perhaps an email client display issue, that is causing my links to be displayed as relative paths.
However, in arriving to this conclusion, I was able to construct the URL from the submitted values.
First, get the ids of the webform components that are  uploaded files. These are in the $submission->data array.
Then, load each like so:
foreach ( $fids as $fid ) {
    $file = file_load($fid);
    $url = file_create_url($file->uri);
}

Webform tokens for submitted images


What is the relation between the coprime groups and direct product groups?

Question: Let $U(n)$ be the set of positive integers that are less than $n$ and coprime to $n$. This set forms a group with multiplication modulo $n$.
Consider $U(15)$ and $U(20)$. Both have order 8, and both are isomorphic to the $\mathbb{Z}_4 \times \mathbb{Z}_2$.
What's the underlying connection? Is there a general result showing how the coprime groups are related to other groups?
Comment: You mean all *positive* integers, right?
Answer: $U(n)$ is always Abelian, so it is a direct product of finite cyclic groups. If $n=uv$ where $(u,v)=1$ then by the Chinese remainder theorem, $U(n)$ is isomorphic to $U(u)\times U(v)$. Finally for every prime $p$, $U(p)=\{1,...,p-1\}$, a cyclic group of order $p-1$ because $\Bbb Z/p\Bbb Z$ is a field and every finite subgroup of the multiplicative group of a field is cyclic. This explains your examples and many others.
Addition You may also use the fact that if $n=p^k$ or $n=2p^k$, $p>2$, prime, then $U(n)$ is a cyclic group of order $p^{k-1}(p-1)$. This is a standard fact
Comment: Your addition needs $p>2$. For $p=2$ we have $U(2^n)\cong C_2\times C_{2^{n-2}}$ (if $n\ge 2$).
Comment: OK, fixed. Thanks!


How to show tooltip value at the position of the mouse in Bootstrap slider

Question: I try to implement a replay function with bootstrap slider. The values represent time. It works just fine.
I need a hover tooltip.
When you move the slider handle the tooltip shows the value for the given position. But when you hover the mouse before a click on the slider there is no feedback for the new value.

Is there any way to attach an event to the hover and get the value back?
Answer: I found a hack to my problem. It is not stable as I use two non documented function _getPercentage, and _toValue.
I have to change to the non jquery usage, to access the non documented functions. There is some additional functionality. I can switch off the update of the slider with SliderUpdateEnabled during slider manipulation. And I can switch off the mousemove event during slider handler movement. The tricky part is in the mousemove event.
<code>var slider = new Slider("#replaySlider", {
    formatter: function(value) {
        return moment(value).format("MM.DD. HH:mm:ss");
    }
});
this.slider = slider;
slider.on('slideStart', function() {
    sm.controller.setSliderMove(true);
    sm.controller.setSliderUpdateEnabled(false);
});
slider.on('slideStop', function() {
    var value = slider.getValue();
    sm.controller.setPlaybackTime(value);
    sm.controller.setSliderUpdateEnabled(true);
    sm.controller.setSliderMove(false);
});

$(".slider-track").on("mousemove",function(evt) {
    if (sm.controller.isSliderMove()) {
        return;
    }
    sm.controller.setSliderUpdateEnabled(false);
    // gets the percentage from the pointer event
    var percent = slider._getPercentage(evt)
    // moves the tooltip to the pointer position
    $(".replayShow").find(".tooltip-main").css("left", percent+"%");
    // updates the text in the tooltip
    $(".replayShow").find(".tooltip-inner").html(moment(slider._toValue(percent)).format("MM.DD. HH:mm:ss"));
});
$(".slider-track").on("mouseout",function(evt) {
    if (sm.controller.isSliderMove()) {
        return;
    }
    sm.controller.setSliderUpdateEnabled(true);
});
</code>
It works now as expected.


Contador e calculo em javascript

Question: Preciso pegar um valor e dividir pela quantidade digitada no input

R$ 4.000,00

Pegar esse valor e dividir pela quantidade digitado aqui:

    -
    <input type="text" class="count" name="qty" value="1">
    +

E mostrar o resultado:

Individual

R$ 4.000,00

Answer:
id nos elementos por serem de identificação únicos
input type="number" min="1"
forma dinamica: função onchange
toLocaleString('pt-BR') - converte Numero para String currency nativo. Detalhe, legal, está seguro contra o bug do ponto flutuante

    // Resultado bugado
    console.log(0.1+0.2);
    // Resultado sem bugs
    console.log((0.1+0.2).toLocaleString());

Código

//função para converter o valor em um numero que se possa utilizar em operações aritméticas.
function converteMoedaFloat(valor){

     if(valor === ""){
          valor =  0;
      }else{
          valor = valor.replace("R$ ","");
          valor = valor.replace(".","");
          valor = valor.replace(",",".");
          valor = parseFloat(valor);
       }
       return valor;
}

function calcular(){
    var valortotal=document.getElementById('valortotal').innerHTML;

    var valorConvertido = (converteMoedaFloat(valortotal));

    var qty=document.getElementById('qty').value;

    var result =(valorConvertido/qty);

    document.getElementById('resultado').innerHTML= (result.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }));

}

R$ 4.000,80

        <input type="number" class="count" id="qty" name="qty" value="1" min="1" onchange="calcular()">

Individual

R$ 4.000,80

Answer: Se você quiser apenas logar o valor e mudar a quantidade a ser dividida pelo valor, pode fazer desta maneira:

let valortotal = 4000;

    let calc = valortotal / document.getElementById('qtde').value;
    console.log('R$'+calc);

R$ 4.000,00

    -
    <input type="text" class="count" name="qty" id="qtde" value="4">
    +

Individual

R$ 4.000,00

Agora, se quiser fazer de uma forma mais dinâmica, pode fazer da seguinte forma:

let valortotal = 4000;

    document.querySelector('#qtde').addEventListener('keypress', function (e) {
        let key = e.which || e.keyCode;
        if (key === 13) {
            let calc = valortotal / document.querySelector('#qtde').value;
            //console.log('R$'+calc);

            document.getElementById('resposta').innerHTML = `R$`+calc;

        }
    });

R$ 4.000,00

    -
    <input type="text" class="count" name="qty" id="qtde">
    +

Individual

R$ 4.000,00

Quando digitar o valor que deseja dividir os 4000 e pressionar enter, o valor aparecerá na div com id "resposta", futuramente poderá colocar a ação do enter em um botão para o layout ficar mais bonito, porem acredito que tirei suas duvidas
Espero ter ajudado ^^
Comment: Otima ajuda, parabéns

Contador e calculo em javascript


Understanding the Fundamental Theorem of Galois Theory (Artin's Text)

Question: Note: I'm using Emil Artin's free text on Galois Theory to understand the Fundamental Theorem of Galois Theory.
Hypothesis: Let $F \subset E$ s.t. $E$ is the splitting field for separable $p(x) \in F[x]$.  Let $F \subset B \subset E$.
Question: At the beginning of the very last paragraph on page 48, Artin states that

$B$ is a normal extension of $F$ if and only if each isomorphism of $B$ into $E$ is an automorphism of $B$.  This follows from the fact that each of the above conditions are equivalent to the assertion that there are the same number of isomorphisms and automorphisms.

This isn't obvious to me at all.  How do I make sense of this?
What I DO understand that might be relevant:
I do understand that if $B$ is normal over $F$, then
$$
\underbrace{|G(B:F)| = (B/F)}_{\text{since $B$ normal over $F$}} = [G(E:F) : G_B]
$$
I also understand that the elements of $\{\sigma G_B : \sigma \in G(E : F)\}$ can be viewed as equivalence classes of distinct $B$ isomorphisms (when the domain's of the elements of these equivalence classes are restricted to $B$).
Answer: I think Artin's text, while legendary, is not suitable for today's audience. There are not many examples, and the notation he used was out of dated. Maybe you should check a relatively common one like Dummit and Foote. I wrote this from the perspective that I learned Galois theory from Artin's text myself for the first time.
For your question, you can think a normal extension as the splitting field of $f(x)$ over $F$ in $E$. Each isomorphism that maps $B$ to $B_{i}$ in $E$ merely permuted the roots of $f(x)$. Therefore all $B_{i}$ must be the same. This only holds for separable extensions, and for non-separable ones you need a family of $f_{i}$s. However the proof should carry through with small modifications.


When will $Hom_R(V,W)\cong V^*\otimes W$ also work for modules?

Question: $Hom(V,W)\cong V^*\otimes W$ works for finite dimensional vector space, when will it also work for modules over ring $R$?
The motivation (i.e. the question is more general than this) is to know whether and why this works for the $C^\infty(M)$-module of sections of a vector bundle which is not vector space since $C^\infty(M)$ is not a field.
It seems that $R$ has to be commutative, and the module also need to be finitely generated or even projective (since Serre–Swan theorem seems to be related). Is that enough and what is the minimum requirement?
Comment: You don't need $R$ commutative, you just want $V$ to be a finitely generated projective $R$-module i.e. a locally free finitely generated bundle.
Answer: Let $R$ be a ring (need not be commutative) and let $M$ and $N$ be left $R$-modules. As usual set $M^* = \hom_R(M,R)$ with its canonical right $R$-module structure. There is a natural map
$$\Psi_{M,N} : M^* \otimes_R N \longrightarrow \hom_R(M,N)$$
such that $\Psi(f\otimes x)(y) = f(y)x$.

Lemma. Fixing $M$, this map is an isomorphism for all $N$ if and only if $M$ is finitely generated and projective.

You can find this, for example, proved in Bourbaki's algebra book.
Indeed, it is standard the following are equivalent:

$P$ is finitely generated and projective
$P$ admits a finite dual basis, that is, there exist $(x_i,y_i) \in P\times P$ for $i\in [n]$ such that for each $x\in P$ we have that $x = \sum_{i=1}^n y_i(x) x_i$ or, what is the same,
We have that $\Psi_{P,P}(u) = 1_P$
for some $u= \sum_{i=1}^n y_i\otimes x_i\in P^*\otimes_R P$.

Proof of the Lemma: if $\Psi_{P,Q}$ is an isomorphism for all $Q$, picking $Q=P$ and covering the identity gives you a dual basis for $P$, by 3. so that $M=P$ is projective.
Conversely, if you have a dual basis, given a map $f: M\to N$, consider the element $\Phi(f) = \sum_{i=1}^n y_i \otimes f(x_i)$. It follows that
$$\Psi(\Phi(f))(x) = \sum_{i=1}^n y_i(x)f(x_i) = f\left( \sum_{i=1}^n y_i(x)x_i\right) = f(x)$$
and that for $g = \Psi(f\otimes x)$
$$\Phi(g)  = \sum_{i=1}^n y_i(-)\otimes f(x_i)x =
               \sum_{i=1}^n y_i(-)f(x_i)\otimes x =
                 f   \otimes x$$
so that $\Psi$ is an isomorphism.

Note that dual bases are a bit less canonical than actual bases of free $R$-modules, so the map $\Phi$ above is not unique.


Why are NFL players introduced with their college team?

Question: At the beginning of many prime time NFL games, the starting players say their names and the college they attended. Why are the college names announced?
Many of these players have been in the league for many reasons, and may have even played in multiple NFL teams since they left NCAA.
So what is the reason behind mentioning the college names? Do the colleges sponsor the NFL or the broadcasting stations for this?
Answer: To understand this phenomenon, you need to know something about the culture of sports in the US.
First: there is no promotion/relegation system for professional sports. This means that in any particular sport, most of the US has no local professional team at the highest level. And if you are not living near a major metropolis, you are not likely to ever get one. There are 32 NFL teams with no expansion on the horizon.
Conversely, there are 128 teams at the top level of NCAA football (Football Bowl Subdivision). Over 97% of the population1 lives in a state with at least one school which plays at the FBS level. This gives nearly everyone in the US some kind of local team to root for. (And unlike NFL games, it's actually affordable to go to a college game.)
Second: NFL teams are not a constant. College teams are. NFL franchises, unlike European football clubs, are not tied to a city. Just in the last two years, three different franchises either moved (St. Louis Rams to Los Angeles, San Diego Chargers to Los Angeles) or announced plans to move (Oakland Raiders to Las Vegas). Or look at Baltimore: the old Baltimore Colts won three NFL championships and a Super Bowl, then moved to Indianapolis and won another Super Bowl. The Cleveland Browns moved to Baltimore, changed their name to the Ravens, and won a couple of Super Bowls; meanwhile, a new Cleveland Browns team was formed to replace them.
Colleges don't do that. If you live in Alabama and your grandpa's grandpa lived in Alabama, you're still rooting for the same school that he did. Or maybe you did switch from Alabama to Auburn (or vice versa), and that could cause tension at family gatherings for years because the rest of your family is still loyal. This happens all over the country, but most particularly in the South (source: anecdotal).
It is also important to note that perhaps none of you actually went to the school that you cheer for. You may have gone to another major school, a small school, or no college at all. College attendance is not a prerequisite to college fandom.
Third: College sports predated professional sports by decades. I touched on this in the last point. College sports are more established, though the NFL has better television deals now. People grew up watching their team.

All of that is to tell you this: in large swaths of the United States, people watch the NFL -- but they care about college football.
I personally know people who root for a particular NFL team that's halfway across the country and isn't particularly good, just because they have players that went to the local university. The players know this, the networks know this, and they give the people what they want.2

Footnotes:
1 Eight states do not have an FBS team: New Hampshire, Maine, Rhode Island, Montana, Delaware, the Dakotas, Alaska, and Vermont. The combined population of those states is less than 9 million out of the 322 million living in the fifty states.
2 I'm not even touching here on the secondary issue of "my school is better than yours because we put more players in the pros". This answer is plenty long enough already. That's also why I didn't mention Division 2 football or try to address cultural differences in the South vs. Northeast vs. West, etc.
Comment: @Nij: In states as large as you describe, the "local" school is almost always called " University". That brings the powerful force of state loyalty into play, which usually trumps geographic proximity.
Comment: It's a bit of a stretch to call a team "local" because they're within the same enormous chunk of land, despite being hundreds of kilometres away. There are regions where a person in one state is closer (by a significant margin) to the teams of at least three other states than "their" one.
Answer: there is no need for them to mention the college that they went to. Some players mention the high school that they went to and some have even mentioned their middle school or elementary school. The school as part of the introduction is just done to give the players a chance to give a shout out to their schools and is a way of giving back to the schools that they went to and helped them have a career.
Answer: To piggy-back on Michael's comment, people like their NFL team, but they LOVE the college teams. There's much more emotion involved in college sports in the U.S. and people will like or dislike a player specifically because of the college they went to. Outside of the college, the conference pride (SEC, Big 10) is big as well.
Saying the college is a way to show their pride in their school or conference. Yes some have said High School, I've never heard anyone say anything less, but that probably has to do with the High Schools that are football factories.
Answer: The concept of noting your University is to emphasize you are a professional.  Your Alma mater was where you earned your sheepskin in order to ply your trade.  It is most evident in football players, but take a look in your doctor/dentist/lawyer offices - they each proudly display where they attended university.
When a football player opts to indicate his high school and yes even his grammar school, he has missed the point entirely.
Answer: Which college you attend can influence one's view of how good a player is at first sight,
IE: If you see someone drafted straight out of high school, you assume that they would be very good to make the leap from High School to the NFL.
If you see someone who was attending a good university, you know that they must have been good to get a sports scholarship at a large university.
It can also be used for trivia, like on TNF when Terry Bradshaw plays trivia. It is a fun fact to know about your favorite player, and test really how much you like a player.
It can also influence which college you could go to.
IE: If you see that your favorite player is from Davidson, at a young age you will be determined to go to that college.
It is most likely used for online marketing for college, and just is a great fact to know


Expectation conditioned on multiple independent variables

Question: I'm trying to figure out whether:
$$
\mathbb{E}\left[X\mid Y, Z\right] = \frac{\mathbb{E}\left[X\mid Y\right] * \mathbb{E}\left[X\mid Z\right]}{\mathbb{E}\left[X\right]}
$$
if $Y$ and $Z$ are independent. This is true for probabilities with Bayes' Rule, and seems intuitively plausible, but I'm having trouble proving it here for expectations. Any thoughts?
Comment: @AaronMontgomery Oops yes - fixed, sorry!
Comment: Do you perhaps mean "if $Y$ and $Z$ are independent"?
Answer: No, it generally doesn't hold. Let $Y$ and $Z$ be two i.i.d. Bernoulli(1/2) random variables and let $X = Y+Z$. Then,
$$E[X|Y,Z] = Y+Z \neq (Y+1/2)(Z+1/2) = \frac{(Y+1/2)(Z+1/2)}{1} = \frac{E[X|Y]E[X|Z]}{E[X]}.$$
It does hold when $X,Y$ and $Z$ are all mutually independent. Or more generally when $X$ is independent of $Z$ and also conditionally independent of $Z$ given $Y$.
Edit: fixed a typo in the last sentence
Comment: Great counterexample - makes sense. Thank you!


Efficient Formula for $\zeta(3)$

Question: I was messing around with Desmos to find an exact form for $\zeta(3)$ and was using the following triple integral form:
$$
\zeta(3)=\int_0^1{\frac 1 z\int_0^z{\frac 1 y\int_0^y{\frac 1 {1-x}}}}dxdydz
$$
I set it to $a$ in Desmos, and evaluated:
$$
\frac {\ln{\big(\frac \pi 2\big)}}{a^3}
$$
To my surprise, Desmos actually gave me a fraction option for the value, which was  $\frac  {238072} {915685}$. Skeptical, I searched Wolfram Alpha for:
$$
\sqrt[3]{\frac {915685} {238072}\ln{\big(\frac \pi 2\big)}}-\zeta(3)
$$
and it gave me an error of $\approx2.098\times10^{-16}$. So I only found an approximation, not an exact form, which doesn't surprise me.
This begs the question: How can I more accurately represent $\zeta(3)$ in Desmos? Any thoughts would be much appreciated.
Comment: Have you taken a look at the fast-converging series representations listed here? https://en.wikipedia.org/wiki/Ap%C3%A9ry%27s_constant#Fast_convergence
Comment: @DanielHast I have $seen$ these but haven't used them in Desmos, due to it not being able to precisely evaluate infinite series oppose to integrals (or so I thought), based on my chosen form for $a$, but it makes sense that you can only get so precise especially with computer assistance. I was looking through the article and saw the Ramanujan series which gets surprisingly close very fast, so I'm sure the others will be useful as well, thanks for steering me in this direction!
Answer: Desmos probably utilized a continued fraction expansion of the machine precision value of $\frac{\log \pi/2}{\zeta(3)^3}$ to obtain an efficient rational approximation.  Specifically, the sequence of convergents is:
$$\left\{0,\frac{1}{3},\frac{1}{4},\frac{6}{23},\frac{7}{27},\frac{13}{50},\frac{774}{2977},\frac{787}{3027},\frac{1561}{6004},\frac{78837}{303227}, \color{red}{\frac{238072}{915685}}, \frac{2086065701}{8023535197}, \ldots \right\}$$
The next convergent in the sequence yields an absolute error of about $1.2 \times 10^{-20}$.
For whatever reason, you chose the function $$f(a) = \frac{\log \frac{\pi}{2}}{a^3}$$
from which to compute a rational approximation, but other functions can also be chosen.  For instance, zeta functions evaluated at positive even arguments are rational multiples of a corresponding even power of $\pi$; e.g.,
$$\zeta(2) = \frac{\pi^2}{6}, \quad \zeta(4) = \frac{\pi^4}{90}, \ldots.$$
I believe it remains an open question if odd arguments of the zeta function show similar phenomena, i.e., if they are rational multiples of an odd power of $\pi$.  To investigate, we could compute the convergents for the choice of function $$g(a) = \frac{a}{\pi^3}$$ at $a = \zeta(3)$ which gives
$$\left\{0,\frac{1}{25},\frac{1}{26},\frac{4}{103},\frac{5}{129},\frac{34}{877},\frac{107}{2760},\frac{141}{3637},\frac{248}{6397},\frac{637}{16431},\frac{885}{22828},\frac{9487}{244711},\frac{29346}{756961}, \ldots \right\}$$
but computing additional terms requires increasingly high numerical precision of $\zeta(3)$ and $\pi$.  If such a rational number existed, the sequence of convergents would terminate.

I should also point out that the convergent $\frac{238072}{915685}$ happens to be an "unusually good" approximation in the sense that the size (number of digits) of the denominator is small compared to the number of decimal places the convergent matches the precise value.  This is observable from the continued fraction expansion
$$\frac{\log \pi/2}{\zeta(3)^3} = \frac{1}{3 + \frac{1}{1 + \frac{1}{5 + \frac{1}{1 + \frac{1}{1 + \frac{1}{59 + \frac{1}{1 + \frac{1}{1 + \frac{1}{50 + \frac{1}{3 + \frac{1}{\color{red}{8762} + \frac{1}{\ddots}}}}}}}}}}}}$$
When the expansion term has a large value, this means it gets "close" to being a rational number.  So the aforementioned convergent--the one that Desmos found--is the one that stops just before $8762$; i.e., it simply lets the part $$\frac{1}{8762 + \frac{1}{2 + \frac{1}{7 + \frac{1}{\ddots}}}} \approx 0.$$
To give you an idea of just how good this approximation is, $8762$ is the $11^{\rm th}$ term in the continued fraction expansion (not counting the initial $0$ since we are dealing with a number that is less than $1$).  The next time we see a number in the expansion sequence that is at least as big is at the $9231^{\rm st}$ term, when it is $18858$.  I am not sure how much precision is attained for the corresponding convergent.
Comment: Fascinating! Thanks for the insight, what are you using to come up with these continued fraction values?
Comment: @AndrewSotomayor Mathematica efficiently calculates continued fraction expansions; e.g., `ContinuedFraction[Log[Pi/2]/Zeta[3]^3, 10000]` gives $10000$ terms in the expansion, and `Convergents[Log[Pi/2]/Zeta[3]^3, 20]` gives the first $20$ convergents from that expansion.
Comment: I need to get on that, thanks!
Answer: We grab the bull by the horns and work with the continued fraction for $\zeta(3)$ itself.
The partial quotients are available from OEIS A013631, and from these we get the convergents below.
$\dfrac11,\dfrac54,\dfrac65\dfrac{113}{94},\color{blue}{\dfrac{119}{99}},\dfrac{232}{193},\dfrac{351}{292},\dfrac{1636}{1361},\dfrac{1987}{1653},\color{blue}{\dfrac{19519}{16238}},\dfrac{177658}{147795},\dfrac{374835}{311828},\dfrac{552493}{459623},\dfrac{927328}{771451},\dfrac{1479821}{1231074},\color{blue}{\dfrac{3886970}{3233599}},...$
Certain of these are colored blue. If we regard an integer in a computer as being represented by $k$ bytes and one of the bits is used for the sign, then with one-byte representation we can use numbers up to $2^7-1$, wuth two-byte representation we can go up to $2^{15}-1$, and with three bytes available we can go to $2^{23}-1$. The blue numbers represent the maxium numerator and denominator within these respective bounds.
So how did we do? Below are the values of the blue fractions, rendered to as many decimal places as would match the exact value of $\zeta(3)$. Thus if we allow $15$ bits plus the sign bit (two bytes), the accuracy to eight decimal places actually corresponds to about $25$ bits in base two. The three-byte limit gives about $40$ bits of accuracy.
$119/99 \approx 1.202$ (the next decimal place is correctly $0$, but the rounded number to four decimal places is $1.2020$ and $\zeta(3)$ rounds to $1.2021$)
$19519/16238\approx 1.20205690$
$3886970/3233599\approx 1.2020569031596$

Efficient Formula for $\zeta(3)$


Envio de formulário e array fora de form via post

Question: Tenho o seguinte problema: Necessito enviar via post os dados de um formulário juntamente com os dados de uma tabela html ao qual monto um array em javascript.
Infelizmente, não faço a ideia de como proceder nesse caso.
Peço auxílio dos colegas neste desafio.
Answer: Eric, temos duas opções:

Serializar os campos enviados dos campos utilizando o nome do campo como prefixo:
Construir manualmente a array com os campos enviados utilizando o nome do campo como prefixo:

- MANEIRA "SERIALIZAR COM PREFIXO DE NOME"
Sejam dois campos com prefixo "campo"
<input type="text" name="campoNome">
<input type="text" name="campoEmail">

Então, salvamos em uma variável o objeto contendo os dados dos campos:
var camposEnviados = $("input[name^='campo']").serialize();

- MANEIRA "CONSTRUIR MANUALMENTE"
Podemos construir a array manualmente (selecionando campo a campo o seu valor):
var camposEnviados = [];
camposEnviados[0] = $('campoNome').val();
camposEnviados[1] = $('campoEmail').val();;

- ENVIANDO VIA AJAX
$.ajax({
   type: "POST",
   data: {camposEnviados: camposEnviados},
   url: "index.php",
   success: function(msg)
   {
     $('.resposta').html(msg);
   }
});

Comment: Olá Felipe! Sua ideia e explicação me ajudaram muito na montagem final do processo. Acabei optando por lançar o array no value de input do tipo 'hidden' e na hora do submit. Muito obrigado pela ajuda! Grande abraço!
Comment: Eric, bom dia! Que bom que resolveu! Abraço
Answer: Tens duas opções,

enviar tudo via AJAX
enviar os dados da tabela num input escondido

Se enviares por ajax podes usar o .serialize() do jQuery e enviar no ajax algo assim:
var fData = $('form').serialize();
$.ajax({
   type: "POST",
   data: {form: fData, table: JSON.stringify(tDada)}, // onde tData é a array da tua tabela
   url: "index.php",
   success: function(msg)
   {
     $('.resposta').html(msg);
   }
});

se quiseres colocar esses dados da tabela dentro de um campo escondido:
<input type="hidden" name="tabela" id="dadosTabela" />

e depois injetas no valor do input os dados da tabela:
$('dadosTabela').val(JSON.stringify(fData));

Comment: Sergio, você salvou meu projeto! Rs. Eu já havia tentado colocar o array no campo tipo hidden. Mas tive dificuldades em aproveitar os dados depois do post, no lado do php. A sua solução de enviá-lo via JSON que tornou o processo funcional. Muito obrigado pelo apoio! Devo-lhe uma!


python - how to append to a dictionary where the dictionary name is a variable

Question: I have a list of dictionaries that I am iterating through. Each of the dictionaries  has the same set of keys. I want to be able to append each item in the list to a new set of 7 dictionaries where the 7 dictionaries are each elements of a specific key.
For example if the dictionaries in the list has a key called 'houses' with values 'Dis' 'Brobnar', I want to have dictionares called 'Dis' and 'Brobnar' that will contain the entire dictionary.
Here's what I've tried, but it fails with an error message -
cards = [
{'house':'Dis','card_title':'Bob'},
{'house':'Brobnar','card_title':'Fred'},
]

Dis = {}
for i in cards:
    if i['house'] == 'Dis':
        i['house'].append(i)

error
i['house'].append(i)
AttributeError: 'str' object has no attribute 'append'

wanted results
Dis = [
{'house':'Dis','card_title':'Bob'},
]
Brobnar = [
{'house':'Brobnar','card_title':'Fred'},
]

Comment: Dynamically creating variables is almost always a bad idea. I suggest you to wrap everything inside another dictionary, such that the house names become keys.
Comment: `i['house'].` gives you a string key, you can't append to it.
Answer: Agree with @Selcuk's comment, so i am going to do an dictionary instead:
d={}.fromkeys([i['house'] for i in cards],[])
d={k:[i for i in cards if i['house']==k] for k,v in d.items()}

And now:
print(d)

Is:
{'Dis': [{'house': 'Dis', 'card_title': 'Bob'}], 'Brobnar': [{'house': 'Brobnar', 'card_title': 'Fred'}]}

Answer: If you already allocated your variable and just want to append to them, you need to create a wrapper dictionary to point to them:
cards = [
{'house':'Dis','card_title':'Bob'},
{'house':'Brobnar','card_title':'Fred'},
]

Dis = []
Brobnar = []

wrapper = {
    'Dis':Dis,
    'Brobnar':Brobnar,
}

for i in cards:
    if not wrapper.get(i['house'], None) is None:
        wrapper[i['house']].append(i)

print( Dis)
print( Brobnar)

#[{'house': 'Dis', 'card_title': 'Bob'}]
#[{'house': 'Brobnar', 'card_title': 'Fred'}]


Wireless Packet captures - VMware

Question: Software: Wireshark
Is it possible to analyse Wireless Packet captures on VMWare using Linux Ubuntu OS? I ask this as I'm using Windows for my computer but I'm struggling to get all the information I need so I've had to resort to a virtual machine.
On windows, wireless packet captures will appear as if they were on a wired network (the 802.11 header is replaced by an Ethernet II) It is possible to capture raw 802.11 traffic on Windows, but only a small number of network cards support it. I've been told It is much easier to capture 802.11 raw data using Linux or a MAC compute
Thanks
Comment: On Windows 7 or later, does npcap support monitor "rfmon" mode on your interface?  There will be a Monitor Mode checkbox in Wireshark's Capture > Options table,  and `%windir%\system32\npcap\WlanHelper.exe  {Interface Name or GUID} modes`  will contain monitor.
Comment: Not sure to be honest but I can find out, thanks. How come I can't look at wireless captures on VMWare? I'm pretty knew to networking just getting an understanding of it all
Comment: I didn't say you couldn't capture on VMware. Just that npcap is your best chance for monitor mode for Wireshark on Windows. Although driver support is bad.
Comment: Ok thanks. What are the solutions of wireless capturing on VMware?
Answer: Get a Linux LiveCD.
If you only want to capture for a while, just download a Linux live image, write it to a DVD or USB thumb drive and boot from it. There are images exactly for such cases which will already contain Wireshark, but any will do. You can install software on a LiveCD session (it will just be gone on the next reboot).
Boot the live session, run Wireshark, store the captured data somewhere. You can analyze the data later with Wireshark on Windows.

Wireless Packet captures - VMware


How can I add markup to a link in node links?

Question: I am trying to add some markup around the number of comments link in the standard node links. I want to do this so I can theme the number of comments as a little comment bubble and hide the text (possibly only on mobile).
I can get this far:
function mytheme_preprocess_links__node(&$variables) {

 if (isset($variables['links']['comment-comments'])) {
    $title = $variables['links']['comment-comments']['text'];
    $count = 7 // need to get the actual count in here.

    $variables['links']['comment-comments']['link']["#title"] = \Drupal::translation()->formatPlural($count, ''1 comment', '@count comments');
  }
}

When I dsm the $title variable I can see that the comment count is in there, I just can't figure out how to get it out into the $count variable. Any help?
Answer: Unfortunately the object PluralTranslatableMarkup has no method to get the protected value count. The serialization was fixed to provide the count value, see issue https://www.drupal.org/node/2844181, but the class is still missing it's own getArguments() to extend it with the count value. You could file an issue and wait for a fix or use this work around with reflection:
  if ($title instanceof \Drupal\Core\StringTranslation\PluralTranslatableMarkup) {
    $reflection = new ReflectionClass($title);
    $property = $reflection->getProperty('count');
    $property->setAccessible(TRUE);
    $count = $property->getValue($title);
  }


there is no property of datagridview in property windows

Question: I'm using Visual Studio 2008. I have no idea what happened, but all of a sudden I noticed that the Properties window for ALL of the DataGridViews in my project went blank. I've tried dropping in new ones..still blank. I restarted Visual Studio and my computer...still blank. I've done some google searches, and I've found people who have had the same problem, but there is no solution and it appears that Microsoft has been unable to duplicate it. Any ideas?
Comment: Try clearing the Reflected Schemas directory.... In my case its found in C:\Users\username\AppData\Roaming\Microsoft\VisualStudio\9.0\ReflectedSchemas where username is your windows login or just search for ReflectedSchemas. I have found that periodically clearing this helps. Don't delete the directory just the files in it.
Comment: i serach this file name but i have no résult, may be because i have french version?
Comment: Its not a filename but a folder (directory)... I'm using Visual Studio 2010 but I'm sure that VS2008 has it too. Sorry I can't be of more help.
Answer: I had the same problem as Badr El Ouassif defined in my XP virtual machine, working with VS2008. In my case it was because I changed a folder's access security to read-only, since this folder needed a big ammount of hard disk capacity and I wanted VS not to write there.
c:\Documents and Settings[USER]\Local Settings\Application Data\Microsoft\VisualStudio\9.0\ProjectAssemblies
The properties appeared as soon as I came back to establish the original configuration of the folder, full control for every user.


Learning Rate in Gradient Boost

Question: How do we decide the learning rate in gradient boost?
I can think of cross validation as one of the methods, but are there any other methods? Also, my teacher said in the class that 0.1 is a good measure for the learning rate (but did not back it with any sources).
Answer: It's a hyperparameter, so you pick it by tuning it, usually using cross-validation. There is no one-size-fits-all "good" value of the parameter, as it will be problem-specific. Algorithms like gradient boosting in many cases will let you get away with good-ish results even if you stick to some "default" settings, but by no means they are the optimal ones.

Learning Rate in Gradient Boost


recursion number of possible paths

Question: There is a terraced structure with N floors (here, for example 4 floors). Each floor has 4 cells.

Write the recursive function that describes the number of all the possible paths from the left bottom cell to the top right cell.
We can go up, down, right but not left and we can't visit in the same cell again.
Use only one variable.
Comment: Welcome to MSE. Interesting question... What are your thoughts about it? What have you try already? What issues are you facing?
Comment: i tried to find the base cases but in could'nt  find the function
Comment: https://math.stackexchange.com/questions/234433/generalizing-the-catalan-numbers?rq=1
Answer: Here is one way to break it down. The terraced structures can be composed by combining two consecutive triangular shapes from this series:
<code>n=2    n=3      n=4
                      1
           1        O 2
  1      O 2      O O 3
O 2    O O 3    O O O 4  ...
</code>
so now the question becomes:

How many paths (using NSE-directions, ie. north south east) can be formed in $T_n$, the triangular shape with $n$ layers ending at one of the numbered positions? Let $P_n(k)$ denote the number of paths in $T_n$ starting from the bottom left corner ending in the numbered position $k$ on the right side of the triangle.

Analysis of triangular shapes
For $n=2$ we have $P_2(1)=P_2(2)=1$, because we have one path leading to each numbered position:
<code>   1*      1
 ──┘     ──2*
</code>
For $n=3$ this becomes $P_3(k)=2$, since you can make a path to either one of the end positions in $T_2$ and then move into the last column in $T_3$ and reach the desired end position:
<code>     1*      1       1             1*      1       1
   ┌─┘     ┌─2*    ┌─┐           O │     O 2*    O 2
 ──┘ 3   ──┘ 3   ──┘ 3*   and  ────┘   ────┘   ────3*
</code>
This principle generalizes, and it follows that $P_n(k)$ is equal for all $k$. Let us hence denote this number simply by $P_n$. Then we have the recursive formula (and obvious solution to it):
$$
P_n=(n-1)P_{n-1}=(n-1)!
$$
Analysis of terraced structure
Given the terrace of size $n$, $S_n$, this can be combined from two triangles:
$$
S_n\sim T_n + T_{n-1}
$$
so for instance $S_3$ can be seen as follows
<code>    3─2 2
  3 3─2
3 3 3
</code>
where the top right corner is $T_2$ placed upside down. Any solution to the original problem will be a connection of paths in the two triangular shapes through one of the connections marked with a line in the figure above. Hence we have:

A solution to the $S_n$ terrace problem, can be constructed by combining a path to one of the top $n-1$ positions in $T_n$ to any end position in $T_{n-1}$. Let $K_n$ denote the number of such paths.

This leads to the recursive formula:
$$
K_n=(n-1)P_n\cdot P_{n-1}=(n-1)!^2
$$

For instance we get $K_2=1!^2=1$ and $K_3=2!^2=4$ and $K_4=3!^2=36$ which you can easily make a sanity check for.

It just occurred to me that one could simply place two $T_n$ triangles with a one column overlap in the middle. This leads directly to:
$$
K_n=(P_n)^2=(n-1)!^2
$$
Comment: Excellent solution! I was wondering if my solution was in the right direction. This is great, just to clarify that NSE-directions means north, sourth, East direction! I got really confused with that haha
Comment: @user614287: Thank you. Yes, I thought for a moment whether to write NSE in a different manner. Perhaps I should edit to make that clear.
Comment: Why gluing two triangles in the middle produces $K_n = (n-1)!^2$?
Answer: You can make a total of $9$ moves to get to the right upper cell in the grid starting from the lower left cell. At any given moment during your moves, The number of right moves made so far is always larger than or equals to the number of up moves made so far. Also, at any given time, the difference between number of right moves and the number of up moves seen so far should not be greater than $3$.
We can translate those condition into restriction on formulas, so we first give definition of some variables.
We let $r$ denote the number of possible right moves that you can still make so far, let $l$ be the number of possible left moves you can still make so far and let $t$ be the number of moves you can still make. Then $r+l=3$(because each time you make a right move, the number of right moves you can still make decreases by $1$ and the number of up moves that you can make increases by $1$) and $t=9$ initially.
let $H(r,l,t)$ be the number of ways to finish all your moves where you can still make $r$ right moves, $l$ left moves and $t$ more moves. Then $H(r,l,t)=1+H(r-1,l+1,t-1)+H(r+1,l-1,t-1)$ The base cases is: $H(r,l,t)=0$ if $(t=0) \vee (r<0) \vee (l<0)$ and you want to solve $H(3,0,9)$.
Hope this is a good recursion.
Comment: I need to slove it for N floors ( 4 was just example), and i i need to use with only one variable
Comment: Ok! so the total number of steps that you have to take if you have 1 floor is $3$, if you add one more floor, then you have yo move up once and move right once, so in total, you will have $3+2$ moves. So each times you add a floor, the total number of moves that you should make increases by 2. So in general, if you have $N$ floors, you have to make $2(N-1)+3$ moves. So if you have to solve the problem for $N$ floor, you would compute $H(3,0,2(N-1)+3)$. Lemme think about how we can do it with only one variable.
Comment: If we let $rr$ be the number right step made so far and $ll$ be the number of left steps made so far, then $H(r,l,t)=H(rr-ll,3-(rr-ll),2(N-1)+3-(rr+ll))$ and this gives two variable?
Comment: wait i can't use left moves, only up,down and right
Comment: Oh I guess we have a solution from below now lol

recursion number of possible paths


How does a machine learning model distinguish between ordered discrete int and continuous int?

Question: Lets say I am classifying if a user will like a Airbnb listing or not (binary classification model)
I have 2 features:

Number of house rules the Airbnb host has. Since this is a count, this is a discrete (categorical) variable. We will store this as an int because it is ordered (10 house rules is greater than 9 house rules).
Price of the Airbnb listing, rounded to the nearest whole dollar. This is clearly a continuous variable. It is also stored as an int.

If I'm not missing anything, do I need to specify anything myself to the machine learning model (let's say logistic regression since XGBoost classifier probably auto handles this) to distinguish between the discrete and continuous int? Or is there nothing to worry about here and it will automatically be handled for me?
Answer: Discrete $\ne$ Categorical
The number of house rules is a numerical variable. You might find value in having individual indicator variables for each house rule, each of which would be categorical, but the count of house rules is every bit as numerical as the price.
Your software does not need to distinguish between these and should run fine.
Also, I contest that your price variable is continuous when it is rounded to the nearest full dollar. Both variables seem to be counts (number of house rules or number of dollars paid).
Comment: Counts are discrete and numerical variables.
Comment: Gotcha. So what would you call a Count variable? Sounds like either discrete or numerical, not categorical?


Determine quality of audio file with comparison

Question: Usually, artists will release their work on multiple platforms, e.g. Bilibili, YouTube, niconico, etc. These platforms have different codecs and/or bitrates. Is there a way that determines which version has the highest audio quality? I'm specifically talking about aac-lc, but if you know about other codecs that's fine as well.
Please tell me if this question should be posted on stackoverflow, because it's kind of related to technology/programming.
Answer: The best thing I have found to compare quality is to run a spectral analysis with Audacity. Audacity is free and has lots of other nice features. Many recordings that are supposed to be 320bps are much close to 128bps. Even FLAC recordings show some poor quality. Just looking at the estimate by Foobar2000 or other audio players isn't enough.
Comment: Some poorly manipulated files seem to have cutoffs below 8000. Likewise, the shape of the roll-off differs between files. For use in a car, most of this doesn't matter. As I don't have a Rolls-Royce, the road noise matters. (In a Rolls, the clock ticking interferes with the high frequencies.)
Comment: Can you give an example? E.g. two versions of one file and where to look at to see the difference.
Comment: I'm not quite familiar with spectral analysis, so an example would be very helpful. Thank you!
Comment: All a spectral analysis will tell you is the cut-off frequency, which isn't going to help at all. If you can't hear the difference, what does it matter what the spectrum says? Can you hear 20KHz? Can your system repro it? Are you listening in the car or on headphones?


Adjust formula automatically based on OptionButton choice

Question: My Excel model allows the user to calculate delivery costs for different product categories in different countries. The choice is made via option buttons on a userform:
Frame 1: USA, UK or Germany
Frame 2: Books, Fashion or Grocery
Let's say the user has chosen USA as a country and Books as product category.
I now use formulas, such as salary_USA / 365, whereas "salary_USA" is a pre-defined range name.
I also copy and paste certain values from an assumption sheet: Worksheets("Assumptions Books").Range("E34:J34").Copy
If the user chooses UK, the formula changes to salary_UK / 365. If Germany is selected, the formula changes to salary_Germany / 365.
Similarly, if the selected product category is Fashion, it should be Worksheets("Assumptions Fashion").Range("E34:J34").Copy etc.
How can I make these commands more flexible, i.e. responsive to the user's selection?
I want to avoid to write a sub for each an every combination (USA-Books, USA-Fashion, USA-Grocery, UK-Books, UK-Fashion etc.)

I thought about defining a variabel as follows:
Public Country As String

Private Sub optUSA_Click()

If optUSA.Value = True Then
Country = "USA"

And then using this variable in the respective formula:
Sub CalculateCosts()

"salary_" & Country / 365

However, this approach does not work.
Answer: You can use all buttons to call the same macro and then, inside it reveald user choice. Look at this code below and test it in your app. It tells you which button was clicked.
  'Procedure to display which button was pressed.
  Sub WhichButton()

     ' Assign the calling object to a variable.
     ButtonName = Application.Caller

     ' Display the name of the button that was clicked.
     Select Case ButtonName

        ' NOTE: When you type the name of the button, note that
        ' Visual Basic is case and space sensitive when comparing
        ' strings. For example, "Button 6" and "button6" are not the
        ' same.
        Case "Button 6"
        MsgBox Application.Caller & "  was Clicked"

        Case "Button 7"
        MsgBox Application.Caller & " was clicked."

        Case "Button 8"
        MsgBox Application.Caller & " was clicked."

     End Select

  End Sub

You will find the code with full info here: http://support.microsoft.com/en-us/kb/143345


Renaming networking interface through systemd-networkd not working in upgraded Ubuntu 18.04

Question: In an Ubuntu 18.04 server, I was not able to rename network interfaces through proven config-management-applied systemd-networkd configuration working on all other servers.
The only difference I see between servers originally set-up by configuration management and this partially hand-petted machine is that the Ubuntu server has been upgraded from at least 14.04, maybe even 12.04.
Answer: Investigating initrd and comparing with a server that worked, two obvious differences appeared through upgrading Ubuntu:

/lib/udev/rules.d/71-biosdevname.rules
This is an old-times relict of renaming network interfaces in Ubuntu. It has to be deleted.
/etc/udev/rules.d/80-net-setup-link.rules
This was set-up shadowing /lib/udev/rules.d/80-net-setup-link.rules, which (among others) also applies configuration from systemd-networkd. It contains a message indicating some miss-interpreted setup as VM (actually, this is a bare metal server):
# This machine is most likely a virtualized guest, where the old persistent
# network interface mechanism (75-persistent-net-generator.rules) did not work.
# This file disables /lib/systemd/network/99-default.link to avoid
# changing network interface names on upgrade. Please read
# /usr/share/doc/udev/README.Debian.gz about how to migrate to the currently
# supported mechanism.

This file also has to be deleted.

A final update-initramfs -u && reboot results in properly renamed network interfaces.


Use a contextual filter value in a view referencing a node name/path rather than id

Question: I would like to create a views that has a contextual filter with a node reference.
I'm able to view the contextual filter working when I use the node's id value, but I need to be able to use the alias or name value of that content type. I have people categorized by office (the office is also a content type because it has much more content than a taxonomy would allow). Then using the office location as a contextual filter I'm trying to show the "team" listed for each office.
/office/atlanta/team rather than /office/6/team
Answer: I'm not sure, but it could be something like

[term:vocabulary]/[term:name]
Comment: You mean in the path for that view I'd use
`about-us/market-offices/[term:name]/team`
rather than
`about-us/market-offices/%/team`
Answer: Instead of Term: ID you might want to use Term: Name. I believe you can also check a box in the contextual filter options panel to display "Term ID converted to term name".
Comment: I think the problem for the OP is that the filter is not a taxonomy term but a node reference so the options you specify are not available.


What are functions that start with 'hook' used for?

Question: I understand how to use hooks (mymodule_HOOKNAME()) but what are functions used for that actually start with hook?
Ex: hook_action_info()
When I am creating custom hooks I normally just use: module_invoke('MODULE', 'HOOK_NAME').
Comment: module_invoke_all() can be used as well. depending on how you wish to use it.
Answer: hook_action_info and other functions that begin with hook_ exist only to document the contract between the caller of the hook and the module that implements it.
Comment: Correct answer. Just would like to add that if others will use your code you should write your own hook_ functions to help them understand yours.
Answer: First off, there's not a single function in Drupal, that starts with hook_.
hook_
Whenever you see a function name starting with hook_, it is a symbolic name for a hook function to be implemented by a module or a theme, where hook_ will be replaced with the module's or theme's actual name.
Within your module, all functions you want to expose to the Drupal's hook system to be called at appropriate times, will start with mymodule_ as long as the name of your module is actually mymodule. That is also the MODULE part in
module_invoke('MODULE', 'HOOK_NAME')

mymodule_HOOKNAME
On the other hand, mymodule_HOOKNAME() refers to all or any hook functions implemented by module mymodule.
All modules that wish to configure custom actions will have to implement a function which starts with the module name and ends in _action_info. Again, that's the HOOK_NAME part in
module_invoke('MODULE', 'HOOK_NAME')

module_invoke
Finally, the module_invoke('MODULE', 'HOOK_NAME') just puts these two concepts (module name and hook name) together to build a specific module's hook function name, check if it exists at all and then call it.
To work out the function name to call, module_invoke puts together the MODULE and HOOK_NAME parts, separated by an underscore. And that is why yourmodule implementing hook_action_info() defines a function yourmodule_action_info().
Answer: From the Drupal 7 API:

Allow modules to interact with the Drupal core.
Drupal's module system is based on the concept of "hooks". A hook is a
  PHP function that is named foo_bar(), where "foo" is the name of the
  module (whose filename is thus foo.module) and "bar" is the name of
  the hook. Each hook has a defined set of parameters and a specified
  result type.
To extend Drupal, a module need simply implement a hook. When Drupal
  wishes to allow intervention from modules, it determines which modules
  implement a hook and calls that hook in all enabled modules that
  implement it.
The available hooks to implement are explained here in the Hooks
  section of the developer documentation. The string "hook" is used as a
  placeholder for the module name in the hook definitions. For example,
  if the module file is called example.module, then hook_help() as
  implemented by that module would be defined as example_help().
The example functions included are not part of the Drupal core, they
  are just models that you can modify. Only the hooks implemented within
  modules are executed when running Drupal.


basic differential question

Question: I need guidance on this problem. Could someone lead me in a direction of how I should go about doing this question. Is there some sort of proof involved in this question? No need to solve the question just some guidance would be good.
show that $f′(−x)=f′(x)$ for all x
EDIT:
f is a differentiable odd function then f(prime) is an even function
Comment: There need to be more assumptions on $f$ for that to be true; a simple counterexample is $f(x) = x^2$.
Comment: I would guess he wants $f(x)$ to be an odd function.
Comment: f is a differentiable odd function while f(prime) is an even function
Comment: If $f(x)$ is an odd function, $f(-x) = -f(x)$ by definition, what can you do to both sides of the equation to make it look like $f^{\prime}(-x) = f^{\prime}(x)$?
Comment: humm @JessicaK ... can I use the definition of derivative?
Comment: You can always use the definition, but I would just use the chain rule.
Comment: humm chain rule, how would that work? I mean how would I use the chain rule in this circumstance?
Answer: This statement is not true. A function $f$ must have additional conditions. Assume that $f$ has some conditions. You can proof directly from the definition of derivative:
$$f'(x)=\lim_{h\to 0} \frac{f(x+h)-f(x)}{h}.$$
Answer: Suppose $f(x)$ is an odd function, then by definition
$$f(-x) = -f(x).$$
Since $f$ is differentiable, apply the derivative to both sides and use the chain rule
$$\frac{d}{dx} f(-x) = \frac{d}{dx}-f(x)$$
or
$$-f^{\prime}(-x) = -f^{\prime}(x)$$
multiplying by -1 gives you the desired result.
Comment: sorry for my lack of understanding in mathematical concepts... but I cannot understand how we can use the chain rule in this case :  d/dx f(−x)= d/dx −f(x)
Comment: $\frac{d}{dx}f(-x) = f^{\prime}(-x)* \frac{d}{dx}(-x) = -f^{\prime}(-x)$ by the chain rule.
Comment: ahh I see now... and now I understand if f(-x) = -f(x) ... the derivative which is an even function should look like its predecessor the odd function... tricky question :p ... but Thanks !

basic differential question


(Combinatorics) If there is a 5 x 5 bingo board with one space missing how many permutations are there

Question: Imagine a 5x5 board with one space fixed but can be filled with 500 different things (or a number 1-500) how many combinations can you generate?
Comment: On a regular bingo board (which uses $1$-$75$), the first column can only contain numbers in the range $1$-$15$, the second column $16$-$30$, and so on. Do we have a similar limitation here?
Comment: And does the order of elements within a row or column matter?  If not, the problem becomes more difficult.
Comment: @Arthur there aren't any traditional rules or structure, it is simply a 5 x 5 entity with 500 discrete elements, similar to a scratch off, but with a space fixed so there are 24 squares
Answer: There are $5\times5-1=24$ spaces to fill with distinct choices from $500$ things. If the order matters, there are
$$24!\times\binom{500}{24}=\frac{500!}{476!}\approx1.96654\times10^{1110},$$
permutations, which is a really big number. If the order doesn't matter, there are
$$\binom{500}{24}=\frac{500!}{24!476!}
=54827357333432750995708546189537690075500\approx5.48274\times10^{40},$$
combinations, which is a big number, but a lot smaller than the other one.


Doing A/B testing

Question: I would like to do some A/B testing.
I would like to have 2 slightly different templates and different modules and paths for each template and then I would like to do to the visitors 50% template A + modules and logics etc. and 50% of the visitors template B + own modules.
It would be based on user IP and some simple logic half visitors will be seeing first template and the second half of the visitors will be seeing the second template with different settings.
An important thing is that a user (based on IP or login) should see the template he saw for the first time forever not only for his session.
I am not sure if I have to install two Drupal versions with two databases and use <code>.htaccess</code> or something to make the decision.
Or I have looked for modules but found only this one:
http://drupal.org/project/multivariate
Which seems too light.
Any advice which way to choose and how to approach this problem.
Comment: Might be of interest: http://www.drupalseobook.com/news/google-website-optimizer-with-drupal
Comment: This is something I've wanted to do many times, but never set the time aside for it. Rendering a page with page manager/panels and creating a custom `Access plugin` for this would be an ideal solution in my book.
Comment: @Letharion thanks in advance for the credits in your book ;)
Answer: I would recommend you to consider testing http://visualwebsiteoptimizer.com/ for your use case. There is also a module http://drupal.org/project/visual_website_optimizer which makes the integration easier for you.
From the FAQ page of VWO you can see that

Uses cookies to track visitors
Visitors see same variation even on repeat visits

So that should solve your problem. To make the decision of which variate should be visible to which users, there is sleek UI for selecting those conditions.
However if you want to do the things, the Drupal way then you can use http://drupal.org/project/multivariate which gives you more control. Multivariate is more like Rules or Context module. You have a set of conditions(is the user using X browser, is his IP originating from Y country and so on) and when those conditions are met a set of actions can be performed(serve his multivariate A instead of B).

An important thing is that a user (based on IP or login) should see
  the template he saw for the first time forever not only for his
  session.

For making sure that above condition is met you can increase the life of the cookies set. If you want to track the users before loggin in(anonymous users) and after they have authenticated, then you might need to do some custom coding.
Answer: There are a few options for A/B testing a Drupal website, and all options will run the simple test requirements of this question (splitting traffic with specified percentages and keeping visitors in their initial experiences). The two basic approaches are using a paid external service to run the A/B tests or using a fully Drupal-integrated module. Here are the options for each approach:
Drupal Modules

A/B test: Available for D7, this module is described on the project page as a "low-level API for implementing A/B tests in code". The tests are implemented with custom PHP, which requires knowledge of Drupal data structures and hooks on the PHP side. Also note that an HTML cacheing layer will complicate matters (if not all site visitors are hitting backend PHP). This module has not been updated since April 2015 and has not had a stable release, but there are 30+ sites that currently report using it.
Multivariate: As Gokul mentioned, Multivariate allows tests to be configured through in the admin UI, without needing any custom code. It is available for D7, but has not had a stable release and hasn't been updated since October, 2013. It does have the highest current usage of any non-external A/B testing module with 100+ sites currently reporting that they use it. As it is a backend solution, an HTML cacheing layer could prevent usage of this module.
A/B Test JS: This is a new module for D7 and D8 that runs tests in JavaScript and exposes an admin UI for test creation. It does not currently have sites reporting usage, but is actively being developed and maintained. Custom JavaScript snippets are required to create tests, and evaluation of the tests must be done in a separate analytics platform like Google Analytics.

External services
The external options run all testing logic on the frontend (in JavaScript) and can be implemented with either direct inclusion of the scripts, or through Drupal modules when available.

Optimizely: I have not used Optimizely, but I do know that is widely used and considered state-of-the art for A/B testing. It includes a WYSIWYG UI for creating the test modifications, so tests can be created without any code. The Optimizely Drupal module is available in D7 and D8, and has the most usage of any of the A/B testing options.
Visual Website Optimizer: I don't have experience with this either, but it does include a WYSIWYG interface for creating tests and interface for viewing results. A Drupal module that includes the VWO javascript in your site's pages is available for D6, D7, and D8, and also has a significant amount of usage on Drupal.
Adobe Test and Target: From personal experience with Adobe T&T, it has the WYSIWYG interface for creating tests, but I found the UI quite buggy, and worst of all, many of our tests caused "flicker" for site visitors, where the original page flashes before test modifications are implemented. The Test&Target Drupal module also has very little usage, and is only available in D7.
Google Content Experiments: As a part of Google Analytics, Content Experiments are not as fully featured as the options above, but I believe the service is free and would satisfy the requirements of this question. The Content Experiments Drupal module is available in D7.

Conclusion
Long story short, this use case can be satisfied with any of these solutions so long as they function as intended. More specifics would be needed to find the best solution. In general, I prefer to use Drupal A/B Test JS, but that's also because I made it :)

Doing A/B testing


how to install multpile control panels into the one server?

Question: i am using cpanel whm in my vps. i would like to test webmin,Virtualmin,OpenPanel etc.
can i install multpile control panels to my vps? i dont want to damage my server, that is why i am asking this question. i am hosting multpile websites in my vps, i do not want to damage any websites. i would like to install and test other control panels.
is there any other way to test these control panels?
Answer: I would suggest that this is a bad idea. Firstly each of the control panel is either going to want to install it's own webserver, DNS server etc, or control the existing one, along with the other controls panels. They are going to fight for control of these items, most likely cause conflicts and problems.
Secondly, testing this on a production server that is already hosting sites, that I assume are important to you or your customers, is a very bad idea. If you want to test control panels get your self some virtual machines, either on your own machine or from one of the many cloud providers and test them on their, not on a live server.
Comment: thanks mate, you have been very helpfull for me. A+ help. thanks for your answer and ideas...


Missing county in Google Maps geocoding API

Question: I've noticed that a handful of zip codes are not returning a county. For example, 30601 (Athens, GA - county is Clarke) json result below. Normally I see county data returned with type administrative_area_level_2. This is missing from the response:
$url https://maps.googleapis.com/maps/api/geocode/json?address=30601&key=topsecretkey

Array
(
    [results] => Array
        (
            [0] => Array
                (
                    [address_components] => Array
                        (
                            [0] => Array
                                (
                                    [long_name] => 30601
                                    [short_name] => 30601
                                    [types] => Array
                                        (
                                            [0] => postal_code
                                        )

                                )

                            [1] => Array
                                (
                                    [long_name] => Athens
                                    [short_name] => Athens
                                    [types] => Array
                                        (
                                            [0] => locality
                                            [1] => political
                                        )

                                )

                            [2] => Array
                                (
                                    [long_name] => Georgia
                                    [short_name] => GA
                                    [types] => Array
                                        (
                                            [0] => administrative_area_level_1
                                            [1] => political
                                        )

                                )

                            [3] => Array
                                (
                                    [long_name] => United States
                                    [short_name] => US
                                    [types] => Array
                                        (
                                            [0] => country
                                            [1] => political
                                        )

                                )

                        )

                    [formatted_address] => Athens, GA 30601, USA
                    [geometry] => Array
                        (
                            [bounds] => Array
                                (
                                    [northeast] => Array
                                        (
                                            [lat] => 34.0593981
                                            [lng] => -83.288826
                                        )

                                    [southwest] => Array
                                        (
                                            [lat] => 33.9479501
                                            [lng] => -83.405851
                                        )

                                )

                            [location] => Array
                                (
                                    [lat] => 34.006845
                                    [lng] => -83.3468784
                                )

                            [location_type] => APPROXIMATE
                            [viewport] => Array
                                (
                                    [northeast] => Array
                                        (
                                            [lat] => 34.0593981
                                            [lng] => -83.288826
                                        )

                                    [southwest] => Array
                                        (
                                            [lat] => 33.9479501
                                            [lng] => -83.405851
                                        )

                                )

                        )

                    [place_id] => ChIJocit0GgT9ogRTBKlRatQYFc
                    [types] => Array
                        (
                            [0] => postal_code
                        )

                )

        )

    [status] => OK
)

If I pass a different zip code, say 30083 (Stone Mountain, GA county DeKalb), the county (and administrative_area_level_2) is returned as expected.
Array
(
    [results] => Array
        (
            [0] => Array
                (
                    [address_components] => Array
                        (
                            [0] => Array
                                (
                                    [long_name] => 30083
                                    [short_name] => 30083
                                    [types] => Array
                                        (
                                            [0] => postal_code
                                        )

                                )

                            [1] => Array
                                (
                                    [long_name] => Stone Mountain
                                    [short_name] => Stone Mountain
                                    [types] => Array
                                        (
                                            [0] => locality
                                            [1] => political
                                        )

                                )

                            [2] => Array
                                (
                                    [long_name] => DeKalb County
                                    [short_name] => Dekalb County
                                    [types] => Array
                                        (
                                            [0] => administrative_area_level_2
                                            [1] => political
                                        )

                                )

                            [3] => Array
                                (
                                    [long_name] => Georgia
                                    [short_name] => GA
                                    [types] => Array
                                        (
                                            [0] => administrative_area_level_1
                                            [1] => political
                                        )

                                )

                            [4] => Array
                                (
                                    [long_name] => United States
                                    [short_name] => US
                                    [types] => Array
                                        (
                                            [0] => country
                                            [1] => political
                                        )

                                )

                        )

                    [formatted_address] => Stone Mountain, GA 30083, USA
                    [geometry] => Array
                        (
                            [bounds] => Array
                                (
                                    [northeast] => Array
                                        (
                                            [lat] => 33.8351599
                                            [lng] => -84.1243101
                                        )

                                    [southwest] => Array
                                        (
                                            [lat] => 33.7368448
                                            [lng] => -84.246361
                                        )

                                )

                            [location] => Array
                                (
                                    [lat] => 33.7994803
                                    [lng] => -84.1909841
                                )

                            [location_type] => APPROXIMATE
                            [viewport] => Array
                                (
                                    [northeast] => Array
                                        (
                                            [lat] => 33.8351599
                                            [lng] => -84.1243101
                                        )

                                    [southwest] => Array
                                        (
                                            [lat] => 33.7368448
                                            [lng] => -84.246361
                                        )

                                )

                        )

                    [place_id] => ChIJcxoG6teo9YgRwtQgWre-Trk
                    [postcode_localities] => Array
                        (
                            [0] => Pine Lake
                            [1] => Stone Mountain
                            [2] => Tucker
                            [3] => Wilshire
                        )

                    [types] => Array
                        (
                            [0] => postal_code
                        )

                )

        )

    [status] => OK
)

Am I doing anything wrong here? If no, is there a way to notify Google of this missing data?
Answer: Looking them up on Google Maps, 30601 goes outside of Clarke County, and thus with just the zip code it's not possible to determine a county value. 30601 appears to include bits of Clarke, Madison, and Jackson counties.
30601 (note the areas in green at the top of the zip code near Sandy Creek Park):

Clarke County:
Comment: Passed the entire st address and am now seeing the county - thank you kind individual!
Comment: Great answer! @acoder please also see [Geocoding Best Practices](https://developers.google.com/maps/documentation/geocoding/best-practices) as it is best for you to input a non unambiguous address in the Geocoding API. And if in a case where you have to input an ambiguous query, it is recommended that you use Places Autocomplete.


How can I integrate R with PHP?

Question: I would like build a web application using R. I am using Windows Vista and have an Apache server. I have tried Rpad, but I was not able to correctly configure it. How do I set up Rpad as I am not that well off with PHP and Apache server? Or are there other ways to use R on Apache server?
Comment: This question appears to be off-topic because it is about programming and not about statistics.
Comment: Did you try RCallerPhp? Here is a link https://github.com/jbytecode/rcaller/tree/master/RCallerPhp
Answer: Here is the easiest way to do it that I found:
This implementation of PHP and R consists of only two files. One written in PHP, and the other an R script. The PHP returns a form which uses the GET method to send a variable N to the server. When the form is submitted, the PHP will then execute an R script from the shell using a combination of the PHP command exec() and the Rscript shell command. This command will pass the variable N to the R script. The R script will then execute and save a histogram plot of N normally distributed values to the filesystem. Finally, when the R script is complete, the PHP will return the HTML tag containing the saved images path. First, the PHP file
< ?php
// poorman.php
echo "< form action='poorman.php' method='get'>";
echo "Number values to generate: < input type='text' name='N' />";
echo "< input type='submit' />";
echo "< /form>";
if( isset($_GET['N']))
{
  $N = $_GET['N'];

  // execute R script from shell
  // this will save a plot at temp.png to the filesystem

  exec("Rscript my_rscript.R $N");

  // return image tag

  $nocache = rand();

  echo(" ");
}
?>

and the R script
# my_rscript.R
args <- commandArgs(TRUE)
N <- args[1]
x <- rnorm(N,0,1)
png(filename="temp.png", width=500, height=500)
hist(x, col="lightblue")
dev.off()

Here are some more you are welcome to try:

http://danpolant.com/r-integration-with-php/
http://steve-chen.net/document/r/r_php
Comment: Above answer copy and pasted from here: http://www.r-bloggers.com/integrating-php-and-r/
Comment: +1, I can confirm that this works and it is very simple. I used it in my pretty complicated project: jQuery+PHP+R.
Answer: If you ever think to switch to Linux, the best way would be to use RApache, which is an Apache module that embeds an R interpreter (mod_R) in the webserver
Answer: If you are looking for a way of executing chunks of R code from PHP, here is a library that might help:
https://github.com/kachkaev/php-r
use Kachkaev\PHPR\RCore;
use Kachkaev\PHPR\Engine\CommandLineREngine;

$r = new RCore(new CommandLineREngine('/usr/bin/R'));
$result = $r->run('1 + 1');
echo $result;

This will output:
> 1 + 1
[1] 2

How can I integrate R with PHP?


Question on the formation of the Harmonic field in general

Question: Given a key note, you can build up any sort of scale, for scales are just patterns of whole and half steps. The minor and major are examples.
Now, if the scale is the set of notes, the harmonic field is the set of chords.
So, suppose we want to write a music in the C key. The next natural step is to search chords. Well, here I became confused; I will explain:
It seems that the "harmonic field construction" is formed, every time, just with the major scale! Example:

key: c
major scale: c d e f g a b
Harmonic field: C Dm Em F G Am Bdim

My question is:
How to build the harmonic field in general?
Note that, I know how to pick a key note, and I know how to establish a scale pattern and write the scale for a given key note. But, the harmonic field in 3) is very specific, the II, III and VI degrees are minor chords, the I, IV and V are major chords and the last degree is diminished. So, I suspect that if I write the minor scale in 2) the harmonic field will not follow the rules of 3).
Answer: Here's how you build a harmonic field from a heptatonic or octatonic scale:

Start with the first note of the scale and use it as the root of the first chord in the harmonic field.
To determine the second note of a chord in the harmonic field, go up the scale two notes from the root note of the chord. For the first chord, this will be the third note of the scale.
To find the third note of a chord in the harmonic field, go up the scale two notes beyond the second note of the chord, or four notes from the root of the chord. For the first chord, this will be the fifth note of the scale.
You have now formed the first chord (triad) in the harmonic field. Determine its quality (e.g., major, minor, augmented, diminished, etc.) and make a note of it.
Repeat steps 2-4 based on each note of the scale to determine the triads that make up the harmonic field for the scale.

For example, the harmonic field of the harmonic minor scale, is as follows (using A harmonic minor as the example scale):

A minor (i)
B diminished (ii°)
C augmented (III+)
D minor (iv)
E major (V)
F major (VI)
G# diminished (vii°)

Note: A harmonic minor is A - B - C - D - E - F - G#
Comment: "which was often used in the common practice period" the harmonic minor scale is more of a theoretical abstraction than something that composers actually used.
Comment: @phoog I've seen a lot of sharpened seventh scale degrees in common practice music, but I think you're right that it's not exactly that that was done because the composer was thinking about the scale. I definitely oversimplified that bit - I thought it would be a more interesting example and wanted to motivate it in some way, so I sort of fudged the justification.
Comment: "it's not exactly that that was done because the composer was thinking about the scale": for most of the common practice period the harmonic minor scale hadn't yet been invented as a theoretical concept.  People had been raising seventh scale degrees for centuries before the common practice period even began, but the harmonic minor scale was invented in the 19th century to account for this practice.  Anyone "generating the harmonic field" in the 18th century would more likely have started with the proposition that the seventh scale degree may be raised or not (and the sixth, for that matter).
Comment: @phoog Um. Ok. What is the goal of your comments?
Answer: The question supposes that all music is diatonic - using only the notes from the particular scale involved. As in key C, only notes CDEFGAB are available for playing. That seems to be a common misconception reading quite a few questions posed on this site alone. It's nowhere near reality, but let's go with it for now.
True, only using diatonic notes, and tertian harmony (stacks of thirds), we do indeed end up with M m m M M m d as the 7 available chords. Quartal harmony gives different chords.
But, you ask about minor. By stacking thirds, you will get a set of chords. More than you do with major, due to there being harmonic and melodic minr scales, giving more triad and four note chords.