MAUI MVVM Navigation, how to navigate from page back to MainPage

Question: I'm learning how Maui MVVM works.  I want to write code that:

starts in MainPage.xaml, where there's a button that takes you to:
FirstPage.xaml, where there's a button that takes you to:
SecondPage.xaml, where there's a button that takes you back to:
MainPage.xaml, where there's still a button that takes you to:
FirstPage.xaml and so on

The problem is I can't go from SecondPage.xaml back to MainPage.xaml.
Where's the problem?
The line of code I need to navigate from SecondPage back to MainPage, but it gives an error:
        public AppShell()
        {
            InitializeComponent();
this line>> Routing.RegisterRoute(nameof(View.MainPage), typeof(View.MainPage));
            Routing.RegisterRoute(nameof(View.FirstPage), typeof(View.FirstPage));
            Routing.RegisterRoute(nameof(View.SecondPage), typeof(View.SecondPage));
        }

The type or namespace MainPage does not exist in ProjectName.View (Are you missing an assembly reference?)

Alas, I am not missing an assembly reference.
It's worth noting that I moved MainPage.xaml into a View folder, but I still get the message when I move it back to root.
It makes sense that I wouldn't be able to put routing info for the starting page, as there sort-of already is routing code for it in AppShell.xaml:
    <ShellContent
        Title="Main Page"
        ContentTemplate="{DataTemplate local:MainPage}"
        Route="MainPage" />

With all that said, how do I navigate back to MainPage.xaml?
Here's my code for reference
Use the CommunityToolkit.MVVM Nuget package.
Add the dependency injections in MauiProgram.cs:
            builder.Services.AddSingleton<MainPage>();
            builder.Services.AddSingleton<MainPageViewModel>();
            builder.Services.AddSingleton<FirstPage>();
            builder.Services.AddSingleton<FirstPageViewModel>();
            builder.Services.AddSingleton<SecondPage>();
            builder.Services.AddSingleton<SecondPageViewModel>();

Add the routing information in App.Shell.xaml.cs:
        public AppShell()
        {
            InitializeComponent();
            Routing.RegisterRoute(nameof(View.FirstPage), typeof(View.FirstPage));
            Routing.RegisterRoute(nameof(View.SecondPage), typeof(View.SecondPage));
        }

For each page, do the following:
Create a ViewModel class for each Page.
Add Binding Context to the ViewModels from the Page's code behind:
public partial class FirstPage : ContentPage
{
    public FirstPage(FirstPageViewModel firstPageViewModel)
    {
        InitializeComponent();
        BindingContext = firstPageViewModel;
    }
}

In Page.xaml, make sure that the file can both access and talk to its corresponding ViewModel, and add a button (or something) that has a command (note this code is generic for every Page):
<ContentPage ...
             xmlns:viewmodel="clr-namespace:ProjectName.ViewModel"
             x:DataType="viewmodel:PageViewModel">

     <Button ...
             Command="{Binding NavigateToPageCommand}"/>
</ContentPage>

Finally, make sure that there's a corresponding method for the Command in PageViewModel.cs, like so:
    public partial class PageViewModel
    {
        [RelayCommand]
        async Task NavigateToPage()
        {
            await Shell.Current.GoToAsync(nameof(View.Page));
        }
    }

EDIT: in response to gratefully-accepted advice
(1) Name your home page HomePage.  Don't confuse yourself.
OK.
(2) In your MainPage.xaml.cs. The first line is something like namespace ProjectName.View;  Take away the View.
I don't have it like that.  Here's my file MainPage.xaml.cs:
namespace EMS_MOBILE_MAUI
{
    public partial class MainPage : ContentPage
    {
        public MainPage(MainPageViewModel mainPageViewModel)
        {
            InitializeComponent();
            BindingContext = mainPageViewModel;
        }
    }
}

(3) Change the DI for MainPage from AddSingleton to AddTransient.
OK.
Can you tell me if this next statement is correct?  It's my interpretation of the difference between AddSingleton and AddTransient:

AddSingleton means exactly that: a static, one-time page.  On one hand, you can change the state of the Page, navigate away from it, come back, and it'll still be in that state.
On the other hand, AddTransient will cause the Page to get re-"newed" if you navigate to another page and back again.

(3) You shouldn't have both of these lines of code:
MauiProgram.cs:
Routing.RegisterRoute(nameof(View.MainPage), typeof(View.MainPage));

AppShell.xaml.xs:
    <ShellContent
        Title="LoginPage"
        ContentTemplate="{DataTemplate local:MainPage}"
        Route="MainPage" />

I don't have both of these lines.  I only have the second line.
Since the routing for MainPage is already in AppShell.xaml.cs, I don't use the other routing line.  I put that line in at the beginning of my question as demonstration of where I thought the problem might lie.
(4) Read the docs.  Carefully.  For example, I bet you didn't know that you can navigate back with "..".
Yeah, you're right. I'm not thinking about navigation in terms of a stack that you push/pop.  I will do that.
In conclusion, the only actual change I can make to my code is changing the MainPage's DI from AddSingleton to AddTransient, which doesn't change the behavior in that I still can't navigate from any Page that I have back to the MainPage.  I bet if I read those docs instead of skimming I'll find my answer.
Comment: For the `AppShell.xaml`, is there only one  ShellContent  in it as you posted?
Comment: @AlexandarMay-MSFT yes.  AppShell.xaml.xs has has exactly that `ShellContent/>` as you described.  It's the only element in the file.
Comment: Thanks for your response, you can see my updated answer.
Answer: Okay.

The type or namespace MainPage does not exist in ProjectName.View (Are
you missing an assembly reference?)

First, I advise you to name your page HomePage. MainPage is something very specific, I see that you are new, you will only confuse yourself.
Second, in your MainPage.xaml.cs. The first line is something like:
namespece ProjectName.View;

You do not have to move around the file. This line is what changes when you move it around, this is why you get it working sometimes, and sometimes not.
And if you have in this line .View you go with View.MainPage. And if you do not, you go with just MainPage.
Second:
builder.Services.AddSingleton<MainPage>();

This should be changed to transient.
builder.Services.AddTransient<MainPage>();

Shell requirement. (Bad things happen otherwise).
Third:
Do not put routes like that:
Routing.RegisterRoute(nameof(View.MainPage), typeof(View.MainPage));

At the same time with routes in the XAML:
Route="MainPage"

About navigation: Read this here, start to end: https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/shell/navigation
Some clarification.
Let's say MainPage is my home, and I have SecondPage defined as global route, that I want to call from anywhere.
This means MainPage stays in the XAML.
<ShellContent
        Title="Main Page"
        ContentTemplate="{DataTemplate local:MainPage}"
        Route="MainPage" />

And SecondPage stays in the CS:
Routing.RegisterRoute(nameof(View.SecondPage), typeof(View.SecondPage));

When the app starts, it will look for the topmost ShellItem in the XAML (that is your main page), and navigate you there.
The navigation stack looks like this //MainPage.
Then you can call GoToAsync("SecondPage"). You will be navigated to SecondPage. The navigation stack looks like this //MainPage/SecondPage.
To go back you can navigate with ".." (the default behavior of the back button will do this).
Common mistake here is to call "//SecondPage". To be able to leave SecondPage as the only page of the stack, it has to be registered as ShellItem. (You need to add it the way you add your MainPage).
Start with two pages, do not try to write everything at once, because it will be nearly impossible to fix all mistakes at once. Build your project step by step.
Comment: Hi H.A.H.  I'm sorry I didn't get back to you, and I appreciate your offer.  I read the Navigation page thoroughly, and I think I'm ok.
Comment: Hi H.A.H.!  Thank you for the notes.  I edited my question in response.
Comment: @Bob if you do not understand specific part, I can add edits to explain it.
Answer: 1.According to your post details, you want to navigate back from SecondPage.xaml to MainPage.xaml like below:
SecondPage --> FirstPage --> MainPage

You should use Backwards navigation which can be performed by specifying ".." as the argument to the GoToAsync.
So you need define your SecondPageViewModel.cs like below:
public partial class SecondPageViewModel
{
     [RelayCommand]
      async Task NavigateTopage()
      {
          await Shell.Current.GoToAsync("../../");
      }

}

Your project structure should like below, MainPage.xaml, FirstPage.xaml and SecondPage.xaml are included in View folder.

View:

FirstPage.xaml

MainPage.xaml

SecondPage.xaml

You should define the AppShell.cs like below:
using EMS_MOBILE_MAUI.View;

namespace EMS_MOBILE_MAUI;

public partial class AppShell : Shell
{
      public AppShell()
      {
          InitializeComponent();

        Routing.RegisterRoute(nameof(FirstPage), typeof(FirstPage));
        Routing.RegisterRoute(nameof(SecondPage), typeof(SecondPage));
    }
}

As to the error :Compiler Error CS0246 below, there are many causes that can lead to this error. See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0246. And this error is irrelevant with DI: AddSingleton and AddTransient.


problems with the disabled buttons in the new design

Question: In the review queue, when a button is disabled the text is not really clear.
I was able to reproduce this in the "First posts" queue.
IN the image below, the "I'm Done" button is not really visible.
I don't know if this is relevant but I'm using chrome.
Didn't try on other browsers.
Comment: Same issue on Firefox for me.
Comment: Same for me. Also, before system used to tell me if there are any review available for me at top bar, but not any more.
Comment: @AdarshKhatri reviews available still showing for me
Comment: yeah, it is showing for me now too. Not sure that was only me in that time.
Comment: This is what I am talking about: http://www.awesomescreenshot.com/image/1051017/b89054a76d2781f137d3255d1b22f387 Not sure if it is normal behavior.
Answer: Thanks for letting us know. This has been corrected.


Send HTTP GET or POST request using C in WIndows

Question: I want to send HTTP GET or POST request using C in Windows. I m using Dev C++ to compile the code. I don't know what library or what to use to get it working.
My HTTP GET request will be like this: http://example.com/search.php?s=coffee
Comment: possible duplicate of [HTTP client example on win32](http://stackoverflow.com/questions/1107862/http-client-example-on-win32)
Comment: So many duplicates, so easy to find them.
Answer: Windows sock API 2 is compatible (or almost) with Berkeley sockets. Functions like socket(), write(), send() are available. It's no hard to do. But you still can use a library such as curl
Answer: Here's a newbie answer. Windows automatically comes with curl. So in theory you could just use the system() function in C execute a curl command.
Example:
#include <stdio.h>
#include <stdlib.h>

int main(){
    system("curl http://example.com/search.php?s=coffee");
}


Convergence of products of sequences

Question: Let $|a_n| \in [0, 1]$ and $\sum_{n=1}^{\infty} 1 - |a_n| < \infty$ ($a_n$ is complex number in my case, but I think this is not important). I want to prove that
$$ \lim_{N \to \infty} \prod_{n=N}^{\infty} |a_n| = 1. $$
If we denote the limit as $L$, clearly $L \leq 1$. But I can't show the converse.
Answer: If $\sum_{n=1}^{\infty} 1 - |a_n| < \infty$ then $a_n \ne 0$ for sufficiently large $n \ge n_0$, and
$$
 \prod_{n = n_0}^\infty |a_n|
$$
converges to a nonzero value $P$. Then
$$
\prod_{n=N}^\infty a_n = \frac{P}{\prod_{n=n_0}^{N-1} |a_n|}
$$
for $n \ge n_0$, and the right-hand side converges to $P/P = 1$.

Convergence of products of sequences


Maximal almos disjoint family isn't $C^{*}$-embedded.

Question: I'm workin with an exercise of topology but I don't know how to solve it. First, some context:
Let $\mathcal{M}$ be a maximal almost disjoint family such that $|\mathcal{M}|=2^{\aleph_0}$ and consider $\psi=\omega\cup\mathcal{M}$ be the Mrowka space asociated to $\mathcal{M}$ with the open basis
$$B=\{\{n\}\mid n\in\omega \}\cup\{\{M\}\cup S\mid M\in\mathcal{M} \ \text{and $S$ is a cofinite subset of $M$ } \}$$
I need to prove that $\mathcal{M}$ is not $C^{*}$-embedded in $\psi$ (in general, $S\subseteq X$ is $C^{*}$-embedded in $X$ if every bounded continuous function $f:S\to\mathbb{R}$ has a continuous bounded extension $g:X\to\mathbb{R}$). But, how can I prove that? Searching in some topology books, I have encountered my exercise with a hint in Porter's book so called Extensions and Absolutes of Hausdorff Spaces:

In another question I asked, I proved the fact that $\mathcal{M}$ is a zero set, but, again, I can't prove the hint! Anyone can help me?
After a lot of tries, my professor gave me a list of steps to prove the hint, but I suspect that the steps are wrong. The steps are the next:
1.- Take $\mathcal{N}\subseteq\mathcal{M}$ such that $|\mathcal{N}|=\aleph_0$. Then $\mathcal{N} = \{N_0,...,N_n,...\}$ where $N_i \not= N_j$ if $i \not= j$.
2.- By the definition of almost disjoint family, we can take $x_0 \in N_0$, $x_1 \in N_1 \setminus N_0$,..., $x_n \in N_n \setminus \bigcup_{i < n}N_i$, ...
3.- Let $F = \{x_0,...,x_n,...\}$. Prove that $|F|=\aleph_0$ and that there exist $T \in \mathcal{M}$ such that $T = F \cup G$ where $G$ is a finite subset of $\omega$. Prove that $T \in \text{cl}_\psi (F)$ and $T \not= N_i$ for all $i < \omega$.
The step 3 is false. If $F\in\mathcal{M}$ then we are done, but, if not? Then there exist $M\in\mathcal{M}$ such taht $M\cap F$ is infinite. But, then, is impossible that $F\cup  G$ be an element of $\mathcal{M}$, with $G$ a finite subset of $\omega$, since $M\cap F\subseteq M\cap (F\cup G)$. I really appreciate any help you can provide me.
Answer: The almost disjoint family $\mathscr{M}$ is maximal, and $F$ is an infinite subset of $\omega$, so there must be an $M\in\mathscr{M}$ such that $F$ and $M$ are not almost disjoint, i.e., such that $M\cap F$ is infinite. Let $U$ be a basic open nbhd of $M$, say $U=\{M\}\cup(M\setminus A)$, where $A$ is a finite subset of $M$; then $U\cap F=(M\setminus A)\cap F=(M\cap F)\setminus A$ is infinite and therefore non-empty. That is, every basic open nbhd of $M$ meets $F$, so $M\in\operatorname{cl}F$.
And $F$ is almost disjoint from each $N_i\in\mathscr{N}$, so $M\notin\mathscr{N}$, i.e., $M\ne N_i$ for $i\in\omega$.


Why is there no American team in Formula One?

Question: As far as I remember, even since the 90s, mostly European teams were racing in F1.
Is there any specific reason? Or is it just that Americans do not care about F1 because they have IndyCar, drag races and so forth?
I don't believe it is financial reasons, but what about technical reasons? Is it too complex to build a new car from scratch?
Comment: Haas will be entering F1 in 2016:  http://en.espn.co.uk/f1/motorsport/story/161097.html
Answer: I think (but I am not sure) that it is for historic reasons.
America has a long history with Indy Racing League, Champ Car, Nascar, drag races, and so on, so most American people follow these races instead of Formula One.
So it is probably a choice taken after a cost-benefit analysis.
However, in 2010 there was an unlucky US team that tried this adventure: US F1.
Comment: @Ale - there is now!  https://en.wikipedia.org/wiki/Alexander_Rossi_(racing_driver)
Comment: Economic reasons are a factor: a F1 team is really expensive and TV exposition in USA is not so great to justify the investment. But Ford engines have a strong history with many championships.
Comment: I agree with it. America's has so other races that take so many TV spectators, so is is more difficult for America TV to find so many spectators
Comment: Nevertheless for big car manufacturer like say Ford or Dodge, whould be a big advertisement and kind of prestige to partecipate in the F1 championship. F1 events are covered all over the world so even from a mediatic point of view make sense to be part of this show. F1 have even one race in the USA.
Comment: @fjanisze. That is what Honda and BMW thought when they ran an F1 team. But after a few years they decided there were better ways to promote their company. F1 is definitely expensive, the technology is much different to the production line cars, and there is a distinct danger that the impression is not "Ford - fast and sporty", but "Ford - much slower and less reliable than a Merc" see http://news.bbc.co.uk/sport2/hi/motorsport/formula_one/7766092.stm
 and http://www.autoblog.com/2009/07/29/breaking-bmw-announces-withdrawal-from-formula-one-at-end-of-20/
Comment: There are also no US driver than can take people watching races on TV
Comment: @davidjwest Up for you and for your update. Anyway I believe that this fact do not change the way of the reply
Answer: A group of capable Americans with extensive experience working in F1 garages and factories absolutely could have the necessary technical capabilities to develop and build a Formula One Car from scratch like all of the other teams on the grid, but there's a simple reason why we don't see many F1 teams that are exclusively American in identity (although Haas has recently broken the trend, and has a competitive package, although they are closely partnered with Ferrari and buy as many Ferrari manufactured parts as the rules will allow).
  The reason there have been very few American F1 teams is because of the lack of exposure and interest for the series in America.  America has a rich history of competitive motorsport, but it has been almost entirely in formats like NASCAR, IndyCar, and dirt track racing.
Running and maintaining a Formula One team is exorbitantly expensive, and so each team on the grid must rely heavily on lucrative endorsements, sponsorship deals, and partnerships with engine and automotive manufacturers to develop a competitive race car anew each year.  Traditional F1 teams headquartered largely in the UK and Italy can command hugely prosperous deals because the viewership numbers and consumer engagement with the sport is exceptional, and in turn provides investors and business partners with means to have their message reach a burgeoning global customer base.
Simply put, potential American Formula One teams cannot raise enough money through the traditional mechanisms of procuring investment capital and sponsorship deals to be able to develop a competitive race car, which exacerbates the same problem in further years until the team in completely insolvent.
A few caveats before I go.  In my answer I was envisioning an "American Formula One" team as a team that readily and openly identifies itself as an American team and that has the majority of its facilities located in The United States, including its Headquarters and the bulk of its manufacturing facilities.
I mention this caveat because we could imagine a case where Dieter Mateschitz gifts Red Bull Racing to one of his close friend's sons whom he acted as Godfather for, and that after a few weeks of the close friend's son firing long-term employees and replacing them with his good friends from The States you could justifiably consider Red Bull Racing to then be an "American Formula One Team", which I think we can agree that it would most certainly in fact not.


Prove for $n\ge 2$, $2\binom{n}{2}+\binom{n}{1}=n^2$

Question: I found this example, and I was wondering how would you prove these kinds of problems?
I thought of proving using $\left(\binom{n-1}{k+1}\right)+\left(\binom{n-1}{k}\right)=\left(\binom{n}{k}\right)$ for pascal triangle
but then again I thought this would be proved by induction.
just overall confused
Comment: $$\binom n2=\dfrac{n(n-1)}2$$
Comment: Do you mean ${n\choose 2}$ ? (mathjax for this is {n\choose 2} )
Comment: yes, thanks! il change it
Answer: From the definition of binomial coefficients:
$$
\binom{n}{2} = \frac{n(n-1)}2
$$
so
$$
2\binom{n}{2} = n^2-n.
$$
Similarly:
$$
\binom{n}{1} = n
$$
Adding it up, you get what you need.
Comment: Thats so easy now wow
Answer: From a combinatorial point of view, we are counting the set of elements $\{(i,j)\mid 1\leq i,j\leq n\}$ in two ways.
The first way is directly - there are $n^2$ such pairs - $n$ values for $i$ and $n$ values for $j$.
The second way is to first count the number of elements on the diagonal $(i,i)$ wich is $\binom{n}{1}$, and then count the number of elements not on the diagonal. There are two elements off the diagonal for each pair $\{a,b\}\in\{1,2,3,\dots,n\}$ with $a\neq b$, so there are $2\binom{n}{2}$ pairs off the diagonal.
In general, if there are $p_k(m)$ ways to partition a set of $m$ objects into $k$ non-empty sets, then  $$n^m = \sum_{k=1}^{m} p_k(m)k!\binom{n}{k}$$
In the case $m=2$, we have $p_1(2)=p_2(2)=1$.
Answer: Suppose you have $n$ different items in a bag. You draw one item, replace it in the bag, and then draw again. The number of different two-item samples you could make is $n^2$.
We could count these outcomes a different way. There are two kinds of samples: those where you draw the same item twice and those where you draw two different items.

The number of ways to draw the same item twice is $\frac{n}{1}$ (just select any one of the $n$ items to draw twice).
The number of ways to draw two different items where order matters is $2 \binom{n}{2}$. The binomial coefficient disregards order, so multiplying this value by $2$ accounts for the order in which the two items may have been drawn.

Adding the two bulleted items gives the total number of ways to draw two items with replacement, which we've already noted is also equal to $n^2$.


What is the trend() function in R

Question: I am reading the book "Forecasting: Principles and Practice".
And in the third block the following code is given:
library("forecast")
library("fpp3")

fit <- global_economy %>%
  model(trend_model = tslm(GDP ~ trend()))

but when I run it, I get the following error:
 object 'trend' not found

What is this object?
Comment: What is `global_economy`?
Comment: Maybe provide the output of `dput(global_economy)`, or `dput(head(global_economy))` if it is very large
Comment: Perhaps it would have been useful to note this: "All R examples in the book assume you have loaded the fpp3 package first: `library(fpp3)`"
Answer: You didn't run the example in the book. You ran tslm not TSLM.
library("forecast")
library("fpp3")

## You ran this
fit <- global_economy %>%
  model(trend_model = tslm(GDP ~ trend()))
#> Error in eval(term[[1]]): object 'trend' not found

## the example in the book
fit <- global_economy %>%
  model(trend_model = TSLM(GDP ~ trend()))
#> Warning: 7 errors (1 unique) encountered for trend_model
#> [7] 0 (non-NA) cases

Created on 2020-01-22 by the reprex package (v0.3.0)
Comment: btw see `?fable::common_xregs` for details on `trend()` and related functions
Comment: thanks, I think your answer is correct, but I can't check it because I can't install the fpp3 package, because I can't install the feasts package on my version 3.4.4 R. Next I have to do this

What is the trend() function in R


$\|f\|^2 =\sum_j|\langle f, f_j \rangle|^2$ implies $\langle f, g \rangle=\sum_j \langle f, f_j\rangle\langle f_j, g\rangle$.

Question:
Let $\mathcal{H}$ be a complex Hilbert space, let $f, g \in \mathcal{H}$ and let $(f_j)_{j \in J} \subset \mathcal{H}$, which is indexed by an index set $J \subseteq \mathbb{Z}$. Suppose $\langle f, f \rangle = \sum_{j \in J} | \langle f, f_j \rangle|^2$. Then
  $$ \langle f, g \rangle = \sum_{j \in J} \langle f, f_j \rangle \langle f_j, g \rangle. $$

I have seen the above result several times, and it seems to be a standard result.  In general, it is mentioned that the result follows by "polarisation". However, I am not entirely sure how to apply the polarisation identity here.
Any help and/or comment is highly appreciated.
Comment: Isn't it given whether $\;\{f_j\}\;$ is a basis or even an orthonormal basis, or something?
Comment: No. I don't think that is necessarily either.
Comment: @jnv Yes, perhaps that's right.
Answer: Hint: (in the real case) $$\langle f,g\rangle=\frac{1}{4}(\|f+g\|^2-\|f-g\|^2)=\frac{1}{4}(\sum_j\langle f+g,f_j\rangle^2-\sum_j\langle f-g,f_j\rangle^2)$$
now expand the last brackets using linearity of the inner product. Basically
$$\langle x+y,z\rangle^2=(\langle x,z\rangle+\langle y,z\rangle)^2=\langle x,z\rangle^2+2\langle x,z\rangle\langle y,z\rangle+\langle y,z\rangle^2$$
for the complex case, see comment.
Comment: Thanks. However, I am mainly interested in a complex Hilbert space. I think the proof follows similar arguments though.
Comment: Yeah... then use $|\langle x,y\rangle|^2=\langle x,y\rangle\cdot \overline{\langle x,y\rangle}$. The proof is anologous, but you also need the complex polarization identity https://en.wikipedia.org/wiki/Polarization_identity#For_vector_spaces_with_complex_scalars
Answer: First notice that your sum converges absolutely because
$$
           \sum_{j}2|\langle f,f_j\rangle \langle f_j,g\rangle| \le \sum_{j}\{|\langle f,f_j\rangle|^2+|\langle g,f_j\rangle|^2\}
$$
Therefore you can define
$$
      [f,g] = \sum_j \langle f,f_j \rangle \langle f_j,g\rangle
$$
and this form has the properties of an inner product, including positivity:
$$
          [f,f] = \sum_j |\langle f,f_j\rangle|^2 = \|f\|^2=\langle f,f\rangle.
$$
Because of this, the polarization identity gives $[f,g]=\langle f,g\rangle$ for all $f,g$, which gives you identity you wanted:
$$
            \langle f,g\rangle = \sum_{j}\langle f,f_j\rangle\langle f_j,g\rangle,\;\;\; f,g\in\mathcal{H}.
$$


How does changing the "size" of the infinitesimal $dx$ change the interpretation of the resulting integral?

Question: I recently asked a question (During U-substitution, is the $du$ that we use as the infinitesimal in $\int f(u) \ du$ changing size?) and was explained that there is sort of a "freedom" with how one chooses to subdivide the area underneath a given curve so long as the way you define your dx (in the context of Riemann sum) will converge to zero as n→∞ .
This immediately made me realize that you could subdivide a given area under the curve an infinitely many number of ways (even "more so" when you consider that the subdivisions do not even have to be uniform).
As I understand it, these changes in subdivisions do not alter the resulting value of the integral. And perhaps that is where my misunderstanding arrives.
Consider the picture below:

In the first picture, we would have an integral of the following form: $\int_A^B f(x) d(x)$
In the second picture, we would have an integral of the following form: $\int_A^B f(x) 2dx$  (at least I believe that is how the notation would work)
My confusion is the following: using either one of these versions of uniform subdivisions will result in the same value. However, I feel like there must be a different interpretation that captures the fact that the subdivision for the lower graph is actually going to "fill up" the area under the curve more quickly.
Could someone please explain?
Edit 1: It seems like a clarification that I need in my question (based on below comments) is my misunderstanding of why a change in our "dx of choice" necessarily redefines the interval we are discussing. I do not see why I can't change the subdivision without changing the interval.
Edit 2: As I know understand, the picture that I have is incorrect in that the bottom image should have its interval redefined to $2A$ and $2B$. However, I still do not understand why the change in interval demands that a corresponding change in subdivision must occur.
Comment: This is not really a different question. The confusion seems to stem from thinking of the $dx$ part of the notation as an independent mathematical object. In reality, you really have to consider the underlying Riemann sums (or their generalizations, as the answers to the other questions explain) if you want to modify the way the integral is computed. Those modifications are known to be consistent with the original value.—For your specific example: consider the change of variables $x=2w$, and think about how that affects all the parts of the integral, not just the $dx$ part.
Comment: I believe what you're implying is that the interval therefore changes in accordance with the change of variable. However, that is not my question and therefore makes me think that I should change the notation from $2*dx$ to $d(2x)$. These mean fundamentally different things, correct?
Comment: After reading a few more things, I realize that $2dx$ and $d(2x)$ are equivalent. My question still remains, though. Namely, that I do not understand why the "subdivision strategy" needs to reflect the change in interval. If all subdivisions are approaching zero anyway, I feel like all values would be equivalent and therefore there shouldn't be ONE specifically (i.e. g$'(x)$ ) that needs to be used.
Comment: Correctly executed, the integral changes to $\int_{A/2}^{B/2}f(2x)\,2dx$ under this substitution.
Answer: In the Riemann sum, if you widen the intervals , say from $\Delta x$ to $  2 \Delta x$, then the number of intervals is half, to cover the same interval in $x$, therefore the sum in the limit does not change.
If I got properly your comment, you are concerned with the doubt :
" up to which point I can modify the subdivision of the $x$ interval  from a standard linear (equal $\Delta x$) into an arbitrary subdivision
(let's call it non-linear), without altering the limit of the Riemann sum ?".
To that, I am going to answer to you just intuitively ; others more expert in the field might give a more rigorous answer.

And the intuition is that given in the sketch: until the function that determines the partition is bi-jective
the limit of the sum will not change.
That is because, where you are taking smaller $\Delta x'_{\,k} $, you are taking more bars in the histogram,
so that the weighted sums $f(x'_{\,k}) \cdot \Delta x'_{\,k} $  and $f(x_{\,k}) \cdot \Delta x_{\,k} $
are going to coincide in the limit.
Comment: @S.Cramer: ok, now I got your (crucial) point: i will extend my answer.
Comment: This is getting closer to the crux of my misunderstanding. My confusion, however, is that if all of these tiny little subdivisions are approaching zero, shouldn't I be able to use any size of "adjusted" subdivision (i.e. not just the $g'(x)$ adjustment)? The only analogy that I can think of to get around this is that it isn't necessarily about whether or not we "find the area under the curve"...the issue is whether or not the subdivision strategies "fill up" the area under the curve at the same time. (hopefully you understand what i mean)
Comment: So, to use my graphs as an example, if we were to fill up the interval "2A to 2B" with twice the "subdivision size" (i.e. $2dx$ )as we were to fill up the "A to B" interval with the unaltered subdivision size (i.e. $dx$) , if we started at the same time, they would both fill up at the exact same instance.
Comment: It would help if you correctly defined the subdivisions. You go from $x_i=A+i\,dx$ to $x_i=A+2i\,dx$, these are different points for the same index, and a different amount of points in the interval $[A,B]$.
Comment: You are aware that the integrals of the same integrand $f$ over $[A/2,B/2]$, $[A,B]$ and $[2A,2B]$ are all different?
Comment: If I change the bottom graph's interval to 2A and 2B (rather than A and B), then this would be correct, yes?
Comment: For the same "subdivision", yes. But for different subdivisions, (i.e. different infinitesimals) they could be the same, right?
Comment: It seems like the "filling up" analogy I am making use of is effectively ensuring that the indices from f(u)du match up with the corresponding indices for f(g(x)g'(x)dx throughout the desired interval


Consider the complex-valued function $\frac{1}{(z^2+1)(z^2+z+1)(z^2-z+1)}$

Question: I have found all the singularities of this function.  They are
$\frac{\sqrt 3}{2} + \frac{1}{2}i$,  $i$, $-\frac{\sqrt 3}{2} + \frac{1}{2}i$, $-\frac{\sqrt 3}{2} - \frac{1}{2}i$, $-i$, $\frac{\sqrt 3}{2} - \frac{1}{2}i$
and $\frac{1}{2} + \frac{\sqrt 3}{2}i$, $\frac{1}{2} - \frac{\sqrt 3}{2}i$, $-\frac{1}{2} + \frac{\sqrt 3}{2}i$, and $-\frac{1}{2} - \frac{\sqrt 3}{2}i$
However, I am not sure which of all of these is/are a removable singularities.
I am more familiar with poles, but less familiar with the essential and removable discontinuities.
Thank you,
Bayerischer
Answer: all of them are removable because they have a finite order. singularities such as $f(z)=e^{\frac{1}{z}}$ at $z=0$ are not removable.


Is Cauchy-continuity a property of a function or its domain?

Question: Is Cauchy-continuity a property of a function or its domain?
To illustrate my question, let $f: A \subseteq \mathbb R \to \mathbb R$ be continuous.  Then for any sequence $(x_n) \in A$, if $(x_n) \to x \in A$, then $(f(x_n)) \to f(x)$.
Suppose there is a sequence $(x_n) \to x \notin A$.  Then it is not necessarily true that $(f(x_n)) \to f(x)$.  An example is $f(x) = 1/x$ on $(0,1)$.
If $A$ is closed, then by definition, if $(x_n) \in A$ converges, it converges to a point in $A$.  Thus, if $A$ is closed, any continuous function on $A$ is Cauchy-continuous.  Conversely, if $A$ is not closed, there exists a sequence $(x_n) \to x \notin A$, for which $f(x)$ is undefined, and therefore $f$ is not Cauchy-continuous.
If the above is correct, than Cauchy-continuous isn't a property of $f$ but rather $A$, and is synonymous with the proposition "$A$ is closed."  Why then do we discuss Cauchy-continuity as a distinct property of functions?

Update
In light of the comments: My definition of Cauchy-continuous is:

A function is Cauchy-continuous if it sends Cauchy sequences to Cauchy sequences.  That is, if $(x_n) \in A$ converges, then $(f(x_n))$ converges.

$x \mapsto 1/x$ is not Cauchy-continuous, since $(1/n) \to 0$ yet $(f(1/n))$ does not converge.  As Alex Kruckman and Anne Bauval comment, $x \mapsto x$ sends these sequences to 0, and is thus Cauchy-convergent, even if we restrict $f$'s domain to $(0,1)$.
Would it be correct to state the following:

If a function is continuous on a closed domain, it is Cauchy-continuous in that domain
If a function is continuous on a non-closed domain, it may still be Cauchy-continuous on that domain, as long as $(x_n) \in A \to x \implies (f(x_n))$ converges.  This condition is met even if $f(x)$ is undefined: $f$ can still be continuous on its domain, and $x$ outside of its domain.  And $f$ can be Cauchy-continuous on its entire domain because, for $x$ outside the domain, we only need that $(x_n) \to x \implies (f(x_n))$ converges, not that $(f(x_n)) \to f(x)$ (which, as Anne Bauval comments, is a nonsensical statement anyway.)
Comment: "If $A$ is not closed, ... $f$ is not Cauchy-continuous." I think this is false. For example, the identity function on $(0,1)$ is certainly Cauchy-continuous. But the  issue may be that we disagree on definitions. What is your definition of Cauchy-continuous?
Comment: The existence of a sequence $(x_n) \to x \notin A$ (for which $f(x)$ is ipso facto undefined) does *not* prevent $f$ from being Cauchy-continuous (e.g. $f=$ a constant function on $A=(0,1),$ and $x_n=\frac1n$).
Comment: If there is a sequence $(x_n) \to x \notin A$, not only is it "not necessarily true that $(f(x_n)) \to f(x)$" but it makes no sense, since $f(x)$ is undefined.
Comment: @AlexKruckman AnneBauval Appreciated! I updated with my definition and a clarification.  Please let me know if it's correct.
Answer: You seem to be conflating "Cauchy sequence" with "convergent sequence" throughout your question. These conditions are equivalent for sequences in $\mathbb{R}$ (or any complete metric space), but not in a general metric space. And since arbitrary subsets of $\mathbb{R}$ need not be complete, this can lead to confusion.
As an instance of this, you write

A function is Cauchy-continuous if it sends Cauchy sequences to Cauchy sequences.  That is, if $(x_n) \in A$ converges, then $(f(x_n))$ converges.

The definition of Cauchy-continuous is: $f$ is Cauchy-continuous if and only if for every Cauchy sequence $(x_n)$ in the domain of $f$, the sequence $(f(x_n))$ is also Cauchy. In your "that is..." clause, you replaced "Cauchy" with "converges". This is equivalent if by  "converges" you mean "converges in $\mathbb{R}$", but not in general.
You are correct that if a function on a closed set $C\subseteq \mathbb{R}$ is continuous, then it is Cauchy-continuous. But I think it would be better to write that if a function on a complete domain is continuous, then it is Cauchy-continuous (and it happens that a subset of $\mathbb{R}$ - or any complete metric space - is complete if and only if it is closed). The point is that if the domain is complete, then every Cauchy sequence in the domain converges in the domain.
You are correct (in the update) that if the domain of a function is not closed, the function may still be Cauchy-continuous. A trivial example is the identity function restricted to any domain.
It's a total red herring to think about a point outside the domain of the function that your sequence converges to. You only need to check that $f$ sends every Cauchy sequences to a Cauchy sequence.
Last comment: Even if it was true that a continuous function with domain  $A$ is Cauchy-continuous if and only if $A$  is  closed, Cauchy-continuity would still be a property of the function, not the domain, just  because continuity itself is a property of the function, not the domain. There are plenty of non-continuous  (and hence non-Cauchy-continuous) functions defined on closed domains.
Comment: @SRobertJames Yes, that's correct. My point is that the point $0$ is not actually relevant to the discussion. $(\frac{1}{n})_{n\in \mathbb{N}_+}$ is a Cauchy sequence, and $(\frac{1}{\sin(\frac{1}{n})})_{n\in \mathbb{N}_+}$ is not a Cauchy sequence, so $f$ is not Cauchy-continuous. We can see this without knowing that the sequence $(\frac{1}{n})_{n\in \mathbb{N}_+}$ happens to converge to $0$ (outside the domain of $f$).
Comment: This clarifies a lot, thank you.  One question: "It's a total red herring to think about a point outside the domain of the function that your sequence converges to".  Consider $f: (0,1) \to \mathbb R, f(x) = 1/\sin x$.  Then $x_n  = 1/n$ is a Cauchy sequence (converging to 0, outside of $f$'s domain), but $f$ does not send $x_n$ to a Cauchy sequence.  Isn't it appropriate and necessary to consider the behavior of $f$ on such sequences which converge to _outside_ of $f$'s domain? And, in fact, aren't these the _only_ sequences which prevent $f$ from being Cauchy-continuous?


Proving a matrix is singular

Question:
If $A \in \mathbb R^{n \times n}$ is singular and has non-zero row sums that are the same for every row, prove that:

$A + \lambda \, 1_n 1_n^\top$ is singular for any nonzero scalar $\lambda$.

$A + 1_n f^\top$ is also singular for any $f \in \mathbb R^n$.

Note that $1_n 1_n^\top$ is an $n \times n$ matrix of ones. Thank you so much in advance for all your help!
Comment: What is $\lambda11^T$?
Comment: Since you're fairly new to MSE I thought I'd point out that you'll find that simple "Here's the statement of my exercise, solve it for me" posts may be poorly received. What is better is for you to edit the question and add context: What you understand about the problem, what you've tried so far, etc.
Comment: @JoséCarlosSantos 1 is the vector of order n x 1 and 1^T is its transpose. Sorry for not being clear on that and thanks for your question, I will edit my post.
Comment: @RodrigodeAzevedo Thank you so much for your help on editing my question!!! I am new to MSE and I still learn to format my questions and the mathematical notations.
Comment: @lhf Thanks for your attention! \lambda is any non-zero scalar.
Comment: @lhf Yes, that's right. \11^T is the constant matrix of order n x n with all elements are ones.
Comment: Can you translate "has non-zero row sums that are the same for every row" to matrix notation?
Comment: Sorry to point out a detail, but the first affirmation is true for $\lambda=0$ too, because $A$ is singular
Comment: Thanks @JohnDoe for your advice! I will take note for my later questions!
Comment: Thanks @user438666 for your point!
Comment: @RodrigodeAzevedo I think it can be rewritten as $\sum_{j=1}^n a_{ij} = \sum_{j=1}^n a_{kj} \neq0 $ for  $ i, k = 1, 2, ..., n$.
Answer: Hint for 1: Suppose that $Av = 0$. Then there necessarily exists a value of $t \in \Bbb R$ such that
$$
(A + \lambda 1_n1_n^T)(v + t\,1_n) = 0
$$
Alternatively, the hint for 2 below also applies.
Hint for 2: Note that the column space of $1_n f^T$ is a subspace of the column space of $A$.
Comment: for your hints! I haven't learned column space yet but I can use your first hint to solve the second one.
Comment: @Sophil here's another approach, then.  Since $A$ is singular, there is a vector $y$ such that $y^TA = 0$ (or if you prefer, $A^Ty = 0$).  Try to show that $y^T 1_n = 0$, which means that $y^T(A + 1_n f^T) = 0$.
Comment: @Sophil actually, I just noticed that this is exactly Macrophage's approach
Comment: Thanks so much for your help! I've just noticed that my first response to you was somehow missing the first word but I cannot edit it, it was "Thanks for your hints!" :) Anw, thanks a lot! :)
Answer: I'll try to solve the first problem.
Since $A$ is singular, there exist $u\in \mathbb R^n$ s.t. $uA^T=0$. Thus, $$u^TA1_n=0=u^T\cdot (s1_n)=s(u^T\cdot 1_n)=0$$($s$ is the sum of elements in each row)
Hence, $$u^T(A+\lambda1_n1_n^T)=u^TA+\lambda u^T1_n1_n^T=0+\lambda(u^T\cdot1_n)1_n^T=0+0=0$$
So the resulting matrix is singular $\forall \lambda\in \mathbb R$
For the second problem, I think you will just need to replace $1_n^T$ with $f^T$ and use the same reasoning.
Comment: You are welcome! :)

Proving a matrix is singular


container cannnot connect to service from another container

Question: I have the following containers running:
$ docker ps
CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                                              NAMES
b02d801f9aa3        development_mongo      "docker-entrypoint.s…"   7 hours ago         Up About an hour    0.0.0.0:50001->27017/tcp                           compose_mongo
2903bb830ea7        development_postgres   "docker-entrypoint.s…"   7 hours ago         Up About an hour    0.0.0.0:50000->5432/tcp                            compose_postgres
6ce3fe015a8f        development_elastic    "/usr/local/bin/dock…"   7 hours ago         Up About an hour    0.0.0.0:50002->9200/tcp, 0.0.0.0:50003->9300/tcp   compose_elastic

When I create/run a Docker container that has python manage.py makemigrations as entrypoint, the Django app can't connect to the Postgres container:
 $ docker run --name test1 repo/myapp:stage_1605191501

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/django/db/backends/base/base.py", line 217, in ensure_connection
self.connect()
  File "/usr/local/lib/python3.6/dist-packages/django/db/backends/base/base.py", line 195, in connect
self.connection = self.get_new_connection(conn_params)
  File "/usr/local/lib/python3.6/dist-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection
connection = Database.connect(**conn_params)
  File "/usr/local/lib/python3.6/dist-packages/psycopg2/__init__.py", line 126, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection refused
    Is the server running on host "0.0.0.0" and accepting
    TCP/IP connections on port 50000?

Why it cannot connect, since that Postgres port is already exposed to the host? What am I missing?
Comment: Please show your docker-compose.yml file.
Comment: I already got the problem, Michael: different networks. Some containers using a custom network and other container connected only to default bridge. I posted the answer below. Thanks :)!
Answer: Basically, all compose_* containers, are attached to a different Docker Network, as well as test1, is associated to another network.
$ docker network inspect development_default | grep 'Name\|IPv4'
    "Name": "development_default",
            "Name": "compose_postgres",
            "IPv4Address": "172.20.0.2/16",
            "Name": "compose_elastic",
            "IPv4Address": "172.20.0.4/16",
            "Name": "compose_mongo",
            "IPv4Address": "172.20.0.3/16",

These containers were created through Docker Compose, without specifying a custom network. If no custom network is defined on your Docker Compose file, docker will create a custom network which uses the name of the directory from were you have your build environment. That's why the development, name of the directory which was holding the files for generating these containers, was used when creating a development_default network for them.

When executed the command $ docker run --name test1 repo/myapp:stage_1605191501, no --network was specified, so test1 will be associated to the default bridge network.
compose_postgres has 5432 port exposed to the host network and it is associated to development_default network (172.20.0.0/16).

Answer (steps):

provide static IP for compose_postgres
define this IP for the Django app definitions, inside the image of test1, in order to provide  connection from the app to compose_postgres database
define development_default as the --network for test1 when running docker run

For further reference:

Docker Compose (define IP for container/service)
Docker Container Network (concept)
Docker Network (connect container to network)
Docket Network (command reference)
Comment: You don't need the `compose_` part, that's the project name in compose which can change. Set it to `postgres`, `elastic`, and `mongo` for the hostnames instead. You'll see network aliases configured for these when deploying your project in compose.


Comparing timestamps in Android/Firebase from 2 different users

Question: I am new to Java and Android and I am making a train app for my college project. The situation is that only 1 seat is available in the train and number of people who want to book that seat is 2(could be more as well). I want my app to book the seat for that person who selected that seat first in their android app and display "seat cannot be booked" to the other person.How do I use timestamp in this case to compare input time from two different devices or users? Also, if both the users somehow selected that seat at the same time, I want the app to book the seat for that person who appears first in the database that I have created in the Firebase (I have made a database for trains and users). How do I do this?
Comment: Either each Android app will have to send across timezone information, or each app will have to send a timestamp in a common timezone, e.g. UTC.
Comment: if you are use long data type for time, then its easy to compare both time. just get values in long change it in your required format. compare both times even a fraction of millisecond difference will be noted
Comment: Relying on the device time would not be my first option here since users can easily cheat with it. Record the time when the request hits the server and use that time for comparison.
Comment: I suggest that you don't need to compare timestamps. You need [transactions](https://firebase.google.com/docs/firestore/manage-data/transactions). In a transaction check to see if the seat is already booked. If it isn't, book it to the person wanting to book it. The transaction will make sure that only one can book it.
Answer: The simplest solution I can think of, is to assign to each seat object in your train, an available property of type boolean with the default value of true. Once an user is booking that seat, turn the value of this property to false and assign the seat to that user. Even if the second user is trying to book that seat after a few milliseconds, that seat won't be available anymore. So there is no need to compare two timestamps in this case.
Comment: This timestamp thing is the last feature/part of my project and I have not yet reached that part.I will revert back once I try your suggestion.Thank you for helping me.
Comment: Thanks for the solution... To the person who is reading this, we used his available suggestion, but instead of assigning that property to the seats, we used an available child in database of trains. It actually helped us in our case... To Alex Mano, thanks for the tip man. My project was the best one :)


Java Hangman - How to assign letter to JButton when clicked?

Question: I have made a basic hangman game on Netbeans, and the way it works is a user clicks one of the 26 buttons (one for each letter of the alphabet) and that letter is tested in the word. The main problem I'm having is getting the letter to be tested.
    //array holding all buttons
    JButton[] alphabet = {AButton, BButton, CButton, DButton, EButton, FButton, GButton, HButton, IButton, JButton, KButton, LButton, MButton, NButton, OButton, PButton, QButton, RButton, SButton, TButton, UButton, VButton, WButton, XButton, YButton, ZButton};

    //getting the current letter(need something in place of the 0)
    String currentLetter = (alphabet[0].getLabel());

    //replace underscores with letters as they are guessed
                for (int i = 0; i < 1; i++) {
                    secretWord = secretWord + currentLetter.charAt(0);
                    foundWord = words[randValue].replaceAll("[^" + secretWord + "]", "_ ");
    }

I read somewhere that using a button array is what I had to do, so I put it in but it didn't work. Also, I read that an ActionListener was needed for the program to read what letter it is. Previous tries I have used were:
currentLetter = AButton.getText();

currentLetter = AButton.getLabel();

but sadly to no avail. So keep in mind that I am using Netbeans and I'm new-ish to Java, so no big elaborate hard stuff, keep it simple. Thanks:)
EDIT:
        private void AButtonActionPerformed(java.awt.event.ActionEvent evt) {
        DoButton.doClick();
}

        private void DoButtonActionPerformed(java.awt.event.ActionEvent evt) {
            JButton button = (JButton) evt.getSource();
            String currentLetter = button.getText();

        //replace underscores with letters as they are guessed
                        for (int i = 0; i < 1; i++) {
                            secretWord = secretWord + currentLetter.charAt(0);
                            foundWord = words[0].replaceAll("[^" + secretWord + "]", "_ ");
               }
    }

Full Code:
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.FontUIResource;

    public class MainFrame extends javax.swing.JFrame {

        public MainFrame() {
            initComponents();
        }

        static String secretWord = "";
        StringBuilder mainWord = new StringBuilder();
        String[] words =         {"technology", "computer", "camera", "graphic", "digital", "media", "technician",
            "photography", "troubleshoot", "pixels", "application", "download"};
        Random r = new Random();
        int randValue = r.nextInt(11)+1;
        String guessWord = words[0];//words[randValue];
        int errors = 0;
        public static int wins = 0, losses = 0;
        String foundWord = null;
        String currentLetter;
        private void RestartButtonActionPerformed(java.awt.event.ActionEvent evt)         {
            //restart game
                DirectionsFrame DFrame = new DirectionsFrame();
                DFrame.setVisible(true);
                setVisible(false);
                MainFrame MFrame = new MainFrame();
                MFrame.dispose();
                secretWord = "";
                foundWord = null;
                DirectionsFrame.WinsLabel.setText(null);
                DirectionsFrame.LossesLabel.setText(null);
        }

        private void GetButtonActionPerformed(java.awt.event.ActionEvent evt)         {
            for (int i = 0; i < guessWord.length(); i++) {
                mainWord.append("_ ");
            }
            String SetMain = mainWord.toString();
            mainWord.append(secretWord);
            WordLabel.setText(SetMain);
            GetButton.setEnabled(false);
            AButton.setEnabled(true);BButton.setEnabled(true);CButton.setEnabled        (true);DButton.setEnabled(true);EButton.setEnabled(true);
            FButton.setEnabled(true);GButton.setEnabled(true);HButton.setEnabled        (true);IButton.setEnabled(true);JButton.setEnabled(true);
    KButton.setEnabled(true);LButton.setEnabled(true);MButton.setEnabled(true);NButton.setEnabled(true);OButton.setEnabled(true);
    PButton.setEnabled(true);QButton.setEnabled(true);RButton.setEnabled(true);SButton.setEnabled(true);TButton.setEnabled(true);
    UButton.setEnabled(true);VButton.setEnabled(true);WButton.setEnabled(true);XButton.setEnabled(true);YButton.setEnabled(true);
    ZButton.setEnabled(true);
}

private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) {
    // Exit the program
    System.exit(0);
}

private void AButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void BButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void CButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void DButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void EButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void FButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void GButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void HButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void IButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void JButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void KButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void LButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void MButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void NButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void OButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void PButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void QButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void RButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void SButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void TButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void UButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void VButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void WButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void XButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void YButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void ZButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DoButton.doClick();
}

private void DoButtonActionPerformed(java.awt.event.ActionEvent evt) {
    JButton button = (JButton) evt.getSource();
    String currentLetter = button.getText();

//replace underscores with letters as they are guessed
            do {
                for (int i = 0; i < 1; i++) {
                    secretWord = secretWord + currentLetter.charAt(0);
                    foundWord = words[0].replaceAll("[^" + secretWord + "]", "_ ");
                //if letter isn't in word
                    if (guessWord.indexOf(currentLetter) == -1) {
                        JOptionPane.showMessageDialog(null, "Sorry, that wasn't in the word.");
                        errors++;
                        if (errors == 1) {
                            Hangman0.setVisible(false);
                        }
                        if (errors == 2) {
                            Hangman1.setVisible(false);
                        }
                        if (errors == 3) {
                            Hangman2.setVisible(false);
                        }
                        if (errors == 4) {
                            Hangman3.setVisible(false);
                        }
                        if (errors == 5) {
                            Hangman4.setVisible(false);
                        }
                        if (errors == 6) {
                            Hangman5.setVisible(false);
                        }
                        if (errors == 7) {
                            Hangman6.setVisible(false);
                        }
                        if (errors == 8) {
                            Hangman7.setVisible(false);
                        }
                        if (errors == 9) {
                            Hangman8.setVisible(false);
                        }
                        if (errors == 10) {
                            Hangman9.setVisible(false);
                            JOptionPane.showMessageDialog(null, "You lost! The word was: " + guessWord);
                            losses++;
                            DirectionsFrame DFrame = new DirectionsFrame();
                            DFrame.setVisible(true);
                            setVisible(false);
                            MainFrame MFrame = new MainFrame();
                            MFrame.dispose();
                            secretWord = "";
                            foundWord = null;
                            String strLosses = Integer.toString(losses);
                            String strWin = Integer.toString(wins);
                            DirectionsFrame.WinsLabel.setText(strWin);
                            DirectionsFrame.LossesLabel.setText(strLosses);
                        }
            }
        }
                WordLabel.setText(foundWord.toUpperCase());
            } while (foundWord == null);
            if (foundWord.equalsIgnoreCase(guessWord)) {
                JOptionPane.showMessageDialog(null, "Yay!");
                wins++;
                DirectionsFrame DFrame = new DirectionsFrame();
                DFrame.setVisible(true);
                setVisible(false);
                MainFrame MFrame = new MainFrame();
                MFrame.dispose();
                secretWord = "";
                foundWord = null;
                String strWin = Integer.toString(wins);
                String strLosses = Integer.toString(losses);
                DirectionsFrame.WinsLabel.setText(strWin);
                DirectionsFrame.LossesLabel.setText(strLosses);
            }
}

Comment: @PaulSullivan, a project actually
Comment: kk sounded a bit like homework though :) good luck with your project
Comment: @PaulSullivan, i guess you could call it homework, but I'm doing this of my own accord without it being assigned, and thanks:)
Answer: Create an action listener:
ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        Object src = evt.getSource();
        if (evt instanceof JButton) {
            currentLetter = ((JButton) src).getText();
            // do something with letter
        } // else something seriously wrong
    }
};

Then add this action listener to each of the buttons in alphabet:
for (JButton button : alphabet) {
    button.addActionListener(al);
}

EDIT I don't see the implementation of initComponents() in your updated code. Regardless, adding an action listener to each button is something that needs to be done only once. here's how I would start implementing initComponents():
private static String[] letters = { "A", "B", "C", "D", "E", "F",
    "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
    "S", "T", "U", "V", "W", "X", "Y", "Z" };
private JButton[] letterButtons = new JButton[letters.length];

private void initComponents() {
    ActionListener al = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            Object src = evt.getSource();
            if (evt instanceof JButton) {
                currentLetter = ((JButton) src).getText();
                // do something with letter
            } // else something seriously wrong
        }
    };
    for (int i = 0; i < letters.length; ++i) {
        letterButtons[i] = new JButton(letters[i]);
        letterButtons[i].addActionListener(al);
    }
    . . .
    // add all the buttons to the user interface
    . . .
}

Please simplify your code by using more arrays! I certainly would not have a separate variable for each letter button or 26 separate methods to deal separately with each letter click.
Comment: @JavaProdigy - Oh. You created your class as a JFrame form. Don't do that; you need to be well-versed with the tool to use it for this kind of thing. Just create a regular Java class and then you can edit the code as you see fit. (You can keep the form around as a kind of sample code for what you really want to do. NetBeans does generate some useful template code.)
Comment: could you explain the logic behind this code? and also where would i put this in my code?
Comment: @JavaProdigy - You need an action listener for something to happen when a button is clicked. The action listener is passed an event that has as its source the button that was clicked. The action listener I suggest simply checks that the source is indeed a JButton (as a somewhat paranoid check, I guess) and then accesses the button text to set `currentLetter`. You would put this in the code where you define `alphabet` (or wherever you are initializing the UI).
Comment: when i add it to my code i get this: `ActionListener is abstract; cannot be instantiated`
Comment: @JavaProdigy - Did you import `java.awt.event.ActionEvent`? Did you use the code I posted?
Comment: i did import it, but i'm not understanding `for (JButton button : alphabet) {
    button.addActionListener(al);
}` do i put this in every letter block?
Comment: @JavaProdigy - You should do it once, when you define the `alphabet` array. It's hard to say where it should go in your code without seeing how it is structured.
Comment: @JavaProdigy - There's a lot about your code that I don't understand, but I've updated my answer to suggest a way forward.
Comment: i dont understand it all myself >.< haha i'm getting a bit frustrated. so in netbeans the `private void initComponents()` is in gray code (i cant edit it) so how would i add an actionlistener?
Comment: thats exactly right. i see what you're saying, if i have future problems I'll post another question, but you got me on the right track. Thanks!
Answer: Yes, a single ActionListener can be used for every button to determine not only what has been clicked but also to get its text. In your listener, you could use:
public void actionPerformed(ActionEvent e) {
    JButton button = (JButton) e.getSource();
    String currentLetter = button.getText();
    updateWord(currentLetter);
}

Once currentLetter is known you could pass it to a helper method, say, updateWord to reveal the necessary characters, etc.
private void updateWord(String currentLetter) {
 // reveal letters
 // increment 'Hangman' guess counter
}

Please read How to Write an Action Listener
Also consider using an Action for sharing functionality between buttons.
Comment: so say for instance my first JButton is called `AButton`. Would i replace all instances of `button` above with `AButton`? and would i have to do this for each of my 26 buttons?
Comment: No, `AButton` is just one button. You will need to add an `ActionListener` to _all_ of your buttons. In this case a single `ActionListener` will suffice.
Comment: let me see if i'm understanding. I have 26 blocks of code, one for each of my buttons. take the first one for example: `private void AButtonActionPerformed(java.awt.event.ActionEvent evt) { JButton button = (JButton) e.getSource();
    String currentLetter = button.getText();
    DoButton.doClick();` then repeat 25 more times for each button letter? the DoButton holds the code that replaces guessed letters with its letter and unguessed letters with underscores
Comment: No just one 'block' of code (with the `actionPerformed` method I have shown above) - but you register that one block with all your buttons.
Comment: this is what my code looks like (see edit in original post). the `        private void AButtonActionPerformed(java.awt.event.ActionEvent evt) {
        DoButton.doClick();
}  ` is copied 25 more times, for each button. the coding all looks the same. is this what u meant?
Comment: An `ActionListener` is an interface so cannot be added _without_ its implementation. Please follow the [link](http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html) above.
Answer: A good solution would not use something like 'AButton', 'BButton' and so on.
As you mentioned you can do it all with an Button-Array (length 26)!
initialize it in a loop, create 26 button instances, and register an ActionListener (always the same, not 26).
You can get the corresponding letter out of the Array-Index!
How? Take the ASCII-Table. Say you want to use Big Letters only, the A has the value 65.
So each buttons corresponds to the letter

65 + indexOf(button)
button[0] -> 65+0 = 'A'  button[1] -> 65+1 = 'B'

You get the idea.
The single ActionListener can use the same method to get the corresponding letter:
Something like:

char theLetter = (char) 65 + buttonArray.indexOf(e.getSource())

And you're done.
I think programming is not about getting it done somehow. You always should look for the perfect solution. If that solution is to hard for you, you should learn how to do it.
Regards!
Comment: could you explain how to do this in java code? and would `char the letter = (char) 65 + buttonArray.indexOf(e.getSource())` be put in my DoButton code? (see edit in original post)
Comment: But anyway: You shoudl use perhaps an ArrayList buttons=new .... You add the Buttons in a loop: for(int i=0; i<26; i++){ JButton button=new JButton(65+i+""); button.addActionListener(this); buttons.add(button) }
Comment: i've been trying to do this myself but im confused and need help, hence why i posted he question. by add buttons, do u mean add it to the frame?
Comment: no to the arraylist called 'buttons' but of course you will need to add them to the jframe too.


Different testing keywords in ruby? describe vs test

Question: I am a bit confused about RSpec/Integration testing in Ruby.
I have noticed some tests start with keyword test and some start with describe? What's the main difference? is it all RSpec?
for example
 test "email should be present" do
      @user.email = "     "
      assert_not @user.valid?
 end

and
describe 'can set' do
  it 'calories' do
    @dessert.calories = 80
  end
end

Edit:
MiniTest vs RSpec
Pros and cons?
Answer: The test...assert syntax is typical of MiniTest, sometimes also called Test Unit.
The describe...it syntax is typical of RSpec.
That said, MiniTest has two kinds of syntaxes, depending on your personal preference:

the test...assert which is the classic syntax; it's the one Rails uses for its own internal testing.
the describe...it syntax which is called MiniTest Spec; it is very much like a straightforward subset of RSpec's syntax.

If you're working on an existing project, it's good to write using the same syntax as the rest of the project, so your teammates can read the syntax easily.
(Your edit asked for pros and cons -- that's a question that's a better fit for googling rather than Stack Overflow, because there's so much to say about it and there are so many strong opinions. Both are excellent choices and in most projects you'll do great by using whatever the project is already using, or your teammates know the best.)
Answer: If you are asking why/how to use describe:
describe is useful because you can test several thing which are related without repeating yourself. For example, if you wanted to test that desert can set calories and taste, you could do:
describe 'desserts' do
  it 'can set calories' do
    @dessert.calories = 80
    ...test...
  end
  it 'can set taste' do
    @dessert.taste = 'delicious'
    ...test...
  end
end

When this fails, you will have a message like "Failed desserts can set calories..."
Instead of:
  it 'dessert can set calories' do
    @dessert.calories = 80
    ...test...
  end
  it 'dessert can set taste' do
    @dessert.taste = 'delicious'
    ...test...
  end

where it is less readable and you are repeating the word dessert.
Answer: The test syntax is from MiniTest, (Test::Unit in older Ruby versions) in the ruby standard library. describe/it are from Rspec.


Unable to get custom parameters passed using Twilio connect function for outgoing and incoming calls

Question: Am trying to create a call center with Twilio, am almost there but now am stuck because i can't get custom passed parameters.
My main aim is to allow customers to call but first they should provide their emails and names first, then click call-customer button, i want to receive the custom parameters on the agent's side.
Now i try to pass the parameters but i can't retrieve them.
Here is my code to make and receive calls and to pass and get the parameters
(Customer side)This code allows outgoing calls, customers to make calls to the call-center agents
require __DIR__ . '/vendor/autoload.php';
use Twilio\Jwt\ClientToken;

$accountSid = '';
$authToken  = '';
$appSid = '';

$capability = new ClientToken($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$token = $capability->generateToken();

So according to the documentation i should pass the custom parameters like this:
var params = {"name": "John", "email": "email@example.com"};
             Twilio.Device.connect(params);

(Agent side) This code allows incoming calls from customers to agents.
$accountSid = '';
$authToken  = '';

$capability = new ClientToken($accountSid, $authToken);
$capability->allowClientIncoming('joey');
$token = $capability->generateToken();

In the agent side i use this code to receive customer information or custom parameters.
According to the documentation a code to get custom parameters is this:
if (connection.customParameters.hasOwnProperty("name")) {
            let displayName = connection.customParameters.get("name");
            console.log(displayName)
        }

        if (connection.customParameters.hasOwnProperty("email")) {
            let customerID = connection.customParameters.get("email");
            console.log(customerID)
        }

but i get undefined
So when a customer calls this twilio function en-queues the call and assign it to an operator
here is the code:
exports.handler = function(context, event, callback) {
  let twiml = new Twilio.twiml.VoiceResponse();

    twiml.say(" Please hold, while we connect you to one of our available agent ");
    twiml.enqueue({
    workflowSid: context.WORKFLOW_SID
    }).task({}, `{"selected_skill":"operator"}`);
  callback(null, twiml);
};

Then from here an available operator will accept the task then dial an agent
The operator dials the client like this
{"skills":["operator"],"contact_uri":"client:joey"}

Please help
Thanks in advance
Answer: Based on my take on the associated documentation, it looks like the parameters are only sent to the Twilio client via TwiML, as shown here.
https://www.twilio.com/docs/voice/client/javascript/changelog#160-aug-29-2018

Added support for custom incoming parameters from TwiML as Map Connection.customParameters. When a TwiML application sends
  custom parameters using the  noun, these parameters will be
  added to Connection.customParameters

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Dial>
    <Client>
      <Identity>alice</Identity>
      <Parameter name="foo" value="bar"/>
      <Parameter name="baz" value="123"/>
    </Client>
  </Dial>
</Response>

It sounds like you are using the Task Router JavaScript SDK, maybe you can add these parameters as attributes to the task, and then access those tasks from the Task Router client SDK?
Comment: @tp45, you're using the TwiML `` verb to pass the call to Task Router, so I am pretty sure you cannot use the TwiML `` noun to pass information to the agent.

For the customer leg, you should see the params you pass to your Twilio Function under, `event.name` and `event.email`, so you can use those values to add Task Router attributes to pass into the Task Router Client via `` and pull them out that way.

So, edit your Twilio Function to change this:
`.task(`{"selected_skill":"operator", "name": "${event.name}", "email": "${event.email}"`);`
Comment: Thanks @Alan. i see this twiml but i don't understand it. like how do i pass  data from html inputs to this twiml , because before a customer make a call they have to input their email and name then click to call, on the agent side they answer the call and they see the products that the customer bought (something like crm)
Comment: So i can still set the custom parameters like this ```let connection = Twilio.Device.connect({
  "customerID": "375d1d60-083b-404d",
  "selectedProductID": "87144192-73e2-45a6"
});```  then get them like  this ```if (connection.customParameters.hasOwnProperty("selectedProductID")) {
   let selectedProductID = connection.customParameters.get("selectedProductID");
   // Do something with selectedProductID
}```
Comment: Yes to first one, no to second.
Comment: Thank you so much @Alan everything works i can get the custom parameters. am getting them like this: ```reservation.task.attributes.name```
Comment: Outstanding :) Thanks for sharing and glad I could help.


Consider the polynomial $f(X) \in \mathbb{Z}[x]$ prove the following

Question: Let  $f(X) \in \mathbb{Z}[x]$ be a polynomial. Prove the following:
i) For every natural $n>0$ the equation $f(x)=n$ has a solution in $\mathbb{Z}$ then $f(x)=\pm x + c$ with $c$ constant.
ii) If $f(\mathbb{Z})$ contains only prime numbers then $f$ is constant. [Something stronger has been proven here A nonconstant polynomial $q$ with $q(0)>1$ attains infinitely many composite values at integers ... or is it stronger? Here I just need to find one number which isn't prime]
iii) If $f(\mathbb{Z})$ contains only numbers of the set $\{\pm 2^a  3^b; a,b \in \mathbb{N}\}$ then $f$ is constant.
I have proved it, but especially for the last two points my solution (at least, to me) doesn't feel elegant...is there a way to prove it directly? Thank you for the help!
Answer: Every number I use, unless specified differently, shall be considered in $\mathbb{Z}$. Also, the generic polynomial shall be $f(x)=a_n x^n + ... + a_1 x + a_0$.
i) Let $deg(f(x))\geq 2$. Consider the derivative $f'(x)$. If the equation $f(x)=n$ has a solution $x_n$ this means we have $f'(x_n)=0$. Thus $f'(x)$ has infinitely many solutions and it is a polynomial. This is absurd $\Rightarrow \ f(x) = a x + c$. If $a=0$ clearly it can't have a solution for every $n$. Then let $|a| \not=1$. Consider $n=|a-1|+c$. The only soution is then $\frac{|a-1|}{a}$ which is not an integer.
ii) We shall prove the converse, namely: "If $f$ is not constant then $f(\mathbb{Z})$ does not contain only prime numbers".
Suppose the absurd "$f(\mathbb{Z})$ contains only prime numbers". Then $f(0)=a_0$ so it's a prime number, which means $a_0>1 \Rightarrow f(a_0)$ is not a prime.
iii) We shall prove the converse, namely: "If $f$ is not constant then $f(\mathbb{Z})$ does not contain only numbers in the form $\pm 2^a  3^b$."
If $a_0=0$ the answer is trivial. If $|a|=1$ then $f(2)$ not in that form. Otherwise $f(a_0) = a_0 (1+a_1 a_0 + ... + a_n a_0^{n-1})$ is not in that form.
Comment: The solution for (i) cannot be right because the polynomial $f(x) = x^3$ has solutions for $f(x_n) = n$ for every natural number $n$, it's just that the solutions are not always natural numbers.
Comment: Oh, it was in $\mathbb{Z}$, but your comment is still valid and yes...it was very silly of me to make such a mistake. Thank you!
Answer: i) Suppose that for every $n$ there exists $x_n$ such that $f(x_n)=n$. Then you have $x_{n+1}-x_n |f(x_{n+1})-f(x_n)=1$ which means that $|x_{n+1}-x_n|=1$. This means that $(x_n)$ is a sequence of consecutive integers (increasing or decreasing). So $x_n = \pm n +c$. As a consequence, we know that the polynomial
$$ f(x)-(\pm x+c)$$ has infinitely many roots, and is therefore the zero polynomial.
ii) Pick an integer such that $f(k)\neq 0,\pm 1$ and denote $p=f(k)$. Then $p|f(k+l\cdot p)-f(k)$ so $f(k+l\cdot p)$ is also divisible with $p$ for any $l$. Since $f(k+l\cdot p)$ gets arbitrary larger and it is divisible by $p$, it cannot be always a prime number.


No connection between two melodies in an opus

Question: I was listening to Beethoven - Symphony No. 5 in C minor, Op. 67:

I have noticed that the opus has two parts: the first part with the famous melody we all know, and the second one which is completely a different one, around 08:43 in the video.
It is interesting to know why an opus has these two different melodies inside of it?
Comment: This is a great idea to listen the symphonies of Beethoven.  I was about 30 years old when I listened the first time to classical Symphonies. But today it is a lot easier to listen and look the youtube videos. What will be helpful - and what we didn't have in our youth was the information you can find today in Wikipedia. It is also interesting to read more about the composer and know his life and the circumstances of the time when a work has been composed. Also the links of Pied Piper are very informativ and it's worth to understand the *sonata form*. Get it and you will like all symphonies.
Answer: There are actually four parts to this symphony (called "movements"). The classical symphony has four movements:

An opening movement in sonata form, usually somewhat fast ("allegro")
A slow movement
A minuet or scherzo with trio
An allegro, rondo, or sonata

Usually there is no musical connection between the movements, except for the key. Later composers during what is known as the "Romantic" period, often did return to earlier themes in the later movements of a symphony (e.g. Mahler in his 1st symphony).
A piece in sonata form usually has two contrasting themes which are first played one after the other (called the "exposition"). This is followed by the "development" where the composer explores harmonic and textural possibilities of the themes. Finally the themes are repeated (the "recapitulation").
More at the link.
Comment: @CarlWitthoft The 9th might be considered to be one of the first "romantic" works
Comment: Beethoven reprises , very brieflly, first movement themes in the last movement of his 9th Symphony
Comment: Ironically, the 4th movement of Beethoven's 5th Symphony quotes the 3rd movement, and the 3rd movement can be said to abuse the same "Fate" rhythmic motif as the 1st movement.


How to get around "Can't convert nil into String (TypeError)" when reading a csv file in Ruby?

Question: I am working on a program that will eventually compare two .csv files and print out any variances between the two. However, at the moment I can't get past a "can't convert nil into String (TypeError)" when reading one of the files.
Here is a sample line from the problematic csv file:
11/13/15,11:31:00,ABCD,4000150097,1321126281700ABCDEF,WR00002440,,,4001,1392,AI,INTERNAL RETURN,INBOUND,,ABCDEF

And here is my code so far:
require 'csv'
class CSVReportCompare

  def initialize(filename_data, filename_compare)
    puts "setting filename_data=", filename_data
    puts "setting compare=", filename_compare
    @filename_data = filename_data
    @filenam_compare = filename_compare
  end

  def printData
    @data = CSV.read(@filename_data)
    puts @data.inspect
  end

  def printCompareData
    @compareData = CSV.read(@filename_compare)
    puts @compareData.inspect
  end

  def compareData

  end

end

c1 = CSVReportCompare.new("data.csv", "compare_data.csv")
c1.printData
c1.printCompareData

Anyways, is there a way to get around the error?
Answer: You have a typo in your initialize method:
@filenam_compare = filename_compare
#-------^ missing "e"

So you're setting the wrong instance variable. Instance variables are created when they're first used and initialized to nil so later, when you try to access @filename_compare, the instance variable with the correct name is created and has a value of nil.
Comment: @sean: If you had warnings on, it would have warned you about `@filename_compare` being uninitialized.
Comment: @AndrewGrimm I will make sure to run my scripts with warnings on. Is there a way to have Ruby always run scripts with warnings (instead of calling scripts with `ruby -w script.rb`? I've been searching around and haven't come up with a way to do this.
Comment: Wow, glad it was my fault and not a problem with the csv file... thank you!
Comment: @Andrew: Oh how I wish warnings were enabled by default. Do we really have to learn this exact same lesson with every single language?
Comment: @muistooshort: Why not propose it for Ruby 2.0?


Can Q-learning or SARSA be used to find an stochastic policy?

Question: If the optimal policy is known to be stochastic (e.g. like in the stone, paper, scissors game), can this stochastic policy be found using SARSA or Q-learning, or is it only possible with policy gradient approaches?
Answer: Neither Q-learning nor SARSA define strictly how the policy should be derived from action-values, so you might be able to use them to learn some approximation to stochastic policies, if you used a variation of Gibbs (or Boltzmann) sampling.
However, I expect it would be an uphill battle. Q-learning especially is built around the idea of bootstrapping from a maximum value, so the assumption of a deterministic policy is built into the learning algorithm. At least with SARSA (or expected SARSA) you can feed in a real policy choice and optimise that - however, even there the assumption is built in that you should increase the probability of taking the current return maximising action. In a scissor-paper-stone scenario this may actually reduce the expected long-term return, so the learning algorithm may oscillate. It is likely to be sensitive to, and limited by, the hyper-parameters of how you make action selection, than you are not able to learn or change within the algorithm (compare to policy gradient methods, where parameters controlling action selection are directly modified by the optimisation).
The problem is that in value-based methods, you get no indication of how changing the policy will affect values. Instead it is implicit that selecting the highest values is always good. Note this is strictly true in fully-specified MDPs, which can be proven to have optimal deterministic policies. So it is not necessarily a bad thing.
Adversarial games like  stone, paper, scissors are not strict MDPs unless you "freeze" the behaviour of an opponent (this opponent can still behave stochastically and react to your previous plays, but once their policy is fixed, then it is possible to optimise a deterministic policy to play against it). When you allow agents to react to each others' play and change both policies is when you need a stochastic policy, and when value-based learning algorithms will start to let you down.
I think you could probably get SARSA using Gibbs action sampling and a low learning rate to learn a correct behaviour for stone, paper, scissors. It would struggle though to learn policies where rewards were not even, e.g. modified stone, paper, scissors, where you score 1 for winning as stone, 2 for winning as paper and 3 for winning as scissors - this has an analytical solution, but you won't get SARSA to approximate it without very careful tuning of the temperature hyper-parameter.


Limiting to a single many-to-many relationship in Laravel eloquent

Question: A Paper can have many Authors and an Author can have many Papers. An Author cannot be listed as an Author more than once on the same Paper.
I've set up the many-to-many relationship in Laravel and I am able to use the attach method to link Authors to a Paper. However, Laravel allows me to add the same Author twice.
Here is a contrived example.
// App\Models\Author
public function papers() {
    return $this->belongsToMany (Paper::class);
}

// App\Models\Paper
public function authors() {
    return $this->belongsToMany (Author::class);
}

// LinkController
public function store (Author $author) {
    $author->papers()->attach (request ("paper")); // works
    $author->papers()->attach (request ("paper")); // adds a second link, should do nothing.
}

Obviously I'm hard-coding the second attach above, but users can select the same author twice.
How can I tell Laravel to silently ignore the second request?
Answer: I've discovered the syncWithoutDetaching method:
// LinkController
public function store (Author $author) {
    $author->papers()->syncWithoutDetaching ([request ("paper")]);
    $author->papers()->syncWithoutDetaching ([request ("paper")]); // does nothing.
}

Comment: Or maybe you can use a composite unique index on those two columns in the pivot table so it will prevent even manual addition.
Comment: Doesn't that cause an error when inserting the second row?


Cannot modify header information - headers already sent by

Question: Hi i have an error on my Codeigniter :
A PHP Error was encountered
Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at C:\PROJECT_TEMP\evaluasiTIK_HG\application\modules\rss\controllers\feed.php:25)

Filename: controllers/feed.php

Line Number: 21

feed.php:
<?php
class Feed extends Controller
{

    function Feed()
    {
        parent::Controller();
        $this->load->model('posts_model', '', TRUE);
        $this->load->helper('xml');
    }

    function index()
    {
        $data['encoding'] = 'utf-8';
        $data['feed_name'] = 'DerekAllard.com';
        $data['feed_url'] = 'http://www.syslog-center.net/theme/theme2/syslog.xml';
        $data['page_description'] = 'Code Igniter, PHP, and the World of Web Design';
        $data['page_language'] = 'en-ca';
        $data['creator_email'] = 'Derek Allard is at derek at derekallard dot com';
        $data['posts'] = $this->posts_model->getRecentPosts();
        header("Content-Type: application/rss+xml");
        view('rss/feed', $data);
    }
}
?>

Anyone can help me. please :)
Comment: Check if your file is saved with UTF-8 BOM, if it is, just remove it.
Comment: What version of CodeIgniter are you using?
Comment: remove the `?>` from the end of feed.php and try again
Answer: You have extraneous whitespace after the ?>, remove the last line.
Answer: Do you use 1.7.2 version of CodeIgniter? Please modified your code:
find
header("Content-Type: application/rss+xml");
view('rss/feed', $data);

replace with:
$this->output->set_header("Content-Type: application/rss+xml");
$this->load->view('rss/feed', $data));


Extract date ("05/Jan/2014") from string

Question: I would like to extract date from a string like :
15/Nov/2013
05/Jan/2014

and reformat it like this
15/11/2013
05/01/2014

Is there a ready-to-use function for this (that already "knows" months : Jan, Feb, etc.) ?
Comment: [Yes, there is such a function](http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior).
Answer: If your locale is english, then the standard datetime module will parse month abbreviations for you:
import datetime

date = datetime.datetime.strptime(inputvalue, '%d/%b/%Y').date()

C (English month names) is the default locale, so this should work anywhere you don't set the Python locale explicitly. As long as you don't call locale.setlocale() or locale.resetlocale() anywhere you can count on the above to work correctly.
Formatting these back to a different format is then trivial:
date.strftime('%d/%m/%Y')

Demo:
>>> datetime.datetime.strptime('15/Nov/2013', '%d/%b/%Y').date()
datetime.date(2013, 11, 15)
>>> datetime.datetime.strptime('05/Jan/2014', '%d/%b/%Y').date()
datetime.date(2014, 1, 5)
>>> datetime.datetime.strptime('15/Nov/2013', '%d/%b/%Y').date().strftime('%d/%m/%Y')
'15/11/2013'
>>> datetime.datetime.strptime('05/Jan/2014', '%d/%b/%Y').date().strftime('%d/%m/%Y')
'05/01/2014'

Comment: @Soumen: [Parse this date in Python: 5th November 2010](http://stackoverflow.com/q/3461435)
Comment: Is there any method to convert "25th November, 2016" this type to string to date object?
Answer: Do this:
>>> import datetime
>>> datetime.datetime.strptime('15/Nov/2013', '%d/%b/%Y').strftime('%d/%m/%Y')
'15/11/2013'

As Martijn Pieters noted, your locale should be English (e.g. en_US) for this to work. If you haven't done anything to alter locale, it will presumably be some flavor of English.
Answer: I tend to go with dateutil.parser to convert a string to a python datetime object. It has so far managed to handle every conversion I have wanted to do. Once you have it in a datetime object, you can easily convert it to a string format of your choice.
>>> import dateutil.parser
>>> dateutil.parser.parse('15/Nov/2013').strftime("%d/%m/%Y")
'15/11/2013'

The function would, at the same time be able to handle other formats, e.g. YYYY-mm-DD without any changes from your side.
>>> dateutil.parser.parse('2013-11-15').strftime("%d/%m/%Y")
'15/11/2013'


Cadastrar com modal e javascript

Question: Tenho um form e dentro dele tenho vários modais com form dentro da modal como faço para salvar o que ta na modal sem interferir no form de fora pois com as modais que tem os forms dentro o form com a action processa/proc_cad_pessoa nao vai para  a página
<form role="form" method = "POST" action = "processa/proc_cad_pessoa.php" name="formulario">

Indentificação Pessoal

                                                        Nome
                                                        <input type="text" class="form-control" name="nomepessoa" placeholder="Nome da Pessoa"/>

                                                        Sexo:

                                                            <input type="radio" name="optradio" value="M">Masculino

                                                            <input type="radio" name="optradio" value="F">Feminino

                                                                                ×

                                                                                Adicionar Ensino

                                                                                Ensino: *

                                                                                Cadastrar

Answer: Não encontrei a tag </form> ser fechada . Seja mais específico na sua pergunta , está um pouco confusa porque não conhecemos seu cenário .
Answer: Olá, você tem que deixar mais claro a diferença entre a tag <form> do html e a classe .form-group do framework boostrap, pois ficou muito confuso a pergunta, felizmente eu pude identificar porque já utilizei esse framework.
Assim como o Leonardo Marques disse, não tem fechamento da tag html <form> nesse código ai, e complemento dizendo que não tem <button> ou tag a do tipo submit, sendo responsável por disparara  ação de enviar os dados pelo method POST para a pagina processa/proc_cad_pessoa.php

Cadastrar com modal e javascript


Question about regularity / integrality

Question:
Let $k$ be an algebraically closed  field, and let $R:=k[X,Y,Z]/(X^2+Y^5+Z^3)$. Show that, for any $f\in (X,Y)\subset k[X,Y]$, the localization $R[f^{-1}]$ is integrally closed,  and deduce  that $R$ is  integrally  closed.

First, observe that $X^2+Y^5+Z^3$ is irreducible, for in $k[X,Y]$ there are no cubic roots of  $X^2+Y^5$, and so it is the minimal polynomial of $\sqrt[3]{X^2+Y^5}$ over $k[X,Y]$. This means that $R$ is a domain and a free $k[X,Y]$-module. We will need also that $\operatorname{Spec}R$ is regular at every  point but $(0,0,0)$, that is easily verified with the Jacobian criterion, knowing $\operatorname{dim}R=2$. Thus a localization $R_\mathfrak M$, for any maximal ideal $\mathfrak M\subset R$, is regular if and only $\mathfrak M$ is not (the image in $R$ of) $(X,Y,Z)$.
Claim: if $S$ is a multiplicatively closed set of a domain $R$, $\mathfrak  p\subset R[S^{-1}]$ is a prime ideal, and $\mathfrak P:=\mathfrak p\cap  R$, then  $R[S^{-1}]_{\mathfrak p}\cong R_{\mathfrak P}$. Proof: for  every subset $A\subseteq R$, denote with $A[S^{-1}]$ the set of (the equivalence classes of) the elements in $R[S^{-1}]$ with numerators in $A$; set also $T:=R-\mathfrak  P$,  so  that $R_{\mathfrak P}\cong R[T^{-1}]$.  We know that $\mathfrak p=\mathfrak P[S^{-1}]$ and $R[S^{-1}]-\mathfrak P[S^{-1}]=T[S^{-1}]$, so $R[S^{-1}]_{\mathfrak p}\cong R[S^{-1}][T[S^{-1}]]^{-1}$. Since $S\subseteq T$, it makes sense to define this map, that is actually a isomorphism: $$R[S^{-1}][T[S^{-1}]]^{-1}\to R[T^{-1}]:\frac rs /\frac t{s'}\mapsto  \frac{rs'}{st}.$$
Then we can say that  for any maximal ideal $\mathfrak m\subset R[f^{-1}]$ there is an isomorphism $R[f^{-1}]_\mathfrak m\cong R_\mathfrak M$, where $\mathfrak M:=\mathfrak m\cap R$. But $R_\mathfrak M$ is regular unless $\mathfrak M=(X,Y,Z)$, and this cannot be, as $f\notin \mathfrak M$, so $R[f^{-1}]_\mathfrak m$ is regular for any $\mathfrak m$. Here I have a question: does regularity (of a domain) implies integral  closedness? If yes, we'd be done since the localization of $R[f^{-1}]$ at any maximal ideal  would be integrally closed; however in my course we only saw that the two conditions are equivalent in dimension $1$, and I didn't find results in this direction on the books of Atiyah&Macdonald or Bosch.
In order to see that $R$ is integrally closed,  we can show that $R=\bigcap_{f\in (X,Y)}R[f^{-1}]$; then we'd be done, for the intersection of integrally closed domains is integrally closed. Notice that $k[X,Y]_f=\{\frac hg\in k(X,Y):g=f^n\text{ for some }n\}$, meaning that $\bigcap_{f\in (X,Y)}k[X,Y]_f$ is the set $\{\frac hg\in k(X,Y):\forall f\in (X,Y)\ (g=f^n\text{ for some }n)\}$; however using that $k[X,Y]$ is a factorial ring it should  easily follow that the only element that is power of every $f\in (X,Y)$ is $1$. Hence $\bigcap_{f\in (X,Y)}k[X,Y]_f=k[X,Y]$; knowing that $R\cong k[X,Y]\oplus k[X,Y]\oplus k[X,Y]$, finally $$\bigcap_{f\in(X,Y)}R[f^{-1}]\cong \bigcap_{f\in(X,Y)}k[X,Y]_f\oplus k[X,Y]_f\oplus k[X,Y]_f\cong k[X,Y]\oplus k[X,Y]\oplus k[X,Y]\cong R.$$
So the main question is the one in italics; anyway you're free to read the (attempt of) proof, any correction is welcome.
Answer: Yes, regularity implies integral closedness. By the Auslander-Buchsbaum theorem, a regular local ring is a UFD, and it is well-known that a UFD is integrally closed in its field of fractions. So the localization of the domain $R[f^{-1}]$ at any maximal ideal is integrally closed in its field of fractions, which implies that $R[f^{-1}]$ must be integrally closed in its field of fractions too. (More generally, a regular scheme is normal, and for any open $U\subset X$ in a normal scheme, $\mathcal{O}_X(U)$ is a normal ring, ref 033J.)
One may also conclude that $R$ is integrally closed from the Serre conditions $R_1$ and $S_2$ - $S_2$ is automatic from being a hypersurface in affine space, and $R_1$ can be shown by computing the singular locus via the Jacobian criteria. This is also well-covered in the literature and on MSE.
Let me also mention that this ring displays some interesting behavior: if $k$ is not of characteristic 2, 3, or 5, the completion of this ring, $k[[x,y,z]]/(x^2+y^3+z^5)$, is the only nonregular normal complete 2-dimensional local ring which is a UFD. This was proven by Lipman in Rational singularities with applications to algebraic surfaces and unique factorization. The spectrum of $R$ is also a Du Val singularity, and the Dynkin diagram you get by resolving it is $E_8$, which is another interesting property.

Question about regularity / integrality