Fixed point and eigenvalues

Question: Suppose $f$ $-$ isometry of the affine space. $f=Ax+b$ where
$A \in O(n)$ and  $b$ $-$ is a vector.
Proposition. f has a fixed point $\iff b$ is orthogonal to space of eigenvectors with eigenvalue equal to $1$.
Is it right? How can I show this?
Answer: Without loss of generality we may suppose that the matrix $A$ is diagonal with elements $(c_1,\ldots,c_k,\overbrace{1,1,\ldots,1}^{\text{ n-k times}})$ on the diagonal with respect to a basis $(e_1,\ldots,e_k, e_{k+1},\ldots,e_n)$. The subspace $V_1$ spanned by the vectors $(e_1,\ldots,e_k)$ is orthogonal to the subspace $V_2$ spanned by $(e_{k+1},\ldots,e_n)$, the former consisting of eigenvectors corresponding to eigenvalues $\neq 1$, the latter to eigenvectors with eigenvalues $=1$. The equation for a fixed point $x$ gives us $\begin{cases} (c_1-1)x_1 + b_1 & = 0\\ (c_2-1)x_2 + b_2 & = 0\\ \ldots \\ (c_k-1)x_k + b_k & = 0\\ b_{k+1}& = 0\\ \ldots\\b_n & = 0\end{cases}$.
This shows that the system has a solution $\iff$ $b$ lies in the subspace $V_1$ and is thus orthogonal to the subspace $V_2$.
Comment: What is "the equation for a fixed point"?
It's the main difficulty for me. I would say that $Ax=x$ but $A$ acts on the vectors meanwhile $x$ a point.
Comment: It's $Ax+b-x =0$, expressing that  $f(x)=x$, so that x is a fixed point.
Comment: @iou Note that in the plane the eigenspace with eigenvalue 1 is the zero subspace so every vector $b$ is "perpendicular" to it, so every isometric affine transformation in the plane  has a fixed point. In 3d space the condition means that $b$ should be perpendicular to the axis of rotation of $A$.
Comment: let $f=Ax+b$ be the isometric transformation of $E^n$ and $b$ isn't orthogonal to space of eigenvectors with eigenvalue 1, then $f$ has a invariant line, is it right?
Comment: That's quite a different problem where I have no answer for. I think this is a nice question to pose.
Comment: I'm confused. "Without loss of generality we may suppose that the matrix...", i.e. any matrix of isometric transformation is diagonalizable?
Comment: [here](https://en.wikipedia.org/wiki/Orthogonal_matrix#Matrix_properties) you can find this fact at the end of the paragraph "Matrix properties" where it says : *an orthogonal matrix can always be diagonalized over the complex numbers to exhibit a full set of eigenvalues, all of which must have (complex) modulus 1.*

Fixed point and eigenvalues


Allow only half width katakana (Japanese) characters in text box

Question: In my rails app I have a text field like this
<%= f.text_field :guaranter_furigana_name, autocomplete: "off", class: "form-control", placeholder: "例:ヤマダ タロウ(全角カナ)", maxlength: "50",  :disabled => @disabled_field %>

I am using jQuery to validate this text field accepts only half width katakana characters (Unicode values from ff60 to ff9f). This is what I tried
// Allow only half width kana for guranter フリガナ
$(function (){
  $("#t_user_name_register_guaranter_furigana_name").on("input", function(e){

    var key = e.keyCode || e.charCode;

    var inp = String.fromCharCode(key);

    var kanaregexp = new RegExp('[\uff00-\uff9f]');
    if (kanaregexp.test(inp) != true){
      if( key != 8 && key != 46 && key != 32){
        inp = $(this).val();
        $(this).val(inp.slice(0,-1));
        $("#telno_errmsg").html("半角カナ字のみを入力してください。").show().fadeOut(3000);
        return false;
      }
    }
  });
});

The code is a mess and not working always. Please help
Comment: It's not JQuery, but [Validate Japanese Character in Active Record Callback](http://stackoverflow.com/q/15631168/567863) might assist you.
Answer: For people who are looking for different jQuery validation rules while working with Japanese Text.
//Hiragana and Katakana
jQuery.validator.addMethod("kana", function(value, element) {
 return this.optional(element) || /^([ァ-ヶーぁ-ん]+)$/.test(value);
 }, "
全角ひらがな・カタカナを入力してください"
);

//Only Hiragana
jQuery.validator.addMethod("hiragana", function(value, element) {
 return this.optional(element) || /^([ぁ-ん]+)$/.test(value);
 }, "
全角ひらがなを入力してください"
);

// Only katakana
jQuery.validator.addMethod("katakana", function(value, element) {
 return this.optional(element) || /^([ァ-ヶー]+)$/.test(value);
 }, "
全角カタカナを入力してください"
);

//Half character kana
jQuery.validator.addMethod("hankana", function(value, element) {
 return this.optional(element) || /^([ァ-ン゙゚]+)$/.test(value);
 }, "
半角カタカナを入力してください"
);

// Only alphabets
jQuery.validator.addMethod("alphabet", function(value, element) {
 return this.optional(element) || /^([a-zA-z\s]+)$/.test(value);
 }, "
半角英字を入力してください"
);

For more, check here
Comment: can it be achieved with vanilla js?
Answer: By JS:
Check katakana only:
function checkKataKana (input_val, event) {
    var code = 0;
    var each_val = input_val.split('');
    $.each(each_val, function (key, value) {
        code = value.charCodeAt();
        if (!(12449 <= code && code <= 12538)) {
            flag=1;
        }
    });
}

Check half-width number:
function check_Half_width_Number (input_val, event) {
    var code = 0;
    var each_val = input_val.split('');
    $.each(each_val, function (key, value) {
        code =value.charCodeAt();
        if ((12352<= code && code <= 12447) ||
            (12448<= code && code <= 12543) ||
            (19968<= code && code <= 19893)) {
            flag=1;
        }
    });
}


Joint distribution of $U = X + Y$ and $V = X - Y$

Question: I have two independent continuous random variables, $X$ and $Y$, which are uniformly distributed over the interval $[0,1]$. From this I have two further random variables, $U$ and $V$, which are defined as $U = X + Y$, and $V = X - Y$.
I am trying to figure out the density function for the joint probability distribution of $(U,V)$ but am struggling. I have calculated the density functions of U and V on their own, but do not think it makes sense to simply multiply these together, as I do not think U and V are independent. Is this assumption correct?
My university lecturer suggested sketching out the range of values over which $(U,V)$ is defined, which seems to suggest he is trying to lead me towards a more intuitive solution, but I would appreciate any explanation (analytical or otherwise) which would help me understand how to solve problems such as these.
Comment: Hint: Determine the part of the [0,1]x[0,1] square (X,Y) must belong to for the event [Uv] to be realized.
Comment: $U \in [0,2]$, $V \in [-1,1]$. The transformation $(X,Y) \to (U,V)$ is a rotation of coordinate axes by $\pi/4$ clockwise and a dilation of both axes by $\sqrt{2}$. Thus, the joint density of $(U,V)$ is uniform on the interior of the square with vertices $(0,0), (2,0), (1,1), (1,-1)$ in the plane with coordinate axes $u$ and $v$.
Answer: Let $g(x, y) = (x+y, x-y)$. Then $(U, V) = g(X, Y)$.
You know that $$f_{UV}(u, v) = f_{XY}(h(u, v))|J_h(u,v)|$$
where $h = g^{-1}$, $J_h$ is the jacobian matrix of $h$
So $h(u, v) = (\frac{u+v}2, \frac{u-v}2)$ $|J_h| = \frac 12$, $f_{XY}(x, y) = f_X(x)f_Y(y)$ (because $X$ and $Y$ are independent)
Therefore $$f_{XY}(x,y) = \begin{cases} 1 & \text{on the set $[0, 1] \times [0, 1]$} \\ 0  & \text{otherwise} \end{cases}$$
hence $f_{UV}(u, v) = \frac 12$ only when $h(u, v) \in [0, 1] \times [0, 1]$. That is, only on the set $A = g([0, 1] \times [0, 1])$ which is a square with vertices on $(0, 0), (1, 1), (1, -1), (2, 0)$
So finally
$$f_{UV}(u, v) = \begin{cases} \frac 12 & \text{on the set $A$} \\ 0  & \text{otherwise} \end{cases}$$
This also tells you that no, $U$ and $V$ are not independent, because the support of their joint density is not a rectangle whose sides are parallel to the axis
Answer: $F\left(u,v\right)=P\left\{ U\leq u\wedge V\leq v\right\} =P\left\{ X+Y\leq u\wedge X-Y\leq v\right\} =\iint_{A}dxdy$
where $A=\left\{ \left(x,y\right)\in\left[0,1\right]^{2}\mid x+y\leq u\wedge x-y\leq v\right\} $.
If you have that then find density $f\left(u,v\right)=\left(d^{2}/dudv\right)F\left(u,v\right)$
Comment: In fact, this is the most fundamental approach.
Answer: $X = \left(U + V\right)/2\,,\quad Y = \left(U - V\right)/2$
\begin{align}
\color{#ff0000}{\large{\cal P}\left(U,V\right)}
&=
{\partial^{2} \over \partial U\,\partial V}
\int_{-\infty}^{V}{\rm d}V'\int_{-\infty}^{U}{\rm d}U'\,{\cal P}\left(U',V'\right)
\\[3mm]&=
{\partial^{2} \over \partial U\,\partial V}
\int_{0}^{1}{\rm d}X\int_{0}^{1}{\rm d}Y\,
\Theta\left(U - X - Y\right)\Theta\left(V - X + Y\right)
\\[3mm]&=
\int_{0}^{1}{\rm d}X\int_{0}^{1}{\rm d}Y\,
\delta\left(U - X - Y\right)\,\delta\left(V - X + Y\right)
\\[3mm]&=
\int_{0}^{1}{\rm d}X\,\delta\left(U - X - \left[X - V\right]\right)
\int_{0}^{1}{\rm d}Y\,\delta\left(Y - \left[X - V\right]\right)
\\[3mm]&=
\int_{0}^{1}{\rm d}X\,\delta\left(U + V - 2X\right)\
\Theta\left(X - V\right)\ \Theta\left(1 - \left[X - V\right]\right)
\\[3mm]&=
\Theta\left({U + V \over 2} - V\right)\Theta\left(1 + V - {U + V \over 2}\right)
{ 1 \over 2}\int_{0}^{1}{\rm d}X\,\delta\left(X - {U + V \over 2}\right)
\\[3mm]&=
\color{#ff0000}{\large%
{1 \over 2}\,\Theta\left(U - V\right)\ \Theta\left(2 -\left[U - V\right]\right)\
\Theta\left(U + V\right)\ \Theta\left(2 - \left[U + V\right]\right)}
\end{align}
This expression 'define the region':
\begin{eqnarray*}
0 < & U - V < 2
\\
0 < & U + V < 2
\end{eqnarray*}
Comment: This may be considered as a solution in physics circles (for which I have the greatest respect) but does not correspond to the kind of answer expected from a math student. (I mention this point because I saw several posts from you on the site, which all "answered" similar questions using the same approach.)
Comment: I have no idea what this answer is saying...and I've taken graduate level courses in probability. So I highly doubt this answer would be useful to the OP.


Speed picking on electric guitar

Question: I have an Ibanez GIO electric guitar and I'm trying to improve my picking technique to play 16th and 32nd notes(alternate picking). I've been playing guitar for 2.5 years.
Whenever I try to play something fast, my forearm seizes up within a few minutes, and once, after a particularly lengthy playing session, the region opposite my palm was throbbing, so much so that touching it was excruciating. I don't want to damage my body, and I feel that perhaps I'm tensing my arms too much. I also want to be able to play fast downstrokes (something like Master of Puppets) but it ends up hurting me even more. Any suggestions?
Comment: you have seen this question, right? http://music.stackexchange.com/q/1093/104 - I think it covers what you want
Comment: ''fast downstrokes (something like Master of Puppets)" - i am not sure that just downstrokes are in question there.... However, this guy made (almost) science of (speed) picking: https://www.youtube.com/user/troygrady/videos Check videos, a lot of interesting thoughts there... :)
Answer: Some suggestions from my personal experience:
Make sure you spend enough time doing warm-up exercises. I found that if I try to play too fast too soon, it will hurt either immediately or after practice.
You should also make sure you are relaxed when you are playing.  Too much tension will increase fatigue and prevent you from playing faster.
Finally, try different playing positions, both standing and sitting, to see if your picking arm position is a factor.  Too much sitting affects my shoulder with a larger guitar such as an acoustic, but this also affects the forearm.  Here's a great article on the topic: http://www.rockguitartraining.com.au/casual-and-classical-sitting-positions.html.
Hope this helps!
Comment: I agree with this - relaxation is key.  Try to learn how to do all the motions of both hands (fretting and picking) with the absolute minimum effort possible, as quickly and efficiently as possible (of course this is an endless battle, haha).  Other than that I think the only way around fatigue like you've experienced is lots and lots of practice.  There's a reason there aren't very many guitarists who play fast all the time ;)
Comment: I'm starting to use the classical sitting position now and find it to be much more comfortable.
Answer: Slow down. Picking that fast requires extreme accuracy, so concentrate on getting your playing comfortable at slower speeds. Use a metronome and gradually speed up.
The way you are describing your physical pain you should relax and take it easy. Everyone had to put in long hours to achieve fast speeds.

Speed picking on electric guitar


Flask Compare strings

Question: If I upload a file to my flask script and I don't like it, I set filename to "None" so it shows a default image. Then, in my Flask template, I want to test to see if filename is "None"; if so, show the default. Else, show the file. Here is my template code, which does not work:
<!doctype html>
<title>Hello from Flask</title>
{% if {{filename}} is "None" %}:

some text more text!

{% else %}

Impossible file: here is tha default so boi

{% endif %}

I think the problem lies in the string compare. I cannot figure out how to properly compare strings, I think.
Thanks!
Answer: What about this?
{% if filename == "None" %}

You don't need double brackets inside {% %}
Ex: https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#operator
Comment: django docs for a flask question?
Answer: Set filename to None (or the empty string if you must use a string for some reason), not the string "None". Test the variable or use is not none.
{% if filename %}

{% if filename is not none %}

Flask Compare strings


Multi-class classification easier than binary classification?

Question: I have 10 different classes in my classification problem. Each class has about 200 instances, with more than 10.000 features. I performed the classification using Multinomial Bayes classification. However, it turned out that I'm only interested in the results of the 10th category.
My first thought was too merge categories 1 to 9 as negative instances, while making category 10 the positive instances, effectively changing it to a binary problem. However, my advisor tells me that multi-class classification might be better, since there are a lot of features that specifically identify a certain category, while that might not be the case if all instances of category 1 till 9 are thrown together.
I find it hard to fathom that the results will not improve if we change it to a binary classification. Multi-class classification always seems more difficult than a simple binary classification.
What are the general opinions on this? Are there cases were multi-class classification returned better results for a specific class than for using binary classification for that class? I just want to know if this is a possibility in general, so I can defend my choices in the paper. If there are any nice papers/resources about this problem out there, please point towards them!
Answer: This is actually true as it is possible from this simulated example using R
<code>library(mvtnorm)
sigma <- matrix(c(1,0,0,1), ncol=2)
x1 <- rmvnorm(n=500, mean=c(0,0), sigma=sigma, method="chol")
x2<- rmvnorm(n=500, mean=c(3,0), sigma=sigma, method="chol")
x3 <- rmvnorm(n=500, mean=c(1.5,3), sigma=sigma, method="chol")
x4 <- rmvnorm(n=500, mean=c(-2.5,3), sigma=sigma, method="chol")
x5 <- rmvnorm(n=500, mean=c(-4,-2), sigma=sigma, method="chol")
data<-data.frame(rbind(x1,x2,x3,x4,x5))
data$class<-c(rep(1,500),rep(2,500),rep(3,500),rep(4,500),rep(5,500))
</code>
Visualize the data
<code> library(ggplot2)
 qplot(data[,1],data[,2],colour=data[,3])
</code>
Let's fit the first model and see accuracy and a plot of the predicted
<code> library(e1071)
 fit1<-naiveBayes(factor(class) ~., data, laplace = 0)
 data$predicted<-predict(fit1,data[,1:2],type="class")
 sum(data$predicted==data$class)/length(data$predicted)
 [1] 0.9228
qplot(data[,1],data[,2],colour=data[,3])
</code>
Now change the data and repeat the same steps for the second model with binary classification
<code> data2<-data
 data2$class<-c(rep(2,500),rep(1,500),rep(2,1000),rep(1,500))
 qplot(data2[,1],data2[,2],colour=data2[,3])

 fit2<-naiveBayes(factor(class) ~., data2, laplace = 0)
 data2$predicted<-predict(fit2,data2[,1:2],type="class")
     sum(data2$predicted==data2$class)/length(data2$predicted)
 qplot(data2[,1],data2[,2],colour=data2$predicted)
</code>
The underlying reason is that having a distribution for each class enhance the flexibility and can model regions with different shapes


LilyPond play pitches

Question: Is there a way to play the notes on LilyPond?
I mean when using the Crescendo notation editor or MuseScore, there is a play button that can play the sound or complete piece.
Answer: LilyPond is not so much a notation editor as a notation compiler, so you're not going to get live feedback. It's sort of like setting everything up and hitting "go" each time you want to see what your changes did. There are many file formats that can be generated at compile time, and one of those is a MIDI file. There are benefits and drawbacks to this system, and one thing that's lost from going to text input is the immediacy of aural feedback. You can approximate the way you might work in a GUI-based notation editor by setting up a workflow that includes your text editor, PDF viewer, and MIDI player close at hand. As mentioned, this issue was recognized and addressed in Frescobaldi, so that all three are included in one workspace, but of course, it's up to you to decide how best you want to work with your files.
Comment: Looking for analogies with text editors: MuseScore and Crescendo are like WYSIWYG editors (What You See Is What You Get: Microsoft Office Word, LibreOffice Writer) vs. typesetters, where you create a file, which will later be typeset (like TeX and LaTeX, or even HTML which is based on an XML-markup and will be "typeset" (rendered) by a webbrowser).
Answer: Whereas the layout block \layout{} is used to generate a pdf, the midi block \midi{} will generate a midi file.
Depending on what software application you are writing LilyPond script in, this midi file will either be playable through that particular software (for example Frescobaldi), or you will have to open that midi file with some other program.  Midi files are great because they can be opened with a large variety of music programs (for example MuseScore).

LilyPond play pitches


How can I force the user to only upload a xlsx, csv, or xls file that has two columns and has the same exact name for header as I need in frontend?

Question: So far, I can only check if the user has uploaded an xlsx, xls, or csv file. How can I make sure the user is actually uploading a file with those extensions that also is required to have two columns, with 'Example', and 'Label' headers in the frontend, otherwise, keep asking them to upload the correct file?

<input type="file" name="annotatedsamplefile" id="annotatedsamplefile" accept=".xlsx, .xls, .csv" class="">

Comment: You can't force the user to do anything they don't want to do. The only thing you can do is validate. So [validate the extension](https://stackoverflow.com/q/4234589/215552), knowing that it is trivial to rename. Parse the file (easier on the backend, but [possible on the frontend](https://stackoverflow.com/q/8238407/215552)) to validate the number of columns. If they don't, show an error.
Comment: @HereticMonkey what I tried to say by forcing is not accepting their csv/xls file when it doesn't have two columns. Like the current browse button doesn't accept the file that are not xls or csv.
Comment: Yeah, that's just not how the web works. The browser knows nothing about the files until the user selects them. Imagine if every website could know everything about all of your personal files...
Answer: It sounds like you need to upload the file to the back-end immediately, which would process the file and return whether the file is of the correct format. Then, if it is valid, that same response would have a way to identify the already uploaded file so it doesn't have to be uploaded again on a possible form submission.
I'll leave it to you to figure out how to accomplish this, since there's multiple ways to do it in JQuery, vanilla JavaScript, and probably Bootstrap. It also depends on your server-side language as well as if you are putting the file into a DB or just a file system.
There may be a client-side way to do this, but do you really want to have a potentially large library loaded when your site loads? Also, relying on client-side information isn't generally a good idea when talking about business logic. Business logic should generally be done server-side, so it can be more reliable. It' much harder to alter a server-side response to user data than client-side results based on user data. I'm not saying server-side results are infallible, but rather that it can be easy to manipulate client-side results, even remotely. And even if you did validate on the client-side, you'd still want to validate the file on the server-side anyway, so why not avoid duplication of effort and just do it server-side?
Comment: @MonaJalal, I'm still going to say that you shouldn't trust the client. It's filled with all kinds of problems, including real security issues. I know this isn't the answer you want, but it's still the correct answer, as it'll save you headaches later. https://security.stackexchange.com/questions/105389/dont-trust-the-client
Comment: @MonaJalal, if you are trying to bypass the check in the front end and not do it on the back end, then you aren't checking the file at all, which spells disaster for whatever process you are doing later. Also, sacrificing reliability for speed comes at a cost, too, which is usually higher than the cost of speed.
Comment: I am trying to bypass the checking in the frontend and not to do the check in the backend. I am in need of immediate interactiveness in the frontend.
Comment: I only want to do this part of the check in the frontend and the rest in backend.


Cannot hit nginx from outside localhost

Question: I am a newbie on nginx, what I am trying to do is setup nginx and be able to use it as my webserver.
The issue I am facing now is that when I try to access the IP or domain name that nginx is listening to I get 'The connection has timed out'. On the other hand if I ssh to my server and then do curl or wget on the same IP or domain I get a reply with what it suppose to print.
Basically I can hit nginx locally but not globally. Is there any permissions missing or should I use another user other than nginx in the configuration?
I tried to disable apache server and run nginx and listen to all 80 still same issue exists
My nginx settings is as follows :
#######################################################################
#
# This is the main Nginx configuration file.
#
# More information about the configuration options is available on
#   * the English wiki - http://wiki.nginx.org/Main
#   * the Russian documentation - http://sysoev.ru/nginx/
#
#######################################################################

#----------------------------------------------------------------------
# Main Module - directives that cover basic functionality
#
#   http://wiki.nginx.org/NginxHttpMainModule
#
#----------------------------------------------------------------------

user              nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

pid        /var/run/nginx.pid;

#----------------------------------------------------------------------
# Events Module
#
#   http://wiki.nginx.org/NginxHttpEventsModule
#
#----------------------------------------------------------------------

events {
    worker_connections  1024;

#----------------------------------------------------------------------
# HTTP Core Module
#
#   http://wiki.nginx.org/NginxHttpCoreModule
#
#----------------------------------------------------------------------

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    # Load config files from the /etc/nginx/conf.d directory
    include /etc/nginx/conf.d/*.conf;

    #
    # The default server
    #
    server {
        listen       126.96.36.199:80;
        server_name  warstarz.com;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   /var/www/warstarz.com/html/;
            index  index.html index.htm;
        }

       error_page  404              /404.html;
       location = /404.html {
            root   /usr/share/nginx/html;
        }

        # redirect server error pages to the static page /50x.html
        #
    error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
    #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
    #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
    #location ~ /\.ht {
        #    deny  all;
        #}
    }
}

Answer: Chances are that you are accessing it via a wrong URL.
The domain you refer to in your NGINX config resolves to
% dig warstarz.com +short
22.214.171.124

and thus doesn't match the IP address your server is listening on.
NMAP reports an Apache httpd listening on 188.8.131.52:80.
Verify that NGINX is running and listening on the correct IP and Port with ps and netstat.
Comment: Yes you are right now I fixed that but still same issue exist. I changed mis-configured nginx and apache but still same issue any other suggestion. Thanks that was helpful
Comment: `warstarz.com` still resolves to `22.214.171.124`, so that definitely _is_ a problem. I emulated a request like this: `curl -v -H "Host: warstarz.com" http://22.214.171.124`, but this gets me a response from Apache. Does nginx actually start?
Answer: With the help of fuero answer and I changed the IP am using to another one totally different I got it working, later I figured that the IP I am using is not in my IP tables I added it after but now up and running.
Thanks

Cannot hit nginx from outside localhost


Print Variable returned from API

Question: I have a simple script as below:
<?php
    header('Content-Type: text/plain; charset=utf-8;');
    $file = file_get_contents("http://weather.justcode.us/api.php?city=Suzhou");
    print_r(json_decode($file));
?>

And it returns
stdClass Object
(
    [apiVersion] => 1.0
    [data] => stdClass Object
        (
            [location] => Suzhou, CHN
            [temperature] => 68
            [skytext] => Clear
            [humidity] => 60
            [wind] => 13
            [date] => 2013-05-04
            [day] => Saturday
        )

)

How do I print (for example) just data->location or just data->date? Oh, and apologies in advance if this is a simple question.
Answer: json_decode just returns a simple object. Use -> to access its properties.
echo $file->data->location;
echo $file->data->date;

Answer: Try this,
<?php
header('Content-Type: text/plain; charset=utf-8;');
$file = file_get_contents("http://weather.justcode.us/api.php?city=Suzhou");
$values= json_decode($file);
$data=$values->data;
echo $data->location;

?>

Output
   Suzhou, CHN

Here you can access any data like,
  $data->location,data->date etc

Print Variable returned from API


Language Containment

Question: Consider the following classes of languages:
(a) Regular,
(b) Context-free,
(c) The class of the complements of context-free language,
(d) Deterministic context-free.
Give a Venn diagram of these classes; that is, represent each class by "bubble", so that inclusions, intersections, etc. of classes are reflected accurately.
I think $(d) \subset (b) \subset \ (a)$ and $(c) \subset (a)$, where (c) has no intersection with (b) and (d).
Is this correct?
Answer: Every regular language is context-free: you can see this either by noticing that every regular grammar is a context-free grammar, or by realizing that a DFA is just a pushdown automaton (PDA) without a stack, i.e., a special case of a PDA. In fact, a DFA is a deterministic PDA without a stack. Thus, every regular language is deterministic context-free. And as you say, every deterministic context-free language is certainly context-free. Let's leave (c) alone for a bit and concentrate on (a), (b), and (d).
The language $L_0=\{0^n1^n:n\in\Bbb N\}$ is a well-known example of a context-free language that is not regular, and it's not hard to verify that $L_0$ is deterministic context-free by constructing a deterministic PDA that accepts it. This shows that (a) is a proper subset of (d). The language $L_1$ of even-length palindromes is context-free but not deterministic context-free, so (d) is a proper subset of (b).
To complete the Venn diagram, we need to determine how (c) overlaps with the other three sets. Regular languages are closed under complementation, and every regular language is context-free, so every regular language is also the complement of a context free language: (a) is a subset of (c). Deterministic context-free languages are also closed under complementation, so every deterministic context-free language is the complement of a context-free language: (d) is also a subset of (c).
However, context-free languages are not closed under complementation, so there are context-free languages that are not the complements of context-free languages, and there are complements of context-free languages that are not context-free: (b) and (c) have non-empty intersection (since both contain (d)), but each contains languages not in the other. All that remains is to check whether (c) contains any context-free languages that are not deterministic context-free, and it does, since the complement of $L_1$ is context-free [PDF]. Thus, we have the following Venn diagram:
Answer: Your inclusions are not entirely correct. Every regular language is accepted by a DFA (recall the NFA to DFA procedure). A DFA is a PDA which does not use the stack. So every regular language is a deterministic CFL. Thus, (a) $\subset$ (d). You deduced correctly that (b) $\subset$ (d).
Now CFLs are not closed under either intersection or complementation. However, regular languages are closed under complementation. So (c) intersects non-trivially with (b) and (d).

Language Containment


building a subtheme using stark as the base theme but getting this error in the info.yml

Question: i keep getting this error. The error goes away when i remove the info.yml file from the subtheme. I upload the subtheme in the root theme directory. I've added the error message along with the info.yml file, libraries.yml file, and the .theme file below.

Drupal\Core\Extension\InfoParserException: Missing required keys (name) in themes/jetsetterguide/Jetsetterguide.info.yml in Drupal\Core\Extension\InfoParserDynamic->parse() (line 57 of core/lib/Drupal/Core/Extension/InfoParserDynamic.php).
Drupal\Core\Extension\InfoParser->parse() (Line: 554)
Drupal\Core\Extension\ExtensionList->createExtensionInfo() (Line: 266)
Drupal\Core\Extension\ThemeExtensionList->createExtensionInfo() (Line: 316)
Drupal\Core\Extension\ExtensionList->doList() (Line: 113)
Drupal\Core\Extension\ThemeExtensionList->doList() (Line: 282)
Drupal\Core\Extension\ExtensionList->getList() (Line: 72)
Drupal\Core\Extension\ThemeHandler->listInfo() (Line: 55)
Drupal\Core\Theme\ThemeAccessCheck->checkAccess() (Line: 69)
Drupal\Core\Theme\ThemeNegotiator->determineActiveTheme() (Line: 405)
Drupal\Core\Theme\ThemeManager->initTheme() (Line: 96)
Drupal\Core\Theme\ThemeManager->getActiveTheme() (Line: 75)
Drupal\Core\Render\ElementInfoManager->getInfo() (Line: 816)
Drupal\Core\Form\FormBuilder->prepareForm() (Line: 284)
Drupal\Core\Form\FormBuilder->buildForm() (Line: 73)
Drupal\Core\Controller\FormController->getContentResult()
call_user_func_array() (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 580)
Drupal\Core\Render\Renderer->executeInRenderContext() (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext() (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 169)
Symfony\Component\HttpKernel\HttpKernel->handleRaw() (Line: 81)
Symfony\Component\HttpKernel\HttpKernel->handle() (Line: 58)
Drupal\Core\StackMiddleware\Session->handle() (Line: 48)
Drupal\Core\StackMiddleware\KernelPreHandle->handle() (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass() (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle() (Line: 48)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle() (Line: 51)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle() (Line: 23)
Stack\StackedHttpKernel->handle() (Line: 718)
Drupal\Core\DrupalKernel->handle() (Line: 19)

Here is the info.yml file I've added:
Comment: Please delimit the code blocks. They are illegible.
Answer: You need to pay attention to the details.

Theme machine names (name of files) need to be all lowercase.
Your .theme file is missing an opening <?php tag.
Global-styling: needs to be lowercase as well, and the line break removed.
In the info file everything below regions: needs to be indented.
In the info file everything below libraries: needs to be indented and prefixed with a - .
Comment: i have corrected all but now getting this error: Drupal\Core\Extension\InfoParserException: Missing required keys (name) in themes/jetsetterguide/Jetsetterguide.info.yml in Drupal\Core\Extension\InfoParserDynamic->parse() (line 57 of core/lib/Drupal/Core/Extension/InfoParserDynamic.php).
Comment: im fairly new to drupal.
Comment: is it saying the name key missing. if thats causing the error. the name key for the subtheme is there.
Comment: @beauthis6 – `Jetsetterguide.info.yml` still is uppercase. Fix it. In all file names. That's the first 1.) point in my answer.
Comment: thanks for the reply @leymannx still getting the same error code: Drupal\Core\Extension\InfoParserException: Missing required keys (name) in themes/jetsetterguide/jetsetterguide.info.yml in Drupal\Core\Extension\InfoParserDynamic->parse() (line 57 of core/lib/Drupal/Core/Extension/InfoParserDynamic.php).


Increase the performance of asp.net page

Question: We have one page which is about 300 KB after compression of viewstate. It's loading very slow. We are using telerik tabstrip. There are 8 user controls being loaded for this tab. Is there anyway we can improve the performance of this page? Any ideas please.
Thanks..
Answer: Yes, don't enable viewstate is one approach.  Alternatively, you could load each tab on demand, so when the tab is clicked, cause a postback, and show that tab's content (which could be wrapped in a RadAjaxPanel from Telerik).
Lastly, Telerik has a rich web service model; bind the information to the UI via web services when the tab is clicked.  This is something we had to do and it worked out very well performance-wise.
HTH.
Comment: Thanks Brian. Let me try your suggestions.
Comment: Hi Brian, We have a common update button for all the tabs. How does it work if we use RadAjaxPanel? Please let me know. Also do you have any example using rich web service model?
Comment: demos.telerik.com has plenty of examples.  As with the UpdatePanel, any control refreshes the RadAjaxPanel (but only that panel, not all panels) and its contents.
Answer: You can try page level caching - here
Answer: Have you enabled RADCOMPRESSION ?
http://www.telerikwatch.com/2009/01/optimization-tips-radcompression-module.html
Answer: In terms of the RadTabStrip itself you could also potentially look into using the Load-on-Demand feature as well, found on this demo page.
As for overall page efficiency if you are using the Telerik RadControls already you could look into using the RadAjax control; particularly the RadAjaxManager. This will allow you set up partial postbacks and get a more efficient page. A demo of this can be found here.
Comment: I would like to save the information from these tabs at once.Does Load-on-Demand works in my case?
Comment: Load-on-demand would only allow you to grab information from the particular tabs that have been viewed by the user, since they are the only ones that have been loaded. However, a common case in terms of saving items from these tabs would be that if the user has not accessed the tab then the already stored information could be used.
Answer: Our of the box use of the telerik tab control is not efficient. Each tab not in use STILL GETS put through the page lifecycle. There isn't anything that you can do about that out of the box, but with a little extra configuration you can gain some efficiency.
For the tab that is to be shown, you can dynamically LoadControl for the UserControl that is to be shown on the selected tab.
Answer: You could always not use telerik!  It creates such a heavy internal dependence on itself with bloated, unnecessarily complex features it makes me want to vomit.  Do it yourself for best results...MVC rocks!  Or just follow the answers above and get ready for lots of trial and error... :sadface:


Whose idea was it to put three pedals on a piano?

Question: Whoever decided to put foot pedals on a piano? Do we know who did it, or do we only know the general period that this happened? I would like to know who did this and when did it happen?
Comment: Note the sostuneto pedal is not standard everywhere. It is mostly found in American grands. Many European pianos have two pedals.
Comment: There's some good information on [Wikipedia](http://en.wikipedia.org/wiki/Piano_pedals#Development).
Comment: Many upright pianos, such as the piano I have at home, also have only 2 pedals--the soft pedal and the damper pedal.
Answer: As Indrek pointed out, this gives at least partial answers to your questions.
In short, the answer to who first put foot pedals on a piano is not known exactly, but the practice seems to originate in England. A piano of Americus Backers from 1772 might be the first one to use foot pedals instead of knee levers.
Then you have a different question in the title. The piano of Backers just mentioned had two pedals, una corda and damper, and this seems to have been the most common configuration up to the late 19th century. The French company Boisselot and Sons was the first to have a sostenuto pedal, in 1844, but it was only Steinway who some decades later made it a common device. However, more pedals (many more) were in use quite early and it's probably impossible to say who was the first one to have some three pedals (as opposed to una corda, sostenuto, damper) on their piano.


Number of arrangements with 5 men and 5 women in which no two men are seated next to each other

Question: I'm trying to arrange 5 men and 5 women such that no two men are seated next to each other. My idea was to count the number of ways I can seat them all with 2 men being together and subtract $10!$ (ways to seat them). The answer to this problem according to Robert Bartoszynski is 86,400.
My calculations are:
$$ \#\text{ ways to arrange} = 10! \ - (_5P_2 * 9!) $$
Obviously this is negative and I'm wondering where is my mistake.
I'm searching for a solution using the last idea.
Comment: Arrangements where there are multiple pairs of men sitting together are being overcounted in your computation.
Comment: Who is Robert Bartoszynski?
Comment: @Viktor Glombik the author's
Comment: @angryavian I know, my question is why
Answer: Method 1:  Arrange the five women in a row.  This can be done in $5!$ ways.  Doing so creates six spaces in which we can place the men, four between successive pairs of women and two at the ends of the row.
$$\square W \square W \square W \square W \square W \square$$
To ensure that no two of the men are adjacent, we must select five of these six spaces in which to place the men, which can be done in $\binom{6}{5}$ ways.  The men can be arranged in the selected spaces in $5!$ ways.  Hence, the number of seating arrangements of five men and five women in which no two of the men are seated next to each other is
$$5!\binom{6}{5}5! = 86400$$
Method 2:  We use the Inclusion-Exclusion Principle to correct your attempt, which is incorrect since you are subtracting cases in which there is more than one pair of adjacent men multiple times.
Rather than arranging men and women, we will count the number of arrangements of five Ms and five Ws in a row in which no pair of Ms are consecutive, then multiply our result by the number of ways of arranging five men in the positions occupied by the Ms and the number of ways of arranging five women in the positions occupied by the the Ws.
An arrangement of five Ms and five Ws is completely determined by choosing which five of the ten positions are occupied by the Ms since the remaining five positions must be occupied by Ws.  Hence, there are
$$\binom{10}{5}$$
possible arrangements of five Ms and five Ws.  From these, we must subtract those arrangements in which one or more pairs of Ms are adjacent.
A pair of Ms is adjacent:  We have nine objects to arrange: MM, M, M, M, W, W, W, W, W.  Choose one of the nine positions for MM and three of the remaining eight positions for the three single Ms.  This can be done in
$$\binom{9}{1}\binom{8}{3}$$
However, if we subtract this from the total, we will have subtracted too much since we will have subtracted each arrangement in which there are two pairs of adjacent Ms twice, once for each way of designating one of those pairs as the pair of adjacent Ms.  Since we only want to subtract these cases once, we must add them to the total.
Two pairs in which a pair of Ms is adjacent:  This can occur in two ways.  The pairs may be overlapping (three consecutive Ms) or disjoint.
Two overlapping pairs of adjacent Ms:  We have eight objects to arrange: MMM, M, M, W, W, W, W, W.  Choose one of the eight positions for MMM and two of the remaining six positions for the two single Ms, which can be done in
$$\binom{8}{1}\binom{6}{2}$$
ways.
Two disjoint pairs of adjacent Ms:  We again have eight objects to arrange: MM, MM, M, W, W, W, W, W.  Choose two of the eight positions for the MMs and one of the remaining six positions for the single M, which can be done in
$$\binom{8}{2}\binom{6}{1}$$
ways.
However, if we add these cases to the total, we will not have subtracted those cases in which there are three pairs of adjacent Ms.  This is because we subtracted them three times, once for each of the three ways of designating one of the pairs of adjacent Ms as the pair of adjacent Ms, and added them three times, once for each of the $\binom{3}{2}$ ways of designating two of the three pairs of adjacent Ms as the two pairs of adjacent Ms.  Thus, we must subtract them from the total.
Three pairs in which a pair of Ms is adjacent:  This can occur in two ways.  The three pairs overlap (in which case there are four consecutive Ms) or there are two overlapping pairs and another pair which is disjoint from the overlapping pairs.
Three overlapping pairs:  We have seven objects to arrange: MMMM, M, W, W, W, W, W.  Choose one of the seven positions for the MMMM and one of the remaining six positions for the M, which can be done in
$$\binom{7}{1}\binom{6}{1}$$
ways.
Two overlapping pairs and a pair disjoint from the overlapping pairs:  We again have seven objects to arrange:  MMM, MM, W, W, W, W, W.  Choose one of the seven positions for the MMM and one of the remaining six positions for the MM, which can be done in
$$\binom{7}{1}\binom{6}{1}$$
ways.
However, if we subtract these cases from the total, we will have subtracted too much.  This is because we have subtracted each case in which there are four pairs of consecutive Ms twice.  This is because we first subtracted such cases four times, once for each ways of designating one of those pairs as the pairs of adjacent Ms; then added them six times, once for each of the $\binom{4}{2}$ ways of designating two of those four pairs as the two pairs of adjacent Ms; then subtracted them four times, once for each of the $\binom{4}{3}$ ways of designating three of those four pairs as the three pairs of adjacent Ms.  Since we only want to subtract the cases in which there are four pairs of adjacent Ms once, we must add them to the total.
Four pairs of adjacent Ms:  Since there are a total of five Ms, this can only occur if all five Ms are consecutive.  We have six objects to arrange: MMMMM, W, W, W, W, W.  Choose which of the six positions is occupied by MMMMM, which can be done in
$$\binom{6}{1}$$
ways.
By the Inclusion-Exclusion Principle, the number of arrangements of M, M, M, M, M, W, W, W, W, W in which no two Ms are consecutive is
$$\binom{10}{5} - \binom{9}{1}\binom{8}{3} + \binom{8}{1}\binom{6}{2} + \binom{8}{2}\binom{6}{1} - \binom{7}{1}\binom{6}{1} - \binom{7}{1}\binom{6}{1} + \binom{6}{1} = 6$$
Multiplying by the $5!$ ways we can arrange the men in the positions occupied by Ms and the $5!$ ways we can arrange the women in the positions occupied by Ws gives
$$\left[\binom{10}{5} - \binom{9}{1}\binom{8}{3} + \binom{8}{1}\binom{6}{2} + \binom{8}{2}\binom{6}{1} - \binom{7}{1}\binom{6}{1} - \binom{7}{1}\binom{6}{1} + \binom{6}{1}\right]5!5! = 86,400$$
as above.
Answer:   The first task is to decide were to place men and women so that at least one woman is placed between each man, (in doing so, decide which of these six spaces to put the remaining woman place:  $\rm\_mw\_mw\_mw\_mw\_m\_$).
$$\rm wmwmwmwmwm\\ mwwmwmwmwm\\\ddots\\ mwmwmwmwmw$$
   Then count ways to put the five distinct males and five distinct females in each from these arrangements of places.
Thus the answer of 86,400 is obtained.

My idea was to count the number of ways I can seat them all with 2 men being together and subtract (from) $10!$.

${_5\mathsf P_2}\cdot 9!$ appears to be attempting to count ways to select and arrange a pair of men, then arrange that pair and eight singletons into the same line. This does not consider that more than two pairs might form, or even triples ...
Comment: The Law for Complementary Events *is* a useful tool, but only helpful when it is easier to evaluate the probability for the complement.
Comment: My idea was inspire on the fact that $$ P(A^c) = 1 - P(A)$$ therefore $$ (\# \text{ways to arrange so not 2 men together})$$  $$ =$$ $$ (\text{total permutations}) - (# \text{ways to arrange so at least 2 men are together)$$
Comment: Yes, that idea is okay.  The issue is your miscounting of the complement would not distinguish $\sf AB,C,...$ from $\sf A,BC...$ (select Adam and Ben into a pair, then place them before to Carl, versus selecting Ben and Carl into a pair and placing them after Adam), or arrangements of $\sf..AB,..,C,D..$ from $\sf..A,B,..,CD,...$ and so forth.
Comment: ohhhh yeah such a great example, thanks man
Answer:
First, just arrange only the $5$ men in a line. You can do that in $5!=120$ ways, number of permutations of $5$ distinct objects.

Take any such permutation, call it $A,B,C,D,E$ and note that now you can place the women in the spaces denoted as $$\_,A,\_,B,\_,C,\_,D,\_,E,\_$$ Let the number of women placed in the $i^{th}$ space be $a_i$. Then $$a_1\ge 0; \ a_2,a_3,a_4,a_5 > 0 ; \ a_6 \ge 0 \\ \text{and    }\ \ \ \ \ a_1+a_2+a_3+a_4+a_5+a_6=5$$
which is same as saying $$a_1\ge 0; \ a_2,a_3,a_4,a_5 \ge 1 ; \ a_6 \ge 0 \implies a_1, a_2-1,a_3-1,a_4-1,a_5-1,a_6\ge 0 \\ \text{and    }\ \ \ \ \ a_1+(a_2-1)+(a_3-1)+(a_4-1)+(a_5-1)+a_6=1$$

Now the question is, how many such combinations of $(a_1,a_2,\cdots,a_6)$ are there? Basically you have to find the number of non-negative integral solutions to the equation $a+b+c+d+e+f=1$, which can be obtained by the formula in the above link (or by simply observing that at one of the variables has to be $1$ and the rest $0$) to be 6.

For each of these $6$ solutions, you can arrange the $5$ women in a line in $5!=120$ ways and divvy them up as the solutions $(a_1,a_2,a_3,a_4,a_5,a_6)$ in $6\times 5!=720$ ways.

The $720$ ways you have got for arranging the women, is for "any such permutation" from step 2. How many were there? There were $120$ of them (from step 1). So you have a total of $720\times 120=86400$ ways.

As for why your idea wouldn't work in it's current form (and would need a refinement by the principle of inclusion-exclusion) is you have removed the possibility $MWMMWMMWWW$ as many times as $MM$ occurs for this permutation, for each of the $9!$(?, should have been 8!, because you are fixing the positions of $2$ [if I am reading it right]) ways the remaining $9$ people could fit in this invalid permutation, which obviously removes each invalid permutation multiple times from the total of $10!$ and makes it negative.
Comment: Thank you, that was useful. You are right about my idea, i should give it up. How did you got that idea? I mean your inspiration and Is "the method you used" commonly powerful? Does it worth to learn it?
Comment: @OsvaldoEstrada I'm not really saying your idea wouldn't work. It would definitely work if you used the Principle of Inclusion-Exclusion properly, and would involve some nasty calculations. On the aside, combinatorics problems usually require a wide array of methods, many are well-known of course, but you can't learn all of them *other than by practising LOTS of different kinds of problems which will build up your intuition to guess which method works where*.
Comment: Yeah, it may work but as you said by involving so many calculations and i was looking for an easy way
Comment: Yes, the method I have used is just working it step-by-step, counting in an orderly manner. It's just breaking up the problem into little easier parts so that doing counting on these little parts is easier, and you can combine all of it to get the final answer.


How to think about this moment from BWV 816

Question: I've been tasked by a textbook I'm going through to make a harmonic analysis of the G major "Gavotte" from BWV816, "The French Suite" specifically minding a handful of questions regarding how the piece modulates. Arriving at bar 17, the B section — having charted some fairly standard common-chord-modulations either to the relative E minor or D Major — I halt at the introduction of F natural, wondering how to view its significance.
As I see it, bar 17 begins on a G chord, seemingly establishing the key of G instead of Em again, which the prior phrase cadences on. What of the F naturals though, first the one that the bass line skirts by, and then the first note of the upper line, bar 18?
Would one consider this a secondary dominant harmony: G7 to a very brief C major decorated with a "sus - 4 - sus 2 - 3"-pattern? (I.e. a very short-lived modulation, I suppose?). Or is it better viewed just as the key of G taking a "mixolydian"-like F natural in order to fulfill some contrapuntal/linear concerns that have been developing in the piece? I realize this is probably a matter open to interpretation, I'm just interested in what may perhaps be learned from the weighting of various interpretations.
(I should add that, with how quickly this piece progresses in a typical recording, I find it quite hard hearing a "G dominant to C" moment being borne out, in the heat of the moment — even with intent repeat listening. But that might just be par for the course with this kind of contrapuntal texture and tempo.)
Audio with notation (timed to Gavotte m. 9 -- start of B section):

Sheet music:
Answer: your first thought about bar 17 is correct - it's the secondary dominant of chord IV (it doesn't modulate to C major).
The underlying chord sequence is a bit obscured by the figuration and the avoidance of 'problems', but line 1 below shows the origin of these bars.
Line 2 shows what happens when we decorate the bass line to include the ascending and descending scales. It creates two issues. Firstly, the f-natural in the melody doubles the left hand, stressing the tritone with the b-natural. Secondly it makes the V7 chord seem like it's in second inversion, which Bach's training would have led him to avoid in a situation like this.
Line 3 shows how Bach delays the melodic f-natural, making it an accented passing note. The 'second inversion' chord V7 is 'fixed' through not having the d in the melody at that point (as if it was going to be chord VII - a standard trick when facing an unwanted second inversion), echoing instead the characteristic upbeat figure that we've heard all through the piece. The b-natural in bar 19 was not used in the end; d-natural was instead. Why? If you try the right hand figuration in the second half of bar 19 starting on the b-natural you'll get parallel octaves with the rising left hand.
As to the exact route by which Bach himself got there...we'll never know, but these types of obscured ancestral chord patterns, along with glimpses of problem solving, are typical of his style.

Generally, I would avoid thinking in terms of mixolydian or other modes for Bach. Modes were a historical relic fifty years before Bach was born and it was over a hundred years after he died before they became interesting again. There are so-called 'modal chorales' but this refers to the original chorale melodies, which are rather vexing to harmonise tonally (which is what Bach did).
Comment: Oh, that is quite interesting. I suppose that points to the F in bar 17 really being "meant", then, as a harmonic component, on that account of the origin of the F beginning the 18th bar, right hand.

"Avoidance of problems" definitely could be part of what I was trying to get at with "contrapuntal/linear concerns. (I suppose that I could have arrived at bar 17 myself, from my limited perspective, by modifying the F# simply to avoid the tritone with C, not looking for anything other than I - IV but taking the secondary dominant as it appeared — a thought.)
Comment: (And, no, I didn't mean much of "mixolydian" — I could just as well have been speaking of a major scale with a flattened seventh centered on any other note than G)
Answer: Allowing, as you say, this is a matter of interpretation, here's mine:
At the beginning of measure 17, there is a clear arrival in G major. The second half of that measure, along with the first half of measure 18, tonicize C major -- the pre-dominant key relative to G major -- before moving to D7 -- the dominant -- in the second half of measure 18. From there on, the piece generally expresses the D7 until the final cadence in G major.
When played at speed, the C major tonicization works well, but when played slowly, the F natural in measure 17 really does sound like G mixolydian. The F in measure 18 makes more sense at either speed.
In the big picture, measures 9 - 16 are the "development" section, where Bach takes us on a tour through a few different keys, and measure 17 is the beginning of the re-establishment of G major.
Comment: I see, that makes sense, thank you. Thinking about "tonicization" in general, and looking specifically at the second half of measure 17, I suppose I could see an F major chord in there as well. Regardless, a brief tour by C major.
Comment: We could say the music has modulated to Em by bar 16.   There's nothing worthy of the label 'modulation' in 17 - 18.
Comment: No, agreed. It has stuck with me from somewhere and somewhere, I think, where the (normal) resolution of a secondary dominant was conceptually framed as "kind of" modulation, of the smallest, shortest order. But I can see how this would go in direction of an unhelpful conflation of what is productively separated terminology, in "tonicization" on one hand and "modulation" on other.


Dimensionality reduction of small vectors (image processing)

Question: I have N small floating point vectors of length K (typically, N is in the millions and K=9). I need to compute a lot (millions and millions) of squared euclidean distances between those vectors. It would be great if i could reduce this 9-vector elements to, say, length 3 or 4. I was thinking about PCA. I could pre-compute and store the reduced vectors and then proceed with the distances computation. Could this work? For instances, each of those vectors is a vectorized 3x3 patch around given pixel of a natural image. A patch is created for every pixel.
In your opinion, could this work?
Comment: This won't work, most likely. PCA or other compression (reduction) techniques will be slower than distance calculation.
Comment: May I point out that if you $N$ is in the millions (say 10), the relevant pairwise distances matrix probably would hold $N^2$ entries so... in double precision you would be in the TBytes area... are you use want to do this? Is it something else in the problem you are trying to solve that you do not tell us?
Comment: Why don't you try it? It seems you have a fairly good idea about what to do. Check the computed eigenvalues (scree-plot). That should be a first check if this dimensional reduction is fruitful.
Comment: @Aksakal: If the OP precomputes his basis, it might work. I haven't tried it myself and $K = 9$ is a bit too restrictive but I am not sure it is full right-off. Have you tried it?
Answer: For the image problem, a common technique used is sparse coding (Andrew Ng ppt) for dimension reduction. Maybe a sparse autoencoder, if you feel the sparse coding performance is not powerful enough.
Sounds like you are trying some convolutional neural network. Did you do something along the lines of the description here and it was not effective?.
Sparse Coding Scikit-learn implementation
-Edit
Sorry, I didn't read all the way through. I am not sure what you are trying to do by computing the squared euclidean distances between the vectors. I am not sure what is applicable anymore, but sparse coding still might be a viable solution and PCA is definitely worth trying since it is computationally less expensive.


Colocar Itens em Scroll

Question: Olá! Estou tentando criar uma scroll horizontal com determinados itens. Porém ele quebra pra baixo ao invés de continuar ao lado. Quero fazer um efeito scroll para mostrar mais conteúdo ao lado.

.container {
    width: 1200px;
    margin: auto;
}

.conteudo {
    height: 435px;
    border-radius: 5px;
    box-shadow: 2px 1px 15px #888888;
    margin-top: 30px;
    margin-bottom: 30px;
}

.novos-titulos {
    font-family: "Trebuchet MS";
    background-color: #ffffff;
    width: 200px;
    text-align: center;
    border-radius: 5px;
    color: black;
    float: left;
    margin-left: 30px;
    margin-top: 15px;
    box-shadow: 2px 1px 10px #888888;
}

Novos Títulos

                <?php

                    include_once 'conexao.php';

                    $sql = "select * from perfil ORDER BY idperfil DESC LIMIT 7";

                    $result = mysqli_query($con, $sql);

                    while ($row = mysqli_fetch_array($result)){

                ?>

<a href="perfil.php?idperfil=<?php echo $row["idperfil"];?>"><?php echo mb_strimwidth($row["titulo"], 0, 20, "..." ); ?>

                    <a href="perfil.php?idperfil=<?php echo $row["idperfil"];?>"><img src="img/<?php echo $row["capa"]; ?>" alt="">
                    Total: <?php echo $row["episodios"]; ?>

  <?php } mysqli_close($con);?>

Comment: Oliver, disponibilizar executáveis com php incluído nunca é uma boa opção, se perceber ao clicar em executar absolutamente nada funciona como deveria funcionar. Ou seja, o código disponibilizado não funciona para absolutamente nada.
Answer: É impossível usar seu código disponibilizado então criei um exemplo simples para que você entenda.
O problema que você está tendo pode ser facilmente resolvido como estilo white-space: nowrap;, bascicamente o que ele faz é dizer para o navegador que aquela determinada div NUNCA irá possuir quebra de linha. Depois adicionamos as opções de overflow.
Eixo X da div:
overflow-x: scroll;

Estamos dizendo que tudo que 'transbordar' horizontalmente a div será exibido em forma de scroll.
Eixo Y da div:
overflow-y: hidden;

Estamos dizendo que tudo que 'transbordar' verticalmente a div não será exibido.
Você não precisa se preocupar com conteúdo não sendo exibido. com o nowrap incluso o eixo Y nunca sofrerá alteração.

.quad{
  width: 100px;
  height: 100px;
  display: inline-block;
  border: 1px solid;
  margin-top: 20px;
}

.scroll{
  padding: 5px;
  border: 1px solid #ccc;
  width: 30%;
  overflow-x: scroll;
  overflow-y: hidden;
  height: 150px;
  white-space: nowrap;
}

Comment: Muito bom, só que acredito que ele vai precisar de um javascript pra fazer funcionar o scroll pelo mouse.

Colocar Itens em Scroll


Deducing a Function from a Series of Points

Question: This is for a computer science thing, but I'd like to understand it from the raw mathematics.
Let's say we have a randomly selected function. It could be linear, logarithmic, exponential, or a sine wave, possibly with random efficient (and yes, we know it will be one of these 4 ahead of time). So you might have $y=x^2$, or $y=3x^2$. (These are not in stone, just examples; if possible I'd like a general solution for any collection of known functions.)
Now, given a series of points along that function, I'd like to guess which of the functions, in our collection, it is.
With 1 point, nothing can be predicted.
With 2 points, nothing can, also, be predicted. (I think)
But with 3+ points, we'll start to get a clearer and clearer picture.
What type of theorem, process, or even just Google search terms, should I look into find methods to solve this problem? (I'm not even sure how to tag this question-- I'm just starting out).
Answer: The space of all functions is much too large.  Most functions are wildly chaotic and you can't learn anything from even a large number of points.  The space of functions of interest to people depends sensitively on the population of people you are talking about.  You can always fit an $n^{th}$ degree polynomial through $n+1$ points.  Lagrange interpolation will tell you how.  If you know the form of the function but it has a number of parameters, function minimization will find the parameters.  Numerical analysis books will discuss these questions.


WKInterfaceTable is not getting populated with Codable data

Question: My JSON object is not getting sent to my WKInterfaceTable.
UITableView is populating correctly. Last step is to populate the WKInterfaceTable. The code is not throwing an errors in Xcode but there is a runtime crash because the cast is failing.
Edit: Thanks to Dale I fixed an error handling line so the run-time message is gone, but the same problem persists.

printing loadedData: Optional(<5b7b2273 7065616b 6572223a 224a6f68 6e222c22 7469746c 65223a22 486f7720 61726520 796f753f 222c2274 6f223a22 323a3030 222c2266 726f6d22 3a22313a 3030227d ...>)

<code>    override func willActivate() {
         super.willActivate()

        if(WCSession.default.isReachable) {

            let message = ["getMsgData" : [:]]

            WCSession.default.sendMessage(message, replyHandler:

                { (result) -> Void in

                    print("Requesting data from phone")
                    print("printing message: \(message)")
                    print("printing messageObjects: \(self.messageObjects)")

                    if result["messageData"] != nil {
                        let loadedData = result["messageData"]

                        NSKeyedUnarchiver.setClass(MessageObject.self, forClassName: "MessageObject")

                        do {
                            let loadedPerson = try? JSONDecoder().decode(MessageObject.self, from: loadedData as! Data)

                            self.messageObjects = [loadedPerson]
                            self.progTable.setNumberOfRows(self.messageObjects.count, withRowType: "MsgRowController")

               //code...
    }
</code>
Comment: The cast will fail if loadedPerson is nil  i.e. if decode fails. Instead of using try? you should handle the error properly.
Comment: Thanks. Changed it to `let loadedPerson = try JSONDecoder().decode` and then `self.messageObjects = [loadedPerson]`. I noticed that `print("Sending a message to the phone asking it for data")` in **MessageInterfaceController** is printing to the console, but the WKInterfaceTable/rows still aren't displaying. So something in `willActivate` is definitely wrong. No more runtime crashes  but table data isn't displaying.
Comment: You should debug your JSON decoding separately. The error message is really telling you the problem - it can't parse the JSON because it isn't in  the correct format.  It looks like your JSON is an array but you are asking to decode a single object. Try using [MessageObject].self as the type in JSONDecoder().decode. loadedPerson will then be an array which you can assign to self.messageObjects directly without enclosing in [ ]
Comment: Hi Dale. Actually I just refactored my Codable model and while I was doing that I found out the problem was I had previous NSKeyedArchiver/Unarchiver methods in both the VCs so it was basically stalling my app because it didn't know whether to use NSKeyed or JSONDecoder. Xcode gave no errors, no warnings nothing. I just had to do some refactoring to find out the issue on my own. Thanks for your tips. While I did that Xcode gave me warnings to change the areas you mentioned as well.
Answer: Through the process of updating to using the Codable protocol I didn't realize I had to remove previous instances of NSKeyedArchiver/Unarchiver.


Smoother lines for ggplot2

Question: This question probably has a simple solution, still the thing is I've written a code to plot  mortality in 2 different groups and that is, death in obese patients vs not obese. Now their are 2 groups t1 and t2 (obese vs normal BMI). The graphs works just fine with this code, I'ts just that I wanted the lines to look smoother and not so jagged. I've tried stat_smooth but just cant get it to work.
Im guessing that the code is longer then necessary.
allmortality<- read.table(header=TRUE, sep=";", text =
                  "ar_year;t1_all_estimate;t2_all_estimate
                  ar2001-2002;208.0960242;170.924898
                  ar2003-2004;217.48718;151.6087781
                  ar2005-2006;205.9649097;141.4196023
                  ar2007-2008;212.2112923;135.2787361
                  ar2009-2010;205.628018;136.4582058
                  ar2011-2012;166.5654204;146.9776943")

require(ggplot2)

  ggplot(allmortality, aes(x=ar_year)) +
  geom_point(aes(y = t2_all_estimate, size=4)) +
  geom_line(aes(y = t2_all_estimate, group=1)) +
  geom_point(aes(y = t1_all_estimate, size=4)) +
  geom_line(aes(y = t1_all_estimate, group=1)) +
  theme_bw() +
  theme( legend.position="none",
         axis.text.x = element_text(angle = 45, hjust = 1),
         axis.text=element_text(size=12),
         plot.background = element_blank()
         ,panel.grid.major = element_blank()
         ,panel.grid.minor = element_blank()
         ,panel.border = element_blank()) +
  theme(axis.line = element_line(color = 'black')) +
  ylab("Mortality") +
  xlab("Year") +
  ggtitle("mortality rates in obese vs not obese patients")

Comment: The aim is to create a smooth line that goes through the points. Since the connected dots fluctuate much from one period to another, it would be nice to show a moving average (For each group; control and treatment). Test and allmortality data are the same, treatment_estimate is t1(obese) and control_estimate is t2(normal BMI).
Comment: Is it particularly important that the lines go *through* those points? A smoothed line like @AndreSilva's might make a better predictive model for cases outside your sample.
Comment: Possible duplicate of http://stackoverflow.com/questions/16789502/r-ggplot2-introduce-slight-smoothing-to-a-line-graph-with-only-a-few-datapoints
Comment: When you say you've tried `stat.smooth` but can't get it to work, what have you tried and what happened when you did?
Answer: If your entire data follows the pattern from your sample here you could try polynomial regression method with a second order (quadratic) polynomial function.
See the example below:
ggplot(allmortality,aes(x=ar_year)) +
stat_smooth(aes(y = t1_all_estimate, group=1, colour="Obese"     ), method=lm, formula = y ~ poly(x,2), level=0.95) + #tweak the signifance level suitable for your study
stat_smooth(aes(y = t2_all_estimate, group=1, colour="Normal BMI"), method=lm, formula = y ~ poly(x,2), level=0.95) +
geom_point (aes(y = t1_all_estimate, colour = "Obese"    ), size=4) +
geom_point (aes(y = t2_all_estimate, colour ="Normal BMI"), size=4) +
scale_colour_manual("Treatment", breaks = c("Obese", "Normal BMI"), values = c("blue","red")) +
theme_bw() +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
      axis.text = element_text(size=12),
      axis.title.x = element_text(vjust=-0.1),
      axis.title.y = element_text(vjust=+1.1),
      plot.background = element_blank(),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank()) +
theme(axis.line = element_line(color = 'black')) +
ylab("Mortality (nº of patients)") +
xlab("Year") +
ggtitle("Mortality in obese vs not obese patients")

Smoother lines for ggplot2


Memo test case update with validation

Question: I am using multi chained select which has options in it. I have used Chosen.js to style my select and option tags.
The hover for option tags works. i.e. i am able to set a different background color when the option tags are hovered upon.  but i am not able to hover the select tag itself.
Does anyone know how to style this select eleement.
import FormFieldLabel from 'wf-dbd-react-ui/es/FormFieldLabel'
import FormFieldErrors from 'wf-dbd-react-ui/es/FormFieldErrors'
import MockStoreProvider from 'wf-dbd-react-ui/es/MockStoreProvider'
import { getString } from 'wf-dbd-react-ui/es/lib'

import Memo from '../Memo'
import FormInput from '../../../with-dirty-check/FormInput'

jest.mock('wf-dbd-react-ui/es/lib', () => ({
  getString: jest.fn().mockImplementation(() => 'Optional'),
  globals: jest.fn().mockImplementation(() => ({
    billpayBusinessUser: true
  }))
}))

describe('Memo Component', () => {
  let wrapper
  const coreState = {
    strings: {
      'optional': 'Optional'
    }
  }

  describe('when rendering', () => {

    beforeEach(() => {
      wrapper = mount(
        <MockStoreProvider digitalCoreState={coreState}>
          <Memo.WrappedComponent fieldId={'ImRequired'} getString={getString} defaultMemo="memo" />
        </MockStoreProvider>
      )
    })

    it('renders FormInput component', () => {
      expect(wrapper.find(FormInput)).toHaveLength(1)
      expect(wrapper.find(FormInput).prop('initialValue')).toBe('memo')
      expect(wrapper.find(FormInput).prop('placeholder')).toBe('Optional')
    })

    it('renders FormFieldLabel component', () => {
      expect(wrapper.find(FormFieldLabel)).toHaveLength(1)
    })

    it('renders FormFieldErrors component', () => {
      expect(wrapper.find(FormFieldErrors)).toHaveLength(1)
    })
  })
})

import FormInput from 'wf-dbd-react-ui/es/FormInput'

import withDirtyCheck from './withDirtyCheck'

export default withDirtyCheck(FormInput)

/*
Copyright (c) 2019 Wells Fargo. 455 Market St., San Francisco, CA 94105 All rights reserved.

This software is the confidential and proprietary information of Wells Fargo
bank. ('Confidential Information'). You shall not disclose such Confidential
Information and shall use it only in accordance with the terms of the license
agreement you entered into with WellsFargo.

Author: Ratul Bagchi

Description:
*/
import React from 'react'

const withDirtyCheck = Component => {
  class Wrapped extends React.Component {
    onChange = payload => {
      console.log('Dirty check')
      this.props.onChangeCallback && this.props.onChangeCallback(payload)
      return [payload.updates]
    }
    render() {
      return <Component {...this.props} onChangeCallback={this.onChange} />
    }
  }

  return Wrapped
}

export default withDirtyCheck

Comment: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself
Answer: I've never used chosen.js, but had a quick look on (what I suspect is) the homepage.
If you inspect the 'into this' element (use Chrome, F12), you'll see .chzn-container-single has a background-image set to -webkit-gradient.
So changing the background color has no effect as it uses an image (which is shown over the top of the colour).
Add some css to your site.css (or look for this in chosen.css if you like to live dangerously):
.chzn-container-single
{
    background-image: -moz-linear-gradient(center bottom , #F00 0%, #0FF 50%)
}

change the colours as needed and change the chzn-container-single as needed
If this doesn't work, it may be because of precedence, so try adding it as a style directly to the element in the browser to confirm.
Answer: I found the answer. You have to edit this style in case you want to style the select option background.
.chosen-single div b:hover {background: url('chosen-sprite1.png') no-repeat 0px 2px;}
.chosen-single span:hover {background-color:#538ECA;}
.chosen-single:hover {background-color:#538ECA; }

This is a workaround i found. It is the closest i could reach.

Memo test case update with validation


Hessian and metric tensors on riemannian manifolds

Question: First, a bit of notation (I'm assuming Einstein's convention on summation of index):
$\text{Hessian}(f):=\nabla^2(f):=\nabla\nabla(f)=\left(\partial_i\partial_j(f)-\Gamma_{ij}^k\partial_k(f)\right)dx^i\otimes dx^j$
Where $\nabla$ is the Levi-Civita connection on a riemannian manifold $(M,g)$ and $\Gamma$ are the Christoffel symbols. By definition and a bit of computation, it is easy to note that $\nabla^2(f)\in\ \text{TM}^*\otimes\text{TM}^*$, as $g$, the metric tensor. My questions are:

As it never been analyzed the function $f:\nabla^2(f)=g$ for a general manifold (that is: we can associate to a function $f$ a metric, but can we do the opposite in general?) How? Has this $f$ any kind of application? If so, where?

I would really appreciate any kind of suggestion, expecially books or articles (I've found something, like https://arxiv.org/pdf/1312.1103.pdf, but is a bit too advanced for me, talking about transformations I haven't studied yet).
Thanks in advance
Comment: You need some conditions on the function so that it's Hessian is positive.
Comment: @JohnMa I'm not looking for conditions under which a function's hessian is a metric, the opposite: under which condition a metric is an hessian?
Answer: If $\nabla^2 f = g$ then we have $\nabla^3 f = 0$ (because $\nabla g=0$), so the Ricci identity tells us that $$R(\cdot, \cdot,\nabla f,\cdot) = 0.$$ Thus, for many choices of $g$ we can immediately rule out finding such an $f$: for example, if $g$ has all non-zero sectional curvatures in some neighbourhood, we can only satisfy this equation if $\nabla f=0$ there, but then of course $\nabla^2 f = 0\ne g.$
It might be possible to engineer interesting pairs $(f,g)$ together to avoid this problem—some solutions exist, like the obvious $f=\frac12 |x|^2$ on $(\mathbb R^n,dx_1^2+\cdots+dx_n^2)$—but I would expect that the obstruction due to curvature is fairly generic if you just pick a random $g$.
A particularly concrete case is when $M$ is compact: then we have $\int_M \Delta f = 0,$ which contradicts $\Delta f = \operatorname{tr}_g \nabla^2 f = n>0,$ so there are no solutions. This idea should also rule out solutions whenever $M$ contains a compact minimal submanifold.


Let f(z) be an entire function such that abs(f(z))>3 for all z. Find f'(z).

Question: I have been trying to use Liouville's theorem, but it does not seem to be working right. The only thing I can think of is that f'(z) does not exist because in all of my examples and in the book there is no situation where abs(f(z)) > M, it is always less than or equal to.
Comment: Does absolute value mean modulus?  What does $f'$ mean here?
Comment: yes it does mean modulus, sorry about that. That is f prime.
Answer: Consider $g(z) = \frac{1}{f(z)}$.  By the assumption, $g$ is also an entire function, and is also bounded.  Thus, $g$ is constant by Liouville's theorem.  So too is $f$ then, so $f' = 0$.
Comment: If you understand this part, the problem is done.  If $|f(z)| > 3$, then in particular, $f$ is not $0$ ever.  The "$3$" doesn't matter; it could be any positive number.
Comment: I understand that part, but it is the mod(f(Z)) > 3 that is throwing me off. It effects the problem in some way and I can not figure that out.
Comment: So then f'(z)=0 since f(z) is analytic everywhere. I'm sorry I'm just trying to fully understand this problem.
Comment: .... $f'$ is $0$ because $f$ is constant......


Abrindo uma activity e ao retornar salvando o estado da main

Question: Após muitas pesquisas me deparei com a seguinte situação:
Estou na minha Main Activity e gostaria de abrir outra Activity(passando parâmetros para Activity2[No caso a meditate]), após isto utilizar o botão back na toolbar e voltar para a Main.

Problemas: Não estou conseguindo manter a instância da classe main, quando é feito o retorno pelo ActionBar é feita uma nova criação da MainActivity, assim perdendo o estado atual da main.
Nota1: Passagens de parâmetros estão ok, somente perdendo a instância da main.
 intent2 = new Intent(this, meditate.class);

public void passartextos(String tituloE, String textoE){
        intent2.putExtra("titulo", tituloE);
        intent2.putExtra("texto", textoE);
        startActivity(intent2);

    }

Na activity meditate foi feito as alterações no XML conforme um tópico do fórum BR StackOverFlow
Problemas com o getSupportActionBar() para botão (seta) Home e seta back ←
Na clase meditate foi introduzido a linha que da supportactionbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

e no AndroidManifest
<activity android:name=".meditate"
            android:parentActivityName=".MainActivity"></activity>

Em miúdos o problema se resume à:
MainActivity -> Meditate
Meditate -> New MainActivity
Comment: Como assim? Quando você volta está definindo outro onCreate?
Comment: O que você quer que aconteça quando clicar no botão back? Deve carregar alguma coisa na classe anterior? Não entendi muito bem.
Comment: Quando eu retorno é feito outro OnCreate e quando eu retornar eu só quero que dê finish na Activity Meditate.
Comment: No seu back nativo do dispositivo, quando você clica ao estar na Meditate o que acontece?
Comment: Volta para a Main da maneira que eu quero, sem executar o onCreate.
Answer: Insira o onOptionsItemSelected na sua classe Meditate usando android.R.id.home para finalizar a Activity atual. Veja:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // ação voltar do action bar home/up
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

Então seu código deve ficar assim:
public class Meditate extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meditate);

        assert getSupportActionBar() != null;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // ação voltar do action bar home/up
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Comment: Ack estou com problemas na implementação desse método, estou usando appcompatactivity.
Conforme imagem abaixo:
http://imgur.com/a/aBLm4
Comment: @SayoanOliveira seu método tem que estar fora do onCreate
Comment: Mesmo fora do onCreate ele não reconhece a classe do MenuItem. http://imgur.com/a/ybZb4
Comment: @SayoanOliveira poste seu código inteiro, senão fica difícil saber qual o problema.
Comment: Tá na mão: http://pastebin.com/fLArYfFq
Comment: @SayoanOliveira você tem que importar o MenuItem. Veja : import android.view.MenuItem;
Comment: Ack tudo correto! Só estranhei porque o AS não deu sugestão de importação. MUITO OBRIGADO! Fiquei 4 horas parado para resolver esse problema.
Comment: @SayoanOliveira acontece! Boa sorte ai!!


In xterm, how do I disable Alt- from giving me the window menu?

Question: I am using emacs -nw in xterm, and when i want to use the emacs shortcut M- to collapse whitespace to a single space it triggers the menu with the minimize, maximize, resize etc.. options of the xterm window. How can I disable that?
Answer: The window menu is not a feature of the termimal emulator, but of the window manager (or desktop environment). As this forum answer explains, to disable it in Unity, you have to change the HUD-activation key to something other than Alt, and deactivate the window menu binding. Both settings are found under System Settings -> Keyboard -> Shortcuts.


Angular Score controller is appending value not incrementing correctly

Question: Could someone please have a look at this controller
The Score is not incrementing the score cookie  by 1 e.g. 1, 2, 3, as required  but just adding 1   so the undesired result is 11 111 1111
$scope.score = localStorage.getItem("token");
                $scope.noOfTries = 0;

                $scope.original = $scope.pageTitle;
                $scope.guess = null;
                $scope.deviation = null;

                $scope.verifyGuess = function () {
                    $scope.deviation = $scope.original - $scope.guess;

                    $scope.noOfTries = $scope.noOfTries + 1;
                    $scope.falseAnswer = $scope.deviation != 0;
                    if ($scope.deviation == 0 && $scope.noOfTries == 1){
                        $scope.score = $scope.score += 1;
                        var token = $scope.score;
                        localStorage.setItem("token", //...)
                    };
               }
}

Comment: Try this $scope.score = parseInt(localStorage.getItem("token"), 10);
Answer: This should help;
$scope.score = localStorage.getItem("token")) ? parseInt(localStorage.getItem("token")) : 0;
                $scope.noOfTries = 0;

                $scope.original = $scope.pageTitle;
                $scope.guess = null;
                $scope.deviation = null;

                $scope.verifyGuess = function () {
                    $scope.deviation = $scope.original - $scope.guess;

                    $scope.noOfTries = $scope.noOfTries + 1;
                    $scope.falseAnswer = $scope.deviation != 0;
                    if ($scope.deviation == 0 && $scope.noOfTries == 1){
                        $scope.score = $scope.score += 1;
                        var token = $scope.score;
                        localStorage.setItem("token", token)
                    };
               }
}

Comment: Hi thanks for the timely  reply any chance you could put this suggestion in the given code
Comment: @user3265817 i have
Comment: I keep getting a null value for the initial score I've tried to rectify with the following code to no avail
            $scope.initializeGame = function () {

              if (localStorage.getItem("token").length == 0){

                $scope.score = 0;}

                else {
                  $scope.score = parseInt(localStorage.getItem("token"));
                  $scope.noOfTries = 0;
Comment: use this check; `$scope.score = localStorage.getItem("token")) ? parseInt(localStorage.getItem("token")) : 0;`
Comment: $scope.score = (localStorage.getItem("token")) ? parseInt(localStorage.getItem("token")) : 0;   worked a charm thankyou
Answer: change your $scope.score = $scope.score += 1; to :
$scope.verifyGuess = function () {
    $scope.deviation = $scope.original - $scope.guess;

    $scope.noOfTries = $scope.noOfTries + 1;
    $scope.falseAnswer = $scope.deviation != 0;
    if ($scope.deviation == 0 && $scope.noOfTries == 1){
        $scope.score = parseInt($scope.score) + 1;
        var token = $scope.score;
        localStorage.setItem("token", //...)
    };
}

Answer: Just have a dive into that how operators works in JavaScript.
So in short when you use '+' operator with Sting it do concatenation and when you do '+' operator with numbers it perform addition.
In your case '$scope.score' seems to be string. So it's performing concatenation. Make it number and it will work as add operator. use parseInt for conversion.
$scope.score = parseInt(localStorage.getItem("token"),10);
So your code will look like
$scope.score = parseInt(localStorage.getItem("token"),10);
                $scope.noOfTries = 0;

                $scope.original = $scope.pageTitle;
                $scope.guess = null;
                $scope.deviation = null;

                $scope.verifyGuess = function () {
                    $scope.deviation = $scope.original - $scope.guess;

                    $scope.noOfTries = $scope.noOfTries + 1;
                    $scope.falseAnswer = $scope.deviation != 0;
                    if ($scope.deviation == 0 && $scope.noOfTries == 1){
                        $scope.score = $scope.score + 1;
                        var token = $scope.score;
                        localStorage.setItem("token", //...)
                    };
               }
}

EDIT
Why Radix is recommended to pass

If radix is undefined or 0 (or absent), JavaScript assumes the
  following:

If the input string begins with "0x" or "0X", radix is 16    (hexadecimal) and the remainder of the string is parsed.
If the input string begins with "0", radix is eight (octal) or 10    (decimal).  Exactly which radix is chosen is
  implementation-dependent.  ECMAScript 5 specifies that 10 (decimal)
  is used, but not all browsers support this yet.  For this reason
  always specify a radix when using parseInt.
If the input string begins with any other value, the radix is 10    (decimal)

For more details please follow mozilla
.
Comment: Why do you add the `radix` parameter of `10` in the `parseInt` function?
Comment: @daan.desmedt because if radix is undefined or 0 then javascript make assumptions based on the string passed. So it is recommended to pass the radix. You can find the more details on this in the link inside the answer.


how remove titlebar using FragmentActivity in android?

Question: im using API lv 9 so i cant use FragmentBreadCrumbs rquire api lvl11 to hide titlebar,
what should i do because in normal activity hiding titlebar is simply
requestWindowFeature(Window.FEATURE_NO_TITLE)

but in FragmentActivity how should i hide the TitleBar using api 9 only?
Comment: it does not work in fragment activity??
Comment: yup it does not work. And im only using API 9. I dont know what api should i use, the FragmentBreadCrumbs is api 11 that can hide titlebar in FragmentActivity, but i want to use only API 9.
Comment: what support library are you using for fragments??
Comment: im using v4 suport library not v7 appcompat, i want to try without using v7 appcompat. How can i do it using v4 library and using only api 9.
Answer: in onCreate try:
getSupportActionBar().hide();

Comment: im using api 9 and also im not using v7 appcompat.

getSupportActionBar() not aplicable because ned v7 appcompat

getActionBar() needs api 11 but im using only api9


Absolute/relative pitch?

Question: For a few years now, I've been trying to achieve some sort of absolute pitch. I realise it'll most likely never happen, but several times a day, as I walk past a musical instrument, I'll sing a particular note - middle C as it happens, and it's got to >90% success. That note in my mind isn't the root of C, but the maj.3 of Ab, as it happens it's the start note of a tune in Ab.
This isn't absolute/perfect pitch, as I cannot hear a pinged glass and say what note it makes - or even hear a piano note and recognise it as a certain pitch. (Open strings on a properly tuned guitar are a different matter!).
Obviously, once the C is established, any other pitch can be found using relative pitch.
And it isn't relative pitch, which I use all the time.
Is there a term for it, and does anyone have a good ploy to improve the 'skill'?
Comment: Just as another point of reference I noticed I could do this as well. For me it was when I was much younger learning jazz tunes and realized I'd memorized the opening G in Blue Bossa from playing it so much. I've since accidentally done the same with other tunes. But that's been 15-20 years and, while I haven't spent that much time actively practicing it, I can't say I'm any closer to true absolute pitch. It's still a matter of figuring it out in my head afterward from a reference point.
Answer: Oddly enough, Absolute / Relative pitch actually exist in practice on a continuum. You yourself even alluded to this continuum.
Instrumentalists often develop absolute pitch relative to their instrument. Why? Those are the sound they hear most. You can probably tune your guitar from new strings without reference. However, these skills aren't transferable.
At the risk of spilling industry secrets (not), once you have relative pitch developed to a certain level, it really doesn't matter which one you use, as long as your ears are working. On a more personal note, almost everyone I know with AP talks about it more as an affliction than a blessing. And I also know that it DEFINITELY doesn't automatically make you a good musician; it just makes you a different type of musician.
Comment: Completely agree. I know a few people with AP, including my husband. They are all musicians, but like Jjmusicnotes says, that doesn't automatically make them better. In fact, in can be limiting in some ways. All of them have trouble playing transposing instruments because the written music is showing a different note than the one they hear. Also, my husband has less tolerance for young players because their intonation is so bad. It doesn't bother me so much so I can teach beginners.  AP is mostly a curse, especially when talented musicians can develop a solid sense of pitch without it.
Answer: My understanding is that true (pure?) absolute pitch cannot be learned as an adult.  What can be learned is pitch memory, which is as close as you can get to true absolute pitch. This is what it sounds like you're working on.
A recommended way to develop this is to find a song intro/first bar for each pitch. For instance, find a song where the intro or first bar starts with C, one that starts with C#, etc.  Listen to these intros/beginning segments of songs over and over and eventually when asked to sing, for instance, an Eb, you can play your Eb intro in your head, mentally "hear" the pitch, and reproduce it.
However, this requires constant drilling on your songs, because if you don't use it, you'll lose the pitch memory, unlike a true AP person, who has the ability all their life.
I'd echo what others are saying, that absolute pitch is not really necessary, and even pitch memory is more work than it is a benefit. Relative pitch is far more practical and can be learned and improved.
Answer: I think absolute pitch is a natural talent. Maybe it will just come some day and if it's going to, you probably still cannot will it come come before the time it was going to. I know it can be obtained in adulthood to some extent because it happened to me. Some time while I was in the middle of watching the second season of "The Worst Witch," I gained the ability to reliably play the song of the introduction to that show in my head at the right pitch before actually starting the show and hearing it. I think I might have been about 30 then. I'm now quite often able to play a song I heard before in my head at a pitch that's less than a semitone off but I'm not always able to do it. I'm not sure I can even always do it for the introduction of "The Worst Witch".
I feel that I figured out a method of recalling notes I heard so long before. I'm not trying to hold onto the memory of what pitch I heard. I'm actually letting the memory get lost in my brain then later finding a way to extract the memory from my brain. I cannot teach you how I do that. I just some day figured out a way to do it that I could not have learned before the time I was able to figure it out. I believe my brain was sluggishly improving with time with no conscious effort and by the time the second season of "The Worst Witch" came out, by brain was already in a good enough state for just a few episodes of that show to trigger that ability.
Comment: You might just be a case of the [Levitin Effect](https://en.wikipedia.org/wiki/Levitin_effect) at work for you. By the way, how faithfully do you remember songs? I tend to remember them so faithfully that I can remember instrumentation details.

Absolute/relative pitch?


Como chamar corretamente uma função através de outra função em C?

Question: Tenho as seguintes funções :
int testarDivisibilidade(int dividendo, int divisor);
int divisibilidade3(int num);

E as seguintes variáveis :
int dividendo;
int divisor;

Com a função testarDivisibilidade, eu vou verificar se o dividendo é divisível pelo divisor.
Código :
int divisibilidade3(int num)
{
    int res = 0;

    while( num > 0 )
    {
        res += num % 10;
        num /= 10;
    }

    if(res > 9)
        return divisibilidade3(res);
    else
        return ! (res % 3);

int testarDivisibilidade(int dividendo,int divisor) {

    if(divisibilidade3(dividendo) == 1) {
        printf("%d é divisivel por %d ", dividendo,divisor);
        return 1;
    }

    return 0;

}

Eu tenho que verificar se divisibilidade3retorna true para poder então disparar a mensagem dentro do if. Mas esta dando problema, pois para todos casos do dividendo, ele retorna como true.

Resumindo : Como posso verificar corretamente a minha função divisibilidade3 dentro da função testarDivisibilidade ?
Answer: Noto que o código exemplo que você postou não compila:

Primeiro, na linha 12, você está chamando uma função Divisibilidade(), quando você certamente queria chamar divisibilidade3() (note o D maiúsculo e a falta do 3).
Segundo, na mesma linha 12, você está chamando a função e descartando o resultado: o que você efetivamente queria dizer é return divisibilidade3(res); Isso faz com que o compilador emita um erro que "nem todos os caminhos de código retornam".
Finalmente, no caso base da recursão, na linha 14, você está retornando res % 3, que não retorna 1 quando num é divisível por 3. Em vez disso, você quer dizer return res % 3 == 0; ou return ! (res % 3);

Com essas alterações, a chamada de divisibilidade3() dentro de testarDivisibilidade() está correta e deve funcionar.
Note que, na função testarDivisibilidade(), você testa se dividendo é divisível por 3 usando divisibilidade3() e, sendo, emite uma mensagem dizendo que dividendo é divisível por divisor, para qualquer valor de divisor! Estritamente, isto está errado a não ser que você passe 3 como argumento para o parâmetro divisor.
Comment: Nossa, muito obrigado, funcionou corretamente. Na verdade só irá chamar a função divisibilidade3 se o usuário escolher o divisor 3.


Most equivalent factors of a number

Question: Given a number 'n', which is a power-of-2, how can I efficiently find the 2 factors which are most equivalent to eachother? In other words, if I have a linear array and want to map it to 2D, how can I find the 2D dimensions that are the most equal (image dimensions most close to a square)?
Gotta be some kind of bitwise operation to make this fast, rather than looping over factors.
Comment: `n` is representable as `2^k` (since you say it's a power of 2). If `k` is even, then `n == 2^(k/2) * 2^(k/2)` (e.g. `16==4*4`). If `k` is odd, then the closest you can get is `n == 2^((k-1)/2) * 2^((k+1)/2)` (e.g. `8==2*4`)
Comment: You are absolutely right in your suspicions. Now, you just need to think what "2 to the nth" power means, mathematically, and given the `n`, how to find a number that when multiplied by itself results in this "2^n". Free clue: this is easy when `n` is even.
Comment: Fantastic! Please post as answer and I will accept.
Answer: n is representable as 2^k (since you say it's a power of 2). If k is even, then n == 2^(k/2) * 2^(k/2) (e.g. 16==4*4). If k is odd, then the closest you can get is n == 2^((k-1)/2) * 2^((k+1)/2) (e.g. 8==2*4)

Most equivalent factors of a number