Why does $\frac{\delta (e^Te)}{\delta e} = 2e^T$ ? Doesn't the product rule apply here?

Question: Why is $$\frac{\delta (e^Te)}{\delta e} = 2e^T$$ ?, where $e$ is a vector. Doesn't the product rule apply here ?
Because from understanding, isn't it like this:
$$\frac{\delta (e^Te)}{\delta e} = e\frac{\delta e^T}{\delta e} + e^T\frac{\delta e}{\delta e} = e + e^T$$, which is completely invalid since $e$ and $e^T$ have different dimensions. Where did my formula go astray?
Answer: Let us write the indices down to understand what is going on. Denote components of the vector $e$ as $e^i$.
$$\frac{\delta (e^{T}e)}{\delta e}=\frac{\delta}{\delta e^{i}}e_{j}e^{j}=\underbrace{e_{j}\delta^{j}_{i}+\delta_{ij}e^{j}}_{\text{product rule}}=e_{i}+e_{i}=2e_{i}=2e^T$$
Here we used the Einstein's notation where summation over repeating indices is always implied, $e_{i}$ corresponds to $e^{T}$, $\delta_{ij}$ is the Kronecker delta (the unit matrix), and we use the facts that $\frac{\delta e^{i}}{\delta e^{j}}=\delta^{i}_{j}$ and $\delta_{j}^{i}f^{j}=f^{i}$. Note that $\partial_{i}x^{j}=\delta^{i}_{j}$, but $\partial_{i}x_{j}=\delta_{ij}$ (see the clarification on Einstein's notation down below).
The reason you have $2e^T$ instead of $e+e^{T}$ is that you take the variation of a scalar quantity with respect to components of a vector; what you obtain must contain exactly one number for each component of the vector with respect to which you take variation. Speaking in fancy terms, if you take variation of a scalar with respect to a vector, you get a covector, and vice versa.
In general, when taking derivatives of complex expressions involving vectors, matrices, tensors etc., often the most robust way to get the right answer is to use Einstein's notation and several simple rules. We call the summation over a pair of repeating indices,one top and one bottom, contraction.
Let us denote $ \frac{\partial }{\partial x^{i}}$ as $\partial_{i}$, components of a vector with $x^{i}$, where $i$ has an appropriate number of values, depending on the dimension of space. Although it is not strictly necessary when working with regular Euclidean space, it is be convenient to denote $x=x^{i}$, $x^{T}=x_{i}$, and use the rule that only a pair of indices where one is on the top and another on the bottom can be summed over (you can matrix multiply $x^{T}x$, but not $xx$ and $x^{T}x^{T}$).
Then
$$\frac{\partial }{\partial x^{i}}x^{j}=\delta^{j}_{i}$$
(the derivative a component of a vector with respect to a component of a vector is one when the indices coincide and 0 otherwise), matrices of linear operators correspond to objects with one top and one bottom index, which act on vectors with appropriate contractions:
$$(A\vec{x})^{i}=A^{i}_{j}x^{j}$$
$$(\vec{x}^{T}A)_{j}=A^{i}_{j}x_{i}$$
Objects with two bottom indices are bilinear forms, since they can be contracted with two vectors and this contraction gives you a scalar, objects with two top indices are "bivectors". Derivatives with respect to vector components have bottom indices, since they can be contracted with vectors to produce a scalar quantity, the divergence. Likewise, derivatives with respect to covector components (i.e. components of transposed vectors) have top indices. In this notation, a derivative of arbitrary complex expression can be calculated, using $\frac{\partial }{\partial x^{i}}x^{j}=\delta^{j}_{i}$, the fact that $\delta^{i}_{j}$ is the unit matrix, so, when being contracted with another expression by one index, it just substitutes its other index into that expression, on the same height on which the index was in the $\delta$ (so $\delta_{ij}$ can "lower indices": $\delta_{ij}e^{j}=e_{i}$, and $\delta^{ij}$ can "raise indices": $\delta^{ij}e_{j}=e^{i}$), and the product rule:
$$\partial_{i}(A(x)B(x))=(\partial_{i}A(x))B(x)+A(x)(\partial_{i}B(x))$$
The last thing to remember is that in this notation the order of components inside a monomial does not matter, since all summations are uniquely defined by the indices, so $A^{i}_{j}b_{i}=b_{i}A^{i}_{j}$, and that a monomial can't contain more than two identical indices.
Comment: First, the product rule is exactly what I have applied, I have even explicitly indicated the moment when I apply it. Second, despite me making the mistake in the description of the result (naturally, the right answer is $e^{T}$), the Einstein's notation is so clever that it took care of it and forced the right calculation.  You can notice that the calculation results in $e_{i}$, $e$ with the lower index. This corresponds to $e^{T}$. The vector $e$ has an upper index, $e^{i}$.
Comment: So, i guess here the product rule can't be directly applied right? Also, could you explain why it isn't 2e. Because. It's actually 2e^T according to the my book :(
Answer: So you are looking for the differential of the map $x\mapsto x^Tx$ where $x\in R^n$ written as a column vector. For fixed $x$ this differential is the linear map from $R^n$ to itself defined by $h\mapsto h^T x+x^Th.$  If you decide to consider $R^n$ as a Euclidean space, ie a space with an inner product here defined by $\langle x,y\rangle=x^Ty,$ then $x^Tx=\|x\|^2.$ In general the differential of a real function $f$ at a point $x$ defined on a Euclidean space $E$, namely the linear  form $h\mapsto f'(x)(h)$ is rather represented by a vector   of $E$ called gradient. This is due to the fact that any linear form $h\mapsto \ell(h)$ on $E$ can be represented by a unique vector $g_{\ell}\in E$ such that $\ell(h)=\langle g_{\ell},h\rangle$. The tradition uses the abuse of notation $g=g_{\ell}=\ell.$ Coming back to your problem, here $R^n$ is Euclidean and the linear map $h\mapsto h^Tx+x^Th$ is written by the scalar product $2\langle x,h\rangle =2x^Th$. The gradient is $2x$ its action on $h$ is written $2x^Th=2h^Tx.$ This why your book speaks (vaguely) by saying that the differential is $2x^T.$


Granting User Permissions to IIS

Question: I'm trying to give a coworker rights to IIS on a server, because currently he can't see the server in IIS manager.  What rights do I need to grant him?  I tried adding him to the IIS_USRS, but he still can't see the server.
Thanks.
Answer: I would think at least in the "Users" group, however, will probably have to be an Admin to make many changes...Try right clicking on "Start Page" and then select "Connect to a Server..." and type localhost, click Next, then Finish, see if that connects to the local IIS install.
Answer: Also be sure that the Web Management Service is started. As default, when this role feature is installed, its startup type will be Manual, set it to Automatic if you want to always be able to connect to your web server
Answer: Is the coworker logging into the server to use IIS Manager or from their workstation? If the server is IIS 7.5, you need to add your coworker to the IIS Manager Permissions for the website you want them to manage. The Management Service role must be installed and set to Windows credentials unless you want to manage IIS credentials. Doing that will let them remotely connect from their IIS Manager tool (Win7) or the IIS7 Administration tool you can install in XP.

Granting User Permissions to IIS


Can forms be added to a page of quick tabs?

Question: I want to create a page of quick tabs with some node editing pages, webforms and some admin pages as well regular static pages which just display information without any editing.
Is that possible?
Answer: Should be possible via custom code. You can read up on how to build quicktabs programmatically here:
https://www.drupal.org/node/2119625
For the node editing pages you will want to use the example for Custom contents (HTML or renderable Array) on that page, where you get the form using the core function drupal_get_form('node_BUNDLE_form') and add it as the "renderable array".
For the webforms you could try to work with the Callback tab type, or again by loading the webform and building the render array.
For the static content i'd recommend to use nodes as this is always better than hardcoding things, so use the Node tabs type.


Positioning Marker head point out to the Polyline path

Question: I want to position the marker head point out to the polyline path starting position and the polyline drawn between source and destination marker.
My code snippet is
list=polyline1.getPoints();
list.add(latlng_value);
now= googleMap.addMarker(new MarkerOptions()
                    .position(list.get(0)) //points = the List of LatLngpoint
                    .draggable(false)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow_up)));

Answer: Here's the logic if you want to put markers on your polyline

First, to draw a polyline, you need a list of LatLng point that define the polyline nodes.
To put the "Source" marker, set its position on the first LatLng point
To put the "Destination" marker, set its position on the last LatLngPoint

A little code snippet for the marker
map.addMarker(new MarkerOptions()
            .position(points.get(0)) //points = the List of LatLng point
            .draggable(false)
            .title(getString(R.string.label_start).toUpperCase()) // Text you want to add as title
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.map_start))); // Custom icon for marker

EDIT
Here's what I would do :
Declare the Points list
list=polyline1.getPoints();

Add the source marker
googleMap.addMarker(new MarkerOptions()
    .position(list.get(0))
    .draggable(false)
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow_up)));

Add the destination marker
googleMap.addMarker(new MarkerOptions()
    .position(list.get(list.size()-1))
    .draggable(false)
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow_up)));

Draw polyline
googleMap.addPolyline(new PolylineOptions()
    .addAll(list);

Comment: I got list of LatLng points from  this code list=line1.getPoints();// list as LatLng List
              list.add(latlng);
            now=  googleMap.addMarker(new MarkerOptions()
              .position(list.get(0)) //points = the List of LatLng point
              .draggable(false)
               // Text you want to add as title
              .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow_up))); //now is marker
Comment: I already drawn the polyline between source and destination and i want to rotate the marker head and it point out to the destination marker direction.
Comment: Use the destination marker code I wrote on my answer for your source marker head.


Differential Equation $y(x)'=(y(x)+x)/(y(x)-x)$

Question: can someone give me some tips on how to solve this differential equation.
I looked at the Wolfram solution which substituted $y(x)=xv(x)$. I'd know how to solve from there, but I have know idea why they did it in the first place, well why the algorithm did it in the first place. When do you substitue $y(x)=xv(x)$?
What are other ways on solving it?
Comment: The reason that works is because the equation is *homogeneous* in the sense that the right hand side of the equality does not change if you multiply $x$ and $y$ by a constant. very time an equation has an invariance property like this, there is a way to simplify it.
Answer: Approach 1
$$y = v x \rightarrow y' = v + x v'$$
Substitute into original ODE. Looks like you know how to do this.
Why does this work?
To solve the equation $\tag 1 \dfrac{dy}{dx} = \dfrac{f_1(x, y)}{f_2(x,y)},$
where $f_1(x,y)$ and $f_2(x,y)$ are homogeneous functions of the same degree in $x$ and $y$, we use the following approach. Let
$$f_1(x,y) = x^n \phi_1\left(\dfrac{y}{x}\right), ~f_2(x,y) = x^n \phi_2\left(\dfrac{y}{x}\right).$$
From $(1)$, we have
$$\dfrac{dy}{dx} = \dfrac{f_1(x, y)}{f_2(x,y)} = \dfrac{x^n \phi_1\left(\dfrac{y}{x}\right)}{x^n \phi_2\left(\dfrac{y}{x}\right)} = \dfrac{\phi_1\left(\dfrac{y}{x}\right)}{\phi_2\left(\dfrac{y}{x}\right)}$$
We can now write this as
$$\dfrac{dy}{dx} = f\left(\dfrac{y}{x}\right)$$
Now, if we say $v = \dfrac{y}{x} \rightarrow y = vx$ and we substitute, we get a separable equation of the form:
$$\dfrac{dv}{f(v) - v} = \dfrac{dx}{x}.$$
Approach 2
Let $x + y = z$.
We have $x + y = z \rightarrow 1 + \dfrac{dy}{dx} = \dfrac{dz}{dx} \rightarrow \dfrac{dy}{dx} = \dfrac{dz}{dx} - 1$.
For the numerator, we substitute $z$ and for the denominator, we substitute $y-x = z-2x$. Do you see how to get that last one?
Now, the ODE is separable.
Approach 3
Let $y-x = z$.
Follow what was done in approach 2.
Comment: Nice "overtime" here! +2 if I could.
Comment: *What are other ways on solving it?*
Comment: @Amzoti
but why?
Like is there a guideline on when this substituion might work?
Comment: @Prankster: Added details as to why it works. Regards
Comment: @PedroTamaroff: Added a second method and details as to why substitution works.
Comment: @Amzoti Thanks heaps. But for Approach 2, don't you mean y-x=z?
That way I get the correct solution. Haven't found a way to solve it using x+y=z
Comment: Needs a thumb's up! +1
Comment: @amWhy: Thanks, just added more details and even a third approach. Hope you have a great day!
Answer: Let's assume a equation scaling $x \to \alpha x$ and $y \to \beta y$. Under such scaling the equation becomes
$$
y'
=
{\alpha \over \beta}\,
{y + \left(\alpha/\beta\right)x \over y - \left(\alpha/\beta\right)x}
$$
Then, we can see the equation doesn't change its form whenever $\alpha = \beta$. It means $y/x$ doesn't change its form either. Then, a change of variables
$\left(~y \to {\rm f}~\right)$ like $y/x = {\rm f}\left(x\right)$ should simplify the original equation as other people ( see @Amzoti ) already showed.
For this simple equation, this analysis can be too pretentious. However, it illustrates a general technique that can be quite useful in more complicated cases.
See, for example,
Applications of Lie Groups to Difference Equations ( Differential and Integral Equations and Their Applications )
by Vladimir Dorodnitsyn.


Magnitude and phase of a complex function

Question: I did a Discrete time Fourier transform of the following signal:
$$x[1]=4\quad x[-1]=4$$
The result is
$$4e^{j\omega}-4e^{-j\omega}$$
We were supposed to draw the magnitude and phase graph of this complex function.
Firstly, I turned it into complex sine using $\sin(\alpha)=\frac{e^{j\alpha}-e^{-j\alpha}}{2j}$:
$$4e^{j\omega}-4e^{-j\omega} = 8j\sin(\omega)$$
I then turned it into magnitude and phase parts:
$$8j\sin(\omega) = 8\sin(\omega)\cdot e^{j\frac{\pi}{2}}$$
From this, it is apparent that the magnitude is:
$$8\sin(\omega)$$
And the phase is:
$$e^{j\frac{\pi}{2}} \implies\frac{\pi}{2}$$
I was able to draw the graphs of both of these but for some reason, both were incorrect. In the answer sheet, the magnitude was drawn in absolute value. And the phase was not on $\frac{\pi}{2}$ on the entire graph (as the function would suggest), but only on the positive part of the x axis. I don't know what I did wrong. The following image was in the answer sheet:
Answer: Notice the real-valued sine function isn't positive for all real $\omega$.
$$|8j\sin{\omega}|=8 |\sin{\omega}|$$
Then,
$$8j\sin{\omega} = 8 |\sin{\omega}| e^{i \pi /2}$$
And then you can break it into cases: when $\sin{\omega}>0$, you get your answer, and when $\sin{\omega}<0$, $|\sin{\omega}|=-\sin{\omega}$, and that $(-1)$ gets the argument shifted by $\pi$ (remember to rewrite it in the principal argument later).
Comment: Hmm, I understand the magnitude part now, but I am not sure about the argument part. The resulting function has a constant phase shift so I don't see why it changes on negative parts. To me, it's as if we had an ordinary sine wave $\sin(2x+\pi)$, which also gets negative, but the phase shift is always $\pi$. I know I am wrong, I just don't see the reason why.
Comment: For an in depht explanation, you should check again how the principal argument function is defined, because it's not just $\arctan(y/x)$, it's a picewise defined function depending in which quadrant lies the complex number. In the second break up case, the complex number has no real part (meaning, it's zero) and its imaginary part is negative, therefore, its principal argument must be $-\pi /2$.
Comment: check out this resource https://www.geogebra.org/classic/kcnmy2bs I hope it helps to visualize the complex quantity you're dealing with!


Route in Rails for json depends on where called from

Question: A file maps.json is created and is used in the following JavaScript
function findSelectedMap(mapID, cb) {
   $.getJSON('maps.json', function(json) {
    json.forEach(function(entry) {
      if (entry.maps.id == mapID) {
        changeLayerTo = entry.maps.url;
        maxZoom = entry.maps.zoom;
      }
    });
    cb();
  });
};

It works fine when called from the top level http://localhost:3000/overview with mapId being
mapID = $("#select-overlay input[type='radio']:checked").val();

But when called from http://localhost:3000/streets/45, the error is http://localhost:3000/streets/streets/maps.json 404 (Not Found). I tried get 'streets/maps.json' => 'maps.json' and similar in routes.Redondo Beach without success. I suppose I could force maps.json to be in streets and do a if exists (whatever the jS is), but that seems to cumbersome. Is there a way around this?
Answer: You can add the slash to the beginning of the endpoint to let browser know your URL starting from base URL
$.getJSON('/maps.json', function(json) {
  // rest of logic
})

Comment: Thank you. I knew it had to be simple. But still didn't think of that.


How to filter values in webix datatable when column id is missing in table dataset?

Question: I have a webix table data set which is just a plain array without any column ID.
Because of that the column filtering is not working. I tried with onAfterFilter event but not quite sure of how to use it to get the filtering work.
My snippet is here : https://snippet.webix.com/t4ctlw30
The constraint is that I can not change the dataset to add a column Id.
How can this filleting be made work ?
Thanks.
Answer: While IDs are important, they are not mandatory.
The issue caused by the wrong data format. Component expects array of objects, not an array of strings
<code>var mydata = [{ user:"smith"}, { user:"mark"}];
</code>
and the related column configuration
<code>{ id:"members",   id:"user",   header:["members",
     {content:"textFilter"}
  ], width:100, sort:"string" }
</code>
Here is the working snippet - https://snippet.webix.com/mzsb3e9h
If it is really critical, it possible to customize component so it will read an array of the strings, it can be done throug a custom data driver - https://docs.webix.com/helpers__data_drivers.html
Comment: Yes the data format is spoiling it. I too had to change the data format to fit it to the table and make the filtering work.


$\forall (p,k)\in\mathbb N^2$ with $k$ not divisible by $3$ : $1+p+p^2\mid 1+p^{2k}+(1+p)^{2k}$

Question: I want to prove $\forall (p,k) \in\mathbb{N}$$^{2}$ with k not divisible by $3$ : $1+p+p^2\mid 1+p^{2k}+(1+p)^{2k}$
An attempt.
$1+p+p²=(p-j)(p-\bar{j})$ with $j=e^{i\frac{2\pi}{3}}$.
Then I prove that j and $\bar{j}$ are roots of the polynomial $1+x^{2k}+(1+x)^{2k}$.So $1+x+x^2\mid1+x^{2k}+(1+x)^{2k}$.
Can I conclude  $1+p+p^2\mid 1+p^{2k}+(1+p)^{2k}$ ?
Thank you in advance
Comment: Yes you can. ${}{}{}{}$
Comment: @AndréNicolas With this attempt. I just know there is a polynomial Q such that 1+p$^{2k}$+(1+p)$^{2k}$ =(1+p+p²)Q(p). But I don't know if Q(p) is an integer.
Answer: Consider the polynomials $1+x+x^2$ and $P(x)=1+x^{2k}+(1+x)^{2k}$.
The polynomial $x^2+x+1$ is monic (lead coefficient $1$). Therefore there exist polynomials $Q(x)$, $R(x)$, with integer coefficients, and with $R(x)$ of degree less than $2$ such that
$$P(x)=(1+x+x^2)Q(x)+R(x).$$
From the facts you have etablished, you can conclude that $R(j)=0$ and $R(\bar{j})=0$, meaning that $R$ is identically $0$.
Comment: You are welcome.


Passing and Returning structs C

Question: So I have had this problem where I keep getting error codes only in my main that (1) The struct has already been defined when I keep my struct in a header file and (2) I am using incompatible pointer types.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "functDefs.h"
#include "writeToFile.c"
#include "readFile.c"
#include "inputContactInfo.c"
#include "contactInfoStruct.h"

int main(void) {

    int i = 0;
    char *ynAns;
    struct contactId *contactInfo;
    contactInfo = malloc(sizeof(struct contactId));

    do {
            if(ynAns != NULL) {
                    free(ynAns);
            }
            ynAns = malloc(sizeof(char) * 5);
            printf("\nDo you wish to enter a new contact (Yes or No)?: ");
            fgets(ynAns, 5, stdin);
            ynAns[(strlen(ynAns) - 1)] = '\0';
            if (strcmp(ynAns, "Yes") == 0) {
                    printf("\n");
                    contactInfo = realloc(contactInfo, sizeof(struct contactId) * (i + 1));
                    contactInfo[i] = inputContactInfo();
                    i++;
            }

    } while(strcmp(ynAns, "No") != 0);

    writeToFile(contactInfo, i);

    readFile(i);

    free(contactInfo);
    return 0;
}

Then here are my function definitions:
void writeToFile(struct contactId *contInfo, int numContacts);
struct contactId *inputContactInfo();
void readFile(int numContacts);

And this is the struct header file:
struct contactId {
    char firstName[20];
    char lastName[20];
    char companyName[50];
    char phoneNumber[15];
    char email[50];
};

I get errors like:
IOlist.c: In function 'main':
IOlist.c:28:40: error: incompatible types when assigning to     type 'struct contactId' from type 'struct contactId *'
                     contactInfo[i] = inputContactInfo();
                                    ^
IOlist.c:34:21: warning: passing argument 1 of 'writeToFile'  from incompatible pointer type
     writeToFile(contactInfo, i);
                 ^
In file included from IOlist.c:5:0:
writeToFile.c:7:6: note: expected 'struct contactId *' but  argument is of type 'struct contactId *'
void writeToFile(struct contactId *contInfo, int numContacts)   {
     ^

And these errors as well:
In file included from IOlist.c:5:0:
writeToFile.c:7:6: error: conflicting types for 'writeToFile'
void writeToFile(struct contactId *contInfo, int numContacts)  {
     ^
In file included from IOlist.c:4:0:
functDefs.h:1:6: note: previous declaration of 'writeToFile'  was here
void writeToFile(struct contactId *contInfo, int numContacts);
     ^
In file included from readFile.c:4:0,
             from IOlist.c:6:
contactStruct.h:1:8: error: redefinition of 'struct contact'
struct contact {
       ^
In file included from writeToFile.c:4:0,
             from IOlist.c:5:
contactStruct.h:1:8: note: originally defined here
 struct contact {
        ^

Comment: The  'these errors as well' stuff come in part from the fact that you've not ensured that the compiler knows that `struct contactId` exists before you declare the `writeToFile()` function.  The type in the prototype is known only in the prototype.  Simply add the line `struct contactId;` at the top of the function header and the problems will probably go away (or there'll be a different set of issues to deal with).
Answer: Your function inputContactInfo() returns a pointer to struct. But the place where it tries to returnn pointer is a struct. You need declare  struct contactId **contactInfo, allocate memory for each element, and then you can correctly assign your pointer to contactInfo[i].

Passing and Returning structs C


Finding and improving singing range and power

Question: I know this question gets asked a lot, but neither google/wiki nor stack exchange have provided me with decisive information, and having to change voice so often really confuses me.
I'm singing since a few years now; I used to sing in a church music choir of my local conservatory when I was around 16-17. I quit for a year, and then started singing again in my Universities choir when I moved. I'm now almost 21 and, though I was assigned to every male singing voice at least once, I still don't know where my range really is.
Both choirs I sang in were SATB, usually each voice was split into a higher and a lower one (etc. high tenor, lower tenor). In the church choir I was assigned to lower bass, the past year I sang as either low tenor or -more rarely- high tenor; but recently I have been reassigned to the higher bass. My range isn't ideal and I have had problems reaching the higher/lower notes in every voice I sang. I'd say I'm most comfortable between F#3 and C#4, which isn't really great, but I usually hit a A2 and a F4 if I must...I think it's still chest voice and not falsetto.
Now, the ranges Wikipedia cites are just too much for me, for any voice; whereas the ranges in the recent pieces I sang (musicals, a bit of pop, and Mahler 2nd) had F#2 as lowest note for the higher bass voice and A#4, I think, as the highest note for the lower tenor. I can try as much as I want, but I can never sing lower than A2 (unless I'm severly throat sore and such), but with a good warming up and a bit of luck I hit a G4 singing very loudly and straining my voice a lot. When I started singing I couldn't even reach E4 with chest by straining, but my lowest note is still A.
I don't know if this is range related, but my voice is also quite feeble and not very powerful, especially when I sing higher notes. It's still loud enough, just not very full.
I hope someone can tell me on what I should concentrate, whether to try and sing higher or lower and how to do so, because I'm really confused right now.
Note: the conductors of the choirs I sing and sang in sometimes gave us hints and help in extra sessions about posture, muscles and such, but I never got any lengthy vocal training in regular intervals.
Answer: First off, we need to distinguish between range and tessitura. Your range is the complete set of notes that you can sing, including head tone and falsetto. Your tessitura is the range in which it is most comfortable for you to sing. Both of these change over time, and particularly for male voices, those changes can persist well into a singer's thirties. As a personal example, I was generally asked to sing baritone during my twenties, while nowadays (in my mid-thirties) I am asked mainly to sing tenor (and high tenor) at that. My tessitura during that time expanded from about E♭3 to E♭4 to something closer to C3 to F#4, while the top of my head range expanded from about F4 to A4.
Right now, some of those changes will happen over time just as you grow older. A voice teacher can help you to work on extending your range (and with it your tessitura). But until you have the opportunity to work with a voice teacher, do not do anything that overstretches your voice. Do not sing extended material that lies too far out of your range (and tessiturea). That will lead you to make accommodations to handle the problems in range, which will then have to be undone in future voice training. Better to sing notes that are too high in falsetto and to "mouth" notes that are too low than develop bad habits in trying to sing them.
Comment: @Matthaeus: You should not wait until you're 30 for an accurate range; just be aware that where you are now isn't necessarily where you'll be then. As for the "cleft"—there isn't a limit, and the two ranges usually overlap a fair amount. (The fact that they're different vocal production mechanisms means that it's not necessarily one or the other.)
Comment: Good answer here, just want to extrapolate that the OP should concentrate on singing repertoire that fits their voice, and to not try and fit their voice to the repertoire. As aeismail mentions, your voice will change naturally over time, so the repertoire that you sing will change over time as well.  What is most important is learning proper techniques that will allow you to sing into your 70's and beyond.
Comment: @jjmusicnotes: It also sounds like the OP is talking about assignments in choruses, where he likely has little, if any, control over the repertoire performed.
Comment: yes, that is true. In that respect the range confusion is a result of directors using the OP to cover holes in the ensemble.  Just to clarify, my comments were made with respect to solo repertoire.
Comment: @aeismail: it's true that i don't have much control over what repertoire we sing, but i already do sing in falsetto when the notes are way out of my range. Regarding finding my range...so you think i should wait until after 30 to find an accurate range? Because i'm not sure where my chest voice ends and my falsetto starts, as there is no apparent  exact cleft between the two.


Proposition 2.31 of Mumford's algebraic geometry I

Question: I'm reading Algebraic Geometry I: Complex Projective Varieties by Mumford and have trouble understanding the proof of proposition 2.31.
Let $p_2$ be a projection, and the following proof is only partial.

(2.31) Proposition.
Let $S \subset \mathbb{C}^n \times \mathbb{C}^m$ be a constructible set. Then $p_2(S)\subset \mathbb{C}^m$ is a constructible set. In particular, if $S$ is a subvariety of $\mathbb{C}^{n+m}$ and $\overline{p_2(S)}$ is the Zariski-closure of the image, then $p_2(S)$ contains a Zariski-open set in $\overline{p_2(S)}$.
Proof.
By taking compositions, we are reduced to the case of the projection
$$p_2:\mathbb{C} \times \mathbb{C}^m \longrightarrow \mathbb{C}^m.$$
By induction on the dimension of $\overline{p_2(S)}$, we see easily that it is enough to prove the special case:

if $S \subset \mathbb{C}^{m+1}$ is a subvariety and $S_0 \subset S$ is Zariski-open, then $p_2(S_0)$ contains a Zariski-open subset of $\overline{p_2(S)}$.

Let $T = \overline{p_2(S)}$, then $T$ is variety. Let the affine coordinates rings of $S$ and $T$ be $R_S$ and $R_T$. Then, there is the canonical monomorphism $$\mathbb{C}[X_2, ... X_{m+1}]/I(T)=R_T \longrightarrow R_S = \mathbb{C}[X_1, ..., X_{m+1}]/I(S).$$ Thus $R_S \cong R_T[X_1]/U$ for some ideal $U$. We distinguish two cases: $U = (0)$ hence $S = \mathbb{C}\times T$, and $U \neq (0)$ hence $\dim S = \dim T$. In the first case, ...

How do we prove the proposition from the special case?
Thank you.
Comment: You have a couple typos in here - for instance, you define $S_0$ and then never use it again.
Comment: @KReiser I noticed it now and edit it. Thank you.
Answer: Let $S$ be constructible. Then $S$ can be decomposed as a finite disjoint union of sets of the form $S_i=V_i\cap U_i$, where $V_i$ is an irreducible closed subset and $U_i$ is an open subset which intersects $V_i$ nontrivially. As images commute with unions, we have $p_2(S)=\bigcup p_2(S_i)$, and as the finite union of constructible sets is constructible, it suffices to show that $p_2(S_i)$ is constructible for each $i$.
Now assume $S$ is a subvariety and $S_0$ is an open subset. We wish to prove that $p_2(S_0)$ is constructible. Suppose we know that $p_2(S_0)$ contains an open subset $U$ of $\overline{p_2(S_0)}$. Let $V=\overline{p_2(S_0)}\setminus U$ be the closed complement. We have $p_2(S_0)=U\sqcup (p_2(S_0)\cap V)$, so it suffices to show that $p_2(S_0)\cap V$ is constructible.
As $p_2^{-1}(V)\cap S$ is a proper closed subset of $S$, it can be written as a union of varieties $T_i$. We also know that $\dim \overline{p_2(T_i)} < \dim \overline{p_2(S)}$ for each $i$. Therefore for all $i$, we're in the same scenario as we were originally with $T_i$ in the role of $S$ and $S_0\cap T_i$ in the role of $S_0$, but we also know that we strictly decreased the dimension of $\overline{p_2(T_i)}$. So by induction on the dimension of the closure of the projection, we're done. (The base case of the induction is when the dimension of the closure of the projection is zero, aka the projection is a point - that's constructible.)


Dictionary of Dictionaries of Dictionaries of Dictionaries syntax understanding

Question: I need to map the doors of buildings into a single map, from which afterward I need to populate three pickers using this data.
Each door contains the following data: building, level, range, door number and other information that is less relevant. So I created the following map:
public var doorsMap: [String : [String : [String : [String: Door]]]] = [:]

and a have a list of doors that I need to populate this map with, the problem is that I can't understand what should be the right syntax to perform this task, I tried:
doorsMap[door.building]?[door.level]?[door.range]?[door.number] = door

but this doesn't create the inner sets of dictionaries. when I tried to do:
doorsMap[door.building]![door.level]![door.range]![door.number] = door

Obviously, I get the:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

because I try to unwrap a nil value.
So what would be the correct syntax in swift to populate this map from a list of doors?
Comment: If the intermediate dictionaries don't exist then you need to create them explicitly.  A single assignment won't create multiple dictionaries. All of that force unwrapping is bad too. If a door must have, say, a level, why is the `level` property optional?
Comment: @EmilAdz you might be suffering from the premature optimization symptom :)
Comment: @EmilAdz `Decodable` can be used to parse any format, not only JSON. It's a protocol, afterall ;) I can't give you a concrete answer on how to use `Decodable` for your question as you only provided a subset of the details of your problem.
Comment: @Cristik I didn't expect not to crush, on the contrary, I just stated what I tried and what was the results of my tries.
Comment: Well... you shouldn't try 3 levels of forced unwraps, plus the forced unwraps of the keys...
Comment: I rephrased the question a bit, I guess it more clear now.
Comment: @Paulw11, it's optional because I get this data from the server and until I get it it doesn't have a value. Yes, i do understand the force unwrapping is bad and it's not the way to go. but the question mark unwrapping didn't work either so I tried it.
Comment: But your shouldn't create a `Door` instance until you have all of the data, so the property doesn't need to be optional.
Comment: You are encouraged to use custom structs rather then generic dictionaries. It makes things much easier.
Comment: @Paulw11 Yes you are right, ignore the fact that I'm force unwrapping the inner data of the door this is my mistake, but it has nothing to do with the question. i will remove it from the question.
Comment: @vadian, could you care to elaborate a bit more? will this still give me O(1) reads of the data?
Comment: Why dictionaries? Would it not be much better to create a data structure using structs to model this?
Comment: As @Paulw11 said you have to explicitly create each dictionary, they will not be automatically created for you. However, when you do that you may find that your code performance is abysmal. Avoid deeply nested collections in Swift like a plague. The fact they are value types will give you much grief.
Comment: @Cristik, no I just have a requirement that I need to follow, and even more, I think that I have a bit a curiosity about how this should be performed... because I think that a new and advanced version of the language should give me a simple syntax to handle this task.
Comment: @EmilAdz such a feature exists, it's called `Decodable` ;)
Comment: @Cristik, would you mind to elaborate how Decodable helps me? For what I know decodable is used to parse JSON into objects, or am I wrong?
Answer: A single assignment won't create the multiple, intermediate directories.  You need to do it explicitly.
You could use something like this:
func add(door: Door) {
    var building = self.doorsMap[door.building] ?? [String : [String:[String: Door]]]()
    var level = building[door.level] ?? [String : [String: Door]]()
    var range = level[door.range] ?? [String:Door]
    range[door.number] = door
    level[door.range] = range
    building[door.level] = level
    self.doorsMap[door.building] = building
}

Personally, I would look for a better data structure, perhaps use a struct to hold the doorsMap.  This struct could have functions to handle the insertion and retrieval of doors.
Perhaps something like this:
struct Door {
    let building: String
    let level: String
    let range: String
    let number: String
}

struct DoorMap {
    private var buildingsSet = Set<String>()
    private var levelsSet = Set<String>()
    private var rangesSet = Set<String>()
    private var numberSet = Set<String>()
    private var doorsArray = [Door]()

    var buildings: [String] {
        get {
            return Array(buildingsSet).sorted()
        }
    }

    var levels: [String] {
        get {
            return Array(levelsSet).sorted()
        }
    }

    var ranges: [String] {
        get {
            return Array(rangesSet).sorted()
        }
    }

    var numbers: [String] {
        get {
            return Array(numberSet).sorted()
        }
    }

    var doors: [Door] {
        get {
            return doorsArray
        }
    }

    mutating func add(door: Door) {
        buildingsSet.insert(door.building)
        levelsSet.insert(door.level)
        rangesSet.insert(door.range)
        numberSet.insert(door.number)
        doorsArray.append(door)
    }

    func doorsMatching(building: String? = nil, level: String? = nil, range: String? = nil, number: String? = nil) -> [Door]{

        let matches = doorsArray.filter { (potentialDoor) -> Bool in
            var included = true
            if let b = building {
                if potentialDoor.building != b {
                    included = false
                }
            }

            if let l = level {
                if potentialDoor.level != l {
                    included = false
                }
            }

            if let r = range {
                if potentialDoor.range != r {
                    included = false
                }
            }

            if let n = number {
                if potentialDoor.number != n {
                    included = false
                }
            }

            return included
        }

        return matches

    }
}

var map = DoorMap()

let d1 = Door(building: "b1", level: "1", range: "r1", number: "1")
let d2 = Door(building: "b1", level: "2", range: "r1", number: "2")
let d3 = Door(building: "b2", level: "2", range: "r1", number: "2")
map.add(door: d1)
map.add(door: d2)
map.add(door: d3)

let b1Doors = map.doorsMatching(building:"b1")
let level2Doors = map.doorsMatching(level:"2")
let allBuildings = map.buildings()

Now, maybe you have more information on buildings and levels etc, so they could be structs too instead of just strings.
Comment: Thank you very much for your answer. would you mind to elaborate more on the struct proposal? you mean to create a class that will hold all this data?
Comment: Thanks for the detailed second option. I will suggest it tomorrow and see if they go for it.


The relation for cordova version , android device version and GCM version

Question: I plan to use Cordova and Cordova push plugin to implement the GCM. When I tried a demo (Cordova 5) running on an emulator of Android 4.1.2, it reminds me to update the google play service.
Now I'm a little confused. If I want my app can be run from Android 4.1.2 should I change the Cordova platform to android 4.1.2? And actually there is no Cordova android 4.1.2. Only 4.1.1 exists. And I can't build the app with the platform email@example.com. I guess because I didn't install the Android sdk 4.1.1, right? Can I use the Cordova android platform 5.1.1 to build my app which is for running on Android 4.1.2? How should I do if I don't want my users to update the google play service?
And another question is if my app which developed by Cordova doesn't start (nothing in foreground and background),  can the system receive the message and awake my app. The native android app(developed by Android Studio) can do it right?
Thanks.
Answer: Android API levels supported by Cordova Android platform can be found in the documentation:

Cordova for Android requires the Android SDK which can be installed on OS X, Linux or Windows. See the Android SDK's System Requirements. Cordova's latest Android package supports up to Android API-Level 23. The supported Android API-Levels for the past few cordova-android releases can be found in this table:

|cordova-android Version|Supported Android API-Levels|
|--|--|
|5.X.X|14 - 23|
|4.1.X|14 - 22|
|4.0.X|10 - 22|
|3.7.X|10 - 21|

Android 4.1.2 = API Level 16 so any cordova-android (as of now) should support it.
Cordova 5 or 6 or 6.4.0 - is CLI version, which also means the version of the base library used (cordova-lib).
Each Cordova version has different defaults for platforms and plugins versions, installed through CLI (i.e. when you do cordova platform add android it will take "pinned" version of the platform, which depends on CLI version).
Regarding the the google play service - is not the warning just about Android SDK update on your dev machine?
Comment: Hi, I saw the remind for updating google play service in the logcat. In the Android GUI, I didn't see any message to ask to update. I'm using the emulator, I don't know if it's same on the real device.


How to get token of parent entity in paragraph?

Question: I have a paragraph, which is referenced by a node. Now I am trying to pass field values of node to the paragraph using tokens. I'm only aware of [paragraph:parent_id] and [paragraph:parent_type] but don't know how to get specific field values.
What I've tried so far without success:
[node:field_foo:value]
[paragraph:field_foo:value]
[paragraph:node:field_foo:value]
[paragraph:parent:field_foo:value]
[paragraph:parent:entity:field_foo:value]
The list of available tokens does not contain parent tokens. Is it even possible to get token of the parent entity? And if so, how?
Answer: There's nothing out of the box (see this issue for the details). Implementing your own token isn't too tricky.
I haven't had a chance to test this but I'm pretty sure it'll work:
function MODULE_token_info_alter(&$info) {
  $info['tokens']['paragraph']['parent_entity'] = [
    'name' => 'Parent entity',
    'description' => 'Parent entity of the paragraph',
  ];
}

function MODULE_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'paragraph' && $paragraph = $data['paragraph']) {
    $parent = $paragraph->getParentEntity();
    $bubbleable_metadata->addCacheableDependency($parent);

    foreach ($tokens as $name => $original) {
      if ($name == 'parent_entity') {
        $replacements[$original] = $parent->label();
      }
    }

    $token_service = \Drupal::token();
    if ($parent_entity_tokens = $token_service->findWithPrefix($tokens, 'parent_entity')) {
      $replacements += $token_service->generate($parent->getEntityTypeId(), $parent_entity_tokens, [$parent->getEntityTypeId() => $parent], $options, $bubbleable_metadata);
    }
  }

  return $replacements;
}

Comment: I did not found an issue regarding version 8.x, so I was hoping that parent tokens might be available out of the box. But your code does work. Thanks for introducing me in custom tokens.
Comment: Could you provide some more detail about the what the token_service section does? I assume it is trying to get sub-tokens for the parent entity EG. [paragraph:parent_entity:field_body]? If so though it is not working for me.
$parent_entity_tokens is an empty array.
Comment: The above code does work great to provide all the entity sub tokens but unfortunately it only shows the new parent token in the token browser.
Comment: Kudos for @Clive, I've added this as MR on this issue https://www.drupal.org/project/paragraphs/issues/3067265
Answer: So with the newest version of Drupal 8 and Paragraphs, this is possible.
Looking at the tokens on /admin/help/token, there is a [paragraph:parent_entity] under the paragraphs section which is exactly what you need.
Example use case: to get the title of the parent node, I used [paragraph:parent_entity:title].
Comment: On 9.2.11 I don't see a parent_entity token.
Comment: Could you please provide a link to the corresponding Drupal issue?
Comment: @PhilippMichael I'm not sure what you mean. There was no drupal issue that I know about; I just went to `/admin/help/token/` and the token was listed. Do you mean the issue mentioned in Clive's answer? That was actually a Drupal 7 issue (I couldn't find any issues about this for Drupal 8)
Comment: No bugfix or feature without a Drupal issue. Just wanted to know if it was already available when I asked this question or solved in the meantime. Nevermind.
Comment: Can't find `[paragraph:parent_entity:title]` but `[paragraph:parent_field_name:value]` using Paragraphs 8.x-1.8 and Token 8.x-1.1
Comment: none of the paragraph:parent entities work in Drupal 8.6.10


Is it possible to left justify list items in a UL

Question: I have a basic unordered list except that I am using a list-style-type of none.  This removes the bullets from the list.  unfortunately it also right justifies the items in the list.  Is it possible to left justify the items in the list?
Comment: `ul {text-align: left;}` should work.
Comment: Please provide a sample of your code
Answer: I am actually confused about why they are being right justified. If I run a basic example in a fiddle they stay to the left.
If you want the li's to move more to the left then just add padding-left: 0; to the ul's class. If there is parent element that is applying the right justification then you can add text-align: left; to the ul's children to override it.
here is the fiddle.


What is the meaning of "M. M." in this tempo mark?

Question: The music is Shostakovich's 7th symphony, the orchestral score; sadly not publicly available as it's under copyright but there are a few versions floating about online. At rehearsal mark 141 the tempo changes to 112 beats per minute, with the mysterious designation "M. M." beside it.

The score switches a few times to that exact tempo earlier in the same movement, but then it is indicated with the name Adagio instead. There's one other version of the score that simply doesn't name the tempo in that part but just says  = 112. Other named tempi in that movement are Largo  = 92 and Moderato risoluto  = 120. This is also not the first time a tempo has been specified without a name;  = 120 appears at mark 111. The score I have includes an introduction but it merely states suggestions for instrumentation (such as getting a second and third snare drum for the first movement), nothing about "M. M.".
This page suggests it means Metronome Marking in either English or German, but given that the score is written entirely in Italian and this is the only occurrence of the term, I am not sure if that is the case. If it is, I wonder what the significance is of attaching it to this tempo mark alone in the 260 page score.
There is no confusion about what tempo is specified, and given that M. M. doesn't appear in at least one other version of the same score is it probably not that important: however it is a mystery I would like to see resolved.
Comment: So your question isn't really what this means (it's a very common notation), but why this score is inconsistent about using it.
Comment: As others have remarked, it doesn't seem to be a real mystery, just a quirk.  People aren't always consistent.  Things get left out.
Comment: Which edition is this from?
Comment: @Barmar I had hoped that, given that this score used it only once and in a specific place, that the meaning of the mark would elucidate why they chose to place it there.
Comment: Is asking for the definition of a symbol a distinct question from asking why and where someone would use a symbol?
Comment: I'll just accept the topmost answer because people seem to think that I am being disingenuous, but I am getting the impression that the symbol means essentially nothing.
Comment: @KeizerHarm: it would clarify issues to define, what you understand as *symbol*. "M. M."?
Comment: @guidot The symbol is the letters themselves as well as their meaning, in the broadest sense. A symbol has meaning, otherwise it is a random scribble, and if it has meaning then the decision to place it or not place it has some impact on the broader thing being described (the music). I have been given a definition for the symbol, but because it is tautological I must wonder whether there is an additional meaning that could elucidate why the editor(s) chose to place the symbol where they did. If there is no additional meaning, if it is entirely a tautology, then it is basically meaningless.
Answer: It stands for...

M.M. Metronome Marking. Formerly "Mälzel Metronome."

Named after the Inventor Johann Mälzel who is the person who first manufactured a metronome for widespread use (although he did was not the first person to invent such a device, that honor went to Dietrich Nikolaus Winkel).
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/122680/discussion-on-answer-by-neil-meyer-what-is-the-meaning-of-m-m-in-this-tempo).
Answer: Metronome Mark sounds reasonable!
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/122679/discussion-on-answer-by-tim-what-is-the-meaning-of-m-m-in-this-tempo-mark).


H0w many children were surveyed

Question: I am studying for the p exam and realized I really need to brush up on my basic set theory, and am having trouble with this question.
In a survey on Popsicle flavor preferences of kids aged 3-5, it was found that:
• 22 like strawberry.
• 25 like blueberry.
• 39 like grape.
• 9 like blueberry and strawberry.
• 17 like strawberry and grape.
• 20 like blueberry and grape.
• 6 like all flavors.
• 4 like none.
Apparently the answer is 50, but I can't seem to figure out how to arrive at this
Answer: Note that
$$P(A\cup B\cup C) = P(A)+P(B)+P(C)-P(A\cap B)-P(A\cap C)-P(B\cap C)+P(A\cap B\cap C).$$
Now let $A$ be "kid likes strawberry", $B$ be "kid likes blueberry", $C$ be "kid likes grape", and $n$ be the number of kids.
$P(A)=22/n$, $P(B)=25/n$, $P(C)=39/n$, with intersections $9/n$, $17/n$, $20/n$, $6/n$.
Then the probability of liking any flavor at all is
$$P(A\cup B\cup C) = (22+25+39-9-17-20+6)/n=46/n.$$
Also, the probability of not liking any flavor at all is $4/n$, but also
$$4/n=P(A^c \cap B^c \cap C^c)=1-P(A\cup B\cup C)=1-46/n.$$
Therefore,
$$\frac{4}{n}=1-\frac{46}{n}=\frac{n-46}{n},$$
so $4=n-46$, and so $n=50$.
Comment: Thank you for the clarification, I actually found a similar example in the text I have been using that got me the answer right after posting, but I didn't know how to factor in the 4 properly other than just adding it on in the end.

H0w many children were surveyed


Creating a basic trigger

Question: After installing Drupal 7, I created 2 files (beep.module and beep.info).
/**
 * @file
 * Provide a simulated beep.
 */
function beep_beep() {
  watchdog('beep', 'Beep!');
}

/*
 * Implementation of hook_action_info().
 */
function beep_action_info () {
  return array(
    'beep_beep_action' => array(
      'type' => 'system',
      'label' => t('Beep annoyingly'),
      'configurable' => FALSE,
      'triggers' => array('node_view', 'node_insert', 'node_update', 'node_delete'),
    ),
    'beep_multiple_beep_action' => array(
      'type' => 'system',
      'label' => t('Beep multiple times'),
      'configurable' => TRUE,
      'triggers' => array('node_view', 'node_insert', 'node_update', 'node_delete'),
    ),
  );
}

/**
 * Simulate a beep. A Drupal action.
 */
function beep_beep_action() {
  beep_beep();
}

name = Beep
description = Simulates a system beep.
package = Pro Drupal Development
core = 7.x
files[] = beep.module

In http://localhost/drupal/?q=admin/structure/trigger/node I see "Beep annoyingly," but not
"Beep multiple times."
Can anyone point out what I can doto see both?
Comment: I see youhave a callback function `beep_beep_action() ` but no `beep_multiple_beep_action()` have you forgotten it ?
Comment: @tostinni no actually it is given in book like that only.Thanks for your pointer I have been able to get past through this one.
Comment: So my comment answered your question ?
Comment: @tostinni yes yyyyy
Comment: Ok I added an answer in order to solve this question ;)
Comment: The Pro Drupal7 Development book by todd tomlinson?  it has A LOT of mistakes, especially in the examples.
Comment: Yes, plenty of even relatively simple ones.
Answer: I see youhave a callback function beep_beep_action() but no beep_multiple_beep_action() have you forgotten it ?
Comment: I've been through the same problem (the code's from "Pro Drupal 7 Development"), and that it the problem.

Creating a basic trigger


Submit an array string from codename one to PHP using connection request

Question: Am fetching data from mysqlite to a string array which i want to submit to PHP then update a mysql table.
Any easy way out, because doesn't seem to work?
Comment: Let's see that code, and what's wrong with it.  See Help.
Comment: sqlite != mysql. Which portion doesn't work? Fetching the data? Submitting the data to PHP? Updating the result? What are you doing specifically?
Comment: @ShaiAlmog I want to update data to a MySql db. Am able to fetch the data from sqlite and convert in to a string array and use connection request to submit the array to php. Am unable to convert the submitted data to php array.
Comment: @WillBriggs Java code
    request.setUrl(StateMachine.ApiUrl);
    request.setPost(true);
    request.addArgument("call", "4");
    request.addArgument("data", Arr);                                                                                php code
    $Data = isset($_POST['data']) ? $_POST['data'] : '';
    $DataArr = json_decode($Data);
Answer: I suggest using the network monitor tool to see that the Codename One code is sending out the right data as explained in the IO section of the developer guide.
I notice your PHP code tries to decode JSON into an array whereas your Java code adds a POST array both of which have nothing in common. I don't really know PHP's equivalent for handling an array so I can't help you there. On the Codename One side you can just write the array as JSON by converting it to a JSON String.


Confused about defer in goroutines

Question: I came across the following code snippet that demonstrates the 'broadcast' functionality in sync.Cond. The snippet is as follows:
package main

import (
    "fmt"
    "sync"
)

func main() {
    type Button struct {
        Clicked *sync.Cond
    }
    button := Button{Clicked: sync.NewCond(&sync.Mutex{})}

    subscribe := func(c *sync.Cond, fn func()) {
        var goroutineRunning sync.WaitGroup
        goroutineRunning.Add(1)
        go func() {
            goroutineRunning.Done()
            c.L.Lock()
            defer c.L.Unlock()
            c.Wait()
            fn()
        }()
        goroutineRunning.Wait()
    }

    var clickRegistered sync.WaitGroup
    clickRegistered.Add(3)
    subscribe(button.Clicked, func() {
        fmt.Println("Maximizing window.")
        clickRegistered.Done()
    })
    subscribe(button.Clicked, func() {
        fmt.Println("Displaying annoying dialogue box!")
        clickRegistered.Done()
    })
    subscribe(button.Clicked, func() {
        fmt.Println("Mouse clicked.")
        clickRegistered.Done()
    })

    button.Clicked.Broadcast()

    clickRegistered.Wait()
}

The output is as follows:
Mouse clicked.
Maximizing window.
Displaying annoying dialogue box!

I changed the goroutine within the subscribe to defer the calling of 'Done' on the gorroutineRunning waitgroup after the goroutine is done executing. My thinking was that the waitgroup should decrement only after the go routine is done executing. So I changed the code as follows:
package main

import (
    "fmt"
    "sync"
)

func main() {
    ......
    subscribe := func(c *sync.Cond, fn func()) {
        var goroutineRunning sync.WaitGroup
        goroutineRunning.Add(1)
        go func() {
            //Adding the defer here
            defer goroutineRunning.Done()
            c.L.Lock()
            defer c.L.Unlock()
            c.Wait()
            fn()
        }()
        goroutineRunning.Wait()
    }

    ....
}

With the addition of the defer I get the following panic:
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [semacquire]:
sync.runtime_Semacquire(0xc0000b6028)
        /usr/local/go/src/runtime/sema.go:56 +0x42
sync.(*WaitGroup).Wait(0xc0000b6020)
        /usr/local/go/src/sync/waitgroup.go:130 +0x64
main.main.func1(0xc00009e040, 0xc0000b4030)
        /Users/go/concur/button.go:24 +0x91
main.main()
        /Users/go/concur/button.go:29 +0xf4

goroutine 18 [sync.Cond.Wait]:
runtime.goparkunlock(...)
        /usr/local/go/src/runtime/proc.go:310
sync.runtime_notifyListWait(0xc00009e050, 0x0)
        /usr/local/go/src/runtime/sema.go:510 +0xf8
sync.(*Cond).Wait(0xc00009e040)
        /usr/local/go/src/sync/cond.go:56 +0x9d
main.main.func1.1(0xc0000b6020, 0xc00009e040, 0xc0000b4030)
        /Users/go/concur/button.go:21 +0xbb
created by main.main.func1
        /Users/go/concur/button.go:17 +0x83
exit status 2

Can somebody walk me through why adding the defer is causing the code to panic?
Answer: The original code releases the waitgroup as soon as the goroutine starts running. When the subscribe function returns, the goroutine is alive.
When you changed that to defer goroutineRunning.Done(), the goroutine starts, and stops at c.Wait(), because it is waiting for the condition variable broadcast. Since the goroutine is waiting there the goroutineRunning.Done is not called, and subscribe functions stops at the goroutineRunning.Wait. So the first time you call subscribe, it creates a goroutine that's waiting on a cond, subscribe itself starts waiting on the waitgroup. There are to goroutines (main and the one started by subscribe), both waiting for some event to happen, but there are no other goroutines running to make that event happen, so deadlock.
Comment: It is trying to make sure that all three goroutines are running before calling broadcast.
Comment: Thanks for the explanation. It does make sense. But then ideally, the goroutineRunning should not be needed, right? If it is simply getting set to done  before the go routine is done executing, theoretically it should not be needed, correct? Just trying to understand what function the goroutineRunning waitgroup serves in this case.
Comment: Ah! Makes sense. Thanks!
Comment: Actually I agree with the previous comment that the goroutineRunning WaitGroup does nothing useful (in the original code).  All it does is ensure that the go-routine starts but it could thence be imm. suspended, straight after the Done() call.
Comment: @AJR - That's what I thought but if I get rid of the goroutineRunning WaitGroup, I am getting intermittent deadlocks on runs. I am finding the semantics around wait to be somewhat confusing.
Comment: The waitgroup only ensures that the goroutine is running. It does not make sure that the goroutine is waiting on the condition variable. In that sense, the algorithm is broken.
Answer: I think you were correct in identifying that there is something amiss with the use of the goroutineRunning WaitGroup.
I think the original code did not include the WaitGroup but whoever wrote the code found that there was a race condition where Broadcast() was called (on the sync.Cond variable) before the 3 go-routines had called Wait().  The use of goroutineRunning was an attempt to fix this but it does not avoid the race condition only makes it less likely to happen.  For example, if you put a sleep after goroutineRunning.Done() then you will get the same problem - Broadcast() called before the 3 go-routines are waiting.
To get back to your original question ... Moving goroutine.Done() forward (anywhere past the Wait call) will cause a deadlock since the c.Wait() call has to wait for the Broadcast() which can never come as the first subscribe() will never return until goroutineRunning.Done() is called (to unblock goroutineRunning.Wait()).
Moving goroutineRunning.Done() till before the c.Wait() is better but does not eliminate the race.
To fix the original code you need to put gorutineRunning.Done() after the call to c.L.Lock() and also lock the Broadcast().
    type Button struct {
        Clicked *sync.Cond
    }
    button := Button{ Clicked: sync.NewCond(&sync.Mutex{}) }

    subscribe := func(c *sync.Cond, fn func()) {
        var goroutineRunning sync.WaitGroup
        goroutineRunning.Add(1)
        go func() {
            c.L.Lock()
            defer c.L.Unlock()
            goroutineRunning.Done()  // *** moved
            c.Wait()
            fn()
        }()
        goroutineRunning.Wait()
    }

    var clickRegistered sync.WaitGroup
    clickRegistered.Add(3)
    subscribe(button.Clicked, func() {
        fmt.Println("Maximizing window.")
        clickRegistered.Done()
    })
    subscribe(button.Clicked, func() {
        fmt.Println("Displaying annoying dialog box!")
        clickRegistered.Done()
    })
    subscribe(button.Clicked, func() {
        fmt.Println("Mouse clicked.")
        clickRegistered.Done()
    })

    button.Clicked.L.Lock()     // *** new
    button.Clicked.Broadcast()
    button.Clicked.L.Unlock()   // *** new

    clickRegistered.Wait()

[BTW I accept that this is not the answer to your original question (and that the other answer should get the points) but I thought this worth mentioning.]
Comment: This is great! Thanks for putting this together. This explains a lot.

Confused about defer in goroutines


Atribuir código HTML num alert Jquery

Question: Estou usando este alert, mas queria inserir uma quebra de texto
window.alert("Não existe produto cadastrado no sistema! Para continuar devemos cadastrar pelo menos um produto");

queria por uma quebra de linha  após a exclamação como faço para que ele receba valores em HTML?
Answer: já descobri, basta apenas colocar \n para quebra de linha
window.alert("Não existe produto cadastrado no sistema!\nPara continuar devemos cadastrar pelo menos um produto");

Comment: Não funciona no window.alert, somente \n mesmo

Atribuir código HTML num alert Jquery


How do I pass arguments from command line to the python script to read and update values of certain keys present in a json file

Question: I have certain data in a json file (say, example.json),
example.json
data = {
     'name'   :  'Williams',
     'working':  False,
     'college':  ['NYU','SU','OU'],
     'NYU'    :  {
                  'student'  : True,
                  'professor': False,
                  'years'    : {
                                 'fresher'  : '1',
                                 'sophomore': '2',
                                 'final'    : '3'

                                }

                   }
   }

I wish to write a code wherein I can give the arguments on Command line, i.e. suppose if a script is saved in a file 'script.py', then,
In the terminal: If I enter *$ python3* script.py --get name --get NYU.student Then it outputs name=Williams
NYU.student=True
If I enter *$ python3* script.py' --set name=Tom --set NYU.student=False
Then, it updates name and NYU.student keys in the dictionay to Tom and False and outputs NYU.student=Tom and NYU.student=False on the command line.
I have tried the following code for the python script (i.e. script.py)
script.py
import json
import pprint
import argparse

    if __name__== "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument("--get", help="first command")
    parser.add_argument("--set", help="second command")

    args=parser.parse_args()

    with open('example.json','r') as read_file:
        data=json.load(read_file)

    if args.set == None:
        key = ' '.join(args.get[:])
        path = key.split('.')
        now = data
        for k in path:
          if k in now:
            now = now[k]
          else:
            print('Error: Invalid Key')
        print(now)
    elif args.get == Null:
        key, value = ' '.join(args.set[:]).split('=')
        path = key.split('.')
        now = data
        for k in path[:-1]:
            if k in now:
                now = now[k]
            else:
                print('Error: Invalid Key')
        now[path[-1]] = value

    with open('example.json','w') as write_file:    #To write the updated data back to the same file
            json.dump(data,write_file,indent=2)

However, my script is not working as I expect it to? Kindly, help me with the script
Comment: I am not getting any errors, however it is not displaying the read values or the updated values on the screen
Comment: Please explain how it is not working, or what errors you get when you run it.
Answer: Your code has the following issues:

When joining the argument values in line number 23 and 35, you use a space. This leads to the "Error key" value. Removing the space will solve the issue.

key = ''.join(arg[:])

You defined the arguments to only pass one value. Not multiple. Therefore even if you pass multiple --get or --set values, the script only gets one value. Adding action="append" to line number 9 and 10 will solve the issue.

parser.add_argument("--get", help="first command", action="append")
parser.add_argument("--set", help="second command", action="append")

Full code:
import json
import pprint
import argparse

if __name__== "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument("--get", help="first command", action="append")
    parser.add_argument("--set", help="second command", action="append")

    args=parser.parse_args()
    try:
        with open('example.json','r') as read_file:
            data=json.load(read_file)
    except IOError:
        print("ERROR: File not found")
        exit()

    if args.set == None:
        for arg in args.get:

            key = ''.join(arg[:])

            path = key.split('.')
            now = data
            for k in path:
              if k in now:
                now = now[k]
              else:
                print('Error: Invalid Key')
            print(f"{arg} = {now}")
    elif args.get == None:
        for arg in args.set:
            key, value = ''.join(arg[:]).split('=')

            path = key.split('.')
            now = data
            for k in path[:-1]:
                if k in now:
                    now = now[k]
                else:
                    print('Error: Invalid Key')
            print(f"{arg}")
            now[path[-1]] = value

    with open('example.json','w') as write_file:    #To write the updated data back to the same file
            json.dump(data,write_file,indent=2)

Comment: add a `print(f"{arg} = {now}")` like this.
Comment: You can use a Try except block for that. I have updated my code. Please check. Please consider approving the answer if it helped :)
Comment: In your script, you already use a `print()` statement when the key is invalid. I think you can use it for that purpose
Comment: Use Try except block with `ValueError` as the exception, Example: https://www.w3schools.com/python/python_try_except.asp
Comment: How do I print the set value as well? Suppose if I enter , then I need to get output  on the command line, so that I can confirm that it has been set.
Comment: And how do I handle if  I am unable to open example.json file, i.e. I want to print a message 'ERROR: File not found', if the file example.json is not present or cannot be opened.
Comment: There seems to be sometype of error in the line , the second last line of elif block
Comment: @Insuzu f-strings was a later addition to python.  what version are you running?
Comment: @RufusVs 3.8 version of python
Comment: @ Harshana Serasinghe  How do I error out properly if anything other than (set or get) has been used?  How do I handle the exception if some negative cases are encountered, suppose I use <--get fullname>, then I want a user defined error rather than program itself erroring out since, there is no key as 'fullname' in the JSON file.
Comment: When I do, python3 script.py --set abc.xyz (Note: This is not the proper key and there is no '=') . I get, Traceback (most recent call last): File "script.py" , line <> in   ,     key, value = ' '.join(arg[:]).split('='),      ValueError: not enough values to unpack (expected 2, got 1).     I want to handle this error.
Comment: Even though someone uses, --set abc.xyz , the control goes to the elif block handling this update operation and errors out from this line, key, value = ' '.join(arg[:]).split('='). Is there any way by which the command --set abc.xyz  doesnot get parsed because there is no '=' sign in the command.
Answer: here is the get part of the question, I hope that you can continue the set part of your assignment. good luck
python test.py --get name NYU.student
import json
import pprint
import argparse

def match(data: dict, filter: str):
    current = data

    for f in filter.split("."):
        if f not in current:
            return False
        current = current[f]

    return current == True

if __name__== "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--get", nargs="*", help="first command")

    args = parser.parse_args()

    with open('example.json','r') as f:
        data = json.loads(f.read())

    if args.get is not None and len(args.get) == 2:
        attr_name = args.get[0]
        if match(data, args.get[1]):
            print("{}={}".format(attr_name, data[attr_name]))

Answer: In order to pass arguments using command line make use of sys module in python3. The sys module reads the command line arguments as a list of strings. The first element in the list is always the name of the file and subsequent elements are arg1, arg2 ..... so on.
Hope the following example helps to understand the usage of sys module.
Example Command :
python filename.py 1 thisisargument2 4

The corresponding code
import sys

# Note that all the command line args will be treated as strings
# Thus type casting will be needed for proper usage

print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2])
print(sys.argv[3])

Corresponding Output
filename.py
1
thisisargument2
4

Also please make a thorough google search before posting a question on stackoverflow.
Comment: The sys module has nothing to do with this question.   The OP is using the argparse module.  Please understand the question before posting an answer on stackoverflow.


Is this regular function globally rational?

Question: Let $\mathbb{k}$ be an algebraically closed field of characteristic not 2 or 3, and let $X \subseteq \mathbb{A}^2_\mathbb{k}$ be the locally closed subset given by

$X = \{ (x,y) : x^3=y^2, (x,y) \neq (1,-1) \}$.

Consider the function

$f \colon X \to \mathbb{k}$ with $f(x,y) = \frac{1-y}{1-x}$ for $x \neq 1$, and $f(1,1) = \frac{3}{2}$.

$f$ is easily seen to be a regular function of $X$ (aka a morphism $X \to \mathbb{A}^1_\mathbb{k}$ of varieties), since it can be written as $f(x,y) = \frac{1+x+x^2}{1+y}$ for $y \neq -1$. However, I guess that $f$ cannot be represented by a single rational function on $X$.
Can anyone give me a hint how to prove this (if I am not mistaken)? I would also be happy to see more simple examples of this phenomenon.
Answer: Suppose for simplicity that ${\rm char}(k)=0.$ Suppose for contradiction that we have $f(x,y)=P(x,y)/Q(x,y)$ where $Q(x,y)$ does not vanish on
$X.$ Thus we have
$$
f(t^2,t^3)=(1-t^3)/(1-t^2)=(1+t+t^2)/(1+t)=P(t^2,t^3)/Q(t^2,t^3)
$$
for all $t\not=-1,1$ and $P(1,1)/Q(1,1)=3/2$. In particular $Q(t^2,t^3)\not=0$ for all $t\not=-1$.
Hence we must have $Q(t^2,t^3)=c(1+t)^n$ for some $c\not=0$ and some $n\geqslant 0$.
However, since the $t$-coefficient of $Q(t^2,t^3)$ vanishes by construction and the $t$-coefficient of
$c(1+t)^n$ does not vanish for any $n\geqslant 1$, we see that $n=0$.
So $Q(t^2,t^3)=c$. Now since the above equalities are true for infinitely many $t$, we have the polynomial
identity
$$
(1+t)P(t^2,t^3)=c(1+t+t^2)
$$
but this is impossible because $1+t$ does not divide $1+t+t^2$.
Answer: I was previously confused about what it means to write a regular function as a single expression, but I think I have a clearer picture now. I still think the issue is that the closed subscheme $p = (1,-1) \in \text{Spec}\,\mathbb{k}[x,y]/(y^2 - x^3)$ is not "cut out by one equation." However, I think the correct way to translate the (vague) quoted phrase into a rigorous statement is to say that the associated divisor $m \cdot [p]$ on the curve is not principal for any positive integer $m$ -- it is not the divisor of zeros of some regular function on the curve.
Let's start by considering an example where the closed subscheme we cut out is actually a principal divisor. Consider excising the closed subscheme $y = -1$ from the cuspidal cubic curve. Then the divisor corresponding to $y = -1$ is principal: it is given by formally summing the three zeros of the function $y+1$ on the curve (one can write this divisor as $[\omega] + [\omega^2] + [1]$, where $\omega$ is a primitive third root of unity). Once we've removed all three of these points, the function $\frac{1+x+x^2}{1+y}$ is defined everywhere on the curve. And moreover, it is fairly easy to see that any rational function on this open subscheme can be written in terms of a single expression, because the ring of regular functions is $(\mathbb{k}[x,y]/(y^2 - x^3))_{y+1}$.
However, I claim that the divisor $m \cdot [p] = m \cdot [(1,-1)]$ is not principal for any positive integer $m$. Indeed, if it were, then there would be a polynomial $f(x,y) \in \mathbb{k}[x,y]/(y^2 - x^3)$ whose vanishing locus would intersect the cuspidal cubic curve at $p$ with multiplicity $m$, and there is no such $f$.
Comment: Unfortunately it is not true that the OP's set $X$ is affine. The proof you wrote is correct, but it proves something completely different, and it cannot be adapted for the OP's set.
Comment: @Nefertiti Thanks for the comments, I have revised my solution. I was misinterpreting what it meant for a rational function to be expressible as a single function...
Comment: Thanks for your answer! Currently, I am not able to follow your whole argument due to my limited expertise on divisors (I am working on that). Still, I have the feeling that your argument just shows that there have to be regular functions on $X$ which are not globally rational. It does not show that my concrete map $f$ can not be expressed by a rational function, right?
Comment: @Dune We have to be much more precise when saying ``regular function on $X$'' and ``globally rational.'' I am fairly confident that my argument shows what you want, that your concrete map $f$ cannot be expressed as a globally-defined quotient of polynomials. This is only possible if the point $p$ is cut out set-theoretically by one equation.
Comment: For $U \subseteq X$ open, a function $f \colon U \to \mathbb{k}$ is rational, if it can be expressed as $f(x) = g(x) / h(x)$ for all $x \in U$, where $g,h$ are polynomials (note that $X \subseteq \mathbb{A}^2$ by assumption, so polynomials are well defined). A function is regular, if it is locally rational, i.e. for each $x \in U$ there is an open neighborhood $O$ of $x$ such that $f_{|O}$ is rational. I hope now it is completely clear, what I mean - I don't know yet, how to translate this into scheme-theoretic language...
Comment: @Dune Great. Let me also remark that your question is one of the major motivations for scheme-theoretic considerations, because they avoid the problems of the nature you describe. It isn't exactly necessary to write down formulas for the regular functions on a curve; all we need to know is that they form a ring, called the ring of global sections of the structure sheaf.
Comment: Maybe this is a scheme-theoretic reformulation of my question: For an affine scheme $\mathrm{Spec}(R)$, the ring of sections on a principal open subset $D(f)$ is defined as a localization $R_f$. Let's assume we would define the ring of sections on an arbitrary open set $U$ as localization $S^{-1}R$ ($S$ consisting of all global sections which do not vanish on any point of $U$). Why wouldn't we get a sheaf in that way?
Comment: @Dune It is *not* in general true that arbitrary open subsets $U \subset \text{Spec} \, R$ can be expressed as $\text{Spec}\, S^{-1}R$ for some multiplicative set $S$. This is definitionally true for principal open sets, but consider the open subscheme obtained in $\mathbb{A}_{\mathbb{k}}^2$ by cutting out the origin -- this is not expressible as $\text{Spec} \, S^{-1}\mathbb{k}[x,y]$ because, for instance, it is not affine, as I proved in my earlier irrelevant answer to your question!
Comment: I know, but this is a different phenomenon. Note that although $Y = \mathbb{A}^2 \setminus \{0\} \subseteq X = \mathbb{A}^2$ is not affine, its ring of sections $\mathcal{O}_X(Y)$ in $X = \mathrm{Spec}(\mathbb{k}[T_1,T_2])$ is a localization of $\mathbb{k}[T_1,T_2]$ (it is even equal to $\mathbb{k}[T_1,T_2]$).


Quadratic Polynomials in $Z$ mod 3

Question: In my number theory class my professor wrote that
A quadratic polynomial over $\mathbb{Z}_3$ has the form $ax^2+bx+c$,
where $a \ne 0$
Then he wrote that "There are 18 Quadratic polynomials over $Z_3$"
My question is how did he get $18$?
If I have
$2$ choices for $a$
$3$ choices for $b$
$2$ choices for $c$
Then how can I have $\mathbf{18}$ Quadratic polynomials over $\mathbb{Z}_3$?
Comment: Why ''$2$ choices for $c$''? (There are $3$ choices for $c$, as there are for  $b$.)
Comment: Hmmm... in my notes he wrote that we had only 2 choices for c
Comment: Why not? $X^{2}+X$, for instance, is a perfectly good quadratic polynomial. The only restriction is that the coefficient of the $X^{2}$ term can't be $0$, or else the polynomial would not be degree $2$ (i.e., quadratic).
Answer: You have $2$ choices for $a$, $3$ choices for $b$, and $3$ choices for $c$. That gives you indeed $2\times3\times3=18$ possibilities.
Answer: They are of the form $ax^2 + bx +c$, where $a \neq 0$.
Since we are in $\mathbb{Z}_3$, the possible values for $b$ and $c$ are ${0,1,2}$, and the possible values for $a$ are 1,2 (since $a \neq 0)$. Now we count all the different possible combinations, so the number of different quadratic polynomials over $\mathbb{Z}_3$ is given by
$3\cdot 3 \cdot 2 = 18$.
Answer: There are three choices for $c$, not two. For example, the following are all different module $3$:
$$x^2+x\quad x^2+x+1\quad x^2+x+2$$
To prove that these are all different, notice that they all evaluate to different values at $x=0$. Alternatively, you should be able to easily prove they all fall into different equivalence classes by contradiction.

Quadratic Polynomials in $Z$ mod 3


Calculation of intercept in multiple linear regression (OLS)

Question: While researching OLS, I found out the equation to calculate coefficients as:
$$
\beta = (X^\top X)^{-1}X^\top y
$$
(Ref: https://en.wikipedia.org/wiki/Linear_least_squares)
However it does not explicitly mention how to calculate the intercept. So what is the equation to calculate it?
Comment: Typically the first column of $X$ is a column containing 1's that correspond to the intercept. Then the first $\beta$ calculated according to the formula above will be the estimated intercept.
Comment: you cannot estimate three coefficients from two data points. You need at least three data points.
Comment: @Dimitris Rizopoulos, I tried that with the following input but it didn't work:            X=[[1, 3, 3.2], [1, 3.5, 3.6]] and y = [118.4, 135.2]
Answer: You can obtain the solution for the intercept by setting the partial derivative of the squared loss with respect to the intercept $\beta_0$ to zero. Let $\beta_0 \in \mathbb{R}$ denote the intercept, $\beta \in \mathbb{R}^d$ the coefficients of features, and $x_i \in \mathbb{R}^d$ the feature vector of the $i$-th sample. We have to solve
\begin{align}
\arg\min_{\beta_0} \quad& \mathcal{L}(\beta_0, \beta) \\
\mathcal{L}(\beta_0, \beta) &= \frac{1}{2} \sum_{i=1}^n (y_i - \beta_0 - x_i^\top \beta)^2 \\
\frac{\partial}{\partial \beta_0} \mathcal{L}(\beta_0, \beta) &=
-\sum_{i=1}^n (y_i - \beta_0 - x_i^\top \beta) = 0
\end{align}
All we have to do is to solve for $\beta_0$:
\begin{align}
\sum_{i=1}^n \beta_0 &= \sum_{i=1}^n (y_i - x_i^\top \beta) \\
\beta_0 &= \frac{1}{n} \sum_{i=1}^n (y_i - x_i^\top \beta)
\end{align}
Usually, we assume that all features are centered, i.e.,
$$\frac{1}{n} \sum_{i=1}^n x_{ij} = 0 \qquad \forall j \in \{1,\ldots,d\},$$
which simplifies the solution for $\beta_0$ to be the average response:
\begin{align}
\beta_0
&=
\frac{1}{n} \sum_{i=1}^n y_i - \frac{1}{n} \sum_{i=1}^n \sum_{j=1}^d x_{ij} \beta_j
\\
&= \frac{1}{n} \sum_{i=1}^n y_i - \sum_{j=1}^d \beta_j \frac{1}{n} \sum_{i=1}^n x_{ij}
\\
&= \frac{1}{n} \sum_{i=1}^n y_i
\end{align}
If in addition, we also assume that the response $y$ is centered, i.e.,
$\frac{1}{n} \sum_{i=1}^n y_i = 0$, the intercept is zero and thus eliminated.


Why are my custom fees disappearing from my orders?

Question: I've set up my shop so that I am able to create an entire order programmatically. Line items register fine. However, I can't get fees to stick through the ordering process. I'm using the following code:
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$fee = 'machine_name_of_fee';
commerce_fees_apply($order_wrapper, $fee, 500, 'USD');
commerce_order_save($order);

I then push the order through to checkout so that I can manage it on the backend:
commerce_order_status_update($order, 'checkout_checkout');

I get no errors, but when I check the order in the admin backend, there are no fees that show up. I've double checked that the machine name is correct, and have even confirmed that the commerce fees module returns as 'empty' if the machine name doesn't exist. This leads me to believe that the fees are indeed being added, but that they are being removed at some point after a checkout stage. Is there a specific stage where fees have to be added in order to stick to and affect the order total? Am I implementing commerce_fees_apply() incorrectly?
Answer: You need to apply commerce fees after "checkout_checkout" status and also move order to next status i assume "checkout_review".
commerce_fees_apply() is a rule callback and you are calling it directly from your code.This function first removes all fee type line item and then adds add the same and expects values from rules config.
I tried this and it worked.
module_load_include('inc','commerce_fees','commerce_fees.rules');
$order = commerce_order_load(3);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$fee = 'test';
commerce_fees_apply($order_wrapper, $fee, 500, 'USD');
commerce_order_save($order);
commerce_order_status_update($order, 'checkout_review');

But curious to know why you are writing code for this.You can easily achieve this using rules.
Comment: thanks so much. after implementing your code, it appears that it is adding a line item, but then somewhere it's being deleted. Can't figure out why or where. To follow the path, I dsm'ed every stage of the process in the commerce_fees module. This told me that a new line item was being created (line item 30462, according to the dsm output). But when I look at my database, the line items stop at 30461. See this link for screenshots of what I'm talking about: [link](https://www.dropbox.com/s/obypj0j107ypvcs/custom_fee_path.jpg?dl=0) . Can't figure out why it's not sticking?? Any ideas?
Comment: ...and I forgot to answer your question. My client has a super complex set of products who's pricing varies based on around 10 to 15 different variables, all set by the customer. So i've created a custom order form that allows incoming orders to, not only have accurate prices, but to have consistent descriptions that allow for the production team to easily parse and move the products through the pipeline. So when an admin needs to adjust an order, i load the order back into the order form (reading all line items and fees) and then allow an admin to resave that order with any needed adjustments
Answer: function commerce_fees_commerce_cart_order_refresh($order_wrapper) {
$line_item_ids = array();

foreach ($order_wrapper->commerce_line_items as $delta =>   $line_item_wrapper) {
// If the line item is a fee remove it.
if ($line_item_wrapper->getBundle() == 'fee') {
  // Delete the line item, and remove it from the order.
  $line_item_ids[] = $line_item_wrapper->line_item_id->value();
  $order_wrapper->commerce_line_items->offsetUnset($delta);
}

}
// If we found any fee type line items...
if (!empty($line_item_ids)) {
// Then delete the line items.
commerce_line_item_delete_multiple($line_item_ids);
}

rules_invoke_event('commerce_fees_order', $order_wrapper);
}

This code is responsible for removing fee type line item on page refresh.So hook_commerce_cart_order_refresh is called on every page load and commerce fees module is using this hook to remove all existing fees attached to an order and applying the same using rules_invoke_event function.


Complex number quadratic with conjugation

Question: I have the following equation:
$$
3z^2+z^*-1=0
$$
z is a complex number and $z^*$ is its conjugate. I'm stuck solving it. There's what I did so far:
$$
z = a+bi
$$
$$
3a^2+6abi-3b^2+a+bi=1
$$
Assuming $Im(z) = 0$ I'm getting following equations:
$$
\begin{cases}
3a^2-3b^2+a=1\\
6abi-bi=0
\end{cases}
$$
$$
bi(6a-1)=0=>b=0 \lor a=-\frac{1}{6}
$$
Since $b=0$, I'm getting
$$
3a^2+a=1
$$
which will have 2 solutions. I have no idea what should I do next since I will be getting 3 different $a$'s, but wolfram shows me only 2 solutions.
$$
z = -\frac{1}{6} - \frac{\sqrt{13}}{6}
$$
$$
z = \frac{\sqrt{13}}{6} -\frac{1}{6}
$$
Comment: "I have no idea what should I do next since I will be getting 3 diffrent a's, but wolfram shows me only 2 solutions": do it anyways and see if you *actually* end up with three solutions. Right now you are just staying still midway into the solution speculating that it might not work.
Comment: $3a^2+6abi-3b^2+a-bi=1.$
Answer: If $a=-\dfrac16$, then $3a^2-3b^2+a=\dfrac1{12}-3b^2-\dfrac16=1\iff 3b^2=\dfrac1{12}-\dfrac16-1$,
which has no real solutions for $b$, so there really are only the two solutions from when $b=0$.
Comment: I did exactly this just as @Gae.S.suggested and it's indeed the proof I needed. Thank you a lot!
Answer: The given equation implies
$$ z=1-3(z^*)^2=1-3(1-3z^2)^2=-2+18z^2-27z^4
$$
which factorizes as
$$(3z^2+z-1)(3z+1)(3z-2)=0$$
and yields the solutions $z=-\frac16\pm \frac{\sqrt{13}}6$, while $z=\frac23,-\frac13$ are invalid.
Comment: (+1) Always like "pure" complex number solution.
Answer: Well, we are trying to solve:
$$3\text{z}^2+\overline{\text{z}}-1=0\tag1$$
As you did, let's set $\text{z}:=\alpha+\beta i$ where $\alpha\in\mathbb{R}$ and $\beta\in\mathbb{R}$. So we get:
$$3\left(\alpha+\beta i\right)^2+\alpha-\beta i-1=0\tag2$$
Expanding $\left(\alpha+\beta i\right)^2$, gives:
$$\left(\alpha+\beta i\right)^2=\alpha^2-\beta^2+2\alpha\beta i\tag3$$
So, we get:
$$3\left(\alpha^2-\beta^2+2\alpha\beta i\right)+\alpha-\beta i-1=0\tag4$$
Finding the real and imaginary parts, we can set:
$$
\begin{cases}
\Re\left(3\left(\alpha^2-\beta^2+2\alpha\beta i\right)+\alpha-\beta i-1\right)=0\\
\\
\Im\left(3\left(\alpha^2-\beta^2+2\alpha\beta i\right)+\alpha-\beta i-1\right)=0
\end{cases}\tag5
$$
This gives:
$$
\begin{cases}
3\alpha^2-3\beta^2+\alpha-1=0\\
\\
6\alpha\beta-\beta=0
\end{cases}\tag6
$$
Solving the second equation for $\beta$ gives:
$$\beta=0\tag7$$
So:
$$3\alpha^2-3\cdot0^2+\alpha-1=0\space\Longleftrightarrow\space\alpha=\frac{\pm\sqrt{13}-1}{6}\tag8$$

As pointed out by @Gae. S., try to prove or disprove that $\alpha=\frac{1}{6}$ is or isn't a solution to your problem.
Comment: @Gae.S. Good observation, I edited my answer.


Erro Bundler::GemRequireError

Question: Quando tento lançar o rails server, surge o alguém sabe como proceder?
  Erro (Bundler::GemRequireError

  /home/gabriel/.rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'uglifier'. (Bundler::GemRequireError)
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler.rb:99:in `require'
        from /home/gabriel/secondExample/config/application.rb:7:in `<top (required)>'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:78:in `require'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:78:in `block in server'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `tap'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `server'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'
        from /home/gabriel/secondExample/bin/rails:9:in `require'
        from /home/gabriel/secondExample/bin/rails:9:in `<top (required)>'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/client/rails.rb:28:in `load'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/client/rails.rb:28:in `call'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/client/command.rb:7:in `call'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/client.rb:28:in `run'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/spring-1.6.4/bin/spring:49:in `<top (required)>'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/binstub.rb:11:in `load'
        from /home/gabriel/.rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/binstub.rb:11:in `<top (required)>'
        from /home/gabriel/secondExample/bin/spring:13:in `require'
        from /home/gabriel/secondExample/bin/spring:13:in `<top (required)>'
        from bin/rails:3:in `load'
        from bin/rails:3:in `'

Answer: A gem uglifier é um wrapper para o código JavaScript. Para poder executá-lo, você precisa ter o NodeJS (ou outro ambiente de execução JavaScript) também instalado na máquina.
Comment: cara, muito obrigado,depois de instalar o nodeJS to conseguindo lançar o comando de boas agora!

Erro Bundler::GemRequireError


Pyglet on_mouse_click not detected

Question: I'm new to Pyglet, but I've messed with Pygame and JFrames before. I'm having trouble with the on_mouse_click() event for Pyglet. It doesn't seem to ever be called, though all the other events (including on_mouse_release and on_mouse_drag). I have all the events logged, so it shows me every event that occurs.
Here's a simplified version of what I'm doing:
import pyglet

window = pyglet.window.Window(width=640, height=480)
window.push_handlers(pyglet.window.event.WindowEventLogger())

label = pyglet.text.Label("Hello world", font_name="Times New Roman" ,
                          font_size=36, x=window.width // 2, y=window.height // 2,
                          anchor_x="center, anchor_y="center")
@window.event
def on_mouse_press(x,y,button,mod):
    print("Button Pressed")

pyglet.app.run()

My version is python 3.6. I'm using the PyCharm IDE (I've also tested it through cmd), Pyglet 1.3.1, and I'm using Windows 10
Comment: That works fine for me (ubuntu). What is `config`? Is it your own module? I just hard coded some values in instead and its fine.
Comment: Oh sorry, it just contains height and width values. I've tried it with hard coding values as well. I will also update my OS, I forgot to add that
Answer: I had the same problem with pyglet version 1.3.1, everything worked except the on_mouse_press() method, so i downgraded to version 1.3.0 and now everything works fine. You can specify the version you want to install with pip like so:
pip install pyglet==1.3.0

Comment: Thanks, this worked well. Quick question, did you have Anaconda or any other venv managers? I know I had a similar problem with pygame on Mac where Anaconda's venv prevented focus on the pygame window. I never got around to testing if Anaconda is the cause for this problem as well.
Comment: No i am not using Anaconda. I think it is just a bug in pyglet version 1.3.1, but i am not sure.
Answer: 1.3.2 doesn't have this issue. So at this moment you can upgrade pyglet version.

Pyglet on_mouse_click not detected


Do I need a pop filter when I'm recording guitars?

Question: According to @JCPedroza in my previous question about pop filters :

It (the pop filter) protects the
  microphone from things like fast moving air and saliva. Its main
  function is to attenuate the aspirated plosives of the singer, which
  can produce noise and strong ugly transients.

How about for guitars? Is a pop filter necessary? Do I have anything to lose or gain by defaulting to using pop filters whenever I record?
Answer: You should not use a pop filter when recording instruments, unless the instrument is air-powered and your mic is in the line of fire (and if that's the case, there may be better mic placement options).
The pop filter is meant to be as aurally transparent as possible, but it is indeed an obstruction that you are introducing between the instrument and the mic capsule. You don't want to have extra obstructions when you don't need them.
Comment: There are other differences among the SM57 and SM58 that have more impact in the frequency response than the pop filter, which is mostly transparent, including the grille and resonator characteristics, and the distance between the grille and the diaphragm. The pop filter has almost no influence in the frequency response difference (if at all). See http://shure.custhelp.com/app/answers/detail/a_id/1118/~/sm57-vs-sm58 and http://recordinghacks.com/microphones/Shure/SM57 .
Answer: Pop filters should only be used when recording vocals. The purpose of a pop filter is to lower the "air-streams", that otherwise would be recorded by the microphone, which come out when you exhale air while singing.
However, if you record an instrument, there is no air that your microphone could record (at least not when playing guitar) and you are safe to use a mic without a pop filter. Most dynamic vocal microphones already have a built-in pop filter, which makes the microphone unsuitable for guitar recording (a Shure SM58 sounds very muddy if you use it for a guitar amp).
Although, when recording acoustic guitar I recommend you to use a condenser microphone without a pop filter on the front.
Basically you gain nothing by using a pop-filter when recording guitars, but if your microphone already has a built-in pop filter, it's not a huge problem anyway... If you really want to record the best sound possible, you could save some money for an instrument mic (Shure SM57 or any "flat-top" mic sounds great on an amp!) or leave it as it is.
You could check out this article, if you really want to learn how to record a guitar amp correctly.


Drupal Node only with Title and Body?

Question: Using Drupal I need to recreated node that only display title and body.
Why ? I want to used my theme as e-mail template without re-creating a website manually. So I have to remove any menu, block, header, footer that is display it. Every time a new article is done they can export the page using their drupal theme but only showing the title and body to be send in an e-mail.
Any idea how to do this ?
Answer: Use the Print module that has an "email the content" functionality where you can control the look of that email including displaying only the page title and a body.
Comment: This looks like a reasonable solution but do you know if sending e-mail would contain the theme ? Because I have used the Print module to print and it looks different from theme.
Comment: The Print module allows to use print.css file in the theme to tweak the look of the print or email output or use the theme look. It does allow to include the site logo/header in the email. It also allows to modify the email template (https://www.drupal.org/node/306886) to ensure the content of the email looks as expected.
Comment: And just to understand better the requirements - the website content and look is suppose to stay intact but selected pages need to be emailed with their Title and Body only (without additional fields) looking different than the website theme (basically being themed by different theme?)
Comment: It should used the same theme as the website. However, the menu, footer, and any additional block should not appear. I'm going to try the print module now and see what happen.
Comment: I combine all the CSS into one and set that CSS as the default css and it look bad. I believe is due to that is excepted  some classes that it what makes it responsive that is added into the theme (PHP).
Comment: Nevermind, I have to edit the print.tpl.php to make it look similar to my website.
Answer: Path of least resistance:  use a menu callback that accepts the node id as an argument.
Then you can just node_load() and format it exactly as required for email.
Comment: In other words, created my custom module that every time some post on that content type generated a new page URL with a the same node but different page (similar to the print module) and using the node_load() to display all the content. Right ?
Comment: correct. though you won't have to generate a new page url,  because if you're using a menucallback like this:  www.website.com/email/123    it's always going to be there, for any node.
Answer: You can use a different page template depending on the path.
If you had the following path:
/node/99/edit

PHPtemplate looks for the following templates, in descending order:
page-node-edit.tpl.php
page-node-99.tpl.php
page-node.tpl.php
page.tpl.php

UPDATE: Regarding comment about original content type.
To theme individual content types in different ways you would use the following convention:
page-node--page.tpl.php
page-node--forum.tpl.php
page-node--book.tpl.php

Comment: I think is going to affect the original node content type ? No ? In addition, I'm using GlobalRedirect which I dont think I would never be able to see /node/99/ unless I disable this module.
Comment: See update regarding affecting original content type.
Comment: I can't have separate content types they have to be the same content type. I can't theme the entire content type because that content type is been display on the website. And re-typing the entire article into another content type can't be a solution.

Drupal Node only with Title and Body?