问:
How to install MIT Scheme on Mac?
I want to install MIT Scheme on my Mac, I have downloaded the MacOS X binary(x86-64).

However, I could not make it work using Mac Terminal.

I have tried to follow these articles:

Installing MIT/GNU Scheme on Mac OS X Leopard

<s>Installing MIT Scheme on Mac OS X</s>

but it seems out of date and does not work.

So, I'm looking for a simple method which allows me to write Scheme code using Mac Terminal.

I have struggled for hours to try to install it.

答:
UPDATE FOR MAC OS HIGH SIERRA:

Worked for me just by executing (if you are using Homebrew):

brew install mit-scheme

Title: How to install MIT Scheme on Mac?


来源: stackexchange

问:
How do I make the "action" of this card game keep executing until a winner is found?
I created this card game that asks the user for an action. "attack" and "swap". they both work fine on the first execution, but how do I make it so that the system keeps asking the user for an action until one of the player wins?

This contains my code for the class GameMaster that the GameConsole will reference. It has links to two other classes I have called Player and Card.

```<code>import java.util.*;
public class GameMaster
{
private int turnCounter = 0;
private ArrayList<Card> deck;
private boolean isThereWinner;
private Player player1;
private Player player2;
public GameMaster (Player a, Player b) //initializes values
{
    turnCounter = turnCounter + 1;
    player1 = a;
    player2 = b;
    deck = new ArrayList<Card>();
    assembleDeck();
    dealCard();
}
private void assembleDeck() //given order of cards
{
    deck.add( new Card( "Dragon", "Aquira", 174, 26 ) );
    deck.add( new Card( "Ghost", "Brawn", 130, 48 ) );
    deck.add( new Card( "Fairy", "Cerulea", 162, 29 ) );
    deck.add( new Card( "Dragon", "Demi", 147, 28 ) );
    deck.add( new Card( "Ghost", "Elba", 155, 37 ) );
    deck.add( new Card( "Fairy", "Fye", 159, 42 ) );
    deck.add( new Card( "Dragon", "Glyede", 129, 26 ) );
    deck.add( new Card( "Ghost", "Hydran", 163, 35 ) );
    deck.add( new Card( "Fairy", "Ivy", 146, 45 ) );
    deck.add( new Card( "Dragon", "Jet", 170, 24 ) );
    deck.add( new Card( "Ghost", "Kineti", 139, 21 ) );
    deck.add( new Card( "Fairy", "Levi", 160, 43 ) );
    deck.add( new Card( "Dragon", "Meadow", 134, 29 ) );
    deck.add( new Card( "Ghost", "Naidem", 165, 26 ) );
    deck.add( new Card( "Fairy", "Omi", 145, 21 ) );
    deck.add( new Card( "Dragon", "Puddles", 170, 34 ) );
    deck.add( new Card( "Ghost", "Quarrel", 151, 29 ) );
    deck.add( new Card( "Fairy", "Raven", 168, 32 ) );
    deck.add( new Card( "Dragon", "Surge", 128, 27 ) );
    deck.add( new Card( "Ghost", "Takiru", 140, 26 ) );
    deck.add( new Card( "Fairy", "Ustelia", 163, 47 ) );
    deck.add( new Card( "Dragon", "Verwyn", 145, 25 ) );
    deck.add( new Card( "Ghost", "Wyverin", 158, 32 ) );
    deck.add( new Card( "Fairy", "Xios", 155, 27 ) );
    deck.add( new Card( "Dragon", "Yora", 159, 44 ) );
    deck.add( new Card( "Ghost", "Zulu", 125, 46 ) );
}
public java.lang.String play (java.lang.String action) // lets player enter action swap or attack
{
   if (turnCounter%2==1) //player 1's turn
   {
        if (action.equals("swap")) // if player one enters "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " swaps out " + player1.getActiveCard().getName()+".");
            player1.swap();

        }
        else if (action.equals("attack")) // if player one enter "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " attacks with " + player1.getActiveCard().getName()+".");
            dealDamage(player1.getActiveCard(), player2.getActiveCard());

            if (player2.getActiveCard().getHealth()<1) //if player 2's health goes below 1
            {
                player2.discard();
                System.out.println("   "+player2.getName() + " discards " + player2.getActiveCard().getName());
                player2.drawCard(deck.get(0));
                System.out.println(player2.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) // if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player1.claimToken();
                System.out.println("   "+player1.getName() + " gets a token!");
                if (player1.getTokens()==3) //if player1 kills three of player2's cards = 3 tokens
                {
                    hasWinner();
                    System.out.println(player1.getName() + " wins!");
                }
            }
        }
    }
    else if (turnCounter%2==0) //player 2's turn
    {
        if (action.equals("swap")) //if player 2 chooses "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getActiveCard().getName() + " swaps out " + player2.getActiveCard().getName());
            player2.swap();

        }
        else if (action.equals("attack")) //if player two chooses "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getName() + " attacks with " + player2.getActiveCard());
            dealDamage(player2.getActiveCard(), player1.getActiveCard());
            if (player1.getActiveCard().getHealth()<1) //if player 1's health drops below 1
            {
                player1.discard();
                System.out.println("   "+player1.getName() + " discards " + player1.getActiveCard().getName());
                player1.drawCard(deck.get(0));
                System.out.println("   "+player1.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) //if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player2.claimToken();
                System.out.println("   "+player2.getName() + " gets a token!");
                if (player2.getTokens()==3) //if player 2 kills 3 of player1's cards = get three tokens
                {
                    hasWinner();
                    System.out.println(player2.getName() + " wins!");
                }
            }

        }

   }
   return "";
}
public boolean checkResistance(java.lang.String type1, java.lang.String type2) //checks for resistance
{
    if (type1.equals("Dragon")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public boolean checkWeakness(java.lang.String type1, java.lang.String type2) //checks for weakness
{
    if (type1.equals("Dragon")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public java.lang.String dealCard() //altertately deals cards to each player at the start of the game
{
    if (turnCounter==1)
    {
        for (int i=0; i<5; i++)
        {
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(i).getName()+".");
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(i).getName()+".");
        }
    }
    else if (turnCounter%2==1) //odd turns = player 1
    {
        if (player1.playerHand.size()==5)
        {
            System.out.println(player1.getName() + "'s hand is full.");
        }
        else if (player1.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter + 1;
    }
    else if (turnCounter%2==0) //even turns = player2
    {
        if (player2.playerHand.size()==5)
        {
            System.out.println(player2.getName() + "'s hand is full.");
        }
        else if (player2.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter;
    }

    return "";
}
public java.lang.String dealDamage(Card inPlay, Card target) //calculates how much damage a card receives, taking into account weakness and resistance
{
    if (checkResistance(target.getType(),inPlay.getType())==true) //if there is resistance
    {
        System.out.println("      "+target.getType() +" is resistant to "+inPlay.getType()+".");
        target.takeHalfDamage(inPlay.getPower());
        checkResistance(inPlay.getType(),target.getType());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()/2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else if (checkWeakness(target.getType(),inPlay.getType())==true) //if there is weakness
    {
        System.out.println("      "+target.getType() +" is weak to "+inPlay.getType()+".");
        target.takeDoubleDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()*2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else //if it does normal damage
    {
        target.takeDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    return "";
}
public boolean hasWinner() //as long as there is no winner, it is false
{
    return true;
}
public java.lang.String gameReport() //prints out a summary of a game as well as each player's stats
{
    System.out.println("___=== GAME SUMMARY ===___");
    System.out.println("This game lasted "+turnCounter+" turns.");
    System.out.println();
    System.out.println(player1.getName());
    System.out.println("        "+player1.statusReport());
    System.out.println();
    System.out.println(player2.getName());
    System.out.println("        "+player2.statusReport());
    return "";

}
</code>```

This is the runner I currently have called GameConsole.

```<code>import java.util.Scanner;
public class GameConsole
{
    public static void main (String[] args)
    {
    Scanner player = new Scanner(System.in);
    System.out.print("Player 1: ");
    String player1String = player.next(); // input player1 name
    System.out.print("Player 2: ");
    String player2String = player.next(); // input player2 name
    System.out.println("Welcome, "+player1String+" and "+player2String+"!");
    System.out.println("The game begins.");
    Player player1 = new Player(player1String); // turns player1's String name into an object
    Player player2 = new Player(player2String); // turns player2's Strign name into an object
    System.out.println();
    GameMaster game = new GameMaster(player1,player2); // uses the player1 and player2 objects as objects for the GameMAster
    System.out.println();
    Scanner move = new Scanner(System.in);
    System.out.print("Attack or Swap? ");
    String whatMove = move.next(); //input for action

    //i tried putting this in a while-loop but the action won't even execute once
    game.play(whatMove); // executes play for action
    }
}
</code>```

When I run it, this is what happens //user input is in ALL CAPS

```<code>Player 1: ADAM
Player 2: BOB
Welcome, ADAM and BOB!
The game begins.
//space
ADAM draws Aquira.
BOB draws Brawn.
ADAM draws Cerulea.
BOB draws Demi.
ADAM draws Elba.
BOB draws Fye.
ADAM draws Glyede.
BOB draws Hydran.
ADAM draws Ivy.
BOB draws Jet.
//space
Attack or Swap? ATTACK    //SWAP works fine too
   ADAM attacks with Aquira.
      Ghost is weak to Dragon.
   Aquira deals 52 damage on Brawn.
   Brawn has 78 left.
//and then it just stops
</code>```

tbh I'm not completely sure if my code works, but because I don't know how to repeat the action, I wouldn't know...I hope what I said made sense...I'm new to CS so I would appreciate any amount of help.

答:
Of course it only runs once - the play() command is only called once in your code, outside of any loops. As it is right now, the code is running perfectly as intended.

You need to put it in a loop, most likely a while loop based on your requirements. The comments said you've already tried that and it didn't work, so why don't you show that code? That way we can at least figure out what's making the code behave not as intended.

By the way, the hasWinner() function you have seems to be unfinished, as all it does is return true all the time. If you used while(!hasWinner()) as the while condition, of course it won't run at all.

ContentLicense: CC BY-SA 3.0

Body:
I created this card game that asks the user for an action. "attack" and "swap". they both work fine on the first execution, but how do I make it so that the system keeps asking the user for an action until one of the player wins?

This contains my code for the class GameMaster that the GameConsole will reference. It has links to two other classes I have called Player and Card.

import java.util.*;
public class GameMaster
{
private int turnCounter = 0;
private ArrayList<Card> deck;
private boolean isThereWinner;
private Player player1;
private Player player2;
public GameMaster (Player a, Player b) //initializes values
{
    turnCounter = turnCounter + 1;
    player1 = a;
    player2 = b;
    deck = new ArrayList<Card>();
    assembleDeck();
    dealCard();
}
private void assembleDeck() //given order of cards
{
    deck.add( new Card( "Dragon", "Aquira", 174, 26 ) );
    deck.add( new Card( "Ghost", "Brawn", 130, 48 ) );
    deck.add( new Card( "Fairy", "Cerulea", 162, 29 ) );
    deck.add( new Card( "Dragon", "Demi", 147, 28 ) );
    deck.add( new Card( "Ghost", "Elba", 155, 37 ) );
    deck.add( new Card( "Fairy", "Fye", 159, 42 ) );
    deck.add( new Card( "Dragon", "Glyede", 129, 26 ) );
    deck.add( new Card( "Ghost", "Hydran", 163, 35 ) );
    deck.add( new Card( "Fairy", "Ivy", 146, 45 ) );
    deck.add( new Card( "Dragon", "Jet", 170, 24 ) );
    deck.add( new Card( "Ghost", "Kineti", 139, 21 ) );
    deck.add( new Card( "Fairy", "Levi", 160, 43 ) );
    deck.add( new Card( "Dragon", "Meadow", 134, 29 ) );
    deck.add( new Card( "Ghost", "Naidem", 165, 26 ) );
    deck.add( new Card( "Fairy", "Omi", 145, 21 ) );
    deck.add( new Card( "Dragon", "Puddles", 170, 34 ) );
    deck.add( new Card( "Ghost", "Quarrel", 151, 29 ) );
    deck.add( new Card( "Fairy", "Raven", 168, 32 ) );
    deck.add( new Card( "Dragon", "Surge", 128, 27 ) );
    deck.add( new Card( "Ghost", "Takiru", 140, 26 ) );
    deck.add( new Card( "Fairy", "Ustelia", 163, 47 ) );
    deck.add( new Card( "Dragon", "Verwyn", 145, 25 ) );
    deck.add( new Card( "Ghost", "Wyverin", 158, 32 ) );
    deck.add( new Card( "Fairy", "Xios", 155, 27 ) );
    deck.add( new Card( "Dragon", "Yora", 159, 44 ) );
    deck.add( new Card( "Ghost", "Zulu", 125, 46 ) );
}
public java.lang.String play (java.lang.String action) // lets player enter action swap or attack
{
   if (turnCounter%2==1) //player 1's turn
   {
        if (action.equals("swap")) // if player one enters "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " swaps out " + player1.getActiveCard().getName()+".");
            player1.swap();

        }
        else if (action.equals("attack")) // if player one enter "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " attacks with " + player1.getActiveCard().getName()+".");
            dealDamage(player1.getActiveCard(), player2.getActiveCard());

            if (player2.getActiveCard().getHealth()<1) //if player 2's health goes below 1
            {
                player2.discard();
                System.out.println("   "+player2.getName() + " discards " + player2.getActiveCard().getName());
                player2.drawCard(deck.get(0));
                System.out.println(player2.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) // if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player1.claimToken();
                System.out.println("   "+player1.getName() + " gets a token!");
                if (player1.getTokens()==3) //if player1 kills three of player2's cards = 3 tokens
                {
                    hasWinner();
                    System.out.println(player1.getName() + " wins!");
                }
            }
        }
    }
    else if (turnCounter%2==0) //player 2's turn
    {
        if (action.equals("swap")) //if player 2 chooses "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getActiveCard().getName() + " swaps out " + player2.getActiveCard().getName());
            player2.swap();

        }
        else if (action.equals("attack")) //if player two chooses "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getName() + " attacks with " + player2.getActiveCard());
            dealDamage(player2.getActiveCard(), player1.getActiveCard());
            if (player1.getActiveCard().getHealth()<1) //if player 1's health drops below 1
            {
                player1.discard();
                System.out.println("   "+player1.getName() + " discards " + player1.getActiveCard().getName());
                player1.drawCard(deck.get(0));
                System.out.println("   "+player1.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) //if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player2.claimToken();
                System.out.println("   "+player2.getName() + " gets a token!");
                if (player2.getTokens()==3) //if player 2 kills 3 of player1's cards = get three tokens
                {
                    hasWinner();
                    System.out.println(player2.getName() + " wins!");
                }
            }

        }

   }
   return "";
}
public boolean checkResistance(java.lang.String type1, java.lang.String type2) //checks for resistance
{
    if (type1.equals("Dragon")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public boolean checkWeakness(java.lang.String type1, java.lang.String type2) //checks for weakness
{
    if (type1.equals("Dragon")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public java.lang.String dealCard() //altertately deals cards to each player at the start of the game
{
    if (turnCounter==1)
    {
        for (int i=0; i<5; i++)
        {
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(i).getName()+".");
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(i).getName()+".");
        }
    }
    else if (turnCounter%2==1) //odd turns = player 1
    {
        if (player1.playerHand.size()==5)
        {
            System.out.println(player1.getName() + "'s hand is full.");
        }
        else if (player1.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter + 1;
    }
    else if (turnCounter%2==0) //even turns = player2
    {
        if (player2.playerHand.size()==5)
        {
            System.out.println(player2.getName() + "'s hand is full.");
        }
        else if (player2.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter;
    }

    return "";
}
public java.lang.String dealDamage(Card inPlay, Card target) //calculates how much damage a card receives, taking into account weakness and resistance
{
    if (checkResistance(target.getType(),inPlay.getType())==true) //if there is resistance
    {
        System.out.println("      "+target.getType() +" is resistant to "+inPlay.getType()+".");
        target.takeHalfDamage(inPlay.getPower());
        checkResistance(inPlay.getType(),target.getType());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()/2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else if (checkWeakness(target.getType(),inPlay.getType())==true) //if there is weakness
    {
        System.out.println("      "+target.getType() +" is weak to "+inPlay.getType()+".");
        target.takeDoubleDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()*2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else //if it does normal damage
    {
        target.takeDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    return "";
}
public boolean hasWinner() //as long as there is no winner, it is false
{
    return true;
}
public java.lang.String gameReport() //prints out a summary of a game as well as each player's stats
{
    System.out.println("___=== GAME SUMMARY ===___");
    System.out.println("This game lasted "+turnCounter+" turns.");
    System.out.println();
    System.out.println(player1.getName());
    System.out.println("        "+player1.statusReport());
    System.out.println();
    System.out.println(player2.getName());
    System.out.println("        "+player2.statusReport());
    return "";

}

This is the runner I currently have called GameConsole.

import java.util.Scanner;
public class GameConsole
{
    public static void main (String[] args)
    {
    Scanner player = new Scanner(System.in);
    System.out.print("Player 1: ");
    String player1String = player.next(); // input player1 name
    System.out.print("Player 2: ");
    String player2String = player.next(); // input player2 name
    System.out.println("Welcome, "+player1String+" and "+player2String+"!");
    System.out.println("The game begins.");
    Player player1 = new Player(player1String); // turns player1's String name into an object
    Player player2 = new Player(player2String); // turns player2's Strign name into an object
    System.out.println();
    GameMaster game = new GameMaster(player1,player2); // uses the player1 and player2 objects as objects for the GameMAster
    System.out.println();
    Scanner move = new Scanner(System.in);
    System.out.print("Attack or Swap? ");
    String whatMove = move.next(); //input for action

    //i tried putting this in a while-loop but the action won't even execute once
    game.play(whatMove); // executes play for action
    }
}

When I run it, this is what happens //user input is in ALL CAPS

Player 1: ADAM
Player 2: BOB
Welcome, ADAM and BOB!
The game begins.
//space
ADAM draws Aquira.
BOB draws Brawn.
ADAM draws Cerulea.
BOB draws Demi.
ADAM draws Elba.
BOB draws Fye.
ADAM draws Glyede.
BOB draws Hydran.
ADAM draws Ivy.
BOB draws Jet.
//space
Attack or Swap? ATTACK    //SWAP works fine too
   ADAM attacks with Aquira.
      Ghost is weak to Dragon.
   Aquira deals 52 damage on Brawn.
   Brawn has 78 left.
//and then it just stops

tbh I'm not completely sure if my code works, but because I don't know how to repeat the action, I wouldn't know...I hope what I said made sense...I'm new to CS so I would appreciate any amount of help.


问:
Pandas: Join Date and Time into one datetime column
I have a dataframe with 13 columns, where two columns are "Date" and "Time".

I would like to
1) join "Date" and "Time" and
2) format the result correctly (DD.MM.YYYY HH:MM:SS)

```<code>        Date    Time
0   2012-09-27  00:40:20
1   2012-09-27  07:24:37
2   2012-09-27  07:25:08
3   2012-09-27  07:43:48
4   2012-09-27  07:44:27
5   2012-09-27  07:55:16
6   2012-09-27  08:04:19
7   2012-09-27  08:08:21
8   2012-09-27  08:09:08
9   2012-09-27  08:15:30
10  2012-09-27  08:15:35
</code>```

So I try:

```<code>>type(df["Date"])
pandas.core.series.Series
</code>```

And I think to myself "Why not convert them both in to string representations and manipulate them that way?"

```<code>>g = df["Time"].astype(str)
>type(g)
pandas.core.series.Series
</code>```

"What?! It's still a Series?!"

So I try to be creative:

```<code>>f = df["Date"].astype(str) + " " + df["Time"].astype(str)
>f
0     2012-09-27 00:40:20
1     2012-09-27 07:24:37
2     2012-09-27 07:25:08
3     2012-09-27 07:43:48
</code>```

"Hey! That works! No let's just get the format right (DD.MM.YYYY HH:MM:SS)"

```<code>>#dt.strptime(f, '%Y-%m-%d %H:%M:%S')
TypeError: strptime() argument 1 must be str, not Series
</code>```

"Still a Series...hmmm....Obviously it won't let itself be converted. Let's try something else"

```<code>>f = p.concat([df["Date"], df["Time"]], axis=1)
>f
        Date    Time
0   2012-09-27  00:40:20
1   2012-09-27  07:24:37
2   2012-09-27  07:25:08
</code>```

"Nice! But.... Isn't this TWO columns still...?"

```<code>>f.shape
(100,2)
</code>```

"Right...back to square one...."

I'm out of ideas....

Anyone?

答:
.astype(str) works on the elements of Series, not the Series itself, so of course type(df["Time"].astype(str)) == pd.Series. This seems to be the source of much of your confusion, you're acting on the Series, not its elements.

A solution (there maybe an easier way) is to just loop over the series:

```<code>dts = [datetime.datetime.strptime(elem, '%Y-%m-%d%H:%M:%S')
       for elem in df['Date'] + df['Time']]

fmted = [elem.strftime('%d-%m-%Y %H:%M:%S') for elem in dts]

df.insert(0, 'DateTime', fmted)
</code>```

Body:
I have a dataframe with 13 columns, where two columns are "Date" and "Time".

I would like to
1) join "Date" and "Time" and
2) format the result correctly (DD.MM.YYYY HH:MM:SS)

        Date    Time
0   2012-09-27  00:40:20
1   2012-09-27  07:24:37
2   2012-09-27  07:25:08
3   2012-09-27  07:43:48
4   2012-09-27  07:44:27
5   2012-09-27  07:55:16
6   2012-09-27  08:04:19
7   2012-09-27  08:08:21
8   2012-09-27  08:09:08
9   2012-09-27  08:15:30
10  2012-09-27  08:15:35

So I try:

>type(df["Date"])
pandas.core.series.Series

And I think to myself "Why not convert them both in to string representations and manipulate them that way?"

>g = df["Time"].astype(str)
>type(g)
pandas.core.series.Series

"What?! It's still a Series?!"

So I try to be creative:

>f = df["Date"].astype(str) + " " + df["Time"].astype(str)
>f
0     2012-09-27 00:40:20
1     2012-09-27 07:24:37
2     2012-09-27 07:25:08
3     2012-09-27 07:43:48

"Hey! That works! No let's just get the format right (DD.MM.YYYY HH:MM:SS)"

>#dt.strptime(f, '%Y-%m-%d %H:%M:%S')
TypeError: strptime() argument 1 must be str, not Series

"Still a Series...hmmm....Obviously it won't let itself be converted. Let's try something else"

>f = p.concat([df["Date"], df["Time"]], axis=1)
>f
        Date    Time
0   2012-09-27  00:40:20
1   2012-09-27  07:24:37
2   2012-09-27  07:25:08

"Nice! But.... Isn't this TWO columns still...?"

>f.shape
(100,2)

"Right...back to square one...."

I'm out of ideas....

Anyone?

Body:
.astype(str) works on the elements of Series, not the Series itself, so of course type(df["Time"].astype(str)) == pd.Series. This seems to be the source of much of your confusion, you're acting on the Series, not its elements.

A solution (there maybe an easier way) is to just loop over the series:

dts = [datetime.datetime.strptime(elem, '%Y-%m-%d%H:%M:%S')
       for elem in df['Date'] + df['Time']]

fmted = [elem.strftime('%d-%m-%Y %H:%M:%S') for elem in dts]

df.insert(0, 'DateTime', fmted)


问:
Move to root view from any where in the application
I need to move user to navigation controller root view whenever user receive push notification.

in my app there is side menu. navigation controllers detail view also.

So if user has opened side menu view then how can I move user to root view of navigationController that is home screen of my application.

also from detail view to root view irrespective of any controller.

Please suggest

Thanks

答:
You can use either

```<code>[self.navigationController popToRootViewController:YES];
</code>```

Or

```<code>[self dismissViewControllerAnimated:YES];
</code>```

Body:
You can use either

[self.navigationController popToRootViewController:YES];

Or

[self dismissViewControllerAnimated:YES];


Title: Pandas: Join Date and Time into one datetime column

Body:
the columns can be joined and assigned to a new or existing column in the dataframe:

df['datetime'] = df['dates'] + " " + df['time']

outputs example:

        dates      time             datetime
0  2012-09-27  00:40:20  2012-09-27 00:40:20
1  2012-09-27  07:24:37  2012-09-27 07:24:37
2  2012-09-27  07:25:08  2012-09-27 07:25:08


问:
Angular takes Array as object and does not display the values
// Updated along the discussion

I try to get JSON objects(Tasks) via http request and parse them into my own class to display them on my HTML page(Task Overwiew).

This is what I get:

This is the json array my php returns:

```<code>    {"result":[{"id":"3","znumber":"vor21423"},{"id":"2","znumber":"vor213"}]}
</code>```

Here's my last try from the turtorial on angular.io. I've tested many answers but most of them relate to .json() which is no longer part of the HTML client.

```<code>export class ApiComponent {
 private apiUrl = 'http://localhost:81/work/get.php';

 results: Steve[];

 constructor(private http: HttpClient) {
 }

 ngOnInit() {
   this.getSteves();
 }

 getSteves() {
   this.http.get<ItemsResponse>(this.apiUrl)
      .subscribe(data => {
        this.results = data.result
          .map(steve => new Steve(steve.id, steve.zNumber));
            console.log(this.results);
            console.log(data);
      });
  }
}
</code>```

The Interface

```<code>import { Steve } from './Steve';
export interface ItemsResponse {
  results: Steve[];
}
</code>```

HTML

```<code><div>
  <div *ngFor="let steve of results">
    <p> - {{steve.id}}</p>
    <p> - {{steve.zNumber}}</p>
  </div>
</div>
</code>```

The Steve Class

```<code>export class Steve {
  public id = 0;
  public zNumber = '';

  constructor(id: number, zNumber: string) {
    this.id = id;
    this.zNumber = zNumber;
  }
}
</code>```

The API

```<code><?php
require_once('db.php');

$sql = 'SELECT * FROM jobs ORDER BY id DESC';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $data = array();
    while($row = $result->fetch_assoc()){
        $data[] = $row;
    }
    echo json_encode(array('result' => $data));
} else {
    echo 0;
}
?>
</code>```

答:
You are using Angular version 4 at least. In version 4 the Angular team decided to implicitly parse JSON results, so you wouldn't have to write JSON.parse(json.result) with each Ajax request.

In your example you replaced the value returned by server: result with steves and then you try to access it: data['steves'] but in the screenshot you can see that the values have already been extracted by Angular implicit JSON parsing and you are dealing with an array of objects.

So data['steves'], data['result'] etc. will always be undefined, cause the Angular HttpClient service, which replaced Http service in version 4 is already parsing JSON before it returns the data.

Just replace:
this.results = data['steves'];
with
this.results = data;
and everything will work.

Body:
// Updated along the discussion

I try to get JSON objects(Tasks) via http request and parse them into my own class to display them on my HTML page(Task Overwiew).

This is what I get:

This is the json array my php returns:

    {"result":[{"id":"3","znumber":"vor21423"},{"id":"2","znumber":"vor213"}]}

Here's my last try from the turtorial on angular.io. I've tested many answers but most of them relate to .json() which is no longer part of the HTML client.

export class ApiComponent {
 private apiUrl = 'http://localhost:81/work/get.php';

 results: Steve[];

 constructor(private http: HttpClient) {
 }

 ngOnInit() {
   this.getSteves();
 }

 getSteves() {
   this.http.get<ItemsResponse>(this.apiUrl)
      .subscribe(data => {
        this.results = data.result
          .map(steve => new Steve(steve.id, steve.zNumber));
            console.log(this.results);
            console.log(data);
      });
  }
}

The Interface

import { Steve } from './Steve';
export interface ItemsResponse {
  results: Steve[];
}

HTML

 - {{steve.id}}

 - {{steve.zNumber}}

The Steve Class

export class Steve {
  public id = 0;
  public zNumber = '';

  constructor(id: number, zNumber: string) {
    this.id = id;
    this.zNumber = zNumber;
  }
}

The API

<?php
require_once('db.php');

$sql = 'SELECT * FROM jobs ORDER BY id DESC';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $data = array();
    while($row = $result->fetch_assoc()){
        $data[] = $row;
    }
    echo json_encode(array('result' => $data));
} else {
    echo 0;
}
?>


问:
Filter EventLog based on date
I am trying to pull out some information from the eventlog through PowerShell based on the date today.

So far I have the code below:

```<code>$today = (Get-Date).ToString("dd/MM/yyyy")
Get-EventLog Security | where {$_.EventID -eq 4624} | where {$_.TimeGenerated -eq $today}
</code>```

Now I have printed the result of today and can confirm that the outputted date is 04/12/2017, I have also printed the date of the TimeGenerated attriubute from the EventID object and that also shows the date in the same format.

Any ideas on where I am going wrong?

答:
The TimeGenerated property holds a DateTime value, not a string, so don't compare it to a date string. Also, you should filter via Get-EventLog parameters whenever possible, because that filtering happens at the source. This is particularly relevant when querying remote eventlogs to reduce the amount of data that is transmitted over the network.

```<code>$today    = (Get-Date).Date
$tomorrow = $today.AddDays(1)

Get-EventLog -LogName Security -InstanceId 4626 -After $today -Before $tomorrow
</code>```

Title: Filter EventLog based on date

Body:
I am trying to pull out some information from the eventlog through PowerShell based on the date today.

So far I have the code below:

$today = (Get-Date).ToString("dd/MM/yyyy")
Get-EventLog Security | where {$_.EventID -eq 4624} | where {$_.TimeGenerated -eq $today}

Now I have printed the result of today and can confirm that the outputted date is 04/12/2017, I have also printed the date of the TimeGenerated attriubute from the EventID object and that also shows the date in the same format.

Any ideas on where I am going wrong?

Body:
The TimeGenerated property holds a DateTime value, not a string, so don't compare it to a date string. Also, you should filter via Get-EventLog parameters whenever possible, because that filtering happens at the source. This is particularly relevant when querying remote eventlogs to reduce the amount of data that is transmitted over the network.

$today    = (Get-Date).Date
$tomorrow = $today.AddDays(1)

Get-EventLog -LogName Security -InstanceId 4626 -After $today -Before $tomorrow


问:
Returning undefined in output
I am new to javascript and I am struggling to understand the return statement:

function solution(number){
     var newarray = []
     for ( var i = 0 ; i < number - 1 ; i++ ) {
        if (i % 3 === 0) {
           newarray.push(number[i]);
        } else if (i % 5 === 0) {
           newarray.push(number[i]);
        } else {
           newarray
        }
      }
      return newarray
    }

   console.log(solution(10));```

This solution is returning an array with values in but they are all undefined. Why is this the case? What essential concept am I missing can anyone help me?

答:
The number passed as input is 10.

You access the number in the for loop as number[i], so you are actually accessing the i-nth position of a number which is undefined.

change it to

```<code>newarray.push(i);
</code>```

Title: Returning undefined in output

Body:
I am new to javascript and I am struggling to understand the return statement:

function solution(number){
     var newarray = []
     for ( var i = 0 ; i < number - 1 ; i++ ) {
        if (i % 3 === 0) {
           newarray.push(number[i]);
        } else if (i % 5 === 0) {
           newarray.push(number[i]);
        } else {
           newarray
        }
      }
      return newarray
    }

   console.log(solution(10));

This solution is returning an array with values in but they are all undefined. Why is this the case? What essential concept am I missing can anyone help me?

Body:
The number passed as input is 10.

You access the number in the for loop as number[i], so you are actually accessing the i-nth position of a number which is undefined.

change it to

newarray.push(i);


问:
Regex to match rails get index urls
I'm trying to create a regex to match only index urls (with or without parameters) in rails.

The following three match what I expect:

```<code>regex = /^http:\/\/localhost:3000\/v2\/manufacturers\/?(\S+)?$/
regex.match?('http://localhost:3000/v2/manufacturers?enabled=true')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers')
#=> true
</code>```

I expect the regex not to match these:

```<code>regex.match?('http://localhost:3000/v2/manufacturers/1')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/123')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/1?enabled=true')
#=> true
</code>```

Edit:

I'm so sorry but I forgot to mention that it should match:

```<code>regex.match?('http://localhost:3000/v2/manufacturers/1/models')
</code>```

as it is a valid index url

答:
You may use

```<code>/\Ahttp:\/\/localhost:3000\/v2\/manufacturers(?:\/?(?:\?\S+)?|\/1\/models\/?)?\z/
</code>```

See the Rubular demo

Pattern details

\A - start of string

http:\/\/localhost:3000\/v2\/manufacturers - a http://localhost:3000/v2/manufacturers string

(?:\/?(?:\?\S+)?|\/1\/models)? - an optional sequence of:

\/? - an optional / char

(?:\?\S+)? - an optional sequence of ? and 1+ non-whitespace

| - or

\/1\/models\/? - /1/models string and an optional / at the end

\z - end of string.

Title: Regex to match rails get index urls

Body:
I'm trying to create a regex to match only index urls (with or without parameters) in rails.

The following three match what I expect:

regex = /^http:\/\/localhost:3000\/v2\/manufacturers\/?(\S+)?$/
regex.match?('http://localhost:3000/v2/manufacturers?enabled=true')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers')
#=> true

I expect the regex not to match these:

regex.match?('http://localhost:3000/v2/manufacturers/1')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/123')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/1?enabled=true')
#=> true

Edit:

I'm so sorry but I forgot to mention that it should match:

regex.match?('http://localhost:3000/v2/manufacturers/1/models')

as it is a valid index url

Body:
You may use

/\Ahttp:\/\/localhost:3000\/v2\/manufacturers(?:\/?(?:\?\S+)?|\/1\/models\/?)?\z/

See the Rubular demo

Pattern details

\A - start of string

http:\/\/localhost:3000\/v2\/manufacturers - a http://localhost:3000/v2/manufacturers string

(?:\/?(?:\?\S+)?|\/1\/models)? - an optional sequence of:

\/? - an optional / char

(?:\?\S+)? - an optional sequence of ? and 1+ non-whitespace

| - or

\/1\/models\/? - /1/models string and an optional / at the end

\z - end of string.


问:
How to round pebble action bar edges?
I'm new to pebble app development and relatively new to programming. I'm trying to create a simple action bar over a text layer. My issue regards its shape. The documentation clearly depicts the action bar as rounded while following its instructions leads to a chunky rectangular vertical rectangle. My question is this: is the vertical rectangle default behavior? If so, can it be changed to the rounded style from within the default api? If not, what steps might I need to take to achieve the rounded (and frankly more attractive) rounded look?

https://developer.pebble.com/docs/c/User_Interface/Layers/ActionBarLayer/#ActionBarLayer

Nice rounded action bar screenshot

Ugly rectangular action bar screenshot

答: What SDK are you using? SDK4 or SDK3? The ugly rectangular action bar is default for SDK4. See this example. It is made for SDK3, that's why it has rounded bar. If you run it in CloudPebble with SDK4 configuration you will see as expected - 'ugly action bar'

Title: How to round pebble action bar edges?


问:
Map activity does not show up in my phone because I have many activities
I created new activity which is map activity. I think I have problem in AndroidManofest.xml.
My phone works perfectly if I create new project with just map activity. If I add it to my project, which has a lot of activities, it does not work. I do not know why.

the problem is about the activities
  AndroidManofest.xml

I checked every thing APU is enable

AndroidManofest.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.abdullahalhajri.smarttutor">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activities.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.RegisterActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.HomePage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchPage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchRating"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchSubject"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.MathTutor"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.ReviewComment"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.TutorProfile"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.UsersActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".activities.MapsActivity"
            android:label="@string/title_activity_maps">

        </activity>
    </application>

</manifest>
</code>```

Error

```<code>12-04 04:31:22.639 25820-26431/com.example.abdullahalhajri.smarttutor E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
                                                                                Ensure that the "Google Maps Android API v2" is enabled.
                                                                                Ensure that the following Android Key exists:
                                                                                API Key: <<redacted>>
</code>```

答:
Use backup key:    </p>

```<code> <meta-data
    android:name="com.google.android.backup.api_key"
    android:value="backupkey" />
</code>```

Body:
I created new activity which is map activity. I think I have problem in AndroidManofest.xml.
My phone works perfectly if I create new project with just map activity. If I add it to my project, which has a lot of activities, it does not work. I do not know why.

the problem is about the activities
  AndroidManofest.xml

I checked every thing APU is enable

AndroidManofest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.abdullahalhajri.smarttutor">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activities.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.RegisterActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.HomePage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchPage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchRating"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchSubject"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.MathTutor"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.ReviewComment"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.TutorProfile"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.UsersActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".activities.MapsActivity"
            android:label="@string/title_activity_maps">

        </activity>
    </application>

</manifest>

Error

12-04 04:31:22.639 25820-26431/com.example.abdullahalhajri.smarttutor E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
                                                                                Ensure that the "Google Maps Android API v2" is enabled.
                                                                                Ensure that the following Android Key exists:
                                                                                API Key: <<redacted>>

Body:
Use backup key:

 <meta-data
    android:name="com.google.android.backup.api_key"
    android:value="backupkey" />


问:
help with Firefox extension in multiple windows
I'm writing a Firefox extension that creates a socket server which will output the active tab's URL when a client makes a connection to it. I have the following code in my javascript file:

```<code>var serverSocket;

function startServer()
{
    var listener =
    {
        onSocketAccepted : function(socket, transport)
        {
            try {
                var outputString = gBrowser.currentURI.spec + "\n";
                var stream = transport.openOutputStream(0,0,0);
                stream.write(outputString,outputString.length);
                stream.close();
            } catch(ex2){ dump("::"+ex2); }
        },

        onStopListening : function(socket, status){}
    };

    try {
        serverSocket = Components.classes["@mozilla.org/network/server-socket;1"]
        .createInstance(Components.interfaces.nsIServerSocket);

        serverSocket.init(7055,true,-1);
        serverSocket.asyncListen(listener);
   } catch(ex){ dump(ex); }

   document.getElementById("status").value = "Started";
}

function stopServer ()
{
    if (serverSocket)
    serverSocket.close();
}

window.addEventListener("load", function() { startServer(); }, false);
window.addEventListener("unload", function() { stopServer(); }, false);
</code>```

As it is, it works for multiple tabs in a single window. If I open multiple windows, it ignores the additional windows. I think it is creating a server socket for each window, but since they are using the same port, the additional sockets fail to initialize. I need it to create a server socket when the browser launches and continue running when I close the windows (Mac OS X). As it is, when I close a window but Firefox remains running, the socket closes and I have to restart firefox to get it up an running. How do I go about that?

答:
You probably want to:

Move your code into a JavaScript component

Register your component as a profile-after-change observer

Whenever someone makes a connection to your socket, find the active window and return its URL.

Use something like

```<code>var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
var spec = win ? win.getBrowser().currentURI.spec : "";
var outputString = spec + "\n";
</code>```

etc.

ContentLicense: CC BY-SA 2.5

Body:
I'm writing a Firefox extension that creates a socket server which will output the active tab's URL when a client makes a connection to it. I have the following code in my javascript file:

var serverSocket;

function startServer()
{
    var listener =
    {
        onSocketAccepted : function(socket, transport)
        {
            try {
                var outputString = gBrowser.currentURI.spec + "\n";
                var stream = transport.openOutputStream(0,0,0);
                stream.write(outputString,outputString.length);
                stream.close();
            } catch(ex2){ dump("::"+ex2); }
        },

        onStopListening : function(socket, status){}
    };

    try {
        serverSocket = Components.classes["@mozilla.org/network/server-socket;1"]
        .createInstance(Components.interfaces.nsIServerSocket);

        serverSocket.init(7055,true,-1);
        serverSocket.asyncListen(listener);
   } catch(ex){ dump(ex); }

   document.getElementById("status").value = "Started";
}

function stopServer ()
{
    if (serverSocket)
    serverSocket.close();
}

window.addEventListener("load", function() { startServer(); }, false);
window.addEventListener("unload", function() { stopServer(); }, false);

As it is, it works for multiple tabs in a single window. If I open multiple windows, it ignores the additional windows. I think it is creating a server socket for each window, but since they are using the same port, the additional sockets fail to initialize. I need it to create a server socket when the browser launches and continue running when I close the windows (Mac OS X). As it is, when I close a window but Firefox remains running, the socket closes and I have to restart firefox to get it up an running. How do I go about that?

Body:
You probably want to:

Move your code into a JavaScript component

Register your component as a profile-after-change observer

Whenever someone makes a connection to your socket, find the active window and return its URL.

Use something like

var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
var spec = win ? win.getBrowser().currentURI.spec : "";
var outputString = spec + "\n";

etc.


问:
HibernateException: Could not create the driver from NHibernate.Driver.MySqlDataDriver
I want to create a connection with MySQL server using FluentNHibernate in ASP.NET Core, but I get an exception.

My Fluent configuration:

```<code>var config = Fluently.Configure()
                     .Database(MySQLConfiguration
                         .Standard
                         .ConnectionString(cs => cs
                             .Server(dbServer)
                             .Database(dbName)
                             .Username(dbUsername)
                             .Password(dbPassword)))
                     .Mappings(x =>x.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                     .BuildSessionFactory();
</code>```

Exception:

```<code>FluentNHibernate.Cfg.FluentConfigurationException: "An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail."
</code>```

InnerExceptions:

HibernateException: Could not create the driver from NHibernate.Driver.MySqlDataDriver, NHibernate, Version=5.0.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4.

TargetInvocationException: Exception has been thrown by the target of an invocation.

TypeLoadException: Could not load type 'System.Data.Common.DbProviderFactories' from assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Project config:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="FluentNHibernate" Version="2.0.3" />
    <PackageReference Include="Iesi.Collections" Version="4.0.2" />
    <PackageReference Include="log4net" Version="2.0.8" />
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
    <PackageReference Include="MySql.Data" Version="6.10.4" />
    <PackageReference Include="MySql.Data.Entity" Version="6.10.4" />
    <PackageReference Include="MySql.Web" Version="6.10.4" />
    <PackageReference Include="NHibernate" Version="5.0.3" />
    <PackageReference Include="System.Configuration.ConfigurationManager" Version="4.4.0" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>
</Project>
</code>```

Link to deps.json: http://pastebin.com/pn67pa6y

What should I do?

答:
FluentNHibernate does not support .NET Core (issue), because NHibernate has not (PR).

NHibernate PR is scheduled for v5.1, due by December 15, 2017 at the time of this writing.

mstancombe has a fork for .NET Core, but you have to build it yourself.

Body:
I want to create a connection with MySQL server using FluentNHibernate in ASP.NET Core, but I get an exception.

My Fluent configuration:

var config = Fluently.Configure()
                     .Database(MySQLConfiguration
                         .Standard
                         .ConnectionString(cs => cs
                             .Server(dbServer)
                             .Database(dbName)
                             .Username(dbUsername)
                             .Password(dbPassword)))
                     .Mappings(x =>x.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                     .BuildSessionFactory();

Exception:

FluentNHibernate.Cfg.FluentConfigurationException: "An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail."

InnerExceptions:

HibernateException: Could not create the driver from NHibernate.Driver.MySqlDataDriver, NHibernate, Version=5.0.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4.

TargetInvocationException: Exception has been thrown by the target of an invocation.

TypeLoadException: Could not load type 'System.Data.Common.DbProviderFactories' from assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Project config:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="FluentNHibernate" Version="2.0.3" />
    <PackageReference Include="Iesi.Collections" Version="4.0.2" />
    <PackageReference Include="log4net" Version="2.0.8" />
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
    <PackageReference Include="MySql.Data" Version="6.10.4" />
    <PackageReference Include="MySql.Data.Entity" Version="6.10.4" />
    <PackageReference Include="MySql.Web" Version="6.10.4" />
    <PackageReference Include="NHibernate" Version="5.0.3" />
    <PackageReference Include="System.Configuration.ConfigurationManager" Version="4.4.0" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>
</Project>

Link to deps.json: http://pastebin.com/pn67pa6y

What should I do?


问:
Can't use Asp.net core 2.0 with entity framework 6
I follow link https://learn.microsoft.com/en-us/aspnet/core/data/entity-framework-6 to do this.
But when I run prọect, It occur error

ConfigurationErrorsException: Configuration system failed to
  initialize
  System.Configuration.ClientConfigurationSystem.EnsureInit(string
  configKey)
  System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(string
  sectionName)
  System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(string
  sectionName)
  System.Configuration.ConfigurationManager.GetSection(string
  sectionName)
  System.Configuration.ConfigurationManager.get_ConnectionStrings()
  System.Data.Entity.Internal.AppConfig..ctor()
  System.Data.Entity.Internal.AppConfig..cctor()

raw exception details

TypeInitializationException: The type initializer for
  'System.Data.Entity.Internal.AppConfig' threw an exception.
  System.Data.Entity.Internal.LazyInternalConnection..ctor(DbContext
  context, string nameOrConnectionString)
  System.Data.Entity.DbContext..ctor(string nameOrConnectionString)
  Repositories.EF6.Context.MyDbContext..ctor()
  Repositories.EF6.Implements.FakeLinkRepository..ctor()
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCreateInstance(CreateInstanceCallSite
  createInstanceCallSite, ServiceProvider provider)
  ....

I have divided the entity framework into a separate project, Can anyone have idea to fix it

This is my code
In EF6 project run on .net framework 4.6.1

```<code>    [DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MyDbContext : DbContext
        {

            public MyDbContext():base(GlobalVariables.ConnectionString == null ? "name=defaultConnectionString" : GlobalVariables.ConnectionString)
            {

            }
            public MyDbContext(string connectionString):base(connectionString)
            {

            }
           .......

    }

public class MyDbConfiguration : MySqlEFConfiguration
    {
        public MyDbConfiguration()
        {
            SetProviderServices("MySql.Data.MySqlClient", new MySqlProviderServices());
            SetDefaultConnectionFactory(new MySqlConnectionFactory());
        }
    }
</code>```

My repository

```<code>public class MyRepository : Repository
    {
        MyDbContext _context;
        public MyRepository ()
        {
            _context = new MyDbContext();
        }
     .....
}
</code>```

In asp.net core 2.0
GlobalVariables.ConnectionString get value of connectionString on appSetting.json and MyDbContext is created by DI create MyRepository

Static class GlobalVariables on Standard class 2.0

This is Error when I run my project asp.net core 2.0 againt

ConfigurationErrorsException: Unrecognized configuration section system.data.

file config is :

```<code><configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="defaultConnectionString" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;user id=root;password=admin;database=té;persistsecurityinfo=True" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.10.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.10.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
</code>```

Update, I found the problem, maybe .net core 2.0 don't support system.Data.Common. I found on nuget but only found this library support with .net standard 1.2.
I think can't use entity framework 6 with asp.net core 2.0, wait for next update.

答:
You can't put an EF6 context in an ASP.NET Core project because .NET
  Core projects don't support all of the functionality that EF6 commands
  such as Enable-Migrations require.

Have you put EF6 in a separate .net 4.6 project?
or try using EF Core instead? https://learn.microsoft.com/en-us/ef/core/

Body:
I follow link https://learn.microsoft.com/en-us/aspnet/core/data/entity-framework-6 to do this.
But when I run prọect, It occur error

ConfigurationErrorsException: Configuration system failed to
  initialize
  System.Configuration.ClientConfigurationSystem.EnsureInit(string
  configKey)
  System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(string
  sectionName)
  System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(string
  sectionName)
  System.Configuration.ConfigurationManager.GetSection(string
  sectionName)
  System.Configuration.ConfigurationManager.get_ConnectionStrings()
  System.Data.Entity.Internal.AppConfig..ctor()
  System.Data.Entity.Internal.AppConfig..cctor()

raw exception details

TypeInitializationException: The type initializer for
  'System.Data.Entity.Internal.AppConfig' threw an exception.
  System.Data.Entity.Internal.LazyInternalConnection..ctor(DbContext
  context, string nameOrConnectionString)
  System.Data.Entity.DbContext..ctor(string nameOrConnectionString)
  Repositories.EF6.Context.MyDbContext..ctor()
  Repositories.EF6.Implements.FakeLinkRepository..ctor()
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCreateInstance(CreateInstanceCallSite
  createInstanceCallSite, ServiceProvider provider)
  ....

I have divided the entity framework into a separate project, Can anyone have idea to fix it

This is my code
In EF6 project run on .net framework 4.6.1

    [DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MyDbContext : DbContext
        {

            public MyDbContext():base(GlobalVariables.ConnectionString == null ? "name=defaultConnectionString" : GlobalVariables.ConnectionString)
            {

            }
            public MyDbContext(string connectionString):base(connectionString)
            {

            }
           .......

    }

public class MyDbConfiguration : MySqlEFConfiguration
    {
        public MyDbConfiguration()
        {
            SetProviderServices("MySql.Data.MySqlClient", new MySqlProviderServices());
            SetDefaultConnectionFactory(new MySqlConnectionFactory());
        }
    }

My repository

public class MyRepository : Repository
    {
        MyDbContext _context;
        public MyRepository ()
        {
            _context = new MyDbContext();
        }
     .....
}

In asp.net core 2.0
GlobalVariables.ConnectionString get value of connectionString on appSetting.json and MyDbContext is created by DI create MyRepository

Static class GlobalVariables on Standard class 2.0

This is Error when I run my project asp.net core 2.0 againt

ConfigurationErrorsException: Unrecognized configuration section system.data.

file config is :

<configSections>

  </configSections>
  <connectionStrings>
    <add name="defaultConnectionString" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;user id=root;password=admin;database=té;persistsecurityinfo=True" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.10.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.10.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>

Update, I found the problem, maybe .net core 2.0 don't support system.Data.Common. I found on nuget but only found this library support with .net standard 1.2.
I think can't use entity framework 6 with asp.net core 2.0, wait for next update.


问:
LogOn to remote protected site using PHP and cURL
I am trying to log on to my company's intranet which is protected by an RSA token. I managed to find out all the necessary data for the log on and it works using this code.

```<code>    <?php
//init curl
$ch = curl_init();

//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);

curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5");

// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);

//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $var);

//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//execute the request (the login)
$store = curl_exec($ch);

?>
</code>```

After the log on I will be logged out instantly. There is set a maximum of 2 hours for a session. How ist that normally set? Where will I find this information in the original site code? I guess it will be stored in a cookie? What do I have to do in order to not being logged out right after the logIn?

Best regards,
Michael

答:
I believe its due to unavailability of SESSION and Cookie info. Eventhough you are getting login success, with very next request to code will check for cookie value generated with login and will check against session value.

So if they won't matched then you will be logged out.

I don't think this code will work for your purpose.

Body:
I am trying to log on to my company's intranet which is protected by an RSA token. I managed to find out all the necessary data for the log on and it works using this code.

    <?php
//init curl
$ch = curl_init();

//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);

curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5");

// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);

//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $var);

//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//execute the request (the login)
$store = curl_exec($ch);

?>

After the log on I will be logged out instantly. There is set a maximum of 2 hours for a session. How ist that normally set? Where will I find this information in the original site code? I guess it will be stored in a cookie? What do I have to do in order to not being logged out right after the logIn?

Best regards,
Michael


问:
How to import txt file with UTF-8 encoding into jsp?
Hey I'm working on a web application and have problems with read UTF-8 chars from txt files. I get UTF-8 working that way: UTF-8 web encoding (and it workes fine except at the import). I tryed a lot of thinks (especially from: read UTF-8 string literal java) but nothing work and I have no idea why.

The importent codesnippets:

import.jsp

```<code><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Import</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css"
media="screen and (min-device-width: 500px)" href="style.css" />
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<form>
    <!-- show import data -->
</form>
<form id="importForm" action="${pageContext.request.contextPath}/ImportData" method="post" onsubmit="return importValidation();" enctype="multipart/form-data">
    <input type="file" name="file" accept=".txt"/>
    <input type="submit" value="Import">
</form>

</body>
</html>
</code>```

ImportData Servlet:

```<code>import java.nio.charset.StandardCharsets;

@WebServlet("/ImportData")
@MultipartConfig
public class ImportData extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
         BufferedReader buf = new BufferedReader(new InputStreamReader(filePart.getInputStream(), StandardCharsets.UTF_8.name()));
         String lineJustFetched = null;
         String[] wordsArray = null;
         ArrayList<String> texts = new ArrayList<String>();
         while(true){
             lineJustFetched = buf.readLine();
             if(lineJustFetched == null){
                 break;
             }else{
                 wordsArray = lineJustFetched.split("\t");
                 for(String each : wordsArray){
                     texts.add(each);
                 }
             }
         }
         buf.close();

        System.out.println(texts);

        //create Import Data in Backend and write it into db

        response.sendRedirect("import.jsp");
    }
}
</code>```

System details:
Tomcat server 7 with Java 1.7

The outprint of texts for UTF-8 chars is a square and in html inputs (and texts) is a � instead of the UTF-8 chars

So my question is: Where and why do I lost the UTF-8 encoding?

答:
Ok I didn't look right... The file is not UTF-8 encoded (it is ANSI encoded) with UTF-8 encoding this code workes fine.

To make it runnable for an other encoding you have only to change the InputStreamReader encoding to read the file correctly.

e.g.

```<code> BufferedReader buf = new BufferedReader(new
       InputStreamReader(filePart.getInputStream(), "Cp1252"));
</code>```

(for windows-ANSI)

Body:
Hey I'm working on a web application and have problems with read UTF-8 chars from txt files. I get UTF-8 working that way: UTF-8 web encoding (and it workes fine except at the import). I tryed a lot of thinks (especially from: read UTF-8 string literal java) but nothing work and I have no idea why.

The importent codesnippets:

import.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Import</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<link rel="stylesheet" type="text/css"
media="screen and (min-device-width: 500px)" href="style.css" />
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<form>

</form>
<form id="importForm" action="${pageContext.request.contextPath}/ImportData" method="post" onsubmit="return importValidation();" enctype="multipart/form-data">
    <input type="file" name="file" accept=".txt"/>
    <input type="submit" value="Import">
</form>

ImportData Servlet:

import java.nio.charset.StandardCharsets;

@WebServlet("/ImportData")
@MultipartConfig
public class ImportData extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
         BufferedReader buf = new BufferedReader(new InputStreamReader(filePart.getInputStream(), StandardCharsets.UTF_8.name()));
         String lineJustFetched = null;
         String[] wordsArray = null;
         ArrayList<String> texts = new ArrayList<String>();
         while(true){
             lineJustFetched = buf.readLine();
             if(lineJustFetched == null){
                 break;
             }else{
                 wordsArray = lineJustFetched.split("\t");
                 for(String each : wordsArray){
                     texts.add(each);
                 }
             }
         }
         buf.close();

        System.out.println(texts);

        //create Import Data in Backend and write it into db

        response.sendRedirect("import.jsp");
    }
}

System details:
Tomcat server 7 with Java 1.7

The outprint of texts for UTF-8 chars is a square and in html inputs (and texts) is a � instead of the UTF-8 chars

So my question is: Where and why do I lost the UTF-8 encoding?

Body:
Ok I didn't look right... The file is not UTF-8 encoded (it is ANSI encoded) with UTF-8 encoding this code workes fine.

To make it runnable for an other encoding you have only to change the InputStreamReader encoding to read the file correctly.

e.g.

 BufferedReader buf = new BufferedReader(new
       InputStreamReader(filePart.getInputStream(), "Cp1252"));

(for windows-ANSI)