How to retrieve Firebase data in a (non Android) Java app?

Question: Is there a way to retrieve data from Firebase to a Java application ?
I have an Android application which stores the data in to a Firebase database and I need to read that data in a Java application. I searched over the Internet, but I have not found a clear answer.
//not the URL from browser, the one above the database
<code>        FirebaseOptions options = new FirebaseOptions.Builder()
            .setDatabaseUrl("https://database-ff395.firebaseio.com/")
            .setServiceAccount(new
      FileInputStream("C:/Users/Denisa/Desktop/database-2aab74679b79.json"))
            .build();
        FirebaseApp.initializeApp(options);

        DatabaseReference ref = FirebaseDatabase
                .getInstance()
                .getReference("restricted_access/secret_document");
</code>
//here I try to reference the database and put a value in it
<code>            final FirebaseDatabase database = FirebaseDatabase.getInstance();
            DatabaseReference ref1 = database.getReferenceFromUrl("https://database-ff395.firebaseio.com/database-ff395");
            ref1.setValue("ooo");
</code>
Answer: Accessing the Firebase Database from a regular (non-Android) JVM is considered a server platform by the Firebase documentation. You can find all about it in the Firebase documentation for its server SDKs.
Comment: One more question: The application should be an web app ?
Comment: I'm not sure what you mean by "web app" in this context. Can you elaborate?
Comment: I made a simple "Java simple app" with public static void main.. and I added the code from the link you gave me. It doesn't work. On the "Prerequisits" it says you have to have "a server running Java 7 or later". I'm not sure what does it means. Should I make a web application running on Tomcat?
Comment: The machine that you run the code on must have Java 7 or greater. Most likely you already have that. What doesn't work? Any errors?
Comment: No errors. I put a simple string to print in the OnDataChange method and I changed manually from firebase..it doesn't print anything. Also I created a reference to the firebase DB and try to set a value to a node but it doesn't work.
Comment: Without seeing your code, all we can do is guess. Please edit your question to include a [MCVE](http://stackoverflow.com/help/mcve).
Comment: That's not how Stack Overflow works. You can [edit](http://stackoverflow.com/posts/37905828/edit) your question to include the **minimal** code to reproduce the problem. If you cannot reduce to a reasonable size and readable code, it is unlikely that I can efficiently help you.
Comment: Thank you, but I have a misunderstanding. In Firebase says I need a Server app, and I don't know exactly what kind of application should I make and also I did not understand how they communicate. Because I made a simpla Java application and It seems to me that the event o changing the data is never triggered.
Comment: The code looks fine at first glance. Is this similar to the code you have in your Android app? Does the Android app work?
Comment: In android I am using this https://www.firebase.com/docs/android/quickstart.html and it works. At this point, I'm trying to read something on the server using this https://firebase.google.com/support/guides/firebase-android#get_a_database_reference_numbered , regardless the android part. I was trying just to connect to a test database, and when I will manage to do so, i will adapt the android part to use the same database as the server.
Comment: I managed to fix it.. It was a dependency error.. But I also wanted to ask you, if there is a way to work with 2 firebase database from the same Android app?
Comment: Good to hear that you found the problem. For accessing multiple databases from a single Android app, see: http://stackoverflow.com/questions/37634767/how-to-connect-to-more-than-one-firebase-database-from-an-android-app/37643374#37643374


Add storm in PATH

Question: Here the steps i should do it

1-  Download a Storm release , unpack it, and put the unpacked bin/
directory on your PATH
2- To be able to start and stop topologies on a remote cluster
, put the cluster information in ~/.storm/storm.yaml

i downloaded storm release and setting up it
i want to do that
"put the unpacked bin/ directory on your PATH"
cause i can't use storm as a command
and the second step what's the cluster info should i do in storm.yaml ?
Answer: Let us say your storm is unpacked at /home/your/download/storm

define that as an env variable by
STORM_HOME="/home/your/download/storm"

export this variable by
export STORM_HOME

do not forget to import the path
export PATH=$PATH:$STORM_HOME/bin

then you can use storm command in it.
Comment: yes just append those command at the end of `.bashrc` file, then `source .bashrc` and those env variable will available
Comment: any output after you executed?
Comment: are you sure `$STORM_HOME/bin` are included in `$PATH` env var? please check it with `echo $PATH`
Answer: Making it more simple with a single export command.
I downloaded apache storm from here and Lets say My download path is /home/username/Downloads/apache-storm-1.0.5
Change your actual path in this command and hit this at terminal.

export PATH=$PATH:/home/username/Downloads/apache-storm-1.0.5/bin

all done.

Add storm in PATH


Why can any song can be played starting from any note?

Question: I'm a complete beginner and trying to understand the basics of music theory these days. I guess I have a good ear and can play most songs by ear on guitar and piano and I'm sure this is a stupid question but I've noticed that any song can be played starting from any note, as long as the tone distances are kept the same.
Let's say the song starts with C,D,Eb (Tone,Tone,Half tone), it also sounds correct when E,F#,G (Tone,Tone,Half tone) is played.
I'm a bit surprised to discover that cause I used to think notes are not interchangeable. Am I missing something? Any suggestions?
Comment: @Cœur - yes it will sound correct. The whole point of Do Re Mi is that it is relative.
Comment: @DoktorMayhem it isn't relative everywhere. Some countries use "[fixed do](https://en.wikipedia.org/wiki/Solf%C3%A8ge#Fixed_do_solf%C3%A8ge)," where _do_ is always a C natural, _re_ is always a D natural, and so on.
Comment: Won't sound correct for this song: https://en.wikipedia.org/wiki/Do-Re-Mi
Comment: So I guess the question is - did 1930s Austria use a fixed *Do* system? And if so, do the notes of Do-Re-Mi correspond to that system?
Comment: @Cœur - The irony is that, in the movie, "Do-Re-Mi" is sung in B flat major.
Answer: This is because most people have a sense of relative pitch, so as you say, as long as the intervals (tone distances) are kept the same, the piece of music is recognisable.
Think about how we recognise things visually for a moment. You'd recognise a computer mouse, or a car, or an apartment block whether it was to your left or right, or above you or below you, or whether the thing was close to you or far away. That's because you don't recognise it as a fixed image, but a 'pattern' that can always be recognised from the relationships that the parts of that thing have with each other.
So because (as you say) C,D,Eb and E,F#,G represent the same pattern of intervals - a tone step, then a half tone step - most people hear it as recognisably the same tune.
Moving a piece up and down in pitch like this is called transposing.
Comment: There's also more direct analogy: people intonate while speaking. You are expected to recognise the intended intonation of the phrase, even if the voice is much higher or lower than yours.
Comment: I think even people with absolute pitch can recognize a tune as being the same even if it's played in a different key. :) Maybe a better explanation is that pitches are recognized relative to a _tonic_, home note, zero-point, origin. The tonic gets set very easily, like calibrating a measuring device.
Comment: BTW the people i know who have perfect pitch also have relative pitch - at least that is my impression - so i don't think of them as mutually exclusive..?
Comment: Visual recognition analogy makes great sense! Thanks so much for the answer.
Comment: @piiperiReinstateMonica if you can set a tonic, isn't that in itself a relative pitch ability?
Answer: Playing a single pitch has no emotional impact. The way we understand pitch information is not dependent on frequency. A C and an F# sound the same in isolation. However, the CHANGE between two pitches ("interval") translates into something we all attach some feeling/emotion to, and each different interval translates to a different feeling. If you play the same piece of music starting from any given note, all of the interval information is completely unchanged and so we recognize it as the "same".
(Intervals can manifest "horizontally" as the difference between two adjacent pitches in a melody line or "vertically" as the difference between pitches that sound simultaneously within a chord.)
It's kind of like how we only feel changes in speed, but not how fast we're going at any given moment...
Comment: I think everyone with absolute pitch (including me) will object to your statement that "A C and an F# sound the same in isolation."
Comment: Yes, my answer disregards people with perfect pitch. But it's true for the vast majority of people that C and F# have no perceivable difference in isolation.


Zeroes of sections of locally free sheaves

Question: Let $X$ be a scheme with a point $x \in X$ and $\mathcal E$ a locally free sheaf of finite rank on $X$ with a global section $s \in \mathcal E(X)$.
If $\varphi \in Hom_{\mathcal O_X}(\mathcal E, \mathcal O_X)$, then $\varphi(X)(s) \in \mathcal O_X(X)$.
Suppose that the class of $\varphi(X)(s)$ in $\mathcal O_{X,x}/\mathcal m_x$ is zero for all $\varphi \in Hom_{\mathcal O_X}(\mathcal E, \mathcal O_X)$.
Does this imply that the class of $s$ in $\mathcal E_x /\mathcal m_x \cdot \mathcal E_x$ is zero?
Comment: With no additional conditions on $\varphi$ I guess the answer is no. Take $\varphi$ to be the zero-morphism and $s$ a non-zero section of $\mathcal{E}$.
Answer: No. The most brutal way to see it is to take an $\mathcal E$ which has a non-zero global section $0\neq s\in \Gamma (X,  {\mathcal E})$ but such that $\Gamma (X, \check {\mathcal E})=0.$
If $X$ is reduced there exists an  $x\in X$ such that  $s(x)\neq 0\in \mathcal E_x /\mathcal m_x \cdot \mathcal E_x$ and this   gives a negative answer  to your question, since obviously $\phi(X)(s)=0$ for all $\phi \in \operatorname {Hom} _{\mathcal O_X}(\mathcal E, \mathcal O_X)=\Gamma (X, \check {\mathcal E})=0$.
Examples of the above set-up abound: the first that comes to mind is $X=\mathbb P_k^n$, $\; \mathcal E=\mathcal O(1)$ and $x\in \mathbb P_k^n$ arbitrary.


Programmatically log in a user

Question: I am trying to authenticate users as below. I don't get any error, but it doesn't log in users.
autoLogin.php is located in the root folder. Visiting http://example.com/drupal8/autoLogin.php shows me the Login required page every time.
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

$uid = 1;
$user = Drupal\user\Entity\User::load(1);
$kernel->prepareLegacyRequest($request);
user_login_finalize($user);
$response->send();
$kernel->terminate($request, $response);

Comment: The code should throw an error about the `user_login_finalize()` function, since the User module hasn't been loaded, yet.
Answer: The code shown in the question would throw an error about user_login_finalize() not being defined. The code isn't loading the User module and the DrupalKernel class doesn't load any module.
I generally use the code shown in authorize.php as guideline on how to bootstrap and programmatically log in a user. In this case, to programmatically log in the user whose ID is 1, I would use the following code.
use Drupal\Core\DrupalKernel;
use Drupal\user\Entity\User;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Route;

$autoloader = (require_once 'autoload.php');

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->boot();

  // A route is required for route matching.
  $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
  $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
  $kernel->preHandle($request);

  if (PHP_SAPI !== 'cli') {
    $request->setSession($kernel->getContainer()->get('session'));
  }
} catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

\Drupal::moduleHandler()->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()->load('system');
\Drupal::moduleHandler()->load('user');
if ($account = User::load(1)) {
  \Drupal::currentUser()->setAccount($account);
  // Add your code.
  $response->setStatusCode(200);
  $response->send();
}

Since it seems you are trying to access a specific page after logging in the user #1, it's probable you need to change the two lines following the A route is required for route matching. comment and use a different route name.
Comment: As side note, I would rather not bootstrap Drupal from an external script. I would create a custom module with its own route which would execute the code I need. Even Drupal core stopped to use an external script (cron.php) to run the cron tasks and instead added a route for running them (system.cron).
Comment: Yes, I am planning to create a custom module but I want to make sure it's working beforehand. It gives `Error: Call to a member function setStatusCode() on null` so I added `$response = $kernel->handle($request);` right after 'Add your code' line. It doesn't log me in though. It still shows the app as unauthenticated.

Programmatically log in a user


How to prove $C_1 \|x\|_\infty \leq \|x\| \leq C_2 \|x\|_\infty$?

Question: I want to prove the following theorem (no idea whether it has a name):
Let $V = \mathbb{R}^n$ or $\mathbb{C}^n$ and $\|\cdot\|$ be a norm on $V$. Then, there exist $C_1, C_2 > 0$ such that for all $x \in V$:
$$C_1 \|x\|_\infty \leq \|x\| \leq C_2 \|x\|_\infty$$
I first let $x \neq 0$ (otherwise it would be trivial). Then, I divided by $\|x\|_\infty$ and normalized the vector $x$ such that $\|x\|_\infty = 1$. That left me with
$$C_1 \leq \|x\| \leq C_2$$
but I don't see how this could help me or how I could possibly limit an unknown norm. How can I proceed? Or is this the wrong way anyway? Thanks for any answers.
Comment: You question is about the equivalence of norm $||\cdot||$ to $||\cdot||_\infty$. In fact all norms on a finite dimensional real (or complex) vector space are equivalent. So search for "equivalence of norms on a finite dimensional real vector space" ... E.g. [this page](http://planetmath.org/encyclopedia/ProofThatAllNormsOnFiniteVectorSpaceAreEquivalent.html).
Comment: It might help to draw a picture, for instance in $\mathbf R^2$. The unit ball in the $||\cdot||$ norm looks like a circle with radius 1, and the unit ball in the $||\cdot||_\infty$ norm looks like a square with sidelength $2$. What you are trying to show is that by rescaling the square, it is both possible to make the square be contained in the circle and the circle contained in the square.
Comment: Strengthened version of this result: http://math.stackexchange.com/questions/1669515/equivalent-norms-without-cauchy-schwarz-inequality
Answer: I try to make a self-contained answer to the question (more info can be found on this page). The short answer is: yes you are on the right track!
What you are missing:

$\|x\|$ is a continuous function with respect to the $\|\cdot\|_\infty$ norm. You can write $x= \sum_m x_m e_m$ with $e_m$ a basis with $\|e_m\|=1$ (similarly, $y= \sum_m y_m e_m$). We are interested in $$\|x-y\| = \left\| \sum_m (x_m - y_m) e_m \right\| \leq \sum_m | (x_m - y_m)|  \leq n \| x - y\|_\infty$$ using the triangle inequality. So for every $\epsilon>0$, we can choose a $\delta =\epsilon/n$ such that with $\| x - y\|_\infty < \delta$ it follows that $\|x-y\| < \epsilon$. Therefore, $\|x\|$ is $\infty$-continuous.

The unit sphere $S= \{x :\|x\|_\infty = 1\}$ is a compact set thereby $\|x\|$ assumes a minimum $C_1$ and a maximum $C_2$ on it.
Comment: @Huy: If you pick a basis for your space, then you've constructed a linear isomorphism between your space and $\mathbb R^n$. These are continuous, so the Heine-Borel theorem holds on your space. Alternatively, the proof of the Heine-Borel theorem should go through mostly unchanged for a finite-dimensional normed vector space.
Comment: I personally find it slightly confusing to use $n$ as an index variable to sum over if $n$ also denotes the dimension of the space.
Comment: @Matt: thank you for the remarks. I changed the answers accordingly.
Comment: This might be somewhat stupid, but is it trivial that the unit sphere is a compact set? I know Heine-Borel's theorem, but as far as I know it is only valid for subsets of $\mathbb{R}^n$.
Comment: @Fabian: Assuming that $\| x \|_\infty := \max_{i \in \{1, \dots , n\} } x_i$ I think you are missing an $n$ in the following line: $$ \| x - y \| = \dots \leq n \| x - y\|_\infty$$
Comment: @Fabian Nice : ) Thank you!
Answer: If you are interested in an elementary proof, try $C_1 = \min_j \| e_j \|$ and $C_2 = \sum_j \| e_j \|$.
Comment: I get why $C_2$ works. But why does $C_1$ work?
Answer: The absolute value of every component is smaller than the absolute value of the max of all components, so the sum of the absolute values of components is smaller than n*max of components. this gives C_2=n
on the other hand, the absolute value of the max of components is smaller than the sum of the absolute values of all components, which is nothing but the first norm. C_1=1.


Gradient descent to solve regressions with large features

Question: We know that the closed-form solution for linear regression is $\beta = (X'X)^{-1}X'Y$.
$X$ is a $N\times M$ matrix, where N is the number of observations and M is the number of features.
However, in the case when we have more features than observations, $M>N$, $X'X$ is not longer invertible since the $M\times M$ matrix of $X'X$ is not full rank. As a result, we can no longer use the closed form solution.
Would it be possible (and reasonable) then to use the gradient descent approach to solve for $\beta$?
It is commonly mentioned that gradient descent is preferred to using the closed-form solution since it doesn't require inverting the $X'X$ matrix which can be time intensive, especially for large $M$.
I was curious if gradient descent can also always guarantee a solution when the closed-form solution can't.
Comment: Keep in mind that there is a [generalized inverse](https://en.wikipedia.org/wiki/Moore–Penrose_inverse), too.
Comment: gradient descent *with weight decay* can guarantee a unique solution because its equivalent to ridge regression
Answer:
It is commonly mentioned that gradient descent is preferred to using the closed-form solution since it doesn't require inverting the X'X matrix which can be time intensive, especially for large M

I am under the impression that inversion of the hat matrix is not how statistical packages fit linear models.  Rather, the QR factorization is employed.

Would it be possible (and reasonable) then to use the gradient descent approach to solve for β?

Possible?  I believe so.  The only condition here is that the minimum is not unique, and so the answer would depend on where you start.
Comment: can you please explain why the minimum would not be unique in this instance?
Comment: @vpy Because $X$ has $N<M$  then the dimension of the kernel of $X$ is greater than 0.  This means I can write $y = X (\beta - \beta^*)$ for $\beta^*$ in the kernel of $X$.  Hence, the solution to the equation $y=X\beta$ is not unique.


preencher combobox com dados de outro combobox

Question: Tenho uma tabela Cidade onde tem os campos nomeCidade, IdEstado, IdPais, alem das tabelas Estado e Pais.
Estou fazendo uma aplicação em c# onde utilizo 3 combobox. Ao selecionar o primeiro combobox (cboCidade) e escolher um registro, quero que seja selecionado na mesma hora, os respectivos estados e paises dos combobox cboEstado e CboPais. Lembrando que os combobox Estado e Pais já estão preenchidos com os respectivos valores das tabelas (Estado e Pais)
Comment: Utilizar o evento `SelectedIndexChanged` no `cboCidade` não resolve seu problema?
Comment: Inclua o seu código à pergunta para podermos indicar a melhor solução dentro do seu cenário.
Comment: a minha duvida está justamente em fazer o codigo. Alem do valor do ValueMenber que o combobox ja retorna, precisaria de outro valor. Teria como isso ??
Answer: Nas propriedades do campo cboCidade, selecione o raio, onde permite a configuração dos eventos. Daí, clique 2 x no item SelectedIndexChanged

Ele irá abrir essa janela de códigos:
private void cboCidade_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

Dentro dele, vc insere a consulta SQL para preencher os combos cboEstado e CboPais com base no valor selecionado de cboCidade
Aqui um exemplo:
private void cboCidade_SelectedIndexChanged(object sender, EventArgs e)
    {

        SqlConnection Conexao = new SqlConnection
        {
            ConnectionString = @"sua string de conexao"
        };
        Conexao.Open();

        //Aqui você trará os Ids de Estado e País, para você preencher os respectivos combos
        string ConsultaSql = string.Concat("SELECT idEstado, idPais FROM Cidade WHERE nomeCidade = '", cboCidade.Text, "';");
        SqlCommand ComandoSQl = new SqlCommand(ConsultaSql, ConexaoSql);
        SqlDataReader LeitorDataReader = ComandoSQl.ExecuteReader();

        int estado = 0;
        int pais = 0;

        while (LeitorDataReader.Read())
        {
            estado = Convert.ToInt32(LeitorDataReader["idEstado"].ToString());
            pais = Convert.ToInt32(LeitorDataReader["idPais"].ToString());
        }
        LeitorDataReader.Close();

        //Aqui você irá preencher o combo estado
        ConsultaSql = string.Concat("SELECT nomeEstado FROM Estado WHERE idEstado = ", estado, ";");
        ComandoSQl = new SqlCommand(ConsultaSql, ConexaoSql);
        LeitorDataReader = ComandoSQl.ExecuteReader();
        cboEstado.Items.Clear();
        cboEstado.Text = string.Empty;

        while (LeitorDataReader.Read())
        {
            cboEstado.Items.Add(LeitorDataReader["nomeEstado"].ToString());
        }
        LeitorDataReader.Close();

        //Aqui você irá preencher o combo pais
        ConsultaSql = string.Concat("SELECT nomePais FROM Pais WHERE idPais = ", pais, ";");
        ComandoSQl = new SqlCommand(ConsultaSql, ConexaoSql);
        LeitorDataReader = ComandoSQl.ExecuteReader();
        cboPais.Items.Clear();
        cboPais.Text = string.Empty;

        while (LeitorDataReader.Read())
        {
            cboEstado.Items.Add(LeitorDataReader["nomePais"].ToString());
        }
        LeitorDataReader.Close();

        ConexaoMySql.Close();

    }

Apenas uma observação:
Adapte os objetos SQL de acordo com o seu banco (SQL Server, MySql, etc)


Can I play the cello without pronation of the bow hand?

Question: I would like to learn to play cello, but I have a mini-disability that prevents me from turning my right hand down (palm-down, or pronation) or up (palm-up, or suspination).
How much is this going to get in the way of handling the bow?
How important is pronation in the mechanics of bowing?
Additional info:

I can approximate rotation of the hand by altering my grasp on the
bow (fingers) and lifting my elbow.
Wikipedia says that

The transmission of weight from the arm to the bow happens through the pronation (inward rotation) of the forearm

but then, can I work around it with the aforementioned 'cheats', or would I lose too much in dexterity or sound quality?

My left hand is fine.
Comment: because you are used to using your hand that way, while you may hold the bow differently to others I will happily assure you can get many hours of enjoyment out of it.
Answer: IANAMPT (music physical therapist), so take this as encouragement rather than direction.
I would not let any physical disability short of losing your arm :-)  stop you from trying to learn the cello.  Find a decent teacher who can either work with you directly or refer you to a music-oriented physiotherapist to figure out a functional bow grip position that won't injure you.  What really matters is the ability to hold the bow in the correct 3 angles (around all three x,y,z axes in space) with proper pressure and so on.  If it takes a strange grip, or even some custom grip-adapter piece of hardware, so be it.
Go for it.
Comment: @Cullub  there's an ancient IntarWebz  abbreviation "IANA..." meaning "I am not a" whatever.
Comment: @CarlWitthoft that's a good acronym to know.  Otherwise when someone tells you they're not a lawyer you might be very very confused at first (and unlikely/hesitant to Google the acronym)
Comment: i agree, go for it. many musicians have been limited in some physical way but have made awesome music. I am not a cello history buff, but Richie Havens comes to mind on guitar, and there are countless others.
Comment: What does IANAMPT stand for?
Comment: I encountered a professional musician recently whose fingers only reach the first joint.  It is amazing to watch him play piano.   You'll be OK.
Comment: Even losing your arm shouldn't stop you if you really want to learn. Prosthetic limbs are pretty amazing these days.
Answer: While I have not played cello, I do (too infrequently) play upright bass.  For upright, there are different ways of holding the bow.  First is French, which is more palm down.  And German which is more palm up.
I have played both ways, and for me I prefer the German style bows.  I feel that it gives me better control and is more comfortable for my hand, wrist and arm.
I don't know if they make a German style cello bow, but the technique may work for you.
I agree with the other posts about finding a good teacher.  Any good teacher will not force you into a painful position.  If you experience pain, then you wont' want to play and that is not what anybody wants.
Comment: Interesting, I had no idea about German bow holding! It does look possible for my hand. A teacher also suggested I try the viol, but then it's suspination that I can't do. I'll definitely give your solution a try!
Comment: [Viol](https://en.wikipedia.org/wiki/Viola_da_Gamba) players (most of which I believe are actually cellists) use in fact a backhanded style similar to German bass bowing. I once tried this on cello and it felt really weird, though it can certainly be used for old music. Using an actual bass bow is also not completely absurd – I myself use a light (French) bass bow a lot these days. You need to take a bit more care not to "squeeze the tones to death", but with a bit practise you do also get a bit of extra oomph in the lower registers.


Why do I get error: Error:  expected in line 9 am I missing a import

Question: Following is my code and I have put comments to explain what am I facing.
Should I be importing something else? I'm using the jGrasp compiler?
import java.awt.*;
import java.applet.*;
import java.lang.*;
/*this is just a test class to learn how to use substring. I was trying to use substring
   to play around with strings in this case my dogs name. I was doing exercises on codingbat.com
  and came across the substring method.
*/
public class Donna extends Applet {

    String DogName = "Donna Peluda";       // declare the String variable DogName
    String FirstDog = "";                  // declare FirstDog String variable blank
    FirstDog = DogName.substring( 0, 2);   // I get "Donna.java:9: error: <identifier> expected"
    // if I comment out line 9 it prints "Donna Peluda" ok
    // Ive tried examples from the web and get the same error and spent 2 evenings on this so

    public void paint(Graphics d) {
        d.drawString(DogName + FirstDog ,25, 25);//print the result to the applet
    }
}

Answer: That is not the right place for assigning.
If you really want to do that at there, try this
public class Donna extends Applet
{
    String dogName = "Donna Peluda";
    String FirstDog = "";
    {
        FirstDog = DogName.substring(0, 2);
    }

    .
    .
    .

Answer: The class body (everything between the first open bracket and the last closing bracket) is only allowed to contain the following artifacts:
class MyClass extends MySuperClass implements YourInterface {
    // field, constructor, and
    // method declarations
}

The line
FirstDog = DogName.substring( 0, 2);

is not allowed in the field declaration section. You can move that line into the constructor. Or just initialize the field directly:
String FirstDog = DogName.substring( 0, 2);

See also http://docs.oracle.com/javase/tutorial/java/javaOO/classdecl.html for a detailed reference.
Answer: Try this:
String DogName = "Donna Peluda";
String FirstDog = getFirst();

public String getFirst()
{
    return DogName.substring( 0, 2);
}

Answer: Because jvm can not ensure the invocation order of this three declaration when init Donna.
String DogName = "Donna Peluda";
String FirstDog = "";
FirstDog = DogName.substring( 0, 2);

But {} can be invoked after class member assignment, so:
String DogName = "Donna Peluda";
String FirstDog = "";
{
    FirstDog = DogName.substring(0, 2);
}

Comment: Pretty sure `pubic` isn't a valid Java access modifier.
Comment: instance method can be invoked by class member's declaration if that method does not refer to that class member. just try:    String str1 = getStr();

    public String getStr(){
        return this.str;
    }


Redirecting form to the index page

Question: I have seat reservation page, when user clicks a seat, she write information and save it,
after saving, she will be directed to update.php. But in update.php there is a button for index page, I just wanted to enter user information to the database.
Instead of clicking "go to index" in update.php, how should I redirect users to index.php after action.php
Link is: http://orhancanceylan.com/sgkm/
Answer: Try this.
//this will redirect the users after action.php...
//Put this after what you want to do.
header('Location: index.php');

More info:
http://php.net/manual/en/function.header.php
*Read the warning.
Answer: Is this what you are looking for?
header('Location: index.php');

Answer: To answer your question specifically, you should add this to your php:
<?php
header( 'Location: http://www.yoursite.com/new_page.html' ) ;
?>

But beware: you should do this at start of the script before any content is written to your page.
Another way to do so is to merge index.php and update.php and check at start of the script if something is posted (this is an update) or not (this is just index). No need to redirection then and your page can be easily moved elsewhere in a more portable way.

Redirecting form to the index page


Android como remover a opção "Fotos" do seletor de opções e deixar somente as opções "Câmera" e "Galeria"

Question: Gostaria de saber como remover a opção "Fotos" do seletor de opções e deixar somente as opções "Câmera" e "Galeria". Pois além de não funcionar, é desnecessária  já que a "Galeria" faz a mesma coisa e melhor. Abaixo segue meu código e o resultado:
Activity EditarContaActivity:
public class EditarContaActivity extends Activity implements OnClickListener {

private static int RESULT_LOAD_IMAGE = 1;
Button btneditar;
File file;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_editarconta);

    imguser = (ImageView)findViewById(R.id.imgdefault_user);

    btneditar = (Button)findViewById(R.id.btneditar1);
    btneditar.setOnClickListener(this);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_editarconta, menu);
    return true;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //Detects request codes
    if(requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK) {
        Bitmap bitmap = null;
        Bundle extras = data.getExtras();
        bitmap = extras.getParcelable("data");

        FileOutputStream fos;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        imguser.setImageBitmap(bitmap);

    }
}

public void onClick(View v) {
    // TODO Auto-generated method stub

        String filename = "profile.jpg";
        file = new File(Environment.getExternalStorageDirectory(), filename);

        Intent testeIntent = CarregarImagem.pegaIntencao(this, file);

        startActivityForResult(testeIntent, RESULT_LOAD_IMAGE);
    }

}

Classe CarregarImagem:
public class CarregarImagem {

public static Intent pegaIntencao(Context contexto, File file) {

    // Intenção da Câmera
    final List<Intent> cameraIntents = new ArrayList<Intent>();
    final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    final PackageManager packageManager = contexto.getPackageManager();
    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
    for (ResolveInfo res : listCam){
        final String packageName = res.activityInfo.packageName;
        final Intent intent = new Intent(captureIntent);
        intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
        intent.setPackage(packageName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        cameraIntents.add(intent);
    }

    // Intenção da Galeria
    final Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    // Seletor de opções
    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Foto de Perfil");

    // Add opção de camera
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));

    return chooserIntent;

}

}
Resultado:
Answer: Você não pode fazer isso. Quem define o que aparece aí é o Android, baseado no tipo de Intent que você passou e em quais aplicações estão escutando esse tipo de ação. Quem deve decidir se essa opção é relevante ou não é o(a) usuário(a), clicando em "Sempre" (quando disponível) ou desinstalando/desativando a aplicação.
Comment: Acabei de verificar aqui que o WhatsApp exibe um monte de aplicativos pra escolher, incluindo o Fotos:

( https://i.imgur.com/pdAHuLh.jpg )

Se o Fotos não funciona para a ação que você quer, é esse o problema que você tem que resolver. Mesmo que você consiga, não é bom limitar as preferências do(a) usuário(a). Eu também já tive esse problema uma vez e fiz funcionar. Você também consegue.
Comment: Mas o watts app não permite aparecer esta opção, acho que é pq ela não funciona, tanto que quando eu clico nela aparece as fotos, porém ao selecionar qualquer foto o app causa um erro.
Comment: você verificou isso aonde? Porque eu estava falando na parte onde você vai mudar a foto de perfil e não na parte de mandar mensagens.
Comment: Essa parte fica em configurações/Perfil.
Comment: Fui em configurações/perfil.
Comment: Sério porque no meu não aparece essa opção, aparece só galeria, câmera e a opção de remover foto, já quando vou executar o app desse projeto aparece.
Comment: Acabei de verificar em outro celular aqui e essa opção aparece, acho que está opção de Fotos do meu celular é que não está funcionando ou o Watts App verifica se a opção vai funcionar primeiro antes de exibir. Realmente não sei como eu faria este tipo de verificação se for o caso.
Comment: @GustavoAlmeidaCavalcante Abra uma outra pergunta especificamente para isso.
Answer: Desta maneira não aparece a camara:
 Intent galleryIntent = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 galleryIntent.setType("image/*");
 final Intent chooserIntent =
                Intent.createChooser(galleryIntent, "Um texto qualquer");
 startActivityForResult(chooserIntent, REQUEST_CODE_LOAD_IMAGE);

Não te esqueças que o REQUEST_CODE_LOAD_IMAGE é uma constante definida por ti que será usada no metodo onActivityResult.
Comment: Mas não é a câmera que eu queria tirar era a opção "Fotos". Mas valew pela atenção.
Comment: Desculpa entendi mal. De qualquer maneira vou deixar ficar a resposta, pode ajudar alguem.

Para a câmara podes tentar Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Answer: Bom, com a ajuda da resposta e os comentários do @Pablo cheguei a conclusão de que a melhor prática é fazer funcionar, porém deve ter alguma forma de verificar se uma das opções que o app vai exibir está funcionando antes de exibir e assim se não estiver ele não exibe essa opção, como o que ocorre com o WattsApp que não exibe essa opção no meu celular e exibe nos outros e no app do código dessa pergunta ele exibe, porém da erro. Dessa forma vou tentar fazer funcionar e tentar fazer ele verificar as opções funcionais antes de exibir. Obrigado pela atenção de todos.


Quando escrevo um comentário aparece o email de todas as pessoas cadastradas. Como faço para aparecer somente meu email que foi logado?

Question: Esse é o código:
<?php

$conexao = mysqli_connect("localhost", "root", "");
mysqli_select_db($conexao, "videoaula");

?>

<?php

$sql = "select comentarios.id, comentarios.comentario, usuarios.email from comentarios, usuarios order by id desc";
$executar = mysqli_query ($conexao, $sql);
while ($exibir = mysqli_fetch_array ($executar)){;

echo "ID:".$exibir ["email"];
echo "
";
echo "Comentário:".$exibir ["comentario"];
echo "

";
}

?>

Quando executo o codigo, aparece todos os email cadastrados, como abaixo:
ID:thaina123
Comentário:olá mundo!!

ID:firstname.lastname@example.com
Comentário:olá mundo!!

ID:email@example.com
Comentário:olá mundo!!

ID:firstname.lastname@example.com
Comentário:olá mundo!!

Answer: Você deve salvar o id do usuário na tabela comentários, e ligá-lo no where conforme abaixo:
select
  comentarios.id,
  comentarios.comentario,
  usuarios.email
from comentarios, usuarios
  where comentarios.idusuario = usuarios.id
order by id desc

Comment: Olá, agradeço sua resposta! Mas como faço para salvar id do usuario na tabela de comentarios?


Removing Claims from ClaimPrincipal in C#

Question: I am kind of scratching my head to resolve this issue where I have to remove all the Claims in one go. When I use the below code, I get this error Collection was modified; enumeration operation may not execute
Since, I am changing/modifying the value from the enumerator that I am currently looping through, therefore, I am getting this error. Any idea how can I resolve this issue. I have used the below code:
private static readonly string[] claimTypes=
    {
        ClaimTypes.Role,
        ClaimTypes.UserSpecific.IdleSessionTimeout,
        ClaimTypes.CustomerSpecific.ApplicationId,
        ClaimTypes.CustomerSpecific.CustomerId,
        ClaimTypes.CustomerSpecific.CustomerName,
        ClaimTypes.CustomerSpecific.CurrencyCode,
        ClaimTypes.CustomerSpecific.Locale,
        ClaimTypes.CustomerSpecific.TimeZone,
        ClaimTypes.CustomerSpecific.ReportingUnitId
    };

public static void RemoveClaimsFor(this ClaimsPrincipal principal, params string[] claimTypes)
    {
        if (principal == null) throw new ArgumentNullException(nameof(principal));

        foreach (var identity in principal.Identities)
        {
            foreach (var claim in identity.FindAll(claim => claimTypes.Any(type => type == claim.Type)))
            {
                identity.TryRemoveClaim(claim);
            }
        }
    }

Since this was giving error so I thought of using the below code. but this also does not work.
public static void RemoveClaimsFor(this ClaimsPrincipal principal, params string[] claimTypes)
    {
        if (principal == null) throw new ArgumentNullException(nameof(principal));
        var claimNamedList = principal.Identities.Select(x=>x.Claims.Select(y=>y.Type).ToList());
        foreach (var identity in principal.Identities)
        {
            var claimNameList = identity.FindAll(claim => claimTypes.Any(type => type == claim.Type));
            foreach (var name in claimNameList)
            {
                var aa = principal.Identities.Select(x => x.Claims.Where(b => b.Type == name.Type));
                identity.TryRemoveClaim(name);
            }
        }

    }

Answer: In order to solve this, you need to create a new collection that you enumerate:
public static void RemoveClaimsFor(this ClaimsPrincipal principal, params string[] claimTypes)
{
    if (principal == null) throw new ArgumentNullException(nameof(principal));

    foreach (var identity in principal.Identities)
    {
        var claimsToRemove = identity
          .FindAll(claim => claimTypes.Any(type => type == claim.Type))
          .ToArray();
        foreach (var claim in claimsToRemove)
        {
            identity.TryRemoveClaim(claim);
        }
    }
}

By using ToArray (or ToListor another To* method), the results of the enumeration are stored in a new collection that you can enumerate over. When removing items, this does not affect the newly created collection so the error will be gone.


add a webform in a product checkout

Question: I would add a webform in the checkout step of a particular product. I need this feature because sometimes the products that i offer needs more information and sometimes the information that i need are different, so the webform that i should show could be change.
I would show the webform during the checkout, i don't want to have a webform that redirect to checkout (commerce webform module i think)
Answer: As per my understanding of your question you should follow below steps:

Create a form using Webform and then in Webform >> Advance settings mark that webform as "Available as block".
Now you can see that webform as a block in Blocks page.
In block configuration you can set the option to display that block on specific page.

Let me know when you implement it.
Comment: you misunderstanding. I want a webform for just some type of product, i don't want alway the same webform for every checkout page
Answer: If you're needing product-related information, Commerce Custom Product would be the way to go. If you're needing order level information, then you can create order-level fields and expose during checkout using Commerce Fieldgroup Panes.
Finally, this post on drupalcommerce.org seems to elude to getting a webform to work within a custom pane.

add a webform in a product checkout


Force bar numbers below the staff and chord names above in LilyPond

Question: In the documentation for the bar number engraver, it's quite clear that the bar numbers were only ever intended to go above the staff.  How do I override that behavior?  It would make a part I'm working on look much cleaner (when they're set to the top, they make a habit of floating way above the main staff when the ossia staff is active in a system but not visible).  This reddit user also found nothing useful except a suggestion of "make sure the bars line up between staves and fake the measure numbers, which only could work in highly specific cases.
Related, can I force chord names to display above the staff?  It looks confusing when they display below the staff.  The sample lead sheet and all the surrounding snippets have the chords above the staff, yet my part keeps placing the chord names below the staff.  I suspect that the ossia staff is causing issues here as well.
Something from the aligning objects documentation seems like it should be useful in both cases, but I'm not sure how to apply it to the actual project I'm working on.
Comment: You can add a Dynamics context below your staves and add the engraver to it that renders the bar numbers. Equally, you can try to shift the chord names using `\consists`. I will give an answer later when I have proper internet
Answer: As for the bar numbers moved below the score, there are two approaches. The first would be to just use \override BarNumber.direction = #DOWN to shift the standard bar numbers down. The second approach adds a centred bar number for each bar below the score. This second approach is best described in this snippet.
For the first approach, you can use the following code:
\version "2.18.2"

\score {
  <<
  \new Staff {
    c'4 d' e' f' g' a' b' c' d' e' f' g' a' b' c' d' \break
    e' f' g' a' b' c' d' e' f' g' a' b' c' d' e' f'
  }
  >>

  \layout {
    \context {
      \Score
      \override BarNumber.direction = #DOWN
    }
  }
}

As for the chord names, you should put your ChordNames context at the correct position and also tell the ossia context to be above or below another context. For example like this (note the named Staff and the reference in the ossia):
\version "2.18.2"

\score {
  <<
  \new ChordNames {
    \chordmode {
      c1 g d a e b f c
    }
  }

  \new Staff = "main" {
    c'4 d' e' f' g' a' b' c' d' e' f' g' a' b' c' d'
    <<
      { e'4 f' g' a' }
      \new Staff \with {
        \remove "Time_signature_engraver"
        \override StaffSymbol.staff-space = #(magstep -3)
        \override StaffSymbol.thickness = #(magstep -3)
        fontSize = #-3
        firstClef = ##f
        alignAboveContext = #"main"
      }
      { e'4 f' g' a' }
    >>
    b'4 c' d' e' f' g' a' b' c' d' e' f'
  }
  >>
}

(Spacing could be nicer, but I hope you get the point.)


Checkbox, PHP & SQL

Question: Quick issue:
I have a checkbox in my code that tells the user if the status of a record is DONE or NOT DONE. When the user does a records search in the database, the records that show up, show up with the current record status (DONE or NOT DONE).
If the checkbox is not check means that the record is NOT DONE, so I'm trying to place a checkbox on one side of the record status so the user can check it as soon as they are done working on the record. After they check the checkbox, the value is sent to the DB telling the DB that the new status of the record is DONE
How can I accomplish this when the following example code: (The results are shown after the user made a search using a form)
<?php
if(!isset($_POST['search']))
{
?>

<?php
}
else
{
    $from = trim($_POST['OLD']);
    $to = trim($_POST['NEW']);
    $status = isset($_POST['Status']) ? "AND status = 'DONE' " :"AND status = 'NOT DONE' ";

    $connection = mysql_pconnect("HOST", "USER", "PASS") or die("Connection failed. ".myslq_error());
    mysql_select_db("DBNAME") or die("Unable to select db. ".mysql_error());
    $query = "SELECT * FROM records WHERE Date >= '$from' AND Date <= '$to' ".$status." ORDER BY date ASC";

    $result = mysql_query($query) or die(mysql_error());

    echo "
";
        echo "
";
            echo "ID	";
            echo "Name	";
            echo "Last Name	";
            echo "Place	";
            echo "Station	";
            echo "Phone	";
            echo "Date of Record	";
            echo "Status	";
        echo "
";
    echo "
";
    while($record = mysql_fetch_object($result))
    {
    echo "
";
        echo "
";
            echo "".$record->ID."	";
            echo "".$record->Name."	";
            echo "".$record->lastName."	";
            echo "".$record->Place."	";
            echo "".$record->Station."	";
            echo "".$record->Phone."	";
            $year_part_of_date = explode('-', $record->date);
            echo "".$record->date."	";
            echo "".$record->Status."	";
        echo "
";
    echo "
";
    }
}
?>

Thanks everyone for showing me the way :D
Answer: You mean, like this?
echo "<input type='checkbox' name='status' ".($record->Status == 'DONE' ? 'checked' : '')."/>	";

Comment: Ok thats pretty good for me. I was thinking the same about those 2 options. I think i'll go with providing a save button/form for now. Later i'll update the code to work with AJAX.

Actually, I already made the form/button to do this, but I got stuck at some point. The thing is that the code I'm using does a search for the records that meet the search specifications, but I'm not sure of how to make the form work for each record status.

Thanks a lot @Fratyr.
Comment: Right! :D Now is showing the checkboxes as DONE! Great! Now the thing I'm trying to figure out is the part where the user check those checkboxes to update the Status on the SQL Database.

Is there anyway to work around and do this?
Comment: In the same form you want to implement update? I'd go for AJAX call on checkbox click, but if that is out of your expertise, then you will have to provide a Save button for the user, that will send the form you draw from a database back to the PHP script, to take new parameters and update database records. That's an easy task when you  know how to do it, but certainly not an easy one to write the whole piece of code here.

Checkbox, PHP & SQL


Exercise 2.27 Atiyah-Macdonald, absolute flatness

Question: A commutative ring $R$ is absolutely flat if every $R$-module is flat. Prove that the following are equivalent:
1) $R$ is absolutely flat
2) Every principal ideal of $R$ is idempotent
3) Every finitely generated ideal of $R$ is a direct summand
I'm stuck on implication $1) \to 2) $
Answer: If $\mathfrak a$ is an ideal in a ring $A$ and $M$ is an $A$-module, then the map
$$
\begin{array}{ccc}
M\otimes_A A/\mathfrak a &\to& M/\mathfrak aM \\
m\otimes (a+\mathfrak a)&\mapsto& ma+\mathfrak a M
\end{array}
$$
is an isomorphism, which we will call the quotienting isomorphism. Proving this map is an isomorphism is exactly Exercise 2.2 in Atiyah-Macdonald.
Now, suppose $R$ is absolutely flat and let $x\in R$. Then
$$
0\to (x)\to R\to R/(x)\to 0\tag{1}
$$
is exact in $_{R}\mathsf{Mod}$. Since $R/(x)$ is flat, applying $(-)\otimes_R R/(x)$ to (1) gives an exact sequence
$$
0\to (x)\otimes_R R/(x)\to R\otimes_R R/(x)\to R/(x)\otimes_R R/(x)\to 0
$$
in $_{R}\mathsf{Mod}$. One then shows that the diagram
$$
\begin{array}{ccccccccc}
0&\to& (x)\otimes_R R/(x)&\to &R\otimes_R R/(x)&\to &R/(x)\otimes_R R/(x)&\to& 0 \\
&&\downarrow && \downarrow && \downarrow \\
0&\to& (x)/(x)^2&\to& R/(x)&=& R/(x)&\to& 0
\end{array}\tag{2}
$$
commutes where the vertical arrows are the quotienting isomorphisms. This implies that the bottom row of (2) is exact so $(x)/(x)^2=0$ as required.
Answer: What happens if you tensor the short exact sequence $$0\to I\to R\to R/I\to 0$$ with $I$?
Comment: Dear Mariano, I can't find an answer to your question which would solve the problem. Could you please add some details?
Comment: @GeorgesElencwajg: For any ideals $I, J$, $\operatorname{Tor}^R_1(R/I,R/J) \cong (I \cap J)/IJ$.
Comment: @zcn: what does what you write have  to do with Mariano's answer, who tensors with $I$ ?
Comment: @GeorgesElencwajg: Ah, I missed that part. In that case, I believe Mariano means: tensor with $R/I$
Answer: I'll put in the picture because I could not write the diagram in latex


Find all solutions to the equation $z^5 = 2 -2i$ and express answers in polar form

Question: So far I have used De Moivres theorem to get $R^5=\sqrt{8}$ and $5\arg(z)=-\frac{1}{4}\pi$.
$z=(\sqrt{8})(\cos(-\frac{1}{4}\pi)+i\mkern1mu\sin(-\frac{1}{4}\pi))^\frac{1}{5}$.
Then by bringing the power down:
$z=(\sqrt{8})^\frac{1}{5}(\cos(-\frac{1}{20}\pi)+i\sin(-1/20\pi))$.
So now I'm confused about solving this.
Answer: I'm not sure how you were taught, but to find the solutions to $z$ you don't actually need to express it in polar form (e.g. $z=r$cis$(\theta)$). You do, however, need to express $2-2i\mkern1mu$ in polar form. So, as you've done, $2-2i\mkern1mu = \sqrt{8}$cis$\frac{7}{4}\pi$.
Then, using De Moivre's formula, we get that $z=\sqrt{8}^\frac{1}{5}$cis$(\frac{7}{20}\pi+\frac{2}{5}\pi k), k\in\mathbb{Z}$
From here, the next five solutions (e.g. for the next $k$ values) will be your solutions.
Answer: You have:
$z^5 = \sqrt 8(\cos -\frac {\pi}{4} + i\sin-\frac {\pi}{4})\\
z = 8^\frac {1}{10}(\cos -\frac {\pi}{4} + i\sin-\frac {\pi}{4})^\frac 15\\
z = 8^\frac {1}{10}(\cos -\frac {\pi}{20} + i\sin-\frac {\pi}{20})$
And this is all good to find one value of $z.$  But there are others.  We can rewrite the first line as:
$z^5 = 8^\frac 12(\cos (-\frac {\pi}{4}+2n\pi) + i\sin(-\frac {\pi}{4}+2n\pi)\\
z = 8^\frac 1{10}(\cos (-\frac {\pi}{20}+\frac {2n\pi}{5}) + i\sin(-\frac {\pi}{20}+\frac {2n\pi}{5})$
and set $n = 1,2,3,4$ for the other roots.
Comment: Ah this makes more sense thank you so much!
Answer: Answer :
$z^5 =2(1-i)$
We put $z=Re^{i\theta} $
$R^5 e^{i5\theta} =2( e^{-\frac {i\pi}{2}} (i+1))=2\sqrt{2} (e^{-\frac{i\pi}{2}}(\frac{\sqrt {2}}{2} +\frac{i\sqrt {2}}{2})) =2\sqrt{2} (e^{-\frac{i\pi}{2}}(e^{i\frac{\pi}{4}})=2\sqrt{2} e^{-i\frac{\pi}4}$
$\Rightarrow $ $R=\sqrt[5]{2\sqrt{2}} $ and $5\theta=\frac{-\pi}{4}+2k\pi$
$\Rightarrow $$ R=\sqrt[5]{2\sqrt{2}}$ and$ \theta=\frac{-\pi}{20}+\frac{2k\pi}{5}$
$\Rightarrow $ $ z= \sqrt[5]{2\sqrt{2}}e^{i(-\frac{\pi}{20}+\frac{2k\pi}{5}) }=\sqrt[5]{\sqrt{8}}e^{i(-\frac{\pi}{20}+\frac{2k\pi}{5}) }$
$k ={0,1,2,3,4} $


Is it possible to show password reset email success in user password page?

Question: I am completely exhausted trying to find out a solution for this simple problem.
I am intending to put a "Forgot Password" in my Drupal site and wants a confirmation when the form emails the password to the user.
For instance, I go to this link http://www.some.com/user/password for the "Forgot Password" link.
when I enter the username or password, it just doesn't show anything and just redirects to the homepage. I intend to change that and want to show the confirmation that an email has been successfully sent.
Any idea how I can do this?
What I tried
I tried creating a page--user--password.tpl.php but it doesn't allow me to make any changes. I am not sure where the values are coming in the form.
Comment: Have you installed some module the override login functionality? The default behavior is set a notification message, "'Further instructions have been sent to your e-mail address." and redirect to /user.
Comment: Thanks Shawn. I installed Login Toboggan. Do you it's happening due to that module?
Comment: Perhaps, I know there's a couple of redirection options for 403's & on login. It's worth disabling and trying password reset to test if that's the issue. Something must be controlling the redirect path.
Answer: By default, drupal_set_message() is set and displayed on form submission when a new password is emailed. It's possible LoginToboggan is interfering with this but I haven't encountered that in my use of it.
Alternatively, if you cannot resolve the issue, you can use hook_form_alter() to create your own submission handler on the password reset form, and use drupal_set_message() to re-show the message (or any custom message you provide) on the form.
<code>function MYMODULE_password_reset_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'my_custom_handler';
}

function my_custom_handler($form, &$form_state) {
  drupal_set_message('An email has been sent with instructions to reset your password.');

}
</code>
Answer: There's definetly a module or something acting with the login behavior.
On a brand new Drupal 7 install, if you use the reset link on /user/passsword, it redirects to /user and show the following system message : Further instructions have been sent to your e-mail address.
You'll need to desactivate modules which could interfere and check for other things like Rules or whatever.
Comment: Welcome to drupal.SE! Sorry to say, but your 'answer' appears to be rather a 'comment' than an actual 'answer' since it provides little to no information that qould be useful to answer the question. Please try to provide some more actual information about possible solutions – be it module names, code snippets, links or the like. Thank you!


FTP'd Text file using Python 3 is empty

Question: I am trying to FTP a file from a windows box running python 3.3 to a linux box running Ubuntu 12.04.
I have been able to FTP the file, but the file on the remote server is always empty even though the local file has about 8k in it. Its a small text file.
I have tried a few suggestions from both Google and the SE network. All the different tests are commented out. Those have failed with various errors and/or similar results as the uncommented one. (0 byte file)
I also read in the txt file to ensure I was FTPing the right file.
Code is below. Any help would be greatly appreciated:
filename = 'Music.txt'

#write data to file
file = open('Music.txt', 'w+')
for music in musicList:
    file.write(music+'\n')

file.close()

localfile = open(filename, 'r')
#print(localfile)
#for line in localfile:
#    print(line)

#ftp file to webserver for consumption
ftp = FTP(host) # connect to host webdev (local)
ftp.login(username, password)
print(ftp.getwelcome())
ftp.cwd('projects/home/musicCat/data')

ftp.retrbinary("RETR Music.txt", localfile.write)
#ftp.storlines("STOR Music.txt", open('Music.txt'))
#ftp.storbinary("STOR Music.txt", localfile.write)
#ftp.storbinary("STOR Music.txt", file(file, "rb"))
#ftp.storbinary('STOR' + localfile.name, open(file.name, 'wb').write)
#ftp.storlines("STOR Music.txt", open(localfile, 'r'))
#ftp.storlines('STOR Music.txt', file)
print(ftp.retrlines('LIST'))
ftp.quit()

Interpreter Output:
220 (vsFTPd 2.3.5)
-rw-r--r--    1 1000     1000            0 Dec 27 21:14 Music.txt
226 Directory send OK.
>>>

BUMP: Anyone have any ideas? I have yet to be able to successfully transfer the file via ftp. I'm debating about using python 2.7 and paramiko.
Answer: I'm sure you're looking for a cross-platform pure python approach, but sometimes it's easiest to just use python to execute an external utility via subprocess.call()
http://docs.python.org/3.3/library/subprocess.html
I had similar issues establishing a SSH tunnel from Windows, and really did not want to switch to 2.7 to use paramiko. I ended up just calling plink.exe from my script.
For ftp on Windows, you can use the built-in utility ftp
Transfers files to and from a computer running an FTP server service
(sometimes called a daemon). Ftp can be used interactively.

FTP [-v] [-d] [-i] [-n] [-g] [-s:filename] [-a] [-A] [-x:sendbuffer] [-r:recvbuffer] [-b:asyncbuffers] [-w:windowsize] [host]

  -v              Suppresses display of remote server responses.
  -n              Suppresses auto-login upon initial connection.
  -i              Turns off interactive prompting during multiple file
                  transfers.
  -d              Enables debugging.
  -g              Disables filename globbing (see GLOB command).
  -s:filename     Specifies a text file containing FTP commands; the
                  commands will automatically run after FTP starts.
  -a              Use any local interface when binding data connection.
  -A              login as anonymous.
  -x:send sockbuf Overrides the default SO_SNDBUF size of 8192.
  -r:recv sockbuf Overrides the default SO_RCVBUF size of 8192.
  -b:async count  Overrides the default async count of 3
  -w:windowsize   Overrides the default transfer buffer size of 65535.
  host            Specifies the host name or IP address of the remote
                  host to connect to.

Notes:
  - mget and mput commands take y/n/q for yes/no/quit.
  - Use Control-C to abort commands.

Comment: I ended up just posting data to and endpoint and the endpoint had access to the server via php and was able to save the data. Moving forward, I plan to user your approach detailed above where you call an os specific program to handle the ftp transfer.
Comment: I'm still trying to do this all in python if possible. But as time passes I may have to go with a different approach, either 2.7 and paramiko or your suggestion plink.

FTP'd Text file using Python 3 is empty


How to tune specific notes on a keyboard to play temperament

Question: I'd like to know if it's possible to modify the tuning of every single note with a given frequency on a keyboard and store it in a specific "scale set". Is that possible? The idea would be to play temperaments in a live execution without too much effort (ideally press a button and you switch temperament).
Comment: Logic Pro has such a feature, comes bundled with loads of historical tuning methods and allows the user to design their own, too.
Comment: Multiply all the temperaments by 12, to find number of combinations, and 'press a button' starts to get very expensive - especially regarding the very limited market for such an instrument. That apart - recommending products isn't part of this site's remit. Vtc.
Comment: @Tim could just be something that stores 10 "scale sets" and press a button to switch in between one of them, I don't nee to have stored all possible combinations...
Comment: @Tim why multiply all the temperaments by 12?  That's not how temperaments were used in the days before equal temperament.
Comment: @phoog - each key would need slightly different tuning for its notes - that's 12 different tunings for one key, or 7 minimum for diatonics. I felt OP wanted to cover loads of different temperaments, so would need loads of different tunings - one for each key at least.
Comment: @Tim that's not how temperaments work.  The point of unequal temperaments is that different keys sound different.  If you base your temperament on the key you're playing in then you lose that.
Comment: @phoog - not quite with you. Tune for, say, just intonation, in key C, and it'll sound fine. Leave all notes tuned thus, but play in key Eb, it won't. So, I think it'll then need re-tuning for ji in key Eb. Then it won't sound quite right for another key. Am I wrong?
Comment: @Tim just intonation isn't a temperament.  You can't reasonably use it to tune a keyboard unless you're willing to accept some serious limitations.  If you tune just intonation in C, then D, Dm, D7, Dm7, and Asus4 (among others) will actually sound horrible, so it will only "sound fine" if you avoid those chords.  The point of a temperament is to make a keyboard actually playable, and historical temperaments were devised to make them playable in all of the commonly used keys (which means that later temperaments enable more keys), though each key sounds a bit different.
Comment: @Tim (correction of an earlier comment): So the idea is that if you want your piece to sound peaceful and calm, you use a key that has low major thirds that are closer to just, which would typically be the keys with fewer signs in the key signature, such as C. If you want it to have more tension, you play in a key with more signs in the signature, such as E or A flat or B, where the thirds will be wider, closer to Pythagorean. In your example, the fact that the E-flat piece sounds different from its transposition to C is a feature, not a bug.
Comment: @Tim to make it a bit more concrete, here's the interval between D and A in just intonation for C, although this is actually A and E. In other words, if you tune your keyboard in G using the usual prescription for just intonation, in which the second degree is 9:8 times the root and the sixth is 5:3 times the root, you get this fifth with a ratio of 40:27 between A and E: https://en.xen.wiki/w/40/27. Tuning JI in C, you get this fourth between A and D: https://en.xen.wiki/w/27/20
Answer: It sounds like you want Scala:

Scala is a freeware software application with versions supporting Windows, OS X, and Linux. It allows users to create and archive musical scales, analyze and transform them with built-in theoretical tools, play them with an on-screen keyboard or from an external MIDI keyboard, and export them to hardware and software synthesizers. (Wikipedia)

Scala is a powerful software tool for experimentation with musical tunings, such as just intonation scales, equal and historical temperaments, microtonal and macrotonal scales, and non-Western scales. It supports scale creation, editing, comparison, analysis, storage, tuning of electronic instruments, and MIDI file generation and tuning conversion. All this is integrated into a single application with a wide variety of mathematical routines and scale creation methods. Scala is ideal for the exploration of tunings and becoming familiar with the concepts involved. In addition, a very large library of scales is freely available for Scala and can be used for analysis or music creation. (Scala Homepage)

You might also find useful information in the following posts on this site:

Software for microtonal MIDI?
Is there any support for microtonality and temperaments in (or beyond) the MIDI specification?
Is there a public domain collection of common musical tunings?
Tuning a keyboard
Software that allows playing in different temperaments
Software for trying out 19-TET (and others)

And a bit indirectly...

This answer to Two tunings included with Scala: "Tau-On-Side Opposite" and "Upside Down Wedding Cake"
Where to find information about tunings?
Comment: And there certainly are keyboard models that switch temperaments "at the touch of a button," though I don't know that the Roland C-30 lets you save custom ones... https://www.roland.com/us/products/c-30/features/


Possible mistake in proof of limit?

Question: Please if someone with enough reputation could show my image it would be great.

In this limit question, at the point where it states:
Take the limit as $n \rightarrow \infty$ I really don't follow the logic at all. Since $a \in (0,1)$ then as $n \rightarrow \infty$, $|f(x)-f(a^nx)| \rightarrow |f(x)-f(0)|$, did they confuse $f(0)$ with $0$? Because otherwise how do you go from $$|f(x)-f(0)| \leq \frac{\epsilon}{1-a} |x|$$ to $$|f(x)| \leq \frac{\epsilon}{1-a} |x|$$
It is also very strange that the first property was not used.
Comment: Actually, that still leaves another issue: their interpretation of the second statement is equivalent to $$\lim_{x\to 0}\frac{f(x)-f(ax)}{x}=0.$$ I suspect that something has gone seriously wrong, here. It seems that each instance of "$x\to\infty$" should actually be "$x\to 0$," unless I'm missing a great deal.
Comment: Perhaps the first property was meant to read $\lim_{x\to 0}f(x)=0$? That would take care of both of your issues, wouldn't it?
Comment: The first statement alone already implies the desired conclusion (limit of product is product of limits), which again indicates something is wrong here.
Comment: The relevant product, here (if the limits are defined right) is $f(x)\cdot\frac1x.$ The limit of each as $x\to\infty$ is $0,$ so the limit of their product is $0,$ too. Thus, as @Shalop points out, the first statement is enough, by itself. As Salamam points out in the answer below, the second statement is enough, by itself. This redundancy, together with the mismatching interpretation of the second statement, makes me all but certain at this point that the limits should all be $x\to 0,$ instead.
Comment: It's also worth noting that they never claimed that the function was continuous, so you can't simply replace $\lim_{n\to\infty}\left|f(x)-f\bigl(a^nx\bigr)\right|$ with $\bigl|f(x)-f(0)\bigr|$ without proof.
Comment: I think that @CameronBuie has written altogether a pretty good answer to your question.
Comment: I can make it an answer, if you like.
Comment: This is only if the limits are defined right. But $\lim_{x\to \infty} x = \infty$
Comment: Yeah mate cheers my bad. Seems you might have a good point that the question could be as $x \rightarrow 0$
Answer: You should have, for $x$ enough great,
$$|f (x)|=|f (x)-f (0)+f (0)|\le $$
$$|f (x)-f (0)|+|f (0)|\le$$
$$ \frac {\epsilon}{1-a}|x|+|f (0)|$$
thus
$$\frac{|f (x)|}{|x|}\le \frac {\epsilon}{1-a}+\frac {|f (0)|}{|x|} $$
and use the fact that
$$\lim_{x\to+\infty}\frac {|f (0)|}{|x|}=0$$
You don't need the first hypothesis.
Comment: This does not appear to answer the question. The OP asks to either explain the given proof, or to verify the issues that the OP has pointed out with the proof. (For what it's worth, I didn't downvote.)
Comment: @CameronBuie He said why they took $f (0)=0$
Comment: Yes, that is *one* of the issues that the OP pointed out.
Comment: @CameronBuie So why this downvote.
Comment: I don't know. I'm merely speculating why someone may have downvoted.
Comment: This seems correct. Thanks.

Possible mistake in proof of limit?


problema ao popular um controle do tipo option

Question: Tenho um codigo VBA mas estou com problemas ao popular um elemento.
Quando tendo colocar dados no controle aparece a seguinte mensagem de erro:
erro em tempo de execução '2146233079 (80131509)':
unknown error: cannot focus element...
<code>Sub x()
    Dim objCollection
    Dim numeroPregao, dataAssinatura, uasg, item, val, m
    Dim c As Integer
    Dim ULogin As Boolean, ieForm
    Dim MyPass As String, MyLogin As String
    Dim driver As New SeleniumWrapper.WebDriver
    Dim windowHandleJanelaInicial As String

    ctr = 2
    For y = 0 To 13680 'vai de zero ao numero de linhas a ser prenchido
    m = 0
    c3 = 1
    c2 = 1

    driver.Start "chrome", "http://comprasnet.gov.br"
    driver.setImplicitWait 5000
    driver.Open "/acesso.asp?url=/Livre/Ata/ConsultaAta00.asp"

    Set objCollection = driver.findElementByCssSelector("frame[name='main2']")
    driver.SwitchToFrame (objCollection)

    driver.FindElementByName("dt_ini").SendKeys "25/11/2015"
    driver.FindElementByName("dt_fim").SendKeys "24/11/2015"
    driver.FindElementByXPath("//option[text()='<Escolha pelo menos um material ou serviço>']").SendKeys "222345" 'o erro ocorre aqui
</code>
Comment: Fazendo um debug, onde está dando o erro?
Comment: na ultima linha 'o erro ocorre aqui
Comment: acredito que o xpath identificado está errado...
Answer: Consegui contornar meu erro! o problema estava ocorrendo porque o controle que eu estava tentando manipular não estava "acessível".
O jeito foi clicar no botão "selecionar" e fazer a interação com os controles do popup seleção de material


Appending ArrayBuffers

Question: What is the preferable way of appending/combining ArrayBuffers?
I'm receiving and parsing network packets with a variety of data structures. Incoming messages are read into ArrayBuffers. If a partial packet arrives I need to store it and wait for the next message before re-attempting to parse it.
Currently I'm doing something like this:
function appendBuffer( buffer1, buffer2 ) {
  var tmp = new Uint8Array( buffer1.byteLength + buffer2.byteLength );
  tmp.set( new Uint8Array( buffer1 ), 0 );
  tmp.set( new Uint8Array( buffer2 ), buffer1.byteLength );
  return tmp.buffer;
}

Obviously you can't get around having to create a new buffer as ArrayBuffers are of a fixed length, but is it necessary to initialize typed arrays? Upon arrival I just want is to be able to treat the buffers as buffers; types and structures are of no concern.
Comment: possible duplicate of [Typed Arrays in Gecko 2: Float32Array concatenation and expansion](http://stackoverflow.com/questions/4554252/typed-arrays-in-gecko-2-float32array-concatenation-and-expansion)
Comment: well you only have `.slice` with `ArrayBuffer`, not much can be done with that. Then you have `.append` with `BlobBuilder` but it's gonna be much more complicated than what you are already doing. Is there a real problem with your current approach?
Comment: @Esailija my real concern is performance, although I haven't reached that point is testing yet. This just seemed like a backhanded way of doing it. Still getting used to JS! Thanks anyway.
Comment: @Esailija, the solution to the above question offers my current approach which is combining typed arrays into a new buffer. Which is fine when you want to deal with typed arrays. I want to avoid them altogether. My question is whether this is possible.
Comment: Each `ArrayBuffer` has a fixed size, so copying data is the only way. You want to use native code to do the copy, not Javascript loops, so `Uint8Array.set` is your best bet - it can detect when its argument is another `Uint8Array` and do a high-speed C-style `memcpy`.

So, your original code example is about as fast & simple as it can be - the `ArrayBuffer` class has no useful methods, since its designers expected typed array's to be the primary interface. For that reason, I prefer to use `Uint8Array` for "raw data", not `ArrayBuffer`.
Answer: Why not using a Blob ? (I realize it might not have been available at that time).
Just create a Blob with your data, like var blob = new Blob([array1,array2,string,...]) and turn it back into an ArrayBuffer (if needed) using a FileReader (see this).
Check this : What's the difference between BlobBuilder and the new Blob constructor?
And this : MDN Blob API
EDIT :
I wanted to compare the efficiency of these two methods (Blobs, and the method used in the question) and created a JSPerf : http://jsperf.com/appending-arraybuffers
Seems like using Blobs is slower (In fact, I guess it's the use of Filereader to read the Blob that takes the most time). So now you know ;)
Maybe it would me more efficient when there are more than 2 ArrayBuffer (like reconstructing a file from its chunks).
Comment: But that's asynchronous…
Comment: @Bergi If you use it in [Workers](https://developer.mozilla.org/en/DOM/Worker), you can use [FileReaderSync](https://developer.mozilla.org/en-US/docs/Web/API/FileReaderSync).
Comment: Indeed, nonetheless I still find it easier to use.
Comment: @JbDrucker do you know how and when is the memory released for the blob? Blob.close()  looks like it's very beta at the moment
Comment: For me today (64-bit, Windows 10, Intel Core i7), revision 4 of your test says that using Blobs is 2x as fast in Firefox 56 and that appendBuffer is 6x as fast in Chrome 61.
Answer: function concat (views: ArrayBufferView[]) {
    let length = 0
    for (const v of views)
        length += v.byteLength

    let buf = new Uint8Array(length)
    let offset = 0
    for (const v of views) {
        const uint8view = new Uint8Array(v.buffer, v.byteOffset, v.byteLength)
        buf.set(uint8view, offset)
        offset += uint8view.byteLength
    }

    return buf
}

Comment: Works for me! For reference, `Uint8Array.set()` is documented [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set).
Answer: It seems you've already concluded that there is no way around creating a new array buffer. However, for performance sake, it could be beneficial to append the contents of the buffer to a standard array object, then create a new array buffer or typed array from that.
var data = [];

function receive_buffer(buffer) {
    var i, len = data.length;

    for(i = 0; i < buffer.length; i++)
        data[len + i] = buffer[i];

    if( buffer_stream_done())
        callback( new Uint8Array(data));
}

Most javascript engines will already have some space set aside for dynamically allocated memory. This method will utilize that space instead of creating numerous new memory allocations, which can be a performance killer inside the operating system kernel. On top of that you'll also shave off a few function calls.
A second, more involved option would be to allocate the memory beforehand.
If you know the maximum size of any data stream then you could create an array buffer of that size, fill it up (partially if necessary) then empty it when done.
Finally, if performance is your primary goal, and you know the maximum packet size (instead of the entire stream) then start out with a handful of array buffers of that size. As you fill up your pre-allocated memory, create new buffers between network calls -- asynchronously if possible.
Comment: I would love to see some bench marking on this one.
Comment: I just may, if I can learn to use JSperf XD. Although, these days, I wouldn't recommend the last option -- it could get too big and crash the tab in the browser, or maybe even cause an overflow in Node (guessing)
Answer: You could always use DataView (http://www.khronos.org/registry/typedarray/specs/latest/#8) rather than a specific typed array, but as has been mentioned in the comments to your question, you can't actually do much with ArrayBuffer on its own.
Comment: There's nothing wrong with treating everything as a Uint8 if the purpose is to simply copy the data, which is the case here. DataView is great if you need the flexibility it's there for, but it's much much less performant for this purpose. See: http://jsperf.com/uint8array-vs-dataview3
Comment: How would that be better than a Uint8Array for this purpose?
Comment: @BHSPitMonkey It's not really - the only reason for mentioning it is that it doesn't assume a particular element type.

Appending ArrayBuffers


Maximum likelihood estimate for mixture with components using both cartesian and polar coordinates

Question: I have a set of points (x,y) that were generated from a mixture of two components: one component uses Cartesian coordinates, and the other polar coordinates.
For example, with probability $\gamma$ I sample points:
$$
X, Y \sim \mathcal{N}(\boldsymbol{\mu}, \Sigma)
$$
and with probability $1 - \gamma$ I sample:
$$
R \sim \mathcal{Gamma}(\alpha, \beta) \\
\Theta \sim \mathcal{U}_{[0, 2\pi)} \\
X = R\cos(\Theta) \\
Y = R\sin(\Theta) \\
$$
Where $R$ and $\Theta$ are independent.
I'd like to estimate the model parameters $\boldsymbol{\mu}, \Sigma, \alpha, \beta, \gamma$, where $\gamma$ is a mixing proportion.
I have previously used EM to fit a mixture of Gaussians, but I'm having trouble getting started due to the polar coordinate part of this problem.
Below is a generated toy data set as a visual aid. The orange cluster was sampled from the bivariate normal distribution.
Comment: Is $R$ and $\Theta$ independent?
Comment: If your assumption is slightly modified to $R^2 \sim \exp(\lambda)$ plus $R$ and $\Theta$ are independent, you can actually show that the distribution the second component is also Gaussian.
Comment: Yes $R$ and $\Theta$ are independent, but I was looking for a general approach for handling the polar coordinate part of the problem. It could be $R \sim \mathcal{U}_{[a,b]}$
Comment: You can always get the component density of $(X, Y)$ from the anti-polar transformation.  But after that, if the mixture is not Gaussians, the EM algorithm (or other optimization methods) will be ugly.  Are you only interested in getting the density or the subsequent numerical steps?  If former, I can post an answer.
Comment: I'm interested in the numerical steps, however the density would be useful to understand. Maybe I can use some black-box optimization methods.
Comment: @Zhanxiong I've updated the problem to be a little close to what I'm interested in, in case you have any ideas of how to reduce the problem to something simpler, as you did above
Comment: Please also add that $R$ and $\Theta$ are independent to the question body.
Answer: By condition, the joint density of $(R, \Theta)$ is
\begin{align}
f(r, \theta) = \frac{\beta^\alpha}{2\pi\Gamma(\alpha)}r^{\alpha - 1}e^{-\beta r}, \quad r > 0, \theta \in [0, 2\pi). \tag{1}
\end{align}
It is easy to verify that the Jacobian determinant of the transformation:
\begin{align}
\begin{cases}
r = \sqrt{x^2 + y^2}, \\[1em]
\theta =  \arctan(y/x).
\end{cases}
\end{align}
is $\frac{1}{\sqrt{x^2 + y^2}}$, which together with $(1)$ imply that the joint density of $(X, Y)$ is
\begin{align}
f_2(x, y) = \frac{\beta^\alpha}{2\pi\Gamma(\alpha)}(x^2 + y^2)^{\frac{\alpha}{2} - 1}e^{-\beta\sqrt{x^2 + y^2}}, \quad (x, y) \in \mathbb{R}^2.
\end{align}
Let $f_1(x, y)$ be the density of $N(\mu, \Sigma)$. The density of the mixture distribution is then given by
\begin{align}
g(x, y) = \gamma f_1(x, y) + (1 - \gamma) f_2(x, y). \tag{2}
\end{align}
Given $(2)$, if you decided to use the EM algorithm to get the MLE of the parameter $\Psi = (\gamma, \mu, \Sigma, \alpha, \beta)$, you can follow the steps outlined in
Section 2.8 in Finite Mixture Models by McLachlan G. and Peel D.


Does sequence converge if its differences become strictly monotonously greater?

Question: Consider the following sequence:
$(x_n) = x_1, x_2, ...$
Now, let's say this particular sequence has this property: $x_{n + 1} - x_n > 0, \forall n \in \mathbb{N}.$  Then we say that this sequence grows. It' certanily possible that this sequence converges (take, for example, sequence $x_1, x_1 + 0.1, x_1 + 0.01, ...$, we see that $n$-th term is obviously $x_1 + 111...1$ which is obviously some real number).
But add another property of this sequence; let' also say that differences $x_2 - x_1, x_3 - x_2, ...$ make another strictly growing sequence, in other words $x_{n + 1} - x_n > x_{m + 1} - x_m$ for every $n$ such that $n > m$ (it's like positive 2nd derivative in a way).
My intuition tells me that then $(x_n)$ cannot converge. If true, how to prove this? Thanks.
Comment: What do you know about Cauchy sequences?
Comment: Exatcly nothing...
Comment: That's fine. Look at things this way: if $(x_n)$ converges (to a finite value) what can you say about $x_n-x_m$ for large $n$ and $m$?
Comment: Or more directly, what would the sequence $(x_{n+1}-x_n)$ converge to?
Comment: $x_n - x_m$ will, at some point, be smaller and smaller (when $n, m, n > m$ are close enough)?
Comment: $x_{n + 1} - x_n$ will eventually go to $0$ I think
Comment: Nice, can you provide me by more rigorous proof?
Answer: The proof is simple. $x_n$ converges if and only if for every $\epsilon > 0$ there exists an index $N > 0$ such that $|x_p-x_q| < \epsilon$ for every $p, q > N$. In particular setting $p = q+1$ yields the necessary condition $|x_{q+1}-x_q| < \epsilon$ for every $q > N$.
(You really don't need Cauchy sequences here. Just notice that if a sequence $x_n$ has to converge, then obviously $x_{n+1}-x_n \to 0$).
You are requiring $x_{n+1}-x_n > x_{m+1}-x_m > 0$ for some $m$ and all $n > m$. Now if you set $\epsilon = x_{m+1}-x_m > 0$, the necessary condition is not satisfied, no matter how you choose $N$ large.


Trials not starting from 1 - Negative binomial

Question: Trying to tabulate the pmf and cdf of a negative binomial distribution. I have a probability of 0.75, and an success of 2, where the number of trials starts at 2 (x = 2, 3, ...).
I am using r (the language) to calculate and I'm aware that the definitions of the negative binomial are different from my x, but is it a case of starting the vector from 2 to make the distributions match or is there something more complicated? Is the code below going to ensure the distributions passed into the dnbinom and pnbinom functions match up with x?
df <- data.frame(X = 2:20,
           pmf = dnbinom(x = 2:20, size, prob),
           cdf = pnbinom(q = 2:20, size, prob, lower.tail = TRUE))

The PMF that is outputted from this is:
x   2.000 3.000 4.000 5.000 6.000    7
pmf 0.105 0.035 0.011 0.003 0.001    0

Comment: Novice or not, you can look at your text for the explanation of the negative binomial distribution:  Are you counting Bernoulli trials _up to and including_ the occurrence of the $r$th Success, or are you counting Failures _before_ the $r$th Success? Or counting something else?
Comment: There are several 'kinds' of negative binomial distribution. Please show the PMF for the one you are using.
Comment: @BruceET - Thanks for the reply. I'm fairly new to stats, the PMF I am using is the one outputted from the code above (added to the question). The only information I have is that X has a negative binomial distribution with r = 2 and p = 3/4. How would I find out the PMF?
Comment: @BruceET My apologies, I misunderstood. Bernoulli trials up to and including second success.
Answer: I solved this by changing the indexing of the vectors passed into the dnbinom and pnbinom functions to start at 0 rather than 2.
df <- data.frame(x = 2:12,
           pmf = dnbinom(x = 0:10, size, prob),
           cdf = pnbinom(q = 0:10, size, prob, lower.tail = TRUE))

This leads to the expected output:
x   2.000 3.000 4.000 5.000 6.000 7.000 8.000    9
pmf 0.562 0.281 0.105 0.035 0.011 0.003 0.001    0
cdf 0.563 0.844 0.949 0.984 0.995 0.999 1.000    1


HTML E CSS - CABEÇALHO

Question: Não consigo por cor tanto na imagem quanto no texto. Tipo uma barra.. do cabeçalho.

.topo {
  background-color: azure;
}

.img {
  float: left;
  width: 25%;
}

.titulo-principal,
p {
  font-size: "Open Sans Condensed", "Arial", sans-serif;
  text-align: center;
}

Hostsite VH

 Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quas consequatur odit assumenda, rerum

Comment: Qual seria o resultado esperado?
Comment: Tente explicar melhor a pergunta. Não consegui compreender o que você quer fazer
Comment: Gostaria de fazer um cabeçalho com uma cor de fundo, e deixar a imagem na parte de baixo um pouquinho fora desse fundo. No jeito que eu fiz aqui, fico só o texto com o fundo da cor que botei ali, e a linha da imagem não.
Comment: Teria como vc Editar sua pergunta e incluir uma imagem do layout que pretende? Pelo que entendi vc quer que um pedaço da imagem fique sobre a cor de fundo e que uma outra parte da imagem fique para fora dessa cor de fundo, é isso?
Comment: Exatamente isso. Botei a imagem agora de como ta ficando. Mas quero que aquela cor azulzinha ali pegue a imagem também e uma parte da imagem fique fora do azul .
Answer: Existem várias formas de fazer isso, a que eu acho que vai ser mais adequado é colocar na imagem position:absolute e ajustar ela na posição usando top e left
Segue o exemplo

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
.topo {
  background-color: azure;
  position: relative;
  padding: 1rem;
}

.img {
  position: absolute;
  max-width: 25%;
  top: 50%;
  left: 30px;
}

.titulo-principal,
p {
  font-size: "Open Sans Condensed", "Arial", sans-serif;
  text-align: center;
  margin: 0 auto;
  max-width: 50%;
}

Hostsite VH

 Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quas consequatur odit assumenda, rerum

Comment: Acho que consegui. Na verdade não estou satisfeita com o logo hahaha, e outras coisinhas. Mas muito obrigada pela ajuda, de verdade!
Comment: Obrigada, hugo!
Comment: Fiz no meu e continua a mesma coisa :/
Comment: @thaty vc colocou position:relative na classe .top ? Se vc copiou exatamente o código que eu coloquei aqui não teria como não ter funcionado ai tb...
Comment: @thaty no inicio é assim mesmo, depois com o tempo vc vai descobrindo como fazer no código exatamente as coisas que estão no layout. É preciso tempo e prática... Se vc acredita que essa resposta resolveu o seu problema considere marca-la como aceita nesse ícone `✔`. Assim ela não fica pendente no site como pergunta não resolvida. Vc pode remover esse voto a qualquer momento caso queira, ou coloca-lo em outra resposta que surja e vc ache mais adequado pro seu caso. E pode perguntar no site sempre que precisar, só lembre de incluir na pergunta todos os detalhes, código e imagem se for o caso ;)

HTML E CSS - CABEÇALHO


Express $y$ from $\ln(x)+3\ln(y) = y$

Question: i am finding a inverse function to $$y=\frac{e^\frac{x^3}{3}}{x^3}$$
First step:
$$x=\frac{e^\frac{y^3}{3}}{y^3}$$
Next: ... $$(xy^3)^3 = e^{{y}^3}$$
and now in this step i have no idea how can i express "y"
$$\ln(x)+3\ln(y) = y$$
Comment: are you sure that an inverse function exists?
Comment: This is a classic example of the XY problem. You really need to find the range, so your attempt is to find the inverse function which is reasonable. However this isn't the best way. If your problem is to find the range, ask to find the range.
Comment: Where did you get $\ln(x)+3\ln(y)$? If you take the log of both sides, you get $3\ln x + 9\ln y = y^3$. In any event, this sort of function generally doesn't have an inverse without the Lambert $W$-function.
Comment: http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem
Comment: i am not sure.. i would like to finde Range of this funciton, is it a good way finding inverse funciton?
Answer: Go back to the original:
$$y = x^{-3}e^{x^3/3}$$
Then: $$\frac{-1}{y}=-x^3e^{-x^3/3}$$
So: $$\frac{-1}{3y} = \frac{-x^3}{3}e^{-x^3/3}$$
This means that:
$$\frac{-x^3}{3} = W\left(\frac{-1}{3y}\right)$$
where $W$ is Lambert's $W$-function, with $W$ an inverse of $ze^z$.
So $$x=\left(-3W\left(\frac{-1}{3y}\right)\right)^{1/3}$$
You are not going to be able to do it without Lambert or some other non-elementary function.
Answer: Consider the function
$$
f(x)=\frac{e^{x^3/3}}{x^3}
$$
This function is defined for $x\ne0$. Also
$$
\lim_{x\to-\infty}f(x)=0,\quad
\lim_{x\to0^-}f(x)=-\infty,\quad
\lim_{x\to0^+}f(x)=\infty,\quad
\lim_{x\to\infty}f(x)=\infty
$$
so the function has no "global" inverse.
Its derivative is
$$
f'(x)=\frac{x^5e^{x^3/3}-3x^2e^{x^3/3}}{x^6}=\frac{x^3-3}{x^4}e^{x^3/3}
$$
which vanishes for $x=\sqrt[3]{3}$ and is negative for $x<\sqrt[3]{3}$ (but $x\ne0$, of course) and positive for $x>\sqrt[3]{3}$.
So the function is decreasing in the intervals $(-\infty,0)$ and $(0,\sqrt[3]{3}]$; it is increasing in the interval $[\sqrt[3]{3},\infty)$.
How can we find the range? We know that the interval $(-\infty,0)$ is contained in the range (consider the $(-\infty,0)$ part of the domain). Since
$$
f(\sqrt[3]{3})=\frac{e}{3}
$$
we know that the range corresponding to the part $(0,\infty)$ of the domain is $[e/3,\infty)$.
Putting things together, the range is
$$
(-\infty,0)\cup[e/3,\infty)
$$
The restriction of $f$ to each of those intervals has an inverse function. Which is, well, the inverse function: there's no "explicit" form for it. But it's not necessary to find an inverse function, in order to determine the range.

Express $y$ from $\ln(x)+3\ln(y) = y$


Add a square to $853$ to form another square

Question: Given that $853$ is a prime number, find the square number $S$ such that $S + 853$ forms another square number.
I have no idea how you would find $S$, and trial and error doesn't help.
Is there a way of finding $S$?
Comment: Hint:   $a^2+n=b^2\implies n=(b-a)(b+a)$.
Comment: Got it. Have the answer now. Thanks
Answer: Since $S$ is a square number, we can write it as $S=s^2$.  Then suppose that $T$ is another square number which can be written as $T=t^2$.  We then have the relation $$T=S+853\implies t^2=s^2+853\implies t^2-s^2=(t-s)(t+s)=853.$$
Since $853$ is a prime number, its only factors are $1$ and $853$, meaning that we have the linear system
\begin{align}
t-s&=1\\
t+s&=853
\end{align}
Can you take it from here?
Answer: Any odd natural number $2n+1$ is the difference between two (consecutive) squares, $(n+1)^2-n^2$. Apply this with $2n+1=853$.
(If the problem had asked for the smallest $S$ of the desired sort, then you'd have to take into account that $853$ is prime, because otherwise there could be smaller solutions. But as long as nobody cares about minimizing $S$, it doesn't matter that $853$ is prime. The same method works for all odd natural numbers.)
Comment: $2n+1=853\ldots$
Comment: @RoddyMacPhee Thanks for the correction; I've edited it into the answer.
Answer: Let $S=s^2$ and $S+853=T=t^2$. Then $T-S=(t+s)(t-s)=853$. But $853$ is a prime, so $t+s=853$ and $t-s=1$, yielding $s=(853-1)/2=426$ and $S=426^2=181476$.
Answer: Just to algebra
Let $S = n^2$ and let $S +853 = m^2$ so
$n^2 + 853 = m^2$.
Now what?
....
Well, $m^2 - n^2 = 853$ and $(m+n)(m-n) = 853$.
Now remember... $853$ is prime and $m,n$ are natural numbers so ....
$m+n$ and $m-n$ are factors of the prime number $853$.
So $m+n = 853$ and $m-n=1$.
Two equations, two unknowns.
Answer: Lets see :

knowing $(2x)^2=4x^2$ and $(2x+1)^2=4x^2+4x+1$ plus $853=4(213)+1$ we can conclude $S$ is of form $2x$ (if we substitute $x+1$ for $x$ and expand yhe difference is of wrong form)
knowing $(3y)^2=9y^2$ and $(3y+1)^2=9y^2+6y+1$ and finally $(3y+2)^2=9y^2+12y+4$ plus $853=3(284)+1$  means $S$ is of form $3y$  ...

Together these limit $S$ to a multiple of 6 . It also has to be greater than 29 as $29^2<853$ and lower than 428 as $428^2-427^2= 428+427=856$