问:
Text file not showing up in document
I'm having trouble displaying the score from my game in a text file, I have two text files, one for player details which works perfect but the other text file for scores is not appearing, after I enter the scores the time of the date modified in the scores text file is the same time I finish the game, its just the scores are not coming up. Here is my code:</p>

```<code>import java.util.Scanner;
import java.io.*;

public class Project
{

    public static void main (String[]args) throws FileNotFoundException // This shows that the programme might encounter a file which is not there.
    {
        String outputFileName ="players.txt";
        //Storing the name of the text file

        PrintWriter writeToFile = new PrintWriter(outputFileName);
        //This allows me to write to the text file that I've called outputFileName

        Scanner playerStringInput = new Scanner(System.in);
        Scanner playerIntInput = new Scanner(System.in);
        //Taking info from the keyboard, one is for Integers and the other is for String

        String name = " ";
        String nickName = " ";
        String homeTown = " ";
        int age = 0;
        int previousGamesPlayed = 0;
        //Declaring the variables that I'm going to use to store the inputs from the programme

        int amtOfPlayers = 2; //The amount of players we have

        for(int i = 0; i < amtOfPlayers; i++) //Loop for both players
        {
            System.out.println("1.Please Enter Name");//Prints out instructitions for user.
            name = playerStringInput.nextLine();//Taking the input to store in name.
            writeToFile.println(name); //Outputs the data into the text file.

            System.out.println("2.Please Enter Nickname");//Printing out the nickname entered onto the screen.
            nickName = playerStringInput.nextLine(); //Taking the input to store in name.
            writeToFile.println(nickName); //Outputs the data into the text file.

            System.out.println("3.Please Enter Home Towm");//Printing out the hometown entered onto the screen.
            homeTown = playerStringInput.nextLine();//Taking the input to store in name.
            writeToFile.println(homeTown);//Outputs the data into the text file.

            System.out.println("4.Please Enter Age, this must be a number.");//Printing out the age entered onto the screen.
            age = playerIntInput.nextInt();//Taking the input to store in name.
            writeToFile.println(age);//Outputs the data into the text file.

            System.out.println("5.Please Enter Previous Games Played");//Printing out the previous games played entered onto the screen.
            previousGamesPlayed = playerIntInput.nextInt();//Taking the input to store in name.
            writeToFile.println(previousGamesPlayed);//Outputs the data into the text file.

            System.out.println("The name entered is: " + name); //Printing out the name entered onto the screen.
            System.out.println("The nickname entered is: " + nickName);//Printing out the nickname entered onto the screen.
            System.out.println("The hometown entered is: " + homeTown);//Printing out the hometown entered onto the screen.
            System.out.println("Age entered is: " + age);//Printing out the age entered onto the screen.
            System.out.println(previousGamesPlayed);//Printing out the name entered onto the screen.
        }

        writeToFile.close(); //Close the file writer so it can write the text into the file
        Scanner scan = new Scanner(System.in);//Allows us to take input from game

        String userInput1 = " ";
        char player1Input;

        String userInput2 = " ";
        char player2Input;
        //Declaring our variables for game

        for(int i = 0; i < 7; i++) //Loop for game which will loop 7 times
        {

        System.out.println("Player 1: Please Enter e.g R for Rock:");
        System.out.println("R.Rock");//Printing out Rock as choice for game
        System.out.println("P.Paper");//Printing out Paper as choice for game
        System.out.println("S.Scissors");//Printing out Scissors as choice for game

        userInput1 = scan.next();
        player1Input = userInput1.charAt(0);

        System.out.println("Player 2: Please Enter e.g S for Scissors");
        System.out.println("R.Rock");//Printing out Rock as choice for game
        System.out.println("P.Paper");//Printing out Paper as choice for game
        System.out.println("S.Scissors");//Printing out Scissors as choice for game

        userInput2 = scan.next();
        player2Input = userInput2.charAt(0);

        switch(player1Input)//beginning of switch statement
        {
            case 'R':  System.out.println ("Player 1:Rock");//

                switch(player2Input)
                {
                    //declaring possible outcomes if player 1 choses paper
                    case'R' : System.out.println("Player 2:Rock");//
                    System.out.println("The Game Result is Draw");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 1 Wins");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;//Terminating the loop before it goes onto the next statement

            case 'P' : System.out.println ("Player 1:Paper");
                switch(player2Input)
                {
                    //declaring possible outcomes if player 1 choses Paper
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Draw");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 2 Wins2");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;//Terminating the loop before it goes onto the next statement

            //declaring possible outcomes if player 1 choses Scissors

            case 'S' : System.out.println ("Player 1:Scissors");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println ("The Game Result is: Draw");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;//Terminating the loop before it goes onto the next statement
        }//Ending of loop for game

        for(int h = 0; i < 2;i++);//for loop for scores, I also needed to call this int h as I already declared int I as a variable in my main method string.
        }

        int [] arrPlayer = new int[2];//using arrays to gather players score

        System.out.println("Player 1 Please Enter Your Score");//Player 1 printing out their score
        arrPlayer[0]=scan.nextInt();
        System.out.println("Player 2 Please Enter Your Score");//Player 2 printing out their score
        arrPlayer[1]=scan.nextInt();

        System.out.println("Player 1 : Score: " + arrPlayer[0]);//Player 1 score
        System.out.println("Player 2 : Score: " + arrPlayer[1]);//Player 2 score

        String outputFileName2 ="scores.txt";
        //Storing the name of the text file

        PrintWriter writeToFile2 = new PrintWriter(outputFileName2);
        //This allows me to write to the text file that I've called outputFileName

        writeToFile.close(); //Close the file writer so it can write the text into the file

    }//End of method
}//End of class
</code>```

答: Your last statement should be writeToFile2.close(), not writeToFile.close().  You're closing the first file twice. The buffer is not being flushed to the file before the program ends.

Title: Text file not showing up in document

Body:
I'm having trouble displaying the score from my game in a text file, I have two text files, one for player details which works perfect but the other text file for scores is not appearing, after I enter the scores the time of the date modified in the scores text file is the same time I finish the game, its just the scores are not coming up. Here is my code:

import java.util.Scanner;
import java.io.*;

public class Project
{

    public static void main (String[]args) throws FileNotFoundException // This shows that the programme might encounter a file which is not there.
    {
        String outputFileName ="players.txt";
        //Storing the name of the text file

        PrintWriter writeToFile = new PrintWriter(outputFileName);
        //This allows me to write to the text file that I've called outputFileName

        Scanner playerStringInput = new Scanner(System.in);
        Scanner playerIntInput = new Scanner(System.in);
        //Taking info from the keyboard, one is for Integers and the other is for String

        String name = " ";
        String nickName = " ";
        String homeTown = " ";
        int age = 0;
        int previousGamesPlayed = 0;
        //Declaring the variables that I'm going to use to store the inputs from the programme

        int amtOfPlayers = 2; //The amount of players we have

        for(int i = 0; i < amtOfPlayers; i++) //Loop for both players
        {
            System.out.println("1.Please Enter Name");//Prints out instructitions for user.
            name = playerStringInput.nextLine();//Taking the input to store in name.
            writeToFile.println(name); //Outputs the data into the text file.

            System.out.println("2.Please Enter Nickname");//Printing out the nickname entered onto the screen.
            nickName = playerStringInput.nextLine(); //Taking the input to store in name.
            writeToFile.println(nickName); //Outputs the data into the text file.

            System.out.println("3.Please Enter Home Towm");//Printing out the hometown entered onto the screen.
            homeTown = playerStringInput.nextLine();//Taking the input to store in name.
            writeToFile.println(homeTown);//Outputs the data into the text file.

            System.out.println("4.Please Enter Age, this must be a number.");//Printing out the age entered onto the screen.
            age = playerIntInput.nextInt();//Taking the input to store in name.
            writeToFile.println(age);//Outputs the data into the text file.

            System.out.println("5.Please Enter Previous Games Played");//Printing out the previous games played entered onto the screen.
            previousGamesPlayed = playerIntInput.nextInt();//Taking the input to store in name.
            writeToFile.println(previousGamesPlayed);//Outputs the data into the text file.

            System.out.println("The name entered is: " + name); //Printing out the name entered onto the screen.
            System.out.println("The nickname entered is: " + nickName);//Printing out the nickname entered onto the screen.
            System.out.println("The hometown entered is: " + homeTown);//Printing out the hometown entered onto the screen.
            System.out.println("Age entered is: " + age);//Printing out the age entered onto the screen.
            System.out.println(previousGamesPlayed);//Printing out the name entered onto the screen.
        }

        writeToFile.close(); //Close the file writer so it can write the text into the file
        Scanner scan = new Scanner(System.in);//Allows us to take input from game

        String userInput1 = " ";
        char player1Input;

        String userInput2 = " ";
        char player2Input;
        //Declaring our variables for game

        for(int i = 0; i < 7; i++) //Loop for game which will loop 7 times
        {

        System.out.println("Player 1: Please Enter e.g R for Rock:");
        System.out.println("R.Rock");//Printing out Rock as choice for game
        System.out.println("P.Paper");//Printing out Paper as choice for game
        System.out.println("S.Scissors");//Printing out Scissors as choice for game

        userInput1 = scan.next();
        player1Input = userInput1.charAt(0);

        System.out.println("Player 2: Please Enter e.g S for Scissors");
        System.out.println("R.Rock");//Printing out Rock as choice for game
        System.out.println("P.Paper");//Printing out Paper as choice for game
        System.out.println("S.Scissors");//Printing out Scissors as choice for game

        userInput2 = scan.next();
        player2Input = userInput2.charAt(0);

        switch(player1Input)//beginning of switch statement
        {
            case 'R':  System.out.println ("Player 1:Rock");//

                switch(player2Input)
                {
                    //declaring possible outcomes if player 1 choses paper
                    case'R' : System.out.println("Player 2:Rock");//
                    System.out.println("The Game Result is Draw");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 1 Wins");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;//Terminating the loop before it goes onto the next statement

            case 'P' : System.out.println ("Player 1:Paper");
                switch(player2Input)
                {
                    //declaring possible outcomes if player 1 choses Paper
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Draw");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 2 Wins2");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;//Terminating the loop before it goes onto the next statement

            //declaring possible outcomes if player 1 choses Scissors

            case 'S' : System.out.println ("Player 1:Scissors");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println ("The Game Result is: Draw");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;//Terminating the loop before it goes onto the next statement
        }//Ending of loop for game

        for(int h = 0; i < 2;i++);//for loop for scores, I also needed to call this int h as I already declared int I as a variable in my main method string.
        }

        int [] arrPlayer = new int[2];//using arrays to gather players score

        System.out.println("Player 1 Please Enter Your Score");//Player 1 printing out their score
        arrPlayer[0]=scan.nextInt();
        System.out.println("Player 2 Please Enter Your Score");//Player 2 printing out their score
        arrPlayer[1]=scan.nextInt();

        System.out.println("Player 1 : Score: " + arrPlayer[0]);//Player 1 score
        System.out.println("Player 2 : Score: " + arrPlayer[1]);//Player 2 score

        String outputFileName2 ="scores.txt";
        //Storing the name of the text file

        PrintWriter writeToFile2 = new PrintWriter(outputFileName2);
        //This allows me to write to the text file that I've called outputFileName

        writeToFile.close(); //Close the file writer so it can write the text into the file

    }//End of method
}//End of class


来源: stackexchange

问:
About Automatic Release of app on iTunes Connect
I want to automatically release my new app at a set date, but I am a bit unsure if it is enough to just cross in the automatic release button and set a date, or do I also need to press the "Release this Version" button to confirm? I am afraid if I press this button it could mean it will actually release it directly?

Do anyone know?

答: I just spoke to an Apple rep about this. She said if you want to automatically release your app, simply set the automatic release date and click Save. Don't click Release this version, or you will immediately release it to the store.

ContentLicense: CC BY-SA 3.0


问:
Design-time-only background color in WPF?
In WPF XAML there is the convenient DesignHeight and DesignWidth, for instance in code as

```<code><UserControl ... d:DesignHeight="500" d:DesignWidth="500" ... />
</code>```

which is great because I can build the layout with a representative, but not locked-in, control size.

However, I'm often building dark UIs, where labels and so forth need to be white, but my controls still need a transparent background color. This creates a design-time inconvenience because white seems to be the default background color for transparent controls in the designer, leading to unreadable white-on-white labels.

Is there a way or strategy for setting the design-time background color, with similar convenience as DesignHeight/DesignWidth?

答:
The d:DesignerProperties.DesignStyle technique shown on this page works great for applying a WPF design-time-only style to a single control, but it doesn't appear to work for a Style in a ResourceDictionary that would apply to all of the appropriately-typed controls or elements under the scope of the dictionary. Below is simple solution I found for deploying a designer-only style into a ResourceDictionary.

Consider for example a Window containing a TreeView, where we want the TreeViewItem nodes to show as fully expanded—but only at design time. First, put the desired style in the XAML dictionary in the normal way.

```<code><Window.Resources>
    <Style TargetType="TreeViewItem">
        <Setter Property="IsExpanded" Value="True" />
    </Style>
</Window.Resources>
</code>```

Here, the Style is put in the ResourceDictionary of the Window but of course you could use any other subsuming dictionary instead. Next, in the C# code, remove the style from the ResourceDictionary when design mode is not detected. Do this is in the OnInitialized override:

```<code>protected override void OnInitialized(EventArgs e)
{
    if (DesignerProperties.GetIsInDesignMode(this) == false)
        Resources.Remove(typeof(TreeViewItem));

    base.OnInitialized(e);
}
</code>```

Design Mode:                                                        Runtime Mode:

Body:
In WPF XAML there is the convenient DesignHeight and DesignWidth, for instance in code as

<UserControl ... d:DesignHeight="500" d:DesignWidth="500" ... />

which is great because I can build the layout with a representative, but not locked-in, control size.

However, I'm often building dark UIs, where labels and so forth need to be white, but my controls still need a transparent background color. This creates a design-time inconvenience because white seems to be the default background color for transparent controls in the designer, leading to unreadable white-on-white labels.

Is there a way or strategy for setting the design-time background color, with similar convenience as DesignHeight/DesignWidth?

Body:
The d:DesignerProperties.DesignStyle technique shown on this page works great for applying a WPF design-time-only style to a single control, but it doesn't appear to work for a Style in a ResourceDictionary that would apply to all of the appropriately-typed controls or elements under the scope of the dictionary. Below is simple solution I found for deploying a designer-only style into a ResourceDictionary.

Consider for example a Window containing a TreeView, where we want the TreeViewItem nodes to show as fully expanded—but only at design time. First, put the desired style in the XAML dictionary in the normal way.

<Window.Resources>
    <Style TargetType="TreeViewItem">
        <Setter Property="IsExpanded" Value="True" />
    </Style>
</Window.Resources>

Here, the Style is put in the ResourceDictionary of the Window but of course you could use any other subsuming dictionary instead. Next, in the C# code, remove the style from the ResourceDictionary when design mode is not detected. Do this is in the OnInitialized override:

protected override void OnInitialized(EventArgs e)
{
    if (DesignerProperties.GetIsInDesignMode(this) == false)
        Resources.Remove(typeof(TreeViewItem));

    base.OnInitialized(e);
}

Design Mode:                                                        Runtime Mode:


问:
Connecting and manuplating data on an access database?
I'm working on my thesis project with Windows Phone 7. I'm developing an application requires store data in a database, my thesis supervisor said an Microsoft Access database is enough for this step, because I'm newbie at developing applications for Windows Phone 7.

How can i do that?

答:
Windows Phone 7 can't have direct access to a database since standard DB connection drivers are not compatible with this platform. What you can do is built a multi-layered project, where there is a web service (easily built with WCF) that connects your Windows Phone 7 application to a local (or remote) database.

You could send request to the web service and it will send those to the database. The same service can send the response back to the app.

ContentLicense: CC BY-SA 2.5


问:
Generate range between two strings [AA] -> [CD] or [CCC] -> [DMK]
I want to generate a sequence of strings between two groups that can be either 1 letter [A] -> [F] , 2 letters such as [AA] -> [CD] or any other length like 3 or 4 letters using c#.

For example I can specify the start and end values, and it will generate the sequence.

From [AA] to [CD] should generate

```<code>AA
AB
AC
AD

BA
BB
BC
BD

CA
CB
CC
CD
</code>```

I tried to utilize base-26 algorithm to generate the required sequence but failed to get the required output.

```<code>string from ="AA";
string to = "CD";
IEnumerable<string> mysequence = Enumerable.Range(ConvertNumber(from), ConvertNumber(to) - ConvertNumber(from)).Select(ConvertAlpha).ToList();

public static string ConvertAlpha(int value)
{
    const int a = (int)'A';
    value = value - 1;
    var returnValue = new StringBuilder();
    while (value > -1)
    {
        var remainder = value % 26;
        returnValue.Insert(0, (char)(a + remainder));
        value = value / 26 - 1;
    }
    return returnValue.ToString();
}

public static int ConvertNumber(string value)
{
    const int a = (int)'A' - 1;
    int returnValue = 0;
    foreach (var character in value.ToUpper())
    {
        returnValue *= 26;
        returnValue += (int)character - a;
    }
    return returnValue;
}
</code>```

答:
Using recursion (but with brute-force rather than elegance):</p>

```<code>static void Main(string[] args)
{
    string fromStr = "AAA";
    string toStr = "CDE";
    List<string> outputList = new List<string>();

    BuildSequence(fromStr, toStr, outputList);

    outputList.ForEach(s => { Console.WriteLine(s); });
    Console.ReadLine();
}

private static void BuildSequence(
    string fromStr,
    string toStr,
    List<string> outputList,
    int index = 0,
    string prev = "")
{
    IEnumerable<string> newStrList = Enumerable
        .Range(fromStr[index], toStr[index] - fromStr[index] + 1)
        .Select(c => String.Concat(prev, (char)c));

    index += 1;

    if (index < fromStr.Length)
    {
        foreach (string newStr in newStrList)
        {
            BuildSequence(fromStr, toStr, outputList, index, newStr);
        }
    }
    else
    {
        outputList.AddRange(newStrList);
    }
}
</code>```

Body:
I want to generate a sequence of strings between two groups that can be either 1 letter [A] -> [F] , 2 letters such as [AA] -> [CD] or any other length like 3 or 4 letters using c#.

For example I can specify the start and end values, and it will generate the sequence.

From [AA] to [CD] should generate

AA
AB
AC
AD

BA
BB
BC
BD

CA
CB
CC
CD

I tried to utilize base-26 algorithm to generate the required sequence but failed to get the required output.

string from ="AA";
string to = "CD";
IEnumerable<string> mysequence = Enumerable.Range(ConvertNumber(from), ConvertNumber(to) - ConvertNumber(from)).Select(ConvertAlpha).ToList();

public static string ConvertAlpha(int value)
{
    const int a = (int)'A';
    value = value - 1;
    var returnValue = new StringBuilder();
    while (value > -1)
    {
        var remainder = value % 26;
        returnValue.Insert(0, (char)(a + remainder));
        value = value / 26 - 1;
    }
    return returnValue.ToString();
}

public static int ConvertNumber(string value)
{
    const int a = (int)'A' - 1;
    int returnValue = 0;
    foreach (var character in value.ToUpper())
    {
        returnValue *= 26;
        returnValue += (int)character - a;
    }
    return returnValue;
}

Body:
Using recursion (but with brute-force rather than elegance):

static void Main(string[] args)
{
    string fromStr = "AAA";
    string toStr = "CDE";
    List<string> outputList = new List<string>();

    BuildSequence(fromStr, toStr, outputList);

    outputList.ForEach(s => { Console.WriteLine(s); });
    Console.ReadLine();
}

private static void BuildSequence(
    string fromStr,
    string toStr,
    List<string> outputList,
    int index = 0,
    string prev = "")
{
    IEnumerable<string> newStrList = Enumerable
        .Range(fromStr[index], toStr[index] - fromStr[index] + 1)
        .Select(c => String.Concat(prev, (char)c));

    index += 1;

    if (index < fromStr.Length)
    {
        foreach (string newStr in newStrList)
        {
            BuildSequence(fromStr, toStr, outputList, index, newStr);
        }
    }
    else
    {
        outputList.AddRange(newStrList);
    }
}


问:
VBA Access SQL Server table insert
I have some problem when I deal with MS Access. I am using SQL Server and MS Access together.

I try to insert data into a new table.

First, this program asks me to add an item to the list (it is like temporary table). And then, there is another submit button which confirms the data (this step is needed and it is not inefficient one. Please do not ask about this step).

To add data to the list, I use a stored procedure. But I do not know what do I need to do to submit the data again.

Here is my code:

```<code>Dim rs As ADODB.Recordset

strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn
cmd.ActiveConnection = conn
Set rs = New ADODB.Recordset
rs.Open "Insert into dbo.Blend values(List731.Column(1, introw),List731.Column(2, introw),TextRequestNo.Value, List731.Column(3, introw),List731.Column(4, introw),List731.Column(5, introw))"
conn.Close
Set rs = Nothing
MsgBox "Done"
</code>```

When I run with this code, I get this error:

I think there is some missing in my code but I do not know how to proceed.
Is there anyone who can give me some information about this?

答:
There are many ways to do this kind of thing.  Something like this should get the job done.</p>

```<code>Sub MoveDateFromAccessToSQLServer()

Dim adoCN As ADODB.Connection
Dim sConnString As String
Dim sSQL As String
Dim lRow As Long, lCol As Long

sConnString = "Provider=sqloledb;Server=servername;Database=NORTHWIND;User Id=xx;Password=password"

Set adoCN = CreateObject("ADODB.Connection")

'adoCN.Open sConnString

'Assumes that you have Field1, Field2 and Field3 in columns A, B and C
'Text values must be enclosed in apostrophes whereas numeric values should not.

    sSQL = "INSERT INTO YOUR_TABLE (FIELD1, FIELD2, FIELD3) " & _
            " VALUES (" & _
            "'" & Column(1, introw) & "', " & _
            "'" & Column(2, introw) & "', " & _
            "'" & Column(3, introw) & "')"

    adoCN.Execute sSQL

adoCN.Close

Set adoCN = Nothing

End Sub
</code>```

Title: VBA Access SQL Server table insert

Body:
I have some problem when I deal with MS Access. I am using SQL Server and MS Access together.

I try to insert data into a new table.

First, this program asks me to add an item to the list (it is like temporary table). And then, there is another submit button which confirms the data (this step is needed and it is not inefficient one. Please do not ask about this step).

To add data to the list, I use a stored procedure. But I do not know what do I need to do to submit the data again.

Here is my code:

Dim rs As ADODB.Recordset

strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn
cmd.ActiveConnection = conn
Set rs = New ADODB.Recordset
rs.Open "Insert into dbo.Blend values(List731.Column(1, introw),List731.Column(2, introw),TextRequestNo.Value, List731.Column(3, introw),List731.Column(4, introw),List731.Column(5, introw))"
conn.Close
Set rs = Nothing
MsgBox "Done"

When I run with this code, I get this error:

I think there is some missing in my code but I do not know how to proceed.
Is there anyone who can give me some information about this?

Body:
There are many ways to do this kind of thing.  Something like this should get the job done.

Sub MoveDateFromAccessToSQLServer()

Dim adoCN As ADODB.Connection
Dim sConnString As String
Dim sSQL As String
Dim lRow As Long, lCol As Long

sConnString = "Provider=sqloledb;Server=servername;Database=NORTHWIND;User Id=xx;Password=password"

Set adoCN = CreateObject("ADODB.Connection")

'adoCN.Open sConnString

'Assumes that you have Field1, Field2 and Field3 in columns A, B and C
'Text values must be enclosed in apostrophes whereas numeric values should not.

    sSQL = "INSERT INTO YOUR_TABLE (FIELD1, FIELD2, FIELD3) " & _
            " VALUES (" & _
            "'" & Column(1, introw) & "', " & _
            "'" & Column(2, introw) & "', " & _
            "'" & Column(3, introw) & "')"

    adoCN.Execute sSQL

adoCN.Close

Set adoCN = Nothing

End Sub


问:
Vertx FileUpload Unit Test
My backend code is very similar to this question.

```<code>Router router  = Router.router(vertx);
router.route().handler(BodyHandler.create().setDeleteUploadedFilesOnEnd(true));

router.route("/api/*")
                    .produces(Constants.JSON_CONTENT_TYPE)
                    .failureHandler(rc -> {
                        // handling failure code
                });

router.post("/api/upload").handler(uploadHandler::uploadHandler);
vertx.createHttpServer(httpOptions)
                    .requestHandler(router::accept)                             // The router::accept, method passes all routes defined in Router.
                    .listen(// do things);
class UploadHandler() {
    void uploadHandler(RoutingContext context) {
        uploads.forEach(// do things);
    }
}
</code>```

I have been using postman to test the methods. It is working perfectly.

In postman, I choose POST, no headers, form-data as body, and choose files instead of text to upload files.

I checked in the server that postman include the content-type automatically.

I am assuming this is a good approach. Please let me know if there's a better approach.

My problem is at unit testing.
I used the code similar to this. https://github.com/vert-x/vertx-examples/blob/master/src/raw/java/upload/UploadClient.java

There are other snippets which does similar things. But the server keeps saying that no files are attached.

What is the a good way to send a file to the server?

答:
The link in your question points to an old version of Vert.x

With a recent version, you should use the Vert.x Web Client.

```<code>String filename = "upload.txt";
FileSystem fs = vertx.fileSystem();

WebClient client = WebClient.create(vertx);

fs.props(filename, ares -> {
  FileProps props = ares.result();
  System.out.println("props is " + props);
  long size = props.size();

  HttpRequest<Buffer> req = client.put(8080, "localhost", "/");
  req.putHeader("content-length", "" + size);

  fs.open(filename, new OpenOptions(), ares2 -> {
    req.sendStream(ares2.result(), ar -> {
      if (ar.succeeded()) {
        HttpResponse<Buffer> response = ar.result();
        System.out.println("Got HTTP response with status " + response.statusCode());
      } else {
        ar.cause().printStackTrace();
      }
    });
  });
});
</code>```

For a full client/server sample, check out the Vert.x examples repository

Title: Vertx FileUpload Unit Test

Body:
My backend code is very similar to this question.

Router router  = Router.router(vertx);
router.route().handler(BodyHandler.create().setDeleteUploadedFilesOnEnd(true));

router.route("/api/*")
                    .produces(Constants.JSON_CONTENT_TYPE)
                    .failureHandler(rc -> {
                        // handling failure code
                });

router.post("/api/upload").handler(uploadHandler::uploadHandler);
vertx.createHttpServer(httpOptions)
                    .requestHandler(router::accept)                             // The router::accept, method passes all routes defined in Router.
                    .listen(// do things);
class UploadHandler() {
    void uploadHandler(RoutingContext context) {
        uploads.forEach(// do things);
    }
}

I have been using postman to test the methods. It is working perfectly.

In postman, I choose POST, no headers, form-data as body, and choose files instead of text to upload files.

I checked in the server that postman include the content-type automatically.

I am assuming this is a good approach. Please let me know if there's a better approach.

My problem is at unit testing.
I used the code similar to this. https://github.com/vert-x/vertx-examples/blob/master/src/raw/java/upload/UploadClient.java

There are other snippets which does similar things. But the server keeps saying that no files are attached.

What is the a good way to send a file to the server?

Body:
The link in your question points to an old version of Vert.x

With a recent version, you should use the Vert.x Web Client.

String filename = "upload.txt";
FileSystem fs = vertx.fileSystem();

WebClient client = WebClient.create(vertx);

fs.props(filename, ares -> {
  FileProps props = ares.result();
  System.out.println("props is " + props);
  long size = props.size();

  HttpRequest<Buffer> req = client.put(8080, "localhost", "/");
  req.putHeader("content-length", "" + size);

  fs.open(filename, new OpenOptions(), ares2 -> {
    req.sendStream(ares2.result(), ar -> {
      if (ar.succeeded()) {
        HttpResponse<Buffer> response = ar.result();
        System.out.println("Got HTTP response with status " + response.statusCode());
      } else {
        ar.cause().printStackTrace();
      }
    });
  });
});

For a full client/server sample, check out the Vert.x examples repository


问:
Slicing a dictionary
I have a dictionary, and would like to pass a part of it to a function, that part being given by a list (or tuple) of keys. Like so:

```<code># the dictionary
d = {1:2, 3:4, 5:6, 7:8}

# the subset of keys I'm interested in
l = (1,5)
</code>```

Now, ideally I'd like to be able to do this:

```<code>>>> d[l]
{1:2, 5:6}
</code>```

... but that's not working, since it will look for a key matching the tuple (1,5), the same as d[1,5].

d{1,5} isn't even valid Python (as far as I can tell ...), though it might be handy: The curly braces suggest an unordered set or a dictionary, so returning a dictionary containing the specified keys would look very plausible to me.

d[{1,5}] would also make sense ("here's a set of keys, give me the matching items"), and {1, 5} is an unhashable set, so there can't be a key that matches it -- but of course it throws an error, too.

I know I can do this:

```<code>>>> dict([(key, value) for key,value in d.iteritems() if key in l])
{1: 2, 5: 6}
</code>```

or this:

```<code>>>> dict([(key, d[key]) for key in l])
</code>```

which is more compact
... but I feel there must be a "better" way of doing this. Am I missing a more elegant solution?

(I'm using Python 2.7)

答:
On Python 3 you can use the itertools islice to slice the dict.items() iterator

```<code>import itertools

d = {1: 2, 3: 4, 5: 6}

dict(itertools.islice(d.items(), 2))

{1: 2, 3: 4}
</code>```

Note: this solution does not take into account specific keys. It slices by internal ordering of d, which in Python 3.7+ is guaranteed to be insertion-ordered.

ContentLicense: CC BY-SA 4.0

Title: Slicing a dictionary

Body:
I have a dictionary, and would like to pass a part of it to a function, that part being given by a list (or tuple) of keys. Like so:

# the dictionary
d = {1:2, 3:4, 5:6, 7:8}

# the subset of keys I'm interested in
l = (1,5)

Now, ideally I'd like to be able to do this:

>>> d[l]
{1:2, 5:6}

... but that's not working, since it will look for a key matching the tuple (1,5), the same as d[1,5].

d{1,5} isn't even valid Python (as far as I can tell ...), though it might be handy: The curly braces suggest an unordered set or a dictionary, so returning a dictionary containing the specified keys would look very plausible to me.

d[{1,5}] would also make sense ("here's a set of keys, give me the matching items"), and {1, 5} is an unhashable set, so there can't be a key that matches it -- but of course it throws an error, too.

I know I can do this:

>>> dict([(key, value) for key,value in d.iteritems() if key in l])
{1: 2, 5: 6}

or this:

>>> dict([(key, d[key]) for key in l])

which is more compact
... but I feel there must be a "better" way of doing this. Am I missing a more elegant solution?

(I'm using Python 2.7)

Body:
On Python 3 you can use the itertools islice to slice the dict.items() iterator

import itertools

d = {1: 2, 3: 4, 5: 6}

dict(itertools.islice(d.items(), 2))

{1: 2, 3: 4}

Note: this solution does not take into account specific keys. It slices by internal ordering of d, which in Python 3.7+ is guaranteed to be insertion-ordered.


问:
Good uses for Apache CollectionUtils
I found the CollectionUtils class a year or so ago and a few of the methods like, collect, and transform seem really cool, however, I have yet to find a use where it would not by syntactically cleaner and\or easier to just write the logic with a simple loop.

Has any found a unique\useful use for these methods (transform, predicatedCollection, collect, etc) e.g. the methods that take a transformer or predicate as an argument?

答:
While we don't use the CollctionUtils we have implemented a few similar utilities our selves and from those we frequently use

empty(Collection c)

to test collections, strings and such for emptyness

has(...)

that only returns !empty(...)

mapToProperty(Collection c, String property, Class newType)

this maps a collection of T1 to a collection of T2 using reflection to call "property"

implode(Collection c, String sep)

A sep seperated string with the elements of c

Title: Good uses for Apache CollectionUtils

OwnerDisplayName: John Nilsson


问:
How to make a background process when app is not running in Cordova?
I am trying to do some functionality when app is suspended. I used -

https://github.com/katzer/cordova-plugin-background-mode

It works perfectly when app is running, when killed the app is stop working. Then, I used - https://github.com/katzer/cordova-plugin-local-notifications

It make a notification when app is killed, but I can't handle any of it's events unless app is running. Does anyone try to do like an ajax call when app is killed after period of time? Is there any other repos to make a background service while app isn't running?

(Push notifications are not a solution for me in this scenario)

Thanks.

答:
You are looking for this plugin: https://ionicframework.com/docs/native/background-fetch/ which allows you to run 30s of code in the background during the user's "active" time of day (as defined by Apple).

```<code>  const config: BackgroundFetchConfig = {
    stopOnTerminate: true, // Set true to cease background-fetch from operating after user "closes" the app. Defaults to true.
  };

  backgroundFetch.configure(config)
     .then(() => {
         console.log('Background Fetch initialized');
         //Your code to be repeatedly executed here

         this.backgroundFetch.finish();

     })
     .catch(e => console.log('Error initializing background fetch', e));
</code>```

To me the docs aren't clear but the method passed to the then is what is called at whatever interval the OS wakes up at.

Body:
You are looking for this plugin: https://ionicframework.com/docs/native/background-fetch/ which allows you to run 30s of code in the background during the user's "active" time of day (as defined by Apple).

  const config: BackgroundFetchConfig = {
    stopOnTerminate: true, // Set true to cease background-fetch from operating after user "closes" the app. Defaults to true.
  };

  backgroundFetch.configure(config)
     .then(() => {
         console.log('Background Fetch initialized');
         //Your code to be repeatedly executed here

         this.backgroundFetch.finish();

     })
     .catch(e => console.log('Error initializing background fetch', e));

To me the docs aren't clear but the method passed to the then is what is called at whatever interval the OS wakes up at.


问:
How to parse comma delimited string in PL/SQL?
I have a comma delimited string in a PL/SQL script (e.g. data:= 'a,b,c,d,e'), that I need to parse out within the script.

I would like to loop through the string and process each item.  Like a 'foreach' loop.

Is this possible in PL/SQL?  Can someone point me to some code?

答:
A simple tokenizer SQL statement working for Oracle 10g and 11g could be written as follow:

```<code>WITH string AS (
      SELECT pv_string value
        FROM dual)
SELECT DISTINCT upper(trim(regexp_substr (value, '[^' || pv_separator || ']+', 1, ROWNUM))) value,
       level
  FROM string
CONNECT BY LEVEL <= LENGTH(regexp_replace (value, '[^' || pv_separator || ']+')) + 1
  ORDER BY level;
</code>```

Where you can replace pv_string by the string to parse (e.g. 'a,b,c,d,e') and pv_separator by the separator string (e.g. ',') .

Body:
A simple tokenizer SQL statement working for Oracle 10g and 11g could be written as follow:

WITH string AS (
      SELECT pv_string value
        FROM dual)
SELECT DISTINCT upper(trim(regexp_substr (value, '[^' || pv_separator || ']+', 1, ROWNUM))) value,
       level
  FROM string
CONNECT BY LEVEL <= LENGTH(regexp_replace (value, '[^' || pv_separator || ']+')) + 1
  ORDER BY level;

Where you can replace pv_string by the string to parse (e.g. 'a,b,c,d,e') and pv_separator by the separator string (e.g. ',') .


问:
WPF DataGrid - How detect if full row is selected?
I have DataGrid in my WPF application, and I want to run a function in the SelectedCellsChanged event, but only if the row is not fully selected, which happens if the user clicks at the header of the row.

My table has only one column.

I've tried the following code and always the value of rowContainer.IsSelected is false.

How can I do this?

Private Sub DataGridEx_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles Me.SelectionChanged

    If SelectedCells.Count <> 1 Then
        Exit Sub
    End If

    If Not SelectedCells.First.Item.ToString.Contains("NewItemPlaceholder") Then

            Me.TheDispatcher.BeginInvoke(
                Sub()
                    Dim cell = SelectedCells.First
                    Dim index = Items.IndexOf(cell.Item) + 1
                    Dim rowContainer As DataGridRow = ItemContainerGenerator.ContainerFromIndex(index)

                    If rowContainer IsNot Nothing Then
                        If Not rowContainer.IsSelected Then
                            ' run a function here
                        End If
                    End If
                End Sub,
                DispatcherPriority.Input)

     End If

End Sub
```

答:
One thing you can do is force your datagrid to the SelectionUnit as FullRow, Cell or CellOrRowHeader

```<code>dim dg = new DataGrid();
dg.SelectionUnit == System.Windows.Controls.DataGridSelectionUnit.FullRow;
dg.SelectionUnit == System.Windows.Controls.DataGridSelectionUnit.CellOrRowHeader;
dg.SelectionUnit == System.Windows.Controls.DataGridSelectionUnit.Cell;
</code>```

In XAML, you would just apply the property setting

```<code><DataGrid SelectionUnit="FullRow" ... >
</code>```

Then you should be able to simply hook into the SelectedCellsChanged or SelectionChanged method to act on it...

Then you don't have to worry about a partial row selection of just a cell or two and not trigger an entire row you are expecting to process.  By forcing a full row, it will have in its collection one entry per row.  Otherwise, if you have it by cell and have 5 columns wide and person selects 3 cells on two rows, it will have 6 cells representing the same row for each individual cell covering the rows..

HTH

Body:
One thing you can do is force your datagrid to the SelectionUnit as FullRow, Cell or CellOrRowHeader

dim dg = new DataGrid();
dg.SelectionUnit == System.Windows.Controls.DataGridSelectionUnit.FullRow;
dg.SelectionUnit == System.Windows.Controls.DataGridSelectionUnit.CellOrRowHeader;
dg.SelectionUnit == System.Windows.Controls.DataGridSelectionUnit.Cell;

In XAML, you would just apply the property setting

<DataGrid SelectionUnit="FullRow" ... >

Then you should be able to simply hook into the SelectedCellsChanged or SelectionChanged method to act on it...

Then you don't have to worry about a partial row selection of just a cell or two and not trigger an entire row you are expecting to process.  By forcing a full row, it will have in its collection one entry per row.  Otherwise, if you have it by cell and have 5 columns wide and person selects 3 cells on two rows, it will have 6 cells representing the same row for each individual cell covering the rows..

HTH


问:
Microsoft ODBC driver for Linux vs FreeTDS?
I am investigating the possibilities to connect to a MSSQL database from a RHEL6 application server. I have found two ways:

FreeTDS

Microsoft SQL Server ODBC Driver for Linux + unixODBC

Does anyone have experience in using either of these setups? (I'm especially curious about the latter, since it is officially supported by MS). Performance? Stability? Any other options I might be missing?

答:
If you're working with older versions of SQL Server (e.g. 2000), current Microsoft ODBC drivers may not work.

FreeTDS claims to work with all versions of MS SQL Server:
http://www.freetds.org/faq.html#Does.FreeTDS.support.my.server


问:
How to use the sequence in Server Template and Inline Template Docusign
I saw the example in docusign to do it like so:

Both Server Template and Inline Template have the same sequence number per composite template
Notice:

```<code>CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 1
CompositeTemplate: ServerTemplate Sequence = 2
                   InlineTemplate Sequence = 2

{
    "emailSubject": "DocuSign API - Composite Templates",
    "emailBlurb": "Composite Templates Sample 1",
    "status": "sent",
    "compositeTemplates": [{
        "serverTemplates": [{
            "sequence": "1",
            "templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
        }],
        "inlineTemplates": [{
            "sequence": "1",
            "recipients": {
                "signers": [{
                    "email": "johndoe@email.com",
                    "name": "John Doe",
                    "recipientId": "1",
                    "roleName": "Buyer"
                }]
            }
        }]
    }, {
        "serverTemplates": [{
            "sequence": "2",
            "templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
        }],
        "inlineTemplates": [{
            "sequence": "2",
            "recipients": {
                "signers": [{
                    "email": "sallydoe@email.com",
                    "name": "Sally Doe",
                    "recipientId": "1",
                    "roleName": "Seller"
                }]
            }
        }]
    }]
}
</code>```

But I also saw in some stack overflow to use it this way:

Multiple Server Templates have the same sequence number, and the inline Templates are the difference

```<code>CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
    {
        "emailSubject": "DocuSign API - Composite Templates",
        "emailBlurb": "Composite Templates Sample 1",
        "status": "sent",
        "compositeTemplates": [{
            "serverTemplates": [{
                "sequence": "1",
                "templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
            }],
            "inlineTemplates": [{
                "sequence": "2",
                "recipients": {
                    "signers": [{
                        "email": "johndoe@email.com",
                        "name": "John Doe",
                        "recipientId": "1",
                        "roleName": "Buyer"
                    }]
                }
            }]
        }, {
            "serverTemplates": [{
                "sequence": "1",
                "templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
            }],
            "inlineTemplates": [{
                "sequence": "2",
                "recipients": {
                    "signers": [{
                        "email": "sallydoe@email.com",
                        "name": "Sally Doe",
                        "recipientId": "1",
                        "roleName": "Seller"
                    }]
                }
            }]
        }]
    }
</code>```

I tried to read the docusign api doc, but still not sure when to use each scenario

答:
Sequence number in one composite template does not affect the sequence number of other composite template. Which means, if you have an array of Composite Template, then sequence number defined in each composite template element of array is independent of sequence number defined in an another composite template.

Now lets go into each composite template, for adding document into composite template, lower the sequence value that document will become the base document of that composite template. For instance,

```<code>CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
</code>```

In above scenario, document to this composite template will be provided by Server Template, whereas in below scenario,

```<code>CompositeTemplate: ServerTemplate Sequence = 2
                   InlineTemplate Sequence = 1
</code>```

Document will come from Inline Template, it will override the document present in the server template.

But the rule for sequence number changes for the recipient information. Template having higher sequence number will add the recipient information to the composite template.

So in nutshell, document is added to a composite template with the lower value, and recipient information is added with the higher value.

Mostly, you will see use of Composite Template as:

```<code>CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
</code>```

In above scenario, document will be added from ServerTemplate (lower sequence value) and Recipient Info will be added from Inline Template (higher sequence value).

Body:
I saw the example in docusign to do it like so:

Both Server Template and Inline Template have the same sequence number per composite template
Notice:

CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 1
CompositeTemplate: ServerTemplate Sequence = 2
                   InlineTemplate Sequence = 2

{
    "emailSubject": "DocuSign API - Composite Templates",
    "emailBlurb": "Composite Templates Sample 1",
    "status": "sent",
    "compositeTemplates": [{
        "serverTemplates": [{
            "sequence": "1",
            "templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
        }],
        "inlineTemplates": [{
            "sequence": "1",
            "recipients": {
                "signers": [{
                    "email": "johndoe@email.com",
                    "name": "John Doe",
                    "recipientId": "1",
                    "roleName": "Buyer"
                }]
            }
        }]
    }, {
        "serverTemplates": [{
            "sequence": "2",
            "templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
        }],
        "inlineTemplates": [{
            "sequence": "2",
            "recipients": {
                "signers": [{
                    "email": "sallydoe@email.com",
                    "name": "Sally Doe",
                    "recipientId": "1",
                    "roleName": "Seller"
                }]
            }
        }]
    }]
}

But I also saw in some stack overflow to use it this way:

Multiple Server Templates have the same sequence number, and the inline Templates are the difference

CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
    {
        "emailSubject": "DocuSign API - Composite Templates",
        "emailBlurb": "Composite Templates Sample 1",
        "status": "sent",
        "compositeTemplates": [{
            "serverTemplates": [{
                "sequence": "1",
                "templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
            }],
            "inlineTemplates": [{
                "sequence": "2",
                "recipients": {
                    "signers": [{
                        "email": "johndoe@email.com",
                        "name": "John Doe",
                        "recipientId": "1",
                        "roleName": "Buyer"
                    }]
                }
            }]
        }, {
            "serverTemplates": [{
                "sequence": "1",
                "templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
            }],
            "inlineTemplates": [{
                "sequence": "2",
                "recipients": {
                    "signers": [{
                        "email": "sallydoe@email.com",
                        "name": "Sally Doe",
                        "recipientId": "1",
                        "roleName": "Seller"
                    }]
                }
            }]
        }]
    }

I tried to read the docusign api doc, but still not sure when to use each scenario

Body:
Sequence number in one composite template does not affect the sequence number of other composite template. Which means, if you have an array of Composite Template, then sequence number defined in each composite template element of array is independent of sequence number defined in an another composite template.

Now lets go into each composite template, for adding document into composite template, lower the sequence value that document will become the base document of that composite template. For instance,

CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2

In above scenario, document to this composite template will be provided by Server Template, whereas in below scenario,

CompositeTemplate: ServerTemplate Sequence = 2
                   InlineTemplate Sequence = 1

Document will come from Inline Template, it will override the document present in the server template.

But the rule for sequence number changes for the recipient information. Template having higher sequence number will add the recipient information to the composite template.

So in nutshell, document is added to a composite template with the lower value, and recipient information is added with the higher value.

Mostly, you will see use of Composite Template as:

CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2

In above scenario, document will be added from ServerTemplate (lower sequence value) and Recipient Info will be added from Inline Template (higher sequence value).


问:
HTML5 formatting on MacOS X? (preferably with TextMate)
Are there any editors or bundles available for MacOS X that support formatting of HTML5 documents? Tidy errors out on newer tags like canvas.</p>

答: Do not about textmate bundles, but how about coda from panic? www.panic.com/coda</p>


问:
How to sort an html access log in fastest way in cpp

local - - [24/Oct/1994:13:41:41 -0600] "GET index.html HTTP/1.0" 200
  150

local - - [24/Oct/1994:13:41:41 -0600] "GET 1.gif HTTP/1.0" 200 1210

local - - [24/Oct/1994:13:43:13 -0600] "GET index.html HTTP/1.0" 200
  3185

remote - - [24/Oct/1994:13:43:14 -0600] "GET 2.gif HTTP/1.0" 200 2555

local - - [24/Oct/1994:13:43:13 -0600] "GET index.html HTTP/1.0" 200
  32618

As in the example, I have an access log that contains around 700.000 logs in text format.

" " stands for our html page, first integer is our http reply code which will be ignored, second integer is bytes in reply that we will be using to calculate visitor numbers. Timestamps will be ignored. We will be sorting total visitor numbers for each website log as quick as possible. Which data structure method in c++ should I be using? I need some suggestion.

答:
If you're just looking to count visitors by URL, you don't need to write a program to do this.

```<code>elb-logs, 515> wc -l /tmp/$$
874597 /tmp/4028

elb-logs, 516> time ( grep GET /tmp/$$ | sed -e 's/.*"GET //' | sed -e 's/ .*//' | sort | uniq -c | sort -n > /tmp/example )

real    0m11.185s
user    0m13.872s
sys 0m0.476s
</code>```

That gives me counts by URL, for GET requests. If I wanted to do something like sum up the number of bytes by URL I would use awk.

Admittedly, the laptop that I'm using to do this has 12 GB of RAM and an SSD, so that will affect the numbers. But even if it takes a minute to run such a command pipeline that's still a lot less time than it would take to write and debug a C++ program.

Body:
If you're just looking to count visitors by URL, you don't need to write a program to do this.

elb-logs, 515> wc -l /tmp/$$
874597 /tmp/4028

elb-logs, 516> time ( grep GET /tmp/$$ | sed -e 's/.*"GET //' | sed -e 's/ .*//' | sort | uniq -c | sort -n > /tmp/example )

real    0m11.185s
user    0m13.872s
sys 0m0.476s

That gives me counts by URL, for GET requests. If I wanted to do something like sum up the number of bytes by URL I would use awk.

Admittedly, the laptop that I'm using to do this has 12 GB of RAM and an SSD, so that will affect the numbers. But even if it takes a minute to run such a command pipeline that's still a lot less time than it would take to write and debug a C++ program.


问:
How to resample and round every index into nearest seconds?
My data looks like (the datatype is Pandas DataFrame) :

```<code>price =

time                bid
03:03:34.797000     116.02
03:03:34.797000     116.02
03:03:54.152000     116.02
03:03:54.169000     116.02
03:03:54.169000     116.02
03:07:36.899000     116.24
03:07:48.760000     116.24
03:07:48.760000     116.24
03:07:48.761000     116.24
</code>```

I tried to resample the data into second level data and align every data into the nearest seconds no earlier than the original time. I expect the result to be:

```<code>03:04:00    116.02
03:05:00    NaN
03:06:00    NaN
03:07:00    NaN
03:08:00    116.24
</code>```

and used

```<code>price.resample('Min').last()
</code>```

However I got.

```<code>03:03:34.797000     116.02
03:04:34.797000     NaN
03:05:34.797000     NaN
03:06:34.797000     NaN
03:07:34.797000     116.24
</code>```

Everything goes well except the alignment. Anyone could help me solve the problem? Thanks.

答:
I tried with this solution and it runs faster.</p>

```<code>df = df.resample('Min').last()
offset_mc = df.index[0].microseconds
offset_sec = df.index[0].seconds % 60
if not (offset_mc == 0 and offset_sec == 0): df.index +=  pd.tslib.Timedelta(str(59-offset_sec)+'seconds '+str(1000000-offset_mc)+'microseconds')
</code>```

Body:
My data looks like (the datatype is Pandas DataFrame) :

price =

time                bid
03:03:34.797000     116.02
03:03:34.797000     116.02
03:03:54.152000     116.02
03:03:54.169000     116.02
03:03:54.169000     116.02
03:07:36.899000     116.24
03:07:48.760000     116.24
03:07:48.760000     116.24
03:07:48.761000     116.24

I tried to resample the data into second level data and align every data into the nearest seconds no earlier than the original time. I expect the result to be:

03:04:00    116.02
03:05:00    NaN
03:06:00    NaN
03:07:00    NaN
03:08:00    116.24

and used

price.resample('Min').last()

However I got.

03:03:34.797000     116.02
03:04:34.797000     NaN
03:05:34.797000     NaN
03:06:34.797000     NaN
03:07:34.797000     116.24

Everything goes well except the alignment. Anyone could help me solve the problem? Thanks.

Body:
I tried with this solution and it runs faster.

df = df.resample('Min').last()
offset_mc = df.index[0].microseconds
offset_sec = df.index[0].seconds % 60
if not (offset_mc == 0 and offset_sec == 0): df.index +=  pd.tslib.Timedelta(str(59-offset_sec)+'seconds '+str(1000000-offset_mc)+'microseconds')


问:
copy specific text to copy another text in javascript
I want to make it like when i copy something i'll get something else on the clipboard.

```<code>document.addEventListener('copy', function(e){
  if(e.clipboardData.getData('Text').toString()==="@Trolluminati")
  e.clipboardData.setData ("Text", "<@325608201175433216>");
  e.preventDefault();
});
</code>```

Idk, how to make it so it will change the last copy of this specific text to the other one.

Right now it just keeps the same copied text and does not change it.

答:
```<code>document.addEventListener('copy', function(e){
  var selectedText  = window.getSelection().toString();
  if (selectedText == '@Trolluminati') {
      e.preventDefault();
      clipboardData = e.clipboardData || window.clipboardData || e.originalEvent.clipboardData;
      clipboardData.setData('text', '<@325608201175433216>');
  }

});
</code>```

Body:
I want to make it like when i copy something i'll get something else on the clipboard.

document.addEventListener('copy', function(e){
  if(e.clipboardData.getData('Text').toString()==="@Trolluminati")
  e.clipboardData.setData ("Text", "<@325608201175433216>");
  e.preventDefault();
});

Idk, how to make it so it will change the last copy of this specific text to the other one.

Right now it just keeps the same copied text and does not change it.


问:
r = r + 1 not working concatenate list while its an int?
I have this function that creates an empty 2D list. getal X getal wide and high.
Though when i execute the code i get this error

```<code>    Traceback (most recent call last):
       line 49, in
    bord = rooster(5, "<>>>>>>>>>>>>>>>>>>>>>>>>")
       line 38, in rooster
    r = r + 1
TypeError: can only concatenate list (not "int") to list
</code>```

r is a counter in this code that stands for rows of the board.

k is also a counter that stands for columns of the board.

reeks is a string that gets split into characters.

The goal of the code is to make the board getal X getal wide and then inserting all characters from 'reeks' into their own separate slot.

```<code>def rooster(getal, reeks):
    #vierkant = [['']*getal]* getal
    vierkant = [[0 for r in range(getal)] for k in range(getal)]
    r = 0
    k = 0
    reekslist = list(reeks)
    while r < getal:
        k = 0
        while k < getal:
            vierkant[r][k] = reekslist[k + r*getal]

            k += 1
        for r in vierkant:
            print(r)
        r = r + 1
bord = rooster(5, "<>>>>>>>>>>>>>>>>>>>>>>>>")
</code>```

答:
Change your for loop before the increment to something like this:

```<code>for v in vierkant:
    print(v)
</code>```

if you use r in the for loop above it get assigned to the new value which is a row in vierkant, which is a list.

Body:
I have this function that creates an empty 2D list. getal X getal wide and high.
Though when i execute the code i get this error

    Traceback (most recent call last):
       line 49, in
    bord = rooster(5, "<>>>>>>>>>>>>>>>>>>>>>>>>")
       line 38, in rooster
    r = r + 1
TypeError: can only concatenate list (not "int") to list

r is a counter in this code that stands for rows of the board.

k is also a counter that stands for columns of the board.

reeks is a string that gets split into characters.

The goal of the code is to make the board getal X getal wide and then inserting all characters from 'reeks' into their own separate slot.

def rooster(getal, reeks):
    #vierkant = [['']*getal]* getal
    vierkant = [[0 for r in range(getal)] for k in range(getal)]
    r = 0
    k = 0
    reekslist = list(reeks)
    while r < getal:
        k = 0
        while k < getal:
            vierkant[r][k] = reekslist[k + r*getal]

            k += 1
        for r in vierkant:
            print(r)
        r = r + 1
bord = rooster(5, "<>>>>>>>>>>>>>>>>>>>>>>>>")

Body:
Change your for loop before the increment to something like this:

for v in vierkant:
    print(v)

if you use r in the for loop above it get assigned to the new value which is a row in vierkant, which is a list.


答:
I have created fiddle with the next code. It works for me in Chrome.

```<code>document.addEventListener('copy', function (event) {
  event.preventDefault();

  var copytext = window.getSelection() + '<@325608201175433216>';

  if (event.clipboardData) {
    event.clipboardData.setData('Text', copytext);
  }
});
</code>```

jsfiddle

Title: copy specific text to copy another text in javascript

Body:
I have created fiddle with the next code. It works for me in Chrome.

document.addEventListener('copy', function (event) {
  event.preventDefault();

  var copytext = window.getSelection() + '<@325608201175433216>';

  if (event.clipboardData) {
    event.clipboardData.setData('Text', copytext);
  }
});

jsfiddle


问:
Applescript to move incoming pictures to other folder with delay
I'm an applescript noob. So I don't know anything about this type of coding.

I want to make a script for a watch folder. I work with an image program that processes images. The process takes a second to create the jpg. So the folder has to wait for a few seconds to move the image to another file.

So this is what I'm looking for: Empty folder - jpg in the folder - wait 2 sec - move jpg to another folder - empty folder.

Thank you!

答:
Here is a little sample script which you could save on your Desktop as monitor:

```<code>#!/bin/bash

# Source directory to watch and destination directory to copy to
SRC="$HOME/Desktop/source"
DST="$HOME/Desktop/dest"

# Create directories if not existent
mkdir -p "$SRC" "$DST"

while : ; do
   find "$SRC" -type f -iname "*.jpg" -Btime +2s -exec mv {} "$DST" \;
   sleep 5
done
</code>```

It basically watches a directory called Desktop/source and looks for any files in there whose name ends in "JPG" and which have not been modified in the last 2 seconds. If it finds any, it then moves them to directory called Desktop/dest and sleeps for 5 seconds before checking again.

You would need to start Terminal and make the script executable by typing:

```<code>chmod +x $HOME/Desktop/monitor
</code>```

Then, whenever you want it running, you just double-click on the icon of monitor on your Desktop.

Body:
Here is a little sample script which you could save on your Desktop as monitor:

#!/bin/bash

# Source directory to watch and destination directory to copy to
SRC="$HOME/Desktop/source"
DST="$HOME/Desktop/dest"

# Create directories if not existent
mkdir -p "$SRC" "$DST"

while : ; do
   find "$SRC" -type f -iname "*.jpg" -Btime +2s -exec mv {} "$DST" \;
   sleep 5
done

It basically watches a directory called Desktop/source and looks for any files in there whose name ends in "JPG" and which have not been modified in the last 2 seconds. If it finds any, it then moves them to directory called Desktop/dest and sleeps for 5 seconds before checking again.

You would need to start Terminal and make the script executable by typing:

chmod +x $HOME/Desktop/monitor

Then, whenever you want it running, you just double-click on the icon of monitor on your Desktop.


问:
convert xml to array in php + xml nodes
How to convert xml to array in php, how to manipulate the nodes that are inside RoomList. Any suggestions on how I can do this?</p>

```<code>       <UREFHotelesTarifas xmlns="http://zafiro.tse.com">
         <Token>10956C8E-E312-4E48-A7BD-09FEB99EEBFD</Token>
        <Preset>xx</Preset>
        <HotelIDLIst>1959,-1</HotelIDLIst>
        <FechaDesde>2017-12-17</FechaDesde>
        <FechaHasta>2017-12-20</FechaHasta>
       <RoomList>
         <Root xmlns="http://test.sytes.net">
            <RoomInfo>
               <AdultNum>2</AdultNum>
              <ChildNum>1</ChildNum>
              <ns1:ChildAges age="2"/>
           </RoomInfo>
        </Root>
     </RoomList>
     <Cupo>1</Cupo>
  </UREFHotelesTarifas>
</code>```

答:
```<code>$xml = simplexml_load_string($xmlString);
$array = json_decode(json_encode((array) $xml), 1);
</code>```

Title: convert xml to array in php + xml nodes

Body:
How to convert xml to array in php, how to manipulate the nodes that are inside RoomList. Any suggestions on how I can do this?

       <UREFHotelesTarifas xmlns="http://zafiro.tse.com">
         <Token>10956C8E-E312-4E48-A7BD-09FEB99EEBFD</Token>
        <Preset>xx</Preset>
        <HotelIDLIst>1959,-1</HotelIDLIst>
        <FechaDesde>2017-12-17</FechaDesde>
        <FechaHasta>2017-12-20</FechaHasta>
       <RoomList>
         <Root xmlns="http://test.sytes.net">
            <RoomInfo>
               <AdultNum>2</AdultNum>
              <ChildNum>1</ChildNum>
              <ns1:ChildAges age="2"/>
           </RoomInfo>
        </Root>
     </RoomList>
     <Cupo>1</Cupo>
  </UREFHotelesTarifas>


问:
c# Given 2 numbers X and Y, make X approach Y but not surpass it
I've been racking my brains for ages trying to work out a good formula for this.

Essentially what i want is given 2 numbers X and Y, I would like X to approach Y but not surpass it depending on the difference between the 2 numbers.

Both X and Y are floats between 0 and 1.

Examples:

X = 0 Y = 1. X should become about 0.7-0.8 ish.

X = 0.5 Y = 1 X should become between 0.8-0.9.

X = 0.9 y = 1 X should become 0.97 ish.

Heres what i've tried:

(1-X) * Y = Just gives linear progression....

0.08/(1.1-(Y-X)) - Better.. but gives a value 0.13 when the difference is 0.5, 0.8 when the difference is 1 and 0.4 when the difference is 0.9.... not quite what i wanted...

Any ideas guys?

Thanks,

Phil.

答:
```<code>y- y * Math.sqrt(y-x)*0.25
</code>```

Just a quick idea. It works for your test cases (kind of).

0.75

0.82

0.92

Body:
y- y * Math.sqrt(y-x)*0.25

Just a quick idea. It works for your test cases (kind of).

0.75

0.82

0.92


问:
Getting a class property value from a textbox
I am wondering how to return the value of a class property with the input of a textbox? i.e. the input in the nameTextBox would go to the Name property of a Pet class, the breedTextBox would be the Breed property, etc.

Using C# windows form.

答:
```<code>Pet pet = new Pet();
pet.Name = nameTextBox.Text;
</code>```

etc.

If your question is how to get this code executed then either have an "update" Button, and in its Click event handler run this code, or subscribe to the Textbox's TextChanged event and do it there. (You can also use binding, a bit more complicated. See here.)

Body:
Pet pet = new Pet();
pet.Name = nameTextBox.Text;

etc.

If your question is how to get this code executed then either have an "update" Button, and in its Click event handler run this code, or subscribe to the Textbox's TextChanged event and do it there. (You can also use binding, a bit more complicated. See here.)


问:
Trying to find a way to construct Julia `generator`
I'm new to Julia.
I mainly program in python.

In python,
if you want to iterate over a large set of values,
it is typical to construct a so-called generator to save memory usage.
Here is one example code:

```<code>def generator(N):
    for i in range(N):
        yield i
</code>```

I wonder if there is anything alike in Julia.
After reading julia manual,
@task macro seems to have the same (or similar) functionality as generator in python.
However,
after some experiments,
the memory usage seems to be larger than usual array in julia.

I use @time in IJulia to see the memory usage.
Here is my sample code:

[Update]: Add the code for generator method

(The generator method)

```<code>function generator(N::Int)
    for i in 1:N
        produce(i)
    end
end
</code>```

(generator version)

```<code>function fun_gener()
    sum = 0
    g = @task generator(100000)
    for i in g
        sum += i
    end
    sum
 end
</code>```

@time fun_gener()

elapsed time: 0.420731828 seconds (6507600 bytes allocated)

(array version)

```<code>function fun_arry()
    sum = 0
    c = [1:100000]
    for i in c
        sum += i
    end
    sum
end
</code>```

@time fun_arry()

elapsed time: 0.000629629 seconds (800144 bytes allocated)

Could anyone tell me why @task will require more space in this case?
And if I want to save memory usage as dealing with a large set of values,
what can I do?

答:
I think that Task has been superseded by Channel().  The usage in terms of Ben Lauwens's Fibonacci generator is:

```<code>fibonacci(n) = Channel(ctype=Int) do c
    a = 1
    b = 1
    for i in 1:n
        push!(c, a)
        a, b = b, a + b
    end
end
</code>```

it can be used using

```<code>for a in fibonacci(10)
    println(a)
end
1
1
2
3
5
8
13
21
34
55
</code>```

Body:
I'm new to Julia.
I mainly program in python.

In python,
if you want to iterate over a large set of values,
it is typical to construct a so-called generator to save memory usage.
Here is one example code:

def generator(N):
    for i in range(N):
        yield i

I wonder if there is anything alike in Julia.
After reading julia manual,
@task macro seems to have the same (or similar) functionality as generator in python.
However,
after some experiments,
the memory usage seems to be larger than usual array in julia.

I use @time in IJulia to see the memory usage.
Here is my sample code:

[Update]: Add the code for generator method

(The generator method)

function generator(N::Int)
    for i in 1:N
        produce(i)
    end
end

(generator version)

function fun_gener()
    sum = 0
    g = @task generator(100000)
    for i in g
        sum += i
    end
    sum
 end

@time fun_gener()

elapsed time: 0.420731828 seconds (6507600 bytes allocated)

(array version)

function fun_arry()
    sum = 0
    c = [1:100000]
    for i in c
        sum += i
    end
    sum
end

@time fun_arry()

elapsed time: 0.000629629 seconds (800144 bytes allocated)

Could anyone tell me why @task will require more space in this case?
And if I want to save memory usage as dealing with a large set of values,
what can I do?

Body:
I think that Task has been superseded by Channel().  The usage in terms of Ben Lauwens's Fibonacci generator is:

fibonacci(n) = Channel(ctype=Int) do c
    a = 1
    b = 1
    for i in 1:n
        push!(c, a)
        a, b = b, a + b
    end
end

it can be used using

for a in fibonacci(10)
    println(a)
end
1
1
2
3
5
8
13
21
34
55


问:
At underscore js, Can I get multiple columns with pluck method after input where method as linq select projection
```<code>var people = [
    {firstName : "Thein", city : "ny", qty : 5},
    {firstName : "Michael", city : "ny", qty : 3},
    {firstName : "Bloom", city : "nj", qty : 10}
];

var results=_.pluck(_.where(people, {city : "ny"}), 'firstName');
</code>```

For example : I need firstName and qty.

答:
YAAUu-Yep Another Answer Using underscore...

// use a proper browser to run this code snippet, a browser that is es6-compliant
let people = [{
    firstName: "Thein",
    city: "ny",
    qty: 5
  },
  {
    firstName: "Michael",
    city: "ny",
    qty: 3
  },
  {
    firstName: "Bloom",
    city: "nj",
    qty: 10
  }
];
// either you pick the properties you want
let picking = _.iteratee((person) => _(person).pick("firstName", "city"));
// either you omit the properties you do not want
let omitting = _.iteratee((person) => _(person).omit("qty"));
// create the filter by city
let living = (people, city) => _(people).where({
  "city": city
});
// put the "filter by city" into a mixin (as I assume it would be used again & again)
_.mixin({
  living: living
});
// do the thing (twice),
// these chaining methods could be done into a mixin as well
console.log("results by picking properties:", _(people).chain().living("ny").map(picking).value());
console.log("results by omitting properties:", _(people).chain().living("ny").map(omitting).value());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script></code>```

Body:
var people = [
    {firstName : "Thein", city : "ny", qty : 5},
    {firstName : "Michael", city : "ny", qty : 3},
    {firstName : "Bloom", city : "nj", qty : 10}
];

var results=_.pluck(_.where(people, {city : "ny"}), 'firstName');

For example : I need firstName and qty.

Body:
YAAUu-Yep Another Answer Using underscore...

// use a proper browser to run this code snippet, a browser that is es6-compliant
let people = [{
    firstName: "Thein",
    city: "ny",
    qty: 5
  },
  {
    firstName: "Michael",
    city: "ny",
    qty: 3
  },
  {
    firstName: "Bloom",
    city: "nj",
    qty: 10
  }
];
// either you pick the properties you want
let picking = _.iteratee((person) => _(person).pick("firstName", "city"));
// either you omit the properties you do not want
let omitting = _.iteratee((person) => _(person).omit("qty"));
// create the filter by city
let living = (people, city) => _(people).where({
  "city": city
});
// put the "filter by city" into a mixin (as I assume it would be used again & again)
_.mixin({
  living: living
});
// do the thing (twice),
// these chaining methods could be done into a mixin as well
console.log("results by picking properties:", _(people).chain().living("ny").map(picking).value());
console.log("results by omitting properties:", _(people).chain().living("ny").map(omitting).value());

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


问:
The feature you are trying to use is on a network resource that is unavailable
Web platform installer 4.5 was downloaded from official site.
During istallation got problem: it doesn't see wpi.msi file in the folder. But when I open this folder in explorer I see this file. Currently I have Web platform installer 4.0 and want to upgrate to version 4.5. So I can't install Web Platform Installer 4.5.

答:
Better late then never!

Try using this solution, looks like you have a corrupt registry key(s).

https://support.microsoft.com/en-us/help/17588/fix-problems-that-block-programs-from-being-installed-or-removed


问:
What dependencies to use in build.sbt for neo4j spark connector?
I was running scala code in spark-shell using this:

```<code>spark-shell --conf spark.neo4j.bolt.password=TestNeo4j --packages neo4j-contrib:neo4j-spark-connector:2.0.0-M2,graphframes:graphframes:0.2.0-spark2.0-s_2.11 -i neo4jsparkCluster.scala
</code>```

This would run execute just fine on the one spark instance, now I want to clusterize it.

I have a build.sbt file as follows:

```<code>name := "Simple Project"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
        "org.apache.spark" %% "spark-core" % "2.2.0",
        "org.apache.spark" %% "spark-sql" % "2.2.0"
)
</code>```

So I am not sure what I need in the libraryDependencies given the libs I am trying to load, I guess the syntax for it?

The errors I get with the sbt package are:

```<code>[info] Compiling 2 Scala sources to /Users/shane.thomas/SparkCourse/spark-sbt-builds/target/scala-2.11/classes...
[error] /Users/shane.thomas/SparkCourse/spark-sbt-builds/neo4jSparkCluster.scala:1: object neo4j is not a member of package org
[error] import org.neo4j.spark._
[error]            ^
[error] /Users/shane.thomas/SparkCourse/spark-sbt-builds/neo4jSparkCluster.scala:5: object streaming is not a member of package org.apache.spark
[error] import org.apache.spark.streaming._
[error]                         ^
[error] /Users/shane.thomas/SparkCourse/spark-sbt-builds/neo4jSparkCluster.scala:6: object streaming is not a member of package org.apache.spark
[error] import org.apache.spark.streaming.StreamingContext._
[error]                         ^
[error] /Users/shane.thomas/SparkCourse/spark-sbt-builds/neo4jSparkCluster.scala:539: not found: value Neo4j
[error]   val neo = Neo4j(sc)
[error]             ^
[error] four errors found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 5 s, completed Dec 7, 2017 2:45:00 PM
</code>```

答:
Try adding the following

```<code>resolvers += "Spark Packages Repo" at "http://dl.bintray.com/spark-packages/maven"
libraryDependencies += "neo4j-contrib" % "neo4j-spark-connector" % "2.1.0-M4"
</code>```

Taken from https://github.com/neo4j-contrib/neo4j-spark-connector under the SBT section

Body:
I was running scala code in spark-shell using this:

spark-shell --conf spark.neo4j.bolt.password=TestNeo4j --packages neo4j-contrib:neo4j-spark-connector:2.0.0-M2,graphframes:graphframes:0.2.0-spark2.0-s_2.11 -i neo4jsparkCluster.scala

This would run execute just fine on the one spark instance, now I want to clusterize it.

I have a build.sbt file as follows:

name := "Simple Project"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
        "org.apache.spark" %% "spark-core" % "2.2.0",
        "org.apache.spark" %% "spark-sql" % "2.2.0"
)

So I am not sure what I need in the libraryDependencies given the libs I am trying to load, I guess the syntax for it?

The errors I get with the sbt package are:

[info] Compiling 2 Scala sources to /Users/shane.thomas/SparkCourse/spark-sbt-builds/target/scala-2.11/classes...
[error] /Users/shane.thomas/SparkCourse/spark-sbt-builds/neo4jSparkCluster.scala:1: object neo4j is not a member of package org
[error] import org.neo4j.spark._
[error]            ^
[error] /Users/shane.thomas/SparkCourse/spark-sbt-builds/neo4jSparkCluster.scala:5: object streaming is not a member of package org.apache.spark
[error] import org.apache.spark.streaming._
[error]                         ^
[error] /Users/shane.thomas/SparkCourse/spark-sbt-builds/neo4jSparkCluster.scala:6: object streaming is not a member of package org.apache.spark
[error] import org.apache.spark.streaming.StreamingContext._
[error]                         ^
[error] /Users/shane.thomas/SparkCourse/spark-sbt-builds/neo4jSparkCluster.scala:539: not found: value Neo4j
[error]   val neo = Neo4j(sc)
[error]             ^
[error] four errors found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 5 s, completed Dec 7, 2017 2:45:00 PM

Body:
Try adding the following

resolvers += "Spark Packages Repo" at "http://dl.bintray.com/spark-packages/maven"
libraryDependencies += "neo4j-contrib" % "neo4j-spark-connector" % "2.1.0-M4"

Taken from https://github.com/neo4j-contrib/neo4j-spark-connector under the SBT section


问:
HTML position = center-10px
I am making an HTML website. I have an map as an background picture and I need a button to be on the map. Like this:

But when I start scaling my site, this happens:
I know what is the problem: the position of the pictures is center-X px and center-Y px, not margin: 40% 0px 0px 20%. But how to do that? position: absolute; left: 50%-30px; top: 50%-83px doesn´t work.

答:
You can use negative margins which has better support than calc().

```<code>position: absolute;
left: 50%;
top: 50%;
margin-top: -83px;
margin-left: -30px;
</code>```

If you already have margins, you can just minus them from there. However, if they are defined as percentages or em's, then you're going to have to convert them accordingly.

Title: HTML position = center-10px

Body:
You can use negative margins which has better support than calc().

position: absolute;
left: 50%;
top: 50%;
margin-top: -83px;
margin-left: -30px;

If you already have margins, you can just minus them from there. However, if they are defined as percentages or em's, then you're going to have to convert them accordingly.


问:
applying a rule once only child selector maybe?
```<code>#mainContent .container{
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}
</code>```

how can only apply those rules to the first div with a class container?

答:
use the :first-child pseudo class:

```<code>#mainContent div.container:first-child {
  /* CSS rules here */
}
</code>```

Body:
#mainContent .container{
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}

how can only apply those rules to the first div with a class container?

Body:
use the :first-child pseudo class:

#mainContent div.container:first-child {
  /* CSS rules here */
}


问:
How To Organize An Array By Key String with Integer
How would I be able to organize the below array into another array using the integer value provided in the array object key?

```<code>[
  {
     "itemQty_0": "443"
   },
   {
     "itemDescription_0": "Et aspernatur aspernatur qui sed ut do enim vel dignissimos libero nisi aut adipisci pariatur Est"
   },
   {
      "itemCapCheckbox_0": "on"
   },
   {
     "itemQty_1": "44"
   },
   {
     "itemDescription_1": "44"
   }
]
</code>```

How can I organize this array into another array that looks like this?

```<code>items: [{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
},{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
 }]
</code>```

答:
Ok so for this we would need to aggregate the array of objects into a structure that looks more like the answer you want. You want to use maybe Array.reduce for that.

```<code>function ReduceItemToArray(acc, item){
  var key = Object.keys(item)[0]; //Get the key (eg "itemQty_1")
  var [newKey, index] = key.split("_"); //Get newkey and index from key ("itemQty" and "1" respectively)
  var newAcc = [...acc]; //make a copy of the current accumulator
  if(newAcc[Number(index)] === undefined) //If there is no bucket on that index, make an empty one
    newAcc[Number(index)] = {};
  newAcc[Number(index)][newKey] = item[key]; //Add the item
  return newAcc; //Return the new item
}

var items = input.reduce(ReduceItemToArray, []);
</code>```

Hope that helps! :)

Body:
How would I be able to organize the below array into another array using the integer value provided in the array object key?

[
  {
     "itemQty_0": "443"
   },
   {
     "itemDescription_0": "Et aspernatur aspernatur qui sed ut do enim vel dignissimos libero nisi aut adipisci pariatur Est"
   },
   {
      "itemCapCheckbox_0": "on"
   },
   {
     "itemQty_1": "44"
   },
   {
     "itemDescription_1": "44"
   }
]

How can I organize this array into another array that looks like this?

items: [{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
},{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
 }]

Body:
Ok so for this we would need to aggregate the array of objects into a structure that looks more like the answer you want. You want to use maybe Array.reduce for that.

function ReduceItemToArray(acc, item){
  var key = Object.keys(item)[0]; //Get the key (eg "itemQty_1")
  var [newKey, index] = key.split("_"); //Get newkey and index from key ("itemQty" and "1" respectively)
  var newAcc = [...acc]; //make a copy of the current accumulator
  if(newAcc[Number(index)] === undefined) //If there is no bucket on that index, make an empty one
    newAcc[Number(index)] = {};
  newAcc[Number(index)][newKey] = item[key]; //Add the item
  return newAcc; //Return the new item
}

var items = input.reduce(ReduceItemToArray, []);

Hope that helps! :)