Gerar números com base no índice no array

Question: Preciso gerar números aleatórios dentro de um intervalo... até ai tudo bem, porém, preciso fazer isso para cada posição do array, por exemplo, na posição 1 do meu array, deverão ser inseridos números aleatórios num intervalo 10 à 20, na posição 2, números aleatórios num intervalo 30 à 40 e assim sucessivamente. A posição inicial e a final, já estarão preenchidas.
-- Trecho do código --
    Random r = new Random();
    int v[] = new int[capacity];

    v[0] = 0;
    v[capacity - 1] = 15;

    for (int i = 1; i < v.length - 1; i++) {
        switch (i) {
        case 1:
            v[i] = 1 + r.nextInt(2);
            break;
        case 2:
            v[i] = 4 + r.nextInt(3);
            break;
        case 3:
            v[i] = 8 + r.nextInt(3);
            break;
        case 4:
            v[i] = 12 + r.nextInt(2);
            break;
        }

Comment: O método `nextInt` da classe `Random` já lhe permite especificar um limite superior. Se somar a algo dá um limite superior e inferior. Aproveite e coloque o código que está a utilizar para o problema, para que a comunidade lhe consiga ajudar na duvida que tem.
Comment: Perfeito Isac... o problema é que recebo o tamanho do array por parâmetro, no exemplo acima, trabalho com um de 6 posições, mas terei de manipular de 5 e 8 posições também...
Answer: Se pretende criar aleatórios em gamas de 20 valores pode faze-lo com um for em vez de manualmente como está a fazer.
Sim, porque apesar de estar a utilizar um for o preenchimento que tem é manual, pois avalia os indices específicos:
for (int i...){
    switch (i) {
        case 1:

Logo seria equivalente, e mais claro fazer:
v[1] = 1 + r.nextInt(2);
v[2] = 4 + r.nextInt(3);
v[3] = 8 + r.nextInt(3);
v[4] = 12 + r.nextInt(2);

Generalizando, ter um for e dentro um switch baseado na variável do for é sempre mau principio.
Para resolver o problema pode fazer assim:
for (int i = 1, base = 10; i < v.length - 1; i++, base += 20) {
    v[i] = base + r.nextInt(11); //11 pois o ultimo índice é exclusive
}

Repare que adicionei a variável base que define a base do aleatório e que vai andando de 20 em 20 com começo no 10.
Para perceber melhor como o aleatório está a ser gerado podemos analisar o primeiro caso. Base 10 + valor aleatório entre 0 e 10 dá um valor entre 10 e 20. O mesmo se aplica para os restantes elementos.
Exemplo a funcionar no Ideone
Comment: Isac, muito obrigado!
Funcionou! E sim, estava horrível aquele case dentro do for... valeu!!!


Klein bottle homeomorphic to union of Möbius strip

Question: I'm having trouble showing that the Klein bottle defined as a quotient space of $I^2$ with relation $(x,-1)R(x,1)$ and $(-1,y)R(1,-y)$  is Hausdorff and that it can be expressed as $X\cup Y$ where $X,Y$ are homeomorphic to the Möbius strip and $X\cap Y$ is homeomorphic to $S^1$.
Comment: Maybe the picture [found here](http://plus.maths.org/content/imaging-maths-inside-klein-bottle) will help you visualize it.
Comment: Your description of $R$ seems to be missing a minus sign on one of the $x$'s or on one of the $y$'s.  As it stands, the quotient is not a Klein bottle but a torus.
Comment: ah thank you I forgot to include a minus sign on y
Answer: This crude drawing may be helpful.


display image from a directory and text from a text file

Question: a current project of mine is giving me some trouble. The web page in question is supposed to display text from a text file followed by an accompanying image from a directory.
Currently, the output is text 1, image 1, text 2, image 1, text 1, image 2, text 2, image 2
My code so far:

    foreach ($DirEntries as $Entry)
    {
        if((strcmp($Entry, '.') != 0) && (strcmp($Entry, '..') != 0))
        {

            $inputFile = fopen("imagelist.txt", "r");
            if ($inputFile)
            {
                while (($line = fgets($inputFile)) !== false)
                {
                    echo "Name, description, and file name:
" . $line."
";
                    echo "

\n";
                }
            }
            else
            {
                echo "There was an error in the opening file";
            }
            fclose($inputFile);

        }
    }
    closedir($DirOpen);
    ?>

Any help would be greatly appreciated.
Answer: Your problem appears to be the nested while loop since you're dealing with a one to one relationship.
This should solve the problem for you:
$inputFile = fopen("imagelist.txt", "r");

// probably better to check for file readability before looping the directory items.
if (!$inputFile) {
    echo "There was an error in the opening file";
}
else {

    foreach ($DirEntries as $entry)
    {
        if($entry === '.' || $entry === '..')
        {
            continue; // using a continue helps keeps the code indentation levels down.
        }

        // assuming that each line corresponds to an image in the same order
        if (($line = fgets($inputFile)))
        {
            echo "Name, description, and file name:
" . $line."
";
            echo "

\n";
        }
        else
        {
            echo "Image '$entry' has no metadata";
        }
    }

    fclose($inputFile);

}
closedir($DirOpen);

Good luck!


Redirection not working when starting the app

Question: I am trying to redirect the page if it is logged in when the app starts.
<code>if (!iSLoggedIn()) {
mainView.router.loadPage({ url: 'index.html', ignoreCache: true, reload: false });}else {
$('#txtUserName').html(localStorage.getItem("fullname"));
    mainView.router.loadPage({ url: 'dashboard.html', ignoreCache: true, reload: true });}
</code>
The problem is when i start the app i am redirecting the page on condition but it is not behaving properly.no event or no function is firing after the redirection.but when i come back there from other page again it works. tried a lot of ways but not working.
I am using framework7.
Answer: AS far as i could find out the page code doesnt load that quick. so i used a timeout for one second. now it works fine


CCK Field with two values?

Question: Is there a way to have a CCK Field have two values for one input?
For example, a field called 'Sodium' and two values, '190mg' and '8%'- first being the amount, second being % of daily value.
If not, whats the best way to achieve this?
Edit:
The best solution I am looking for would be sets of Fieldgroups, and each row having 3 inputs. Label | value (required) | value (optional) - so, Sodium | 190mg | 8%
Comment: your solution appears great to me. Simplest way to achieve what you want.
Answer: Take a look at the CCK multi group options, which are only a part of CCK 3.0+. This functionality allows you to combine multiple base fields into one field grouping. See http://drupal.org/node/119102 for the long history on how this came about.
I actually can't find good documentation on using it, as CCK 3.0 is still only in Alpha, so unfortunately you'll just have to play around with it some.
The other option is to write your own CCK field type, in which there is no issue creating multiple inputs for one field. The upshot is that you can definitely achieve this using your own custom field, the downsides are you are writing custom code (which is nice to avoid) and it's not as flexible as the multigroup options built into CCK 3.0
Answer: So you want to combine two cck fields in one, in a way?
You could use two seperate fields 'sodium mg' & 'sodium %' - and add a computed field, so you can combine the values of those two fields into one field, 'sodium values' for example.
Some more info about the Computed Field module to make such computed field possible (from its project page):

Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!
Answer: I might be missing something but the easiest thing would be to enter the whole string "Sodium | 190mg | 8%" into the text field and then parse out the values at the theme level to do whatever you need to do - putting it in table, making a graph, etc. Underneath the text field put an example, problem solved. No alpha required.
Comment: Thought this might help,
[http://drupalbin.com/17997]
Answer: You can add all the data you want to a single CCK field, but you need a CCK type that supports this.
With CCK you can specify, how the data store should be (field_settings), how the form for inputting should be (widget) and how the field should be renderen (formatters).
You're not quite clear on how you want things, but the easiest thing to do, would be to create a have a single input/storage, and use a custom formatter to display the single value as two, based on some regex or similar.
You could also make your widget, that would create a custom form for the field and how the data should be stored. If multiple values is setup for the field, you could use delta to separate the values. This requires more in depth knowledge of the inner workings of CCK, but would give you better data control.
The documentation on doing all of this is very limited, but looking at other modules will give you an idea on how to do it.
Comment: I'm not sure what you are saying here.
Comment: That would depend on the site. The CCK maintainers have stated there will be an upgrade path, but I've never tested moving from 2 to 3. I would recommend extensive testing with 3 to make sure everything is working as expected.
Comment: Yeah. Its a legacy site with a -lot- of modules.
Answer: The module that allows you to achieve this in Drupal 6 is called Multigroup, and it is part of CCK 3.x, which has an alpha release. This module allows you to add multiple fields to a fieldset, and then presents the fieldset in the familiar 'add another' manner that CCK uses for multi-value fields.
Comment: Can a site using CCK 2 start using CCK 3 without a lot of issues?

CCK Field with two values?


TilePane: como criar evento individual nos botões

Question: tenho uma dificuldade em usar o TilePane, não consigo criar um evento para cada botão do array. Segue o código para vocês me ajudarem.
<code>   `TilePane tilePane = new TilePane();
    tilePane.setPrefColumns(3); //preferred columns
    tilePane.setAlignment(Pos.CENTER);

    Button[] buttons = new Button[9];

    for (int j = 0; j < buttons.length; j++) {

        buttons[j] = new Button("" + (""), new ImageView(BUTTON_CLOSE_IMAGE));
        buttons[j].setId("btn_transparent");
        buttons[j].setPrefSize(90, 90);
        tilePane.getChildren().add(buttons[j]);

        // Aqui tenho um layout com nove botões em três colunas, mas quero que cada         //botão tenha um código diferente. como fazer isso?

    }`
</code>
Answer: estava errando quanto ao local em que estava colocando o evento, mas fazendo várias tentativas, acabei conseguindo:
<code>TilePane tilePane = new TilePane();
tilePane.setPrefColumns(3); //preferred columns
tilePane.setAlignment(Pos.CENTER);

Button[] buttons = new Button[9];

for (int j = 0; j < buttons.length; j++) {

    buttons[j] = new Button("" + (""), new ImageView(BUTTON_CLOSE_IMAGE));
    buttons[j].setId("btn_transparent");
    buttons[j].setPrefSize(90, 90);
    tilePane.getChildren().add(buttons[j]);
</code>
}
<code> buttons[0].setOnAction(e -> System.out.print("oi")); // Minha resposta
</code>


Connect four game- making a grid

Question: I'm trying to make a connect four game. At this point, I am trying to make the game for console interaction only and am having trouble making the grid to look like this format:
Create 7 columns and each containing '.' till the time replaced by either color(just in case the formatting is not shown correctly):
1  2  3  4  5  6  7
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  Y  .  .  .  .
.  Y  R  .  .  .  .
.  R  Y  .  .  .  .
.  R  R  .  .  .  .

here is what I have so far:
NONE = ' '
RED = 'R'
YELLOW = 'Y'

BOARD_COLUMNS = 7
BOARD_ROWS = 6

# board=two dimensional list of strings and
# turn=which player makes next move'''
ConnectFourGameState = collections.namedtuple('ConnectFourGameState',
                                              ['board', 'turn'])

def new_game_state():
    '''
    Returns a ConnectFourGameState representing a brand new game
    in which no moves have been made yet.
    '''
    return ConnectFourGameState(board=_new_game_board(), turn=RED)

def _new_game_board():
    '''
    Creates a new game board.  Initially, a game board has the size
    BOARD_COLUMNS x BOARD_ROWS and is comprised only of strings with the
    value NONE
    '''
    board = []

    for col in range(BOARD_COLUMNS):
        board.append([])
        for row in range(BOARD_ROWS):
            board[-1].append(NONE)

    return board

Comment: What is your question?  What results are you getting now?
Answer: You will want to set NONE to '.', not a space. Then, you could make such a print function for the board:
def printBoard (b):
    print('  '.join(map(lambda x: str(x + 1), range(BOARD_COLUMNS))))
    for y in range(BOARD_ROWS):
        print('  '.join(b[x][y] for x in range(BOARD_COLUMNS)))

Used like this:
>>> x = _new_game_board()
>>> printBoard(x)
1  2  3  4  5  6  7
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  .  .  .  .  .

And when reconstructing your example state:
>>> x[1][-1] = RED
>>> x[1][-2] = RED
>>> x[1][-3] = YELLOW
>>> x[2][-1] = RED
>>> x[2][-2] = YELLOW
>>> x[2][-3] = RED
>>> x[2][-4] = YELLOW
>>> printBoard(x)
1  2  3  4  5  6  7
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  Y  .  .  .  .
.  Y  R  .  .  .  .
.  R  Y  .  .  .  .
.  R  R  .  .  .  .

If you are interested, I made a simple implementation of the whole game based on this idea. You can see it here.
Comment: Thanks poke..but I am supposed to usethe following code and build upon it:
Comment: No worries, I just got interested in building it on my own yesterday, and since I got it working, I thought why not share it? :)

Connect four game- making a grid


How do I import attributes with the feed mapper?

Question: I have a Drupal 7 instance with Ubercart 3, and I'm also using the Ubercart Feed Mappers module to map out the importing of product fields. I have all the fields, images and categories working well, but not attributes.
I've searched high and low for an answer or a short how to for importing attributes and multiple attributes for each product but with no success. How can I achieve it?
Answer: You need 'UC Feeds Product Importer' a sub module built to import all the product related fields.
check this: https://drupal.org/node/1802908

Create an importer (at admin/structure/feeds/create). Or try my default importer module, which creates a csv importer from all Ubercart fields - including attributes - automatically. If you use it, please leave feedback on the issue!
Download the template from the import page (if you use the default importer above, it will be at /import/uc_feeds_product_importer/template)
Fill in the template. For each attribute option you want enabled, fill in at least one of the cells for weight, price, or cost (a zero value works). If you fill in at least one of the three, any unfilled will default to zero. If you leave all three blank, that option will not be enabled on the imported product.
Import the completed csv at /import/uc_feeds_product_importer (if you're using my module above), otherwise go to /import and choose the importer you created.
Answer: http://www.ubercart.org/project/node_import_uc_stock#comment-55048
Node Import and Ubercart File Download Integration
I've extended node_import_supported_v5.zip to add support for importing "Ubercart File Downloads". The only modification between my version and v5 is that I've added this patch to resolve an issue with node_import and PHP 5.3
I've also included the additional doxygen generated API docs, so that hopefully others will be able to get a handle on the API and contribute improvements.
It would be best if we could get these ubercart extensions added into the core node_import, so that others will find and use it. I think in order for that to happen though, cpILL's code will need to properly provide "$values['nid']" in postprocess functions. Right now that'll mess up any other contrib modules which depend on that functionality.


Erro de compilação do VBScript ao executar ficheiro bat para envio de email

Question: O erro está descrito na imagem. Alguém me sabe dizer o motivo? Já tentei guardar o ficheiro com encoded ANSI  mas continua a não dar.
 Set objMail = CreateObject("CDO.Message")
    Set objConf = CreateObject("CDO.Configuration")
    Set objFlds = objConf.Fields
    objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
    objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
    objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
    'uncomment next three lines if you need to use SMTP Authorization
    'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
    'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
    'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
    objFlds.Update
    objMail.Configuration = objConf
    objMail.FromName = "Your Name"
    objMail.From = "firstname.lastname@example.com"
    objMail.To = "firstname.lastname@example.com"
    objMail.Subject = "Email Subject Text"
    objMail.TextBody = "The message of the email..."
    objMail.Send
    Set objFlds = Nothing
    Set objConf = Nothing
    Set objMail = Nothing

Comment: qual editor estás usando?
Comment: Já está resolvido.
Basta remover a linha 12 que não será necessária uma vez que a caixa ja esta configurada para o Nome correto.
Comment: Você pode postar uma resposta explicando como foi resolvido ou simplesmente editar sua pergunta para que os outros usuários entendam.
Comment: Já esta, agora pode votar para que demonstre a resolução pf
Answer: Solução:
Set objMail = CreateObject("CDO.Message")
    Set objConf = CreateObject("CDO.Configuration")
    Set objFlds = objConf.Fields
    objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
    objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
    objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
    'uncomment next three lines if you need to use SMTP Authorization
    'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
    'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
    'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
    objFlds.Update
    objMail.Configuration = objConf
    objMail.From = "email@example.com"
    objMail.To = "firstname.lastname@example.com"
    objMail.Subject = "Email Subject Text"
    objMail.TextBody = "The message of the email..."
    objMail.Send
    Set objFlds = Nothing
    Set objConf = Nothing
    Set objMail = Nothing

Guardar o ficheiro com o encoding ANSI e extensão .vbs e já ira funcionar perfeitamente. Para alem disso teremos de dar permissão na caixa de correio para enviar email por smtp.


Have I been teaching rolls wrong?

Question: I teach beginning band to first-year players aged 10-12.  I have always taught 5-stroke and 9-stroke rolls this way:  Assuming that we are in a simple meter like 2/4, 3/4, or 4/4, I first divide the notated roll note into 16ths.  There are 4 sixteenths in the quarter note of a 9-stroke roll and 2 in the eighth note of a 5-stroke roll.  Then, I teach the kids to allow the stick to "bounce" on each stroke, which results in the correct number of impacts on the head.  So, a kid playing a 9-stroke roll will use wrists/arms to play four main strokes (that will sound exactly like 16ths); they will let the stick bounce once on each of these main strokes to fill in the remaining notes (which would sound like 32nd notes).  Adding the next quarter note after the roll gives 9 strokes total, which sounds correct.  Once they learn how to control the speed of the bounce they can execute pretty decent rolls and they are ready to learn more rolls.

Today, however, 2 different students told me that their private drum teacher instructed them to execute the 9-stroke roll with 9 separate strokes (RRLLRRLL R), and no bounces.   I'm perfectly willing to accept that as a "band" teacher I may have it wrong, and I'd happily defer to a "percussion" teacher...  But if the kids are trying to execute a roll with 9 full motions like this, how will they ever get it to sound smooth at tempo?
Am I teaching it wrong?
This post here seems related...
How can double-stroke rolls be faster than single-strokes?
Comment: I'd say that either and both are fine. There are single and double rolls, and good drummers should be capable of combining each in whatever they do. That said, I drum, but haven't had formal lessons. But wouldn't be surprised if there's more than one way to skin a cat, so to speak.
Comment: Thanks so much for asking this.  When a kid perceives a contradiction between the band teacher and the private teacher, it can be very uncomfortable for the kid.
Comment: At least it wasn't uncomfortable for these kids.  I know them well, and I know their drum teacher:)
Answer: I wonder if you're both teaching only part of rolls. I don't see anything in your question about grip or technique, and the thing that unlocked rolls for me was using a technique where I change my grip as the roll gets faster.
So for a slow "roll", I do consciously play every stroke (as the private teacher suggested). On your side of things, even when I play a single stroke I am thinking about rebound and bounce as a way to take up the stick at the end of the stroke, even when I'm not playing another stroke with the same stick.
I do slow rolls with a loose grip, and I take up the sticks off the bounce and prepare for the next stroke. Volume is mostly controlled by initial stick height with a bit of Moeller influence in my overall technique. For a mid speed roll, my wrists move less and I'm using my back fingers to take up the bounce and execute the next stroke. My grip at the thumb and forefinger tightens slightly. For the fastest rolls, I move my thumb to the top of the stick and grip the stick firmly, and use more elbow to bring the stick up and down. The thumb takes the first bounce and drives the stick back to the head almost instantly for the second stroke, and then my elbow is lifting to prevent a third stroke.
So I agree with you that managing and using the bounce is not only advantageous, it's critical beyond a certain speed. You just can't roll as fast without it.
However, I also agree with the private teacher that learning to play even, deliberate strokes without using the bounce (aside from uptake), and learning to play them pretty fast, is a great foundation for both rolls and other techniques.
I would tell your students that both are correct, and that they are learning different things that at some point will synthesize and give them the most control over rolls at any speed.
Comment: @Tim Even when I'm not bouncing I still call it a double stroke if I strike twice in quick succession with the same hand. Some teachers instruct their students to learn to double stroke fairly quickly without using the bounce. So I wouldn't say everyone agrees that "bounce" means "double" and "double" means "bounce".
Comment: Is it true that what I've described is a "double" roll, but a separate stroke for each 32nd note is a "single?"  My percussion methods class is about 20 years behind me...
Comment: @nuggethead I'm not sure if I understand your question about "single" vs "double". To me, if you're stroking or "bouncing" twice with the same hand, that's a double stroke. The point of my answer is that the same roll can be played with or without using the bounce, and students would ideally learn both ways. I'm 99% sure that you can't play the fastest rolls without using the bounce, but there are definitely players who can rolls quite fast with deliberate strokes that are not just bouncing.
Comment: Single rolls are just what it says on the tin - single alternate strokes. Doubles will bounce for each stroke - LlRrLlRr.
Comment: Awesome @Todd Wilcox I think this is the answer.  I'm thinking I just found double strokes easier to execute on my own and then forgot there was an alternative!  But it's good to know that both are valid, and both have their place.
Comment: I hear what you're saying, and agree. But at certain speeds, I think the bounce is needed to articulate that second hit. Is that fair? Or would each second strike be exactly like the first of each pair?
Comment: @Tim Certainly for me, and I expect many or most players, I can only go above a certain speed by using the bounce. And learning to use the bounce is a technique every drummer should learn, IMHO. For me, a double is two deliberate strokes at slow speeds and using the bounce at high speeds, which is what I was trying to explain in my answer.
Comment: For me, that bounce is an integral part of playing - controlled sometimes by fingers, sometimes by wrist, and even by forearm. And even by where the sticks are held (distance from end) and how high they start above the skin. Let alone where on the drum they land. So much to do...

Have I been teaching rolls wrong?


Exporting menu structure using services

Question: Is it possible to to export the menu structure of my drupal site using the services module? This way the website structure can be generated on the drupal website -> make it available for webservices -> acces by mobile in order to build the same structure dynamically in the mobile app.
Answer: The Menu API is fairly extensive.  It is likely there is already a function available to return what you need.
For example, you can return an entire menu tree using the menu_tree_all_data().
<code>$navigation_tree = menu_tree_all_data('navigation');
</code>
You could also return everything known to the menu router with menu_get_router();
<code>$everything = menu_get_router();
</code>

Exporting menu structure using services


"Pseudo-terminal will not be allocated because stdin is not a terminal" when running ssh through python without paramiko

Question: I am running ssh from within Python without the use of an external library like Paramiko. I have my reasons for doing it this way instead of through an external library.
Basically I am doing subprocess.Popen("ssh -t bla -- command")
I get the following message when doing this:
Pseudo-terminal will not be allocated because stdin is not a terminal.

The reason I am running it with -t is I want the remote command to terminate when I kill my python script.
When I try with -t -t (to force it), I get the following message:
tcgetattr: Inappropriate ioctl for device

Is there a way I can run my ssh command with -t through Python?
Comment: If you can muck about with remote sshd settings, this should help: http://superuser.com/questions/396994/setting-ssh-to-terminate-remote-process-upon-disconnection
Answer: May I respectfully suggest that you are asking the wrong question, and that the right question might be something like "how do I make sure a sub process terminates when my python program terminates"
You could do some clever unix stuff like allocate a pty and make sure that you sub process uses this as std in out etc. so that the ssh command thinks that it's talking to a terminal rather than a pipe, but this is probably not what you really want to do.
Comment: The ssh subprocess does terminate when I kill my python script. However, the command that it initiated on the remote host does not terminate unless I pass in -t flag to the ssh command.
But when I pass in the -t flag to ssh, it doesn't respect that flag and gives me the error message I pasted in the question body.
Comment: Then It's the other process that I think you should be looking at.why doesn't it exit properly when the remote ssh gets dropped.sounds like it's ignoring a signal that it shouldn't.
Answer: To terminate the remote command when the python script gets killed, you may (as an alternative to the -t option to ssh) implement a workaround that uses a named pipe to convert "EOF to SIGHUP" when the stdin of sshd is being closed (see Bug 396 - sshd orphans processes when no pty allocated).
# sample code in Bash

# press ctrl-d for EOF
ssh localhost '
TUBE=/tmp/myfifo.fifo
rm -f "$TUBE"
mkfifo "$TUBE"
#exec 3<>"$TUBE"

<"$TUBE" sleep 100 &  appPID=$!

# cf. "OpenSSH and non-blocking mode",
# http://lists.mindrot.org/pipermail/openssh-unix-dev/2005-July/023090.html
#cat >"$TUBE"
#socat -u STDIN "PIPE:$TUBE"
dd of="$TUBE" bs=1 2>/dev/null
#while IFS="" read -r -n 1 char; do printf '%s' "$char"; done > "$TUBE"

#kill -HUP -$appPID
kill $appPID

rm -f "$TUBE"
'

Answer: It sounds like you're really asking for the inverse of the old nohup command; that is to say some way to ensure that the remote command responds to the HUP (hang-up) signal that's generated by the TTY (PTY or psuedo-tty) driver when the underlying connection to it is closed.
Personally I suspect that Paramiko is going to be far better than trying to manage this with the subprocess module.  You can have Paramiko open the connection, allocate the pty and execute your commands without any cruft; and the code to use your existing known_hosts and identity files (private keys) is relatively straightforward.
This recipe Copy files over SSH using paramiko  at ActiveState shows the basics of loading ssh known_hosts, using identity files and interacting with any ssh agent you might be running.  From there what you're asking for should simply be a matter of:

creating a session,
creating a channel,
getting a pty
and executing your remote command or invoking a shell and sending the your command to that shell using the stdin file like object it returns.

You could also use the TwistedConch implementation of the SSH protocols.  However, wrapping your head around the Twisted programming framework might be rather more difficult.
Here's an example of a simple ssh server in Twisted, with pty support: Twisted Conch in 60 Seconds: PTY Requests
Here's an SO thread from only a week before yours was posted Best way to run remote commands thru ssh in Twisted? but that didn't cover pty related issues at all.  Looking at the docs for twisted.conch.ssh.session suggests that it has pty support; but lists it as "Undocumented."
Of course you could even go with Pexpect, spawn a shell to your local ssh client and send your remote command through that.  This would most closely emulate the way that you'd run the command from your own shell.


apache2.4 mod_rewrite exclude specific alias directroy/uri

Question: I have the following setup on one of my vhosts:
...<VirtualHost *:80>
    ServerName cloud.domain.de
    ServerAdmin firstname.lastname@example.com
    ServerSignature Off

    Alias "/.well-known/acme-challenge" "/var/www/domain.de/vh-www/htdocs/public/.well-known/acme-challenge"

    <Directory "/var/www/domain.de/vh-www/htdocs/public/.well-known/acme-challenge">
      Require all granted
      ForceType 'text/plain'
    </Directory>

    <ifmodule mod_rewrite.c>
      RewriteEngine On
      RewriteCond %(REQUEST_URI) !/\.well\-known/acme\-challenge/?.*
      RewriteCond %{HTTPS} off
      # RewriteRule ^\.well-known/acme-challenge/([A-Za-z0-9-]+)/?$ - [L]
      RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    </ifmodule>...

What I want to achieve is, that mod_rewrite does not rewrite the URL when the url http://cloud.domain.de/.well-known/acme-challenge/ is accessed.
I already tried different approaches, one of them being the commented-out RewriteRule above, but nothing seems to work: the server rewrites it to https everytime.
When I disable the rewriting for testing purposes, I can access the alias URL just fine...
How do I achieve the specific URL not being rewritten?
Answer: Like that :
<ifmodule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/\.well\-known/acme\-challenge/
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</ifmodule>

If the URI match start with /.well-known/acme-challenge/ the request will not be redirected
Comment: Edited : there was () instead of {} and `RewriteCond %{HTTPS} off` is not requiered
Comment: Rewrite configurations can be inherited to all virtual hosts with `RewriteOptions InheritDown` since Apache 2.4.8. `RewriteEngine On` has still to be present in each virtual host configuration.
Comment: First, thanks for you advice! Unfortunately, it didn't work. When you visit: `http://www.server-plant.de/.well-known/acme-challenge/`it is still being rewritten. (I applied the same Rewrrite Rules and Conditions for my www-Subdomain, so it's excatly the same as the cloud-Subdomain)
Comment: Yeah, I just blindly copied yours without checking for the right brackets, but well, sh.. happens :) Now it works like charm and you're also right regarding the other condition. Just one question left: How to change the condition to also match everything behind the trailing `/`? So it wouldn't catch index.html and so on?
Comment: it already match all `start with /.well-known/acme-challenge/`that mean  `/.well-known/acme-challenge/anything` will not be redirect too
Comment: Okay, it seems there was something in my browser's cache or so. Now at home it works out of the box. And again, thanks alot!
Comment: "Note that rewrite configurations are not inherited by virtual hosts. This means that you need to have a RewriteEngine on directive for each virtual host in which you wish to use rewrite rules." https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html
Answer: @mark
Correct version of the "shorter and more robust" variant:
RewriteCond %{REQUEST_URI} ^/\.well\-known
RewriteRule . - [L]

Comment: The single dot in line 2 did not work for me. Is it because it only matches one char and the url consists of several chars? I am using ^(.*)$ instead.
Comment: adding this to stop the ssl redirect rules below it is awesome
Answer: IMHO shorter and more robust:
RewriteCond %{REQUEST_URI} ^\.well\-known
RewriteRule - [L]

you may want to add /acme-challenge/ eventually but if you would like to debug it with an arbitrary file, like ./well-known/test this solution works better
what does it actually do:
looks whether the request starts with .well-known, in that case does nothing (the meaning of -) and make it the last rule [L]
Comment: nope. The virtualhosts still seem to have precedence. "Sections inside  sections are applied after the corresponding sections outside the virtual host definition. This allows virtual hosts to override the main server configuration." from https://httpd.apache.org/docs/current/sections.html


Value of $b_{5}\;,b_{6}\;\;b_{7}.$ If $b_{n}$ Rep. no. of $n$ digit integer ending with $1$

Question:
Let $a_{n}$ denote the number of all $n-$ digit positive integers formed by the digits $0,1$
or both such that no consecutive digits in them are $0$ and $b_{n}$ denote number of such
$n$ digit integers ending with digit $1$ and $c_{n}$ denote number of such
  $n$ digit integers
ending with digit $0$.
$(i)\;\;\;$ Then calculate the values $b_{5}\;,b_{6}\; ,b_{7}$
$(ii)\;\; $Also, find which of the following is right?

$\bf{Options::}$

$(a)\;\; a_{17}=a_{16}+a_{15}\;\;\;\;\;(b)\;\; c_{17}\neq c_{16}+c_{15}\;\;\;\;\;(c)\;\;b_{17}\neq b_{16}+c_{16}\;\;\;\;\; (d)\;\ a_{17}=c_{17}+b_{16}$

$\bf{My\; Try::}$ Here  Given $a_{n}$ Represent all $n$ Digit positive integer ending with $0,1$
and $b_{n}$ Represent such all $n$ Digit positive Integer ending with $1$
and $c_{n}$ Represent such all $n$ Digit positive Integer ending with $0$
So we get  $a_{n} = b_{n}+c_{n}.$
and $a_{1} = 1(1)\;\;,a_{2}=2(10,11)\;\;,a_{3}=3(110,101,111)\;\;,a_{4}=5(1111,1110,1101,1011,1010)$
and $b_{1}=1(1)\;\;,b_{2}=1(11)\;\;,b_{3}=2(101,111)\;\;,b_{4}=3(1111,1101,1011)$
Similarly $c_{1}=0\;\;,c_{2}=1(10)\;\;,c_{3} =1(110)\;\;,c_{4}=2(1110,1010)$
Now I did not understand How can I solve after that.
Help Required.
Thanks.
Answer: By definition $a_n = b_n + c_n$.
If we have a correct number of length $n+1$ ending in $1$, then removing the final $1$ will always result in a correct number of length $n$ (of which there are $a_n$). And if we have a correct number of length $n$, we can always append a 1 to it, and get a correct number of lenght $n+1$, ending in $1$ (of which there are $b_{n+1}$), because the $1$ can never cause the 2 consecutive $0$ condition to fail.
So $b_{n+1} = a_n$ for all $n$. (This also holds for your small number examples, as you can see).
If we have a correct number of length $n+1$ ($n \ge 2$) ending in $0$, then it must end in $10$ as $00$ would have been illegal. Removing the final $10$ leaves us with a correct number of length $n-1$, of which there are $a_{n-1}$ by definition. Conversely again, having a correct number of length $n-1$ we can always add $10$ to it, which will never spoil the correctness, and get a valid number of length $n+1$ ending in $0$.
So $c_{n+1} = a_{n-1}$, as also can be seen from your examples.
So $a_{n+1} = b_{n+1} + c_{n+1} = a_n + a_{n-1}$ for all $n \ge 2$. I.e. we have a Fibonacci sequence.
Comment: The $b_n$ form a shifted Fibonacci sequence. So they're easy to compute once you have two consecutive values. @OsheenSachdev
Comment: What about part (1)? How would we do that?
Comment: Ah right...didn't quite understand the answer in the first go. Thank you!


UIResponder Signal

Question: Boa tarde,
fiz uma pequena app com o swift 2.3 Xcode 7.3.1.
com a actualização do swift 3 e Xcode 8 começou a apresentar o erro abaixo.
alguma ajuda por favor.
Comment: tinha botões mal conectados, reconectei e resolveu
Answer: O Thread 1: signal SIGABRT significa que você está fazendo alguma requisição para algo que não existe ou não está bem definido. Ocorre, por exemplo, quando você não conecta os botões do storyboard com o código apropriadamente; quando apaga modifica o nome de uma função associada a algum elemento no storyboard, mas esquece de desfazer o link antigo pelo storyboard (ele não detecta automaticamente mudanças, você precisa apagá-las manualmente). Confira se nada do tipo está acontecendo.
Comment: Acabei de perceber depois. Obrigado

UIResponder Signal


node.js async each function callback failing

Question: I'm making a call to my db, and want to use the results to fire off a request to another server, and then handle the responses. I want to do this asynchronously so I am trying to use the async library.
var sendRequest = function (store) {

    console.log(store);
}

connection.connect();

connection.query('SELECT * from stores', function(err, rows, fields) {
    if (!err){
        async.each(rows, function(row, sendRequest) {
            var store = {id: row.id, address: row.address};
            //console.log(store); <-- this works
            sendRequest(store); <-- this logs {id: '', address: null} only once
        }, function(err){
            console.log(err);
        });
    }
    else
        console.log('Error performing query');
});

connection.end();

If I log the store variable directly, it logs for each instance in the array rows and properly. If I try to do it through the sendRequest callback, it does it only once and improperly.
Comment: @haaduken: Ha! see! even you are confused! Then rename the other variable (the function argument) to something else to stop it from being overridden.
Comment: Can you tell me if you are using the nodeJS "async" library here? https://www.npmjs.com/package/async#each
Comment: @NormanBreau, yes I am. Thats the async.each function call.
Comment: It's probably a bad idea to have two variables named `sendRequest`. It can cause potential confusion making people think the `sendRequest` inside the `async.each` callback have anything to do with the `sendRequest` function at the top.
Comment: @slebetman, but I want it to call that function.
Answer: You confused some things. You're using the same name, sendRequest, for the each callback. You should do instead:
connection.query('SELECT * from stores', function(err, rows, fields) {
  if (!err){
    async.each(rows, function(row, callback) {
        var store = {id: row.id, address: row.address};
        sendRequest(store);
        callback();

    }, function(err){
        console.log(err);
    });
  }
  else
    console.log('Error performing query');
});

Comment: so what goes in callback and where is it defined?
Comment: @haaduken: That callback is passed to you by `async.each`, just like `row`
Comment: `callback` is an argument of the function that `async.each` has to call for each item in the array, to notify that it has finished. You can use whatever name you want, just make sure that this name is not in use by other functions or variables.


Why is the residual independence assumption important in OLS regression and how may it be violated?

Question: I haven't found a clear answer to this question yet. What parts of the equation does it affect exactly, and how can b weights still be unbiased? Does it bias your results? I know the answer to the last question is yes, but how and in what ways? People say time series designs and clusters violate this assumption, but what other ways can it be violated?
Comment: Residuals are *not* assumed to be independent in regression. Indeed they're necessarily dependent; one can readily compute their variance-covariance matrix ($\sigma^2 (I-H)$, for $H$ the hat-matrix) under iid errors. The error term is the thing assumed to be independent. $y-\hat{y}\neq y-E(y|x)$ e.g. see [Errors and Residuals](https://en.wikipedia.org/wiki/Errors_and_residuals)
Answer: Independence of the residuals or error term from predictors is a core assumption of all regression modeling regardless of the method used to estimate the model, whether it be OLS, maximum likelihood, FIML, whatever. Jeffrey Wooldridge in Econometric Analysis of Cross Section and Panel Data has the clearest explanation for why this is "bad" for models beginning on page 50,

An explanatory variable is said to be endogenous if it is correlated
  with u (the errors or disturbance)...This usually arises in one of
  three ways: Omitted variables...these appear when we would like to
  control for one or more additional variables but...they cannot be
  included in the model...Measurement error...or Simultaneity which
  arises when at least one of the explanatory variables is determined
  simultaneously along with y.

None of these are desirable properties for any model. Regrettably, many of the workarounds and "solutions," e.g., 2SLS in time series, etc., don't do that great of a job of solving these problems either.
Comment: I realize the question conflates the terms "residual" and "error" but I think answers to it should not. Please don't compound the confusion in the question by repeating it in an answer; I am not saying you have to correct the error in the question, but at the least, I think you should refrain from calling errors "residuals".
Comment: @Glen_b Got it...


Unrecognized selector sent to class runtime error

Question: I am using a third party framework containing a category on NSData and having a static method dataUsingBase64String: in it.
The framework got linked fine and code builds successfully. But I am getting unrecognized selector sent to class runtime error when this method gets called.
I have also tried adding -ObjC,-all_load flags in OTHER_LINKER_FLAGS of XCode with no luck..
Answer: I guess your library is statically linked. A common problem in that is categories are not included or linked. You additionally need to add -all_load to the Other Linker Flags of the target which is using your static library.
Also check the below answers similar to your problem
Answer 1 - NSData Unrecognized selector sent to class
Answer 2 - Objective-C Category Causing unrecognized selector
Answer 3 - "unrecognized selector sent to instance" to a static library despite ObjC flag
I hope this helps
Answer: Note: I needed to add framework in this way,
Framework Search Paths instead of adding frameworks to "Linked Frameworks and Libraries" section
Here, somehow the framework was not loaded even after adding-Objc or -all_load.
Finally, -framework in OTHER_LINKER_FLAGS did the trick for me.
Something about it from manpage,
-framework name[,suffix]
                 This option tells the linker to search for `name.frame-
                 work/name' the framework search path.  If the optional suffix
                 is specified the framework is first searched for the name
                 with the suffix and then without (e.g. look for `name.frame-
                 work/name_suffix' first, if not there try `name.frame-
                 work/name').

Answer: If -Objc does not take effect, you can try to delete your Category from the project and drag it to the project again, and check Target membership.


Proving $\frac{1}{\cos^2\frac{\pi}{7}}+ \frac {1}{\cos^2\frac {2\pi}{7}}+\frac {1}{\cos^2\frac {3\pi}{7}} = 24$

Question: Someone gave me the following problem, and using a calculator I managed to find the answer to be $24$.

Calculate $$\frac {1}{\cos^2\frac{\pi}{7}}+ \frac{1}{\cos^2\frac{2\pi}{7}}+\frac {1}{\cos^2\frac{3\pi}{7}}\,.$$

The only question left is, Why? I've tried using Euler's Identity, using a heptagon with Law of Cosine w/ Ptolemy's, etc. but the fact that the cosine values are all squared and in the denominator keeps getting me stuck.
If $\zeta=e^{\frac{2\pi i}{7}}$, then the required expression is
$$4\left(\frac{\zeta^2}{(\zeta+1)^2}+\frac{\zeta^4}{(\zeta^2+1)^2}+\frac{\zeta^6}{(\zeta^3+1)^2}\right).$$
How do we simplify this result further?
Comment: Seems to be a special case of $$\sum_{k=0}^{n-1} \frac{1}{\cos\big(\frac{k\pi}{n}\big)^2}=n^2$$ when $n$ is odd.
Comment: I have an answer coming but it will take some time.
Comment: @arctictern Would you mind sharing where you found that identity?
Comment: @mikevandernaald I didn't find it anywhere, I evaluated the sum for n=7 and n=5 to figure out that it's equal to n^2 (well, I assume).
Comment: See http://math.stackexchange.com/questions/265229/prove-that-cot2-pi-7-cot22-pi-7-cot23-pi-7-5
Comment: See http://math.stackexchange.com/questions/309271/proving-csc2-left-frac-pi7-right-csc2-left-frac2-pi7-right
Answer: The roots of $x^6+x^5+\ldots+x+1$ over $\mathbb{C}$ are $x=\exp\left(\frac{2\pi\text{i}}{7}\right)$ for $k=1,2,\ldots,6$.  Let $y:=x+\frac{1}{x}$.  Then, $$\frac{x^6+x^5+\ldots+x+1}{x^3}=\left(y^3-3y\right)+\left(y^2-2\right)+y+1=y^3+y^2-2y-1\,.$$
Hence, the roots of $y^3+y^2-2y-1$ are $y=y_k:=2\,\cos\left(\frac{2k\pi}{7}\right)$ for $k=1,2,3$.  Observe that $$S:=\sum_{k=1}^3\,\frac{1}{\cos^{2}\left(\frac{k\pi}{7}\right)}=\sum_{k=1}^3\,\frac{2}{1+\cos\left(\frac{2k\pi}{7}\right)}=4\,\sum_{k=1}^3\,\frac{1}{2+y_k}\,.$$
Since $y_k^3+y_k^2-2y_k-1=0$, we have $$y_k^2-y_k=\frac{1}{2+y_k}$$ for all $k=1,2,3$.  Consequently,
$$S=4\,\sum_{k=1}^3\,\left(y_k^2-y_k\right)\,.$$
The rest should be easy.

In general, let $n$ be a nonnegative integer and we are evaluating the sums $\displaystyle \sum_{k=0}^{2n}\,\frac{1}{\cos^{2}\left(\frac{k\pi}{2n+1}\right)}$ and $\displaystyle \sum_{k=1}^{n}\,\frac{1}{\cos^{2}\left(\frac{k\pi}{2n+1}\right)}$.  The roots of $x^{2n+1}-1$ over $\mathbb{C}$ are $x=x_k:=\exp\left(\frac{2k\pi}{2n+1}\right)$, for $k=0,1,2,\ldots,2n$.  Observe that
$$\frac{1}{1+x_k}=\frac{1}{2}\,\left(\frac{1+x_k^{2n+1}}{1+x_k}\right)=\frac{1}{2}\,\sum_{j=0}^{2n}\,(-1)^j\,x_k^j=\frac{2n+1}{2}-\frac{1}{2}\,\sum_{j=1}^{2n}\,\left(1-\left(-x_k\right)^j\right)\,.$$
That is,
$$\frac{1}{\left(1+x_k\right)^2}=\frac{2n+1}{2}\left(\frac{1}{1+x_k}\right)-\frac{1}{2}\,\sum_{j=1}^{2n}\,\sum_{i=0}^{j-1}\,(-1)^i\,x_k^i\,,$$
or equivalently,
$$\frac{1}{\left(1+x_k\right)^2}=\frac{2n+1}{4}\,\sum_{j=0}^{2n}\,(-1)^j\,x_k^j-\frac{1}{2}\,\sum_{j=1}^{2n}\,\sum_{i=0}^{j-1}\,(-1)^i\,x_k^i\,.$$
Consequently,
$$\frac{x_k}{\left(1+x_k\right)^2}=\frac{2n+1}{4}\,\sum_{j=0}^{2n}\,(-1)^j\,x_k^{j+1}-\frac{1}{2}\,\sum_{j=1}^{2n}\,\sum_{i=0}^{j-1}\,(-1)^i\,x_k^{i+1}=\frac{2n+1}{4}+f\left(x_k\right)$$ for some polynomial $f(x)$ of degree at most $2n$ without the constant term.  Then, $$\sum_{k=0}^{2n}\,\frac{x_k}{\left(1+x_k\right)^2}=\frac{(2n+1)^2}{4}+\sum_{k=1}^{2n}\,f\left(x_k\right)\,.$$
It is evident that $\displaystyle\sum_{k=0}^{2n}\,f\left(x_k\right)=0$.  Furthermore, $$\frac{x_k}{\left(1+x_k\right)^2}=\frac{1}{2}\,\left(\frac{1}{1+\cos\left(\frac{2k\pi}{2n+1}\right)}\right)=\frac{1}{4}\,\left(\frac{1}{\cos^2\left(\frac{k\pi}{2n+1}\right)}\right)\,.$$ Ergo,
$$\frac{1}{4}\,\sum_{k=0}^{2n}\,\frac{1}{\cos^2\left(\frac{k\pi}{2n+1}\right)}=\sum_{k=0}^{2n}\,\frac{x_k}{\left(1+x_k\right)^2}=\frac{(2n+1)^2}{4}\,.$$  This shows that $$\sum_{k=0}^{2n}\,\frac{1}{\cos^2\left(\frac{k\pi}{2n+1}\right)}=(2n+1)^2\,.$$  Furthermore, we have
$$\sum_{k=1}^n\,\frac{1}{\cos^2\left(\frac{k\pi}{2n+1}\right)}=\frac{(2n+1)^2-1}{2}=2n(n+1)\,.$$
Comment: Very nice. Unexpected sources lead to the solution.
Answer: In this lovely answer, @joriki establishes the identity
$$
\sum _{l=1}^{n}\tan^2 \frac {l\pi } {2n+1}=n(2n+1)\;.
$$
With $n=3$ this gives
$$
\tan^2\frac\pi7+\tan^2\frac{2\pi}7 + \tan^2\frac{3\pi}7=21.
$$
The desired result follows from the identity $\sec^2\theta=1+\tan^2\theta$.
Answer: First notice that since $\cos(x)=\cos(\pi-x)$, we have
$$1+2\left(\frac{1}{\cos(\frac{\pi}{7})^2}+\frac{1}{\cos(\frac{2\pi}{7})^2}+\frac{1}{\cos(\frac{3\pi}{7})^2}\right)=\sum_{k=0}^6 \frac{1}{\cos(\frac{k\pi}{7})^2}$$
Now, $x\mapsto 2x$ is a bijection of the integers mod $7$, so we may make the summands $\cos(\frac{2\pi k}{7})^{-2}$.
Using $\cos(\frac{2\pi k}{n})=(\zeta^k+\zeta^{-k})/2$ where $\zeta=e^{2\pi i/n}$ combined with the geometric sum formula
$$\frac{a^n+b^n}{a+b}=\sum_{r=0}^{n-1} a^{(n-1)-r}b^r,$$
and the fact that for $n$th roots of unity $\xi$,
$$\sum_{k=0}^{n-1} \xi^k =\begin{cases} n & \xi=1 \\ 0 & \xi\ne1 \end{cases} $$
we may derive
$$\sum_{k=0}^{n-1}\frac{1}{\cos(\frac{2\pi k}{n})^m}=\sum_k \left(\frac{2}{\zeta^k+\zeta^{-k}}\right)^m=\sum_k \left(\frac{\zeta^{nk}+\zeta^{-nk}}{\zeta^k+\zeta^{-k}}\right)^m $$
$$=\sum_k\left(\sum_{r=0}^{n-1}(-1)^r \zeta^{-(2r+1)k}\right)^m=\sum_k \sum_{\substack{r_1,\cdots,r_m \\ \sum r_i=r}}(-1)^r\zeta^{-(2r+m)k}$$
$$ =\sum_{\substack{r_1,\cdots,r_m \\ \sum r_i=r}} (-1)^r \sum_k (\zeta^{-2r-m})^k=n(A-B).$$
Therefore in conclusion we have
Theorem.
$$\sum_{k=0}^{n-1} \frac{1}{\cos(\frac{2\pi k}{n})^m}=n(A-B)$$
where $A$ and $B$ count the solutions to $r_1+\cdots+r_m\equiv -m/2$ mod $n$ with $\sum_i r_i$ even and odd respectively (and $0\le r_1,\cdots,r_m<n$).
As a special case, if $m=2$ we see that $A=n$ and $B=0$, yielding the corollary
$$\sum_{k=0}^{n-1}\frac{1}{\cos(\frac{2\pi k}{n})^2}=n^2.$$
Answer: Incomplete solution
The idea behind this solution is using Vieta's cubic formulas to rewrite the equality in a simpler, more manageable way. Letting $\cos^2\frac{\pi}{7}=\alpha$, $\cos^2\frac{2\pi}{7}=\beta$, and $\cos^2\frac{3\pi}{7}=\gamma$, we have this:
$$\frac{1}{\alpha}+\frac{1}{\beta}+\frac{1}{\gamma}=24$$
$$\frac{\alpha\beta+\alpha\gamma+\beta\gamma}{\alpha\beta\gamma}=24$$
By letting $\alpha,\beta,$ and $\gamma$ be roots to a cubic, we use Vieta's formula's to see that $-\frac{c}{d}=24$

Now, consider the three denominators as roots to a cubic polynomial. Let's make a third degree equation using them:
$$(x-\cos^2\frac{\pi}{7})(x-\cos^2\frac{2\pi}{7})(x-\cos\frac{3\pi}{7})$$
Let's use substitutions to avoid some nasty simplified expression. Let $u=\cos\frac{\pi}{7}$. Using some angle addition trig identities, we transform our equation into this:
$$(x-u^2)(x-4u^2+4u-1)(x-16u^6+24u^4-9u^2)$$
Multiply them out:
$$x^3+(-16u^6+24u^4-14u^2+4u-1)x^2+(80u^8-64u^7-104u^6+96u^5+25u^4-40u^3+10u^2)x+(-64u^{10}+64u^9+80u^8-96u^7-12u^6+36u^5-9u^4)$$
Consider the form $ax^3+bx^2+cx+d$. Per Vietas' formulas, $-c/d=24$.
$$\frac{80u^6-64u^5-104u^4+96u^3+25u^2-40u+10}{64u^8-64u^7-80u^6+96u^5+12u^4-36u^3+9u^2}=24$$
I will continue to work on proving this last part, but I figured at least simplifying your problem to this might be of some asssistance, and someone else may be able to validate the last equation before I do. Basically, if you prove the last equality you prove the question posted.


Understanding a proof about a Poisson distribution

Question:
Let $X$ be Poisson distributed where $P(X=n) = p_n(\lambda) = \frac{\lambda^n}{n!}e^{-\lambda}$ for $n \geq 0$. Show
  $$P(x \leq n) = 1 - \int_0^\lambda P_n(x) dx.$$

This is the argument given:
$\frac{d}{d\lambda} p_n = p_{n-1} - p_n$ where $p_{-1} = 0$. Hence
$$(\frac{d}{d \lambda})P(X \leq n) = p_n(\lambda).$$
Can someone please explain this argument better, because I am understanding nothing at all.
Comment: Which step is unclear?
Comment: Actually i am not understanding the reasoning at all. To be more precise, why $(\frac{d}{d \lambda})P(X \leq n) = p_n(\lambda)$ and how can this solve the problem.
Comment: 1. Find $\frac{d}{d\lambda}\left(\frac{\lambda^n}{n!}e^{-\lambda}\right)$ and compare this with $p_{n-1}(\lambda)-p_{n}(\lambda)$
Comment: 2. $P(X \le n)= p_{0}(\lambda)+p_{1}(\lambda) +\cdots + p_{n}(\lambda)$.  Take the derivative of both sides of this with respect to $\lambda$, using the previous result, and telescope
Answer: I think the correct formula should be
$$\tag{1}(\frac{d}{d \lambda})P(X \leq n) = -p_n(\lambda).$$
(with a minus sign in the RHS). The proof of (1) is as follows:
Let us apply the classical rule $d(fg)/d\lambda=(df/d\lambda).g+f.(dg/d\lambda)$ to the formula:
$$p_n(\lambda) = \frac{\lambda^n}{n!}e^{-\lambda}$$
We get:
$$\frac{d}{d\lambda} p_n = n\dfrac{\lambda^{n-1}}{n!}e^{-\lambda} + \dfrac{\lambda^{n}}{n!}(-e^{-\lambda})=\dfrac{\lambda^{n-1}}{(n-1)!}e^{-\lambda} - \dfrac{\lambda^{n}}{n!}e^{-\lambda}=p_{n-1} - p_n  \ \ \ \text{(property} \ P_n)$$
Thus, adding the equations of properties $P_0, P_1, \cdots P_n$, one obtains (because of concellations in the RHS):
$$\frac{d}{d\lambda}(p_0+p_1+\cdots+p_n)=p_0-p_n=-p_n$$
proving (1) because the LHS is nothing but $p_0+p_1+\cdots+p_n=P(X \leq n)$.
Edit : (following a good remark of @Henry) How convention
$$\tag{2}p_{-1}=0$$
can be explained ? Let us have a look at case $n=0$ :
$$\frac{d}{d\lambda} p_0 = \frac{d}{d\lambda} e^{-\lambda}=-e^{-\lambda}=-p_0=p_{-1}-p_0$$
if one takes convention (2).
Edit (following another remark of @Henry) : Let us establish the first relationship written under the following form (with a capital $X$ and a more neutral variable "$u$" in the integral):
$$\tag{3}P(X \leq n) = 1 - \int_0^\lambda P_n(u) du.$$
Here is a proof; clearly, from (1), one can deduce :
$$\tag{4}P(X \leq n) = K - \int_0^\lambda P_n(u) du$$
for a certain constant $K$ (this kind of additive constant appears whenever a primitive function is taken on both sides of an equality). The question is now, comparing (3) and (4) : why do we have $K=1$ ?
In fact, there is an explicit expression for the integral in (4) (see (https://en.wikipedia.org/wiki/List_of_integrals_of_exponential_functions)):
$$\tag{5}\int_0^\lambda P_n(u) du=\int_0^\lambda \frac{u^n}{n!}e^{-u} du=\left[\left(\sum_{k=0}^n \frac{u^k}{k!}\right)e^{-u}\right]_{u=0}^{u=\lambda}=\left(\sum_{k=0}^n \frac{\lambda^k}{k!}\right)e^{-\lambda}-1$$
Plugging this result into (4), one gets
$$\tag{6}P(X\leq n)=K+\left(\sum_{k=0}^n \frac{\lambda^k}{k!}\right)e^{-\lambda}-1$$
When $n \rightarrow \infty$, for any fixed value of $\lambda$,

the LHS of (6) tends to $1$,
the RHS of (6) tends to $K+e^{\lambda}e^{-\lambda}-1=K+1-1=K$ (due to the series expansion of "exp" function).

explaining why $K=1.$
Comment: I suspect you need $p_{-1}(\lambda)=0$ somewhere, and perhaps also $P(X \le n) = 1$ when  $\lambda=0$
Comment: Thanks for your comments @Henry. Concerning the explanation about $p_{-1}(\lambda)=0$, you are right, I am going to make an edit to my answer. I should have said that a particular case occurs at the beginning :$\frac{d}{d\lambda} p_0 = \frac{d}{d\lambda} e^{-\lambda}=-e^{-\lambda}=-p_0=p_{-1}-p_0$ if one takes the convention $p_{-1}=0$. But, I don't understand your second remark : for me, the case $\lambda=0$ never occurs for Poisson distribution.
Comment: Where does the $1$ come from in  $\displaystyle 1 - \int_0^\lambda P_n(x) dx$ ?
Comment: @Henry: Your question is interesting and deserves also an "edit" to my answer.  I am going to do it (I had just not adressed this issue because it was not asked by the OP). In short, this "1" is an additive constant the kind of which appears whenever a primitive function is taken on both sides of an equality. But why "1" ?
Comment: Perhaps $\displaystyle \int_0^\lambda p_n(x) dx = \left. -P_x(X \le n) {\, \atop \,} \right|_{x=0}^{x=\lambda}= -P_\lambda(X \le n) + P_0(X \le n)$.  Then rearrange to $\displaystyle   P_\lambda(X \le n) = P_0(X \le n)- \int_0^\lambda p_n(x) dx$  and use $P_0(X \le n)=1$.
Comment: But a constant $K$ should be introduced in $\displaystyle \int_0^\lambda p_n(x) dx = \left. -P_x(X \le n) {\, \atop \,} \right|_{x=0}^{x=\lambda}+K=\cdots$. See the edit to my answer I just wrote.
Comment: I suspect that you do not need a constant of integration for a definite integral (as if you add it then you will also subtract it).  No matter
Comment: In fact, it should not be considered a definite integral, for the following reason: there is arbitrariness in the choice of the lower bound $0$. Thus constant $K$ "compensates" this arbitrariness.
Comment: No need to respond further.  My view is that an almost-surely-constant-zero random variable, i.e. with $P(X=0)=1$, can be described as a Poisson random variable with $\lambda=0$, and that leads to $P_0(X \le n)=1$ here.  You seem to be less comfortable with that.
Comment: @Henry Thanks very much for pointing that. I had never considered this limit case.


How I predict a response with NA using logistic regression in R?

Question: I have this data set:
age -- job ------- loan -- y
57 -- retired - - -  yes -- no
44 -- admin - - --   no -- no
39 -- unknown --   no --  no
47 -- services --  no -- yes
41 -- admin  -----    no -- NA
51 -- teacher  ---  yes --no
45 -- unknown -- no -- yes
57 -- retired ------   no -- no
42 -- teacher -----   no  --NA
30 -- student -----   no -- NA
I want to predict all the values of y by using logistic regression, but I get only 7 out of 10 predictions. So, it omits the cases with y==NA.
Here is my codes:
 fit <- glm(y~ age+ as.factor(job)+ as.factor(loan), data= mydat, family=binomial)
 predict( fit, type="response", na.action=na.pass)

How I can predict the response value y even in cases with missing values?
Answer: Your question is a bit confusing because you either want a mulinomial logit/probit model, where NA is a third category of outcome or you want an imputation model to fill-in values of y based on the other data. As @Roland has answered, you're not going to be able to predict missing values using a binary outcome model provided by glm.
If the former (multinomial logit/probit model), take a look at your options on the Econometrics Task View.
If the latter (imputation), you also have lots of options like Amelia, mice, and mi.
Comment: Check out Amelia, which will give you a list containing several imputed dataframes. It's very easy to use.
Comment: Thank you Thomas, yes I actually try to impute the NA values by using logistic regression. I have already used mice package, but what I try to do here is to get a new data set with the imputed values; because I couldn't get it using mice. Do you have an idea about that?
Answer: If you don't have data for something, you cannot model it and consequently not predict. E.g., you have no data for students with no loans. So how do you suggest to predict y for students with no loans? That would require magic.
On the other hand, if you omit the job from your model or recode somehow (e.g., beginner/experienced/unknown) you could be able to predict all cases. The best advice would of course be to get more data.
Comment: Thank you Roland, I thought it's possible to predict the response (even if it's a missing value)if we have all the values of explanatory variables along with their parameters.
Comment: But for each combination of predictor factor variables you need at least some response values. Otherwise the information is simply not there.
Answer: Delete "student" from your data and use the newdata argument in predict:
predict(fit,newdata=mydat,type="response")


Django queries to retrieve specific attribute

Question: max_shoots = player.objects.all().aggregate(Max('Num_baskets')['Num_baskets__max']
name1 = player.objects.get(Num_baskets=max_shoots)
return render(
    request,
    'index.html',
    context={'max_shoots':max_shoots, 'name':name1 },
)

Here player is our class name. we need to retrieve a specific attribute(eg:roll no. of a 'name1').could you please help me to solve it.using max_shoots that we already retrieved. I want to know Django query to retrieve above information.
Answer: You can do like this
player_obj = player.objects.order_by('-Num_baskets').first()
#do player_obj.roll_no


Why angular 2 need node.js

Question: I don't have experience in front-end but I want to create a simple app using Angular 2.
Why do I need to install Node.js as a prerequisite step? Why does Angular use Node.js?
Answer: There are a couple of things that Angular uses Node.js for:

Installing and managing packages. From the Quickstart tutorial:

Angular application developers rely on the npm package manager to install the libraries and packages their apps require. The Angular team recommends the starter-set of packages specified in the dependencies and devDependencies sections.

Compiling the TypeScript used into JavaScript that the browser understands - browsers can't process TypeScript natively and the SystemJS imports used in your code aren't supported in browsers yet:

We strongly recommend transpiling (AKA compiling) to JavaScript during a build phase before running the application for several reasons including:
We see compiler warnings and errors that are hidden from us in the browser.
Precompilation simplifies the module loading process and it's much easier to diagnose problems when this is a separate, external step.
Precompilation means a faster user experience because the browser doesn't waste time compiling.
We iterate development faster because we only recompile changed files. We notice the difference as soon as the app grows beyond a handful of files.
Precompilation fits into a continuous integration process of build, test, deploy.
Comment: So if I want to develop angular 2 application with VS 2013/2015 I dont need Node js and Npm correct? Since VS comes with Typescript plugin and web server. correct me if i am wrong
Comment: I would imagine that it is *possible*, but I don't think it's a great idea. If you don't have `npm`, you'll be unable to import other libraries, and you'll be completely tied to VS. I haven't tested it myself though, so I don't really know.
Answer: node.js is required in order to install the library using the node package manager (npm).
It is not required to run an app using angular2, only to build it.
Answer: For any modern JS based application, as the complexity grows, the app becomes difficult to manage.
In order to make developing and managing complex applications simpler, there are frameworks such as Angular, React etc. and they provide number of tools for the same.
These tools are linting, scaffolding, running unit test cases, starting web server for local development, minify and creating build for the production use etc.
These tools are based on NodeJS as it is JavaScript only and therefore can be customize as per developers needs.
And that's the reason you need Node.js for Angular2 development.

Why angular 2 need node.js


Weak topology Banach space with separable dual

Question: Let $B$ be a Banach space with separable dual and let $(f_n)$ be dense and countable in $B^*$. Let $\tilde{\tau}$ be the initial topology associated to the collection of maps $f_n : B\rightarrow \mathbb{R}$.
My question: is $\tilde{\tau}$ the standard weak topology on $B$?
My attempt :
Let $\tau$ denote the weak topology on $B$. Obviously, $\tau$ makes all the $f_n$'s continuous. Being $\tilde{\tau}$ the smallest doing so, $$\tilde{\tau}\subseteq \tau.$$
Conversely, I tried to reason with the basis of such topologies. Fix arbitrary $x_0 \in B$, $\epsilon >0$ and $g_1,...,g_N \in B^*$ and recall that $U_{x_0}(\epsilon,g_1,...,g_N):= \{x \in B \colon |g_i(x-x_0)|< \epsilon, \ i=1,...,N\}$ is open neighborhood of $x_0$ in $\tau$. To conclude, it is sufficient to show that there exists an open neighborhood $\tilde{U}$ of $x_0$ in $\tilde{\tau}$ so that $\tilde{U}\subset U_{x_0}(\epsilon,g_1,...,g_N)$.
My guess is to pay some $\tilde{\epsilon}$ in requiring $f_{n_i} \approx g_i$ for all $i=1,..,N$ and define $\tilde{U}:= U_{x_0}(\tilde{\epsilon},f_{n_1},...,f_{n_N})$, but I am struggling in bounding the term $|f_{n_i}(x)-g_i(x)|$ uniformly on $x$.
Comment: Welcome to MSE. Nice first question!
Answer: If $(f_n)$ is supposed to be dense in the norm of $B^{*}$ then this is quite easy. Let $f \in B^{*}$.  There exist $n_1<n_2<...$ such that $\|f_{n_i}-f\| \to 0$. This implies that $f_{n_i} \to f$ uniformly on any ball in $B$. Since each $f_{n_i}$ is continuous w.r.t. $\overline {\tau}$ it follows that $f$ is also continuous w.r.t $\overline {\tau}$. Thus every $f \in B^{*}$ is continuous w.r.t $\overline {\tau}$. Hence $\tau \subset \overline {\tau}$.
Comment: Absolutely right, thanks !


nested routing in angular2 not working

Question: How to manage nested link in angular2.
for eg. I have two file :
app.component.ts
import { Component, forwardRef } from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
import {HTTP_PROVIDERS}    from 'angular2/http';
import 'rxjs/Rx';

import { HeroService } from './hero.service';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
import { TestComponent } from './test.component';
import { HeroDetailComponent } from './hero-detail.component';
import { LinkComponent } from './link.ts'

@Component({
  selector: 'my-app',
  template: `

{{title}}

    <link111></link111>
    <router-outlet></router-outlet>
  `,
  styleUrls: ['app/app.component.css'],
  directives: [ROUTER_DIRECTIVES, forwardRef(() => LinkComponent)],
  providers: [
    HTTP_PROVIDERS,
    ROUTER_PROVIDERS,
    HeroService
  ]
})
@RouteConfig([
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: DashboardComponent,
    useAsDefault: true
  },
  {
    path: '/detail/:id',
    name: 'HeroDetail',
    component: HeroDetailComponent
  },
  {
    path: '/heroes',
    name: 'Heroes',
    component: HeroesComponent
  },
  {
    path: '/test',
    name: 'Test',
    component: TestComponent
  }
])
export class AppComponent {
  title = 'Tour of Heroes';
}

link.ts
import {Component} from 'angular2/core';
import { ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
@Component({
    selector:'link111',
    template:`

          Dashboard
          Heroes
          Test

    `,
    directives: [ROUTER_DIRECTIVES],
    providers: [ROUTER_PROVIDERS]
})
export class LinkComponent {
}

When [routerLink] define in app.component.ts in place of link111 tag it works, but when i separate it into different file it doesn't work.
please help me, Thanks.
Answer: When [routerLink] define in app.component.ts in place of link111 tag it works, because angular look routing from the
    main root file(that is app.ts in your case), but when you separate it into different file it doesn't work because
    than routing is defined in the root file but you are calling from childern (i.e not from parent). so to resolve this
    change this like this -
      Dashboard
      Heroes
      Test

because If the route begins with ./, the router will look up the current components childern route from the root of the app.

From officials -
The first route name should be prepended with /, ./, or ../. If the route begins with /, the router will look up the route from the root of the app. If the route begins with ./, the router will instead look in the current component's children for the route. And if the route begins with ../, the router will look at the current component's parent.

for more info refer this -

https://angular.io/docs/ts/latest/api/router/RouterLink-directive.html
How to use child routes in Angular 2.
Angular 2 router examples + @RouteConfig typing support
Comment: Change the link as you given above, URL change but  component template doesn't change.
Comment: whats the error you got ? could you regenrate your problem on plunkr ?

nested routing in angular2 not working


What are these constructions similar to a pushout and pullback called?

Question: Apparently, a colimit also reverses the index category. So what are these called?
Comment: I only recognize two compositions $f\circ g$, $f\circ h$ on the right above and again two composition $g\circ f$,$h\circ f$ on the left down.
Answer: These are just the existence of compositions of morphisms. Let's take the top right one, for instance. From the left vertex, you have an arow going to the lower vertex and then up to the top vertex. This induces an arrow from the left vertex to the top vertex. That's composition of morphisms. Same with the other three dotted arrows.


Infix to Postfix(Reverse Polish Notation) conversion works with parentheses but not without

Question: Rules of Assignment:

Must have separate Operator class and separate PostFix class containing the conversion method.
Evaluate left to right.
Operators are placed into a Stack.
Only binary operators
Separate Operator class and PostFix class, where PostFix contains the Conversion method.
C#

My Issue:
My conversion works if all/most of the equation is in parentheses. It works without parentheses only if the input is in the order of operations.
I believe I'm just not checking priority properly, but I'm not certain that's the issue. I've rewritten my conversion method 4 times now and spent around 25 hours tweaking and running through the debugger on different iterations of the method, and Googling, but I'm just not comprehending where the issue is in my code. I see it while debugging but I'm not sure what I have to do to fix it, so I figured maybe a third party's perspective would help.
Examples
Incorrect output:
a=5+3/4-(9*8-1)*1         =>        a 5 3 + 4 / 9 8 * 1 -  - 1 * =
      should be       a 5 3 4 / + 9 8 * 1 - - 1 * =

alpha = beta + gamma * delta        =>        alpha beta gamma + delta * =
      should be       alpha beta gamma delta * + =

Correct output:
a = ((((a+b)-c)*d)/(e+1))         =>        a a b +  c -  d *  e 1 +  /  =

alpha = beta * gamma + delta         =>        beta gamma * delta + alpha =

My code
Operator class:
class Operator
{
    private byte precedence = 1;        //Precedence of operator over others
    private char identity = 'x';        //the character behind the operator

    ///
    /// Creates an operator based on the passed character
    ///
    /// <param name="OperatorIn">Character definition of the operator</param>
    public Operator(char OperatorIn)
    {
        identity = OperatorIn;
        switch (OperatorIn)
        {
            case '*':
                precedence = 2;
                break;
            case '/':
                precedence = 2;
                break;
            case '(':
                precedence = 3;
                break;

            case ')':
                precedence = 3;
                break;

            case '=':
                precedence = 3;
                break;
            case '+':
                precedence = 1;
                break;

            case '-':
                precedence = 1;
                break;

            default:
                precedence = 0;
                break;
        }//switch
    }//Operator(char)

    ///
    /// Retrieves the char representation of the operator
    ///
    /// <returns>Char representation of the operator</returns>
    public char ToChar()
    {
        return this.identity;
    }//ToChar()

    ///
    /// Returns the byte value of precedence of the operator
    ///
    /// <returns>byte value of precedence</returns>
    public byte GetPrecedence()
    {
        return this.precedence;
    }
}//Operator

Conversion method:
public static string Convert(string infix)
    {
        #region original
        Stack<Operator> OpStack = new Stack<Operator>();
        String Postfix = String.Empty;
        InfixPostfix.Operator Previous = new Operator('x'),
                              Current = null;   //NextOp = new Operator(infix[infix.IndexOfAny(Ops, i)]);
        char[] Ops = {'+','-','=','*','/'};
        string term = String.Empty;

        foreach(char c in infix)
        {
            if (Ops.Contains(c))                        //if the char is one of the operator chars
            {
                Postfix += term + " ";                  //split term and add to output
                while (OpStack.Count > 0)               //While there's actually operators in the stack
                {
                    Current = OpStack.Pop();            //Assign the operator as Current Operator
                    if (Current.GetPrecedence() < Previous.GetPrecedence())     //If Current Op is less priority than preceding Op
                        Postfix += Current.ToChar() + " ";                      //Output the character of the Op
                    else                                //If Current Op priority is higher than the previous
                    {
                        Previous = Current;             //Store the current as previous to move on
                        OpStack.Push(Current);          //Store current in stack
                        break;                          //Move to next char
                    }//else
                }//while
                OpStack.Push(new Operator(c));          //If stack is empty, push the operator
                term = "";                              // and reset the term to empty
            }//if
            else if (c == ')')                          //If the char is a close paren
            {
                Postfix += term + " ";                  //store the previous characters as a term in postfix
                term = "";                              //establish a new term
                Previous = Current;                     //Set Current as the old Op
                Current = OpStack.Pop();                //Get the new Current op
                while (Current.ToChar() != '(')         //Pop the stack until you get an open paren op
                {
                    Postfix += Current.ToChar() + " ";  //Add the term to the output string
                    //Previous = Current;
                    try
                    {
                        Current = OpStack.Pop();        //Try to pop another operator
                    }//try
                    catch(Exception)                    //If the stack is empty
                    {
                        return "Error! Mismatched parentheses!";    //Then there is a missing/misaligned paren
                    }//catch
                }//while
            }//else if
            else if (c == '(')                          //If the op is an open paren
                OpStack.Push(new Operator(c));          //store it
            else if (c != ' ')                          //If it's an alphanumeric char,
                term += c;                              //build a term with it
        }//foreach
        Postfix += term + " ";                          //add the last term to the output
        while(OpStack.Count > 0)                        //If there are remaining ops on the stack,
        {
            Current = OpStack.Pop();                    //pop them off
            if (Current.ToChar() == '(' || Current.ToChar() == ')') //If there is a paren remaining
                return "Error! Mismatched parentheses!";            // it's because of missing complement or misalignment
            Postfix += Current.ToChar() + " ";              //if regular op, add to output
        }//while
        return Postfix;
    }

Thank you in advance!
Comment: Possible duplicate of [Handling parenthesis while converting infix expressions to postfix expresssions](http://stackoverflow.com/questions/19721072/handling-parenthesis-while-converting-infix-expressions-to-postfix-expresssions)
Answer: Alright, so, I got a few upvotes that indicated there was interest in the answer. My solution was once again trashing what I had and starting over. I sat down and went through the algorithm on paper multiple times then went through it while debugging one line at a time. This led to some "interesting" tweaks just to finish this.
Honestly, what I came up with is disgusting -- at one point I have a for-else if-if-if-while-if. So this thing isn't pretty, and probably is really inefficient. Luckily I don't get graded on efficiency in this class, haha. I just needed to get it done as it's due on Friday and I have an Assembly project to start. Anyway...
Code
Operator class has updated precedence values in the constructor.
public Operator(char OperatorIn)
    {
        identity = OperatorIn;
        switch (OperatorIn)
        {
            case '*':
                precedence = 2;
                break;
            case '/':
                precedence = 2;
                break;

            case '=':
                precedence = 1;
                break;
            case '+':
                precedence = 1;
                break;

            case '-':
                precedence = 1;
                break;

            default:
                precedence = 0;
                break;
        }//switch
    }//Operator(char)

Structure is similar for the Convert method. There's a lot of if(Stack.Count>0) checks which probably indicates bad logic inside loops and other if/whiles. But it seems to work perfectly.
public static string Convert(string infix)
    {
        Stack<Operator> OpStack = new Stack<Operator>();
        String Postfix = String.Empty;
        Operator Previous = new Operator('x'),
                 Current = null;
        char[] Ops = { '+', '-', '=', '*', '/' };
        string term = String.Empty;

        foreach (char c in infix)                           //Iterate through char at a time
        {
            if (c == '(')                                   //If open paren
                OpStack.Push(new Operator(c));              // put on the stack
            else if (c == ')')                              //If close paren
            {
                Postfix += term + " ";                      //Output the term
                term = "";                                  // and clear out the term holder
                Previous = OpStack.Peek();                  //Get a value to know Previous has as real value instead of 'x'
                while (Previous.ToChar() != '(')             // pop until we reach the open paren
                {
                    if (OpStack.Count > 0)
                        Current = OpStack.Pop();                //Current becomes what was on top of the stack
                    if(Current.ToChar() != ')' && Current.ToChar() != '(')
                        Postfix += Current.ToChar() + " ";       //  add to output
                    try                                          //Make sure we have more to pop
                    {
                        Previous = OpStack.Pop();                //Previous becomes what was 2nd on the stack
                    }//try
                    catch (Exception)                            //If there's nothing to pop and we're still in this loop
                    {
                        return "Error! Mismatched parentheses!"; //Mismatched or missing parenthesis
                    }//catch
                }//while
            }//else if
            else if (Ops.Contains(c))                       //If it's an operator
            {
                Postfix += term + " ";                      //output the term
                term = "";                                  // and clear the term holder
                Current = new Operator(c);                  //Assign the current character as Current Op
                if (OpStack.Count > 0)                      //If there are previous ops in stack
                {
                    Previous = OpStack.Peek();              // get top op on stack to compare

                    if (Previous.GetPrecedence() > Current.GetPrecedence() && OpStack.Count > 0)            //Decide between > and =
                    {
                        while (Previous.GetPrecedence() > Current.GetPrecedence() && OpStack.Count > 0)       //Pop until we find lesser precedence op
                        {
                            Previous = OpStack.Pop();           //Remove the compared value from stack
                            Postfix += Previous.ToChar() + " "; //Add the popped ops to output
                            if (OpStack.Count > 0)              //make sure we aren't looping too far
                                Previous = OpStack.Peek();      //assign new value before compare occurs
                        }//while
                    }//if
                    else if(Previous.GetPrecedence() == Current.GetPrecedence() && OpStack.Count > 0 && Previous.ToChar() != '=')       //Decide between > and =
                    {
                        while (Previous.GetPrecedence() == Current.GetPrecedence() && OpStack.Count > 0 && Previous.ToChar() != '=')    //Pop until = precedence found
                        {
                            Previous = OpStack.Pop();           //Remove the compared value from stack
                            Postfix += Previous.ToChar() + " "; //Add the popped ops to output
                            if (OpStack.Count > 0)              //make sure we aren't looping too far
                                Previous = OpStack.Peek();      //assign new value before compare occurs
                        }//while
                    }//else if
                    OpStack.Push(Current);                  //Once a <= op is found, store the Current op
                    continue;
                }//if
                else                                        //If there are no ops on stack
                    OpStack.Push(Current);                  // store it immediately
            }//else if
            else if (c != ' ')                              //If alphanumeric
                term += c;                                  // add into term holder
        }//foreach
        Postfix += term + " ";                              //There will be a term left over after the final c, so output it
        while(OpStack.Count > 0)                            //There may also be ops left, so pop them
        {
            Current = OpStack.Pop();
            if (Current.ToChar() == '(' || Current.ToChar() == ')') //If there is a paren remaining
                return "Error! Mismatched parentheses!";            // it's because of missing complement or misalignment
            Postfix += Current.ToChar() + " ";                      //output the operator
        }//while
        return Postfix;
        }//Convert v2


LDA as the dimension reduction before or after partitioning

Question: I am doing a classification and I have this question about using linear discriminant analysis (LDA) just for dimension reduction:
Shall the LDA be applied on whole feature matrix including train and test data and then (after reducing the dimension of data) do the partitioning of feature matrix to provide train and test sets for classification? Is it true?
Then, suppose we need to partition the data before applying the LDA. How is it possible to do the classification on the test data using the Matlab's internal classifiers like kNN and SVM?
Answer: LDA works with the covariance(correlation) matrix based on the input features.  It's best to use cross validation (CV), something like 10-fold, during which you randomly split the objects in the entire dataset into 10 partitions or "folds."  Then apply LDA to objects (i.e., train) in the first 9 folds and predict class membership for the objects left out of training in the 10th fold, and then increment elements of the confusion matrix accordingly.  Next, apply LDA to objects in the first 8 folds, and 10th fold, and predict class for objects in the 9th fold.  Repeat the above until you have predicted class for objects in all 10 of the folds which are left out of LDA each time.  So, LDA will be applied 10 times to your data in this case.
It's inefficient to split a dataset into training and testing one time and then apply a classification algorithm.  Some of the best work on CV was done by Ron Kohavi at Stanford-U, and his classic paper on CV is here.
There's another CV method called leave one out CV (LOOCV), which performs the same operations outlined above, but which predicts class membership for each object when it is left out of training singly.  (thus, here, a fold has one object).  LOOCV gets computational expensive and is inefficient for large datasets with $n$ samples, since you'd have to run LDA $n$ times.
I also don't recommend LDA as a first choice, since it looks at correlation between features -- if you have highly correlated features, their corr matrix could be positive semi-definite or singular, rather than positive definite -- called "pathologies" among corr matrices.
It's better to first employ multivariate linear regression (LREG), for which you set $\mathbf{y}_i=(-1,+1,-1,-1)$ for e.g. an object whose true class is 2 for a 4-class problem, and then assign this example object to class 1 if the predicted y-hat is e.g. $\mathbf{\hat{y}}_i=(+0.35,-0.7,-1.2,-2.6)$.  If the prediction accuracy for LREG 10-fold CV is very poor, then maybe your dataset is not linearly separable.  Then you know that LDA may not be the best choice, but rather, maybe kNN will work better.  Certainly, when data are not very linearly separable, SVM with an RBF kernel function will probably work the best -- but never use SVM first, like most students do who know nothing about first determining whether the data are linearly separable.  I like to use LREG and kNN first before any other classifier -- since it lets me know if linear prediction works.  For very large datasets, kNN is very fast.  Also, ID3 is a nice classifier.
But if you start with LDA, you're committed to a lot of excess baggage involving quality of the correlation matrix from the standpoint of eigendecomposition -- which is not an optimal method if linear separability is low, and there are non-linearities present.  LDA is like a school bus, while kNN is like a go-kart.
Comment: Thanks @wrtsvkrfm for your answer. Regarding your point about leave one out approach, I have one question. As I use the SVM and KNN of internal Matlab, then how is it possible to do the test on one sample after transforming that sample with LDA matrix?
Comment: The left out sample cannot be in the training data which are fed into a classifier e.g., (LDA).  MatLab should have a LOOCV method, which will leave out each sample singly during run time.


how to wait for element with timeouts in javascript

Question: I am looking for a way to wait for element to be displayed in DOM and throw a timeout exception when it is not displayed in a give time. How can I accomplish that? I have this take, but sure it will not work.
function waitForElement(element, timeout) {
    return new Promise((resolve, reject) => {
        const t = setTimeout(() => {
            let queryInterval = setInterval(() => {
                const isElementVisible = document.contains(element);
                if (!isElementVisible) {
                    clearInterval(queryInterval);
                    clearTimeout(t);
                    resolve(true);
                }
            }, 10);
            console.log("Timeout!");
            clearTimeout(t);
            reject("Time Out!");
        }, timeout);
    });
}

Answer: Check out the mutation observer api.
Here's a sample implementation that returns a Promise that either resolves with the added node or rejects if the node doesn't appear within the allotted time.
It accomplishes this by setting up a MutationObserver to watch for a node to appear that passes the given testFn. It sets a timeout that disconnects the observer and rejects after a given amount of time. If the observer sees the node appear before the timeout expires it clears the timeout and resolves with the node.

// Waits for a node that passes testFn to appear and returns it.
// Gives up and rejects after 'wait' ms.
// Returns a Promise that resolves with the found node.
const waitForElement = (testFn, wait = 1000) => {

  return new Promise((resolve, reject) => {

    // create an observer using onDomChange (defined below)
    const observer = new MutationObserver(onDomChange);

    // watch the container for childList changes
    observer.observe(container, {
      childList: true
    });

    // set a countdown to give up and reject
    const timeout = setTimeout(
      () => {
        // when the timeout expires, stop watching…
        observer.disconnect();
        // and reject
        reject('Never showed up.')
      },
      wait // how long to wait before rejecting
    );

    // the callback for observed dom changes
    function onDomChange(mutations, observer) {
      // find an addedNode that passes the testFn in the mutations
      const node = mutations.map(m => [...m.addedNodes]).flat().find(testFn);

      // if we find a match…
      if (node) {
        // stop the rejection timeout
        clearTimeout(timeout);

        // stop observing
        observer.disconnect();

        // and resolve with the found node
        resolve(node);
      }
    }
  });
}

// convenience for creating a div with the given text
const d = (text) => {
  const el = document.createElement('div');
  el.className = 'bananas';
  el.innerText = text;
  return el;
}

// test the waitForElement with the given delay
async function go(delay) {
  const container = document.getElementById('container');

  // wait for the specified duration before adding a div with the delay as the text
  setTimeout(() => container.appendChild(d(delay)), delay);

  try {
    // wait for the element to appear
    const el = await waitForElement(n => n.innerText.endsWith(delay));
    // append some text to the content
    el.innerText += ' - found it.'
    // add a css class
    el.classList.add('found');
  } catch (e) {
    // log an error if it didn't appear in time
    console.error(`rejected for ${delay}`);
  }
}

// default wait time is 1000ms, so…
go(300); // under the 1000ms wait time. finds it.
go(5000); // takes too long. rejects
go(100); // finds it.
go(600); // finds it.
go(3000); // rejects
.bananas {
  margin-bottom: .5em;
  padding: 0.25em;
  background: #ffff99;
}

.found {
  background: tomato;
  color: bisque;
}

Comment: Updated with sample implementation. (Which I admit wasn't *quite* as trivial as I thought it would be.)