Sorting JDOM elements using Java API

Question: I need your help with following issue:
In my code I have a list of elements, I need to sort this list according to 2 attributes: season and number.
List example:
<episode_list>
<episode id="280" number="13" season="1">
<title><![CDATA[Bowl Game]]></title>
</episode>
<episode id="314" number="12" season="1">
<title><![CDATA[Piss Test]]></title>
</episode>
<episode id="730" number="11" season="1">

I use Collections.sort(), but getting exception. As I understand I can't use it with JDOM Elements:
List<Element> episodes;

Collections.sort(episodes, new Comparator<Element>() {

            @Override
            public int compare(Element elem1, Element elem2) {
                Integer seasonNumber1 = Integer.valueOf(myService.valueOfAttribute("season", elem1));
                Integer seasonNumber2 = Integer.valueOf(myService.valueOfAttribute("season", elem2));
                int seasonComp = seasonNumber1.compareTo(seasonNumber2);
                if (seasonComp != 0) {
                    return seasonComp;
                } else {
                    Integer episodeNumber1 = Integer.valueOf(myService.valueOfAttribute("number", elem1));
                    Integer episodeNumber2 = Integer.valueOf(myService.valueOfAttribute("number", elem2));
                    return episodeNumber1.compareTo(episodeNumber2);
                }
            }
        });

Exception: java.util.Collections$UnmodifiableList$1.set(Unknown Source)
          java.util.Collections.sort(Unknown Source)

Actually I don't need sorted xml, the only thing I need is the episode attribute "id" (for the lowest season and the lowest episode number).
What could you recommend? I have another implementation, where I go through all elements, but I don't think it's a nice solution...I also can create Java class Episode(id, episode, season), transform List to List  and sort it, but also don't think it's a good idea. There is also sortContent method for Element, but I'm not sure how to implement it.
I'll appreciate any help.
Answer: Content attached to JDOM Elements cannot be sorted using the standard Collections.sort() mechanism because that process does not honour the only-attached-at-one-place-at-a-time rule for XML content.
JDOM has sort() methods built in to the Element class that allows you to sort the chile Elements or other Child content: See The Element.sortChildren() Javadoc for the JDOM way to do it.
Update: Also, for your reference, the error you are getting is because at some point you created an unmodifiable version of the List.... this is not something that happens from JDOM method calls. The error you are getting is because you are trying to modify a List that has been intentionally made read-only.
Comment: Thank you! I just decided to go through all elements since I don't need the whole xml sorted.
Comment: For people who are stuck on JDOM 1, the easiest workaround appears to be to get the list using element.removeContent(), then sort it, then use setContent() or addContent() to put it back.
Answer: What's wrong with going through the list and finding the minimum. It is O(n), while sorting is O(n*log(n)). You might use a generic min function, such as the one in guava
Element firstEpisode = Ordering.from(your-comparator).min(episodes.iterator());

If you really want to sort it, why don't you sort new ArrayList<Element>(episodes) (I agree with rolfl that you cannot use Collections.sort for JDOM lists and that the error comes from your use of unmodifiable list).

Sorting JDOM elements using Java API


How to select the items in form helper

Question: I want to know how to use form helper deeply
Given, there is a table like this
ID |student |sex
1  | bob    | 2
2  | kayo   | 1
3  | ken    | 2

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
       ->add('student')

this code shows
shows select box
<option> bob</option>
<option> kayo</option>
<option> ken</option>

But I want to show only candidate whose sex is 2
<option> bob</option>
<option> ken</option>

How can I do this?
Please help me.
Answer: I do not use SonataAdminBundle but I think you can do it like that cause it using Symfony entity type so your code should looks like:
$formMapper
   ->add(
       'student',
       'entity',
       array(
           'query_builder' => function (\Doctrine\ORM\EntityRepository $rep) {
                return $rep
                    ->createQueryBuilder('s')
                    ->where('s.sex = 2')
                ;
           }
       )
   )
;

Comment: Thanks!l310!! I have changed 'entity' -> 'null' because it shows the class is missing error.my final code is.

            ->add('student',
                    null,
                        array(
                       'query_builder' => function (\Doctrine\ORM\EntityRepository $rep) {
                            return $rep
                                ->createQueryBuilder('s')
                                ->where('s.sex = 1');
                        }
                    )
                 )
Comment: thanks l310. I really appreciate your help. http://stackoverflow.com/questions/16135722/how-to-select-the-items-which-belonging-to-group-in-form-helper However I bumped into new issue,I made another question.Please have a look if you have time.

How to select the items in form helper


If $\sum a_n$ diverges, prove that $\sum \frac{a_n}{1+a_n}$ diverges

Question: And suppose that $a_n > 0\quad \forall n$. Since the case $b_n := \frac{a_n}{1+a_n} \to p$ with $p \ne 0$ is clear, I'm supposing that $b_n\to 0$ and that $\sum b_n$ converges.
So for any real $M > 0$ I have that there's a natural $N$ such that $n\ge N \implies$ $$1+\frac{1}{a_n}>M$$
I feel that there's a way to limit $a_n$ by $b_n$ so that convergence of $\sum b_n$ implies the contradiction that $\sum a_n$ converges. But I'm getting nothing from these hypothesis.
Comment: I think  one of the statements in your title is backwards
Comment: Let $a_n=n^2-1$. Then $\sum a_n$ diverges but $\sum\frac{1}{1+a_n}$ converges.
Comment: It's $\sum \frac{a_n}{1+a_n}$, I corrected it
Comment: https://math.stackexchange.com/q/131678/321264
Answer: If $a_n\not\to0$, then ${a_n\over1+a_n}\not\to0$.  If $a_n\to0$ (and $a_n\ge0$), then ${a_n\over1+a_n}\gt{a_n\over2}$ for all large $n$.  In either case $\sum{a_n\over1+a_n}$ diverges.
Comment: @FryanBury, if $a_n\to0$, then $a_n\lt1$ for large $n$, and if $0\le a_n\lt1$, then $1/(1+a_n)\gt1/2$.
Comment: I didn't understand how you got $\frac{a_n}{1+a_n} > \frac{a_n}{2}$ from $a_n \to 0$ and $a_n>0$.
Answer: There are $2$ cases to consider:
$a)$ The sequence $\{a_n\}$ is bounded, which means $|a_n| < M$ for some $M > 0$. Thus $\dfrac{a_n}{1+a_n}> \dfrac{a_n}{1+M}$, and $\sum_{n}\dfrac{1} {1+M}a_n$ diverges to $+\infty$, hence $\sum_{n}\dfrac{a_n}{1+a_n}$ diverges to $+\infty$
$b)$ The sequence $\{a_n\}$ is unbounded, thus for each $k \ge 1$, we can find a term $a_{n_k}$ such that $a_{n_k}> k\implies \sum_{n}\dfrac{a_n}{1+a_n} \ge \sum_{k}\dfrac{a_{n_k}}{1+a_{n_k}} > \sum_{k}\dfrac{k}{1+k} > \sum_{k}\dfrac{1}{k} = +\infty$
In either case, we find that the series in question diverges by comparison with a diverging series.
Comment: Minor quibble:  You want the $n_k$'s to be distinct, e.g, $n_1\lt n_2\lt n_3\lt\cdots$.
Answer: asymptotic comparison
If $\lim_{n\to+\infty}a_n=0$ then
$$a_n\sim \frac {a_n}{1+a_n} \;\;(n\to+\infty) $$
so the two series have the same nature.


What will happen to an F1 team if they exceed the budget cap for a season?

Question: Recently, there were news regarding the Red Bull team where they may have exceeded the budget cap for the 2021 season. I believe that this case is still under investigation. What would happen to the Red Bull team if they were found guilty of exceeding the budget cap? Would the championship be transferred to Hamilton or not?
Answer: TL;DR
Depending on the severity of the breach, and assuming that it is Red Bull who are the guilty party (I don't think it's official that they are the team under investigation but the rumour mill is well and truly saying it is), then, yes, there is a possibility that the Driver's Championship could be handed to Lewis Hamilton, by the means of a Points deduction for Max Verstappen, or even out-right disqualification from the Championship, though these are only some of the possible reprimands.

This will depend on just how much any alleged teams have overspent. The punishments are split between a "Minor" and a "Material" overspend breach, which appears to be defined as whether the overspend is above/below 5% over the cap.
From the 2021 FIA Financial Regulations1:

8.10 A "Minor Overspend Breach" arises when:
(a) an F1 Team submits its Full Year Reporting Documentation and Relevant Costs reported therein exceed the Cost Cap by less than 5%; or
(b) following the review of an F1 Team's Full Year Reporting Documentation (including, where applicable, the conclusion of any investigation undertaken by the Cost Cap Administration and/or the Independent Audit Firm appointed by the Cost Cap Administration), the F1 Team's Relevant Costs have been determined to exceed the Cost Cap by less than 5%.
8.11 In the event the Cost Cap Adjudication Panel determines that an F1 Team has committed a Minor Overspend Breach, the Cost Cap Adjudication Panel may impose a Financial Penalty and/or any Minor Sporting Penalties.
8.12 A "Material Overspend Breach" arises when:
(a) an F1 Team submits its Full Year Reporting Documentation and Relevant Costs reported therein exceed the Cost Cap by 5% or more; or
(b) following the review of an F1 Team's Full Year Reporting Documentation (including, where applicable, the conclusion of any investigation undertaken by the Cost Cap Administration and/or the Independent Audit Firm appointed by the Cost Cap Administration), the F1 Team's Relevant Costs have been determined to exceed the Cost Cap by 5% or more.
8.13 In the event the Cost Cap Adjudication Panel determines that an F1 Team has committed a Material Overspend Breach, the Cost Cap Adjudication Panel shall impose a Constructors' Championship points deduction in accordance with Article 9.1(c)(i) and additionally may impose a Financial Penalty and/or any other Material Sporting Penalties.

Then later in the regulations, the punishments for a Minor and Material breach are laid out in Article 9:

9.1 The following sanctions may be imposed for breach of these Financial Regulations as set out in Article 8:
(a) A "Financial Penalty", meaning a fine in an amount to be determined on a case by case basis.

(b) A "Minor Sporting Penalty", meaning one or more of the following:
(i) public reprimand;
(ii) deduction of Constructors' Championship points awarded for the
Championship that took place within the Reporting Period of the breach;
(iii) deduction of Drivers' Championship points awarded for the Championship that took place within the Reporting Period of the breach;
(iv) suspension from one or more stages of a Competition or Competitions,
excluding for the avoidance of doubt the race itself;
(v) limitations on ability to conduct aerodynamic or other Testing; and/or
(vi) reduction of the Cost Cap

(c) A "Material Sporting Penalty", meaning one or more of the following:
(i) deduction of Constructors' Championship points awarded for the
Championship that took place within the Reporting Period of the breach;
(ii) deduction of Drivers' Championship points awarded for the Championship
that took place within the Reporting Period of the breach;
(iii) suspension from one or more stages of a Competition or Competitions,
excluding for the avoidance of doubt the race itself;
(iv) limitations on the ability to conduct aerodynamic or other Testing;
(v) suspension from an entire Competition or Competitions, including for the avoidance of doubt the race itself;
(vi) exclusion from the Championship; or
(vii) reduction of the Cost Cap

These are the regulations for the year in which Red Bull were alleged to have broken the rules


Prove $x^3 + \sin(3x) = 98$ has a solution in $(0 , 10)$

Question: I believe I need to use the intermediate value theorem for this, but I'm unsure where to go from there. Note that it's a polynomial, so it's going to be continuous.
So I let $f(x)=x^3+\sin(3x)=98$
then we are looking for a number between 1 and 10 such that $f(c)=0$ So I start plugging in numbers and looking for the solution to go from flip from negative to positive or vice versa.
$f(1)= (1)^3+sin(3*1)-98$
$= sin(3)-97$
$= -96.85887$
$f(2) = 2^3 +sin(2) -98 $
$=-90.9092$
.
.
.
$f(5) = 5^3 +sin(5) - 98 $
$= 26.9128442$
And here it's gone positive. Hence proved?
Am I on the right track?
Comment: Yes, your way is correct, but overy complex. Instead just evaluate the function at the interval edges: $0^3+\sin(3x)=0 < 98$ and $10^3+\sin(30)\geq 1000-1 = 999$. Thus by the intermediate value theorem a solution must exists in $(0,10)$.
Comment: Yes, on the right track. To complete the proof, you just have to tell us which theorem is being used here.
Comment: $97\le 98-sin(3x)\le 99$.  Let $x_1=\sqrt[3] {97}$ and  $x_2=\sqrt[3] {99}$.  $x_1\le x\le x_2$ will give the $x$ you want.
Comment: "So I let $f(x)=x^3+\sin(3x)=98$." The $=98$ is not part of the definition of $f$ and shouldn't be there.
Comment: Also for calculating the solution: Note that we need to have $x^3-1\leq 98 \leq x^3+1$. Thus $x$ must be so that $97\leq x^3\leq 99$. Thus by taking the third root we get $4.594<x<4.627$. By evaluating the $\sin(3x)$ at these bounds we can refine the bounds to $x^3 +0.937\leq 98\leq x^3 + 0.968$. Thus we get $97.032\leq x^3\leq 97.063$ and thus
$$ 4.595\leq x \leq 4.596 $$
We can continue like that to quickly approximate the solution.
Answer: Yes, but you can easily prove more.
If
$f(x)
=x^3+\sin(ax)-b
$
where $b > 0$
($b=98$ here),
since
$-1 \le \sin(ax) \le 1$
so
$x^3-1-b
\le f(x)
\le x^3+1-b
$.
Therefore
if
$x \lt \sqrt[3]{b-1}
$
then
$f(x) < 0$
and if
$x \gt \sqrt[3]{b+1}
$
then
$f(x) < 0$.
Therefore $f(x)$
has a root between these two values.
If your case,
these are
$\sqrt[3]{b-1}
\approx 4.59
$
and
$\sqrt[3]{b-1}
\approx 4.63
$.


My Aquia Dev Desktop is insanely slow. What could be the problem?

Question: I'm running Drupal 7 with the latest version of Aquia Dev Desktop and the site is REALLY slow on local host. I mean something like one minute to load a node  to edit it, and three minutes to load the modules page.
I tried the Boost module, and I have all the performance settings maxed out.   What could the problem be (a port, the PHP version, too many installs)? I have about seven sites in there.
The site on the live server (in the USA) is faster and I'm connecting from Thailand; that is twice as fast as localhost.
Comment: There are literally dozens of things that could be responsible for a site being slow, please provide some more details about what's causing the problem and flag for reopening. If you think it's not your own configuration but rather an inherent problem with the software you're using, please report this to them as a bug. Many thanks
Answer: I experienced the same thing when I tried using the Acquia Dev Desktop.
I now use c9.io (clould 9) and do all my development in the cloud <code>:)</code>
Here is a nice overview video of the IDE.
Comment: I looked at your profile, form lower mainland? I'm from Vancouver, send me a message from my site? I'll try your suggestion. Cheers!


How to add a sound to your program?

Question: I am trying to add sound in program. I have no experience how to add sound in program.
I am trying this but this code giving me exception "null". I don't know what argument I have to pass in playSound function. So help me please.
import java.io.InputStream;
import sun.audio.*; //import the sun.audio package
import java.io.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class Main {

    public Main() {

    }

    public static void main(String[] args) {
        System.out.println("hello there");
        playSound("Hi there");

    }

    public static synchronized void playSound(final String url) {
        new Thread(new Runnable() { // the wrapper thread is unnecessary, unless
                                    // it blocks on the Clip finishing, see
                                    // comments
                    public void run() {
                        try {
                            Clip clip = AudioSystem.getClip();
                            AudioInputStream inputStream = AudioSystem
                                    .getAudioInputStream(Main.class
                                            .getResourceAsStream("pacman_chomp.wav"
                                                    + url));
                            clip.open(inputStream);
                            clip.start();
                        } catch (Exception e) {
                            System.err.println(e.getMessage());
                        }
                    }
                }).start();
    }

}

Comment: You have to give the path to a .wav file or some other sound file.
Comment: @ console...
1st it print "Hello there" in second line "null"
Answer: It might be giving you a null exception because it can't find the file. At the moment it is looking for a file called:

"pacman_chomp.wavHi there"

Because the value of url is being set to "Hi there" and you are constructing it like this:
AudioInputStream inputStream = AudioSystem
                                    .getAudioInputStream(Main.class
                                            .getResourceAsStream("pacman_chomp.wav"
                                                    + url));

I presume you want the file ""pacman_chomp.wav"? In which case remove the "+ url".
Comment: Well Chris thanks for answering.
you are right the file name is pacman_chomp.wave but it's strill not working :(
Comment: Is it in the right place? It will be looking for the file in the same location as your "Main.class" file
Answer: Since you said your playSound method didn't work, here's a sound class I coded.
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class AePlayWave extends Thread {

    protected static final boolean DEBUG = false;

    protected InputStream inputStream;

    public AePlayWave(InputStream inputStream) {
        this.inputStream = inputStream;
        if (DEBUG) System.out.println("AePlayWave constructor");
    }

    @Override
    public void run() {
        if (DEBUG) System.out.println("AePlayWave running");

        AudioInputStream audioInputStream = verifyInputStream();
        if (audioInputStream == null) {
            return;
        }

        AudioFormat format = audioInputStream.getFormat();
        SourceDataLine audioLine = openInputStream(format);

        if (DEBUG) System.out.println(audioLine.getLineInfo());

        if (audioLine != null) {
            audioLine.start();
            playInputStream(audioInputStream, audioLine);
        }
    }

    protected AudioInputStream verifyInputStream() {
        if (DEBUG) System.out.println("AePlayWave verifyInputStream");
        AudioInputStream audioInputStream = null;
        try {
            audioInputStream = AudioSystem.getAudioInputStream(inputStream);
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return audioInputStream;
    }

    protected SourceDataLine openInputStream(AudioFormat format) {
        if (DEBUG) System.out.println("AePlayWave openInputStream");
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
        SourceDataLine audioLine = null;
        if (DEBUG) System.out.println("AePlayWave openInputStream try");
        try {
            audioLine = (SourceDataLine) AudioSystem.getLine(info);
            if (DEBUG) System.out.println("AePlayWave openInputStream getLine");
            audioLine.open(format);
            if (DEBUG) System.out.println("AePlayWave openInputStream open");
        } catch (LineUnavailableException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return audioLine;
    }

    protected void playInputStream(AudioInputStream audioInputStream,
            SourceDataLine audioLine) {
        if (DEBUG) System.out.println("AePlayWave playInputStream");
        int externalBufferSize = (int) audioInputStream.getFrameLength() * 4;
        if (DEBUG) System.out.println("AePlayWave playInputStream externalBufferSize: "
                + externalBufferSize);
        int nBytesRead = 0;
        byte[] abData = new byte[externalBufferSize];

        try {
            while (nBytesRead != -1) {
                nBytesRead = audioInputStream.read(abData, 0, abData.length);
                if (nBytesRead >= 0) {
                    if (DEBUG) System.out.println("Bytes read: " + nBytesRead);
                    audioLine.write(abData, 0, nBytesRead);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            audioLine.drain();
            audioLine.close();
        }
    }
}

And here's how it's called:
InputStream inputStream = getClass().getResourceAsStream("alarm-clock-1.wav");
AePlayWave playWave = new AePlayWave(inputStream);
playWave.run();

Comment: I am getting error in this line
InputStream inputStream = getClass().getResourceAsStream("alarm-clock-1.wav");
Error = "Cannot make a static reference to a non-static method getClass() from the type Object".
And thanks for Answering
Answer: playSound("pacman_chomp.wav");

public static synchronized void playSound(final String url) {
    new Thread(new Runnable() { // the wrapper thread is unnecessary, unless
                                // it blocks on the Clip finishing, see
                                // comments
                public void run() {
                    try {
                        Clip clip = AudioSystem.getClip();
                        AudioInputStream inputStream = AudioSystem
                                .getAudioInputStream(Main.class
                                        .getResourceAsStream(url));
                        clip.open(inputStream);
                        clip.start();
                    } catch (Exception e) {
                        System.err.println(e.getMessage());
                    }
                }
            }).start();
}

a: as stated above it looks for "pacman_chomp.wavHi there"
b: hardcoding is not recommended here. you lose the ability to reuse the code. as an example, you can't do this if you hardcode in the playSound method:
    playSound("pacman_chomp.wav");
    playSound("pacman_dies.wav");

in addition, the method name "playSound" becomes poorly named (in hardcoded file), because it will always play the pacman_chomp file (if pointed correctly).
c: what's the purpose of "Hi there" anyways?
Comment: I am just testing how to add Sound in program. i don't know what's this url argument do so i just send "Hi there" string.
If i succeed then i will add sound in my main program. Hope so u got me...Sorry for bad English .
Comment: the url is the path to the file. so if the file is in the same directory as the class, you can type "pacman_chop.wav" as the argument.
Comment: I did this but this thing also not working...
Comment: three things:
one: did you replace.getResourceAsStream("pacman_chomp.wav"
                                                    + url)); with
 .getResourceAsStream(url));?
two:are the files in the same path? if not, you need to provide a path to the file.
three: did you spell the filename correctly?

if it doesn't work after this:
put a breakpoint here: clip.open(inputStream); if inputStream is null or it doesnt hit this breakpoint: then there is something wrong with: getAudioInputStream or getResourceAsStream
Answer: Clip dont allow long audio files. See these classes which are from my game engine.
SoundState
WavPlayer
WavSound
Then use this code.
// First load the sound
WavSound snd = WavPlayer.loadSound("pacman_chomp.wav");
// play it then
snd.play();

You may use these classes for free. Hope they helps.

How to add a sound to your program?


Computing the difference between first and last values in a rolling window

Question: I am using the Pandas rolling window tool on a one-column dataframe whose index is in datetime form.
I would like to compute, for each window, the difference between the first value and the last value of said window. How do I refer to the relative index when giving a lambda function? (in the brackets below)
df2 = df.rolling('3s').apply(...)

Answer: IIUC:
In [93]: df = pd.DataFrame(np.random.randint(10,size=(9, 3)))

In [94]: df
Out[94]:
   0  1  2
0  7  4  5
1  9  9  3
2  1  7  6
3  0  9  2
4  2  3  7
5  6  7  1
6  1  0  1
7  8  4  7
8  0  0  9

In [95]: df.rolling(window=3).apply(lambda x: x[0]-x[-1])
Out[95]:
     0    1    2
0  NaN  NaN  NaN
1  NaN  NaN  NaN
2  6.0 -3.0 -1.0
3  9.0  0.0  1.0
4 -1.0  4.0 -1.0
5 -6.0  2.0  1.0
6  1.0  3.0  6.0
7 -2.0  3.0 -6.0
8  1.0  0.0 -8.0

Comment: Is there a way to do this without apply? apply is insanely slow
Comment: I was getting `KeyError: -1` with pandas 1.5.2. Using `iloc` fixed the issue: `df.rolling(window=3).apply(lambda x: x.iloc[0]-x.iloc[-1])`.
Comment: and what if you wanted the first and last row of each window as well? tried the apply approach, it works but simply does not scale well.


Eigenvalues and eigenvectors of a linear transformation that transposes a matrix

Question: a) Consider the transformation $T$ in the space $M^{2\times2}$ of $2\times2$ matrices, $T(A)=A^{\top}$. Find all its eigenvalues and eigenvectors. Is it possible to diagonalize this transformation?
b) Can you do the same problem but in the space of $n\times n$ matrices?
Since all linear transformation can be represented as a matrix, there should be a matrix that multiplies a $2 \times 2$ matrix that turns it into its transpose. But based on what I've read so far, there is no such matrix that exist. I might be misunderstanding this question, but if we can't find this matrix, how are we suppose to find its eigenvalues and eigenvectors?
Comment: Note that the space of $2\times2$ matrices is $4$-dimensional, so the matrix representing a transformation in the space of $2\times2$ matrices will be $4\times4$
Comment: You've just got to think about how you would represent a $2\times2$ matrix as a column vector; I guess it would live in $\mathbb R^4$. Since the transpose swaps two elements in a matrix, the corresponding transformation of $\mathbb R^4$ would do the same. The $4\times4$ matrices that do this are called [permutation matrices](https://en.wikipedia.org/wiki/Permutation_matrix). If you study those, I think you'll find your answer.
Comment: If $(A+B)^t=A^t+B^t$, and $(cA)^t=cA^t$, then it's linear, right, William?
Comment: You have a map T from a vector space to itself. You have a definition of what it means for that map to be linear. You apply that definition to that map, using what you know about the transpose. Then, you tell me whether or not it's a linear transformation on that vector space.
Comment: You have only read the first half of that top answer. Please go back and read the second half, William.
Comment: oh yes . a 4 by 4 matrix would be possible. I assumed it had to be a 2 by 2 matrix which would be impossible
Comment: Even if you couldn't find the matrix, you could still find all the solutions of $A^t=\lambda A$, couldn't you, William?
Comment: is the transformation that transpose matrix actually a liner map? there are many threads here saying it is not linear?
Comment: @GerryMyerson is the transpose transformation for a specific matrix linear? I believe the operation that transposes all matrix is not a linear transformation, however it is linear if we fix a specific matrix to transpose. But even without any matrix, we know the diagonals are unchanged so the diagonal entries will be the eigenvalues
Comment: @GerryMyerson https://math.stackexchange.com/questions/1143614/is-matrix-transpose-a-linear-transformation  The top answer here is saying that matrix transpose is not a linear transformation
Comment: What is the eigenvalue for $\pmatrix{0&1\\-1&0}$ under the transpose transformation?
Comment: So, William, where do we stand now?
Comment: @GerryMyerson this problem is solved now. I set T^2=I which means the only eigenvalues are -1,1 where 1 corresponds to the symmetric matrices, so its multiplicity is n and -1 is for the anti symmetric matrices with multiplicity n(n-1) Thank you for your help.
Comment: I think you're undercounting the symmetric matrices (and overcounting the antisymmetric). But let me encourage you to write up what you have found, and to post it as an answer.
Comment: For example, the symmetric $2\times2$ matrices form a vector space of dimension three, the antisymmetric, one, whereas your formulas give two for both.
Answer: For solving this problem, my suggestion is that you use isomorphism first. Since the domain is $M^{2\times2}$, the basis should be $\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} 0 & 1\\ 0 & 0 \end{bmatrix} \begin{bmatrix} 0 & 0\\ 1 & 0 \end{bmatrix} \begin{bmatrix} 0 & 0\\ 0 & 1 \end{bmatrix}$, which I named as $\mathcal{B}=\{v_1,v_2,v_3,v_4\}$ orderly.
Then we hope $Tv_1=v_1,\;Tv_2=v_3,\;Tv_3=v_2,\;Tv_4=v_4$.
Thus $[T]_{\mathcal{B}} =\begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\\end{bmatrix}$. Then $\det([T]_\mathcal{B}-\lambda I)=(\lambda-1)^3(\lambda+1)$.
Then compute the $\text{Ker}(T-\lambda I)$.
For $\lambda = 1$, $\text{Ker}(T-I)=\text{span}\left\{ \begin{bmatrix} 1 \\ 0 \\ 0 \\ 0 \end{bmatrix}, \begin{bmatrix} 0 \\ 0 \\ 0 \\ 1 \end{bmatrix}, \begin{bmatrix} 0 \\ 1 \\ 1 \\ 0 \end{bmatrix} \right\}$.
For $\lambda = -1$, $\text{Ker}(T+I)=\text{span}\left\{ \begin{bmatrix} 0 \\ 1 \\ -1 \\ 0 \end{bmatrix}\right\}$.
By written in this form, you can diagonalize it.
When problem goes to $M^{n\times n}$, you just write a basis in the same way and abstract it to a basis $\mathcal{B}={v_1,\dots,v_{n^2}}$, better in a relatively symmetric way (i.e. swap $v_i$ and $v_{n^2+1-i}$) so that your $[T]_{\mathcal{B}}$. In this way, you can compute the characteristic polynomial easier.
Answer: When you're treating matrices as objects in a vector space, instead of as representations of a transformation, then it's often useful to think of them as vectors with components.
A 2x2 matrix has four components, a 3x3 matrix has 9 components, a 4x4 matrix has 16 components, and so on.
Every 2x2 matrix can be written uniquely as:
$$\begin{bmatrix}a & b \\ c & d\end{bmatrix} = a\begin{bmatrix}1 & 0 \\ 0 &0 \end{bmatrix} + b\begin{bmatrix}0 & 1 \\ 0 &0 \end{bmatrix} + c\begin{bmatrix}0 & 0 \\ 1 &0 \end{bmatrix}+d\begin{bmatrix}0 & 0 \\ 0 &1 \end{bmatrix}$$
In other words, these four matrices on the right hand side form a basis for the space.

Because we're treating these matrices as objects in a vector space, you are free to write them as vectors if you like.
$$\begin{bmatrix}a & b \\ c & d\end{bmatrix} \leadsto \begin{bmatrix}a \\ b\\ c\\d\end{bmatrix}$$
Written in this form, transposition is the transformation:
$$T : \begin{bmatrix}a \\ b\\ c\\d\end{bmatrix} \mapsto \begin{bmatrix}a \\ c\\ b\\d\end{bmatrix}$$
which you can write in matrix form as:
$$\underbrace{\begin{bmatrix}1 & 0 & 0 & 0\\ 0 & 0 & 1 & 0 \\ 0 & 1& 0 & 0\\ 0&0&0&1\end{bmatrix}}_T\begin{bmatrix}a \\ b\\ c\\d\end{bmatrix} = \begin{bmatrix}a \\ c\\ b\\d\end{bmatrix}$$
and you can do the rest.

Of course, you can also get some intuition about transposition using intuition about eigenvectors, without relying on specific components.
If a linear transformation scales an object by a factor of $\lambda\neq 0$, then that object is an eigenvector with eigenvalue $\lambda$. (As a special case, if a linear transformation has no effect on an object, it's an eigenvector with eigenvalue $\lambda=1$.)
Let's exclude the zero matrix from consideration in everything that follows.  There are three kinds of matrices that are unaffected by transposition $T$:
$$\begin{bmatrix}a & 0\\ 0 & 0\end{bmatrix}, \begin{bmatrix}0 & 0\\ 0 & b\end{bmatrix},
\begin{bmatrix}0 & c\\ c & 0\end{bmatrix}$$
As a result, these are eigenvectors of $T$, and they all have eigenvalue 1.  The linear combinations of these matrices form a three dimensional space of matrices that  are all eigenvectors with eigenvalue 1:
$$\begin{bmatrix}a & c \\ c & d\end{bmatrix}\qquad \forall a, b, c$$


A data analysis question on finding a model has a strong linear relationship but also a model that will be useful for prediction and inference.

Question: Suppose I have a response (dependent) variable $Y$
and 15 predictor (indepentent) variables $X_1, X_2, ..., X_{15}$.
I have the 30 data measurements for both the response vaiable and each predictor variables.
Which sample space $n=30$
$\mathbf{The~question~is}$:
How can I find a model exhibiting a strongest simple linear relationship
bettween the response (dependent) variable and one of 15 predictor (indepentent) variables,
and this model need to be useful for prediction and inference (new datas).
$\mathbf{My~Thought}$:
I can find a strongest simple linear relationship bettween the response (dependent) variable and one of 15 predictor (indepentent) variables
maybe by Doing the F statistic tests for all 15 predictor variables to see if there exists significant linear relationship,
and Find the $R^2$ for all predictor variables to see how much variation the regression line explains.
(the closer for $R^2$ to 1, the better the model is doing.)
$\mathbf{Problems}$:
Right now I don't know are those enough for finding a model exhibiting a strongest simple linear relationship
bettween the response (dependent) variable and one of 15 predictor (indepentent) variables ??
Also, I don't know what should I do to make sure this model is useful for prediction and inference (new datas) ??
Answer: First, built up all 15 models with the responce variable $Y$.
Then, find out the $R^2$ and also do the F-test for all 15 models to see weather each model is significant.
Then, find out outliers and leverages for each the 15 models, and find out if the leverages
or outliers are needed to remove from each the models.
Then, look into the standard residuals plots, fitted value plots, and qq plots for each 15 models to determine weather each model is violate the 4 assumption for simple linear regression. (e.g. if there is a fanning pattern, then that is means the model violates the constant variance assumption; and if there is a curvy pattern, then that is means the model violates the assumption of normality)  Last,
Then, do a transformation for the model that violate the constant variance assumption and assumption of normality.
Last, check which simple linear regression model has the highest $R^2$.
Also, find the confidence interval and the prediction interval and indicate that this model is useful for prediction and inference.


Prepending a string to a Smarty variable

Question: I'm looking for a way to prepend a string to a Smarty variable. I have a dynamic form having element-names like input-1 (where 1 is the id of the setting/field).
I've tried to do this with {capture}{/capture} but this only seems to work the first time (as the fields are displayed by a loop).
Is there an opposite function from |cat:'text' for Smarty, or do I have to:

Create my own modifier
Rename inputs
Comment: Maybe I misunderstood but wouldn't it be that simple? `{'input-'|cat:$id}`
Answer: I'm not sure I understand what you're trying to achieve, but there is an alternative syntax to cat, using backticks (and much more elegant and clear imho):
Using cat:
{"my string"|cat:$my_var|cat:"other string"|cat:$other_var}

The same, using bacticks:
{"my string `$my_var` other string `$other_var`"}

Using backticks, you can easily place your variables anywhere inside the string:
{"input-`$id`"}

Answer: Do you really need it in a variable? I usually do these things like this:
<input name="input-{$id}" type="..." />

If you need it in a variable you can use {assign}:
{assign var="name" value="input-$id"}
<input name="{$name}" type="..." />


analogue of Fourier transform where i is replaced by $sqrt{i}$

Question: For some reason complicated to explain, I am interested in the operator $T$ which to some test function $\Phi$ associates $$T\Phi(x)=\int_\mathbb{R} e^{jxw}\Phi(v)dv$$
where $j=(1+\imath)/\sqrt{2}$. Has anyone seen such a transform? Or is there a general class of transforms from which it is a particular case?
Comment: It's a slice of the bilateral Laplace transform, isn't it?
Answer: Well,
$$
T\Phi(x)=\mathcal F\Phi\Bigl(\frac{j}{i}\,cx\Bigr).
$$


Times when you want $(\cdot)^2$ and not $|\cdot|^2$ when porting from $\mathbb{R}$ to $\mathbb{C}$

Question: Over $\mathbb{R}$,  the square, $(\cdot)^2$, and usual square-norm, $|\cdot|^2$, functions agree for all inputs and are occasionally used interchangeably. For instance, when computing the variance of some data $\{x_1,\cdots,x_n\}$, $n>1$, with mean $\mu$, I have only ever seen the formula given as
$$
\sigma^2 = \frac{1}{n-1}\sum_{i=1}^{n}(x_i-\mu)^2;
$$it should be $|x_i-\mu|^2$ so that even if the data are complex, the variance is real and non-negative.
However, I am interested in instances when $(\cdot)^2$ and not $|\cdot|^2$ is the correct generalization. A clear parallel in linear algebra is the adjugate matrix: given a square matrix $A$, its adjugate is the transpose of the cofactor matrix $C$, but not the conjugate-transpose, even when the entries of the matrix are complex. That is, we have $\text{adj}(A)=C^T$, not $\text{adj}(A)=C^*$. Off the top of my head, I can't think of any scenarios where this distinction is important, but I am curious if the community can name any.
Comment: Anything not concerning any inner product should serve as an example. For instances, polynomial functions in $\mathbb C$ are in the form of $z\mapsto\sum_kc_kz^k$, not $z\mapsto\sum_kc_k|z|^k$; the identity $\sin^2x+\cos^2x=1$ remains the same in $\mathbb C$, while $|\sin x|^2+|\cos x|^2=1$ is not correct because sine and cosine are unbounded in $\mathbb C$.
Comment: I know this is a meta-issue, but can you justify your sequence of edits?  As an outside observer, they seem to be used to bump the question rather than adding anything material.  Since we have a built-in tool (bounties) to increase visibility and participation, the edit sequence leaves me with a bad taste in my mouth.
Comment: @BrianMoehring I'm happy to bounty it, if needed. I admit some of the earlier ones are insubstantial, but the most recent one got rid of some extra fluff (the point is that the functions agree over $\mathbb{R}$ but not $\mathbb{C}$; the positive-definite bit is unnecessary). Looking at the meta site, it seems my behavior is seen as poor etiquette. I will try to be better in the future.
Comment: @user1551 Those are good examples, thanks! Series convergence is another example: something like $\ln(1+z^2)$ converges everywhere on the unit circle except at $\pm i$, but $\ln(1+|z|^2)$ converges nowhere on the unit circle. Another instance would be something like exponentiation by squaring: at each step you want to preserve the imaginary parts.
Answer: Posting an answer (CW) so the question has one; feel free to add more.

Anything not concerning an inner product, including polynomial and power-series. That is, they look like $z\mapsto \sum_k c_k z^k$, not $z\mapsto \sum_k c_k |z|^k$.
In particular, this affects convergence of series, as $z\to z^2$ will double the singularities at the boundary of the radius of convergence, but $z\to|z|^2$ will make the entire boundary divergent.
$\sin^2(x)+\cos^2(x)=1$ holds identically over $\mathbb{C}$ but $|\sin(x)|^2+|\cos(x)|^2=1$ doesn't.
Exponentiation by squaring works by, wanting to compute $x^n$ for integer $n$, using the base-$2$ representation of $n$ and using successive squaring and multiplication to compute integer powers. However, if $x$ is complex, clearly $x^2$ might have an imaginary part on squaring, whereas $|x|^2$ does not; thus, $(\cdot)^2$ and not $|\cdot|^2$ is the correct computation at each step.


Is there any relation between the definition of metric as defined in differential geometry and one in metric spaces?

Question: If one opens a book on metric spaces, one is greeted with the definition of metric as a function of pairs of elements on a set to the real line satisfying a few properties. However, in Tristan Needham's Visual Differential Geometry, it's given that a metric gives the relation between separations on surfaces and its mapped points in the chart.
Is there any relation between these two ideas of the same name?
Comment: Associated with a Riemannian metric on a manifold is a distance function. The distance function defines a metric space structure on the manifold.
Comment: "The relation between separations on the surfaces"?
Answer: The two uses of "metric", on a space $M$ while somewhat related should not be confused; while both are somehow related to lengths/distances, they have different meanings.
The "metric" in "metric space" is a  function $d:M\times M\to[0,\infty)$ satisfying 3 properties. However, the use in Riemannian geometry assumes first $M$ is a smooth manifold, and that you have a certain special $(0,2)$-tensor field $g$ on $M$; it just happens that we call this a metric tensor field. The main difference is that the metric tensor field is by its very definition an "infinitesimal description of $M$" of lengths and angles, meaning at each point $x\in M$, you have an inner product (a $(0,2)$ tensor) $g_x$ on the tangent space $T_xM$. On the other hand,
a distance function is by its definition a "global" property, meaning it deals directly with points of $M$.
We have the following theorem. Given a connected (hence smooth-arcwise connected) Riemannian manifold $(M,g)$, we can define the function $d:M\times M\to [0,\infty)$ as
\begin{align}
d(x,y)&:=\inf_{\gamma}\,(\text{length}(\gamma)):=\inf_{\gamma}\int_a^b\sqrt{g_{\gamma(t)}(\dot{\gamma}(t),\dot{\gamma}(t))}\,dt,
\end{align}
where the infimum is taken over the set of all piecewise $C^{\infty}$ curves $\gamma:[a,b]\to M$ from $x$ to $y$. The statement of the theorem is then that $d$ is a distance function on $M$ (satisfies the three axioms of a "metric space"), and that the topology $M$ inherits as a metric space using $d$ is equal to the topology $M$ already has by virtue of being a smooth manifold. Proving $d$ is a distance function isn't so hard; proving it gives the same topology is slightly harder.
There are also further interesting theorems, such as Hopf-Rinow, which says (among other things) that two notions of "completeness" are equivalent: Cauchy-completeness in the sense of metric spaces is equivalent to geodesic completeness (every geodesic having the whole of $\Bbb{R}$ as the domain).
Comment: @Buraian google the definition smooth manifold. The topology in its definition  has nothing to do with the introduction of a metric tensor
Comment: How do you mean by topology? Does the differential geometry metric define a topology?


is jquery .one() computing checks every event?

Question: And therefore adding a bit of computing load?
For those of you unfamiliar with the .one() jquery function it basically triggers an event just once. Such as if you wanted to add a div on the first time a page is scrolled.
To bring background to the matter, I came across this question:
How to alert when scroll page only first time using javascript?
I have been in projects where I had to add hundreds or thousands of events, so for me it's always very important to optimize computing power, plus, I am a curious person so I just need to know.
One of the answers where the guy uses vanilla javascript is basically an endless loop where you switch a boolean on the first instance and basically have to continually enter the function to see if it has been already triggered.
var xxx;

$(window).scroll(function () {

if(!xxx)
{
    xxx = true;
    var div = $("#myDiv");
    alert(div.height());
}
  });

My idea is that jquery being already heavy on the page it probably just performs this same action under the hood, but I would like to be completely certain as for my future implementations.
Answer: No. jQuery's .one works similarly to, for example:

calling addEventListener, and then, in the callback, calling removeEventListener
calling addEventListener with { once: true } in the options object
in jQuery, like calling .on, and then, in the callback, calling .off

Once the listener runs once, it's de-attached; no further logic takes place when the event occurs in the future, because the listener is no longer connected at all.
So .one is very light on computing resources, even if you add lots and lots of .ones.
You can see the source code of one here:
    if (one === 1) {
        origFn = fn;
        fn = function (event) {

            // Can use an empty set, since event contains the info
            jQuery().off(event); // <-------------------------------------------------
            return origFn.apply(this, arguments);
        };

        // Use same guid so caller can remove using origFn
        fn.guid = origFn.guid || (origFn.guid = jQuery.guid++);
    }

    return elem.each(function () {
        jQuery.event.add(this, types, fn, data, selector);
    });

where jQuery() returns a jQuery collection containing elements matching the current selector. When one is called, the callback is wrapped in another that calls .off as soon as the function is executed.
The sample code in the answer you linked to is quite inefficient, and should not be used, especially for scroll events, which fire very frequently.
Comment: Perfect answer, and I am glad it is as optimized as it can get too! Thanks buddy


Como posso persistir dados usando ArrayList?

Question: Preciso que minha estrutura de dados ArrayList seja visível em mais de um metodo da minha classe Produtos.
Estou trabalhando da seguinte maneira:
package estoque;

import java.awt.Component;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.util.ArrayList;

public class produtos {

   public static void cadastro() {
      ArrayList<String> Produto = new ArrayList<>();
      JTextField field1 = new JTextField();
      JTextField field2 = new JTextField();
      JTextField field3 = new JTextField();
      Object[] message = {
         "Código:", field1,
         "Descrição:", field2,
         "Quantidade:", field3};
      Component parent = null;
      int option = JOptionPane.showConfirmDialog(parent, message, "Cadastro de Produtos", JOptionPane.OK_CANCEL_OPTION);
      if (option == JOptionPane.OK_OPTION) {
         String codigo = field1.getText();
         String descricao = field2.getText();
         String quantidade = field3.getText();

         if (codigo.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Por favor, preencha o campo Código!");
            cadastro();
         } else if (descricao.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Por favor, preencha o campo Descrição!");
            cadastro();
         } else if (quantidade.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Por favor, preencha o campo Quantidade!");
            cadastro();
         } else {
            Produto.add(codigo + ' ' + descricao + ' ' + quantidade);
            JOptionPane.showMessageDialog(null, "Produto cadastrado com sucesso!");
            System.out.println(Produto);
            Estoque.menu();
         }
      }
   }

   public static void listar() {
      JOptionPane.showMessageDialog(null, " Código - Descrição - Produto\n", "Lista de Produtos", 1);
   }

}

Da opção menu eu acesso Cadastro e realizo o cadastro de um produto que será armazenado em  ArrayList<String> Produto = new ArrayList<>();
Depois eu volto para outra classe chamada Menu e seleciono a Opção Listar, que acessa o método listar();
Nesse método o ArrayList não é global, portando eu não consigo acesso a ele, como eu posso torna-lo global para realizar a leitura neste método ?
Comment: Agora que reparei que é estatico. Basta adicionar dessa forma: `private static ArrayList Produto = new ArrayList<>();` assim vira um parâmetro estático de classe, e não de instância.
Comment: Acredito que esta pergunta não será util para ninguém visto que o meu problema foi apenas uma falha na semântica em esquecer o uso de static
Comment: Coloque-o como atributo da classe: `private ArrayList Produto = new ArrayList<>();`
Comment: Ai o ArrayList Produto não fica visivel no metodo, como eu chamaria ele ?
Comment: Era isso mesmo! coloca como resposta e adiciona uma explicação, para que eu possa marca-la como correta, tinha me esquecido de static, meio que tenho uma confusão em java quando se trata disso!
Comment: Veja [esta pergunta](http://pt.stackoverflow.com/q/93048/18246).
Answer: Você pode definir o ArrayList<String> como um atributo da classe, fazendo com que o escopo da classe inteiro tenha acesso ao valor, assim você poderá usar e alterar em qualquer método da mesma:
public class Produtos {
  private List<String> produtos;

  public void cadastro() {
    produtos = new ArrayList<String>();
    produtos.add("seu produto");
  }

  public void listar() {
    //Os produtos estarão disponíveis aqui também, caso a lista esteja inicializada
    if (produtos != null) {
      for (String prod : produtos) {
        System.out.println(prod);
      }
    }
  }

}


Does the product $\sigma$-algebra coincides with the Borel $\sigma$-algebra for compact metric spaces?

Question: Suppose $E_{0}$ is a topological space, with topology $\tau_{0}$. Let $\mathcal{F}_{0}$ be its Borel $\sigma$-algebra, i.e. the $\sigma$-algebra generated by its open sets. Now, take $I$ a countable set and set $E := \prod_{i\in I}E_{0}$. We can equip $E$ with both its product topology $\tau$ and its product $\sigma$-algebra $\mathcal{F}$. It is a well-known result that if $E$ is metrizable (or metric) and separable, then the product $\sigma$-algebra $\mathcal{F}$ coincides with the Borel $\sigma$-algebra on $E$. In the theory of Gibbs measures, however, we usually take $E_{0}$ to be metric (or metrizable) and compact, not necessarily separable. However, I'm not sure that the product topology and the product $\sigma$-algebra, in this case, are compatible, i.e. if the product $\sigma$-algebra is the $\sigma$-algebra generated by the open sets of $E$ when it's equipped with its product topology. I think we need separability here, but some references do not explicitly assume $E_{0}$ separable.
Question: If $E_{0}$ is a compact metric space, is the product $\sigma$-algebra the $\sigma$-algebra generated by open sets of $E$ when it's equipped with the product topology?
Comment: *"to be metric (or metrizable) and compact, not necessarily separable"* A metrizable compact space is always separable.
Comment: how you define the product $\sigma$-algebra when $I$ is infinite? As the product $\sigma$-algebra generated by cylinders?
Comment: The usual construction as the smallest $\sigma$-algebra in which every projection map $\pi_{i}: E \to E_{i}$ is measurable. I believe that, at least when $I$ is countable, this is equivalent to the $\sigma$-algebra generated by cylinders.
Answer: In fact, I don't see a reason to worry, as all compact (or Lindelöf) metric (or metrisable) spaces are separable (just take a finite (or countable) subcover of the cover of all $\frac{1}{n}$-balls, for every $n$, and collect the centres used in all these subcovers to get a countable dense subset of the space).
So compact is more than enough to apply your result on separable metric spaces.
Comment: Oh, it was so easy! Thanks a lot for enlightening me!


why same msdn C# sample program output is not same as mine?

Question: this is a beginner type question, and I am sorry for my poor English.
here is the program:
using System;
public class BoolTest
{
    static void Main()
    {
        Console.Write("Enter a character: ");
        char c = (char)Console.Read();
        if (Char.IsLetter(c))
        {
            if (Char.IsLower(c))
            {
                Console.WriteLine("The character is lowercase.");
            }
            else
            {
                Console.WriteLine("The character is uppercase.");
            }
        }
        else
        {
            Console.WriteLine("Not an alphabetic character.");
        }
    }
}

MSDN output is:
Enter a character: X
The character is uppercase.
Additional sample runs might look as follow:

Enter a character: x
The character is lowercase.
Enter a character: 2
The character is not an alphabetic character.

my output doesn't say anything for this version of code. If I added a while(1==1) line before the if statement, I take three line output like:

Enter a character: X
The character is uppercase.
The character is not an alphabetic character.
The character is not an alphabetic character.
Enter a character: x
The character is lowercase.
The character is not an alphabetic character.
The character is not an alphabetic character.
Enter a character: 2
The character is not an alphabetic character.
The character is not an alphabetic character.
The character is not an alphabetic character.

I tried Console.ReadLine() end of the else statement but does not work. Also I tested comment the else blocks with while (1==1), I get only 1 output line..
I am wondering why the output is including 3 lines for me for the same sample code ?
Comment: Are you pressing the `enter` button between characters?  If so that is actually two characters that are not alphabetic.
Comment: Is your project set up as a Console Application?
Comment: yes this created as a Console Application
Comment: thank you very much steve, that is my answer actually..
Answer: My first answer was wrong - Console.Read() blocks. You probably just missed the output when running the program from Visual Studio because the window closes immediately. Just append Console.ReadLine(); twice at the end of the program to keep the window open. The first Console.ReadLine(); will consume the return you pressed after the character, the second one will wait until you press return again and therefore keep the window open.
Or slightly modify the program to use Console.ReadKey() - use
var c = Console.ReadKey().KeyChar;

// Insert a line break to get the output on a new line.
Console.WriteLine();

and add a single Console.ReadLine(); at the end of the program. Console.ReadKey() will not block until you hit return and therefore there is no need to consume the new line with a second Console.ReadLine();.
Original answer
Console.Read() does not block and will immediately return -1 if no character is available. You could just insert
while (!Console.KeyAvailable) { }

right before
 char c = (char)Console.Read();

to wait until a character is available.
Comment: It would be preferable to just use `Console.ReadKey()` which blocks, instead of adding a spinwait.
Comment: I am wrong - it actually blocks until you hit enter. I have to reread the documentation.


Autocomplete textfield using tableview and array filter in swift

Question: So, I have a tableview , a textfield, and an array which contains some data. What i want to achieve is that whenever I start typing in the textfield, a filter() method should fire on my array containing the data and the tablview should return data matching to the characters I typed in the textfield.
For eg, if i type W it should give me result as "Walmart","Wally,"Wily" and so on. IF i type in "Sac" it should give "sacramento","satisfied" and so on. In short, an auto-complete textfield without using any external libraries at all.
I know this is simple , i have tried doing it but i am getting zero data.Also, i am new to swift. Please Help anybody :-)
Comment: I tried using filter on my array containing the data, and thereafter i reload my tableview. But, i get 0 elements. Could you please give me a short code snippet just as overview which i can refer to ?
Comment: This is library i had made for tableview you can refers its code for your project https://github.com/insideApple/VPAutoComplete
Comment: Thanks..But i figured out how to do it anyways yesterday ! But thank you for your help :-D @vp2698
Answer: Look at this link
for my case, Here is a solution with UISearchbar.I am getting an array of dictionary & perform the search
<code>//MARK:- search items & reload table
func filter(array : [[String : [MyModel]]], byString filterString : String) {
    let searchByNamesArray = array.filter { $0.values.contains { $0.contains { $0.nameString.lowercased().contains(filterString.lowercased())} } }
    //Assign searched array into arrayOfMerchants
    self.arrayOfItems = searchByNamesArray
    //Reload table with new Data
    self.merchantTableView.reloadData()
}
</code>
For Search bar code
<code>   func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        if !((searchBar.text?.isEmpty)!){
            filter(array: self.arrayOfItems, byString: searchBar.text!)
        }
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        if (searchBar.text?.isEmpty)!  //in case there is no text in Searchbar, reload all record
        {
            self.arrayOfItems = self.arrayOfRecordsHolding  //array of original record holder
            self.merchantTableView.reloadData()
        }
        else
        {
            self.arrayOfItems = self.arrayOfRecordsHolding
            filter(array: self.arrayOfMerchants, byString: searchBar.text!)
        }
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        //reload all data when cancel button pressed on searchbar
        self.arrayOfItems = self.arrayOfRecordsHolding
        searchBar.text = ""
        self.merchantTableView.reloadData()
        searchBar.resignFirstResponder()
    }
</code>
Comment: Could you please explain me this line ?  `let searchByNamesArray = array.filter { $0.values.contains { $0.contains { $0.nameString.lowercased().contains(filterString.lowercased())} } }`
Comment: MyModel has an intance 'nameString'. I am searching on the based of names.  $0.nameString.lowercased().contains(filterString.lowercased()) statment check whether 'nameString' conatins 'filterString'
Comment: Thanks For your solution..It Worked but i had to modify that $0 Variables to my object type , then it worked :-) Thanks @Gagan_iOS
Answer: LOl I am a noob and yet i m answering my own question. Here arrStoreNameFilteredData and arrStoreName are both arrays containing data of same object type. However, arrStoreNameFilteredData will contain the data that will be filtered out whenever the user will start typing a character in the textfield.
<code>         if textField.text?.isEmpty == true && string.isEmpty == true
        {
            textField.text = ""
            arrStoreNameFilteredData = arrStoreName
            tblData.reloadData()
        }
        else
        {
            tblData.isHidden = false

            let substring = (textField.text! as NSString).replacingCharacters(in: range, with: string)
            print("Substring : \(substring)")

            arrStoreNameFilteredData = arrStoreName.filter({ (store: Stores) -> Bool in
                return ((store.storeName?.lowercased())?.contains(substring.lowercased()))!
            })
            tblData.reloadData()

        }
</code>
the filter predicate doesn't work quite as good when you use it with "$0"..instead use an alias variable. Here, store is aa variable of object type Stores, which will then filter out the data as i type in each character.
<code>((store.storeName?.lowercased())?.contains(substring.lowercased()))!</code>
The above line is what made it work for me :-D. Thanks to all the people who replied to my post tho, without them i wouldn't have been able to post my own answer :-D.


Did I contradict this correctly?

Question: The question is as follows:
Let $A,B \subseteq \mathbb{R}^n$ be connected subsets of $\mathbb{R}^n$ with $A\cap B \neq \emptyset$. Prove $A\cup B$ is connected.
I haven't done contradiction proofs in quite some time, but I just want to correctly contradict this statement. Is this the correct contradiction statement:
$A,B \subseteq \mathbb{R}^n$ are separate subsets of $\mathbb{R}^n$ with $A \cup B = \emptyset$. Do I also have to contradict what I am trying to prove, or is the goal to still show that $A\cup B$ is connected, or is what I have done wrong?
Comment: Proof by contradiction generally involves assuming that the conclusion is false. In this case you would assume that $A \cup B$ are not connected and then hope to find a contradiction by seeing that invalidates the previous assumptions (e.g. That $A,B$ are not connected subsets or that $A \cap B$ is is empty, etc.).
Answer: An implication $(P \implies Q)$ is equivalent to $(\neg P \lor Q)$. Negating this statement will give $(P\land \neg Q)$. If $(P\land \neg Q)$ is false then its negation $(P\implies Q)$ is true.
You should therefore assume that $A,B\subseteq \mathbb{R}^{n}$ are connected subsets of $\mathbb{R}^{n}$ and their intersection is non-empty, as well as, $A \cup B$ is not connected.
Comment: This helps a lot, thank you! I gotta brush up on my skills in that area

Did I contradict this correctly?


How to add Search form/Advanced search form view to advanced forum pages?

Question: I found two things in Advanced forum.
1. Advanced forum provides the views, one of which is advanced forum search as shown in the following image, which provide the specific search on the forum.

2. But it is a separate link, and totally separate page, if it will be under the title of the advanced forum topic and on every forum discussion page, it will be very suitable for visitors. As shown in this image.

Now, how to add that advanced forum box and advanced option selection box provided in views under the forum title? I mean all on all the pages of forum except the first main page. Very Thanks.
Answer: You need to display the exposed filters in a block, and then display that block on single forum node pages.
Here's how to do that:

Edit the Forum Search view: /admin/structure/views/view/advanced_forum_search/edit.
Under "Exposed form" -> "Exposed form in block" choose "Yes".
Save the view.
Navigate to /admin/structure/block.
Enable the "Exposed form: advanced_forum_search-page" block, and show it for example in the "Content" area and only for "Forum topic" nodes. You can change this to your liking of course.

Users now can use this form from single forum nodes, and submitting it will take them to the search page.
Update
If you want to make this available in your templates and position it within other elements, you'll have to edit the template.php of your theme add a hook_preprocess_X() implementation.
Choice depends on the template you want to add the form to. For example:

hook_preprocess_node() - to make the form available in node.tpl.php
hook_preprocess_page() - to make the form available in page.tpl.php
hook_preprocess_html() - to make the form available in html.tpl.php

Here's the code:
function YOUR_THEME_preprocess_REPLACE_THIS(&$variables) {
  // Load the view and generate the search form.
  //
  // You can have any dynamic conditions here (e.g. limit to some content types
  // and so on).
  $view = views_get_view('advanced_forum_search');
  $view->set_display('page');
  $view->init_handlers();
  $form_state = array(
    'view' => $view,
    'display' => $view->display_handler->display,
    'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
    'method' => 'get',
    'rerender' => TRUE,
    'no_redirect' => TRUE,
  );
  $variables['search_form'] = drupal_build_form('views_exposed_form', $form_state);
}

Then in your .tpl.php file you would use this code to display the form:
<?php print render($search_form); ?>

Note that this way the visibility settings in admin won't be applied.
Comment: Hmmm...this is working...
Comment: Is there any way that search form can be placed besides the "New Topic" as shown in the image above? I understood that, this process is displaying the the search form view as a block and that block we are placing to the main-content. This way  it can be placed either to the top or bottom of main page.
Comment: That depends on your CSS. You could also make it available through a `hook_preprocess_whatever()` function, and then invoke it in the template. Will update my answer shortly.
Comment: Answer updated.
Comment: Well...I did not get few things, If you please can put light on that.  I am little familiar with preprocess. Why you want to implement in `page() or node() or html()` tpl file. why not to the `.tpl.php` file where the the code of `New topic` is there. Why not in `advanced-forum.naked.topic-list-outer-view.tpl.php` which has the code of `
` which prints `New topic`. And put that tpl file in theme's templates folder.


How to listen to children elements events in a directive?

Question: Since there is no template, what's the best way to listen to child elements event in a directive? Is it possible with HostListener? If not, is there any other way?
There's also this similar question: How to listen for child event from parent directive in Angular2, but the suggested approach does not solve my problem, as my directive and child element aren't in the same template (directive is on host).
Cheers!
Edit #1
This is how I'm currently doing it (there has to be a better way):
First injecting ElementRef into my directive:
constructor(private elView: ElementRef) {}

Then binding with jQuery (or plain JS):
$(this.elView.nativeElement)
.on('drag', '#childId', this.slide.bind(this))

Comment: I am not sure, but [this](http://orizens.com/wp/topics/angular-2-attribute-directive-creating-an-infinite-scroll-directive/) may be helpful
Answer: If the event you want to listen to is a native DOM event that bubbles, then you can just use @HostListener()
@HostListener('click', ['$event'])
handleClick(event) {
  // handle event
}

If they are outputs of child components, you can query them and subscribe to their outputs
@ContentChildren(ChildComponent) children:QueryList<ChildComponent>;

ngAfterContentInit() {
  this.children.toArray().forEach((item) => {
    item.someOutput.subscribe(...);
  });
}

or you can use the approach used in the answer you linked to in your question.
Comment: Thanks for your answer. `HostListener` is not bulletproof enough, as many events will not propagate due to `stopPropagation`. I was hoping for something that would allow me to bind directly to a child element.
Comment: That's what `@ContentChildren()` does or as also suggested in the other answer, a shared service.
Comment: Those two techniques would not work, as I'm not necessarily listen to events that have been initiated by components. I'm also (mostly) looking to listen to DOM events that were initiated by "normal" elements.
Comment: You can use `@ContentChildren(ChildComponent, {read: ElementRef}) children:QueryList;` and add event listeners like explained in http://stackoverflow.com/a/36116838/217408
Comment: Ah that's cool! But correct me if I'm wrong, `ContentChildren` only returns direct children. The events I want to listen to don't necessarily come from direct children. And I can't use `querySelector` for web workers.
Comment: If you want to utilize web workers, direct DOM access (`querySelector`) will cause issues. `ContentChildren` by default queries for children and descendants. You can pass `{descendants: false}` to only get direct children.
Comment: That's the thing though, I need to listen events on children that might be descendants and I also need it to be web worker safe.
Answer: You might consider to make your components communicate with each other via the service-class.
// service class
class Service {
  private someEventSource = new Subject();
  public someEvent = this.someEventSource.asObservable();

  public invokeAnEvent (data: string) {
    this.someEventSource.next(data);
  }
}

// parentComponent class
Service.someEvent.subscribe(data => {
  console.log(data);
});

// childComponent class
Service.invokeAnEvent('some data to pass');

From Angular documentation:
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
Comment: I think this would be overkill to listen to DOM events.
Answer: my solution to this problem is to add in the root component ngAfterContentChecked and there to select all my relevant elements and add the event. example:
  ngAfterContentChecked() {
    //console.log('MASTER ngAfterContentChecked')
    let rgx = /^[0-9,\.]+$/;
    let preventNonNumber = e => {
      //let v = (e.target as HTMLInputElement).value
      if (
        // Allow: Delete, Backspace, Tab, Escape, Enter
        [46, 8, 9, 27, 13].indexOf(e.keyCode) !== -1 ||
        (e.keyCode === 65 && e.ctrlKey === true) || // Allow: Ctrl+A
        (e.keyCode === 67 && e.ctrlKey === true) || // Allow: Ctrl+C
        (e.keyCode === 86 && e.ctrlKey === true) || // Allow: Ctrl+V
        (e.keyCode === 88 && e.ctrlKey === true) || // Allow: Ctrl+X
        (e.keyCode === 65 && e.metaKey === true) || // Cmd+A (Mac)
        (e.keyCode === 67 && e.metaKey === true) || // Cmd+C (Mac)
        (e.keyCode === 86 && e.metaKey === true) || // Cmd+V (Mac)
        (e.keyCode === 88 && e.metaKey === true) || // Cmd+X (Mac)
        (e.keyCode >= 35 && e.keyCode <= 39) // Home, End, Left, Right
      ) {
        return;  // let it happen, don't do anything
      }

      if (rgx.test(e['key']) == false) {
        e.preventDefault();
      }
    };
    let inputs = document.querySelectorAll('label-input[numberOnly] input, cbx-label-input[numberOnly] input')
    //console.log(inputs)
    inputs.forEach(i => (i as HTMLInputElement).onkeydown = preventNonNumber)
  }

NOTICE that the ngAfterContentChecked gets fired everytime you touch an input, so the selector runs everytime again, and also setting of the function, but since its a static function that your just override there isn't so much of a performance problem.


CSS Problems using vh and vw with FlexBox

Question: I want to build a panel with its main content (PAGE CONTENT) and a right sided stacked command button list with a title. The whole page must shrink or grow depending on the viewport (this will be used on a touch tablet, so landscape/portrait view needs to resize all elements proportionally).
Here is my HTML code snippet:

.panel-container {
  width: 100%;
  display: flex;
  flex-direction: row;
  padding: 0px;
  margin: 0px;
}

.panel-container-left {
  flex-grow: 1;
  flex-shrink: 0;
}

.panel-container-right {
  justify-self: flex-end;
}

.title {
    background-color: grey;
    color: white;
    margin: 5px;
    width: 25vw;
    height: 10vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.stacked {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100vh;
    overflow-y: scroll;
}

.button {
  background-color: blue;
  color: white;
  margin: 5px;
  width: 25vw;
  height: 10vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

    PAGE CONTENT

      Button Page

      TITLE

      Button 1

      Button 2

      Button 3

      Button 4

      Button 5

      Button 6

      Button 7

      Button 8

      Button 9

      Button 10

I can't make the right panel work properly. What I need is to keep all the buttons of same size, and same size of the panel title and panel button. If the height of the stacked buttons increase, I need then to scroll-y, but never go out of screen boundaries or loose its proportional size compared to the title and panel button.
Currently the panel buttons are shrinking to keep all 10 buttons in view, where I wanted an y-scroll with buttons at the same size of the panel button.
Comment: Can your create a snippet from your code right here in your question? That is the preferred way. External code sites should only be used if the required snippet functionality is not available on StackOverflow itself.
Comment: @connexo: Done. I forgot about this new feature...
Comment: It's not exactly new...
Comment: "The whole page must shrink or grow depending on the viewport (this will be used on a touch tablet, so landscape/portrait view needs to resize all elements proportionally)." Have a feeling you need to go media queries for this one..
Answer: I have documented all changes in the CSS. Hope this helps.

.panel-container {
  width: 100%;
  display: flex;
  /* flex-direction: row; NOT NECESSARY, IS THE DEFAULT */
  padding: 0px;
  margin: 0px;
}

/* NOT NECESSARY
.panel-container-left {
  flex-grow: 1;
  flex-shrink: 0;
}
*/

.panel-container-right {
  /* justify-self: flex-end; THIS DOES NOT EXIST */
}

.title {
    background-color: grey;
    color: white;
    margin: 5px;
    width: 25vw;
    height: 10vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.stacked {
    /* display: flex;
    flex-direction: column; */
    width: 100%;
    height: 80vh; /* TITLE IS 10VH + A BIT EXTRA FOR THE EFFECT */
    overflow-y: scroll;
}

.button {
  background-color: blue;
  color: white;
  margin: 5px;
  width: 25vw;
  height: 10vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

    PAGE CONTENT

      Button Page

      TITLE

      Button 1

      Button 2

      Button 3

      Button 4

      Button 5

      Button 6

      Button 7

      Button 8

      Button 9

      Button 10

Comment: What solved the issue is removing the `display: flex` from stacked... I can't understand why, as I'm opening a new `div section` as the parent section...
Comment: @Mendes Take a look here: https://stackoverflow.com/questions/14962468/flexbox-and-vertical-scroll-in-a-full-height-app-using-newer-flexbox-api
Answer: If I got this right, you should try to set max-width of right panel to 100vh and then add overflow-y to scroll.
.panel-container-right {
  max-height: 100vh;
  overflow-y: scroll;
}


Apache connections limit

Question: My hosting says that apache connections limit is 30. I don't whether its enough or not for an average site with 100 visitors per day. I want to know what are the things I should adapt for this limit while coding the site. Mostly I 'll use php sessions and little ajax . I want to know if there any precautions and recommended practices (if any) to avoid hitting this limit.
Thank you.
Comment: i wouldn't worry, it would be a very poor host that couldn't support a site of that size.
Answer: Since you will be using AJAX, I can't stress this enough...Do not long poll with Apache! It will hold your connections open and effectively perform a DOS(Denial of Service) on your own site.
Other than that, minimize the time it takes between when Apache receives a request to when it outputs and closes. The big blinking neon sign here is to use caching. Whether it is file based caching or something like Memcached or APC, this can drastically reduce the time Apache holds a connection open.
Answer: Taken by itself, the statement "apache connections limit is 30" doesn't actually mean much -- Apache configuration can be fairly involved and there are a lot of numbers/parameters. But if we assume that what this really means is 'MaxClients is 30', then what you need to know is that you have a limit of 30 simultaneous connections. However, connection 31 isn't rejected -- it should just be queued until there's a thread available to respond to the request.  There's a lot of specifics according to the config, etc, but I doubt you need to worry much.
Answer: This means there are 30 possible concurrent connections possible, if you have 100 visitors per day, it's very unlikely to have about a third at the same time.
As you are growing with your site I'd recommend you another server/hoster.
But as if you don't make long running persistent connections and high frequent AJAX call all the time, this should be enough.
Comment: Performing post and get requests by jquery in response to events(clicking,etc) count as persistent connections? because I heard that ajax calls will keep the connections open
Comment: No all requests in HTTP are short living. To keep persistent connections without getting a timeout you have to do more requests to keep it alive. With persistent I meant Streams for example
Answer: Connection limit is most probably simultaneous requests. So if you're only at the development stage, that is fine. But as for once it has launched, that is a different story. If your expected traffic is only about 100 visitors a day, then you will most probably be fine. I would however recommend to change your VPS host if it is anything over that, as if the server is turning away visitors, then it is not good for business.
But in all honesty you're better off developing locally for now to save your bandwidth for actual visitors, as from your description you don't seem to be using anything that requires a live site.

Apache connections limit


Reasons not to one-hot-encode categorical features

Question: I overheard a colleague discussing her strategy for using categorical features the other day, and she mentioned that instead of one-hot-encoding, she does something like this:
cat_string    cat_num
dog                 0
cat                 1
dog                 0
dog                 0
horse               2

Then she feeds cat_num (along with other inputs, potentially) into her model(s), without one-hot-encoding.
Now, there's obviously no issue if she wanted to assign these numbers to the categories and one-hot-encode - inputs created by OHEing cat_string versus cat_num would be identical, and she would actually be doing a sort of file compression if she dropped cat_string and just preserved that mapping - so nothing bad about that.
I could see not one-hot-encoding cat_num maybe being fine in two other cases
1) Where there is some natural ordering to the categories, e.g. low, medium, and high, and that ordering is reflected in the integer encoding applied, e.g. low: 0, medium: 1, and high: 2
2) Where cat_num has relatively low cardinality, no inherent ordering, and you're using a tree-based models - the idea there being that, with a well-specified tree, your tree might identify reasonable split points and effectively "learn" the one-hot-encoding, in a way. But that seems to be poor practice, when one-hot-encoding looks to be the best-practice way of doing things. OHEing, IMO and in general, makes things much easier to understand for these types of scenarios, and is trivial if you have enough computing power. I don't think this second approach would scale to high-cardinality categorical features with no inherent ordering, as learning "important" splits like cat_num <= 1000 seems like nonsense. Especially with a linear model, measuring the effect on the output from a "one-unit increase in cat_num", holding all else constant, is nonsense.
Can anyone else offer insight to this question?
Comment: You point towards practical arguments, but there also are efficiency issues with introducing variables for each value (i.e. a price is paid on the model stability front).
Answer: A note on terminology:
As far as I am aware (unfortunately, there are a lot of blogs written by people who overlook the subtle differences and thus mis-information spreads):
One hot encoding is exactly what you described, generating a map from each unique value in a string column to an integer
Dummying is making K new columns (in which K is the number of unique values), of which exactly one column per row must be one.
In the "dog, cat, horse" example, when using a decision tree, consider the following example. Perhaps your target variable is "has it ever meowed?". Clearly what you want your decision tree to do is be able to ask the question "is it a cat? (yes/no)".
If you one-hot encode, such that dog -> 0, cat-> 1, horse->2, the tree can't isolate all of the cats using one question, because decision trees always split using "is feature x greater than or less than X?"
If you're using logistic regression, it also can't assign higher probabilities of meowing to cats.
If you dummy, the tree can explicitly ask the question "the column which signifies cat greater than 0.5?", thus splitting your data into cats and not cats.
If you use logistic regression, your optimiser can learn that the coefficient related to this column should be positive.
Thus in my opinion, whenever you have categorical data which has no implicit ordinality, always dummy, never one-hot encode.
In the case where your data has high cardinality, this could cause problems, especially if the number of examples of each type is tiny, but this is a problem you can't really solve, you simply have too detailed information for the size of your training data and using it would lead to over-fitting.
Nonetheless, one way to mitigate this, is to do some manual clustering (or actual clustering), in which you make a synthetic column, which can take fewer values, and many of the unique values of the original column map to the same value in the new column (e.g. dog, cat, horse-> mammal,  pigeon, parrot , chicken -> bird). This makes it easier for the algorithm to learn, and if there's enough data, it can split further within each cluster.
Comment: I completely agree with your conclusion, but my understanding of one-hot encoding was the same as dummy encoding – creating *k* vectors with either 1 or 0, depending on whether the each row in each vector had that attribute. That definition seems to follow the intuitive understanding most would obtain when hearing "*one*-hot encoding." I'm not sure of a standard way of referring to creating that mapping besides "mapping," and disagree that that's what "one-hot-encoding" is.
Comment: @blacksite I've seen it referred to *mapping* the unique string values to integers as *label encoding*. I agree with you, *one-hot encoding* refers to the act of encoding the values into [one-hot vectors](https://en.wikipedia.org/wiki/One-hot).
Answer: I have never been happy with one hot encoding.
See:
https://roamanalytics.com/2016/10/28/are-categorical-variables-getting-lost-in-your-random-forests/
Recently, I have tried CatBoost (http://CatBoost.ai), Open Source from Yandex.
CatBoost uses Categorical variables directly.  (XGBoost uses one-hot-encoding under the covers.)
It seems to score better and faster than H2O's XGBoost, but training seems to take longer.
You might want to give it a try.


Array adding and set methods

Question: I am passing in an array to my class, I am constructing it and then I have the ability to transactions (replaces the array with new data) or add transactions (so if the array is first off size 10 then another 10 are added on to make it have 20 elements, the amount in the array may not always be 20 etc)
the code produces the correct results I am expecting when using the first two methods but not the add transaction method. which does not add another 10 elements as expected
does anyone know what issues they are in my coding?
I am fairly bound by the assignment structure in this one so working with the avaliable structures are ideal.
Transaction* tArray;
int nTransactions;

Analyser::Analyser(Transaction* transactions, int numTransactions)
{
    //contructs the array and the amount of transations
    tArray = transactions;
    nTransactions = numTransactions;
}

void Analyser::setTransactions(Transaction* transactions, int numTransactions)
{
    //set tArray to new set of transactions
    tArray = transactions;
}

void Analyser::addTransactions(Transaction* transactions, int numTransactions)
{

    Transaction* newT;
    newT = new Transaction[numTransactions + nTransactions];

    for(int i = 0; i<nTransactions; i++)
    {
        newT[i] = tArray[i];
    }
    for (int j = nTransactions; j<numTransactions + nTransactions; j++ )
    {
        newT[j] = transactions[j-nTransactions];
    }
    tArray = newT;
 }

Comment: In `setTransactions`, you're not modifying `nTransactions`. This will cause errors if `tArray` and `transactions` are not of the same size.
Comment: Do you get an error? Does the program crash?
Comment: what does a debugger say
Comment: no it runs correctly but gives the same results - as if it ignores the addtransaction method.
Comment: BTW - use std::vector
Comment: fyi you never clean up `tArray` before reassigning it to `newT`, this will be a memory leak.
Comment: @pm100 The OP says the following: "I am fairly bound by the assignment structure in this one so working with the avaliable structures are ideal."
Comment: do it with std::vector too for extra credit :-)
Answer: You should do this:
void Analyser::setTransactions(Transaction* transactions, int numTransactions)
{
//set tArray to new set of transactions
tArray = transactions;
ntransactions = numTransactions //HERE YOU NEED TO UPDATE THIS TOO
 }

As stated in the comments, also in here:
 void Analyser::addTransactions(Transaction* transactions, int numTransactions)
 {

    nTransactions += numTransactions;

    Transaction* newT;
    newT = new Transaction[nTransactions];    //Enough for all transactions

    for(int i = 0; i< nTransactions; i++)
    {
        newT[i] = tArray[i];
    }
    for (int j = 0; j< numTransactions; j++ )
    {
         newT[nTransactions - numTransactions + j] = transactions[j];
    }
    tArray = newT;

 }

Comment: I added the line which you mention however it stills seem like the addtransaction code is not working - if I comment it out or not the results remain the same.
Comment: You also forgot to update `nTransactions` in `addTransactions`. Use `nTransactions += numTransactions`.
Comment: I am now getting a memory error when i add that line in the add transaction code. Access violation reading location 0xabababab.
Comment: on the final iteration in the first loop - the answer is right in front of me but I brain is not working lol
Comment: @user2075995 Make sure the line is added at the end of the function, as in my answer. If you add it at the beginning of your function, `tArray` (the old one) will be assumed to be larger than it really is, and you will be reading values past the end of the array that aren't really there.
Answer: You are missing the line
nTransactions = numTransactions;

in your setTransactions. Your constructor should simply call your setTransactions method, so you have that code only once.
Comment: I added the line which you mention however it stills seem like the addtransaction code is not working - if I comment it out or not the results remain the same
Answer: Your addTransactions code should look like this:
void Analyser::addTransactions(Transaction* transactions, int numTransactions)
{

    Transaction* newT;
    newT = new Transaction[numTransactions + nTransactions];

    for(int i = 0; i<nTransactions; i++)
    {
        newT[i] = tArray[i];
    }
    for (int j = nTransactions; j<numTransactions + nTransactions; j++ )
    {
        newT[j] = transactions[j-nTransactions];
    }
    delete[] tArray;
    tArray = newT;
    nTransactions += numTransactions;
 }

delete[] tArray makes sure that you're not leaking any memory. In this case, I am assuming that Analyser always owns tArray, even when the given pointer is just used as in the constructor and setTransactions.
nTransactions += numTransactions; makes sure that the size of the tArray is appropriately updated. You should also edit setTransactions, as mentioned before.
Comment: I believe this works! - thanks a lot for your help and all the commenters :)

Array adding and set methods


simple vs simple hypothesis, finding sample size given type 1 and 2 error probabilities

Question: The problem is:
It is decided to investigate the hypotheses H0 : μ = €678 and H1 : μ = €720.
Assuming that the prices are normally distributed with standard deviation €100, what sample size must be tested so that the probabilities of making a type I and type II error are 5% and 10%, respectively?
So, i have no idea how to solve it. I need to find a sample size but how can i do it in case of simple vs simple hypothesis?
Answer: There are various calculators  (depending on the assumption of the distribution of both classes) to help calculate the sample size for a hypothesis test. Given those parameters, the sample size for a 1-sided test is 98.
Comment: Thank you! As i understand the formula used here is: $n=\frac{\sigma^{2}\left(z_{1-\beta}+z_{1-\alpha}\right)^{2}}{\left(\mu_{0}-\mu_{1}\right)^{2}}$ But using this formula the required sample size is 48, not 98. I cannot figure out why im getting different result. It must be that calculator uses different formula or i messed up with calculations but it seems right: $n=\frac{\ 100^{2}\left(1.282+1.645\right)^{2}}{\left(720-678\right)^{2}}$
 Would you be able to clarify it a little bit?
Comment: The discrepancy may come from whether this is a one-sample or two-sample test. The latter will introduce a factor of 2 to the RHS of the formula quoted by @Avrg_economics_student (as $\sigma^2$ will now be $100^2 + 100^2 = 2 \times 100^2$).
Comment: @B.Liu Thank you! It seems right, the calculator assumes two sample test, when in fact a one sample test would be correct.


Evitar o efeito do clique de botão sem afetar outros links

Question: Como eu consigo no jQuery, evitar o efeito do clique de um link que tenha href="#" sem afetar o comportamento padrão de outros links.
Exemplo:
Tenho 3 links
Link 1
Link 2
Link 3

O que eu to tentando fazer é que quando o usuário clique no link com href = #, não tenha aquele efeito de ir pro topo da página. E ao mesmo tempo, quero que outros links da páginas funcionem normalmente. Só quero afetar o comportamento de todos os .
Answer: No lugar do # você pode colocar:
 Link 2
Ou colocar uma classe nele:
 Link 2
CSS
a.none-link{
   pointer-events: none;
}

pointer-events: none - Essa propriedade com esse valor descarta todos os eventos do elemento. Click, Hover, Focus, Etc.
Comment: Deu certinho! Obrigado!


Operando em uma lista de listas com o condicional

Question: Estou tentanto usar compreensão de listas em um código mas eu "empaquei" em usar as estruturas for e if em determinada parte. Alguém pode me auxiliar? Basicamente eu tenho uma lista chamada "sup" cujas 2000 entradas são também listas de diversos comprimentos. Tenho uma outra lista de listas chamada "gap" (também com 2000 entradas e cujas listas-elemento são de mesmo comprimento da lista "sup".
Eu devo "apagar" todo elemento em "sup" cujo correspondente em "gap" é igual a 0. (Por exemplo, sup[i][j] deve ser apagado de sup[i] se gap[i][j] é igual a zero para todo i e j). As duas listas "sup" e "gap" possuem entradas do tipo "float" ainda que a "gap" só contenha zeros e uns.
De tudo o que tentei escrever a única escrita que não acusou erro de sintaxe (uso python 3 no Spyder) foi a seguinte mas que também não funciona.
    sup_new = [[sup[i].remove(int(j)) for j in gap[i] if gap[i][int(j)] > 0] for i in range(len(sup))]

Mas o retorno é

ValueError: list.remove(x): x not in list

Alguém pode me mostrar onde estou errando? Obrigado.
Answer: O erro é que você está tentando remover aquilo que não existe. Ao executar, por exemplo, [1, 2].remove(3), dará o erro citado, porque não há como remover o número 3 da lista [1, 2]. Você está tentando remover o int(j) de sup[i], mas ele não existe. Outro detalhe é que o retorno de list.remove é None, pois ele modifica a própria lista, então ao utilizá-lo dentro da compreensão de listas você estaria criando uma lista somente de None, não com as listas filtradas.
Python já possui uma função que filtra uma sequência com base em outra sequência: itertools.compress.
from itertools import compress

x = ['a', 'b', 'c']
y = [1.0, 0.0, 1.0]

result = compress(x, y)

print(list(result))  # ['a', 'c']

No exemplo acima, 'b' não é retornado porque em y o valor é 0.0.
Assim, basta fazer:
sup_new = [list(compress(s, g)) for s, g in zip(sup, gap)]

O list em list(compress(...)) serve apenas para forçar que seja uma lista ao invés de um iterador do tipo itertools.compress.
Sobre a classe zip, leia como Associar duas listas em python
Comment: Woss, obrigado pela ajuda. Nunca tinha lido sobre essas associações de listas. vou ler à respeito. Obrigado mesmo"
Comment: @LucianoMagrini Adicionei no início da resposta uma descrição do que fez errado também...
Comment: Woss, agradeço novamente. Estou lendo sobre essa associação de listas e essa função zip que não conhecia. Faz todo o sentido a sua descrição do meu erro. Entrei com sua sugestão no meu código mas ele retorna um erro de sintaxe. Veja:

`sup_new = [list(compress(s, g)) for zip(sup, gap)]` cujo retorno é

`File "", line 1
       sup_new = [list(compress(s, g)) for zip(sup, gap)]
SyntaxError: invalid syntax`
Comment: @LucianoMagrini O código foi corrigido na resposta já... estava mesmo errado
Comment: obrigado. Realmente faltavam os loopings rs. Estou há dias quebrando a cabeça com isso. Acho que vou parar tudo o que estou fazendo e vou ler tod a documentação sobre listas primeiro. Retroceder uma casa para ganhar tempo depois. Realmente, valeu!


Different way of solving $\frac{d^2u}{dx^2}=1$?

Question: I'm a third year physics student, not a math student.
The conventional way to solve this would be:
$$\frac{d^2u}{dx^2}=\frac{d}{dx}(\frac{du}{dx})=1 \Rightarrow d(\frac{du}{dx})= dx\Rightarrow \int d(\frac{du}{dx})=\int dx\Rightarrow \frac{du}{dx}=x+A \Rightarrow
du=(x+A)dx \Rightarrow u=\frac{x^2}{2}+Ax+B$$
So I'm wondering if what follows is correct:
$$\frac{d^2u}{dx^2}=1 \Rightarrow d^2u=(dx)^2 \Rightarrow d(du)=dxdx \Rightarrow \int d(du)=\int dxdx \Rightarrow du=\int dxdx$$
At this point, I don't know if there are other ways to proceed, but I use integration by parts
$$\int vdw=vw-\int wdv$$
by considering $v=dx$ and $dw=dx$, so that $w=x$ and $dv=d(dx)$:
$$du=\int dxdx=xdx-\int x·d(dx)$$
If I assume that $-\int x·d(dx)=C$ is a constant, we get
$$du=xdx+C \Rightarrow u=\frac{x^2}{2}+Cx+D$$
which is what we had originally.
However, how would I go about proving that $\int x·d(dx)=constant$? Is it because $d(dx)=0$? And how do I prove that? Are there any other interesting ways to solve this differential equation?
Answer: Sorry, this is not correct. Already the first step $d^2 u = (dx)^2$ is meaningless.
Comment: @elcocodrilotito see https://math.stackexchange.com/questions/1784671/when-can-we-not-treat-differentials-as-fractions-and-when-is-it-perfectly-ok
Comment: If I may counter with a question: why on earth **would** it be valid? What does it even **mean**?
Comment: @shaihorowitz Thank you, that's probably where my confusion comes from
Comment: Why, though? That was also a question I had
Comment: @HansLundmark I thought $\frac{d^2u}{dx^2}=1$ could be treated as a fraction. Besides, $d^2u$ is the operator $d$ acting twice on $u$ and $dx^2$ is just $dxdx$, I believe, so to me the equation $d^2u=dxdx$ made sense
Comment: But what is the operator $d$? And what does $dxdx$ mean? What kind of mathematical objects do these symbols denote? Until you can give precise answers to these questions, the expression is meaningless.


p-adic Pontryagin class invariance

Question: It is a well-known result due to Novikov that the universal Pontryagin class of a tangent bundle over $\mathbb{Q}$ is a topological invariant.
Also, it is known that over $\mathbb{Z}$ Pontryagin class is not invariant.
What happens over $\mathbb{Z}_p?$
Comment: Pontryagin classes are diffeomorphism invariant for *any* coefficients, since they are natural with respect to bundle maps and a diffeomorphism induces an isomorphism of tangent bundles. The non-trivial result of Novikov states that rational Pontryagin classes are *homotopy* invariant.
Comment: @William Thank you, yes that is what I meant. Corrected in my last edit.
Answer: Pontryagin classes of manifolds with coefficients in $\mathbb{Z}_p$ are not topological invariants in general.  In particular, by the argument in Section 4.4 of the book The Novikov Conjecture: Geometry and Algebra by Kreck and Lück, for any $n>1$, there exists a topological manifold $M$ with the following properties:

$M$ has the homotopy type of a Moore space $M(\mathbb{Z}/k,4n-1)$ for some $k>1$.
$M$ admits a smooth structure for which the $n$th integral Pontryagin class is trivial.
$M$ admits a smooth structure for which the $n$th Pontryagin class $p_n\in H^{4n}(M;\mathbb{Z})\cong\mathbb{Z}/k$ is a generator of $\mathbb{Z}/k$

For any prime $p$ dividing $k$, it follows that the $p$-adic $n$th Pontryagin classes $p_n\in H^{4n}(M;\mathbb{Z}_p)$ for these two smooth structures are also different, since the map $H^{4n}(M;\mathbb{Z})\to H^{4n}(M;\mathbb{Z}_p)$ is nontrivial (explicitly, $H^{4n}(M;\mathbb{Z}_p)\cong \mathbb{Z}/(p^m)$ for the largest $m$ such that $p^m\mid k$, with the map $\mathbb{Z}/k\to\mathbb{Z}/(p^m)$ then being the quotient map).
Interestingly, this does not apply to every prime $p$.  Indeed, the primes which can appear as factors of the number $k$ for some $n$ in this construction are $2$, odd primes $p$ such that the multiplicative order of $2$ mod $p$ is odd, and primes which divide the numerator of $\frac{B_{4n}}{4n}$ for some $n$ where $B_{4n}$ is the $4n$th Bernoulli number.  This does not include all primes--for instance, this means $p=3$ will never be a factor of $k$.  In fact, by the results of the paper Topologically invariant integral characteristic classes by Sharma, for each $n$ there is an integer $e_n$ which is a product of primes of the form above such that $e_np_n$ is a topological invariant.  This implies that the Pontryagin classes with coefficients in any ring $R$ in which all such primes are units are topological invariants, which in particular includes $R=\mathbb{Z}_p$ for any prime $p$ not of this form.

p-adic Pontryagin class invariance