问:
I get NullPointerException in Java
Hello I get NullPointerException in this program can you help me ? Author class has private attributes and getter setter methods. Fileoperations class read a file and use stringtokenizer to split line by line. I getting an error at " athr[0].setId(tempId); " line. When i read from file tempId equals 100. I think problem is at Autor class but I couldn't fix that.

Author

```<code>public class Author {

    private int id;
    private String name;
    private String univ;
    private String depart;
    private String email;
    private String article[] = new String[5];
    private int artCtr=0;

    public int getArtCtr() {
        return artCtr;
    }

    public void setArtCtr(int artCtr) {
        this.artCtr = artCtr;
    }

    FileOperations flp =new FileOperations();

    public String getArticle(int nmb) {
        return article[nmb];
    }

    public void setArticle(String article,int nmb) {
        this.article[nmb] = article;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUniv() {
        return univ;
    }

    public void setUniv(String univ) {
        this.univ = univ;
    }

    public String getDepart() {
        return depart;
    }

    public void setDepart(String depart) {
        this.depart = depart;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}
</code>```

FileOperations

```<code>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class FileOperations {

    Author athr[] = new Author[500];
    int athCtr = 0;
    int flag = 0;
    String temp;
    int tempId;

    public void strAthr(String path) throws IOException {
        String metin = "Suheyb";
        System.out.println(path);
        FileReader fl = new FileReader(path);

        try (BufferedReader read = new BufferedReader(fl)) {

            while (metin != null) {
                metin = read.readLine();
                if (metin != null) {
                    StringTokenizer str = new StringTokenizer(metin, "/t ");

                    if (str.hasMoreTokens()) {
                        temp = str.nextToken();
                        tempId = Integer.parseInt(str.nextToken());
                        System.out.println(tempId + " " + athCtr);

                        if (athCtr != 0) {
                            for (int i = 0; i < athCtr; i++) {
                                if (athr[i].getId() == tempId) {
                                    flag = 1;
                                    if (str.hasMoreTokens()) {
                                        athr[i].setName(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[i].setDepart(str.nextToken());
                                            if (str.hasMoreTokens()) {
                                                athr[i].setEmail(str
                                                        .nextToken());
                                                if (str.hasMoreTokens()) {
                                                    athr[i].setArticle(
                                                            str.nextToken(), 0);
                                                    athr[i].setArtCtr(1);
                                                    if (str.hasMoreTokens()) {
                                                        athr[i].setArticle(
                                                                str.nextToken(),
                                                                1);
                                                        athr[i].setArtCtr(2);
                                                        if (str.hasMoreTokens()) {
                                                            athr[i].setArticle(
                                                                    str.nextToken(),
                                                                    2);
                                                            athr[i].setArtCtr(3);
                                                            if (str.hasMoreTokens()) {
                                                                athr[i].setArticle(
                                                                        str.nextToken(),
                                                                        3);
                                                                athr[i].setArtCtr(4);
                                                                if (str.hasMoreTokens()) {
                                                                    athr[i].setArticle(
                                                                            str.nextToken(),
                                                                            4);
                                                                    athr[i].setArtCtr(5);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (flag != 0) {
                                flag = 0;
                                athr[athCtr].setId(tempId);
                                if (str.hasMoreTokens()) {
                                    athr[athCtr].setName(str.nextToken());
                                    if (str.hasMoreTokens()) {
                                        athr[athCtr].setDepart(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[athCtr].setEmail(str
                                                    .nextToken());
                                            if (str.hasMoreTokens()) {
                                                athr[athCtr].setArticle(
                                                        str.nextToken(), 0);
                                                athr[athCtr].setArtCtr(1);
                                                if (str.hasMoreTokens()) {
                                                    athr[athCtr].setArticle(
                                                            str.nextToken(), 1);
                                                    athr[athCtr].setArtCtr(2);
                                                    if (str.hasMoreTokens()) {
                                                        athr[athCtr]
                                                                .setArticle(
                                                                        str.nextToken(),
                                                                        2);
                                                        athr[athCtr]
                                                                .setArtCtr(3);
                                                        if (str.hasMoreTokens()) {
                                                            athr[athCtr]
                                                                    .setArticle(
                                                                            str.nextToken(),
                                                                            3);
                                                            athr[athCtr]
                                                                    .setArtCtr(4);
                                                            if (str.hasMoreTokens()) {
                                                                athr[athCtr]
                                                                        .setArticle(
                                                                                str.nextToken(),
                                                                                4);
                                                                athr[athCtr]
                                                                        .setArtCtr(5);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                athCtr++;

                            }

                        }

                        else {
                            System.out.println(tempId);
                            athr[0].setId(tempId);
                            System.out.println(athr[0].getId());
                            if (str.hasMoreTokens()) {

                                athr[athCtr].setName(str.nextToken());
                                if (str.hasMoreTokens()) {
                                    athr[athCtr].setDepart(str.nextToken());
                                    if (str.hasMoreTokens()) {
                                        athr[athCtr].setEmail(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[athCtr].setArticle(
                                                    str.nextToken(), 0);
                                            athr[athCtr].setArtCtr(1);
                                            if (str.hasMoreTokens()) {
                                                athr[athCtr].setArticle(
                                                        str.nextToken(), 1);
                                                athr[athCtr].setArtCtr(2);
                                                if (str.hasMoreTokens()) {
                                                    athr[athCtr].setArticle(
                                                            str.nextToken(), 2);
                                                    athr[athCtr].setArtCtr(3);
                                                    if (str.hasMoreTokens()) {
                                                        athr[athCtr]
                                                                .setArticle(
                                                                        str.nextToken(),
                                                                        3);
                                                        athr[athCtr]
                                                                .setArtCtr(4);
                                                        if (str.hasMoreTokens()) {
                                                            athr[athCtr]
                                                                    .setArticle(
                                                                            str.nextToken(),
                                                                4);
                                                athr[athCtr]
                                                        .setArtCtr(5);
                                            }
                                        }
                                    }
                                }

enter code here

        }
                                    }
                                }
                            }
                            athCtr++;
                        }
                    }
                }
            }
        }
    }

}
</code>```

答:
Your array doesn't have any elements!
you just declared it but you didn't initialize it!
Author athr[] =new Author[500];
now that array doesn't have any data, all the elements are null!
now when you are trying to use a element, you get NullPointException!
now first take </p>

```<code>    Author a= new Author();
    a.setName("bro");
    a.setId(123);
    arthr[0]=a; // you have an element in the first Index!
               // now, you want to initialize all
    for(int i=0; i< arthr.length; i++){
      arthr[i] =new Author();
      arthr[i].setName("bro");//you can set and get names, id's etc
}
</code>```

Title: I get NullPointerException in Java

Body:
Hello I get NullPointerException in this program can you help me ? Author class has private attributes and getter setter methods. Fileoperations class read a file and use stringtokenizer to split line by line. I getting an error at " athr[0].setId(tempId); " line. When i read from file tempId equals 100. I think problem is at Autor class but I couldn't fix that.

Author

public class Author {

    private int id;
    private String name;
    private String univ;
    private String depart;
    private String email;
    private String article[] = new String[5];
    private int artCtr=0;

    public int getArtCtr() {
        return artCtr;
    }

    public void setArtCtr(int artCtr) {
        this.artCtr = artCtr;
    }

    FileOperations flp =new FileOperations();

    public String getArticle(int nmb) {
        return article[nmb];
    }

    public void setArticle(String article,int nmb) {
        this.article[nmb] = article;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUniv() {
        return univ;
    }

    public void setUniv(String univ) {
        this.univ = univ;
    }

    public String getDepart() {
        return depart;
    }

    public void setDepart(String depart) {
        this.depart = depart;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

FileOperations

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class FileOperations {

    Author athr[] = new Author[500];
    int athCtr = 0;
    int flag = 0;
    String temp;
    int tempId;

    public void strAthr(String path) throws IOException {
        String metin = "Suheyb";
        System.out.println(path);
        FileReader fl = new FileReader(path);

        try (BufferedReader read = new BufferedReader(fl)) {

            while (metin != null) {
                metin = read.readLine();
                if (metin != null) {
                    StringTokenizer str = new StringTokenizer(metin, "/t ");

                    if (str.hasMoreTokens()) {
                        temp = str.nextToken();
                        tempId = Integer.parseInt(str.nextToken());
                        System.out.println(tempId + " " + athCtr);

                        if (athCtr != 0) {
                            for (int i = 0; i < athCtr; i++) {
                                if (athr[i].getId() == tempId) {
                                    flag = 1;
                                    if (str.hasMoreTokens()) {
                                        athr[i].setName(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[i].setDepart(str.nextToken());
                                            if (str.hasMoreTokens()) {
                                                athr[i].setEmail(str
                                                        .nextToken());
                                                if (str.hasMoreTokens()) {
                                                    athr[i].setArticle(
                                                            str.nextToken(), 0);
                                                    athr[i].setArtCtr(1);
                                                    if (str.hasMoreTokens()) {
                                                        athr[i].setArticle(
                                                                str.nextToken(),
                                                                1);
                                                        athr[i].setArtCtr(2);
                                                        if (str.hasMoreTokens()) {
                                                            athr[i].setArticle(
                                                                    str.nextToken(),
                                                                    2);
                                                            athr[i].setArtCtr(3);
                                                            if (str.hasMoreTokens()) {
                                                                athr[i].setArticle(
                                                                        str.nextToken(),
                                                                        3);
                                                                athr[i].setArtCtr(4);
                                                                if (str.hasMoreTokens()) {
                                                                    athr[i].setArticle(
                                                                            str.nextToken(),
                                                                            4);
                                                                    athr[i].setArtCtr(5);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (flag != 0) {
                                flag = 0;
                                athr[athCtr].setId(tempId);
                                if (str.hasMoreTokens()) {
                                    athr[athCtr].setName(str.nextToken());
                                    if (str.hasMoreTokens()) {
                                        athr[athCtr].setDepart(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[athCtr].setEmail(str
                                                    .nextToken());
                                            if (str.hasMoreTokens()) {
                                                athr[athCtr].setArticle(
                                                        str.nextToken(), 0);
                                                athr[athCtr].setArtCtr(1);
                                                if (str.hasMoreTokens()) {
                                                    athr[athCtr].setArticle(
                                                            str.nextToken(), 1);
                                                    athr[athCtr].setArtCtr(2);
                                                    if (str.hasMoreTokens()) {
                                                        athr[athCtr]
                                                                .setArticle(
                                                                        str.nextToken(),
                                                                        2);
                                                        athr[athCtr]
                                                                .setArtCtr(3);
                                                        if (str.hasMoreTokens()) {
                                                            athr[athCtr]
                                                                    .setArticle(
                                                                            str.nextToken(),
                                                                            3);
                                                            athr[athCtr]
                                                                    .setArtCtr(4);
                                                            if (str.hasMoreTokens()) {
                                                                athr[athCtr]
                                                                        .setArticle(
                                                                                str.nextToken(),
                                                                                4);
                                                                athr[athCtr]
                                                                        .setArtCtr(5);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                athCtr++;

                            }

                        }

                        else {
                            System.out.println(tempId);
                            athr[0].setId(tempId);
                            System.out.println(athr[0].getId());
                            if (str.hasMoreTokens()) {

                                athr[athCtr].setName(str.nextToken());
                                if (str.hasMoreTokens()) {
                                    athr[athCtr].setDepart(str.nextToken());
                                    if (str.hasMoreTokens()) {
                                        athr[athCtr].setEmail(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[athCtr].setArticle(
                                                    str.nextToken(), 0);
                                            athr[athCtr].setArtCtr(1);
                                            if (str.hasMoreTokens()) {
                                                athr[athCtr].setArticle(
                                                        str.nextToken(), 1);
                                                athr[athCtr].setArtCtr(2);
                                                if (str.hasMoreTokens()) {
                                                    athr[athCtr].setArticle(
                                                            str.nextToken(), 2);
                                                    athr[athCtr].setArtCtr(3);
                                                    if (str.hasMoreTokens()) {
                                                        athr[athCtr]
                                                                .setArticle(
                                                                        str.nextToken(),
                                                                        3);
                                                        athr[athCtr]
                                                                .setArtCtr(4);
                                                        if (str.hasMoreTokens()) {
                                                            athr[athCtr]
                                                                    .setArticle(
                                                                            str.nextToken(),
                                                                4);
                                                athr[athCtr]
                                                        .setArtCtr(5);
                                            }
                                        }
                                    }
                                }

enter code here

        }
                                    }
                                }
                            }
                            athCtr++;
                        }
                    }
                }
            }
        }
    }

}

Body:
Your array doesn't have any elements!
you just declared it but you didn't initialize it!
Author athr[] =new Author[500];
now that array doesn't have any data, all the elements are null!
now when you are trying to use a element, you get NullPointException!
now first take

    Author a= new Author();
    a.setName("bro");
    a.setId(123);
    arthr[0]=a; // you have an element in the first Index!
               // now, you want to initialize all
    for(int i=0; i< arthr.length; i++){
      arthr[i] =new Author();
      arthr[i].setName("bro");//you can set and get names, id's etc
}


来源: stackexchange

问:
What is a purpose of Lambda's with Receiver?
What is a purpose of Lambda's with Receiver in Kotlin, while we have extension functions ?

Two functions below do the same things, however first one is more readable and short:

```<code>fun main(args: Array<String>) {
    println("123".represents(123))
    println(123.represents("123"))
}

fun String.represents(another: Int) = toIntOrNull() == another

val represents: Int.(String) -> Boolean = {this == it.toIntOrNull()}
</code>```

答:
Lambdas with receivers are basically exactly the same as extension functions, they're just able to be stored in properties, and passed around to functions. This question is essentially the same as "What's the purpose of lambdas when we have functions?". The answer is much the same as well - it allows you to quickly create anonymous extension functions anywhere in your code.

There are many good use cases for this (see DSLs in particular), but I'll give one simple example here.

For instance, let's say you have a function like this:

```<code>fun buildString(actions: StringBuilder.() -> Unit): String {
    val builder = StringBuilder()
    builder.actions()
    return builder.toString()
}
</code>```

Calling this function would look like this:

```<code>val str = buildString {
    append("Hello")
    append(" ")
    append("world")
}
</code>```

There are a couple interesting things this language feature enabled:

Inside the lambda you pass to buildString, you're in a new scope and as such have new methods and properties available for use. In this specific case, you can use methods on the StringBuilder type without having to call them on any instance.

The actual StringBuilder instance these function calls are going to be made on is not managed by you - it's up to the internal implementation of the function to create one and call your extension function on it.

Consequently, it would also be possible for this function to do much more than just call the lambda you passed to it once on one StringBuilder - it could call it multiple times, on various StringBuilder instances, store it for later use, etc.

ContentLicense: CC BY-SA 3.0

Body:
What is a purpose of Lambda's with Receiver in Kotlin, while we have extension functions ?

Two functions below do the same things, however first one is more readable and short:

fun main(args: Array<String>) {
    println("123".represents(123))
    println(123.represents("123"))
}

fun String.represents(another: Int) = toIntOrNull() == another

val represents: Int.(String) -> Boolean = {this == it.toIntOrNull()}

Body:
Lambdas with receivers are basically exactly the same as extension functions, they're just able to be stored in properties, and passed around to functions. This question is essentially the same as "What's the purpose of lambdas when we have functions?". The answer is much the same as well - it allows you to quickly create anonymous extension functions anywhere in your code.

There are many good use cases for this (see DSLs in particular), but I'll give one simple example here.

For instance, let's say you have a function like this:

fun buildString(actions: StringBuilder.() -> Unit): String {
    val builder = StringBuilder()
    builder.actions()
    return builder.toString()
}

Calling this function would look like this:

val str = buildString {
    append("Hello")
    append(" ")
    append("world")
}

There are a couple interesting things this language feature enabled:

Inside the lambda you pass to buildString, you're in a new scope and as such have new methods and properties available for use. In this specific case, you can use methods on the StringBuilder type without having to call them on any instance.

The actual StringBuilder instance these function calls are going to be made on is not managed by you - it's up to the internal implementation of the function to create one and call your extension function on it.

Consequently, it would also be possible for this function to do much more than just call the lambda you passed to it once on one StringBuilder - it could call it multiple times, on various StringBuilder instances, store it for later use, etc.

ContentLicense: CC BY-SA 4.0


问:
How to access file shared with slack bot
I am writing a slack app having a bot user also. I am currently working on a workflow where if a user is sharing a file with the bot or uploading to a channel and then sharing a file with the bot I want to download that file. Till now what I have done is if a user is sharing a file then I am listening to file_share event and whenever I got the event then I am getting the file object with the event also having a field named "url_private" which helps me to download the file. But now the issue is to download the file I have request that URL along with user token or api token(Token that starts with xoxp-) but for a team that token is the token of the member who has installed the app in the workspace but for all other members I don't have the token so I am not able to download the file. So I want to know if I can get the token for all other members to download the file or my understanding is incorrect and I am not obliged to download the file that belongs to the user. Please help.</p>

答:
No, you do not need to gather access tokens from all you users.

Once a file has been shared in a channel with your bot you can download it using the bot's token as follows:

Make a GET call to the URL from the url_private property

Provide the bot's access token as authorization in the header. The syntax is:

Authorization: Bearer A_VALID_TOKEN

See here for reference and additional infos.


问:
How to get a list of installed android applications and pick one to run
I asked a similar question to this earlier this week but I'm still not understanding how to get a list of all installed applications and then pick one to run.

I've tried:

```<code>Intent intent = new Intent(ACTION_MAIN);
intent.addCategory(CATEGORY_LAUNCHER);
</code>```

and this only shows application that are preinstalled or can run the ACTION_MAIN Intent type.

I also know I can use PackageManager to get all the installed applications, but how do I use this to run a specific application?

答:
Get All the apps:

```<code>    PackageManager pm = getContext().getPackageManager();
    List<ApplicationInfo> apps = pm.getInstalledApplications(0);
</code>```

Check if installed app then open:

```<code>if((app.flags & (ApplicationInfo.FLAG_UPDATED_SYSTEM_APP | ApplicationInfo.FLAG_SYSTEM)) > 0) {
                String app_package = app.packageName;
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(app_package);
context.startActivity(launchIntent);
</code>```

Body:
I asked a similar question to this earlier this week but I'm still not understanding how to get a list of all installed applications and then pick one to run.

I've tried:

Intent intent = new Intent(ACTION_MAIN);
intent.addCategory(CATEGORY_LAUNCHER);

and this only shows application that are preinstalled or can run the ACTION_MAIN Intent type.

I also know I can use PackageManager to get all the installed applications, but how do I use this to run a specific application?

Body:
Get All the apps:

    PackageManager pm = getContext().getPackageManager();
    List<ApplicationInfo> apps = pm.getInstalledApplications(0);

Check if installed app then open:

if((app.flags & (ApplicationInfo.FLAG_UPDATED_SYSTEM_APP | ApplicationInfo.FLAG_SYSTEM)) > 0) {
                String app_package = app.packageName;
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(app_package);
context.startActivity(launchIntent);


问:
Creating latitude, longitude pairs for distance calculation, based on matching zip in 2 spark dataframes
I have a pyspark dataframe A, that has 3 columns:

```<code>Lat lon zip
-69 40  trp
-69 41  nxt
</code>```

I have another pyspark dataframe B, that has same columns, but values captured will be different:

```<code>Lat lon zip
-68 43  trp
-89 45  trp
</code>```

I want to create latitude longitude pairs for each record of A, based on matching zip in dataframe B.

So the output RDD pairs would be like:

```<code>(([-69,40],[-68,43]),
 ([-69,40],[-89,45]))
</code>```

Can I do this without looping? I was trying to replicate .map used here:Spark cartesian product

Unsuccessfully

答:
A cartesian product is a join without any join key, it projects all the lines of a dataframe on all the lines of another dataframe. Say you have 2 dataframes A and B with nA and nB rows respectively, then you'll end up with a dataframe with  nA x nB rows.

What you are looking for is a regular inner join with join key zip:

A = spark.createDataFrame([[-69,40,"trp"],[-69,41,"nxt"]], ["Lat","lon","zip"])
B = spark.createDataFrame([[-68,43,"trp"],[-89,45,"trp"]], ["Lat","lon","zip"])
A.join(B, "zip").show()

    +---+---+---+---+---+
    |zip|Lat|lon|Lat|lon|
    +---+---+---+---+---+
    |trp|-69| 40|-68| 43|
    |trp|-69| 40|-89| 45|
    +---+---+---+---+---+
```

<p><strong>Note:</strong> be carefull with column name disambiguation, you  can for instance put <code>lon, Lat</code> in a structure for each dataframe before joining them:</p>

<pre class="lang-py prettyprint-override"><code>import pyspark.sql.functions as psf
A = A.select("zip", psf.struct("Lat", "Long").alias("A"))
B = B.select("zip", psf.struct("Lat", "Long").alias("B"))

df = A.join(B, "zip")
df.show()
df.printSchema()

    +---+--------+--------+
    |zip|       A|       B|
    +---+--------+--------+
    |trp|[-69,40]|[-68,43]|
    |trp|[-69,40]|[-89,45]|
    +---+--------+--------+

    root
     |-- zip: string (nullable = true)
     |-- A: struct (nullable = false)
     |    |-- Lat: long (nullable = true)
     |    |-- lon: long (nullable = true)
     |-- B: struct (nullable = false)
     |    |-- Lat: long (nullable = true)
     |    |-- lon: long (nullable = true)
</code>```

Body:
I have a pyspark dataframe A, that has 3 columns:

Lat lon zip
-69 40  trp
-69 41  nxt

I have another pyspark dataframe B, that has same columns, but values captured will be different:

Lat lon zip
-68 43  trp
-89 45  trp

I want to create latitude longitude pairs for each record of A, based on matching zip in dataframe B.

So the output RDD pairs would be like:

(([-69,40],[-68,43]),
 ([-69,40],[-89,45]))

Can I do this without looping? I was trying to replicate .map used here:Spark cartesian product

Unsuccessfully

Body:
A cartesian product is a join without any join key, it projects all the lines of a dataframe on all the lines of another dataframe. Say you have 2 dataframes A and B with nA and nB rows respectively, then you'll end up with a dataframe with  nA x nB rows.

What you are looking for is a regular inner join with join key zip:

A = spark.createDataFrame([[-69,40,"trp"],[-69,41,"nxt"]], ["Lat","lon","zip"])
B = spark.createDataFrame([[-68,43,"trp"],[-89,45,"trp"]], ["Lat","lon","zip"])
A.join(B, "zip").show()

    +---+---+---+---+---+
    |zip|Lat|lon|Lat|lon|
    +---+---+---+---+---+
    |trp|-69| 40|-68| 43|
    |trp|-69| 40|-89| 45|
    +---+---+---+---+---+

Note: be carefull with column name disambiguation, you  can for instance put lon, Lat in a structure for each dataframe before joining them:

import pyspark.sql.functions as psf
A = A.select("zip", psf.struct("Lat", "Long").alias("A"))
B = B.select("zip", psf.struct("Lat", "Long").alias("B"))

df = A.join(B, "zip")
df.show()
df.printSchema()

    +---+--------+--------+
    |zip|       A|       B|
    +---+--------+--------+
    |trp|[-69,40]|[-68,43]|
    |trp|[-69,40]|[-89,45]|
    +---+--------+--------+

    root
     |-- zip: string (nullable = true)
     |-- A: struct (nullable = false)
     |    |-- Lat: long (nullable = true)
     |    |-- lon: long (nullable = true)
     |-- B: struct (nullable = false)
     |    |-- Lat: long (nullable = true)
     |    |-- lon: long (nullable = true)


问:
How to verify if the sitemap generated indexes return 200 code?
I have generated the Sitemap indexes for Google. The only issue which I have is that how to verify that all the indexes(URL's) which got generated work or not. Based on the guide it says something like this:

you write a script to test each URL in the sitemap against your application
  server and confirm that each link returns an HTTP 200 (OK) code. Broken links may indicate a mismatch
  between the URL formatting configuration of the Sitemap Generator

I just wanted to see if somebody had such experience on how to write such script?

答:
google webmaster tools will report you within "site configuration -> sitemaps" any HTTP errors and redirects (pretty much everything that is not an HTTP 200), additionally in the "Diagnostics -> Crawl Errors -> in Sitemaps" is another view of errors that occured while crawling urls that were listed within the sitemaps.

if that is not what you want, i would just do some logfile grep-ing. (grep for "googlebot" and an identifier of the urls that you listed within your sitemaps)

you could propably write your own crawler to pre-check if your sites return an HTTP 200, but well, if it returns an HTTP 200 for you now, does not mean it will return an HTTP 200 for googlebot next week / month / year. so i recommend to stick with google webmaster tools and logfile analysis (visualized with i.e.: munin, cacti, ...)

ContentLicense: CC BY-SA 2.5


问:
Rotate a cube to be isometric
I'm following this rotating cube tutorial and I'm trying to rotate the cube to an isometric perspective (45 degrees, 30 degrees).

The problem is, I think, is that the rotateY and rotateX functions alter the original values such that the two red dots in the middle of the cube (visually) don't overlap. (If that makes any sense)

How can I rotate the cube on it's X and Y axis at the same time so the functions don't effect each other?

const canvas = document.getElementById('stage');
    canvas.width = canvas.parentElement.clientWidth
    canvas.height = canvas.parentElement.clientHeight
    const context = canvas.getContext('2d');
    context.translate(200,200)

    var node0 = [-100, -100, -100];
    var node1 = [-100, -100,  100];
    var node2 = [-100,  100, -100];
    var node3 = [-100,  100,  100];
    var node4 = [ 100, -100, -100];
    var node5 = [ 100, -100,  100];
    var node6 = [ 100,  100, -100];
    var node7 = [ 100,  100,  100];
    var nodes = [node0, node1, node2, node3, node4, node5, node6, node7];

    var edge0  = [0, 1];
    var edge1  = [1, 3];
    var edge2  = [3, 2];
    var edge3  = [2, 0];
    var edge4  = [4, 5];
    var edge5  = [5, 7];
    var edge6  = [7, 6];
    var edge7  = [6, 4];
    var edge8  = [0, 4];
    var edge9  = [1, 5];
    var edge10 = [2, 6];
    var edge11 = [3, 7];
    var edges = [edge0, edge1, edge2, edge3, edge4, edge5, edge6, edge7, edge8, edge9, edge10, edge11];

    var draw = function(){

      for (var e=0; e<edges.length; e++){
        var n0 = edges[e][0]
        var n1 = edges[e][1]
        var node0 = nodes[n0];
        var node1 = nodes[n1];

        context.beginPath();
        context.moveTo(node0[0],node0[1]);
        context.lineTo(node1[0],node1[1]);
        context.stroke();
      }

      //draw nodes
      for (var n=0; n<nodes.length; n++){
        var node = nodes[n];
        context.beginPath();
        context.arc(node[0], node[1], 3, 0, 2 * Math.PI, false);
        context.fillStyle = 'red';
        context.fill();
      }
    }

    var rotateZ3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);
      for (var n=0; n< nodes.length; n++){
        var node = nodes[n];
        var x = node[0];
        var y = node[1];
        node[0] = x * cos_t - y * sin_t;
        node[1] = y * cos_t + x * sin_t;
      };
    };

    var rotateY3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);

      for (var n=0; n<nodes.length; n++){
        var node = nodes[n];
        var x = node[0];
        var z = node[2];
        node[0] = x * cos_t - z * sin_t;
        node[2] = z * cos_t + x * sin_t;
      }
    };

    var rotateX3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);

      for (var n = 0; n< nodes.length; n++){
        var node = nodes[n];
        var y = node[1];
        var z = node[2];

        node[1] = y * cos_t - z * sin_t;
        node[2] = z * cos_t + y * sin_t;
      }
    }

    rotateY3D(Math.PI/4);
    rotateX3D(Math.PI/6);

    draw();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#stage {
  background-color: cyan;
 }</code>```

<canvas id="stage" height='500px' width='500px'></canvas>```

Edit: I should have included a picture to further explain what I'm trying to achieve.  I have a room picture that is isometric (45°,30°) and I'm overlaying it with a canvas so that I can draw the cube on it.  As you can see it's slightly off, and I think its the effect of two compounding rotations since each function alters the original node coordinates.

答:
I think the issue may be that the rotation about the x-axis of the room is not 30°. In isometric images there is often an angle of 30° between the sides of a cube and the horizontal. But in order to get this horizontal angle, the rotation around the x-axis should be about 35° (atan(1/sqrt(2))). See the overview in the Wikipedia article.

Having said that, sometimes in computer graphics, the angle between the sides of a cube and the horizontal is about 27° (atan(0.5)), since this produces neater rastered lines on a computer screen. In that case, the rotation around the x-axis is 30°. Check out this article for a lot more information about the different types of projection.

Title: Rotate a cube to be isometric

Body:
I'm following this rotating cube tutorial and I'm trying to rotate the cube to an isometric perspective (45 degrees, 30 degrees).

The problem is, I think, is that the rotateY and rotateX functions alter the original values such that the two red dots in the middle of the cube (visually) don't overlap. (If that makes any sense)

How can I rotate the cube on it's X and Y axis at the same time so the functions don't effect each other?

const canvas = document.getElementById('stage');
    canvas.width = canvas.parentElement.clientWidth
    canvas.height = canvas.parentElement.clientHeight
    const context = canvas.getContext('2d');
    context.translate(200,200)

    var node0 = [-100, -100, -100];
    var node1 = [-100, -100,  100];
    var node2 = [-100,  100, -100];
    var node3 = [-100,  100,  100];
    var node4 = [ 100, -100, -100];
    var node5 = [ 100, -100,  100];
    var node6 = [ 100,  100, -100];
    var node7 = [ 100,  100,  100];
    var nodes = [node0, node1, node2, node3, node4, node5, node6, node7];

    var edge0  = [0, 1];
    var edge1  = [1, 3];
    var edge2  = [3, 2];
    var edge3  = [2, 0];
    var edge4  = [4, 5];
    var edge5  = [5, 7];
    var edge6  = [7, 6];
    var edge7  = [6, 4];
    var edge8  = [0, 4];
    var edge9  = [1, 5];
    var edge10 = [2, 6];
    var edge11 = [3, 7];
    var edges = [edge0, edge1, edge2, edge3, edge4, edge5, edge6, edge7, edge8, edge9, edge10, edge11];

    var draw = function(){

      for (var e=0; e<edges.length; e++){
        var n0 = edges[e][0]
        var n1 = edges[e][1]
        var node0 = nodes[n0];
        var node1 = nodes[n1];

        context.beginPath();
        context.moveTo(node0[0],node0[1]);
        context.lineTo(node1[0],node1[1]);
        context.stroke();
      }

      //draw nodes
      for (var n=0; n<nodes.length; n++){
        var node = nodes[n];
        context.beginPath();
        context.arc(node[0], node[1], 3, 0, 2 * Math.PI, false);
        context.fillStyle = 'red';
        context.fill();
      }
    }

    var rotateZ3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);
      for (var n=0; n< nodes.length; n++){
        var node = nodes[n];
        var x = node[0];
        var y = node[1];
        node[0] = x * cos_t - y * sin_t;
        node[1] = y * cos_t + x * sin_t;
      };
    };

    var rotateY3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);

      for (var n=0; n<nodes.length; n++){
        var node = nodes[n];
        var x = node[0];
        var z = node[2];
        node[0] = x * cos_t - z * sin_t;
        node[2] = z * cos_t + x * sin_t;
      }
    };

    var rotateX3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);

      for (var n = 0; n< nodes.length; n++){
        var node = nodes[n];
        var y = node[1];
        var z = node[2];

        node[1] = y * cos_t - z * sin_t;
        node[2] = z * cos_t + y * sin_t;
      }
    }

    rotateY3D(Math.PI/4);
    rotateX3D(Math.PI/6);

    draw();

#stage {
  background-color: cyan;
 }

<canvas id="stage" height='500px' width='500px'></canvas>

Edit: I should have included a picture to further explain what I'm trying to achieve.  I have a room picture that is isometric (45°,30°) and I'm overlaying it with a canvas so that I can draw the cube on it.  As you can see it's slightly off, and I think its the effect of two compounding rotations since each function alters the original node coordinates.


问:
Never prompted for password when installing LAMP server
I was following a tutorial on how to set up a LAMP Server on a Raspberry Pi but I got different results than the tutorial.

When installing MySQL using:

apt-get install mysql-server php-mysql -y

I was never prompted to provide a password. Afterwards, when installing phpMyAdmin, using:

apt-get install phpmyadmin -y

Again, I was not prompted to provide a password.

Then, of course, it came time to login to phpMyAdmin, but I did not have any password to use.... I have been working through a number of online tutorials to reset my MySQL password but None of them have worked. Furthermore, it appears that I have MariaDB instead of MySQL--so I tried some tutorials to reset that password, again, nothing.

Then, I tried reinstalling MySQL completely, but again, I was not prompted for a password.

Is there a way I can just force the terminal to prompt me for a password when reinstalling? That seems like it would be the easiest way to solve this issue.

答:
Did you try force to set mysql password?

mysql -u root -p

If this not work and you are in "apt-distro" try to completelly remove mysql with:

sudo apt-get purge mysql*
sudo apt-get autoremove
sudo apt-get autoclean

and then install it again.


问:
Xamarin : Reverse the bool value in xamarin listview viewcell
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have two images inside listview-viewcell, one is for showing like and other for unlike.
If the value of isUserLiked is true show the second image and otherwise show the first one. I try with !, but not working.
Here is my code:

```<code>   <StackLayout HeightRequest="500">
        <ListView x:Name="ListView1" RowHeight="500" HorizontalOptions="CenterAndExpand">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout
                            Orientation="Vertical">
                                <Image
                                    Source="unlike.png"
                                    IsVisible="{Binding !isUserLiked}">
                                </Image>
                                <Image
                                    Source="like.png"
                                    IsVisible="{Binding isUserLiked}">
                                </Image>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>
</code>```

How to reverse the binding value inside listview-viewcell.
Anybody please suggest a solution with working code.
Thanks in advance.

答:
You can't use operator in binding.
Best way to use trigger for that like this :

```<code><Image Source="unlike.png">
    <Image.Triggers>
        <DataTrigger TargetType="Image" Binding="{Binding isUserLiked}" Value="True">
            <Setter Property="Source" Value="like.png" />
        </DataTrigger>
    </Image.Triggers>
</Image>
</code>```

 Or

Another way to use converter like this:

Converter

```<code>public class InverseBoolConverter : IValueConverter, IMarkupExtension
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return !((bool)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
            //throw new NotImplementedException();
        }

        public object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }
</code>```

Now you can use in your Xaml code like this :

```<code><Image Source="unlike.png" IsVisible="{Binding isUserLiked, Converter={Helpers:InverseBoolConverter}}" />
</code>```

Don't forgot to add assembly in xaml header :

xmlns:Helpers="clr-namespace:MyNameSpace.Helpers"

Body:
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have two images inside listview-viewcell, one is for showing like and other for unlike.
If the value of isUserLiked is true show the second image and otherwise show the first one. I try with !, but not working.
Here is my code:

   <StackLayout HeightRequest="500">
        <ListView x:Name="ListView1" RowHeight="500" HorizontalOptions="CenterAndExpand">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout
                            Orientation="Vertical">
                                <Image
                                    Source="unlike.png"
                                    IsVisible="{Binding !isUserLiked}">
                                </Image>
                                <Image
                                    Source="like.png"
                                    IsVisible="{Binding isUserLiked}">
                                </Image>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>

How to reverse the binding value inside listview-viewcell.
Anybody please suggest a solution with working code.
Thanks in advance.

Body:
You can't use operator in binding.
Best way to use trigger for that like this :

<Image Source="unlike.png">
    <Image.Triggers>
        <DataTrigger TargetType="Image" Binding="{Binding isUserLiked}" Value="True">
            <Setter Property="Source" Value="like.png" />
        </DataTrigger>
    </Image.Triggers>
</Image>

 Or

Another way to use converter like this:

Converter

public class InverseBoolConverter : IValueConverter, IMarkupExtension
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return !((bool)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
            //throw new NotImplementedException();
        }

        public object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }

Now you can use in your Xaml code like this :

<Image Source="unlike.png" IsVisible="{Binding isUserLiked, Converter={Helpers:InverseBoolConverter}}" />

Don't forgot to add assembly in xaml header :

xmlns:Helpers="clr-namespace:MyNameSpace.Helpers"


问:
Make nested children 100% height of variable height container without flexbox
I have a bunch of nested lists inside a variable height container, and I'd like all of the nested lists/children to take up 100% height of the container.

I have tried using flexbox, which works in principle, but with around 5-6 nested lists (of which all have display: flex; and flex-direction: column;) I'm noticing huge performance issues in Chrome, FF and Safari when adding more nested lists programmatically (too many reflows maybe?) so I can't use flexbox in this case. I've also not been able to get it to work using table and table-cell.

A very simple example here: https://jsfiddle.net/bf0f6zj5/

The markup:

```<code><ul>
  <li>
    <div>
      text 1
    </div>
    <ul>
      <li>
        <div>
          some very long text here
        </div>
        <ul>
          <li>
            <div>
              text 3
            </div>
            <ul>
              <li>text</li>
              <li>text</li>
              <li>text</li>
              <li>text</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>
</code>```

The CSS:

```<code>ul, li {
  margin:0;
  padding:0;
  list-style-type: none;
  overflow:hidden;
}

li {
  border-left: 1px solid grey;
  padding-left: 8px;
}

li > div {
  padding-right: 4px;
  float:left;
  writing-mode: vertical-rl;
}
</code>```

The goal is to make the left borders of the nested lists the same height as the largest one, without using flexbox.

Edit: Created a new fiddle https://jsfiddle.net/vgjkzhqq/3/ to show the performance problems I'm having with flexbox (notice how long it takes to render - over 2000ms for me)

Edit 2: pasted wrong link

答:
Flexbox is not causing performance problems, according to a lot of different sources, including Google Web developpers :

Flexbox layout isn't slow - Google Developpers

Does deep nesting flexbox layout cause performance issue? - SO

Use flexbox over older layout models - Google Developpers

TL;DR

Flexbox is usually faster than older display properties. As Paul says:

Old flexbox (display: box) is 2.3x slower than new flexbox (display: flex)

Hope it helps :)

Body:
I have a bunch of nested lists inside a variable height container, and I'd like all of the nested lists/children to take up 100% height of the container.

I have tried using flexbox, which works in principle, but with around 5-6 nested lists (of which all have display: flex; and flex-direction: column;) I'm noticing huge performance issues in Chrome, FF and Safari when adding more nested lists programmatically (too many reflows maybe?) so I can't use flexbox in this case. I've also not been able to get it to work using table and table-cell.

A very simple example here: https://jsfiddle.net/bf0f6zj5/

The markup:

      text 1

          some very long text here

              text 3

text

text

text

text

The CSS:

ul, li {
  margin:0;
  padding:0;
  list-style-type: none;
  overflow:hidden;
}

li {
  border-left: 1px solid grey;
  padding-left: 8px;
}

li > div {
  padding-right: 4px;
  float:left;
  writing-mode: vertical-rl;
}

The goal is to make the left borders of the nested lists the same height as the largest one, without using flexbox.

Edit: Created a new fiddle https://jsfiddle.net/vgjkzhqq/3/ to show the performance problems I'm having with flexbox (notice how long it takes to render - over 2000ms for me)

Edit 2: pasted wrong link


问:
Change BrowserWindow position dynamically in electron app
I am creating a menu in window.js when we click on it the current browser window position will change. I have my app.js file where I have created my browserWindow and have set x,y . Now how can I change the x,y values of current browserWindow ?

My BrowserWindow in app.js

```<code> window = new BrowserWindow({
      width: 265,
      height: screenheight,
      x: screenXPosition,
      y: 0,
      icon: "icon.ico",
      skipTaskbar: true,
      alwaysOnTop: false,
      show: false,
      frame: false,
      autoHideMenuBar: true,
      transparent: true,
      // resizable: false
    })
</code>```

I have one Window.js file where my menu is .Is it required to pass current window instance to window.js? If yes, how should I pass current browserWindow instance to window.js to app.js? and how can we change the x,y values?
Is it possible ?
my window.js menu

```<code>//Menu
const menu = new Menu()
// Build menu one item at a time, unlike
menu.append(new MenuItem({
    label: 'Settings'

}))
menu.append(new MenuItem({
    type: 'separator'
}))
menu.append(new MenuItem({
    label: 'position',
    submenu: [{
            label: 'right',
            role: '25%',
            type: 'checkbox',
            checked: true,
            click: function () {
                console.log('25%');
            }
        },
        {
            type: 'separator'
        },
        {
            label: 'left',
            role: '50%',
            click: function () {
                console.log('50%');
            }
        },
        {
            type: 'separator'
        },
        {
            label: 'center',
            role: '50%',
            click: function () {
                console.log('50%');
            }
        }
    ]
}))
window.addEventListener('contextmenu', (e) => {
    e.preventDefault()
    menu.popup(remote.getCurrentWindow())
}, false)
</code>```

答:
In the menuItem click there is a argument for the current browserWindow.

To set the x and y position you can use window.setPosition(x, y).

So your menuItem code would be something like this:

```<code>{
    label:   'right',
    role:    '25%',
    type:    'checkbox',
    checked: true,
    click:   function (item, focusedWindow) {
        console.log('25%');
        focusedWindow.setPosition(10, 10);
    }
}
</code>```

window.setPosition

menuItem arguments

Body:
I am creating a menu in window.js when we click on it the current browser window position will change. I have my app.js file where I have created my browserWindow and have set x,y . Now how can I change the x,y values of current browserWindow ?

My BrowserWindow in app.js

 window = new BrowserWindow({
      width: 265,
      height: screenheight,
      x: screenXPosition,
      y: 0,
      icon: "icon.ico",
      skipTaskbar: true,
      alwaysOnTop: false,
      show: false,
      frame: false,
      autoHideMenuBar: true,
      transparent: true,
      // resizable: false
    })

I have one Window.js file where my menu is .Is it required to pass current window instance to window.js? If yes, how should I pass current browserWindow instance to window.js to app.js? and how can we change the x,y values?
Is it possible ?
my window.js menu

//Menu
const menu = new Menu()
// Build menu one item at a time, unlike
menu.append(new MenuItem({
    label: 'Settings'

}))
menu.append(new MenuItem({
    type: 'separator'
}))
menu.append(new MenuItem({
    label: 'position',
    submenu: [{
            label: 'right',
            role: '25%',
            type: 'checkbox',
            checked: true,
            click: function () {
                console.log('25%');
            }
        },
        {
            type: 'separator'
        },
        {
            label: 'left',
            role: '50%',
            click: function () {
                console.log('50%');
            }
        },
        {
            type: 'separator'
        },
        {
            label: 'center',
            role: '50%',
            click: function () {
                console.log('50%');
            }
        }
    ]
}))
window.addEventListener('contextmenu', (e) => {
    e.preventDefault()
    menu.popup(remote.getCurrentWindow())
}, false)

Body:
In the menuItem click there is a argument for the current browserWindow.

To set the x and y position you can use window.setPosition(x, y).

So your menuItem code would be something like this:

{
    label:   'right',
    role:    '25%',
    type:    'checkbox',
    checked: true,
    click:   function (item, focusedWindow) {
        console.log('25%');
        focusedWindow.setPosition(10, 10);
    }
}

window.setPosition

menuItem arguments


问:
Command not found and ImportError in Python for OSX
I have OSX El Captain with installed Python3.5 and Python2.7.
I have a folder with my python script and functions which I already added to the environment variable PATH and somehow[*] also to sys.path:

```<code>Project_folder/
- Python/
-- __init__.py
-- batchProc.py (written in Python 3.4)
-- (other python files)
</code>```

I set my PATH with a .bash_profile file:

```<code>PATH=“/Users/Robyc/Project_folder/Python:${PATH}”
export PATH
</code>```

And the folder it's there:

```<code>echo $PATH
“/Users/Robyc/Project_Folder/Python:/Library/Frameworks/Python.framework/Versions/3.5/bin:/opt/local/bin:/opt/local/sbin:/usr/local/mysql/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/Library/TeX/texbin”
</code>```

My sys.path variable

```<code>['/Applications/PyCharm CE.app/Contents/helpers/pydev', '/Applications/PyCharm CE.app/Contents/helpers/pydev', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages', '/Users/Robyc/Project_Folder/Python', '/Users/Robyc/Project_Folder/']
</code>```

I have two problems which I have the feeling that are linked to each other.

if I type bacthProc.py in the terminal I get Command not found. I need to go to ~/Project_folder/Python

if I run ~/Project_folder/Python/batchProc.py the code starts but I get ImportError: No module named Python.

I really don't understand what's wrong with my configuration.

[*] my ~/Project_folder was already there before, but I don't remember how I added it...
My PYTHONPATH is empty. I now used a pth file as suggested in the
   documentation to add my ~/Project_folder/Python folder to the
   sys.path, i.e. I created the following file:

```<code>/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/svn_code.pth
</code>```

which contains:
    /Users/Robyc/Project_folder/Python/

答:
For the sake of completeness I share the solution to the problem.

The problem was, as expected, in the PATH variable:
the text editor (TextEdit.app) I used to modify the .bash_profile modified the quotation marks ("...") in a way not correctly recognized by the shell.
This can be actually seen in the path I posted in the question above: the quotation marks shouldn't appear when doing echo $PATH in the terminal.
As a result the PATH variable was not properly set. That's why it wasn't possible to call python anymore.

Solution: open the bash_profile with nano and modify the quotation marks...
and never use again TextEdit to modify the bash_profile

Body:
I have OSX El Captain with installed Python3.5 and Python2.7.
I have a folder with my python script and functions which I already added to the environment variable PATH and somehow[*] also to sys.path:

Project_folder/
- Python/
-- __init__.py
-- batchProc.py (written in Python 3.4)
-- (other python files)

I set my PATH with a .bash_profile file:

PATH=“/Users/Robyc/Project_folder/Python:${PATH}”
export PATH

And the folder it's there:

echo $PATH
“/Users/Robyc/Project_Folder/Python:/Library/Frameworks/Python.framework/Versions/3.5/bin:/opt/local/bin:/opt/local/sbin:/usr/local/mysql/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/Library/TeX/texbin”

My sys.path variable

['/Applications/PyCharm CE.app/Contents/helpers/pydev', '/Applications/PyCharm CE.app/Contents/helpers/pydev', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages', '/Users/Robyc/Project_Folder/Python', '/Users/Robyc/Project_Folder/']

I have two problems which I have the feeling that are linked to each other.

if I type bacthProc.py in the terminal I get Command not found. I need to go to ~/Project_folder/Python

if I run ~/Project_folder/Python/batchProc.py the code starts but I get ImportError: No module named Python.

I really don't understand what's wrong with my configuration.

[*] my ~/Project_folder was already there before, but I don't remember how I added it...
My PYTHONPATH is empty. I now used a pth file as suggested in the
   documentation to add my ~/Project_folder/Python folder to the
   sys.path, i.e. I created the following file:

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/svn_code.pth

which contains:
    /Users/Robyc/Project_folder/Python/


问:
Pandas, are there any faster ways to update values?
Currently, my table has over 10000000 records, and there is a column named ID, and I want to update column named '3rd_col' with a new value if the ID is in the given list.

I use .loc and here is my code

```<code>for _id in given_ids:
    df.loc[df.ID == _id, '3rd_col'] = new_value
</code>```

But the performance of the above code is slow, how can I improve the performance of updating value?

Sorry, here I want to be more specific on my problem, different id has different values to be assigned based on a function and there are about 4 columns to be assigned.

```<code>for _id in given_ids:
    df.loc[df.ID == _id, '3rd_col'] = return_new_val_1(id)
    df.loc[df.ID == _id, '4rd_col'] = return_new_val_2(id)
    df.loc[df.ID == _id, '5rd_col'] = return_new_val_3(id)
    df.loc[df.ID == _id, '6rd_col'] = return_new_val_4(id)
</code>```

答:
You can create dictionary first and then replace:

```<code>#sample function
def return_new_val(x):
    return x * 3

given_ids = list('abc')

d = {_id: return_new_val(_id) for _id in given_ids}
print (d)
{'a': 'aaa', 'c': 'ccc', 'b': 'bbb'}

df = pd.DataFrame({'ID':list('abdefc'),
                   'M':[4,5,4,5,5,4]})

df['3rd_col'] = df['ID'].replace(d)
print (df)

  ID  M 3rd_col
0  a  4     aaa
1  b  5     bbb
2  d  4       d
3  e  5       e
4  f  5       f
5  c  4     ccc
</code>```

Or map, but then get NaNs for no match:

```<code>df['3rd_col'] = df['ID'].map(d)
print (df)

  ID  M 3rd_col
0  a  4     aaa
1  b  5     bbb
2  d  4     NaN
3  e  5     NaN
4  f  5     NaN
5  c  4     ccc
</code>```

EDIT:

If need append data by multiple functions first create new DataFrame and then join to original:

```<code>def return_new_val1(x):
    return x * 2

def return_new_val2(x):
    return x * 3

given_ids = list('abc')
df2 = pd.DataFrame({'ID':given_ids})
df2['3rd_col'] = df2['ID'].map(return_new_val1)
df2['4rd_col'] = df2['ID'].map(return_new_val2)
df2 = df2.set_index('ID')
print (df2)
   3rd_col 4rd_col
ID
a       aa     aaa
b       bb     bbb
c       cc     ccc
</code>```

```<code>df = pd.DataFrame({'ID':list('abdefc'),
                   'M':[4,5,4,5,5,4]})

df = df.join(df2, on='ID')
print (df)
  ID  M 3rd_col 4rd_col
0  a  4      aa     aaa
1  b  5      bb     bbb
2  d  4     NaN     NaN
3  e  5     NaN     NaN
4  f  5     NaN     NaN
5  c  4      cc     ccc

#bur replace NaNs by values in `ID`
cols = ['3rd_col','4rd_col']
df[cols] = df[cols].mask(df[cols].isnull(), df['ID'], axis=0)
print (df)
  ID  M 3rd_col 4rd_col
0  a  4      aa     aaa
1  b  5      bb     bbb
2  d  4       d       d
3  e  5       e       e
4  f  5       f       f
5  c  4      cc     ccc
</code>```

Body:
Currently, my table has over 10000000 records, and there is a column named ID, and I want to update column named '3rd_col' with a new value if the ID is in the given list.

I use .loc and here is my code

for _id in given_ids:
    df.loc[df.ID == _id, '3rd_col'] = new_value

But the performance of the above code is slow, how can I improve the performance of updating value?

Sorry, here I want to be more specific on my problem, different id has different values to be assigned based on a function and there are about 4 columns to be assigned.

for _id in given_ids:
    df.loc[df.ID == _id, '3rd_col'] = return_new_val_1(id)
    df.loc[df.ID == _id, '4rd_col'] = return_new_val_2(id)
    df.loc[df.ID == _id, '5rd_col'] = return_new_val_3(id)
    df.loc[df.ID == _id, '6rd_col'] = return_new_val_4(id)

Body:
You can create dictionary first and then replace:

#sample function
def return_new_val(x):
    return x * 3

given_ids = list('abc')

d = {_id: return_new_val(_id) for _id in given_ids}
print (d)
{'a': 'aaa', 'c': 'ccc', 'b': 'bbb'}

df = pd.DataFrame({'ID':list('abdefc'),
                   'M':[4,5,4,5,5,4]})

df['3rd_col'] = df['ID'].replace(d)
print (df)

  ID  M 3rd_col
0  a  4     aaa
1  b  5     bbb
2  d  4       d
3  e  5       e
4  f  5       f
5  c  4     ccc

Or map, but then get NaNs for no match:

df['3rd_col'] = df['ID'].map(d)
print (df)

  ID  M 3rd_col
0  a  4     aaa
1  b  5     bbb
2  d  4     NaN
3  e  5     NaN
4  f  5     NaN
5  c  4     ccc

EDIT:

If need append data by multiple functions first create new DataFrame and then join to original:

def return_new_val1(x):
    return x * 2

def return_new_val2(x):
    return x * 3

given_ids = list('abc')
df2 = pd.DataFrame({'ID':given_ids})
df2['3rd_col'] = df2['ID'].map(return_new_val1)
df2['4rd_col'] = df2['ID'].map(return_new_val2)
df2 = df2.set_index('ID')
print (df2)
   3rd_col 4rd_col
ID
a       aa     aaa
b       bb     bbb
c       cc     ccc

df = pd.DataFrame({'ID':list('abdefc'),
                   'M':[4,5,4,5,5,4]})

df = df.join(df2, on='ID')
print (df)
  ID  M 3rd_col 4rd_col
0  a  4      aa     aaa
1  b  5      bb     bbb
2  d  4     NaN     NaN
3  e  5     NaN     NaN
4  f  5     NaN     NaN
5  c  4      cc     ccc

#bur replace NaNs by values in `ID`
cols = ['3rd_col','4rd_col']
df[cols] = df[cols].mask(df[cols].isnull(), df['ID'], axis=0)
print (df)
  ID  M 3rd_col 4rd_col
0  a  4      aa     aaa
1  b  5      bb     bbb
2  d  4       d       d
3  e  5       e       e
4  f  5       f       f
5  c  4      cc     ccc


问:
db.table doesn't bring updated value ,When I update table manually from sql database
I am working on mvc c# , with sql database at backend. My problem is when I update a table's data manually from sql table at backend. It is not updated on the frontend until I open the website again after closing the webpage.

Here is the Image of database table where am updating it manually.

here am retrieving data from database.

```<code>  public ActionResult AddQuiz()
    {

        ViewBag.quizes_List = db.EntityFrameWorkConnection.Zasa_Quiz.OrderByDescending(mm => mm.quiz_code).ToList();
        return View();
    }
</code>```

This is where am using my ViewBag to display quizes list

```<code> @foreach (var item in @ViewBag.quizes_List)
                        {
                            <tr>
                                <td>
                                    <span class="badge bg-blue">@item.quiz_code</span>
                                </td>
                                <td>
                                    @item.quiz_title
                                </td>

                                <td><span class="badge bg-blue">@item.quiz_date.ToString().Substring(0, 10)</span></td>
                            </tr>
                        }
</code>```

EntityFrameWorkConnection is in constants class.
and db is declared like this in controller: and all this is working fine.

```<code> private static Constants db = new Constants();

 public class Constants
{
    public ZASA_AK_DBEntity EntityFrameWorkConnection = new ZASA_AK_DBEntity();
    public SqlConnection ADOConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["adocon"].ConnectionString);
    public string ConnectionString = ConfigurationManager.ConnectionStrings["adocon"].ConnectionString;

}
</code>```

答:
@Zainab The snippet you provided doesn't have any refresh or dynamic data retrieval. The AddQuiz() method retrieves data and calls the View. Now, if you change something in Backend, view should be refreshed or AddQuiz() should be called again to get the Updated Data.

Try .Reload() method on your entity and if that doesn't fix it, try disposing your dbcontext as soon as you are finished with the method call and create a new dbcontext everytime.

Body:
I am working on mvc c# , with sql database at backend. My problem is when I update a table's data manually from sql table at backend. It is not updated on the frontend until I open the website again after closing the webpage.

Here is the Image of database table where am updating it manually.

here am retrieving data from database.

  public ActionResult AddQuiz()
    {

        ViewBag.quizes_List = db.EntityFrameWorkConnection.Zasa_Quiz.OrderByDescending(mm => mm.quiz_code).ToList();
        return View();
    }

This is where am using my ViewBag to display quizes list

 @foreach (var item in @ViewBag.quizes_List)
                        {

                                    @item.quiz_code

                                    @item.quiz_title

                                @item.quiz_date.ToString().Substring(0, 10)

                        }

EntityFrameWorkConnection is in constants class.
and db is declared like this in controller: and all this is working fine.

 private static Constants db = new Constants();

 public class Constants
{
    public ZASA_AK_DBEntity EntityFrameWorkConnection = new ZASA_AK_DBEntity();
    public SqlConnection ADOConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["adocon"].ConnectionString);
    public string ConnectionString = ConfigurationManager.ConnectionStrings["adocon"].ConnectionString;

}


问:
CSV display on swings page
I am trying to read a csv and show it on a swings page, I am able to read but every time, it overwrites all the rows with the last row. Please help me figure out how to have all the rows displayed</p>

```<code>/*View Data UI code*/
        try
        {
            br = new BufferedReader(new FileReader(csvFile));
             while ((line = br.readLine()) != null)
            {
                 while ((line = br.readLine()) != null)
                {
                // use comma as separator
                  String cellValue[] = line.split(",");
                  String data[][]={{cellValue[1],cellValue[2],cellValue[3],cellValue[4],cellValue[5],cellValue[6],cellValue[7],cellValue[8]}
                  };
                  String column[]={"Date","Shop","Item","Category","Quantity","Units","Amount","Payment"};
                  System.out.println(data);
                  JTable jt = new JTable(data,column);
                  jt.setPreferredScrollableViewportSize(jt.getPreferredSize());
                 // jt.setFillsViewportHeight(true);
                  sp=new JScrollPane(jt);
                }
            }

        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (br != null)
            {
                try
                {
                    br.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        /*End of Data UI Code*/
</code>```

答: I think your problem might be that you create a new JTable for every run of your loop. That would explain why you only see the last row.

Title: CSV display on swings page

Body:
I am trying to read a csv and show it on a swings page, I am able to read but every time, it overwrites all the rows with the last row. Please help me figure out how to have all the rows displayed

/*View Data UI code*/
        try
        {
            br = new BufferedReader(new FileReader(csvFile));
             while ((line = br.readLine()) != null)
            {
                 while ((line = br.readLine()) != null)
                {
                // use comma as separator
                  String cellValue[] = line.split(",");
                  String data[][]={{cellValue[1],cellValue[2],cellValue[3],cellValue[4],cellValue[5],cellValue[6],cellValue[7],cellValue[8]}
                  };
                  String column[]={"Date","Shop","Item","Category","Quantity","Units","Amount","Payment"};
                  System.out.println(data);
                  JTable jt = new JTable(data,column);
                  jt.setPreferredScrollableViewportSize(jt.getPreferredSize());
                 // jt.setFillsViewportHeight(true);
                  sp=new JScrollPane(jt);
                }
            }

        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (br != null)
            {
                try
                {
                    br.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        /*End of Data UI Code*/


问:
How do I sort a list of words by their letter endings?
How do I sort a list of strings by the last two characters

Input:

```<code> ['abby', 'acts', 'aden', 'afro', 'agni', 'agra', 'aida', 'ainu', 'alba', 'aldo', 'alec', 'alex', 'alma', 'alpo', 'alps', 'alta', 'alva', 'amie', 'amos']
</code>```

Output:

```<code>**aa
**ab
**ac
**ad
**ae
**af
**ag
**ah
**ai
**aj
**ak
**al
**am
**an
**ao
**ap
**aq
**ar
**as
**at
**au
**av
**aw
**ax
**ay
**az
etc...
**ba
**ca
**da
**ea
**fa
**ga
etc...
</code>```

答:
This is indeed where lambda becomes useful. If you don't understand lambda, let this example explain it for you:

```<code>l =  ['abby', 'acts', 'aden', 'afro', 'agni', 'agra', 'aida', 'ainu', 'alba', 'aldo', 'alec', 'alex', 'alma', 'alpo', 'alps', 'alta', 'alva', 'amie', 'amos']
</code>```

Now you can do:

```<code>sorted(l, key = lambda x: x[-2:])
</code>```

or the equivalent without lambda:

```<code>def func(x):
    return x[-2:]

sorted(l, key = func)
</code>```

But with a function you can build in more logic too without losing readability.
For instance deciding what to do with words that are not of length 4.

```<code>def func(x):
    if len(x) == 4:
        return x[-2:]
    else:
        return ''
</code>```

You also have the option to use:

sorted(list) # which creates a copy of the list that is sorted

list.sort() # which sorts the list itself

Body:
How do I sort a list of strings by the last two characters

Input:

 ['abby', 'acts', 'aden', 'afro', 'agni', 'agra', 'aida', 'ainu', 'alba', 'aldo', 'alec', 'alex', 'alma', 'alpo', 'alps', 'alta', 'alva', 'amie', 'amos']

Output:

**aa
**ab
**ac
**ad
**ae
**af
**ag
**ah
**ai
**aj
**ak
**al
**am
**an
**ao
**ap
**aq
**ar
**as
**at
**au
**av
**aw
**ax
**ay
**az
etc...
**ba
**ca
**da
**ea
**fa
**ga
etc...

Body:
This is indeed where lambda becomes useful. If you don't understand lambda, let this example explain it for you:

l =  ['abby', 'acts', 'aden', 'afro', 'agni', 'agra', 'aida', 'ainu', 'alba', 'aldo', 'alec', 'alex', 'alma', 'alpo', 'alps', 'alta', 'alva', 'amie', 'amos']

Now you can do:

sorted(l, key = lambda x: x[-2:])

or the equivalent without lambda:

def func(x):
    return x[-2:]

sorted(l, key = func)

But with a function you can build in more logic too without losing readability.
For instance deciding what to do with words that are not of length 4.

def func(x):
    if len(x) == 4:
        return x[-2:]
    else:
        return ''

You also have the option to use:

sorted(list) # which creates a copy of the list that is sorted

list.sort() # which sorts the list itself


问:
What is the purpose of python 2.7's download package "Windows x86 MSI program database"?
Upgrading from python 2.5/2.6 to python 2.7 on WinXP, I've found new download package forms for python at http://www.python.org/download/releases/2.7.1/.

So I'm wondering what is the purpose of python 2.7's download package "Windows x86 MSI program database"? Searching on web didn't bring me clarifications on this.

Actually it contains lots for .pdb library files, which on my PC are associated to Palm PDB files. This should be false, as Palm OS is dead.

答: .pdb is an extension used by Visual Studio for debugging token databases. That package looks like it's there for those who wish to debug Python. You'll still need the standard Python libraries/executables if you wish to debug python.</p>


问:
Get non matching records from School table (highlighted)

I want to get the highlighted records from table 'School' which has the subject not in Tution. Tried left join which is going wrong for some reason. Can someone help please. I am using sql server.

答:
```<code>SELECT Student, Subject, Marks FROM School
EXCEPT
SELECT Student, Subject, Marks FROM Tution
</code>```


问:
Does the installation of a PHP extension require a restart or reload of PHP-FPM?
In my specific case I work with a CentOS 7 environment with both PHP-FPM 5.4 and 7.1 installed. I recently installed php-pecl-imagick and was wondering if a reload or restart was in order to make use of the service, or not at all. (and if httpd needed to be restarted/reloaded) The PHP manual doesn't seem to give an answer on this, and I've seen different recommendations in installation manuals.</p>

答:
You need to restart the apache service after PHP extensions are installed / uninstalled. If you have SSH communication, you can try the command below.

service http restart
// service (service name) restart```


问:
Starting neo4j gives exception saying "Address 127.0.0.1:7687 is already in use, cannot bind to it"
While starting neo4j browser from an Ubuntu terminal by running ./bin/neo4j, the following error is occurring. How can I solve this error?

ERROR Failed to start Neo4j: Starting Neo4j failed: Component
  'org.neo4j.server.database.LifecycleManagingDatabase@bdc8014' was
  successfully initialized, but failed to start. Please see the attached
  cause exception "Address 127.0.0.1:7687 is already in use, cannot bind
  to it.". Starting Neo4j failed: Component
  'org.neo4j.server.database.LifecycleManagingDatabase@bdc8014' was
  successfully initialized, but failed to start. Please see the attached
  cause exception "Address 127.0.0.1:7687 is already in use, cannot bind
  to it.". org.neo4j.server.ServerStartupException: Starting Neo4j
  failed: Component
  'org.neo4j.server.database.LifecycleManagingDatabase@bdc8014' was
  successfully initialized, but failed to start. Please see the attached
  cause exception "Address 127.0.0.1:7687 is already in use, cannot bind
  to it.".  at
  org.neo4j.server.exception.ServerStartupErrors.translateToServerStartupError(ServerStartupErrors.java:68)
    at
  org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:219)
    at
  org.neo4j.server.ServerBootstrapper.start(ServerBootstrapper.java:111)
    at
  org.neo4j.server.ServerBootstrapper.start(ServerBootstrapper.java:79)
    at
  org.neo4j.server.CommunityEntryPoint.main(CommunityEntryPoint.java:32)
  Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component
  'org.neo4j.server.database.LifecycleManagingDatabase@bdc8014' was
  successfully initialized, but failed to start. Please see the attached
  cause exception "Address 127.0.0.1:7687 is already in use, cannot bind
  to it.".  at
  org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:466)
    at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
    at
  org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:211)
    ... 3 more Caused by: java.lang.RuntimeException: Error starting
  org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory,
  /home/app42admin/neo4jcommunityedition/neo4j-community-3.4.0-alpha01/data/databases/graph.db
    at
  org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.initFacade(GraphDatabaseFacadeFactory.java:211)
    at
  org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.newFacade(GraphDatabaseFacadeFactory.java:126)
    at
  org.neo4j.server.CommunityNeoServer.lambda$static$0(CommunityNeoServer.java:58)
    at
  org.neo4j.server.database.LifecycleManagingDatabase.start(LifecycleManagingDatabase.java:88)
    at
  org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:445)
    ... 5 more Caused by: org.neo4j.kernel.lifecycle.LifecycleException:
  Component 'org.neo4j.bolt.transport.NettyServer@3e850122' was
  successfully initialized, but failed to start. Please see the attached
  cause exception "Address 127.0.0.1:7687 is already in use, cannot bind
  to it.".  at
  org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:466)
    at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
    at
  org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:445)
    at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
    at
  org.neo4j.kernel.extension.KernelExtensions.start(KernelExtensions.java:84)
    at
  org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:445)
    at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
    at
  org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.initFacade(GraphDatabaseFacadeFactory.java:207)
    ... 9 more Caused by: org.neo4j.helpers.PortBindException: Address
  127.0.0.1:7687 is already in use, cannot bind to it.  at io.netty.channel.unix.Errors.newIOException(Errors.java:117)     at
  io.netty.channel.unix.Socket.bind(Socket.java:285)    at
  io.netty.channel.epoll.AbstractEpollChannel.doBind(AbstractEpollChannel.java:696)
    at
  io.netty.channel.epoll.EpollServerSocketChannel.doBind(EpollServerSocketChannel.java:70)
    at
  io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:558)
    at
  io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1283)
    at
  io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:501)
    at
  io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:486)
    at
  io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:989)
    at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:254)
    at
  io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:365)
    at
  io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)>    at
  io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:403)
    at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:309)
    at
  io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
    at java.lang.Thread.run(Thread.java:748) 2017-11-15 09:54:42.077+0000
  INFO  Neo4j Server shutdown initiated by request

答:
The root error is Address 127.0.0.1:7687 is already in use, cannot bind to it.

So you already have something on your computer that is using the port 7687.

Do you have an other Neo4j instance that is running?
Or do you have an other server that i using the port 7687?


问:
How to find Outlook contact Unique ID?
I want to see all fields of the contacts in outlook. Here the contacts are synchronized from D365. All fields that are coming from D365 will also be shown in outlook contacts (fields such as PrimaryId, CreatedBy, Owner, CreatedDate, modified By, modifiedDate etc.. )

When I open the contacts, not all fields are showing. How can I see all fields of the records?

Suggestions are appreciated.

答:
In Outlook client for CRM, follow these steps to view the fields.

The EntryID is the unique identifier for each mail object in the user’s mailbox. This value is also used in the idMappingTable to relate the CRMID to the appropriate Outlook EntryID.

crmEntryID (*) corresponds to the Outlook EntryID of the object

Crmid corresponds to the created record’s unique GUID in CRM

Read more.

Title: How to find Outlook contact Unique ID?


问:
Lambda expressions support in VS2008 SP1
Is there support for lambda expressions from C++ 0x in Visual Studio 2008 SP1? Example below throws me syntax errors. Is there any '-Cpp0x' flag for compiler or something?

```<code>#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>

using namespace std;

int main()
{
  vector<int> v;

  for (int i = 0; i < 10; ++i)
  {
    v.push_back(i);
  }

  for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
  cout << endl;
}
</code>```

Thank you in advance.

答: Visual studio doesnot support, instead use Boost library.</p>

OwnerDisplayName: Jarek

Body:
Is there support for lambda expressions from C++ 0x in Visual Studio 2008 SP1? Example below throws me syntax errors. Is there any '-Cpp0x' flag for compiler or something?

#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>

using namespace std;

int main()
{
  vector<int> v;

  for (int i = 0; i < 10; ++i)
  {
    v.push_back(i);
  }

  for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
  cout << endl;
}

Thank you in advance.

LastEditorDisplayName: Serge

OwnerDisplayName: Vinay


问:
Can/Should I Use an Asynchronous Controller Here? (ASP.NET MVC 3)
I have this [HttpPost] action method:

```<code>[HttpPost]
public ActionResult AddReview(Review review)
{
   repository.Add(review);
   repository.Save();
   repository.UpdateSystemScoring(review.Id); // call SPROC with new Review ID.
   return View("Success", review);
}
</code>```

So, basically a user clicks a button, i add it to my database (via Entity Framework 4.0), save changes, and then i call a stored procedure with the identity field, which is that second last line of code.

This needs to be done after the review is saved (as the identity field is only created once Save is called, and EF persists the changes), and it is a system-wide calculation.

From the user point of view, he/she doesn't/shouldn't care that this calculation is happening.

This procedure can take anywhere from 0-20 seconds. It does not return anything.

Is this a candidate for an asynchronous controller?

Is there a way i can add the Review, and let another asynchronous controller handle the long-running SPROC call, so the user can be taken to the Success page immediately?

I must admit (partially ashamed of this): this is a rewrite of an existing system, and in the original system (ASP.NET Web Forms), i fired off another thread in order to achieve the above task - which is why i was wondering if the same principal can be applied to ASP.NET MVC 3.

I always try and avoid multi-threading in ASP.NET but user experience is the #1 priority, and i do not want the page timing out.

So - is this possible? Also happy to hear any other ideas. Also - i can't use triggers here, don't really want to go into too much detail why - but i can't.

答:
I think asynchronous controllers are more for things where the request may take a long time to return a response, but the main thread would spend most of that time waiting for another thread/process. This is mostly useful for ajax calls rather than main page load, when it is acceptable to just show a progress indicator until the response is returned.

I use a separate queueing system for this type of task, which is more robust and easier to work with but does take a bit more work to set up. If you really need to do it within the ASP.net process, a separate request is probably the best option, though there is some potential for the task not to run - for example I'm not sure what happens if the connection drops or the app pool recycles while an async task is running.

Body:
I have this [HttpPost] action method:

[HttpPost]
public ActionResult AddReview(Review review)
{
   repository.Add(review);
   repository.Save();
   repository.UpdateSystemScoring(review.Id); // call SPROC with new Review ID.
   return View("Success", review);
}

So, basically a user clicks a button, i add it to my database (via Entity Framework 4.0), save changes, and then i call a stored procedure with the identity field, which is that second last line of code.

This needs to be done after the review is saved (as the identity field is only created once Save is called, and EF persists the changes), and it is a system-wide calculation.

From the user point of view, he/she doesn't/shouldn't care that this calculation is happening.

This procedure can take anywhere from 0-20 seconds. It does not return anything.

Is this a candidate for an asynchronous controller?

Is there a way i can add the Review, and let another asynchronous controller handle the long-running SPROC call, so the user can be taken to the Success page immediately?

I must admit (partially ashamed of this): this is a rewrite of an existing system, and in the original system (ASP.NET Web Forms), i fired off another thread in order to achieve the above task - which is why i was wondering if the same principal can be applied to ASP.NET MVC 3.

I always try and avoid multi-threading in ASP.NET but user experience is the #1 priority, and i do not want the page timing out.

So - is this possible? Also happy to hear any other ideas. Also - i can't use triggers here, don't really want to go into too much detail why - but i can't.


问:
Set FAB icon color

current FAB

I would like to know how to change the icon color of the FAB (Floating Action Button) widget supplied by the 'com.android.support:design:22.2.0' library from green to white.

style.xml

```<code><resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/color_primary</item>
    <item name="colorPrimaryDark">@color/color_primary_dark</item>
    <item name="colorAccent">@color/accent</item>

</style>
<color name="color_primary">#00B33C</color>
<color name="color_primary_dark">#006622</color>
<color name="accent">#FFB366</color>
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include android:id="@+id/toolbar" layout="@layout/toolbar" />

    <TextView android:id="@+id/text"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:paddingTop="16dp"
        android:textSize="20sp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:paddingTop="8dp"
        android:paddingBottom="16dp" />

</LinearLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:src="@android:drawable/ic_input_add"
    android:layout_margin="24dp"
    app:elevation="6dp"
    app:pressedTranslationZ="12dp"
    app:borderWidth="0dp" />
</code>```

答:
It's easier than get the drawables, you only need to access to the color filter and set it to the color that you want.</p>

```<code>FloatingActionButton myFab = (FloatingActionButton) findViewById(R.id.myfabid);

myFab.setColorFilter(Color.WHITE);
</code>```

Title: Set FAB icon color

Body:
current FAB

I would like to know how to change the icon color of the FAB (Floating Action Button) widget supplied by the 'com.android.support:design:22.2.0' library from green to white.

style.xml

<resources>

<color name="color_primary">#00B33C</color>
<color name="color_primary_dark">#006622</color>
<color name="accent">#FFB366</color>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include android:id="@+id/toolbar" layout="@layout/toolbar" />

    <TextView android:id="@+id/text"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:paddingTop="16dp"
        android:textSize="20sp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:paddingTop="8dp"
        android:paddingBottom="16dp" />

</LinearLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:src="@android:drawable/ic_input_add"
    android:layout_margin="24dp"
    app:elevation="6dp"
    app:pressedTranslationZ="12dp"
    app:borderWidth="0dp" />

Body:
It's easier than get the drawables, you only need to access to the color filter and set it to the color that you want.

FloatingActionButton myFab = (FloatingActionButton) findViewById(R.id.myfabid);

myFab.setColorFilter(Color.WHITE);