问:
React Native/Expo: Event Emitter between screens; trigger refresh
I've scoured this site and various Github issues for a solution but am still a bit stuck. In essence, this is the flow that I desire:

Land on first component/screen, which has some information

Click a button and be pushed to a second component/screen

Do something on this second component/screen

Pop back to first component/screen

Have refreshed information be displayed when we come back to this page

Issues:

Component lifecycles don't work because when I'm popping from the second component to the first component (the parent), there's no component lifecycle method I can call in this case.

Event Emitters won't suffice as a solution because they only work within a single component (is this correct btw?)

Would greatly appreciate any help I can get. Thank you!

答: In the first component, create a function that will refresh the component by updating the state. Pass the function to the second component and when you pop, call this function.</p>


来源: stackexchange

问:
PHP OOP need advice
i am building this sms notification system, which will send 10 times free sms based on certain occasion to the web's member, and after a certain member reach 10 times, the system would send a last notification system saying that "this is the last free sms notification", i am currently learning PHP OOP and trying to use an OOP aproach on this

without further a do here's my code:

```<code><?php
class SmsBonus {
//bonus_sms fields = id, member_id, counter, end_status

public static function find_member($id=0){
    //query to find a certain member
}

public function add_counter($id=0){
    //query to increment the value of counter field
}

public function status_check($id=0){
    //query to check whether the given member's counter has reach the number 10
}

public static function send_sms($id, $message){
    $found = $this->find_member($id);
    $status_check = $this->status_check($id);

    if(!empty($found) && !empty($status_check) && $found->counter == 10){
        //send the sms notification saying that this member has reach the end of the bonus period

        //update this member's end_status table to 1
    }else{
        //send the regular notification
    }
}

}
?>
</code>```

would this lines:

```<code>$found = $this->find_member($id);
$status_check = $this->status_check($id);
</code>```

work as expected (i cant test this one out because i am currently building this on local)? and is this a best practice regarding OOP aproach ? or am i doing this wrong ?

i need advice, thank you very much.

EDIT:

of course on my original code i declare the class, i am sorry that by not writing it here confuses everybody :D, i am actually looking for a kind of answer (advice) that pointed the way i should implement a best approach (best practice) on my codes (in this case methods), things that i worry about is that i don't meet the requirements such as K.I.S.S or D.R.Y.

UPDATE
i manage to do some modifications based on your suggestions, how is this looks like ?

```<code><?php
    class SmsBonus{
        //bonus_sms fields = id, member_id, counter, end_status
        protected $max_sms = 10;

        public $id;
        public $member_id;
        public $counter;
        public $end_status;

        public function find_member($id=0){
            //query to find a certain member
        }

        public function add_counter($id=0){
            //query to increment the value of counter field
        }

        public function status_check($id=0){
            //query to check whether the given member's counter has reach the number 10
        }

        public function update_status($id=0){
            //query to update when a certain member reach its sms bonus limit
        }

        protected function can_still_send_sms($member_id){
            $found          = $this->find_member($member_id);
            $status_check   = $this->status_check($id);
            return !empty($found) && $found->counter < $this->max_sms && !empty($status_check);
        }

        public function send_sms($id, $message){
            $phone  = Phone::find_member($id); //
            if ($this->can_still_send_sms($id)) {
                //send the sms notification saying that this member has reach the end of the bonus period

                $this->update_status($id);
            }else{
                //send the regular notification

                $this->add_counter($id);
            }
        }
    }
    $sms_bonus = new SmsBonus();
?>
</code>```

答:
According to OOP you can't call $this->find_member($id) on a static member function.  Besides you didn't declare any class at all, so $this is meaningless (as far as I remember PHP). You probalby wanted to declare some SmsClient class which would be initialized from db query filling in member variables.  Your static find_member($id=0) function would query db by id and return initialized object of SmsClient with its id = $id

```<code>class SmsClient
{
 private $id;
 private $nSmsSent;

 public __construct($id)
 {
  $res = DAL->GetClient($id);
  //initialize vars here
 }

 public send_sms(...)
 {
  $this->nSmsSent++;
 }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP OOP need advice

Body:
i am building this sms notification system, which will send 10 times free sms based on certain occasion to the web's member, and after a certain member reach 10 times, the system would send a last notification system saying that "this is the last free sms notification", i am currently learning PHP OOP and trying to use an OOP aproach on this

without further a do here's my code:

<?php
class SmsBonus {
//bonus_sms fields = id, member_id, counter, end_status

public static function find_member($id=0){
    //query to find a certain member
}

public function add_counter($id=0){
    //query to increment the value of counter field
}

public function status_check($id=0){
    //query to check whether the given member's counter has reach the number 10
}

public static function send_sms($id, $message){
    $found = $this->find_member($id);
    $status_check = $this->status_check($id);

    if(!empty($found) && !empty($status_check) && $found->counter == 10){
        //send the sms notification saying that this member has reach the end of the bonus period

        //update this member's end_status table to 1
    }else{
        //send the regular notification
    }
}

}
?>

would this lines:

$found = $this->find_member($id);
$status_check = $this->status_check($id);

work as expected (i cant test this one out because i am currently building this on local)? and is this a best practice regarding OOP aproach ? or am i doing this wrong ?

i need advice, thank you very much.

EDIT:

of course on my original code i declare the class, i am sorry that by not writing it here confuses everybody :D, i am actually looking for a kind of answer (advice) that pointed the way i should implement a best approach (best practice) on my codes (in this case methods), things that i worry about is that i don't meet the requirements such as K.I.S.S or D.R.Y.

UPDATE
i manage to do some modifications based on your suggestions, how is this looks like ?

<?php
    class SmsBonus{
        //bonus_sms fields = id, member_id, counter, end_status
        protected $max_sms = 10;

        public $id;
        public $member_id;
        public $counter;
        public $end_status;

        public function find_member($id=0){
            //query to find a certain member
        }

        public function add_counter($id=0){
            //query to increment the value of counter field
        }

        public function status_check($id=0){
            //query to check whether the given member's counter has reach the number 10
        }

        public function update_status($id=0){
            //query to update when a certain member reach its sms bonus limit
        }

        protected function can_still_send_sms($member_id){
            $found          = $this->find_member($member_id);
            $status_check   = $this->status_check($id);
            return !empty($found) && $found->counter < $this->max_sms && !empty($status_check);
        }

        public function send_sms($id, $message){
            $phone  = Phone::find_member($id); //
            if ($this->can_still_send_sms($id)) {
                //send the sms notification saying that this member has reach the end of the bonus period

                $this->update_status($id);
            }else{
                //send the regular notification

                $this->add_counter($id);
            }
        }
    }
    $sms_bonus = new SmsBonus();
?>

Body:
According to OOP you can't call $this->find_member($id) on a static member function.  Besides you didn't declare any class at all, so $this is meaningless (as far as I remember PHP). You probalby wanted to declare some SmsClient class which would be initialized from db query filling in member variables.  Your static find_member($id=0) function would query db by id and return initialized object of SmsClient with its id = $id

class SmsClient
{
 private $id;
 private $nSmsSent;

 public __construct($id)
 {
  $res = DAL->GetClient($id);
  //initialize vars here
 }

 public send_sms(...)
 {
  $this->nSmsSent++;
 }
}


问:
Why is % used to calculate hashCode index conversion?
Let's say my bucket count is 100 for my Hash Table. My hash code comes out to 500 for Key A, and 600 for Key B. These both resolve to 0 for hashCode % this.bucketCount, which is a collision for different hash codes.

I'm wondering why % is used to calculate the index. Can someone explain the math on this? Why is the index output by that math the place where I should insert my node?

```<code>HashTable.prototype.hashFunction = function(key){
    var hash = 0;
    for (var i=0;i< key.length; i++){
        console.log(key.charCodeAt(i))
        hash += key.charCodeAt(i)
    }
    return hash;
};

HashTable.prototype.convertHashToIndex = function(hashCode) {
    return hashCode % this.bucketCount;
};
</code>```

答: Because there are bucketCount buckets, the modulus (or remainder) of division by the number of buckets is used to ensure that the result fits in the buckets available. If you didn't take the modulus, you'd get results without being able to store them.

ContentLicense: CC BY-SA 3.0

Body:
Let's say my bucket count is 100 for my Hash Table. My hash code comes out to 500 for Key A, and 600 for Key B. These both resolve to 0 for hashCode % this.bucketCount, which is a collision for different hash codes.

I'm wondering why % is used to calculate the index. Can someone explain the math on this? Why is the index output by that math the place where I should insert my node?

HashTable.prototype.hashFunction = function(key){
    var hash = 0;
    for (var i=0;i< key.length; i++){
        console.log(key.charCodeAt(i))
        hash += key.charCodeAt(i)
    }
    return hash;
};

HashTable.prototype.convertHashToIndex = function(hashCode) {
    return hashCode % this.bucketCount;
};


问:
Angular 2 Scroll to bottom (Chat style)
I have a set of single cell components within an ng-for loop.

I have everything in place but I cannot seem to figure out the proper

Currently I have

```<code>setTimeout(() => {
  scrollToBottom();
});
</code>```

But this doesn't work all the time as images asynchronously push the viewport down.

Whats the appropriate way to scroll to the bottom of a chat window in Angular 2?

答:
I added a check to see if the user tried to scroll up.

I'm just going to leave this here if anyone wants it :)

```<code><div class="jumbotron">
    <div class="messages-box" #scrollMe (scroll)="onScroll()">
        <app-message [message]="message" [userId]="profile.userId" *ngFor="let message of messages.slice().reverse()"></app-message>
    </div>

    <textarea [(ngModel)]="newMessage" (keyup.enter)="submitMessage()"></textarea>
</div>
</code>```

and the code:

```<code>import { AfterViewChecked, ElementRef, ViewChild, Component, OnInit } from '@angular/core';
import {AuthService} from "../auth.service";
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/concatAll';
import {Observable} from 'rxjs/Rx';

import { Router, ActivatedRoute } from '@angular/router';

@Component({
    selector: 'app-messages',
    templateUrl: './messages.component.html',
    styleUrls: ['./messages.component.scss']
})
export class MessagesComponent implements OnInit {
    @ViewChild('scrollMe') private myScrollContainer: ElementRef;
    messages:Array<MessageModel>
    newMessage = ''
    id = ''
    conversations: Array<ConversationModel>
    profile: ViewMyProfileModel
    disableScrollDown = false

    constructor(private authService:AuthService,
                private route:ActivatedRoute,
                private router:Router,
                private conversationsApi:ConversationsApi) {
    }

    ngOnInit() {

    }

    public submitMessage() {

    }

     ngAfterViewChecked() {
        this.scrollToBottom();
    }

    private onScroll() {
        let element = this.myScrollContainer.nativeElement
        let atBottom = element.scrollHeight - element.scrollTop === element.clientHeight
        if (this.disableScrollDown && atBottom) {
            this.disableScrollDown = false
        } else {
            this.disableScrollDown = true
        }
    }

    private scrollToBottom(): void {
        if (this.disableScrollDown) {
            return
        }
        try {
            this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
        } catch(err) { }
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Angular 2 Scroll to bottom (Chat style)

Body:
I have a set of single cell components within an ng-for loop.

I have everything in place but I cannot seem to figure out the proper

Currently I have

setTimeout(() => {
  scrollToBottom();
});

But this doesn't work all the time as images asynchronously push the viewport down.

Whats the appropriate way to scroll to the bottom of a chat window in Angular 2?

Body:
I added a check to see if the user tried to scroll up.

I'm just going to leave this here if anyone wants it :)

<div class="jumbotron">
    <div class="messages-box" #scrollMe (scroll)="onScroll()">
        <app-message [message]="message" [userId]="profile.userId" *ngFor="let message of messages.slice().reverse()"></app-message>
    </div>

    <textarea [(ngModel)]="newMessage" (keyup.enter)="submitMessage()"></textarea>
</div>

and the code:

import { AfterViewChecked, ElementRef, ViewChild, Component, OnInit } from '@angular/core';
import {AuthService} from "../auth.service";
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/concatAll';
import {Observable} from 'rxjs/Rx';

import { Router, ActivatedRoute } from '@angular/router';

@Component({
    selector: 'app-messages',
    templateUrl: './messages.component.html',
    styleUrls: ['./messages.component.scss']
})
export class MessagesComponent implements OnInit {
    @ViewChild('scrollMe') private myScrollContainer: ElementRef;
    messages:Array<MessageModel>
    newMessage = ''
    id = ''
    conversations: Array<ConversationModel>
    profile: ViewMyProfileModel
    disableScrollDown = false

    constructor(private authService:AuthService,
                private route:ActivatedRoute,
                private router:Router,
                private conversationsApi:ConversationsApi) {
    }

    ngOnInit() {

    }

    public submitMessage() {

    }

     ngAfterViewChecked() {
        this.scrollToBottom();
    }

    private onScroll() {
        let element = this.myScrollContainer.nativeElement
        let atBottom = element.scrollHeight - element.scrollTop === element.clientHeight
        if (this.disableScrollDown && atBottom) {
            this.disableScrollDown = false
        } else {
            this.disableScrollDown = true
        }
    }

    private scrollToBottom(): void {
        if (this.disableScrollDown) {
            return
        }
        try {
            this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
        } catch(err) { }
    }

}


问:
Grouping a dataframe by time with "nice" breaks using dplyr
Intro:

I would like to aggregate some 5-minute data into 10-minute data. Specifically, I only want to aggregate on the 10-minute marks (00:10:00, 00:20:00, 00:30:00, etc.).

The code below almost achieves this, but the breaks are on the 5 minute mark instead of the 10 minute mark (00:05:00, 00:15:00, 00:25:00). I think dplyr is using the first row in the dataframe when determining the cutpoints.

Are there any ways to achieve "nice" 10-min breaks using cut {base} and group_by() {dplyr}? I would be okay with just removing the first row of data, but I really need the solution to manage many different files, each of which with unique starting points.

Thanks in advance!

Example Code:

```<code>date <- c("2017-06-14 14:35:00", "2017-06-14 14:40:00", "2017-06-14 14:45:00", "2017-06-14 14:50:00")
co <- as.numeric(c(5.17,10.07,13.88,13.78))
no <- as.numeric(c(34.98,32.45,31.34,29.09))
no2 <- as.numeric(c(0.00,0.00,0.00,0.00))
o3 <- as.numeric(c(5.17,10.07,13.88,13.78))

data <- data.frame(date, co, no , no2, o3)
data$date <- strptime(data$date, format = "%Y-%m-%d %H:%M")
data$date <- as.POSIXct(data$date)

head(data)

data_10min <- data %>%
      group_by(date = cut(date, breaks = "10 min")) %>%
      summarize(co = mean(co), no = mean(no), no2 = mean(no2), o3 = mean(o3))

head(data_10min)
</code>```

Desired Output:

```<code>2017-06-14 14:40:00
2017-06-14 14:50:00
</code>```

答:
Just adding 300 seconds to date column during group_by gets the desired result.

```<code>library(magrittr)
library(dplyr)

df_10min <- df %>%
  group_by(date = cut(as.POSIXct(x) + 300, breaks = "10 min")) %>%
  summarize_each(funs(mean))

df_10min
</code>```

The result:

```<code># # A tibble: 2 × 5
# date    co     no   no2    o3
# <fctr> <dbl>  <dbl> <dbl> <dbl>
# 1 2017-06-14 14:40:00  7.62 33.715     0  7.62
# 2 2017-06-14 14:50:00 13.83 30.215     0 13.83
</code>```

Body:
Intro:

I would like to aggregate some 5-minute data into 10-minute data. Specifically, I only want to aggregate on the 10-minute marks (00:10:00, 00:20:00, 00:30:00, etc.).

The code below almost achieves this, but the breaks are on the 5 minute mark instead of the 10 minute mark (00:05:00, 00:15:00, 00:25:00). I think dplyr is using the first row in the dataframe when determining the cutpoints.

Are there any ways to achieve "nice" 10-min breaks using cut {base} and group_by() {dplyr}? I would be okay with just removing the first row of data, but I really need the solution to manage many different files, each of which with unique starting points.

Thanks in advance!

Example Code:

date <- c("2017-06-14 14:35:00", "2017-06-14 14:40:00", "2017-06-14 14:45:00", "2017-06-14 14:50:00")
co <- as.numeric(c(5.17,10.07,13.88,13.78))
no <- as.numeric(c(34.98,32.45,31.34,29.09))
no2 <- as.numeric(c(0.00,0.00,0.00,0.00))
o3 <- as.numeric(c(5.17,10.07,13.88,13.78))

data <- data.frame(date, co, no , no2, o3)
data$date <- strptime(data$date, format = "%Y-%m-%d %H:%M")
data$date <- as.POSIXct(data$date)

head(data)

data_10min <- data %>%
      group_by(date = cut(date, breaks = "10 min")) %>%
      summarize(co = mean(co), no = mean(no), no2 = mean(no2), o3 = mean(o3))

head(data_10min)

Desired Output:

2017-06-14 14:40:00
2017-06-14 14:50:00

Body:
Just adding 300 seconds to date column during group_by gets the desired result.

library(magrittr)
library(dplyr)

df_10min <- df %>%
  group_by(date = cut(as.POSIXct(x) + 300, breaks = "10 min")) %>%
  summarize_each(funs(mean))

df_10min

The result:

# # A tibble: 2 × 5
# date    co     no   no2    o3
# <fctr> <dbl>  <dbl> <dbl> <dbl>
# 1 2017-06-14 14:40:00  7.62 33.715     0  7.62
# 2 2017-06-14 14:50:00 13.83 30.215     0 13.83


问:
Angular2, "replace" scrollbar
I have an angular app with a scrollable sidenav.

This sidenav has the native ugly scrollbar. I want to replace this one with a styleable scrollbar.

Are there any good solutions for angular 2 which don't require jQuery?

Do I have to use an external JavaScript solution which doesn't rely on angular?

Thanks in advance!

PS: If important, I use Angular Material 2

PPS: I've already tried gemini-scrollbar, but this has broken the width of the sidenav and simplebar which has caused a ram overflow.

Edit:
I want to replase this ugly scrollbar:

答: You don't need JQuery to archive this task. It's pretty simple and easy to use ADD to do this. There's a example in this link https://css-tricks.com/almanac/properties/s/scrollbar/</p>

Title: Angular2, "replace" scrollbar


问:
How to pass entire directory into python via command line and sys.argv
So in the past when I've used a unix server to do my python development if I wanted to pass in an entire folder or directory, I would just put an asterisk() on the end of it. An example would be something like users/wilkenia/shakespeare/ to pass in a set of files containing each of shakespeare's plays. Is there a way to do this in windows? I've tried putting in C:\Users\Alexander\Desktop\coding-data-exam\wx_data* and the same with the disk name removed. Nothing has worked so far, in fact, it takes in the directory as an argument itself.

Edit: implemented glob, getting a permissions error, even though I'm running as administrator. Here's my code if anyone wants to have a look.

答:
You can use the glob module, it does exactly this.

A quick demo:

```<code>In [81]: import glob

In [82]: glob.glob('*')
Out[82]:
[
... # a bunch of my personal files from my cwd
]
</code>```

If you want to extend this for your use case, you'll need to do something along the lines of:

```<code>import sys
import glob

arg = sys.argv[1]

for file in glob.glob(arg):
    ....
</code>```

You'll read your args with sys.argv and pass it onto glob.

Body:
You can use the glob module, it does exactly this.

A quick demo:

In [81]: import glob

In [82]: glob.glob('*')
Out[82]:
[
... # a bunch of my personal files from my cwd
]

If you want to extend this for your use case, you'll need to do something along the lines of:

import sys
import glob

arg = sys.argv[1]

for file in glob.glob(arg):
    ....

You'll read your args with sys.argv and pass it onto glob.


问:
create-react-app + docker = QA and PROD Deploy
I'm using create-react-app for my projects using docker as my dev env.

Now I would like to know how is the best practice to deploy my project into AWS (I'll deploy the docker).

Maybe my question is a dummy but I'm really stuck on it.

My docker file has a command yarn start... for dev it is enough I don't need to build anything, my bundle will run in memory, but for QA or PROD I would like to build using npm run build but as I know it will create a new folder with the files that should be used on prod env.

That said, my question is: what is the best practice for this kind of situation?

Thanks.

答:
This is what I did:

Use npm run build to build all static files.

Use _/nginx image to customize an HTTP server which serves those static files. (Dockerfile)

Upload the customized image to Amazon EC2 Container Service (ECS).

Load the image in ECS task. Then use ELBv2 to start a load balance server to forward all outside requests to ECS.

(Optional) Enable HTTPS in ELBv2.

One time things:

Figure out the mechanism of ECS. You need to create at least one host server for ECS. I used the Amazon ECS-Optimized AMI.

Create a Docker repository on ECS so you can upload your customized Docker image.

Create ECS task definition(s) for your service.

Create ECS cluster(s) and add task(s).

Configure ELBv2 so it can forward the traffic to your internal ECS dynamic port.

(Optional) Write script to automate everyday deployment.

I would get paid if someone wants me to do those things for her/him. Or you can figure it out by yourself following those clues.

However, if your website is a simple static site, I recommend to use Github pages: it's free and simple. My solution is for multiple static + dynamic applications which may involved other services (e.g. Redis, ElasticSearch) and required daily/hourly deployments.


问:
Returning values from thread
I am running selenium tests inside a for loop which takes time.

I needed to indicate the progress of those tests using javafx progressbar.

So I replaced the code inside for loop with a task.

Following is my code

The runTests() method returns a String which is displayed as an Alert

I cannot return a String from inside Task<Void> as the return type is Void

The test code is inside runTest(data) method which returns true or false

```<code>@FXML
private void handleRunTestButton(ActionEvent aEvent) throws IOException {
    String testResultMessage = runTests();
    if (!testResultMessage.equals("Testing Complete!")) {
        Alert alert = DialogUtils.getAlert("Info", "Information", testResultMessage, "info");
        alert.showAndWait();

    } else {
        Alert alert = DialogUtils.getAlert("Error", "Error(s)", testResultMessage, "error");
        alert.showAndWait();
    }

}

private String runTests() {
    /* xlsx read */
    FileInputStream fis = null;
    File testDataFile = null;
    try {
        fis = new FileInputStream(selectedTestDataFile);
    } catch (FileNotFoundException e) {
        return "File Input Stream Error: File Not Found";
    }

    // Finds the workbook instance for XLSX file
    XSSFWorkbook myWorkBook = null;
    try {
        myWorkBook = new XSSFWorkbook(fis);
    } catch (IOException e) {
        return "XSSFWorkbook I/O Error";
    }

    // Return first sheet from the XLSX workbook
    XSSFSheet mySheet = myWorkBook.getSheetAt(0);

    int totalWids = mySheet.getLastRowNum();

    final Task<Void> task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            for (int rowIndex = 1; rowIndex <= totalWids; rowIndex++) {
                updateProgress(rowIndex, totalWids);
                Row row = mySheet.getRow(rowIndex);
                if (row != null) {
                    String data = "";

                    Cell cellData = row.getCell(2);

                    if (cellData != null) {
                        data = cellWid.getStringCellValue();
                        boolean testresult = runTest(data);
                        System.out.println(rowIndex + ". data = " + data + ", testresult = " + testresult);
                    }
                }
            }
            return null;
        }
    };

    progressBar.progressProperty().bind(task.progressProperty());
    progressIndicator.progressProperty().bind(task.progressProperty());

    final Thread thread = new Thread(task, "task-thread");
    thread.setDaemon(true);
    thread.start();

    /* xlsx read */
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(selectedTestDataFile);
    } catch (FileNotFoundException e) {
        try {
            myWorkBook.close();
        } catch (IOException e1) {
            return "Error: Please Close Workbook";
        }
        return "Error: File Not Found";
    }
    try {
        myWorkBook.write(fos);
    } catch (IOException e) {
        try {
            myWorkBook.close();
        } catch (IOException e1) {
            return "Error: Please Close Workbook";
        }
        return "Error: Workbook Write";
    }
    try {
        fos.close();
    } catch (IOException e) {
        try {
            myWorkBook.close();
        } catch (IOException e1) {
            return "Error: Please Close Workbook";
        }
        return "Error: File Output Stream";
    }
    try {
        myWorkBook.close();
    } catch (IOException e) {
        return "Error: Please Close Workbook";
    }
    try {
        fis.close();
    } catch (IOException e) {

        return "Error: Input file format";
    }
    return "Testing Complete!";
}
</code>```

However, now it returns Testing Complete! while the tests are still running.

I am new to multithreading. Please suggest me how to structure the code.

How can I make the runTests() method return a String value from inside

```<code>final Task<Void> task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            for () {

            }
            return null;
        }
    };
</code>```

Before this, when I didn't use Task my code showed the alert properly however the progress bar did not update despite of setting the progress from within the for loop.

答:
First off, you can't return a value from the thread in the sense you want it to without blocking. Instead, try calling a method when the thread is done.

Let say we have this thread that runs some intensive task (in this case a simple forloop) and you want it to "return" the sum when it is done:

```<code>private void startMyThread() {
    Thread t = new Thread( () -> {
        System.out.println("Thread Started.");

        // Some intensive task
        int sum = 0;
        for(int i = 0; i < 1000000; i++) {
            sum++;
        }

        System.out.println("Thread ending.");
        threadIsDone(sum);
    });

    System.out.println("Starting Thread.");
    t.start();
}
</code>```

Instead of getting your return value from startMyThread() you wait to execute your action until threadIsDone() is called:

```<code>private void threadIsDone(int sum) {
    Platform.runLater( () -> {
        /* Update Progress Bar */
        System.out.println("Updated Progress Bar");
    });

    System.out.println("Thread ended.");
}
</code>```

You'll notice I use Platform.runLater() inside the method because all updates to JavaFx elements needs to be done on the main thread and since we called threadIsDone() from a different thread, we need to tell JavaFx that we want it to do this action on the main thread and not the current thread.

Title: Returning values from thread

Body:
I am running selenium tests inside a for loop which takes time.

I needed to indicate the progress of those tests using javafx progressbar.

So I replaced the code inside for loop with a task.

Following is my code

The runTests() method returns a String which is displayed as an Alert

I cannot return a String from inside Task<Void> as the return type is Void

The test code is inside runTest(data) method which returns true or false

@FXML
private void handleRunTestButton(ActionEvent aEvent) throws IOException {
    String testResultMessage = runTests();
    if (!testResultMessage.equals("Testing Complete!")) {
        Alert alert = DialogUtils.getAlert("Info", "Information", testResultMessage, "info");
        alert.showAndWait();

    } else {
        Alert alert = DialogUtils.getAlert("Error", "Error(s)", testResultMessage, "error");
        alert.showAndWait();
    }

}

private String runTests() {
    /* xlsx read */
    FileInputStream fis = null;
    File testDataFile = null;
    try {
        fis = new FileInputStream(selectedTestDataFile);
    } catch (FileNotFoundException e) {
        return "File Input Stream Error: File Not Found";
    }

    // Finds the workbook instance for XLSX file
    XSSFWorkbook myWorkBook = null;
    try {
        myWorkBook = new XSSFWorkbook(fis);
    } catch (IOException e) {
        return "XSSFWorkbook I/O Error";
    }

    // Return first sheet from the XLSX workbook
    XSSFSheet mySheet = myWorkBook.getSheetAt(0);

    int totalWids = mySheet.getLastRowNum();

    final Task<Void> task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            for (int rowIndex = 1; rowIndex <= totalWids; rowIndex++) {
                updateProgress(rowIndex, totalWids);
                Row row = mySheet.getRow(rowIndex);
                if (row != null) {
                    String data = "";

                    Cell cellData = row.getCell(2);

                    if (cellData != null) {
                        data = cellWid.getStringCellValue();
                        boolean testresult = runTest(data);
                        System.out.println(rowIndex + ". data = " + data + ", testresult = " + testresult);
                    }
                }
            }
            return null;
        }
    };

    progressBar.progressProperty().bind(task.progressProperty());
    progressIndicator.progressProperty().bind(task.progressProperty());

    final Thread thread = new Thread(task, "task-thread");
    thread.setDaemon(true);
    thread.start();

    /* xlsx read */
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(selectedTestDataFile);
    } catch (FileNotFoundException e) {
        try {
            myWorkBook.close();
        } catch (IOException e1) {
            return "Error: Please Close Workbook";
        }
        return "Error: File Not Found";
    }
    try {
        myWorkBook.write(fos);
    } catch (IOException e) {
        try {
            myWorkBook.close();
        } catch (IOException e1) {
            return "Error: Please Close Workbook";
        }
        return "Error: Workbook Write";
    }
    try {
        fos.close();
    } catch (IOException e) {
        try {
            myWorkBook.close();
        } catch (IOException e1) {
            return "Error: Please Close Workbook";
        }
        return "Error: File Output Stream";
    }
    try {
        myWorkBook.close();
    } catch (IOException e) {
        return "Error: Please Close Workbook";
    }
    try {
        fis.close();
    } catch (IOException e) {

        return "Error: Input file format";
    }
    return "Testing Complete!";
}

However, now it returns Testing Complete! while the tests are still running.

I am new to multithreading. Please suggest me how to structure the code.

How can I make the runTests() method return a String value from inside

final Task<Void> task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            for () {

            }
            return null;
        }
    };

Before this, when I didn't use Task my code showed the alert properly however the progress bar did not update despite of setting the progress from within the for loop.

Body:
First off, you can't return a value from the thread in the sense you want it to without blocking. Instead, try calling a method when the thread is done.

Let say we have this thread that runs some intensive task (in this case a simple forloop) and you want it to "return" the sum when it is done:

private void startMyThread() {
    Thread t = new Thread( () -> {
        System.out.println("Thread Started.");

        // Some intensive task
        int sum = 0;
        for(int i = 0; i < 1000000; i++) {
            sum++;
        }

        System.out.println("Thread ending.");
        threadIsDone(sum);
    });

    System.out.println("Starting Thread.");
    t.start();
}

Instead of getting your return value from startMyThread() you wait to execute your action until threadIsDone() is called:

private void threadIsDone(int sum) {
    Platform.runLater( () -> {
        /* Update Progress Bar */
        System.out.println("Updated Progress Bar");
    });

    System.out.println("Thread ended.");
}

You'll notice I use Platform.runLater() inside the method because all updates to JavaFx elements needs to be done on the main thread and since we called threadIsDone() from a different thread, we need to tell JavaFx that we want it to do this action on the main thread and not the current thread.


问:
AttributeError: 'Series' object has no attribute 'days'
I have a column 'delta' in a dataframe dtype: timedelta64[ns], calculated by subcontracting one date from another. I am trying to return the number of days as a float by using this code:

```<code>from datetime import datetime
from datetime import date
df['days'] = float(df['delta'].days)
</code>```

but I receive this error:

```<code>AttributeError: 'Series' object has no attribute 'days'
</code>```

Any ideas why?

答:
While subtracting the dates you should use the following code.

```<code>df = pd.DataFrame([ pd.Timestamp('20010101'), pd.Timestamp('20040605') ])
(df.loc[0]-df.loc[1]).astype('timedelta64[D]')
</code>```

So basically use .astype('timedelta64[D]') on the subtracted column.

Body:
I have a column 'delta' in a dataframe dtype: timedelta64[ns], calculated by subcontracting one date from another. I am trying to return the number of days as a float by using this code:

from datetime import datetime
from datetime import date
df['days'] = float(df['delta'].days)

but I receive this error:

AttributeError: 'Series' object has no attribute 'days'

Any ideas why?

Body:
While subtracting the dates you should use the following code.

df = pd.DataFrame([ pd.Timestamp('20010101'), pd.Timestamp('20040605') ])
(df.loc[0]-df.loc[1]).astype('timedelta64[D]')

So basically use .astype('timedelta64[D]') on the subtracted column.


问:
How to install an R package to R-3.3.0 from GitHub, which is built on R-3.4.0?
We have R-3.3.0 in our university's computing system. For some reason, the IT staffs do not want to update R version to R-3.4.0 soon. However, I need to install an R package from the GitHub, which is built on R-3.4.0. Is there any way to install that R package from the GitHub's to R-3.3.0? </p>

答:
You can find the description file for OPWeight here.

Change this part

Depends:
      R (>= 3.4.0),

to whatever R you are using and see if things break. The logic of the description file is explained here. Obviously a last resort.


问:
MSXML2.ServerXMLHTTP - The parameter is incorrect
I'm trying to use the following code to download a webpage:

```<code>dim xmlhttp : set xmlhttp = createobject("MSXML2.ServerXMLHTTP")
dim fso : set fso = createobject ("scripting.filesystemobject")
dim newfile : set newfile = fso.createtextfile("getVersion.htm", true)

xmlhttp.SetOption SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS, true
xmlhttp.open "GET", "https://mysite:8443/remote/epo.GetVersion", "username", "password"
xmlhttp.send

newfile.write (xmlhttp.responseText)
newfile.close
</code>```

However, it fails with "mxm13.dll: The parameter is incorrect." on line 6.  What am I doing wrong?

答:
If you're using Windows 8, Windows 8.1 or Windows Server 2012/2012R2, you might have to apply the following HotFix, which fixed this problem for me in a similar scenario:

https://support.microsoft.com/en-us/help/2968741/error-0x80070057-when-sql-server-communicates-to-a-web-server-using-st

For further info you can also read this post on my blog or take a look to this other SO thread.

Body:
I'm trying to use the following code to download a webpage:

dim xmlhttp : set xmlhttp = createobject("MSXML2.ServerXMLHTTP")
dim fso : set fso = createobject ("scripting.filesystemobject")
dim newfile : set newfile = fso.createtextfile("getVersion.htm", true)

xmlhttp.SetOption SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS, true
xmlhttp.open "GET", "https://mysite:8443/remote/epo.GetVersion", "username", "password"
xmlhttp.send

newfile.write (xmlhttp.responseText)
newfile.close

However, it fails with "mxm13.dll: The parameter is incorrect." on line 6.  What am I doing wrong?


问:
Changing dropdown options
I am developing a musical store. In that application in makepayment.jsp I have four links for user choice and based on user choice I want change the options in my dropdown. How can I do that?

答:
get the combobox object by id or name in the javascript.

```<code><select id="myCombo" name="myCombo">
</select>

var opt = document.createElement("option");
opt.text="something"
opt.value="something"
document.getElementById("myCombo").options.add(opt);
</code>```

also you can assign id to options.

Title: Changing dropdown options

Body:
get the combobox object by id or name in the javascript.

<select id="myCombo" name="myCombo">
</select>

var opt = document.createElement("option");
opt.text="something"
opt.value="something"
document.getElementById("myCombo").options.add(opt);

also you can assign id to options.


问:
Checkbox select create an array
I'm trying to create a group of checkboxes that on selection creates an array of objects with multiple fields. Whenever I select a checkbox here it errors and asks for a key. I have a key so I'm a little confused by it.

Path: Form Component

```<code>export default class RoleAndSkillsFormPage extends Component {
  constructor(props) {
    super(props);

    this.state = {
      rolesInterestedIn: [],
    };

    this.handleRoleTypeSelection = this.handleRoleTypeSelectionTwo.bind(this);
  }

  handleRoleTypeSelection(evt){
    evt.preventDefault();

    this.setState({
      rolesInterestedIn: [{
        roleType: evt.target.value,
        yearsOfExpereince: ''
      }]
    })
  }

  render() {
    return (
      <div className="paper">
        <Form className="roleAndSkillsForm" onSubmit={this.handleFormSubmit}>
          <CheckboxGroupTwo
            name={'typeOfWork'}
            options={['Audit - internal', 'Audit - external', 'Tax']}
            label={'What roles are you most interested in? *'}
            controlFunc={this.handleRoleTypeSelection}
          />
        </Form>
      </div>
    );
  }
}
</code>```

Path: Checkboxgroup Component

```<code>const CheckboxGroup = (props) => (
  <FormGroup controlId={props.name}>
    {props.options.map(opt => {
      console.log(opt);
      return (
        <Checkbox
          name={props.name}
          key={opt}
          onChange={props.controlFunc}
          value={opt}
          checked={opt.selectedOption}
          inline
        >
          {opt}
        </Checkbox>
        );
      })}
    </FormGroup>
  );

  CheckboxGroup.propTypes = {
    name: PropTypes.string,
    options: PropTypes.array,
    selectedOption: PropTypes.string,
    controlFunc: PropTypes.func,
    label: PropTypes.string
  };
</code>```

答:
When you are using the map method on the given array use the index parameter and pass them into the key attribute.

For example ;

```<code>const array = ['food', 'drinks', 'clothes'];
array.map((item, index) => {
    <li key={index}>{item}</li>
});
</code>```

When you don't have stable IDs for rendered items, you may use the
  item index as a key as a last resort:

```<code>const todoItems = todos.map((todo, index) =>
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);
</code>```

For more information on keys and lists refer to Lists and Keys - React.

Title: Checkbox select create an array

Body:
I'm trying to create a group of checkboxes that on selection creates an array of objects with multiple fields. Whenever I select a checkbox here it errors and asks for a key. I have a key so I'm a little confused by it.

Path: Form Component

export default class RoleAndSkillsFormPage extends Component {
  constructor(props) {
    super(props);

    this.state = {
      rolesInterestedIn: [],
    };

    this.handleRoleTypeSelection = this.handleRoleTypeSelectionTwo.bind(this);
  }

  handleRoleTypeSelection(evt){
    evt.preventDefault();

    this.setState({
      rolesInterestedIn: [{
        roleType: evt.target.value,
        yearsOfExpereince: ''
      }]
    })
  }

  render() {
    return (

        <Form className="roleAndSkillsForm" onSubmit={this.handleFormSubmit}>
          <CheckboxGroupTwo
            name={'typeOfWork'}
            options={['Audit - internal', 'Audit - external', 'Tax']}
            label={'What roles are you most interested in? *'}
            controlFunc={this.handleRoleTypeSelection}
          />
        </Form>

    );
  }
}

Path: Checkboxgroup Component

const CheckboxGroup = (props) => (
  <FormGroup controlId={props.name}>
    {props.options.map(opt => {
      console.log(opt);
      return (
        <Checkbox
          name={props.name}
          key={opt}
          onChange={props.controlFunc}
          value={opt}
          checked={opt.selectedOption}
          inline
        >
          {opt}
        </Checkbox>
        );
      })}
    </FormGroup>
  );

  CheckboxGroup.propTypes = {
    name: PropTypes.string,
    options: PropTypes.array,
    selectedOption: PropTypes.string,
    controlFunc: PropTypes.func,
    label: PropTypes.string
  };

Body:
When you are using the map method on the given array use the index parameter and pass them into the key attribute.

For example ;

const array = ['food', 'drinks', 'clothes'];
array.map((item, index) => {
    <li key={index}>{item}</li>
});

When you don't have stable IDs for rendered items, you may use the
  item index as a key as a last resort:

const todoItems = todos.map((todo, index) =>
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);

For more information on keys and lists refer to Lists and Keys - React.


问:
How does delegation work in array OrderBy method in C#?
I'm learning delegation with array data structure in C#. Please take a look at my code. I tried to expand lambda expression and delegation in array OrderBy() method in order to fully understand how it works. But Visual Studio gives syntax error even though the running result is correct. I'd appreciate it if someone can help me correct "delegation 3" part. Thank you.</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test2 {
    class Program {

        delegate int Del(int i);

        static void Main(string[] args) {

            int[] MyArray = new int[5] { 3, 2, 6, 10, -3 };

            // print original array
            foreach (var i in MyArray) {
                Console.Write(i + " ");
            }

            Console.WriteLine();
            //Console.ReadKey();

            // sort array by using either Linq or OrderBy
            // Linq works
            //int[] mynewarray = (from i in MyArray orderby i ascending select i).ToArray();

            // delegation 1 works
            //int[] mynewarray = MyArray.OrderBy(i => i).ToArray();
            // delegation 2 works
            //int[] mynewarray = MyArray.OrderBy(delegate (int i) { return i; }).ToArray();
            // delegation 3 has syntax error
            Del del = MyInt;
            int[] mynewarray = MyArray.OrderBy(del(int i)).ToArray();

            // print sorted array
            foreach (var i in mynewarray) {
                Console.Write(i + " ");
            }

            Console.ReadKey();

        }
        public static int MyInt(int i) {
            return i;
        }

    }
}
</code>```

答:
Here is what I learned today. Below is a very traditional way to use delegate (c#1.0). It's just a way to help me understand delegate. I actually wanted to use below way of delegate in the code I posted in my question.</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateDemo_2 {
    class Program {

        delegate bool IsTeenAge(Student stud);

        static void Main(string[] args) {

            // reference: http://www.tutorialsteacher.com/linq/linq-lambda-expression

            IsTeenAge isteenage = new IsTeenAge(CheckAge);
            Student stud1 = new Student() { Age = 17 };
            Console.WriteLine(isteenage(stud1));

            Console.ReadKey();
        }

        static bool CheckAge(Student s) {
            return s.Age > 12 && s.Age < 18;
        }
    }
}
</code>```

Body:
I'm learning delegation with array data structure in C#. Please take a look at my code. I tried to expand lambda expression and delegation in array OrderBy() method in order to fully understand how it works. But Visual Studio gives syntax error even though the running result is correct. I'd appreciate it if someone can help me correct "delegation 3" part. Thank you.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test2 {
    class Program {

        delegate int Del(int i);

        static void Main(string[] args) {

            int[] MyArray = new int[5] { 3, 2, 6, 10, -3 };

            // print original array
            foreach (var i in MyArray) {
                Console.Write(i + " ");
            }

            Console.WriteLine();
            //Console.ReadKey();

            // sort array by using either Linq or OrderBy
            // Linq works
            //int[] mynewarray = (from i in MyArray orderby i ascending select i).ToArray();

            // delegation 1 works
            //int[] mynewarray = MyArray.OrderBy(i => i).ToArray();
            // delegation 2 works
            //int[] mynewarray = MyArray.OrderBy(delegate (int i) { return i; }).ToArray();
            // delegation 3 has syntax error
            Del del = MyInt;
            int[] mynewarray = MyArray.OrderBy(del(int i)).ToArray();

            // print sorted array
            foreach (var i in mynewarray) {
                Console.Write(i + " ");
            }

            Console.ReadKey();

        }
        public static int MyInt(int i) {
            return i;
        }

    }
}

Body:
Here is what I learned today. Below is a very traditional way to use delegate (c#1.0). It's just a way to help me understand delegate. I actually wanted to use below way of delegate in the code I posted in my question.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateDemo_2 {
    class Program {

        delegate bool IsTeenAge(Student stud);

        static void Main(string[] args) {

            // reference: http://www.tutorialsteacher.com/linq/linq-lambda-expression

            IsTeenAge isteenage = new IsTeenAge(CheckAge);
            Student stud1 = new Student() { Age = 17 };
            Console.WriteLine(isteenage(stud1));

            Console.ReadKey();
        }

        static bool CheckAge(Student s) {
            return s.Age > 12 && s.Age < 18;
        }
    }
}


问:
string cannot start a parameter declaration
I am getting the following compilation errors:

```<code>bool isRotated(string str1, string str2)
{

}
</code>```

'string' cannot start a parameter declaration

) expected

Header files included are:

```<code>iostream.h
string.h
</code>```

Am I missing something here?

答:
There is no fully qualified type name string in C++ standard library. All standard library types are declared in the std namespace, so the name of the type that you're looking for is std::string. Also, you did not include the header which declares std::string: <string> (<string.h> is a completely different header, part of the C standard library which is included in C++ standard library).

P.S. <iostream.h> header is not standard - although it was used by some compilers prior to standardization. You're looking for <iostream>. Although, your example doesn't use anything from that header.

Body:
I am getting the following compilation errors:

bool isRotated(string str1, string str2)
{

}

'string' cannot start a parameter declaration

) expected

Header files included are:

iostream.h
string.h

Am I missing something here?


答:
Neither iostream.h nor string.h exist in C++*, and the type is called std::string.

You seem to be learning from an extremely old resource (outdating what we actually call C++ since 1998).

```<code>#include <string>

bool isRotated(std::string str1, std::string str2)
{
}
</code>```

* Pedants will note that string.h is included for compatibility with C, but is better known as cstring and is regardless not at all the same header that you are intending to use here.

Title: string cannot start a parameter declaration

Body:
Neither iostream.h nor string.h exist in C++*, and the type is called std::string.

You seem to be learning from an extremely old resource (outdating what we actually call C++ since 1998).

#include <string>

bool isRotated(std::string str1, std::string str2)
{
}

* Pedants will note that string.h is included for compatibility with C, but is better known as cstring and is regardless not at all the same header that you are intending to use here.


问:
How do I upload to cdnjs?
How do I upload to cdnjs? I have no clue and no experience with git.

I have a file that I want to upload to cdnjs. Do I have to download something.
Can someone walk me through what I have to do?

答:
You can't just "upload" a single file to cdnjs.

Read CDNJS contributing document, in particular, for library even to be considered:

[...] please make sure it's not a personal project, we have a basic requirement for the popularity, like 100 stars on GitHub or 500 downloads/month on npm registry.

The new library must have at least one officially public accessable repository and open source license.

When you have that covered, you can create a pull request for your library to be included in cdnjs's master GitHub repo.

Title: How do I upload to cdnjs?


问:
MyFirstApp tutorial Android Studio 2.3 Build Errors re EXTRA_MESSAGE and textview
MyFirstApp tutorial Android Studio Issue with receiving messages within the app.

Build Errors are as follows:

Error:(17, 60) error: cannot find symbol variable EXTRA_MESSAGE

  Error:(20, 57) error: cannot find symbol variable textView

My code for the message receiver looks like this:

```<code>    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);

    // Get the Intent that started this activity and extract the
       string
    Intent intent = getIntent();
    String message =
      intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    // Capture the layout's TextView and set the string as its text
    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setText(message);
}
</code>```

Note:  EXTRA_MESSAGE and textview are in RED.

The sending code looks like this:

```<code>    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    /** Called when the user taps the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this,
             DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
    }
}
</code>```

Note: In this line in my code from above:

```<code>public void sendMessage(View view)
</code>```

The first "View" has a light horizontal line through it and I get an error message something like sendMessage(View view) is depreciated.

I think the problem may relate to the

```<code>public void sendMessage(View view)
</code>```

and its depreciated code message...   (?)

Links to the tutorial where the problem arises:

https://developer.android.com/training/basics/firstapp/starting-activity.html

答:
check this line on your MainActivity.java file, in your code is missing. </p>

```<code>public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
</code>```

Body:
MyFirstApp tutorial Android Studio Issue with receiving messages within the app.

Build Errors are as follows:

Error:(17, 60) error: cannot find symbol variable EXTRA_MESSAGE

  Error:(20, 57) error: cannot find symbol variable textView

My code for the message receiver looks like this:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);

    // Get the Intent that started this activity and extract the
       string
    Intent intent = getIntent();
    String message =
      intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    // Capture the layout's TextView and set the string as its text
    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setText(message);
}

Note:  EXTRA_MESSAGE and textview are in RED.

The sending code looks like this:

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    /** Called when the user taps the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this,
             DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
    }
}

Note: In this line in my code from above:

public void sendMessage(View view)

The first "View" has a light horizontal line through it and I get an error message something like sendMessage(View view) is depreciated.

I think the problem may relate to the

public void sendMessage(View view)

and its depreciated code message...   (?)

Links to the tutorial where the problem arises:

https://developer.android.com/training/basics/firstapp/starting-activity.html

Body:
check this line on your MainActivity.java file, in your code is missing.

public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";


问:
Android ImageView onclicklistenener not working
I am new to android and I tried to implement onclicklistener on image view. But it's not working.. Please help. When I click on the image it dose not responds.

```<code>import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        ImageView ad = (ImageView) findViewById(R.id.imageView1);
        ad.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            startActivity(new Intent(MainActivity.this, ads.class));
            }
        });

        return true;

    }

}
</code>```

this is my code...

答:
When I had a similar issue, I got it fixed it by adding android:layout_width="44dp" to make sure user would have enough area to click on. Then, you can align image content the way you wannt. In my case:

```<code>    <ImageView
    android:id="@+id/locationImageView"
    android:layout_width="44dp"
    android:layout_height="16dp"
    android:layout_centerVertical="true"
    android:layout_marginStart="4dp"
    android:layout_toEndOf="@id/locationText"
    android:adjustViewBounds="true"
    android:scaleType="fitStart"
    android:src="@drawable/icn_edit_small_white"/>
</code>```

Body:
I am new to android and I tried to implement onclicklistener on image view. But it's not working.. Please help. When I click on the image it dose not responds.

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        ImageView ad = (ImageView) findViewById(R.id.imageView1);
        ad.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            startActivity(new Intent(MainActivity.this, ads.class));
            }
        });

        return true;

    }

}

this is my code...

Body:
When I had a similar issue, I got it fixed it by adding android:layout_width="44dp" to make sure user would have enough area to click on. Then, you can align image content the way you wannt. In my case:

    <ImageView
    android:id="@+id/locationImageView"
    android:layout_width="44dp"
    android:layout_height="16dp"
    android:layout_centerVertical="true"
    android:layout_marginStart="4dp"
    android:layout_toEndOf="@id/locationText"
    android:adjustViewBounds="true"
    android:scaleType="fitStart"
    android:src="@drawable/icn_edit_small_white"/>


问:
Creating foreign key requires ENGINE keyword to be included in MySQL statement
My server data .. Ubuntu - NGINX - MySQL

I need to create a table in wordpress database with a foreign key with wp_posts table .. but I noticed that to create a foreign key in the new table I must include ENGINE keyword into create table statement, I don't know why but creating foreign key failed when ENGINE keyword not included.

Of course I need this statement to be programmatically for my clients so I cannot include ENGINE='USER DB ENGINE' .. So Is there anyway to use the default database engine?

P.S. I should include ENGINE keyword.

答:
MySQL supports foreign keys only for specific database engines. The two most commonly used and present in an installation are:

MyISAM

InnoDB

InnoDB supports foreign key constraints, MyISAM does not. It is somewhere on the to do list to implement foreign key constraints in MyISAM, however nobody got to that in the last 15 years (plus/minus a few).


问:
Structure for "dynamic" objects in a simulation
I want to create a more or less simple gravity simulation and I'm currently making some decisions about the structure. I've come across one problem, which I don't know how to solve "nicely". Here is a simple class diagram of the problem:

On a first look you probably can't see any problem, but let me tell you one additional fact: if a Star reaches a certain density (Schwarzschildradius > Radius), it should form a BlackHole. So how can I tell the Simulation to swap the Star instance with a BlackHole one? I could add a Simulation instance to each body, where they themselves can then modify the bodies array, but there has to be a better way!

Another approach could be, to instead let Planet, Star and BlackHole be subclasses of a new class BodyType, of which Body would then hold an instance.

What do you think? How would you solve this in a nice and clean way? Any help is appreciated!

Edit: for further clarification, here is an illustration of both methods I mentioned. Which one of the two is better? Or is there a better one I didn't mention?

答:
Perhaps this may help; one common method to changing behavior at runtime is the strategy pattern; the idea is to keep things common to all body types in the Body class and separate out different behaviour into different strategies, this way the strategy can be swapped whenever the body changes type.  Rather than have BlackHole, Planet and Star extend Body they can implement an interface, say BodyBehavior;

```<code>public interface BodyBehaviour {
    String getType ();
    Double getLuminosity (Body body);
    // anything else you need that's type specific....
}

public class PlanetBodyBehavior implements BodyBehaviour {
    public static final String TYPE = "Planet"
    @Override
    public String getType() {
        return TYPE;
    }

    @Override
    public Double getLuminosity(Body body) {
        // planet specific luminosity calculation - probably 0
        return calculatedLuminosity;
    }
}
</code>```

And your body class would look something like;

```<code>public class Body {
    private Double mass;

    // coordinates,radius and other state variables

    private BodyBehavior bodyBehaviour;

    public void setBodyBehaviour (BodyBehaviour behaviour) {
        this.bodyBehaviour = behaviour;
    }

    public String getBodyType () {
        bodyBehaviour.getType();
    }

    public Double getLuminosity () {
        bodyBehavior.getLuminosity(this);
    }
}
</code>```

And for your simulation you could have something along the lines of;

```<code>// init - note we keep our behaviors stateless so we only need one instance of each
public class Simulation () {
    BodyBehaviour planetBehavior = new PlanetBodyBehavior();
    BodyBehaviour starBehavior = new StarBodyBehavior()
    BodyBehaviour blackHoleBehavior = new BlackHoleBodyBehavior()
    // Just showing initialisation for a single star...
    Body body = new Body(initilising params....)
    body.setBehaviour (starBehavior);

        // iterations....
    while (!finished) {
        // assume we have many bodies and loop over them
        for (Body body : allBodies) {
            // update body positions etc.
            // check it's still a star - don't want to be changing it every iteration...
            if (body.hasBecomeBlackHole() {
                // and this is the point of it all....
                body.setBodyBehaviour(blackHoleBehavior);
            }
        }
    }
}
</code>```

Happy simulating!

Note in this case it's the top level simulation loop that invokes the behavior change but you could add this to your BodyBehavior;

```<code>boolean hasBecomeBlackHole (Body body);
</code>```

and in body you could do something like

```<code>public boolean hasBecomeBlackHole () {
    bodyBehaviour.hasBecomeBlackHole(this);
}
</code>```

For StarBodyBehavior;

```<code>public boolean hasBecomeBlackHole (final Body body) {
    return doSomeCalculations(body.getMass(), body.getRadius());
}
</code>```

And for planets and blackholes

```<code>public boolean hasBecomeBlackHole (final Body body) {
    return false;
}
</code>```

Body:
Perhaps this may help; one common method to changing behavior at runtime is the strategy pattern; the idea is to keep things common to all body types in the Body class and separate out different behaviour into different strategies, this way the strategy can be swapped whenever the body changes type.  Rather than have BlackHole, Planet and Star extend Body they can implement an interface, say BodyBehavior;

public interface BodyBehaviour {
    String getType ();
    Double getLuminosity (Body body);
    // anything else you need that's type specific....
}

public class PlanetBodyBehavior implements BodyBehaviour {
    public static final String TYPE = "Planet"
    @Override
    public String getType() {
        return TYPE;
    }

    @Override
    public Double getLuminosity(Body body) {
        // planet specific luminosity calculation - probably 0
        return calculatedLuminosity;
    }
}

And your body class would look something like;

public class Body {
    private Double mass;

    // coordinates,radius and other state variables

    private BodyBehavior bodyBehaviour;

    public void setBodyBehaviour (BodyBehaviour behaviour) {
        this.bodyBehaviour = behaviour;
    }

    public String getBodyType () {
        bodyBehaviour.getType();
    }

    public Double getLuminosity () {
        bodyBehavior.getLuminosity(this);
    }
}

And for your simulation you could have something along the lines of;

// init - note we keep our behaviors stateless so we only need one instance of each
public class Simulation () {
    BodyBehaviour planetBehavior = new PlanetBodyBehavior();
    BodyBehaviour starBehavior = new StarBodyBehavior()
    BodyBehaviour blackHoleBehavior = new BlackHoleBodyBehavior()
    // Just showing initialisation for a single star...
    Body body = new Body(initilising params....)
    body.setBehaviour (starBehavior);

        // iterations....
    while (!finished) {
        // assume we have many bodies and loop over them
        for (Body body : allBodies) {
            // update body positions etc.
            // check it's still a star - don't want to be changing it every iteration...
            if (body.hasBecomeBlackHole() {
                // and this is the point of it all....
                body.setBodyBehaviour(blackHoleBehavior);
            }
        }
    }
}

Happy simulating!

Note in this case it's the top level simulation loop that invokes the behavior change but you could add this to your BodyBehavior;

boolean hasBecomeBlackHole (Body body);

and in body you could do something like

public boolean hasBecomeBlackHole () {
    bodyBehaviour.hasBecomeBlackHole(this);
}

For StarBodyBehavior;

public boolean hasBecomeBlackHole (final Body body) {
    return doSomeCalculations(body.getMass(), body.getRadius());
}

And for planets and blackholes

public boolean hasBecomeBlackHole (final Body body) {
    return false;
}


问:
c# extract mp3 file from mp4 file
is there any easy way of extracting a mp3 file from a mp4 file?

I've already tried to change the file extension, but that won't let me to edit the mp3 description.

thank you!

答:
using FFMPEG you could do something like this:

```<code>using System;
using System.Diagnostics;

namespace ConvertMP4ToMP3
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var inputFile = args[0] + ".mp4";
            var outputFile = args[1] + ".mp3";
            var mp3out = "";
            var ffmpegProcess = new Process();
            ffmpegProcess.StartInfo.UseShellExecute = false;
            ffmpegProcess.StartInfo.RedirectStandardInput = true;
            ffmpegProcess.StartInfo.RedirectStandardOutput = true;
            ffmpegProcess.StartInfo.RedirectStandardError = true;
            ffmpegProcess.StartInfo.CreateNoWindow = true;
            ffmpegProcess.StartInfo.FileName = "//path/to/ffmpeg";
            ffmpegProcess.StartInfo.Arguments = " -i " + inputFile + " -vn -f mp3 -ab 320k output " + outputFile;
            ffmpegProcess.Start();
            ffmpegProcess.StandardOutput.ReadToEnd();
            mp3out = ffmpegProcess.StandardError.ReadToEnd();
            ffmpegProcess.WaitForExit();
            if (!ffmpegProcess.HasExited)
            {
                ffmpegProcess.Kill();
            }
            Console.WriteLine(mp3out);
        }
    }
}
</code>```

Perhaps? Here your would call the .exe from the command line with the path to the input and output files minus the extensions, a la:

C:\>ConvertMP3ToMP4.exe C:\Videos\Aqua\BarbieGirl C:\Music\Aqua\BarbiGirl

You will, of course, need to provide the full path to the FFMPEG executable on line 19. A small caveat here, I just back of the enveloped this so the code may have problems, I did not compile or test it, this is just a starting point. Good luck.

Title: c# extract mp3 file from mp4 file

Body:
using FFMPEG you could do something like this:

using System;
using System.Diagnostics;

namespace ConvertMP4ToMP3
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var inputFile = args[0] + ".mp4";
            var outputFile = args[1] + ".mp3";
            var mp3out = "";
            var ffmpegProcess = new Process();
            ffmpegProcess.StartInfo.UseShellExecute = false;
            ffmpegProcess.StartInfo.RedirectStandardInput = true;
            ffmpegProcess.StartInfo.RedirectStandardOutput = true;
            ffmpegProcess.StartInfo.RedirectStandardError = true;
            ffmpegProcess.StartInfo.CreateNoWindow = true;
            ffmpegProcess.StartInfo.FileName = "//path/to/ffmpeg";
            ffmpegProcess.StartInfo.Arguments = " -i " + inputFile + " -vn -f mp3 -ab 320k output " + outputFile;
            ffmpegProcess.Start();
            ffmpegProcess.StandardOutput.ReadToEnd();
            mp3out = ffmpegProcess.StandardError.ReadToEnd();
            ffmpegProcess.WaitForExit();
            if (!ffmpegProcess.HasExited)
            {
                ffmpegProcess.Kill();
            }
            Console.WriteLine(mp3out);
        }
    }
}

Perhaps? Here your would call the .exe from the command line with the path to the input and output files minus the extensions, a la:

C:\>ConvertMP3ToMP4.exe C:\Videos\Aqua\BarbieGirl C:\Music\Aqua\BarbiGirl

You will, of course, need to provide the full path to the FFMPEG executable on line 19. A small caveat here, I just back of the enveloped this so the code may have problems, I did not compile or test it, this is just a starting point. Good luck.


问:
Python Pandas Groupby and Aggregation
Hi I am trying to aggregate some data in a dataframe by using agg but my initial statement mentioned a warning "FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version".  I rewrote it based on Pandas documentation but instead of getting the right column label I am getting a function label. example: "". How can I correct the output so that the labels match the deprecated output above with column names std, mean, size, sum?

Deprecated Syntax Command:

```<code>Top15.set_index('Continent').groupby(level=0)['Pop Est']
      .agg({'size': np.size, 'sum': np.sum, 'mean': np.mean, 'std': np.std})
</code>```

Deprecated Syntax Output:

```<code>                        std          mean  size           sum
Continent
Asia           6.790979e+08  5.797333e+08   5.0  2.898666e+09
Australia               NaN  2.331602e+07   1.0  2.331602e+07
Europe         3.464767e+07  7.632161e+07   6.0  4.579297e+08
North America  1.996696e+08  1.764276e+08   2.0  3.528552e+08
South America           NaN  2.059153e+08   1.0  2.059153e+08
</code>```

New Syntax Command:

```<code>Top15.set_index('Continent').groupby(level=0)['Pop Est']\
    .agg(['size', 'sum', 'mean', 'std'])\
    .rename(columns={'size': np.size, 'sum': np.sum, 'mean': np.mean, 'std': np.std})
</code>```

New Syntax Output:

```<code>               <function size at 0x0000000002DE9950>  <function sum at 0x0000000002DE90D0>  <function mean at 0x0000000002DE9AE8>  <function std at 0x0000000002DE9B70>
Continent
Asia                                               5                          2.898666e+09                           5.797333e+08                          6.790979e+08
Australia                                          1                          2.331602e+07                           2.331602e+07                                   NaN
Europe                                             6                          4.579297e+08                           7.632161e+07                          3.464767e+07
North America                                      2                          3.528552e+08                           1.764276e+08                          1.996696e+08
South America                                      1                          2.059153e+08                           2.059153e+08                                   NaN
</code>```

Dataframe:

```<code>                    Rank  Documents  Citable documents  Citations  Self-citations  Citations per document  H index  Energy Supply  Energy Supply per Capita  % Renewable          2006          2007          2008          2009          2010          2011          2012          2013          2014          2015       Pop Est      Continent
Country
China                  1     127050             126767     597237          411683                    4.70      138   1.271910e+11                      93.0    19.754910  3.992331e+12  4.559041e+12  4.997775e+12  5.459247e+12  6.039659e+12  6.612490e+12  7.124978e+12  7.672448e+12  8.230121e+12  8.797999e+12  1.367645e+09           Asia
United States          2      96661              94747     792274          265436                    8.20      230   9.083800e+10                     286.0    11.570980  1.479230e+13  1.505540e+13  1.501149e+13  1.459484e+13  1.496437e+13  1.520402e+13  1.554216e+13  1.577367e+13  1.615662e+13  1.654857e+13  3.176154e+08  North America
Japan                  3      30504              30287     223024           61554                    7.31      134   1.898400e+10                     149.0    10.232820  5.496542e+12  5.617036e+12  5.558527e+12  5.251308e+12  5.498718e+12  5.473738e+12  5.569102e+12  5.644659e+12  5.642884e+12  5.669563e+12  1.274094e+08           Asia
United Kingdom         4      20944              20357     206091           37874                    9.84      139   7.920000e+09                     124.0    10.600470  2.419631e+12  2.482203e+12  2.470614e+12  2.367048e+12  2.403504e+12  2.450911e+12  2.479809e+12  2.533370e+12  2.605643e+12  2.666333e+12  6.387097e+07         Europe
Russian Federation     5      18534              18301      34266           12422                    1.85       57   3.070900e+10                     214.0    17.288680  1.385793e+12  1.504071e+12  1.583004e+12  1.459199e+12  1.524917e+12  1.589943e+12  1.645876e+12  1.666934e+12  1.678709e+12  1.616149e+12  1.435000e+08         Europe
Canada                 6      17899              17620     215003           40930                   12.01      149   1.043100e+10                     296.0    61.945430  1.564469e+12  1.596740e+12  1.612713e+12  1.565145e+12  1.613406e+12  1.664087e+12  1.693133e+12  1.730688e+12  1.773486e+12  1.792609e+12  3.523986e+07  North America
Germany                7      17027              16831     140566           27426                    8.26      126   1.326100e+10                     165.0    17.901530  3.332891e+12  3.441561e+12  3.478809e+12  3.283340e+12  3.417298e+12  3.542371e+12  3.556724e+12  3.567317e+12  3.624386e+12  3.685556e+12  8.036970e+07         Europe
India                  8      15005              14841     128763           37209                    8.58      115   3.319500e+10                      26.0    14.969080  1.265894e+12  1.374865e+12  1.428361e+12  1.549483e+12  1.708459e+12  1.821872e+12  1.924235e+12  2.051982e+12  2.200617e+12  2.367206e+12  1.276731e+09           Asia
France                 9      13153              12973     130632           28601                    9.93      114   1.059700e+10                     166.0    17.020280  2.607840e+12  2.669424e+12  2.674637e+12  2.595967e+12  2.646995e+12  2.702032e+12  2.706968e+12  2.722567e+12  2.729632e+12  2.761185e+12  6.383735e+07         Europe
South Korea           10      11983              11923     114675           22595                    9.57      104   1.100700e+10                     221.0     2.279353  9.410199e+11  9.924316e+11  1.020510e+12  1.027730e+12  1.094499e+12  1.134796e+12  1.160809e+12  1.194429e+12  1.234340e+12  1.266580e+12  4.980543e+07           Asia
Italy                 11      10964              10794     111850           26661                   10.20      106   6.530000e+09                     109.0    33.667230  2.202170e+12  2.234627e+12  2.211154e+12  2.089938e+12  2.125185e+12  2.137439e+12  2.077184e+12  2.040871e+12  2.033868e+12  2.049316e+12  5.990826e+07         Europe
Spain                 12       9428               9330     123336           23964                   13.08      115   4.923000e+09                     106.0    37.968590  1.414823e+12  1.468146e+12  1.484530e+12  1.431475e+12  1.431673e+12  1.417355e+12  1.380216e+12  1.357139e+12  1.375605e+12  1.419821e+12  4.644340e+07         Europe
Iran                  13       8896               8819      57470           19125                    6.46       72   9.172000e+09                     119.0     5.707721  3.895523e+11  4.250646e+11  4.289909e+11  4.389208e+11  4.677902e+11  4.853309e+11  4.532569e+11  4.445926e+11  4.639027e+11           NaN  7.707563e+07           Asia
Australia             14       8831               8725      90765           15606                   10.28      107   5.386000e+09                     231.0    11.810810  1.021939e+12  1.060340e+12  1.099644e+12  1.119654e+12  1.142251e+12  1.169431e+12  1.211913e+12  1.241484e+12  1.272520e+12  1.301251e+12  2.331602e+07      Australia
Brazil                15       8668               8596      60702           14396                    7.00       86   1.214900e+10                      59.0    69.648030  1.845080e+12  1.957118e+12  2.056809e+12  2.054215e+12  2.208872e+12  2.295245e+12  2.339209e+12  2.409740e+12  2.412231e+12  2.319423e+12  2.059153e+08  South America
</code>```

答:
Try using just this:</p>

```<code>Top15.set_index('Continent').groupby(level=0)['Pop Est'].agg(['size', 'sum', 'mean', 'std'])
</code>```

Title: Python Pandas Groupby and Aggregation

Body:
Hi I am trying to aggregate some data in a dataframe by using agg but my initial statement mentioned a warning "FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version".  I rewrote it based on Pandas documentation but instead of getting the right column label I am getting a function label. example: "". How can I correct the output so that the labels match the deprecated output above with column names std, mean, size, sum?

Deprecated Syntax Command:

Top15.set_index('Continent').groupby(level=0)['Pop Est']
      .agg({'size': np.size, 'sum': np.sum, 'mean': np.mean, 'std': np.std})

Deprecated Syntax Output:

                        std          mean  size           sum
Continent
Asia           6.790979e+08  5.797333e+08   5.0  2.898666e+09
Australia               NaN  2.331602e+07   1.0  2.331602e+07
Europe         3.464767e+07  7.632161e+07   6.0  4.579297e+08
North America  1.996696e+08  1.764276e+08   2.0  3.528552e+08
South America           NaN  2.059153e+08   1.0  2.059153e+08

New Syntax Command:

Top15.set_index('Continent').groupby(level=0)['Pop Est']\
    .agg(['size', 'sum', 'mean', 'std'])\
    .rename(columns={'size': np.size, 'sum': np.sum, 'mean': np.mean, 'std': np.std})

New Syntax Output:

               <function size at 0x0000000002DE9950>  <function sum at 0x0000000002DE90D0>  <function mean at 0x0000000002DE9AE8>  <function std at 0x0000000002DE9B70>
Continent
Asia                                               5                          2.898666e+09                           5.797333e+08                          6.790979e+08
Australia                                          1                          2.331602e+07                           2.331602e+07                                   NaN
Europe                                             6                          4.579297e+08                           7.632161e+07                          3.464767e+07
North America                                      2                          3.528552e+08                           1.764276e+08                          1.996696e+08
South America                                      1                          2.059153e+08                           2.059153e+08                                   NaN

Dataframe:

                    Rank  Documents  Citable documents  Citations  Self-citations  Citations per document  H index  Energy Supply  Energy Supply per Capita  % Renewable          2006          2007          2008          2009          2010          2011          2012          2013          2014          2015       Pop Est      Continent
Country
China                  1     127050             126767     597237          411683                    4.70      138   1.271910e+11                      93.0    19.754910  3.992331e+12  4.559041e+12  4.997775e+12  5.459247e+12  6.039659e+12  6.612490e+12  7.124978e+12  7.672448e+12  8.230121e+12  8.797999e+12  1.367645e+09           Asia
United States          2      96661              94747     792274          265436                    8.20      230   9.083800e+10                     286.0    11.570980  1.479230e+13  1.505540e+13  1.501149e+13  1.459484e+13  1.496437e+13  1.520402e+13  1.554216e+13  1.577367e+13  1.615662e+13  1.654857e+13  3.176154e+08  North America
Japan                  3      30504              30287     223024           61554                    7.31      134   1.898400e+10                     149.0    10.232820  5.496542e+12  5.617036e+12  5.558527e+12  5.251308e+12  5.498718e+12  5.473738e+12  5.569102e+12  5.644659e+12  5.642884e+12  5.669563e+12  1.274094e+08           Asia
United Kingdom         4      20944              20357     206091           37874                    9.84      139   7.920000e+09                     124.0    10.600470  2.419631e+12  2.482203e+12  2.470614e+12  2.367048e+12  2.403504e+12  2.450911e+12  2.479809e+12  2.533370e+12  2.605643e+12  2.666333e+12  6.387097e+07         Europe
Russian Federation     5      18534              18301      34266           12422                    1.85       57   3.070900e+10                     214.0    17.288680  1.385793e+12  1.504071e+12  1.583004e+12  1.459199e+12  1.524917e+12  1.589943e+12  1.645876e+12  1.666934e+12  1.678709e+12  1.616149e+12  1.435000e+08         Europe
Canada                 6      17899              17620     215003           40930                   12.01      149   1.043100e+10                     296.0    61.945430  1.564469e+12  1.596740e+12  1.612713e+12  1.565145e+12  1.613406e+12  1.664087e+12  1.693133e+12  1.730688e+12  1.773486e+12  1.792609e+12  3.523986e+07  North America
Germany                7      17027              16831     140566           27426                    8.26      126   1.326100e+10                     165.0    17.901530  3.332891e+12  3.441561e+12  3.478809e+12  3.283340e+12  3.417298e+12  3.542371e+12  3.556724e+12  3.567317e+12  3.624386e+12  3.685556e+12  8.036970e+07         Europe
India                  8      15005              14841     128763           37209                    8.58      115   3.319500e+10                      26.0    14.969080  1.265894e+12  1.374865e+12  1.428361e+12  1.549483e+12  1.708459e+12  1.821872e+12  1.924235e+12  2.051982e+12  2.200617e+12  2.367206e+12  1.276731e+09           Asia
France                 9      13153              12973     130632           28601                    9.93      114   1.059700e+10                     166.0    17.020280  2.607840e+12  2.669424e+12  2.674637e+12  2.595967e+12  2.646995e+12  2.702032e+12  2.706968e+12  2.722567e+12  2.729632e+12  2.761185e+12  6.383735e+07         Europe
South Korea           10      11983              11923     114675           22595                    9.57      104   1.100700e+10                     221.0     2.279353  9.410199e+11  9.924316e+11  1.020510e+12  1.027730e+12  1.094499e+12  1.134796e+12  1.160809e+12  1.194429e+12  1.234340e+12  1.266580e+12  4.980543e+07           Asia
Italy                 11      10964              10794     111850           26661                   10.20      106   6.530000e+09                     109.0    33.667230  2.202170e+12  2.234627e+12  2.211154e+12  2.089938e+12  2.125185e+12  2.137439e+12  2.077184e+12  2.040871e+12  2.033868e+12  2.049316e+12  5.990826e+07         Europe
Spain                 12       9428               9330     123336           23964                   13.08      115   4.923000e+09                     106.0    37.968590  1.414823e+12  1.468146e+12  1.484530e+12  1.431475e+12  1.431673e+12  1.417355e+12  1.380216e+12  1.357139e+12  1.375605e+12  1.419821e+12  4.644340e+07         Europe
Iran                  13       8896               8819      57470           19125                    6.46       72   9.172000e+09                     119.0     5.707721  3.895523e+11  4.250646e+11  4.289909e+11  4.389208e+11  4.677902e+11  4.853309e+11  4.532569e+11  4.445926e+11  4.639027e+11           NaN  7.707563e+07           Asia
Australia             14       8831               8725      90765           15606                   10.28      107   5.386000e+09                     231.0    11.810810  1.021939e+12  1.060340e+12  1.099644e+12  1.119654e+12  1.142251e+12  1.169431e+12  1.211913e+12  1.241484e+12  1.272520e+12  1.301251e+12  2.331602e+07      Australia
Brazil                15       8668               8596      60702           14396                    7.00       86   1.214900e+10                      59.0    69.648030  1.845080e+12  1.957118e+12  2.056809e+12  2.054215e+12  2.208872e+12  2.295245e+12  2.339209e+12  2.409740e+12  2.412231e+12  2.319423e+12  2.059153e+08  South America

Body:
Try using just this:

Top15.set_index('Continent').groupby(level=0)['Pop Est'].agg(['size', 'sum', 'mean', 'std'])


问:
Run multiple tasks with the same command?
I want to chain up some commands / tasks I defined in tasks.json.

I have many different sub-projects (C# csproj files) that should be built, then tested (shell commands) in a big single task.

I have this tasks.json working, but I can only invoke the different commands one by one.

答:
Update

After getting further clarification, what you are trying to accomplish can be configured as post build steps in Visual Studio. Configure the commands for the last project that will build.

Original Answer

You can execute your tasks in parallel:

```<code>public class TaskCollection
{
    public string version { get; set; }
    public List<Task> tasks { get; set; }
    public static void RunTasks()
    {
        string json = new WebClient().DownloadString("https://gist.githubusercontent.com/eppz/f941f2e85e12e7cc81c63ee2ac1354e5/raw/fa15f7b9774083f481504677b96353fe0da777be/tasks.json");
        TaskCollection col = new JavaScriptSerializer().Deserialize<TaskCollection>(json);
        Parallel.ForEach(col.tasks, (x) =>
        {
            ExecuteTask(x);
        }
        );
    }

    private static void ExecuteTask(Task x)
    {
        //Do something
    }
}

public class Task
{
    public string taskName { get; set; }
    public bool isBuildCommand { get; set; }
    public string command { get; set; }
    public string[] args { get; set; }
    public string showOutput { get; set; }
    public string problemMatcher { get; set; }
    public bool isShellCommand { get; set; }
    public bool isTestCommand { get; set; }
}
</code>```

Body:
Update

After getting further clarification, what you are trying to accomplish can be configured as post build steps in Visual Studio. Configure the commands for the last project that will build.

Original Answer

You can execute your tasks in parallel:

public class TaskCollection
{
    public string version { get; set; }
    public List<Task> tasks { get; set; }
    public static void RunTasks()
    {
        string json = new WebClient().DownloadString("https://gist.githubusercontent.com/eppz/f941f2e85e12e7cc81c63ee2ac1354e5/raw/fa15f7b9774083f481504677b96353fe0da777be/tasks.json");
        TaskCollection col = new JavaScriptSerializer().Deserialize<TaskCollection>(json);
        Parallel.ForEach(col.tasks, (x) =>
        {
            ExecuteTask(x);
        }
        );
    }

    private static void ExecuteTask(Task x)
    {
        //Do something
    }
}

public class Task
{
    public string taskName { get; set; }
    public bool isBuildCommand { get; set; }
    public string command { get; set; }
    public string[] args { get; set; }
    public string showOutput { get; set; }
    public string problemMatcher { get; set; }
    public bool isShellCommand { get; set; }
    public bool isTestCommand { get; set; }
}


问:
GraphQL: Query.type field type must be Output Type but got: undefined
I'm trying my first GraphQL approach. Here is the code:

schema.js:

```<code>import {
    GraphQLSchema,
    GraphQLObjectType,
    GraphQLInputObjectType,
    GraphQLNonNull,
    GraphQLString,
    GraphQLBoolean,
    GraphQLInt,
    GraphQLID,
    GraphQLList
} from 'graphql';

import Company from '../../models/Company';

const CompanyType = new GraphQLObjectType({
    name: 'Company',
    description: 'Company',
    fields: {
        _id: {
            type: new GraphQLNonNull(GraphQLID)
        },
        name: {
            type: GraphQLString
        }
    }
})

const Companies = {
    type: CompanyType,
    args: {
        id: {
            name: 'ID',
            type: new GraphQLNonNull(GraphQLID)
        }
    },
    resolve(root, params) {
        return Company.find(params.id).exec();
    }
}

export default new GraphQLSchema({

    query: new GraphQLObjectType({
        name: 'Query',
        fields: Companies
    })
});
</code>```

Then on my server.js:

```<code>import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import morgan from 'morgan';
import graphqlHTTP from 'express-graphql';

import schema from './schema';

mongoose.Promise = global.Promise;

// set up example server
const app = express();
app.set('port', (process.env.API_PORT || 3001));

 // logger
 app.use(morgan('dev'));

// parse body
app.use(bodyParser.json());

// redirect all requests to /graphql
app.use(function redirect(req, res) {
  res.redirect('/graphql');
});

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphqli: true,
  pretty: true
}));
</code>```

I'm getting the following errror:

```<code>D:\test\node_modules\graphql\jsutils\invariant.js:19
    throw new Error(message);
    ^

Error: Query.type field type must be Output Type but got: undefined.
    at invariant (D:\test\node_modules\graphql\jsutils\invariant.js:19:11)
    at D:\test\node_modules\graphql\type\definition.js:361:29
    at Array.forEach (native)
    at defineFieldMap (D:\test\node_modules\graphql\type\definition.js:352:14)
    at GraphQLObjectType.getFields (D:\test\node_modules\graphql\type\definition.js:306:44)
    at typeMapReducer (D:\test\node_modules\graphql\type\schema.js:206:25)
    at Array.reduce (native)
    at new GraphQLSchema (D:\test\node_modules\graphql\type\schema.js:95:34)
    at Object.<anonymous> (D:/9. DEV/WORKSPACE/mom/client/graphql/index.js:62:16)
    at Module._compile (module.js:570:32)
    at loader (D:\test\node_modules\babel-register\lib\node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (D:\test\node_modules\babel-register\lib\node.js:154:7)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
</code>```

答:
Inside your Query type definition, you wrote:

```<code>fields: Companies
</code>```

It should be

```<code>fields: { Companies }
</code>```

Looking at the docs, fields takes an object or a function returning an object, with that object's keys mapping to the names of all the fields in the type (all the queries in your schema in this case).

Also, for clarity, since queries and mutations are fields of their respective types, it may be better to name them in camelCase rather than PascalCase (i.e. { companies: Companies }

Body:
I'm trying my first GraphQL approach. Here is the code:

schema.js:

import {
    GraphQLSchema,
    GraphQLObjectType,
    GraphQLInputObjectType,
    GraphQLNonNull,
    GraphQLString,
    GraphQLBoolean,
    GraphQLInt,
    GraphQLID,
    GraphQLList
} from 'graphql';

import Company from '../../models/Company';

const CompanyType = new GraphQLObjectType({
    name: 'Company',
    description: 'Company',
    fields: {
        _id: {
            type: new GraphQLNonNull(GraphQLID)
        },
        name: {
            type: GraphQLString
        }
    }
})

const Companies = {
    type: CompanyType,
    args: {
        id: {
            name: 'ID',
            type: new GraphQLNonNull(GraphQLID)
        }
    },
    resolve(root, params) {
        return Company.find(params.id).exec();
    }
}

export default new GraphQLSchema({

    query: new GraphQLObjectType({
        name: 'Query',
        fields: Companies
    })
});

Then on my server.js:

import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import morgan from 'morgan';
import graphqlHTTP from 'express-graphql';

import schema from './schema';

mongoose.Promise = global.Promise;

// set up example server
const app = express();
app.set('port', (process.env.API_PORT || 3001));

 // logger
 app.use(morgan('dev'));

// parse body
app.use(bodyParser.json());

// redirect all requests to /graphql
app.use(function redirect(req, res) {
  res.redirect('/graphql');
});

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphqli: true,
  pretty: true
}));

I'm getting the following errror:

D:\test\node_modules\graphql\jsutils\invariant.js:19
    throw new Error(message);
    ^

Error: Query.type field type must be Output Type but got: undefined.
    at invariant (D:\test\node_modules\graphql\jsutils\invariant.js:19:11)
    at D:\test\node_modules\graphql\type\definition.js:361:29
    at Array.forEach (native)
    at defineFieldMap (D:\test\node_modules\graphql\type\definition.js:352:14)
    at GraphQLObjectType.getFields (D:\test\node_modules\graphql\type\definition.js:306:44)
    at typeMapReducer (D:\test\node_modules\graphql\type\schema.js:206:25)
    at Array.reduce (native)
    at new GraphQLSchema (D:\test\node_modules\graphql\type\schema.js:95:34)
    at Object.<anonymous> (D:/9. DEV/WORKSPACE/mom/client/graphql/index.js:62:16)
    at Module._compile (module.js:570:32)
    at loader (D:\test\node_modules\babel-register\lib\node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (D:\test\node_modules\babel-register\lib\node.js:154:7)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)

Body:
Inside your Query type definition, you wrote:

fields: Companies

It should be

fields: { Companies }

Looking at the docs, fields takes an object or a function returning an object, with that object's keys mapping to the names of all the fields in the type (all the queries in your schema in this case).

Also, for clarity, since queries and mutations are fields of their respective types, it may be better to name them in camelCase rather than PascalCase (i.e. { companies: Companies }