问:
Saving index values and results in a vector, list or data frame in triple for loop in R
I have the following triple for loop in R :

```<code>res <- data.frame()

for (i in c(1,3,5,7,9,11,13)) {
  for (k in c(3,5,7,9,11,13)) {
    for (j in 1:41) {

      tmp <- chisq.test(matrix(c(counts[j,i],counts[j,(i+1)],counts[j,k],counts[j,(k+1)]),nrow=2,ncol=2,byrow=TRUE))

      res<-c(res,c(tmp$p.value))
}}}
</code>```

Where counts is a 14x41 data frame with genotype counts values (numbers like 600, 400, 240.. you can generate your own with random values in order to reproduce this in your computer).

And i want to save the resulting p.value of the chisq.test in a vector (res, from "results"). For now, the output is the following:

Which is OK, but now I also want it to have three more columns that indicate j,i and k values so then i can track where each p value came from, later. So, the desired output would be:

```<code>res
(p value 1) j1 i1 k1
(p value 2) j2 i2 k2
...
</code>```

So, I modified the loop adding j,i,k to the final line, like this:

```<code>res <- data.frame()

for (i in c(1,3,5,7,9,11,13)) {
  for (k in c(3,5,7,9,11,13)) {
    for (j in 1:41) {

      tmp <- chisq.test(matrix(c(counts[j,i],counts[j,(i+1)],counts[j,k],counts[j,(k+1)]),nrow=2,ncol=2,byrow=TRUE))

      res<-c(res,c(tmp$p.value,j,i,k))
}}}
</code>```

And it produces the following result (which I don't like):

Any thoughts? thank you !

答:
You could add a new row to a dataframe instead of concatenating the results together.

Maybe something like this:

```<code>res <- NULL

for (i in c(1,3,5,7,9,11,13)) {
  for (k in c(3,5,7,9,11,13)) {
    for (j in 1:41) {

      tmp <- chisq.test(matrix(c(counts[j,i],counts[j,(i+1)],counts[j,k],counts[j,(k+1)]),nrow=2,ncol=2,byrow=TRUE))

      res<-rbind(res, data.frame(p.value = tmp$p.value,
                                 i = i,
                                 j = j,
                                 k = k,
                                 stringsAsFactors = FALSE))
    }}}
</code>```

Data:

```<code>counts <- matrix(data = sample(1:1000, 574, replace = FALSE),
             nrow = 41, ncol = 14)
</code>```

Body:
I have the following triple for loop in R :

res <- data.frame()

for (i in c(1,3,5,7,9,11,13)) {
  for (k in c(3,5,7,9,11,13)) {
    for (j in 1:41) {

      tmp <- chisq.test(matrix(c(counts[j,i],counts[j,(i+1)],counts[j,k],counts[j,(k+1)]),nrow=2,ncol=2,byrow=TRUE))

      res<-c(res,c(tmp$p.value))
}}}

Where counts is a 14x41 data frame with genotype counts values (numbers like 600, 400, 240.. you can generate your own with random values in order to reproduce this in your computer).

And i want to save the resulting p.value of the chisq.test in a vector (res, from "results"). For now, the output is the following:

Which is OK, but now I also want it to have three more columns that indicate j,i and k values so then i can track where each p value came from, later. So, the desired output would be:

res
(p value 1) j1 i1 k1
(p value 2) j2 i2 k2
...

So, I modified the loop adding j,i,k to the final line, like this:

res <- data.frame()

for (i in c(1,3,5,7,9,11,13)) {
  for (k in c(3,5,7,9,11,13)) {
    for (j in 1:41) {

      tmp <- chisq.test(matrix(c(counts[j,i],counts[j,(i+1)],counts[j,k],counts[j,(k+1)]),nrow=2,ncol=2,byrow=TRUE))

      res<-c(res,c(tmp$p.value,j,i,k))
}}}

And it produces the following result (which I don't like):

Any thoughts? thank you !

Body:
You could add a new row to a dataframe instead of concatenating the results together.

Maybe something like this:

res <- NULL

for (i in c(1,3,5,7,9,11,13)) {
  for (k in c(3,5,7,9,11,13)) {
    for (j in 1:41) {

      tmp <- chisq.test(matrix(c(counts[j,i],counts[j,(i+1)],counts[j,k],counts[j,(k+1)]),nrow=2,ncol=2,byrow=TRUE))

      res<-rbind(res, data.frame(p.value = tmp$p.value,
                                 i = i,
                                 j = j,
                                 k = k,
                                 stringsAsFactors = FALSE))
    }}}

Data:

counts <- matrix(data = sample(1:1000, 574, replace = FALSE),
             nrow = 41, ncol = 14)


来源: stackexchange

问:
Unable to iterate a list and compare strings python
I am new to python programming and I really need help in comparing values in a list.

I have two lists(drink,food) .I'm not doing a comparison between two lists. What i am trying to do is comparing all the values within a list by itself.

So, I have to first compare all the values in drink list first using a for loop and an if-else statement. If there's a match in drink, I will do another for loop for food list and compare the values in food list using an if-else statement.

These are my code:

```<code>drinks = []
food = []

drinks.append("lemontea")
drinks.append("coke")
drinks.append("sprite")
drinks.append("orangejuice")
drinks.append("fantagrape")

food.append("nugget")
food.append("pizza")
food.append("chickenwing")
food.append("fries")
food.append("pizza")

for i in drinks:
    if i == drinks:
        for j in food:
            if j == food:
                print("fail")
    else:
         print("success")
</code>```

My issue is that I am supposed to be getting an 'failed' output as I have the same item in the food list that is pizza. Also, i'm not sure why am i getting 5 success output when im expected to get either only 1 'failed' or 'success' output.

This is my output i got:

```<code>success
success
success
success
success
</code>```

I would appreciate if any help was given. Thank you.

Update:
Thanks for the reply but however, it seem that people are confused with my question, hence im providing more information.

The reason why i have to compare each item in a list is because the items are generated randomly and are of string type which are then appended to the list. For example, the first item generated is '00100ABC'and so on. So in case, there are duplicate values/item in the list, i have to give an error message.

答:
```<code>#So you have
#drinks = ['lemontea', 'coke', 'sprite', 'orangejuice', 'fantagrape']
#food = ['nugget', 'pizza', 'chickenwing', 'fries', 'pizza']

for i in drinks:
    if i == drinks:
        for j in food:
            if j == food:
                print("fail")
    else:
         print("success")
</code>```

iteration 1

```<code>i = 'lemontea'
if i == drinks:
</code>```

Here you are evaluating does 'i==drinks',
where drinks is a list object and i is a string object.
As i and drinks are not equivalent, (they are different objects with different values)
the if statement evaluates to False,and
executes the else statement, which prints success.

iteration 2

```<code>i = 'coke'
if i == drinks
</code>```

Again, you are evaluating the string object 'coke' with the list object drinks,
which is False. This same condition applies to all conditions.

What you need to do is change your code to work with indexes

```<code>eg.
drinks[0] = 'lemontea'
drinks[1] = 'coke'
drinks[2] = 'sprite'
ect...
food[0] = 'nugget'
food[1] = 'pizza'
food[2] = 'chickenwing'
</code>```

to compare identical positions for equivalency use index

```<code>for i in range(0, len(drinks)):
    if drinks[i] == food[i]:            #compare index for index
        print('Matching index')
    else:
        print('Index does not match')
</code>```

Now this will not work if the item in the index's are not orderd in both list, eg so nuggets may not be in index 2 in both lists. To see if the item occurs in both lists regardless of order use 'in'

```<code>for item in food:    #eg item 0 = 'lemontea'
    if item in food and item in drinks:
        print(item, 'is in both lists')
    else:
        print(item, 'does not occur in both lists')
</code>```

Hope that helps.

Edit

```<code>for x in food:
    while food.count(x) > 1:  #breaks loops when only occurrence left.
        print("There are", food.count(x), 'occurrence of', x, 'in food')
        food.pop(x)
        print("deleted one occurrence")
</code>```

This loop tests each item in the loop for more than one occurrence and deletes all but one.

Alternative cleaner method. - use sets as it removes duplicates by definition.

```<code>unique_in_food = list(set(food))   #sets remove all duplicates by definition

now if you want unique items across multiples lists

unique_in_both = list( (set(food) | set(drinks) )
# set(a) | set(b)    finds the union between two sets
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to python programming and I really need help in comparing values in a list.

I have two lists(drink,food) .I'm not doing a comparison between two lists. What i am trying to do is comparing all the values within a list by itself.

So, I have to first compare all the values in drink list first using a for loop and an if-else statement. If there's a match in drink, I will do another for loop for food list and compare the values in food list using an if-else statement.

These are my code:

drinks = []
food = []

drinks.append("lemontea")
drinks.append("coke")
drinks.append("sprite")
drinks.append("orangejuice")
drinks.append("fantagrape")

food.append("nugget")
food.append("pizza")
food.append("chickenwing")
food.append("fries")
food.append("pizza")

for i in drinks:
    if i == drinks:
        for j in food:
            if j == food:
                print("fail")
    else:
         print("success")

My issue is that I am supposed to be getting an 'failed' output as I have the same item in the food list that is pizza. Also, i'm not sure why am i getting 5 success output when im expected to get either only 1 'failed' or 'success' output.

This is my output i got:

success
success
success
success
success

I would appreciate if any help was given. Thank you.

Update:
Thanks for the reply but however, it seem that people are confused with my question, hence im providing more information.

The reason why i have to compare each item in a list is because the items are generated randomly and are of string type which are then appended to the list. For example, the first item generated is '00100ABC'and so on. So in case, there are duplicate values/item in the list, i have to give an error message.

Body:
#So you have
#drinks = ['lemontea', 'coke', 'sprite', 'orangejuice', 'fantagrape']
#food = ['nugget', 'pizza', 'chickenwing', 'fries', 'pizza']

for i in drinks:
    if i == drinks:
        for j in food:
            if j == food:
                print("fail")
    else:
         print("success")

iteration 1

i = 'lemontea'
if i == drinks:

Here you are evaluating does 'i==drinks',
where drinks is a list object and i is a string object.
As i and drinks are not equivalent, (they are different objects with different values)
the if statement evaluates to False,and
executes the else statement, which prints success.

iteration 2

i = 'coke'
if i == drinks

Again, you are evaluating the string object 'coke' with the list object drinks,
which is False. This same condition applies to all conditions.

What you need to do is change your code to work with indexes

eg.
drinks[0] = 'lemontea'
drinks[1] = 'coke'
drinks[2] = 'sprite'
ect...
food[0] = 'nugget'
food[1] = 'pizza'
food[2] = 'chickenwing'

to compare identical positions for equivalency use index

for i in range(0, len(drinks)):
    if drinks[i] == food[i]:            #compare index for index
        print('Matching index')
    else:
        print('Index does not match')

Now this will not work if the item in the index's are not orderd in both list, eg so nuggets may not be in index 2 in both lists. To see if the item occurs in both lists regardless of order use 'in'

for item in food:    #eg item 0 = 'lemontea'
    if item in food and item in drinks:
        print(item, 'is in both lists')
    else:
        print(item, 'does not occur in both lists')

Hope that helps.

Edit

for x in food:
    while food.count(x) > 1:  #breaks loops when only occurrence left.
        print("There are", food.count(x), 'occurrence of', x, 'in food')
        food.pop(x)
        print("deleted one occurrence")

This loop tests each item in the loop for more than one occurrence and deletes all but one.

Alternative cleaner method. - use sets as it removes duplicates by definition.

unique_in_food = list(set(food))   #sets remove all duplicates by definition

now if you want unique items across multiples lists

unique_in_both = list( (set(food) | set(drinks) )
# set(a) | set(b)    finds the union between two sets


问:
Gradle does not use the Maven Local Repository for a new dependency
I have Maven with M2_HOME defined to /Users/manuelj/apache/maven/3.2.5

I have the settings.xml file, located on /Users/manuelj/apache/maven/3.2.5/conf/settings.xml

where I have the following declared:

```<code><localRepository>/Users/manuelj/apache/maven/repository</localRepository>
</code>```

Until here with Maven all works fine. Any new dependency goes there.

I have a project based with Gradle, among many things in my build.gradle, exists the following:

```<code>apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'
apply plugin: 'application'

version = '1.0.0'
sourceCompatibility = '1.8'

repositories {
   mavenLocal()
   mavenCentral()
}
… more
</code>```

Until here, all works fine too. Code compile, executes well.

My confusion is the following.

According with my understanding is that Gradle's mavenLocal() should use the same path than <localRepository> defined on Maven's settings.xml file.

Now confirming that in the Maven local repository exists some dependencies already downloaded.

When I execute for example gradle build, I did realize that

If a dependency already exists from the Maven Local Repository, it is used from there.

If a dependency does not exist from the Maven Local Repository Gradle download the new dependency to: /Users/manuelj/.gradle/caches/modules-2/files-2.1

I want that the new dependency go directly to the same Maven Local Repository.

Therefore, what extra configuration is need it?

答:
Use

```<code>mavenLocal()
</code>```

for example:

```<code>buildscript {
    ext {
        springBootVersion = '2.0.0.M1'
    }
    repositories {
        mavenCentral()
        mavenLocal()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
    mavenLocal()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('com.oracle:ojdbc6:11.2.0.4')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}
</code>```

I am using Gradle 3.5

ContentLicense: CC BY-SA 4.0

Body:
I have Maven with M2_HOME defined to /Users/manuelj/apache/maven/3.2.5

I have the settings.xml file, located on /Users/manuelj/apache/maven/3.2.5/conf/settings.xml

where I have the following declared:

<localRepository>/Users/manuelj/apache/maven/repository</localRepository>

Until here with Maven all works fine. Any new dependency goes there.

I have a project based with Gradle, among many things in my build.gradle, exists the following:

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'
apply plugin: 'application'

version = '1.0.0'
sourceCompatibility = '1.8'

repositories {
   mavenLocal()
   mavenCentral()
}
… more

Until here, all works fine too. Code compile, executes well.

My confusion is the following.

According with my understanding is that Gradle's mavenLocal() should use the same path than <localRepository> defined on Maven's settings.xml file.

Now confirming that in the Maven local repository exists some dependencies already downloaded.

When I execute for example gradle build, I did realize that

If a dependency already exists from the Maven Local Repository, it is used from there.

If a dependency does not exist from the Maven Local Repository Gradle download the new dependency to: /Users/manuelj/.gradle/caches/modules-2/files-2.1

I want that the new dependency go directly to the same Maven Local Repository.

Therefore, what extra configuration is need it?

Body:
Use

mavenLocal()

for example:

buildscript {
    ext {
        springBootVersion = '2.0.0.M1'
    }
    repositories {
        mavenCentral()
        mavenLocal()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
    mavenLocal()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('com.oracle:ojdbc6:11.2.0.4')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

I am using Gradle 3.5


问:
How to create NS_OPTIONS-style bitmask enumerations in Swift?
In Apple's documentation about interacting with C APIs, they describe the way NS_ENUM-marked C-style enumerations are imported as Swift enumerations. This makes sense, and since enumerations in Swift are readily provided as the enum value type it's easy to see how to create our own.

Further down, it says this about NS_OPTIONS-marked C-style options:

Swift also imports options marked with the NS_OPTIONS macro. Whereas
  options behave similarly to imported enumerations, options can also
  support some bitwise operations, such as &, |, and ~. In Objective-C,
  you represent an empty option set with the constant zero (0). In
  Swift, use nil to represent the absence of any options.

Given that there isn't an options value type in Swift, how can we create a C-Style options variable to work with?

答:
Use an Option Set Type, in swift 3 use OptionSet

```<code>struct ShippingOptions: OptionSet {
    let rawValue: Int

    static let nextDay    = ShippingOptions(rawValue: 1 << 0)
    static let secondDay  = ShippingOptions(rawValue: 1 << 1)
    static let priority   = ShippingOptions(rawValue: 1 << 2)
    static let standard   = ShippingOptions(rawValue: 1 << 3)

    static let express: ShippingOptions = [.nextDay, .secondDay]
    static let all: ShippingOptions = [.express, .priority, .standard]
}
</code>```

Body:
Use an Option Set Type, in swift 3 use OptionSet

struct ShippingOptions: OptionSet {
    let rawValue: Int

    static let nextDay    = ShippingOptions(rawValue: 1 << 0)
    static let secondDay  = ShippingOptions(rawValue: 1 << 1)
    static let priority   = ShippingOptions(rawValue: 1 << 2)
    static let standard   = ShippingOptions(rawValue: 1 << 3)

    static let express: ShippingOptions = [.nextDay, .secondDay]
    static let all: ShippingOptions = [.express, .priority, .standard]
}


问:
How do I get information of the variables from one class to another Action Listener class?
This is my code for the two file classes. What do I have to add/fix in order for the variables to transfer and print in the action listener JFrame? The error "No field named "(the variable I used in action listener from main class)" was found in type "Next"

```<code>  import java.awt.*; //for Dimension
  import javax.swing.*; //for GUI components

  public class MortgageCalculator
  {
   public static void main (String[] args)
    {
    JFrame frame = new JFrame ();
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame.setSize (new Dimension (300, 250));
    frame.setTitle ("Mortgage Calculator");

    frame.getContentPane ().setLayout (new BorderLayout ());

    frame.getContentPane ().add (new JLabel ("                          Personal Information"), BorderLayout.NORTH);

    JPanel centerPanel = new JPanel (new GridLayout (15, 1));
    centerPanel.add (new JLabel ("Full Name:"));
    JTextField nameField = new JTextField ();
    centerPanel.add (nameField);
    centerPanel.add (new JLabel ("Your Age:"));
    JTextField ageField = new JTextField ();
    centerPanel.add (ageField);
    centerPanel.add (new JLabel ("Yearly Income:"));
    JTextField incomeField = new JTextField ();
    centerPanel.add (incomeField);
    centerPanel.add (new JLabel ());
    centerPanel.add (new JLabel ("                          Mortgage Information"));

    centerPanel.add (new JLabel ("Price of Property:"));
    JTextField priceField = new JTextField ();
    centerPanel.add (priceField);
    centerPanel.add (new JLabel ("Down Payment:"));
    JTextField downPayField = new JTextField ();
    centerPanel.add (downPayField);
    centerPanel.add (new JLabel ("Interest Rate:"));
    JTextField interestRateField = new JTextField ();
    centerPanel.add (interestRateField);
    centerPanel.add (new JLabel ("Amortization Period (Years):"));
    frame.getContentPane ().add (centerPanel, BorderLayout.CENTER);

    JPanel southPanel = new JPanel (new GridLayout (5, 2));
    JButton amort20 = new JButton ("20");
    southPanel.add (amort20);
    JButton amort25 = new JButton ("25");
    southPanel.add (amort25);
    JButton amort30 = new JButton ("30");
    southPanel.add (amort30);
    southPanel.add (new JLabel ("Payment Option:"));
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ());
    JButton paymentWeek = new JButton ("Weekly");
    southPanel.add (paymentWeek);
    JButton paymentBiweek = new JButton ("Biweekly");
    southPanel.add (paymentBiweek);
    JButton paymentMonth = new JButton ("Monthly");
    southPanel.add (paymentMonth);
    //To add a blank line in frame, added three blank JLabels because it is 3 horiontal for grid layout
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ());
    southPanel.add (new JButton ("Clear Information"));
    southPanel.add (new JLabel ());
    JButton nextButton = new JButton ("Next");
    southPanel.add (nextButton);
    frame.getContentPane ().add (southPanel, BorderLayout.SOUTH);

    frame.pack ();
    frame.setVisible (true);
    nextButton.addActionListener (new Next ());

    //Gets the personal information from the text fields
    int age, income, price, downPay, interestRate;
    String name = nameField.getText ();
    String ageText = ageField.getText ();
    age = Integer.parseInt (ageText);
    String incomeText = incomeField.getText ();
    income = Integer.parseInt (ageText);
    //Gets the mortgage information from the text fields
    String priceText = priceField.getText ();
    price = Integer.parseInt (ageText);
    String downPayText = downPayField.getText ();
    downPay = Integer.parseInt (ageText);
    String interestRateText = interestRateField.getText ();
    interestRate = Integer.parseInt (interestRateText);

 }
}
</code>```

The ActionListener:

```<code>import java.awt.*; //for Dimension
import javax.swing.*; //for GUI components
import java.awt.event.*; //for MessageListener

public class Next implements ActionListener
{
 public void actionPerformed (ActionEvent event)
 {
    //Output frame
    JFrame frame2 = new JFrame ();
    frame2.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame2.setSize (new Dimension (300, 250));
    frame2.setTitle ("Mortgage Calculator");
    frame2.getContentPane ().setLayout (new BorderLayout ());

    JPanel westPanel2 = new JPanel (new GridLayout (3, 1));
    JLabel nameLabel = new JLabel ("Name: " + name);
    westPanel2.add (nameLabel);
    JLabel ageLabel = new JLabel ("Age: " + age);
    westPanel2.add (ageLabel);
    JLabel incomeLabel = new JLabel ("Yearly Income: " + income);
    westPanel2.add (incomeLabel);
    frame2.getContentPane ().add (westPanel2, BorderLayout.WEST);

    JPanel centerPanel2 = new JPanel (new GridLayout (3, 1));
    JLabel priceLabel = new JLabel ("    Price of property: " + price);
    centerPanel2.add (priceLabel);
    JLabel downPayLabel = new JLabel ("    Down Payment: " + downPay);
    centerPanel2.add (downPayLabel);
    JLabel interestRateLabel = new JLabel ("    Interest Rate: " + income);
    centerPanel2.add (interestRateLabel);
    frame2.getContentPane ().add (centerPanel2, BorderLayout.CENTER);

    frame2.pack ();
    frame2.setVisible (true);

  }
}
</code>```

答:
The variables in your main method are local variables, so your listener won't be able to see them.

There are a lot of ways to fix this. First, you have to make the state variables (name, etc) member variables of the MortgageCalculator class, so that they'll be visible to other methods or classes. Then, give the listener code access to those variables. Some options:

Make Next an inner class of MortgageCalculator, so that it can automatically see the member variables.

Make MortgageCalculator implement ActionListener, and move the actionPerformed method inside the resulting class. Then, instead of writing nextButton.addActionListener(new Next());, you'd say nextButton.addActionListener(this); - but only inside a non-static method (so not main - you'd need to make main call a non-static method on an instance of MortgageCalculator).

Body:
This is my code for the two file classes. What do I have to add/fix in order for the variables to transfer and print in the action listener JFrame? The error "No field named "(the variable I used in action listener from main class)" was found in type "Next"

  import java.awt.*; //for Dimension
  import javax.swing.*; //for GUI components

  public class MortgageCalculator
  {
   public static void main (String[] args)
    {
    JFrame frame = new JFrame ();
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame.setSize (new Dimension (300, 250));
    frame.setTitle ("Mortgage Calculator");

    frame.getContentPane ().setLayout (new BorderLayout ());

    frame.getContentPane ().add (new JLabel ("                          Personal Information"), BorderLayout.NORTH);

    JPanel centerPanel = new JPanel (new GridLayout (15, 1));
    centerPanel.add (new JLabel ("Full Name:"));
    JTextField nameField = new JTextField ();
    centerPanel.add (nameField);
    centerPanel.add (new JLabel ("Your Age:"));
    JTextField ageField = new JTextField ();
    centerPanel.add (ageField);
    centerPanel.add (new JLabel ("Yearly Income:"));
    JTextField incomeField = new JTextField ();
    centerPanel.add (incomeField);
    centerPanel.add (new JLabel ());
    centerPanel.add (new JLabel ("                          Mortgage Information"));

    centerPanel.add (new JLabel ("Price of Property:"));
    JTextField priceField = new JTextField ();
    centerPanel.add (priceField);
    centerPanel.add (new JLabel ("Down Payment:"));
    JTextField downPayField = new JTextField ();
    centerPanel.add (downPayField);
    centerPanel.add (new JLabel ("Interest Rate:"));
    JTextField interestRateField = new JTextField ();
    centerPanel.add (interestRateField);
    centerPanel.add (new JLabel ("Amortization Period (Years):"));
    frame.getContentPane ().add (centerPanel, BorderLayout.CENTER);

    JPanel southPanel = new JPanel (new GridLayout (5, 2));
    JButton amort20 = new JButton ("20");
    southPanel.add (amort20);
    JButton amort25 = new JButton ("25");
    southPanel.add (amort25);
    JButton amort30 = new JButton ("30");
    southPanel.add (amort30);
    southPanel.add (new JLabel ("Payment Option:"));
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ());
    JButton paymentWeek = new JButton ("Weekly");
    southPanel.add (paymentWeek);
    JButton paymentBiweek = new JButton ("Biweekly");
    southPanel.add (paymentBiweek);
    JButton paymentMonth = new JButton ("Monthly");
    southPanel.add (paymentMonth);
    //To add a blank line in frame, added three blank JLabels because it is 3 horiontal for grid layout
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ());
    southPanel.add (new JButton ("Clear Information"));
    southPanel.add (new JLabel ());
    JButton nextButton = new JButton ("Next");
    southPanel.add (nextButton);
    frame.getContentPane ().add (southPanel, BorderLayout.SOUTH);

    frame.pack ();
    frame.setVisible (true);
    nextButton.addActionListener (new Next ());

    //Gets the personal information from the text fields
    int age, income, price, downPay, interestRate;
    String name = nameField.getText ();
    String ageText = ageField.getText ();
    age = Integer.parseInt (ageText);
    String incomeText = incomeField.getText ();
    income = Integer.parseInt (ageText);
    //Gets the mortgage information from the text fields
    String priceText = priceField.getText ();
    price = Integer.parseInt (ageText);
    String downPayText = downPayField.getText ();
    downPay = Integer.parseInt (ageText);
    String interestRateText = interestRateField.getText ();
    interestRate = Integer.parseInt (interestRateText);

 }
}

The ActionListener:

import java.awt.*; //for Dimension
import javax.swing.*; //for GUI components
import java.awt.event.*; //for MessageListener

public class Next implements ActionListener
{
 public void actionPerformed (ActionEvent event)
 {
    //Output frame
    JFrame frame2 = new JFrame ();
    frame2.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame2.setSize (new Dimension (300, 250));
    frame2.setTitle ("Mortgage Calculator");
    frame2.getContentPane ().setLayout (new BorderLayout ());

    JPanel westPanel2 = new JPanel (new GridLayout (3, 1));
    JLabel nameLabel = new JLabel ("Name: " + name);
    westPanel2.add (nameLabel);
    JLabel ageLabel = new JLabel ("Age: " + age);
    westPanel2.add (ageLabel);
    JLabel incomeLabel = new JLabel ("Yearly Income: " + income);
    westPanel2.add (incomeLabel);
    frame2.getContentPane ().add (westPanel2, BorderLayout.WEST);

    JPanel centerPanel2 = new JPanel (new GridLayout (3, 1));
    JLabel priceLabel = new JLabel ("    Price of property: " + price);
    centerPanel2.add (priceLabel);
    JLabel downPayLabel = new JLabel ("    Down Payment: " + downPay);
    centerPanel2.add (downPayLabel);
    JLabel interestRateLabel = new JLabel ("    Interest Rate: " + income);
    centerPanel2.add (interestRateLabel);
    frame2.getContentPane ().add (centerPanel2, BorderLayout.CENTER);

    frame2.pack ();
    frame2.setVisible (true);

  }
}


问:
Spring Security Active Directory
I am trying to do LDAP authentication by Spring Security.

My code...

```<code> auth.ldapAuthentication()
            .userSearchFilter("(uid={0})").userSearchBase("ou=TTU")
            .groupSearchFilter("uniqueMember={0}").groupSearchBase("ou=TTU")
            .contextSource(contextSource())
            .passwordCompare()
                .passwordEncoder(new LdapShaPasswordEncoder())
                .passwordAttribute("userPassword");
</code>```

But always return 401 "Bad credentials"
What can be the kind of mistake?
Perhaps someone has an example with Java config.

答:
it's work ... maybe anybody willbe helpfull.</p>

```<code>       auth.authenticationProvider(ldapAuthenticationProvider());
       auth.eraseCredentials(true);

@Bean
public DefaultSpringSecurityContextSource contextSource(){

    DefaultSpringSecurityContextSource contextSource =
            new DefaultSpringSecurityContextSource(Arrays.asList("ldap://url:389/"),"dc=ttu,dc=ru");
    contextSource.setUserDn(userDn);
    contextSource.setPassword(passwordForLDAP);
    contextSource.setReferral("follow");
    return contextSource;
  }

@Bean
public LdapAuthenticationProvider ldapAuthenticationProvider(){
    return new LdapAuthenticationProvider(ldapAuthenticator(),ldapAuthoritiesPopulator());
}

@Bean
public LdapAuthenticator ldapAuthenticator(){
    BindAuthenticator authenticator = new BindAuthenticator(contextSource());
    authenticator.setUserSearch(userSearch());
    return authenticator;
}

@Bean
public DefaultLdapAuthoritiesPopulator ldapAuthoritiesPopulator(){
    DefaultLdapAuthoritiesPopulator ldapAuthoritiesPopulator =
            new DefaultLdapAuthoritiesPopulator(contextSource(),"ou=TTU");
    ldapAuthoritiesPopulator.setSearchSubtree(true);
    ldapAuthoritiesPopulator.setIgnorePartialResultException(true);
    //ldapAuthoritiesPopulator.setGroupSearchFilter("member={0}");
    ldapAuthoritiesPopulator.setRolePrefix("ROLE_");
    ldapAuthoritiesPopulator.setConvertToUpperCase(true);
    return ldapAuthoritiesPopulator;
}

@Bean
public FilterBasedLdapUserSearch userSearch(){
    FilterBasedLdapUserSearch filterBasedLdapUserSearch =
            new FilterBasedLdapUserSearch("","(sAMAccountName={0})",contextSource());
    filterBasedLdapUserSearch.setSearchSubtree(true);
    return filterBasedLdapUserSearch;
}
</code>```

Title: Spring Security Active Directory

Body:
I am trying to do LDAP authentication by Spring Security.

My code...

 auth.ldapAuthentication()
            .userSearchFilter("(uid={0})").userSearchBase("ou=TTU")
            .groupSearchFilter("uniqueMember={0}").groupSearchBase("ou=TTU")
            .contextSource(contextSource())
            .passwordCompare()
                .passwordEncoder(new LdapShaPasswordEncoder())
                .passwordAttribute("userPassword");

But always return 401 "Bad credentials"
What can be the kind of mistake?
Perhaps someone has an example with Java config.

Body:
it's work ... maybe anybody willbe helpfull.

       auth.authenticationProvider(ldapAuthenticationProvider());
       auth.eraseCredentials(true);

@Bean
public DefaultSpringSecurityContextSource contextSource(){

    DefaultSpringSecurityContextSource contextSource =
            new DefaultSpringSecurityContextSource(Arrays.asList("ldap://url:389/"),"dc=ttu,dc=ru");
    contextSource.setUserDn(userDn);
    contextSource.setPassword(passwordForLDAP);
    contextSource.setReferral("follow");
    return contextSource;
  }

@Bean
public LdapAuthenticationProvider ldapAuthenticationProvider(){
    return new LdapAuthenticationProvider(ldapAuthenticator(),ldapAuthoritiesPopulator());
}

@Bean
public LdapAuthenticator ldapAuthenticator(){
    BindAuthenticator authenticator = new BindAuthenticator(contextSource());
    authenticator.setUserSearch(userSearch());
    return authenticator;
}

@Bean
public DefaultLdapAuthoritiesPopulator ldapAuthoritiesPopulator(){
    DefaultLdapAuthoritiesPopulator ldapAuthoritiesPopulator =
            new DefaultLdapAuthoritiesPopulator(contextSource(),"ou=TTU");
    ldapAuthoritiesPopulator.setSearchSubtree(true);
    ldapAuthoritiesPopulator.setIgnorePartialResultException(true);
    //ldapAuthoritiesPopulator.setGroupSearchFilter("member={0}");
    ldapAuthoritiesPopulator.setRolePrefix("ROLE_");
    ldapAuthoritiesPopulator.setConvertToUpperCase(true);
    return ldapAuthoritiesPopulator;
}

@Bean
public FilterBasedLdapUserSearch userSearch(){
    FilterBasedLdapUserSearch filterBasedLdapUserSearch =
            new FilterBasedLdapUserSearch("","(sAMAccountName={0})",contextSource());
    filterBasedLdapUserSearch.setSearchSubtree(true);
    return filterBasedLdapUserSearch;
}


问:
SSH key already exists on bitbucket
I was trying to add the SSH key of my server in laravel-forge to bitbucket. The ssh key is usually located in ~/.ssh/id_rsa.pub inside the laravel-forge terminal. Bitbucket did not allow me to add this. This is usually added in bitbucket by clicking 'Access Keys' under 'Settings'. The error message was: that key has already been added by a user. But I could not find which other user in the team had added it. The bitbucket site could not show me which user had added it.

答: I want to answer my own question so that it helps someone. After I contacted bitbucket, I came to know that a specific user had used that ssh key. All I did was create a new ssh key using ssh-keygen command in the laravel-forge server terminal. I was successfully able to add this new ssh key for laravel-forge in bitbucket and I was able to deploy.

Title: SSH key already exists on bitbucket


问:
How do I run an external javascript function in a web page?
I can run Javascript in-page, thus:

Javascript.html:

```<code><html>
    <body>
        Hello <span id="mySpan"> World! </span>
    </body>
    <script>
        function worldInSpanish() {
            return "Mundo!";
        }
        document.getElementById('mySpan').innerHTML = worldInSpanish();
    </script>
</html>
</code>```

Hello Mundo!

But when I try to run it from an external file, it doesn't work.

javascript.js:

```<code>function worldInSpanish() {
    return "Mundo!";
}
</code>```

External_javascript.html:

```<code><html>
    <body>
        Hello <span id="mySpan"> World! </span>
    </body>
    <script src="javascript.js">
        document.getElementById('mySpan').innerHTML = worldInSpanish();
    </script>
</html>
</code>```

Doesn't change the text:

Hello World!

What am I doing wrong? I'm guessing that I need to do something more to "import" the function into the HTML page or "export" it from the Javascript file.

答:
This should solve the problem. you are using same tag for attaching the external, and calling the function, do it in separate tags</p>

```<code><html>
    <body>
        Hello <span id="mySpan"> World! </span>
    </body>
    <script src="javascript.js"></script>
    <script>
        document.getElementById('mySpan').innerHTML = worldInSpanish();
    </script>
</html>
</code>```

Body:
I can run Javascript in-page, thus:

Javascript.html:

        Hello  World!

Hello Mundo!

But when I try to run it from an external file, it doesn't work.

javascript.js:

function worldInSpanish() {
    return "Mundo!";
}

External_javascript.html:

        Hello  World!

Doesn't change the text:

Hello World!

What am I doing wrong? I'm guessing that I need to do something more to "import" the function into the HTML page or "export" it from the Javascript file.

Body:
This should solve the problem. you are using same tag for attaching the external, and calling the function, do it in separate tags

<html>
    <body>
        Hello <span id="mySpan"> World! </span>
    </body>
    <script src="javascript.js"></script>
    <script>
        document.getElementById('mySpan').innerHTML = worldInSpanish();
    </script>
</html>


问:
ASP.NET MVC multiple begin forms?
Hi I am using multiple begin forms. I am not sure if this is a good Idea. This is my code.

```<code><% using (Html.BeginForm("TagManagement", "InternalTag",FormMethod.Post))
   {%>
   <%: Html.AntiForgeryToken() %>

    <table>
        <tr>
            <td><%:Html.Label("Type") %></td>
            <td style="text-align:left"><%:Html.DropDownList("ObjectType",ViewData["TagObjects"] as IEnumerable<SelectListItem>)%></td>
        </tr>
        <tr>
            <td><%:Html.Label("Search ID")%></td>
            <td style="text-align:left"><%:Html.TextBox("ObjectID2")%></td>
        </tr>
        <tr>
            <td></td>
            <td><input id="Search" type="submit" value="Search" />   <input id="Create" type="button" value="Add to New Tag" onclick="AddTagElements()" /></td>
        </tr>
    </table>
    <br />

<% } %>

<% using (Html.BeginForm("CreateTag","InternalTag",FormMethod.Post)) { %>
<%: Html.AntiForgeryToken() %>
<div id="AddTag">
      <input id='SaveTag' type='submit' value='Save' style='width: 125px' />
</div>
<% } %>
</code>```

routing code

```<code>"Tags/{controller}/{action}/{id}/{type}",
new { action = "Index", id = UrlParameter.Optional, type = UrlParameter.Optional }
</code>```

my controller methods:

```<code>public ActionResult TagManagement(FormCollection FC,Guid? ID,InternalTagRef_Types? Type)
public ActionResult CreateTag(FormCollection FC, Guid ID, InternalTagRef_Types Type)
</code>```

when I click on search TagManagement Actions parameters get properly populated. When I click on SaveTag it tries call the CreateTag action but cannot because it is missing ID and Type. I get the error The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Guid'. It should get these values from the URL i.e.
http://localhost:1338/Tags/InternalTag/TagManagement/D104EBF5-470B-4FAA-9FC7-5391922CCE94/Projects like TagManagement.  Please help.

答:
I would suggest including a hidden field in this form which will have your tags, thus when submitting the form your tags will be available. Secondly, and equally important

```<code><input id="Create" type="button" value="Add to New Tag" onclick="AddTagElements()" />
</code>```

the AddTagElements javascript function needs to update the value of the hidden field with the new tag(s).

```<code><% using (Html.BeginForm("CreateTag","InternalTag",FormMethod.Post)){%>
    <%: Html.AntiForgeryToken() %>
    <div id="AddTag">
        <input id="tags" type="hidden" value=""/>
        <input id='SaveTag' type='submit' value='Save' style='width: 125px' />
    </div>
<%}%>
</code>```

ContentLicense: CC BY-SA 2.5

Title: ASP.NET MVC multiple begin forms?

Body:
Hi I am using multiple begin forms. I am not sure if this is a good Idea. This is my code.

<% using (Html.BeginForm("TagManagement", "InternalTag",FormMethod.Post))
   {%>
   <%: Html.AntiForgeryToken() %>

            <%:Html.Label("Type") %>
            <%:Html.DropDownList("ObjectType",ViewData["TagObjects"] as IEnumerable<SelectListItem>)%>

            <%:Html.Label("Search ID")%>
            <%:Html.TextBox("ObjectID2")%>

            <input id="Search" type="submit" value="Search" />   <input id="Create" type="button" value="Add to New Tag" onclick="AddTagElements()" />

<% } %>

<% using (Html.BeginForm("CreateTag","InternalTag",FormMethod.Post)) { %>
<%: Html.AntiForgeryToken() %>

      <input id='SaveTag' type='submit' value='Save' style='width: 125px' />

<% } %>

routing code

"Tags/{controller}/{action}/{id}/{type}",
new { action = "Index", id = UrlParameter.Optional, type = UrlParameter.Optional }

my controller methods:

public ActionResult TagManagement(FormCollection FC,Guid? ID,InternalTagRef_Types? Type)
public ActionResult CreateTag(FormCollection FC, Guid ID, InternalTagRef_Types Type)

when I click on search TagManagement Actions parameters get properly populated. When I click on SaveTag it tries call the CreateTag action but cannot because it is missing ID and Type. I get the error The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Guid'. It should get these values from the URL i.e.
http://localhost:1338/Tags/InternalTag/TagManagement/D104EBF5-470B-4FAA-9FC7-5391922CCE94/Projects like TagManagement.  Please help.

Body:
I would suggest including a hidden field in this form which will have your tags, thus when submitting the form your tags will be available. Secondly, and equally important

<input id="Create" type="button" value="Add to New Tag" onclick="AddTagElements()" />

the AddTagElements javascript function needs to update the value of the hidden field with the new tag(s).

<% using (Html.BeginForm("CreateTag","InternalTag",FormMethod.Post)){%>
    <%: Html.AntiForgeryToken() %>
    <div id="AddTag">
        <input id="tags" type="hidden" value=""/>
        <input id='SaveTag' type='submit' value='Save' style='width: 125px' />
    </div>
<%}%>


问:
How to run shim from inside grub2 code?
I am new to grub. I am trying to enable UEFI secure boot from grub. I have decided to use shim to verify kernel's signature. Grub can be verified from UEFI.

I have pulled patches from Ubuntu's grub git repository. Grub uses grub_efi_locate_protocol() function to locate shim, currently it is not able to find shim and returns NULL.

I have following queries:

Where should I place shim.efi binary (I have placed it /boot partition)

Where does grub_efi_system_table variable get populated, and how is it used by grub_efi_locate_protocol?

Thanks

答:
I was able to solve this issue. When shim is executed, it installs shim protocol. Shim protocol is installed only when secure boot is enabled. I was trying to use the shim protocol with no secure boot, so, grub was unable to find shim protocol. A complete explanation of shim is here
https://mjg59.dreamwidth.org/19448.html</p>

Title: How to run shim from inside grub2 code?


问:
Hide/Disable other fields based on Input field
I want to hide or update a field on the UI based on conditions of another field.

For example, if I have a field called Color:

```<code>[PXUIField(DisplayName="Color")]
[PXStringList("Red,Blue,Other")]
[PXDefault("Red")]
</code>```

And text field for comments only shown when "Other" is selected, how is this accomplished?

答:
The requested behavior can either be accomplished either with a series of event handlers or with a bunch of attributes. You can find several examples on how to subscribe to the RowSelected and FieldUpdated events in the T200 training course, available at Acumatica University and Acumatica Open University

Going with field attributes is a more convenient and way easier option for your particular scenario. I would recommend setting CommitChanges to True for the drop-down, so the Comments field is cleared and disabled/enabled immediately after the user updates Color. Also, it's very to have your Color declared after Comments, so the framework will process Comments field first and always clear the current Comments value after the Color field got updated.

```<code>public class Other : Constant<string>
{
    public Other() : base("Other") { }
}
public abstract class comments : IBqlField { }
[PXDBString(255, IsUnicode = true)]
[PXUIField(DisplayName = "Comments")]
[PXUIEnabled(typeof(Where<color, Equal<Other>>))]
[PXFormula(typeof(Default<color>))]
[PXDefault(PersistingCheck = PXPersistingCheck.Nothing)]
public string Comments { get; set; }

public abstract class color : IBqlField { }
[PXDBString(10, IsUnicode = true)]
[PXUIField(DisplayName = "Color")]
[PXStringList("Red,Blue,Other")]
[PXDefault("Red")]
public string Color { get; set; }
</code>```

The only way to conditionally hide/show editor on a form is though the RowSelected event handler:

```<code>public void YourDAC_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
{
    YourDAC row = e.Row as YourDAC;
    if (row == null) return;

    PXUIFieldAttribute.SetVisible<YourDAC.comments>(sender, row, row.Color == "Other");
}
</code>```

I believe, in the T200 training course, there are several examples on the PXUIFieldAttribute.SetVisible method.

Body:
I want to hide or update a field on the UI based on conditions of another field.

For example, if I have a field called Color:

[PXUIField(DisplayName="Color")]
[PXStringList("Red,Blue,Other")]
[PXDefault("Red")]

And text field for comments only shown when "Other" is selected, how is this accomplished?

Body:
The requested behavior can either be accomplished either with a series of event handlers or with a bunch of attributes. You can find several examples on how to subscribe to the RowSelected and FieldUpdated events in the T200 training course, available at Acumatica University and Acumatica Open University

Going with field attributes is a more convenient and way easier option for your particular scenario. I would recommend setting CommitChanges to True for the drop-down, so the Comments field is cleared and disabled/enabled immediately after the user updates Color. Also, it's very to have your Color declared after Comments, so the framework will process Comments field first and always clear the current Comments value after the Color field got updated.

public class Other : Constant<string>
{
    public Other() : base("Other") { }
}
public abstract class comments : IBqlField { }
[PXDBString(255, IsUnicode = true)]
[PXUIField(DisplayName = "Comments")]
[PXUIEnabled(typeof(Where<color, Equal<Other>>))]
[PXFormula(typeof(Default<color>))]
[PXDefault(PersistingCheck = PXPersistingCheck.Nothing)]
public string Comments { get; set; }

public abstract class color : IBqlField { }
[PXDBString(10, IsUnicode = true)]
[PXUIField(DisplayName = "Color")]
[PXStringList("Red,Blue,Other")]
[PXDefault("Red")]
public string Color { get; set; }

The only way to conditionally hide/show editor on a form is though the RowSelected event handler:

public void YourDAC_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
{
    YourDAC row = e.Row as YourDAC;
    if (row == null) return;

    PXUIFieldAttribute.SetVisible<YourDAC.comments>(sender, row, row.Color == "Other");
}

I believe, in the T200 training course, there are several examples on the PXUIFieldAttribute.SetVisible method.


问:
Error when try to add Google Maps
Couple moths ago i testing this app on Android N and all will work correctly, but now i have error. Now i'am using MapFragment and have this error:

```<code>05-09 23:22:35.816 11112-11112/pc.dd.sex_startup E/AndroidRuntime: FATAL EXCEPTION: main
                                                               Process: pc.dd.sex_startup, PID: 11112
                                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{pc.dd.sex_startup/pc.dd.sex_startup.LogIn.Maps.Map}: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class fragment
                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                   at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                                Caused by: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class fragment
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:543)
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                   at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
                                                                   at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                   at pc.dd.sex_startup.LogIn.Maps.Map.onCreate(Map.java:85)
                                                                   at android.app.Activity.performCreate(Activity.java:6303)
                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                   at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                                Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class fragment
                                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:786)
                                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:708)
                                                                   at android.view.LayoutInflater.rInflate(LayoutInflater.java:839)
                                                                   at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802)
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                   at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
                                                                   at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                   at pc.dd.sex_startup.LogIn.Maps.Map.onCreate(Map.java:85)
                                                                   at android.app.Activity.performCreate(Activity.java:6303)
                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                   at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Configuration android.content.res.Resources.getConfiguration()' on a null object reference
                                                                   at android.util.ResolutionOverride.<init>(ResolutionOverride.java:56)
                                                                   at android.view.SurfaceView.init(SurfaceView.java:207)
                                                                   at android.view.SurfaceView.<init>(SurfaceView.java:187)
                                                                   at com.google.maps.api.android.lib6.gmm6.vector.an.<init>(:com.google.android.gms.DynamiteModulesB:231)
                                                                   at com.google.maps.api.android.lib6.gmm6.vector.ai.<init>(:com.google.android.gms.DynamiteModulesB:163)
                                                                   at com.google.maps.api.android.lib6.gmm6.api.ao.<init>(:com.google.android.gms.DynamiteModulesB:389)
                                                                   at com.google.maps.api.android.lib6.gmm6.api.ao.a(:com.google.android.gms.DynamiteModulesB:349)
                                                                   at com.google.android.gms.maps.internal.eb.a(:com.google.android.gms.DynamiteModulesB:4048)
                                                                   at com.google.maps.api.android.lib6.impl.az.a(:com.google.android.gms.DynamiteModulesB:403)
                                                                   at com.google.maps.api.android.lib6.impl.az.a(:com.google.android.gms.DynamiteModulesB:320)
                                                                   at com.google.maps.api.android.lib6.impl.cp.a(:com.google.android.gms.DynamiteModulesB:82)
                                                                   at com.google.maps.api.android.lib6.impl.co.a(:com.google.android.gms.DynamiteModulesB:139)
                                                                   at com.google.android.gms.maps.internal.w.onTransact(:com.google.android.gms.DynamiteModulesB:107)
                                                                   at android.os.Binder.transact(Binder.java:387)
                                                                   at com.google.android.gms.maps.internal.IMapFragmentDelegate$zza$zza.onCreateView(Unknown Source)
                                                                   at com.google.android.gms.maps.SupportMapFragment$zza.onCreateView(Unknown Source)
                                                                   at com.google.android.gms.dynamic.zza$4.zzb(Unknown Source)
                                                                   at com.google.android.gms.dynamic.zza.zza(Unknown Source)
                                                                   at com.google.android.gms.dynamic.zza.onCreateView(Unknown Source)
                                                                   at com.google.android.gms.maps.SupportMapFragment.onCreateView(Unknown Source)
</code>```

and in java:

```<code>public class Map extends AppCompatActivity  implements OnMapReadyCallback {
private MapView mapView;
private GoogleMap map;
private android.app.FragmentManager fragmentManager;
private android.app.FragmentTransaction fragmentTransaction;
private FragmentImage fragment;
public ClusterManager<MyItem> mClusterManager;
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_main);

    //add status bar
    statusBarFragment status_bar = new statusBarFragment();
    fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
            .add(R.id.statbar_container_map, status_bar)
            .commit();

    // Get the map and register for the ready callback.
    MapFragment mapFragment = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
    mapFragment.getMapAsync(this);
</code>```

and xml:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="320dp"
        android:id="@+id/container"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"></RelativeLayout>

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:id="@+id/statbar_container_map">

    </FrameLayout>

</RelativeLayout>
</code>```

also try to change AppCompatActivity to FragmentActivity. Before that i'am using SupportMapFragment and have same error. What wrong?

答:
I also experience the same(which was no problem previously). Workaround is to add following flag to your MapActivity in your AndroidManifest.xml file

android:hardwareAccelerated="true"

Title: Error when try to add Google Maps

Body:
Couple moths ago i testing this app on Android N and all will work correctly, but now i have error. Now i'am using MapFragment and have this error:

05-09 23:22:35.816 11112-11112/pc.dd.sex_startup E/AndroidRuntime: FATAL EXCEPTION: main
                                                               Process: pc.dd.sex_startup, PID: 11112
                                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{pc.dd.sex_startup/pc.dd.sex_startup.LogIn.Maps.Map}: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class fragment
                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                   at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                                Caused by: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class fragment
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:543)
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                   at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
                                                                   at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                   at pc.dd.sex_startup.LogIn.Maps.Map.onCreate(Map.java:85)
                                                                   at android.app.Activity.performCreate(Activity.java:6303)
                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                   at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                                Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class fragment
                                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:786)
                                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:708)
                                                                   at android.view.LayoutInflater.rInflate(LayoutInflater.java:839)
                                                                   at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802)
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                                                                   at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
                                                                   at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                   at pc.dd.sex_startup.LogIn.Maps.Map.onCreate(Map.java:85)
                                                                   at android.app.Activity.performCreate(Activity.java:6303)
                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                   at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Configuration android.content.res.Resources.getConfiguration()' on a null object reference
                                                                   at android.util.ResolutionOverride.<init>(ResolutionOverride.java:56)
                                                                   at android.view.SurfaceView.init(SurfaceView.java:207)
                                                                   at android.view.SurfaceView.<init>(SurfaceView.java:187)
                                                                   at com.google.maps.api.android.lib6.gmm6.vector.an.<init>(:com.google.android.gms.DynamiteModulesB:231)
                                                                   at com.google.maps.api.android.lib6.gmm6.vector.ai.<init>(:com.google.android.gms.DynamiteModulesB:163)
                                                                   at com.google.maps.api.android.lib6.gmm6.api.ao.<init>(:com.google.android.gms.DynamiteModulesB:389)
                                                                   at com.google.maps.api.android.lib6.gmm6.api.ao.a(:com.google.android.gms.DynamiteModulesB:349)
                                                                   at com.google.android.gms.maps.internal.eb.a(:com.google.android.gms.DynamiteModulesB:4048)
                                                                   at com.google.maps.api.android.lib6.impl.az.a(:com.google.android.gms.DynamiteModulesB:403)
                                                                   at com.google.maps.api.android.lib6.impl.az.a(:com.google.android.gms.DynamiteModulesB:320)
                                                                   at com.google.maps.api.android.lib6.impl.cp.a(:com.google.android.gms.DynamiteModulesB:82)
                                                                   at com.google.maps.api.android.lib6.impl.co.a(:com.google.android.gms.DynamiteModulesB:139)
                                                                   at com.google.android.gms.maps.internal.w.onTransact(:com.google.android.gms.DynamiteModulesB:107)
                                                                   at android.os.Binder.transact(Binder.java:387)
                                                                   at com.google.android.gms.maps.internal.IMapFragmentDelegate$zza$zza.onCreateView(Unknown Source)
                                                                   at com.google.android.gms.maps.SupportMapFragment$zza.onCreateView(Unknown Source)
                                                                   at com.google.android.gms.dynamic.zza$4.zzb(Unknown Source)
                                                                   at com.google.android.gms.dynamic.zza.zza(Unknown Source)
                                                                   at com.google.android.gms.dynamic.zza.onCreateView(Unknown Source)
                                                                   at com.google.android.gms.maps.SupportMapFragment.onCreateView(Unknown Source)

and in java:

public class Map extends AppCompatActivity  implements OnMapReadyCallback {
private MapView mapView;
private GoogleMap map;
private android.app.FragmentManager fragmentManager;
private android.app.FragmentTransaction fragmentTransaction;
private FragmentImage fragment;
public ClusterManager<MyItem> mClusterManager;
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_main);

    //add status bar
    statusBarFragment status_bar = new statusBarFragment();
    fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
            .add(R.id.statbar_container_map, status_bar)
            .commit();

    // Get the map and register for the ready callback.
    MapFragment mapFragment = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
    mapFragment.getMapAsync(this);

and xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="320dp"
        android:id="@+id/container"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"></RelativeLayout>

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:id="@+id/statbar_container_map">

    </FrameLayout>

</RelativeLayout>

also try to change AppCompatActivity to FragmentActivity. Before that i'am using SupportMapFragment and have same error. What wrong?


问:
Excel VBA to summarize last cell of certain column to 'summary' worksheet
I am trying to summarize worksheets (invoices) into "Summary-Sheet" using below code that I found Internet. I am unsuccessfully trying to modify it to select last cell in column F (total amount) which represents total of each invoice.

Total in column F has varying row number based on items sold.

Please help me in updating code to it select total amount from last cell having value in column F.

Thank you!

```<code>Sub Summary_All_Worksheets_With_Formulas()
Dim Sh As Worksheet
Dim Newsh As Worksheet
Dim myCell As Range
Dim ColNum As Integer
Dim RwNum As Long
Dim Basebook As Workbook

With Application
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
End With

'Delete the sheet "Summary-Sheet" if it exist
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Worksheets("Summary-Sheet").Delete
On Error GoTo 0
Application.DisplayAlerts = True

'Add a worksheet with the name "Summary-Sheet"
Set Basebook = ThisWorkbook
Set Newsh = Basebook.Worksheets.Add
Newsh.Name = "Summary-Sheet"

'The links to the first sheet will start in row 2
RwNum = 1

For Each Sh In Basebook.Worksheets
    If Sh.Name <> Newsh.Name And Sh.Visible Then
        ColNum = 1
        RwNum = RwNum + 1
        'Copy the sheet name in the A column
        Newsh.Cells(RwNum, 1).Value = Sh.Name

        For Each myCell In Sh.Range("A1,A2,C3,E3,C4,E4,C5,E5")  '<--Change the range
            ColNum = ColNum + 1
            Newsh.Cells(RwNum, ColNum).Formula = _
            "='" & Sh.Name & "'!" & myCell.Address(False, False)
        Next myCell

    End If
Next Sh

Newsh.UsedRange.Columns.AutoFit

With Application
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
End With
End Sub
</code>```

答:
You do not need to loop through the cells to find your "total amount".  I modified part of your code as follows:

```<code>    If Sh.Name <> Newsh.Name And Sh.Visible Then
      ColNum = 1
      RwNum = RwNum + 1
      'Copy the sheet name in the A column
      Newsh.Cells(RwNum, 1).Value = Sh.Name

      'put this declaration on top
      Dim CellsArray() As String
      Dim RangeString As String
      Dim intCount As Integer

      'your collection of ranges
      RangeString = "A1,A2,C3,E3,C4,E4,C5,E5"

      'split them into array
      CellsArray = Split(RangeString, ",")

      'loop through your array
      For intCount = LBound(CellsArray) To UBound(CellsArray)

        ColNum = ColNum + 1
        Newsh.Cells(RwNum, ColNum).Formula = _
        "='" & Sh.Name & "'!" & CellsArray(intCount) '<- access each range in array

      Next intCount

      'Find last row in the column: "Total Amount"
      LastRow = Sh.Cells(Sh.Rows.Count, "F").End(xlUp).Row

      'Assign that cell to myCell
      Set myCell = Sh.Range("F" & LastRow)

      'total
      ColNum = ColNum + 1
      Newsh.Cells(RwNum, ColNum).Formula = _
      "='" & Sh.Name & "'!" & myCell.Address(False, False)

    End If
</code>```

Edit: I added the loop cycle in the middle as requested

Body:
I am trying to summarize worksheets (invoices) into "Summary-Sheet" using below code that I found Internet. I am unsuccessfully trying to modify it to select last cell in column F (total amount) which represents total of each invoice.

Total in column F has varying row number based on items sold.

Please help me in updating code to it select total amount from last cell having value in column F.

Thank you!

Sub Summary_All_Worksheets_With_Formulas()
Dim Sh As Worksheet
Dim Newsh As Worksheet
Dim myCell As Range
Dim ColNum As Integer
Dim RwNum As Long
Dim Basebook As Workbook

With Application
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
End With

'Delete the sheet "Summary-Sheet" if it exist
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Worksheets("Summary-Sheet").Delete
On Error GoTo 0
Application.DisplayAlerts = True

'Add a worksheet with the name "Summary-Sheet"
Set Basebook = ThisWorkbook
Set Newsh = Basebook.Worksheets.Add
Newsh.Name = "Summary-Sheet"

'The links to the first sheet will start in row 2
RwNum = 1

For Each Sh In Basebook.Worksheets
    If Sh.Name <> Newsh.Name And Sh.Visible Then
        ColNum = 1
        RwNum = RwNum + 1
        'Copy the sheet name in the A column
        Newsh.Cells(RwNum, 1).Value = Sh.Name

        For Each myCell In Sh.Range("A1,A2,C3,E3,C4,E4,C5,E5")  '<--Change the range
            ColNum = ColNum + 1
            Newsh.Cells(RwNum, ColNum).Formula = _
            "='" & Sh.Name & "'!" & myCell.Address(False, False)
        Next myCell

    End If
Next Sh

Newsh.UsedRange.Columns.AutoFit

With Application
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
End With
End Sub

Body:
You do not need to loop through the cells to find your "total amount".  I modified part of your code as follows:

    If Sh.Name <> Newsh.Name And Sh.Visible Then
      ColNum = 1
      RwNum = RwNum + 1
      'Copy the sheet name in the A column
      Newsh.Cells(RwNum, 1).Value = Sh.Name

      'put this declaration on top
      Dim CellsArray() As String
      Dim RangeString As String
      Dim intCount As Integer

      'your collection of ranges
      RangeString = "A1,A2,C3,E3,C4,E4,C5,E5"

      'split them into array
      CellsArray = Split(RangeString, ",")

      'loop through your array
      For intCount = LBound(CellsArray) To UBound(CellsArray)

        ColNum = ColNum + 1
        Newsh.Cells(RwNum, ColNum).Formula = _
        "='" & Sh.Name & "'!" & CellsArray(intCount) '<- access each range in array

      Next intCount

      'Find last row in the column: "Total Amount"
      LastRow = Sh.Cells(Sh.Rows.Count, "F").End(xlUp).Row

      'Assign that cell to myCell
      Set myCell = Sh.Range("F" & LastRow)

      'total
      ColNum = ColNum + 1
      Newsh.Cells(RwNum, ColNum).Formula = _
      "='" & Sh.Name & "'!" & myCell.Address(False, False)

    End If

Edit: I added the loop cycle in the middle as requested


问:
Merge and split columns in pandas dataframe
I want to know how to merge multiple columns, and split them again.

Input data

```<code>A B C
1 3 5
2 4 6
</code>```

Merge A, B, C to one column X

```<code>X
1
2
3
4
5
6
</code>```

Process something with X, then split X into A, B, C again. The number of rows for A, B, C is same(2).

```<code>A B C
1 3 5
2 4 6
</code>```

Is there any simple way for this work?

答:
Start with df:

```<code>   A  B  C
0  1  3  5
1  2  4  6
</code>```

Next, get all values in one column:

```<code>df2 = df.unstack().reset_index(drop=True).rename('X').to_frame()

print(df2)

   X
0  1
1  2
2  3
3  4
4  5
5  6
</code>```

And, convert back to original shape:

```<code>df3  = pd.DataFrame(df2.values.reshape(2,-1, order='F'), columns=list('ABC'))
print(df3)

   A  B  C
0  1  3  5
1  2  4  6
</code>```

Body:
I want to know how to merge multiple columns, and split them again.

Input data

A B C
1 3 5
2 4 6

Merge A, B, C to one column X

X
1
2
3
4
5
6

Process something with X, then split X into A, B, C again. The number of rows for A, B, C is same(2).

A B C
1 3 5
2 4 6

Is there any simple way for this work?

Body:
Start with df:

   A  B  C
0  1  3  5
1  2  4  6

Next, get all values in one column:

df2 = df.unstack().reset_index(drop=True).rename('X').to_frame()

print(df2)

   X
0  1
1  2
2  3
3  4
4  5
5  6

And, convert back to original shape:

df3  = pd.DataFrame(df2.values.reshape(2,-1, order='F'), columns=list('ABC'))
print(df3)

   A  B  C
0  1  3  5
1  2  4  6


问:
Invoke MethodInvoker Delegate for more than 1 item at a time
The code below works just fine but I am looking for a way to combine all 3 into just one invoke statement:

```<code>this.Invoke(new MethodInvoker(delegate () {
   String.Format(
       "------------------------------------------------------------")
   );
}));

this.Invoke(new MethodInvoker(delegate () {
   String.Format(
       "- END " + archiveFullName + " -"
   );
}));

this.Invoke(new MethodInvoker(delegate () {
   String.Format(
       "------------------------------------------------------------")
   );
}));
</code>```

I've already tried:

```<code>this.Invoke(new MethodInvoker(delegate () {
   listBox1.Items.Add(
      this.listBox1.Items.Add("--------------------------------------------------------")
      this.listBox1.Items.Add("- END " + archiveFullName + " -")
      this.listBox1.Items.Add("-------------------------------------------------------")
   );
}));
</code>```

But that does not seem to work.

Any resolution would be great!

答:
Use the AddRange method.</p>

```<code>listBox1.Items.AddRange(...
</code>```

Body:
The code below works just fine but I am looking for a way to combine all 3 into just one invoke statement:

this.Invoke(new MethodInvoker(delegate () {
   String.Format(
       "------------------------------------------------------------")
   );
}));

this.Invoke(new MethodInvoker(delegate () {
   String.Format(
       "- END " + archiveFullName + " -"
   );
}));

this.Invoke(new MethodInvoker(delegate () {
   String.Format(
       "------------------------------------------------------------")
   );
}));

I've already tried:

this.Invoke(new MethodInvoker(delegate () {
   listBox1.Items.Add(
      this.listBox1.Items.Add("--------------------------------------------------------")
      this.listBox1.Items.Add("- END " + archiveFullName + " -")
      this.listBox1.Items.Add("-------------------------------------------------------")
   );
}));

But that does not seem to work.

Any resolution would be great!

Body:
Use the AddRange method.

listBox1.Items.AddRange(...


问:
How to start rails server?
I am developing rails 2.3.2 application.

When I type the command "rails script/server"

I got the following output instead of server starting why?

```<code>rails script/server
Usage:
  rails new APP_PATH [options]

Options:
  -J, [--skip-javascript]        # Skip JavaScript files
      [--dev]                    # Setup the application with Gemfile pointing to your Rails checkout
      [--edge]                   # Setup the application with Gemfile pointing to Rails repository
  -G, [--skip-git]               # Skip Git ignores and keeps
  -m, [--template=TEMPLATE]      # Path to an application template (can be a filesystem path or URL)
  -b, [--builder=BUILDER]        # Path to a application builder (can be a filesystem path or URL)
      [--old-style-hash]         # Force using old style hash (:foo => 'bar') on Ruby >= 1.9
      [--skip-gemfile]           # Don't create a Gemfile
  -d, [--database=DATABASE]      # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)
                                 # Default: sqlite3
  -O, [--skip-active-record]     # Skip Active Record files
      [--skip-bundle]            # Don't run bundle install
  -T, [--skip-test-unit]         # Skip Test::Unit files
  -S, [--skip-sprockets]         # Skip Sprockets files
  -r, [--ruby=PATH]              # Path to the Ruby binary of your choice
                                 # Default: /home/xichen/.rvm/rubies/ruby-1.8.7-p352/bin/ruby
  -j, [--javascript=JAVASCRIPT]  # Preconfigure for selected JavaScript library
                                 # Default: jquery

Runtime options:
  -q, [--quiet]    # Supress status output
  -s, [--skip]     # Skip files that already exist
  -f, [--force]    # Overwrite files that already exist
  -p, [--pretend]  # Run but do not make any changes

Rails options:
  -h, [--help]     # Show this help message and quit
  -v, [--version]  # Show Rails version number and quit

Description:
    The 'rails new' command creates a new Rails application with a default
    directory structure and configuration at the path you specify.

Example:
    rails new ~/Code/Ruby/weblog

    This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
    See the README in the newly created application to get going.
</code>```

When I type linux command "ls" I got the following directories and files showing:

```<code>app  Capfile  config  criptq  db  doc  features  Gemfile  Gemfile.lock  generate  lib  log  nbproject  public  Rakefile  README  script  spec  test  tmp  vendor
</code>```

my Gemfile is:

```<code>source "http://rubygems.org"

gem "rails", "2.3.2"
gem "mysql", "2.8.1"
gem "fastercsv"
gem "will_paginate", "2.3.16"
gem "chronic", "0.6.4"
gem "whenever", "0.4.1"
gem "searchlogic", "2.4.28"

group :development do
  gem "mongrel", "1.1.5"
end

group :test do
  gem "rspec", "1.3.2"
  gem "rspec-rails", "1.3.4"
  gem "factory_girl", "1.3.3"
end
</code>```

答:
I also faced the same issue, but my fault was that I was running "rails s" outside of my application directory.
After opening the cmd, just go inside your application and run the commands from their, it worked for me. </p>

Title: How to start rails server?

Body:
I am developing rails 2.3.2 application.

When I type the command "rails script/server"

I got the following output instead of server starting why?

rails script/server
Usage:
  rails new APP_PATH [options]

Options:
  -J, [--skip-javascript]        # Skip JavaScript files
      [--dev]                    # Setup the application with Gemfile pointing to your Rails checkout
      [--edge]                   # Setup the application with Gemfile pointing to Rails repository
  -G, [--skip-git]               # Skip Git ignores and keeps
  -m, [--template=TEMPLATE]      # Path to an application template (can be a filesystem path or URL)
  -b, [--builder=BUILDER]        # Path to a application builder (can be a filesystem path or URL)
      [--old-style-hash]         # Force using old style hash (:foo => 'bar') on Ruby >= 1.9
      [--skip-gemfile]           # Don't create a Gemfile
  -d, [--database=DATABASE]      # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)
                                 # Default: sqlite3
  -O, [--skip-active-record]     # Skip Active Record files
      [--skip-bundle]            # Don't run bundle install
  -T, [--skip-test-unit]         # Skip Test::Unit files
  -S, [--skip-sprockets]         # Skip Sprockets files
  -r, [--ruby=PATH]              # Path to the Ruby binary of your choice
                                 # Default: /home/xichen/.rvm/rubies/ruby-1.8.7-p352/bin/ruby
  -j, [--javascript=JAVASCRIPT]  # Preconfigure for selected JavaScript library
                                 # Default: jquery

Runtime options:
  -q, [--quiet]    # Supress status output
  -s, [--skip]     # Skip files that already exist
  -f, [--force]    # Overwrite files that already exist
  -p, [--pretend]  # Run but do not make any changes

Rails options:
  -h, [--help]     # Show this help message and quit
  -v, [--version]  # Show Rails version number and quit

Description:
    The 'rails new' command creates a new Rails application with a default
    directory structure and configuration at the path you specify.

Example:
    rails new ~/Code/Ruby/weblog

    This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
    See the README in the newly created application to get going.

When I type linux command "ls" I got the following directories and files showing:

app  Capfile  config  criptq  db  doc  features  Gemfile  Gemfile.lock  generate  lib  log  nbproject  public  Rakefile  README  script  spec  test  tmp  vendor

my Gemfile is:

source "http://rubygems.org"

gem "rails", "2.3.2"
gem "mysql", "2.8.1"
gem "fastercsv"
gem "will_paginate", "2.3.16"
gem "chronic", "0.6.4"
gem "whenever", "0.4.1"
gem "searchlogic", "2.4.28"

group :development do
  gem "mongrel", "1.1.5"
end

group :test do
  gem "rspec", "1.3.2"
  gem "rspec-rails", "1.3.4"
  gem "factory_girl", "1.3.3"
end


问:
Multi-tenant setup for Jenkins
I want to setup multi-tenant support for our Jenkins. Let, we have 5 jobs for two users (GitHub user) in Jenkins and all the 5 jobs are in a single server.

user_1 has j1, j2, j3 jobs

user_2 has j4, j5 jobs

Now,

user_1 can see only j1, j2 and j3 jobs (and don't see j4 or j5)

user_2 can see only j4 and j5 jobs

when they come in Jenkins.

How can we setup Jenkins for multi-tenant support?

答:
For the quickest approach to accomplish what you are describing, follow these steps:

Go to "Configure Global Security" and navigate to the "Authorization" tab

Use "Role Based Strategy"

Give desired access to users

Provide desired job level access for users

You can utilize some type of naming convention for your jobs and you can use regular expression to provide access for a set of jobs.

Another option would be to check out some of the Authentication/Authorization plugins available for Jenkins. A popular plugin in this realm is the Matrix Authorization Strategy Plugin (often combined with Active Directory), though I have not personally used this.

Title: Multi-tenant setup for Jenkins


问:
How to exclude print commands of python script in variable of shell script
I have a python script called spark.py. This scipt will be invoked using a shell script in Linux.

The spark.py is like below:

```<code>#!/usr/bin/env python

import sys
import os

if len(sys.argv) != 2:
     print "Invalid number of args......"
     print "Usage: spark-submit file.py Arguments"
     exit()

table=sys.argv[1]
hivedb=sys.argv[2]

from pyspark import SparkContext, SparkConf
conf = SparkConf()
sc = SparkContext(conf=conf)
from pyspark.sql import HiveContext
sqlContext = HiveContext(sc)
from datetime import datetime

df.registerTempTable('mytempTable')

date=datetime.now().strftime('%Y-%m-%d %H:%M:%S')

try:
    sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
    status = 'fail'
    error_message = e
else:  # Executes only if no Exception.
    status = 'success'
    error_message = 'No error'
print error_message

print ("{},{},{},{},{}".format(hivedb,table,date,status,error_message))

if status != 'success': sys.exit(1)
sc.stop()
</code>```

The shell.sh is like below

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

source /home/$USER/source.sh

[ $# -ne 2 ] && { echo "Usage : $0 input file "; exit 1; }
table=$1
hivedb=$2

TIMESTAMP=`date "+%Y-%m-%d"`
touch /home/$USER/logs/${TIMESTAMP}.success_log
touch /home/$USER/logs/${TIMESTAMP}.fail_log
success_logs=/home/$USER/logs/${TIMESTAMP}.success_log
failed_logs=/home/$USER/logs/${TIMESTAMP}.fail_log

#Function to get the status of the job creation
function log_status
{
       status=$1
       message=$2
       if [ "$status" -ne 0 ]; then
                echo "$result" | tee -a "${failed_logs}"
                else
                    echo "$result" | tee -a "${success_logs}"
                fi
}

result=$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/spark.py ${table} ${hivedb})
g_STATUS=$?
log_status $g_STATUS  "$result"
</code>```

In this shell script I am collecting the output of the spark.py as a variable. When I do so I am unable to see any print commands of the spark.py in the console logs in Linux.

How can I have all the print commands to be printed in the linux console logs.

And In my spark.py script I have

```<code>print error_message

print ("{},{},{},{},{}".format(hivedb,table,date,status,error_message))
</code>```

How can I exclude the print error_message while collecting the output as a variable in the shell.sh .

答:
The cleanest way I can think of is to create a new file without print error_messsage and use it in shell.sh…

```<code>$ sed '/print\serror_message/d' "/home/${USER}/spark.py" > "/home/${USER}/spark_no_err_msg.py"
</code>```

Body:
I have a python script called spark.py. This scipt will be invoked using a shell script in Linux.

The spark.py is like below:

#!/usr/bin/env python

import sys
import os

if len(sys.argv) != 2:
     print "Invalid number of args......"
     print "Usage: spark-submit file.py Arguments"
     exit()

table=sys.argv[1]
hivedb=sys.argv[2]

from pyspark import SparkContext, SparkConf
conf = SparkConf()
sc = SparkContext(conf=conf)
from pyspark.sql import HiveContext
sqlContext = HiveContext(sc)
from datetime import datetime

df.registerTempTable('mytempTable')

date=datetime.now().strftime('%Y-%m-%d %H:%M:%S')

try:
    sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
    status = 'fail'
    error_message = e
else:  # Executes only if no Exception.
    status = 'success'
    error_message = 'No error'
print error_message

print ("{},{},{},{},{}".format(hivedb,table,date,status,error_message))

if status != 'success': sys.exit(1)
sc.stop()

The shell.sh is like below

#!/bin/bash

source /home/$USER/source.sh

[ $# -ne 2 ] && { echo "Usage : $0 input file "; exit 1; }
table=$1
hivedb=$2

TIMESTAMP=`date "+%Y-%m-%d"`
touch /home/$USER/logs/${TIMESTAMP}.success_log
touch /home/$USER/logs/${TIMESTAMP}.fail_log
success_logs=/home/$USER/logs/${TIMESTAMP}.success_log
failed_logs=/home/$USER/logs/${TIMESTAMP}.fail_log

#Function to get the status of the job creation
function log_status
{
       status=$1
       message=$2
       if [ "$status" -ne 0 ]; then
                echo "$result" | tee -a "${failed_logs}"
                else
                    echo "$result" | tee -a "${success_logs}"
                fi
}

result=$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/spark.py ${table} ${hivedb})
g_STATUS=$?
log_status $g_STATUS  "$result"

In this shell script I am collecting the output of the spark.py as a variable. When I do so I am unable to see any print commands of the spark.py in the console logs in Linux.

How can I have all the print commands to be printed in the linux console logs.

And In my spark.py script I have

print error_message

print ("{},{},{},{},{}".format(hivedb,table,date,status,error_message))

How can I exclude the print error_message while collecting the output as a variable in the shell.sh .

Body:
The cleanest way I can think of is to create a new file without print error_messsage and use it in shell.sh…

$ sed '/print\serror_message/d' "/home/${USER}/spark.py" > "/home/${USER}/spark_no_err_msg.py"


问:
Controlling simple relay switch via USB
I'm looking to control a mains powered light from a simple relay switch connected via USB to the computer.

The relay switch isn't even a USB device, it's just a simple switch that requires the USB voltage to turn it on. When the voltage drops below a threshold, the switch will turn the light off.

My problem is that I can't control the power output of a USB port. I'm happy to do it using any language on Windows or Linux (but preferably Java because I'm used to it).

答:
You need a USB-GPIO microcontroller:

Adafruit FT232H  (about $15)

Arduino Nano ATmega328 (about $7)

See this answer

Title: Controlling simple relay switch via USB