问:
Treat URL path as virtual host using Apache
The problem is that I have only one domain name on which three different products need to be run (two of them PHP based and one python). So I need to treat the path in the URL as a different virtual host; i.e.:

```<code>www.domain.com/first_URL/
www.domain.com/second_URL/
www.domain.com/third_URL/
</code>```

Where the first to third will act as separate virtual hosts.

How can I do this?

答:
This example explains how to assign a different PHP version per directory. It can also be adapted to add Python support by running the Python interpreter as fast_cgi on a particular port.

For the purpose of the example, I assume there is a separate directory for each PHP version and they are named according to the PHP version that runs them, but this can be adjusted.

```<code>mkdir /home/user/www
mkdir /home/user/www/5.6.5
mkdir /home/user/www/7.0.2
mkdir /home/user/www/7.0.4
mkdir /home/user/www/7.0.6
</code>```

Create symbolic links to directories that should be handled by different PHP versions:

```<code>sudo ln -s /home/user/www/7.0.2/ /var/www/html/7.0.2
sudo ln -s /home/user/www/7.0.4/ /var/www/html/7.0.4
sudo ln -s /home/user/www/7.0.6/ /var/www/html/7.0.6
</code>```

Then add the following lines to /etc/apache2/sites-enabled/000-default.conf in default virtual host *:80

(For your needs, you can set up one more FastCGI handler here for the website that requires Python). I assume PHP 5.6.5 runs on port 9999, 7.0.2 runs on port 9998, etc.

```<code>DirectoryIndex index.html index.php
ProxyPassMatch ^/5.6.5/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9999/var/www/html/
ProxyPassMatch ^/7.0.2/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9998/var/www/html/
ProxyPassMatch ^/7.0.4/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9997/var/www/html/
ProxyPassMatch ^/7.0.6/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9996/var/www/html/
</code>```

Assuming your server is pointed by example.com, you can test it on:

```<code>http://example.com/5.6.5/
http://example.com/7.0.2/
http://example.com/7.0.4/
http://example.com/7.0.6/
</code>```

Body:
The problem is that I have only one domain name on which three different products need to be run (two of them PHP based and one python). So I need to treat the path in the URL as a different virtual host; i.e.:

www.domain.com/first_URL/
www.domain.com/second_URL/
www.domain.com/third_URL/

Where the first to third will act as separate virtual hosts.

How can I do this?

Body:
This example explains how to assign a different PHP version per directory. It can also be adapted to add Python support by running the Python interpreter as fast_cgi on a particular port.

For the purpose of the example, I assume there is a separate directory for each PHP version and they are named according to the PHP version that runs them, but this can be adjusted.

mkdir /home/user/www
mkdir /home/user/www/5.6.5
mkdir /home/user/www/7.0.2
mkdir /home/user/www/7.0.4
mkdir /home/user/www/7.0.6

Create symbolic links to directories that should be handled by different PHP versions:

sudo ln -s /home/user/www/7.0.2/ /var/www/html/7.0.2
sudo ln -s /home/user/www/7.0.4/ /var/www/html/7.0.4
sudo ln -s /home/user/www/7.0.6/ /var/www/html/7.0.6

Then add the following lines to /etc/apache2/sites-enabled/000-default.conf in default virtual host *:80

(For your needs, you can set up one more FastCGI handler here for the website that requires Python). I assume PHP 5.6.5 runs on port 9999, 7.0.2 runs on port 9998, etc.

DirectoryIndex index.html index.php
ProxyPassMatch ^/5.6.5/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9999/var/www/html/
ProxyPassMatch ^/7.0.2/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9998/var/www/html/
ProxyPassMatch ^/7.0.4/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9997/var/www/html/
ProxyPassMatch ^/7.0.6/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9996/var/www/html/

Assuming your server is pointed by example.com, you can test it on:

http://example.com/5.6.5/
http://example.com/7.0.2/
http://example.com/7.0.4/
http://example.com/7.0.6/


来源: stackexchange

问:
Expand UILabel inside UITableView with "more" button like Instagram
I've got a project (that has been written by other people) where there's a feed with content and text displayed inside a table view. Each post corresponds to one section in table view, and each section has its own rows corresponding to elements like content, text, like button etc.

I need to display a short label for post captions with a "more" button inside table view cell, and when more button is tapped, the label will expand to whatever size the caption fits, all happening inside a table view cell. When the more button is tapped I change the label's numberOfLines property to zero, and as the cells have automatic height, all I need is to reload that particular caption cell. (the cell displays correctly with the expanded size if I set numberOfLines to 0 at the first place before displaying the cell.)

I've tried:

[tableView beginUpdates];
tableView endUpdates];

I've tried various animation options with:

[tableView reloadRowsAtIndexPaths:@[myPath] withRowAnimation:UITableViewRowAnimation(Bottom,Top,None etc)];

I've tried:

[tableView reloadSections:[NSIndexSet indexSetWithIndex:myPath.section] withRowAnimation:UITableViewRowAnimation(Top,Bottom,None etc)];

But they all yield the same result: the whole table view layout gets messed up: it jumps to another cell, some views go blank, cells overlap each other, video inside cells stop playing, and the label doesn't expand (but refreshes inside itself, e.g. that short preview txt with one line animates from top/bottom etc but doesn't expand).

What might be causing the mess up of the whole table view and how I can reload just one cell correctly with and expansion animation, without messing up the whole layout? I've seen many questions and answers regarding this, but they all recommend the options that I've already tried and explained above.

My app targets iOS 8.0+

UPDATE: Here is the relevant code (with some parts regarding inner workings that aren't related to layout, removed):

```<code>MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier: MyCellIdentifier forIndexPath:indexPath];
cell.delegate = self;
cell.indexPathToReloadOnAnimation = indexPath;
cell.shouldShortenCaption = YES;

id post = self.posts[indexPath.section] ;
[cell setPost:post];

return cell;
</code>```

And inside setPost::

```<code>if(self.shouldShortenCaption){
    captionLabel.numberOfLines = 2;
}else{
    captionLabel.numberOfLines = 0;
}
NSString *text = [some calculated (deterministic) text from post object];
</code>```

Button action is simple:

```<code>self.shouldShortenCaption = NO;
[one of the reload codes that I've written above in the question]
</code>```

UPDATE 2: Here are some more methods regarding the issue:

```<code>- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section < self.posts.count) {
        return 59;
    }else
        return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section < self.posts.count) {
        MyFeedHeader *header = [tableView dequeueReusableCellWithIdentifier:MyFeedHeaderIdentifier];
        header.delegate = self;
        [header setPostIndex:section];
        [header setPost:self.posts[section]] ;

        return header;
    }
    else
        return nil;
}
</code>```

Header's setPost: method basically sets the relevant texts to labels (which have nothing to do with the caption, they are completely different cells. the problematic cell is not the header cell). The table doesn't have any footer methods. The only method regarding height is the one above.

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section >= self.posts.count) {
        return 1;
    }
    id post = self.posts[section];
    [calculate number of rows, which is deterministic]
    return [number of rows];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    BOOL hasCursor = self.cursor && self.hasMore ? 1 : 0;
    return self.posts.count + hasCursor;
}
</code>```

(Post count and cursor and hasMore are also deterministic).

UPDATE 3: I've asked a question (which wasn't a duplicate, even though there are similar questions) and got a useful answer that solved my problem. Can the downvoters please elaborate the reason that they've downvoted?

答:
Here is an example: https://github.com/DonMag/DynamicCellHeight

Table B is one way of accomplishing "More/Less" (Table A was for another layout I played around with). It uses the [tableView beginUpdates]; tableView endUpdates]; method of triggering the table re-layout.

The key is getting all your constraints set up correctly, so the Auto-Layout engine does what you expect.

The example is in Swift, but should be really easily translated back to Obj-C (I think I did it in Obj-C first).

Edit: some additional notes...

This is using a pretty standard method of dynamic-height table view cells. The vertical spacing constraints between elements effectively "pushes out" the bounds of the cell. The tap here toggles the numberOfLines property of the label between 2 and 0 (zero meaning as many lines as necessary). Sequential calls to beginUpdates / endUpdates on the table view tells the auto-layout engine to recalculate the row heights without needing to reload the data.

For this example, I did use a little "trickery" to get the smooth expand/collapse effect... The multiline label you see here is contained in a UIView (with clipsToBounds true). There is a second, duplicate multiline label (alpha 0 so it's not visible) that is controlling the height. I found that changing the numberOfLines on the visible label sort of "snapped" to 2 lines, and then the size change animation took place... resulting in the text "jumping around."

Just for the heck of it, I added the "not so good" version to my GitHub repo for comparison's sake.

ContentLicense: CC BY-SA 3.0

Body:
I've got a project (that has been written by other people) where there's a feed with content and text displayed inside a table view. Each post corresponds to one section in table view, and each section has its own rows corresponding to elements like content, text, like button etc.

I need to display a short label for post captions with a "more" button inside table view cell, and when more button is tapped, the label will expand to whatever size the caption fits, all happening inside a table view cell. When the more button is tapped I change the label's numberOfLines property to zero, and as the cells have automatic height, all I need is to reload that particular caption cell. (the cell displays correctly with the expanded size if I set numberOfLines to 0 at the first place before displaying the cell.)

I've tried:

[tableView beginUpdates];
tableView endUpdates];

I've tried various animation options with:

[tableView reloadRowsAtIndexPaths:@[myPath] withRowAnimation:UITableViewRowAnimation(Bottom,Top,None etc)];

I've tried:

[tableView reloadSections:[NSIndexSet indexSetWithIndex:myPath.section] withRowAnimation:UITableViewRowAnimation(Top,Bottom,None etc)];

But they all yield the same result: the whole table view layout gets messed up: it jumps to another cell, some views go blank, cells overlap each other, video inside cells stop playing, and the label doesn't expand (but refreshes inside itself, e.g. that short preview txt with one line animates from top/bottom etc but doesn't expand).

What might be causing the mess up of the whole table view and how I can reload just one cell correctly with and expansion animation, without messing up the whole layout? I've seen many questions and answers regarding this, but they all recommend the options that I've already tried and explained above.

My app targets iOS 8.0+

UPDATE: Here is the relevant code (with some parts regarding inner workings that aren't related to layout, removed):

MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier: MyCellIdentifier forIndexPath:indexPath];
cell.delegate = self;
cell.indexPathToReloadOnAnimation = indexPath;
cell.shouldShortenCaption = YES;

id post = self.posts[indexPath.section] ;
[cell setPost:post];

return cell;

And inside setPost::

if(self.shouldShortenCaption){
    captionLabel.numberOfLines = 2;
}else{
    captionLabel.numberOfLines = 0;
}
NSString *text = [some calculated (deterministic) text from post object];

Button action is simple:

self.shouldShortenCaption = NO;
[one of the reload codes that I've written above in the question]

UPDATE 2: Here are some more methods regarding the issue:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section < self.posts.count) {
        return 59;
    }else
        return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section < self.posts.count) {
        MyFeedHeader *header = [tableView dequeueReusableCellWithIdentifier:MyFeedHeaderIdentifier];
        header.delegate = self;
        [header setPostIndex:section];
        [header setPost:self.posts[section]] ;

        return header;
    }
    else
        return nil;
}

Header's setPost: method basically sets the relevant texts to labels (which have nothing to do with the caption, they are completely different cells. the problematic cell is not the header cell). The table doesn't have any footer methods. The only method regarding height is the one above.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section >= self.posts.count) {
        return 1;
    }
    id post = self.posts[section];
    [calculate number of rows, which is deterministic]
    return [number of rows];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    BOOL hasCursor = self.cursor && self.hasMore ? 1 : 0;
    return self.posts.count + hasCursor;
}

(Post count and cursor and hasMore are also deterministic).

UPDATE 3: I've asked a question (which wasn't a duplicate, even though there are similar questions) and got a useful answer that solved my problem. Can the downvoters please elaborate the reason that they've downvoted?


问:
C# DateTime not correct
I have a problem with the difference in getting the time which has arisen this week, possibly due to Daylight Savings Time in the U.S. There is an hour difference in C# and Java (Android). I want the Java to behave the same as the C#.

Windows 10 - C#

```<code>value = DateTime.Now;
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
System.Diagnostics.Trace.WriteLine("span: " + (int)span.TotalSeconds);
</code>```

Unix epoch seconds:

1489764265

Which converts to:

Fri, 17 Mar 2017 15:24:25 GMT

Java - Android Studio - Run on Samsung T5330-NU

```<code>Date date = new Date(); // current date and time
Integer.toString(ConvertToTimestamp(date))
</code>```

Unit epoch seconds:

1489760686

Which converts to:

Fri, 17 Mar 2017 14:24:46 GMT

The seconds (:25 vs :46) is fine.
The hours are the problem  (15 vs 14)
Somehow daylight savings time must be involved.

What can be done?

Using this to convert Unix epoch time:

http://www.onlineconversion.com/unix_time.htm

Edit:

Original Java code gets current date/time like so:

```<code>Calendar cal = Calendar.getInstance();
</code>```

Based on the comment by @AkosNagy, I tried:

```<code>Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("MST"));
</code>```

and

```<code>Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("MDT"));
</code>```

but there is no difference.

Edit:

Changed the title because this is in the end a question about C# and why the C# is not giving the correct time.

Edit:
This is the line I was looking for:

```<code>Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
</code>```

答:
(CHECK EDIT BELOW)

In c#, DateTime.Now returns the local time of your computer so time zones don't matter, as you can see in MSDN documentation.

For java, I found these code snippets which use other methods like LocalDateTime.now().

EDIT:

after reading your answer again, I understood that your problem is with the c# code. that is my solution:
instead of that Unix epoch seconds thing:

```<code>value = DateTime.Now;
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
System.Diagnostics.Trace.WriteLine("span: " + (int)span.TotalSeconds);
</code>```

just use this:

```<code>//first, get the corrent time
DateTime date = DateTime.Now;
//print the time
Console.WriteLine(date.ToString());
// For en-US culture, for other culture type refer to MSDN link
//output mm/dd/yyyy hh:mm:ss AM/pm
</code>```

If you realy need the Unix epoch seconds, refer to this thread
also check your system clock.

Hope I helped!

EDIT: I changed the link to what you needed

Title: C# DateTime not correct

Body:
I have a problem with the difference in getting the time which has arisen this week, possibly due to Daylight Savings Time in the U.S. There is an hour difference in C# and Java (Android). I want the Java to behave the same as the C#.

Windows 10 - C#

value = DateTime.Now;
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
System.Diagnostics.Trace.WriteLine("span: " + (int)span.TotalSeconds);

Unix epoch seconds:

1489764265

Which converts to:

Fri, 17 Mar 2017 15:24:25 GMT

Java - Android Studio - Run on Samsung T5330-NU

Date date = new Date(); // current date and time
Integer.toString(ConvertToTimestamp(date))

Unit epoch seconds:

1489760686

Which converts to:

Fri, 17 Mar 2017 14:24:46 GMT

The seconds (:25 vs :46) is fine.
The hours are the problem  (15 vs 14)
Somehow daylight savings time must be involved.

What can be done?

Using this to convert Unix epoch time:

http://www.onlineconversion.com/unix_time.htm

Edit:

Original Java code gets current date/time like so:

Calendar cal = Calendar.getInstance();

Based on the comment by @AkosNagy, I tried:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("MST"));

and

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("MDT"));

but there is no difference.

Edit:

Changed the title because this is in the end a question about C# and why the C# is not giving the correct time.

Edit:
This is the line I was looking for:

Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

Body:
(CHECK EDIT BELOW)

In c#, DateTime.Now returns the local time of your computer so time zones don't matter, as you can see in MSDN documentation.

For java, I found these code snippets which use other methods like LocalDateTime.now().

EDIT:

after reading your answer again, I understood that your problem is with the c# code. that is my solution:
instead of that Unix epoch seconds thing:

value = DateTime.Now;
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
System.Diagnostics.Trace.WriteLine("span: " + (int)span.TotalSeconds);

just use this:

//first, get the corrent time
DateTime date = DateTime.Now;
//print the time
Console.WriteLine(date.ToString());
// For en-US culture, for other culture type refer to MSDN link
//output mm/dd/yyyy hh:mm:ss AM/pm

If you realy need the Unix epoch seconds, refer to this thread
also check your system clock.

Hope I helped!

EDIT: I changed the link to what you needed


问:
c# Richtext box can not load rtf file while Microsoft word using that file
i used a read stream to read an rtf file however it failed when this rtf file is opened by  Microsoft word.

is there anyone know how to solve this problem?

答:
Like this:</p>

```<code>new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Like this:

new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)


问:
Spring Scheduled tasks: specifying time zone in XML configuration
Is it possible to achieve the time zone setting in XML configuration as done in Java with the following annotation?

```<code>@Scheduled(cron = "0 0 8,20 * * *", zone = "GMT-3")
</code>```

I can't see any other attributes in XML definition, but perhaps there's a workaround for achieving the desired goal.

Sample config:

```<code><task:scheduler id="myScheduler" pool-size="2" />
<bean class="MyClass"
    id="myBean" />
<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="myBean" method="gprs" fixed-rate="300000" />
    <task:scheduled ref="myBean" method="reporteGpsGprs" cron="0 0 8,20 * * *" />
</task:scheduled-tasks>
</code>```

Current Spring Dependencies:

```<code>    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.2.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.2.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.2.2.RELEASE</version>
    </dependency>
</code>```

答:
Unfortuanately, looking at the xsd I don't see any other property to define timezone in xml. What you could do is use the ref and method properties to define a factory class that returns the schedule.

Ref : http://www.springframework.org/schema/task/spring-task-4.0.xsd

Body:
Is it possible to achieve the time zone setting in XML configuration as done in Java with the following annotation?

@Scheduled(cron = "0 0 8,20 * * *", zone = "GMT-3")

I can't see any other attributes in XML definition, but perhaps there's a workaround for achieving the desired goal.

Sample config:

<task:scheduler id="myScheduler" pool-size="2" />
<bean class="MyClass"
    id="myBean" />
<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="myBean" method="gprs" fixed-rate="300000" />
    <task:scheduled ref="myBean" method="reporteGpsGprs" cron="0 0 8,20 * * *" />
</task:scheduled-tasks>

Current Spring Dependencies:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.2.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.2.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.2.2.RELEASE</version>
    </dependency>


问:
Read 2D matrix from file to 2D int array in C#
I have problem in reading 2D text from file and import it to an int array. Specifically, my text file looks like below:

2,3,4,5,6

5,2,3,4,5

2,4,6,7,4

2,7,8,5,6

So each cell in matrix is separated by comma and each new row starts with new line.

I tried many ways to make it works but I can't! Simply, I want an int[][] or int[,] array at the end.

P.S: I can read 1-D matrix simply to int[] as below:

```<code>int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();
</code>```

答:
```<code>// Read the text file
var text = File.ReadAllLines(@"path\to\file.txt");

// Split on `,`, convert to int32, add to array, add to outer array
var result = text.Select(x => (x.Split(',').Select(Int32.Parse).ToArray())).ToArray();
</code>```

Result is int[][].

Body:
I have problem in reading 2D text from file and import it to an int array. Specifically, my text file looks like below:

2,3,4,5,6

5,2,3,4,5

2,4,6,7,4

2,7,8,5,6

So each cell in matrix is separated by comma and each new row starts with new line.

I tried many ways to make it works but I can't! Simply, I want an int[][] or int[,] array at the end.

P.S: I can read 1-D matrix simply to int[] as below:

int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();

Body:
// Read the text file
var text = File.ReadAllLines(@"path\to\file.txt");

// Split on `,`, convert to int32, add to array, add to outer array
var result = text.Select(x => (x.Split(',').Select(Int32.Parse).ToArray())).ToArray();

Result is int[][].


问:
Laravel Call to a member function send() on a non-object
I am trying to send a mail using my laravel controller, a very simple mail which is sent in my localhost with no problems but once in server I get this error :

```<code>20170325T153701: /public/index.php
PHP Fatal error:  Call to a member function send() on a non-object in /public/index.php on line 56
PHP Fatal error:  Call to a member function send() on a non-object in /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php on line 107
</code>```

The browser only shows a 500 error, the error is only seen in my error log. Here is the code used to send the mail

```<code>    use Illuminate\Support\Facades\Mail; // just to say I'm calling it
    $v_code = str_random(30);
    $mail_content = array('code' => $v_code);

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['pass']),
    ]);

    if ($user) {
        Mail::send('User::mail.verifyMail', $mail_content, function ($message) use ($data) {
            $message->to($data['email'], $data['name'])
                ->subject('Verify your email address');
        });
</code>```

答: The solution was on casting the $name with a (string). I don't know why, but anytime the name contains a space (' ') it simply fails and the $name is considered as null. Thus, a (string) resolved this.</p>

Body:
I am trying to send a mail using my laravel controller, a very simple mail which is sent in my localhost with no problems but once in server I get this error :

20170325T153701: /public/index.php
PHP Fatal error:  Call to a member function send() on a non-object in /public/index.php on line 56
PHP Fatal error:  Call to a member function send() on a non-object in /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php on line 107

The browser only shows a 500 error, the error is only seen in my error log. Here is the code used to send the mail

    use Illuminate\Support\Facades\Mail; // just to say I'm calling it
    $v_code = str_random(30);
    $mail_content = array('code' => $v_code);

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['pass']),
    ]);

    if ($user) {
        Mail::send('User::mail.verifyMail', $mail_content, function ($message) use ($data) {
            $message->to($data['email'], $data['name'])
                ->subject('Verify your email address');
        });


问:
Thread-safe implementation of the Copy-on-write (COW) idiom?
Can anyone point me to a thread-safe implementation of the Copy-on-write (COW) idiom? The sample code on this site looks good -- is it thread-safe?

In case anyone is wondering what I will be using it for: I have a Foo class that has a std::map<int,double> member. Foo objects are copied very frequently in my code, but the copies rarely modify the contained map. I found that COW gives me a 22% performance boost, compared to copying the whole map contents in the Foo copy constructor, but my COW implementation crashes when multiple threads are used.

UPDATE:

Okay, here is the code, reduced to a minimal example, since you asked for it:

First, a reference-counting map:

```<code>class RcMap {
 public:
  typedef std::map<int,double> Container;
  typedef Container::const_iterator const_iterator;
  typedef Container::iterator iterator;

  RcMap() : count_(1) {}

  RcMap(const RcMap& other) : count_(1) {
    m_ = other.Get();
  }

  unsigned Count() const { return count_; }
  unsigned IncCount() { return ++count_; }
  unsigned DecCount() {
    if(count_ > 0) --count_;
    return count_;
  }
  void insert(int i, double d) {
    m_.insert(std::make_pair(i,d));
  }
  iterator begin() { return m_.begin(); }
  iterator end() { return m_.end(); }
  const_iterator begin() const { return m_.begin(); }
  const_iterator end() const { return m_.end(); }

 protected:
  const Container& Get() const { return m_; }

 private:
  void operator=(const RcMap&); // disallow

  Container m_;
  unsigned count_;
};
</code>```

And here is the class Foo that contains such a map RcMap, using a Copy-on-write mechanism:

```<code>class Foo {
 public:
  Foo() : m_(NULL) {}

  Foo(const Foo& other) : m_(other.m_) {
    if (m_) m_->IncCount();
  }

  Foo& operator= (const Foo& other) {
    RcMap* const old = m_;
    m_ = other.m_;
    if(m_ != 0)
      m_->IncCount();
    if (old != 0 && old->DecCount() == 0) {
      delete old;
    }
    return *this;
  }

  virtual ~Foo() {
    if(m_ != 0 && m_->DecCount() == 0){
      delete m_;
      m_ = 0;
    }
  }

  const RcMap& GetMap() const {
    if(m_ == 0)
      return EmptyStaticRcMap();
    return *m_;
  }

  RcMap& GetMap() {
    if(m_ == 0)
      m_ = new RcMap();
    if (m_->Count() > 1) {
      RcMap* d = new RcMap(*m_);
      m_->DecCount();
      m_ = d;
    }
    assert(m_->Count() == 1);
    return *m_;
  }

  static const RcMap& EmptyStaticRcMap(){
    static const RcMap empty;
    return empty;
  }

 private:
  RcMap* m_;
};
</code>```

I haven't yet been able to reproduce the crash using this minimal example, but in my original code it happens when I use the copy constructor or assignment operator of Foo objects in parallel. But maybe someone can spot the thread-safety bug?

答:
If you're copying a mutable map (it looks like you are), then don't decrease the reference count on the original object until after the copy is complete. (Because otherwise you may wind up allowing writes to the object you're copying, thereby breaking thread safety.)

Better yet, use a fully immutable map implementation (that makes copies and updates even cheaper by using shared substructure) if you can. There's a previous question on this topic that's currently unanswered.

Body:
Can anyone point me to a thread-safe implementation of the Copy-on-write (COW) idiom? The sample code on this site looks good -- is it thread-safe?

In case anyone is wondering what I will be using it for: I have a Foo class that has a std::map<int,double> member. Foo objects are copied very frequently in my code, but the copies rarely modify the contained map. I found that COW gives me a 22% performance boost, compared to copying the whole map contents in the Foo copy constructor, but my COW implementation crashes when multiple threads are used.

UPDATE:

Okay, here is the code, reduced to a minimal example, since you asked for it:

First, a reference-counting map:

class RcMap {
 public:
  typedef std::map<int,double> Container;
  typedef Container::const_iterator const_iterator;
  typedef Container::iterator iterator;

  RcMap() : count_(1) {}

  RcMap(const RcMap& other) : count_(1) {
    m_ = other.Get();
  }

  unsigned Count() const { return count_; }
  unsigned IncCount() { return ++count_; }
  unsigned DecCount() {
    if(count_ > 0) --count_;
    return count_;
  }
  void insert(int i, double d) {
    m_.insert(std::make_pair(i,d));
  }
  iterator begin() { return m_.begin(); }
  iterator end() { return m_.end(); }
  const_iterator begin() const { return m_.begin(); }
  const_iterator end() const { return m_.end(); }

 protected:
  const Container& Get() const { return m_; }

 private:
  void operator=(const RcMap&); // disallow

  Container m_;
  unsigned count_;
};

And here is the class Foo that contains such a map RcMap, using a Copy-on-write mechanism:

class Foo {
 public:
  Foo() : m_(NULL) {}

  Foo(const Foo& other) : m_(other.m_) {
    if (m_) m_->IncCount();
  }

  Foo& operator= (const Foo& other) {
    RcMap* const old = m_;
    m_ = other.m_;
    if(m_ != 0)
      m_->IncCount();
    if (old != 0 && old->DecCount() == 0) {
      delete old;
    }
    return *this;
  }

  virtual ~Foo() {
    if(m_ != 0 && m_->DecCount() == 0){
      delete m_;
      m_ = 0;
    }
  }

  const RcMap& GetMap() const {
    if(m_ == 0)
      return EmptyStaticRcMap();
    return *m_;
  }

  RcMap& GetMap() {
    if(m_ == 0)
      m_ = new RcMap();
    if (m_->Count() > 1) {
      RcMap* d = new RcMap(*m_);
      m_->DecCount();
      m_ = d;
    }
    assert(m_->Count() == 1);
    return *m_;
  }

  static const RcMap& EmptyStaticRcMap(){
    static const RcMap empty;
    return empty;
  }

 private:
  RcMap* m_;
};

I haven't yet been able to reproduce the crash using this minimal example, but in my original code it happens when I use the copy constructor or assignment operator of Foo objects in parallel. But maybe someone can spot the thread-safety bug?


问:
Put values from arrays into input value separated by commas
I have multiple date arrays, I need to put these in input type hidden field value.

```<code>["5/3/2017"]
["12/3/2017"]
["19/3/2017"]
["26/3/2017"]
["26/2/2017"]
</code>```

I want to make it like this:

```<code><input type="hidden" value="5/3/2017, 12/3/2017, 19/3/2017, 26/3/2017, 26/2/2017">
</code>```

I tried with merge, join() but I managed to get just one value to the input and I think its the last value. Any ideas ?

Here is part of the code where I try to do this:

```<code>        var dayAll = sundayData['date'];
        var monthAll = sundayData['month'];
        var yearAll = sundayData['year'];

        var sundayDatesAll = dayAll + '/' + (monthAll + 1) + '/' + yearAll;

        var sundayDate = [];

        sundayDate.push(sundayDatesAll);

        $('input').val(sundayDate);
</code>```

I get the arrays from sundayDate

答:
please check need to give full code for us so know what happened.
but try with this same i thinks issue solve by this.

```<code>sundayDatesAll[0] = ["5/3/2017"];
sundayDatesAll[1] = ["12/3/2017"];
sundayDatesAll[2] = ["19/3/2017"];
sundayDatesAll[3] = ["26/3/2017"];

sundayDate.push(sundayDatesAll);

var manvar = sundayDate.join();

alert(manvar);
</code>```

https://jsfiddle.net/manish1226/8py4o6uc/3/

Body:
I have multiple date arrays, I need to put these in input type hidden field value.

["5/3/2017"]
["12/3/2017"]
["19/3/2017"]
["26/3/2017"]
["26/2/2017"]

I want to make it like this:

<input type="hidden" value="5/3/2017, 12/3/2017, 19/3/2017, 26/3/2017, 26/2/2017">

I tried with merge, join() but I managed to get just one value to the input and I think its the last value. Any ideas ?

Here is part of the code where I try to do this:

        var dayAll = sundayData['date'];
        var monthAll = sundayData['month'];
        var yearAll = sundayData['year'];

        var sundayDatesAll = dayAll + '/' + (monthAll + 1) + '/' + yearAll;

        var sundayDate = [];

        sundayDate.push(sundayDatesAll);

        $('input').val(sundayDate);

I get the arrays from sundayDate

Body:
please check need to give full code for us so know what happened.
but try with this same i thinks issue solve by this.

sundayDatesAll[0] = ["5/3/2017"];
sundayDatesAll[1] = ["12/3/2017"];
sundayDatesAll[2] = ["19/3/2017"];
sundayDatesAll[3] = ["26/3/2017"];

sundayDate.push(sundayDatesAll);

var manvar = sundayDate.join();

alert(manvar);

https://jsfiddle.net/manish1226/8py4o6uc/3/


问:
ReflectionException: Class ClassName does not exist - Laravel
As soon, I am typing php artisan db:seed command.

I'm getting Error Like:

[ReflectionException]

      Class UserTableSeeder does not exist

root@dd-desktop:/opt/lampp/htdocs/dd/laravel# php artisan db:seed

Here, Is my UserTableSeeder.php & DatabaseSeeder.php Page

UserTableSeeder.php

```<code><?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class UserTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('users')->delete();
        User::create(array(
        'name'     => 'Chris Sevilleja',
        'username' => 'sevilayha',
        'email'    => 'chris@scotch.io',
        'password' => Hash::make('awesome'),
        ));
    }
}
</code>```

DatabaseSeeder.php

```<code><?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Eloquent::unguard();
        $this->call('UserTableSeeder');
    }
}
</code>```

I'm Referring This Link To Design & Develop Login Page.
Please Help me to resolve this issue. Thanks.

答:
I had this problem and I could solve it by doing php artisan config:cache.  The problem was that I had already run that command previously and later included some new seeder classes.  The cached configurations didn't recognize the new classes.  So running that command again worked.

If you see yourself making frequent changes to include new seeder classes then consider running php artisan config:clear.  This will enable you to make as many changes as you'd like and then after testing you can run config:cache again to make things run optimally again.

ContentLicense: CC BY-SA 4.0

Body:
As soon, I am typing php artisan db:seed command.

I'm getting Error Like:

[ReflectionException]

      Class UserTableSeeder does not exist

root@dd-desktop:/opt/lampp/htdocs/dd/laravel# php artisan db:seed

Here, Is my UserTableSeeder.php & DatabaseSeeder.php Page

UserTableSeeder.php

<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class UserTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('users')->delete();
        User::create(array(
        'name'     => 'Chris Sevilleja',
        'username' => 'sevilayha',
        'email'    => 'chris@scotch.io',
        'password' => Hash::make('awesome'),
        ));
    }
}

DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Eloquent::unguard();
        $this->call('UserTableSeeder');
    }
}

I'm Referring This Link To Design & Develop Login Page.
Please Help me to resolve this issue. Thanks.


问:
PHPBB send template variable to overall_footer.html
Since overall_footer.html is served by a core phpbb file which shouldn't be edited, how would I go by sending some variables to the template without editing the core files?

To be a bit more specific, I'm trying to do a conditional statement using comments inside of overall_footer.html and I also need to include a functions file (functions_chat.php) in whatever file I will be editing to make this happen correctly.

答:
So for anyone curious about the answer to this, it seems that the footer is actually generated in the functions.php file. Located at /includes

```<code>    function page_footer($run_cron = true, $display_template = true, $exit_handler = true)
{
    global $db, $config, $template, $user, $auth, $cache, $phpEx;
    global $request, $phpbb_dispatcher, $phpbb_admin_path;

    // A listener can set this variable to `true` when it overrides this function
    $page_footer_override = false;

    /**
    * Execute code and/or overwrite page_footer()
    *
    * @event core.page_footer
    * @var  bool    run_cron            Shall we run cron tasks
    * @var  bool    page_footer_override    Shall we return instead of running
    *                                       the rest of page_footer()
    * @since 3.1.0-a1
    */
    $vars = array('run_cron', 'page_footer_override');
    extract($phpbb_dispatcher->trigger_event('core.page_footer', compact($vars)));

    if ($page_footer_override)
    {
        return;
    }

    phpbb_check_and_display_sql_report($request, $auth, $db);

    $template->assign_vars(array(
        'DEBUG_OUTPUT'          => phpbb_generate_debug_output($db, $config, $auth, $user, $phpbb_dispatcher),
        'TRANSLATION_INFO'      => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
        'CREDIT_LINE'           => $user->lang('POWERED_BY', '<a href="https://www.phpbb.com/">phpBB</a>® Forum Software © phpBB Limited'),

        'U_ACP' => ($auth->acl_get('a_') && !empty($user->data['is_registered'])) ? append_sid("{$phpbb_admin_path}index.$phpEx", false, true, $user->session_id) : '')
    );

    // Call cron-type script
    $call_cron = false;
    if (!defined('IN_CRON') && !$config['use_system_cron'] && $run_cron && !$config['board_disable'] && !$user->data['is_bot'] && !$cache->get('_cron.lock_check'))
    {
        $call_cron = true;
        $time_now = (!empty($user->time_now) && is_int($user->time_now)) ? $user->time_now : time();

        // Any old lock present?
        if (!empty($config['cron_lock']))
        {
            $cron_time = explode(' ', $config['cron_lock']);

            // If 1 hour lock is present we do not call cron.php
            if ($cron_time[0] + 3600 >= $time_now)
            {
                $call_cron = false;
            }
        }
    }

    // Call cron job?
    if ($call_cron)
    {
        global $phpbb_container;

        /* @var $cron \phpbb\cron\manager */
        $cron = $phpbb_container->get('cron.manager');
        $task = $cron->find_one_ready_task();

        if ($task)
        {
            $url = $task->get_url();
            $template->assign_var('RUN_CRON_TASK', '<img src="' . $url . '" width="1" height="1" alt="cron" />');
        }
        else
        {
            $cache->put('_cron.lock_check', true, 60);
        }
    }
</code>```

And this is where the variables are assigned to the template

```<code>$template->assign_vars(array(
        'DEBUG_OUTPUT'          => phpbb_generate_debug_output($db, $config, $auth, $user, $phpbb_dispatcher),
        'TRANSLATION_INFO'      => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
        'CREDIT_LINE'           => $user->lang('POWERED_BY', '<a href="https://www.phpbb.com/">phpBB</a>® Forum Software © phpBB Limited'),

        'U_ACP' => ($auth->acl_get('a_') && !empty($user->data['is_registered'])) ? append_sid("{$phpbb_admin_path}index.$phpEx", false, true, $user->session_id) : '')
    );
</code>```

Body:
So for anyone curious about the answer to this, it seems that the footer is actually generated in the functions.php file. Located at /includes

    function page_footer($run_cron = true, $display_template = true, $exit_handler = true)
{
    global $db, $config, $template, $user, $auth, $cache, $phpEx;
    global $request, $phpbb_dispatcher, $phpbb_admin_path;

    // A listener can set this variable to `true` when it overrides this function
    $page_footer_override = false;

    /**
    * Execute code and/or overwrite page_footer()
    *
    * @event core.page_footer
    * @var  bool    run_cron            Shall we run cron tasks
    * @var  bool    page_footer_override    Shall we return instead of running
    *                                       the rest of page_footer()
    * @since 3.1.0-a1
    */
    $vars = array('run_cron', 'page_footer_override');
    extract($phpbb_dispatcher->trigger_event('core.page_footer', compact($vars)));

    if ($page_footer_override)
    {
        return;
    }

    phpbb_check_and_display_sql_report($request, $auth, $db);

    $template->assign_vars(array(
        'DEBUG_OUTPUT'          => phpbb_generate_debug_output($db, $config, $auth, $user, $phpbb_dispatcher),
        'TRANSLATION_INFO'      => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
        'CREDIT_LINE'           => $user->lang('POWERED_BY', '<a href="https://www.phpbb.com/">phpBB</a>&reg; Forum Software &copy; phpBB Limited'),

        'U_ACP' => ($auth->acl_get('a_') && !empty($user->data['is_registered'])) ? append_sid("{$phpbb_admin_path}index.$phpEx", false, true, $user->session_id) : '')
    );

    // Call cron-type script
    $call_cron = false;
    if (!defined('IN_CRON') && !$config['use_system_cron'] && $run_cron && !$config['board_disable'] && !$user->data['is_bot'] && !$cache->get('_cron.lock_check'))
    {
        $call_cron = true;
        $time_now = (!empty($user->time_now) && is_int($user->time_now)) ? $user->time_now : time();

        // Any old lock present?
        if (!empty($config['cron_lock']))
        {
            $cron_time = explode(' ', $config['cron_lock']);

            // If 1 hour lock is present we do not call cron.php
            if ($cron_time[0] + 3600 >= $time_now)
            {
                $call_cron = false;
            }
        }
    }

    // Call cron job?
    if ($call_cron)
    {
        global $phpbb_container;

        /* @var $cron \phpbb\cron\manager */
        $cron = $phpbb_container->get('cron.manager');
        $task = $cron->find_one_ready_task();

        if ($task)
        {
            $url = $task->get_url();
            $template->assign_var('RUN_CRON_TASK', '<img src="' . $url . '" width="1" height="1" alt="cron" />');
        }
        else
        {
            $cache->put('_cron.lock_check', true, 60);
        }
    }

And this is where the variables are assigned to the template

$template->assign_vars(array(
        'DEBUG_OUTPUT'          => phpbb_generate_debug_output($db, $config, $auth, $user, $phpbb_dispatcher),
        'TRANSLATION_INFO'      => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
        'CREDIT_LINE'           => $user->lang('POWERED_BY', '<a href="https://www.phpbb.com/">phpBB</a>&reg; Forum Software &copy; phpBB Limited'),

        'U_ACP' => ($auth->acl_get('a_') && !empty($user->data['is_registered'])) ? append_sid("{$phpbb_admin_path}index.$phpEx", false, true, $user->session_id) : '')
    );


问:
scikit learn: train_test_split, can I ensure same splits on different datasets
I understand that the train_test_split method splits a dataset into random train and test subsets. And using random_state=int can ensure we have the same splits on this dataset for each time the method is called.

My problem is slightly different.

I have two datasets, A and B, they contain identical sets of examples and the order of these examples appear in each dataset is also identical. But they key difference is that exmaples in each dataset uses a different sets of features.

I would like to test to see if the features used in A leads to better performance than features used in B. So I would like to ensure that when I call train_test_split on A and B, I can get the same splits on both datasets so that the comparison is meaningful.

Is this possible? Do I simply need to ensure the random_state in both method calls for both datasets are the same?

Thanks

Body:
Yes, random state is enough.

>>> X, y = np.arange(10).reshape((5, 2)), range(5)
>>> X2 = np.hstack((X,X))
>>> X_train, X_test, _, _ = train_test_split(X,y, test_size=0.33, random_state=42)
>>> X_train2, X_test2, _, _ = train_test_split(X2,y, test_size=0.33, random_state=42)
>>> X_train
array([[4, 5],
       [0, 1],
       [6, 7]])
>>> X_train2
array([[4, 5, 4, 5],
       [0, 1, 0, 1],
       [6, 7, 6, 7]])
>>> X_test
array([[2, 3],
       [8, 9]])
>>> X_test2
array([[2, 3, 2, 3],
       [8, 9, 8, 9]])


问:
how to scrape data from multiple pages in the same csv row?
I need to scrape data from multiple pages. First it should scrape data from the first page then from this page extract a url to the second page and get some data from it, too

All should be on the same csv row.

This is the first page:
https://www.catalogs.ssg.asia/toyota/?fromchanged=true&lang=en&l=bWFya2V0PT1nZW5lcmFsfHxzdD09MjB8fHN0cz09eyIxMCI6IlJlZ2lvbiIsIjIwIjoiTWlkZGxlIEVhc3QifQ%3D%3D

example of the data is the first row on the table e.g:catalog, model, production, and series.

This is the second page:
https://www.catalogs.ssg.asia/toyota/?fromchanged=true&lang=en&l=bWFya2V0PT1nZW5lcmFsfHxzdD09MzB8fHN0cz09eyIxMCI6IlJlZ2lvbiIsIjIwIjoiTWlkZGxlIEVhc3QiLCIzMCI6IjRSVU5ORVIgNjcxMzYwIn18fGNhdGFsb2c9PTY3MTM2MHx8cmVjPT1CMw%3D%3D
example of the data: series, engine, production date.

both should be together on the same csv row like the screenshot:

This is my code:

```<code>import datetime
import urlparse
import socket
import scrapy

from scrapy.loader.processors import MapCompose, Join
from scrapy.loader import ItemLoader
from scrapy.http import Request

from properties.items import PropertiesItem

class BasicSpider(scrapy.Spider):
    name = "manual"

    # This is the page which i will hit middle est from.
    start_urls = ["https://www.catalogs.ssg.asia/toyota/?fromchanged=true&lang=en"]

    def parse(self, response):
        # First page
        next_selector ="https://www.catalogs.ssg.asia/toyota/?fromchanged=true&lang=en&l="+response.xpath('//*[@id="rows"]/tr[2]/@onclick').re(r"HM\.set\('([^']+)'")[0]
        yield Request(next_selector, callback=self.parse_item)

    def parse_item(self, response):
        for tr in response.xpath("/html/body/table[2]/tr/td/table/tr")[1:]:
            item = PropertiesItem()

            item['Series']= tr.xpath("td[1]/text()").extract()
            item['Engine']= tr.xpath("td[2]/text()").extract()
            second_selector ="https://www.catalogs.ssg.asia/toyota/?fromchanged=true&lang=en&l="+response.xpath('/html/body/table[2]/tr/td/table/tr/@onclick').re(r"HM\.set\('([^']+)'")

            yield item

    def parse_item_2(self, response):
        item = PropertiesItem()
        item['Building_Condition']=response.xpath('/html/body/table[2]/tr/td/table/tr[2]/td[1]/text()').extract()
        yield item
</code>```

I need to write some code in parse item to go to parse_item_2 and handle the second page and get the results to be on the same csv row.
How to do that?

答:
If you want to build a single item using data from different urls you should pass it from one Request object to the next using the meta attribute. Finally you yield the resulting item in order to write it into a single row.</p>

```<code>def parse_item(self, response):
    for tr in response.xpath("/html/body/table[2]/tr/td/table/tr")[1:]:
        [...]
        second_selector = [...]
        meta = {'item': item}
        yield Request(second_selector, meta=meta, callback=self.parse_item_2)

    def parse_item_2(self, response):
        item = PropertiesItem(response.meta['item'])
        item['Building_Condition']=response.xpath('/html/body/table[2]/tr/td/table/tr[2]/td[1]/text()').extract()
        yield item
</code>```

Body:
I need to scrape data from multiple pages. First it should scrape data from the first page then from this page extract a url to the second page and get some data from it, too

All should be on the same csv row.

This is the first page:
https://www.catalogs.ssg.asia/toyota/?fromchanged=true&lang=en&l=bWFya2V0PT1nZW5lcmFsfHxzdD09MjB8fHN0cz09eyIxMCI6IlJlZ2lvbiIsIjIwIjoiTWlkZGxlIEVhc3QifQ%3D%3D

example of the data is the first row on the table e.g:catalog, model, production, and series.

This is the second page:
https://www.catalogs.ssg.asia/toyota/?fromchanged=true&lang=en&l=bWFya2V0PT1nZW5lcmFsfHxzdD09MzB8fHN0cz09eyIxMCI6IlJlZ2lvbiIsIjIwIjoiTWlkZGxlIEVhc3QiLCIzMCI6IjRSVU5ORVIgNjcxMzYwIn18fGNhdGFsb2c9PTY3MTM2MHx8cmVjPT1CMw%3D%3D
example of the data: series, engine, production date.

both should be together on the same csv row like the screenshot:

This is my code:

import datetime
import urlparse
import socket
import scrapy

from scrapy.loader.processors import MapCompose, Join
from scrapy.loader import ItemLoader
from scrapy.http import Request

from properties.items import PropertiesItem

class BasicSpider(scrapy.Spider):
    name = "manual"

    # This is the page which i will hit middle est from.
    start_urls = ["https://www.catalogs.ssg.asia/toyota/?fromchanged=true&lang=en"]

    def parse(self, response):
        # First page
        next_selector ="https://www.catalogs.ssg.asia/toyota/?fromchanged=true&lang=en&l="+response.xpath('//*[@id="rows"]/tr[2]/@onclick').re(r"HM\.set\('([^']+)'")[0]
        yield Request(next_selector, callback=self.parse_item)

    def parse_item(self, response):
        for tr in response.xpath("/html/body/table[2]/tr/td/table/tr")[1:]:
            item = PropertiesItem()

            item['Series']= tr.xpath("td[1]/text()").extract()
            item['Engine']= tr.xpath("td[2]/text()").extract()
            second_selector ="https://www.catalogs.ssg.asia/toyota/?fromchanged=true&lang=en&l="+response.xpath('/html/body/table[2]/tr/td/table/tr/@onclick').re(r"HM\.set\('([^']+)'")

            yield item

    def parse_item_2(self, response):
        item = PropertiesItem()
        item['Building_Condition']=response.xpath('/html/body/table[2]/tr/td/table/tr[2]/td[1]/text()').extract()
        yield item

I need to write some code in parse item to go to parse_item_2 and handle the second page and get the results to be on the same csv row.
How to do that?

Body:
If you want to build a single item using data from different urls you should pass it from one Request object to the next using the meta attribute. Finally you yield the resulting item in order to write it into a single row.

def parse_item(self, response):
    for tr in response.xpath("/html/body/table[2]/tr/td/table/tr")[1:]:
        [...]
        second_selector = [...]
        meta = {'item': item}
        yield Request(second_selector, meta=meta, callback=self.parse_item_2)

    def parse_item_2(self, response):
        item = PropertiesItem(response.meta['item'])
        item['Building_Condition']=response.xpath('/html/body/table[2]/tr/td/table/tr[2]/td[1]/text()').extract()
        yield item


问:
Error inflating class android.support.v4.view.ViewPager
App crashed because

```<code>Binary XML file line #17: Error inflating class android.support.v4.view.ViewPager
</code>```

My gradle

```<code>    compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support:design:25.3.0'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
compile 'com.yalantis:contextmenu:1.0.7'
compile 'com.android.support:recyclerview-v7:25.3.0'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'org.litepal.android:core:1.5.1'
compile 'com.android.support:cardview-v7:25.3.0'
compile 'com.github.florent37:materialviewpager:1.2.1'
compile 'com.flaviofaria:kenburnsview:1.0.7'
compile 'com.jpardogo.materialtabstrip:library:1.1.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
</code>```

It is xml code.

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:layout_marginTop="16dp"
    android:gravity="center"
    android:orientation="vertical">
</LinearLayout>
<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="330dp"
    android:layout_gravity="bottom"
    android:paddingStart="@dimen/card_padding"
    android:paddingLeft="@dimen/card_padding"
    android:paddingRight="@dimen/card_padding"
    android:paddingEnd="@dimen/card_padding"
    android:paddingBottom="30dp"
    android:overScrollMode="never"
    android:clipToPadding="false">
</android.support.v4.view.ViewPager>
</code>```

Here is part of my logcat.......

android.view.InflateException: Binary XML file line #17: Error inflating class android.support.v4.view.ViewPager
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2196)
  Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class android.support.v4.view.ViewPager
  at android.view.LayoutInflater.createView(LayoutInflater.java:620)
  Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class android.support.v4.view.ViewPager                                                                         at android.view.LayoutInflater.createView(LayoutInflater.java:620)                                                                         at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
   Caused by: java.lang.reflect.InvocationTargetException                                                                         at java.lang.reflect.Constructor.constructNative(Native Method)                                                                         at java.lang.reflect.Constructor.newInstance(Constructor.java:423)                                                                         at android.view.LayoutInflater.createView(LayoutInflater.java:594)

I failed to upload my total logcat.Whatever I did,there always was an error in  editting.(By the way,I use Android Studio 2.3  ...)

答:
You have to add to the project the correct library.

Go to Project->Properties->Java Build Path->Order and export tab. Set android-support-v4.jar library checked and up it into top of the list.

Clean and rebuild it, it should works.

Body:
App crashed because

Binary XML file line #17: Error inflating class android.support.v4.view.ViewPager

My gradle

    compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support:design:25.3.0'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
compile 'com.yalantis:contextmenu:1.0.7'
compile 'com.android.support:recyclerview-v7:25.3.0'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'org.litepal.android:core:1.5.1'
compile 'com.android.support:cardview-v7:25.3.0'
compile 'com.github.florent37:materialviewpager:1.2.1'
compile 'com.flaviofaria:kenburnsview:1.0.7'
compile 'com.jpardogo.materialtabstrip:library:1.1.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'

It is xml code.

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:layout_marginTop="16dp"
    android:gravity="center"
    android:orientation="vertical">
</LinearLayout>
<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="330dp"
    android:layout_gravity="bottom"
    android:paddingStart="@dimen/card_padding"
    android:paddingLeft="@dimen/card_padding"
    android:paddingRight="@dimen/card_padding"
    android:paddingEnd="@dimen/card_padding"
    android:paddingBottom="30dp"
    android:overScrollMode="never"
    android:clipToPadding="false">
</android.support.v4.view.ViewPager>

Here is part of my logcat.......

android.view.InflateException: Binary XML file line #17: Error inflating class android.support.v4.view.ViewPager
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2196)
  Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class android.support.v4.view.ViewPager
  at android.view.LayoutInflater.createView(LayoutInflater.java:620)
  Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class android.support.v4.view.ViewPager                                                                         at android.view.LayoutInflater.createView(LayoutInflater.java:620)                                                                         at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
   Caused by: java.lang.reflect.InvocationTargetException                                                                         at java.lang.reflect.Constructor.constructNative(Native Method)                                                                         at java.lang.reflect.Constructor.newInstance(Constructor.java:423)                                                                         at android.view.LayoutInflater.createView(LayoutInflater.java:594)

I failed to upload my total logcat.Whatever I did,there always was an error in  editting.(By the way,I use Android Studio 2.3  ...)


问:
Solving list of expressions in sympy
I have list of expression in the form.

```<code>f1 = q1 * f2 + r1
f2 = q2 * r1 + r2
r1 = q3 * r2 + r3
r2 = q4 * r3 + r4
</code>```

I would like to express r4 in terms of f1, f2 and qn(i.e. q1, q2, ...). How can i perform this operation in sympy?

答:
sympy.solve can be passed a list of expressions (equal to zero) and a list of Symbols to be solved for. If there is a solution, it is returned in a dict.
Since you seek a solution in terms of the fs and qs, solve for all of the r variables.

```<code>f1, f2, r1, r2, r3, r4, q1, q2, q3, q4 = sy.symbols('f1,f2,r1,r2,r3,r4,q1,q2,q3,q4')
ans = sy.solve([
    f1 - q1 * f2 - r1,
    f2 - q2 * r1 - r2,
    r1 - q3 * r2 - r3,
    r2 - q4 * r3 - r4], [r4, r3, r2, r1])
print(ans[r4])
</code>```

prints

```<code>f2*(q3*q4 + 1) - (f1 - f2*q1)*(q2*q3*q4 + q2 + q4)
</code>```

Title: Solving list of expressions in sympy

Body:
I have list of expression in the form.

f1 = q1 * f2 + r1
f2 = q2 * r1 + r2
r1 = q3 * r2 + r3
r2 = q4 * r3 + r4

I would like to express r4 in terms of f1, f2 and qn(i.e. q1, q2, ...). How can i perform this operation in sympy?

Body:
sympy.solve can be passed a list of expressions (equal to zero) and a list of Symbols to be solved for. If there is a solution, it is returned in a dict.
Since you seek a solution in terms of the fs and qs, solve for all of the r variables.

f1, f2, r1, r2, r3, r4, q1, q2, q3, q4 = sy.symbols('f1,f2,r1,r2,r3,r4,q1,q2,q3,q4')
ans = sy.solve([
    f1 - q1 * f2 - r1,
    f2 - q2 * r1 - r2,
    r1 - q3 * r2 - r3,
    r2 - q4 * r3 - r4], [r4, r3, r2, r1])
print(ans[r4])

prints

f2*(q3*q4 + 1) - (f1 - f2*q1)*(q2*q3*q4 + q2 + q4)


问:
What are the chronological steps in building a cross browser compatible site?
I am working on my first project that requires me to worry about cross browser compatibility.  Since this is my first time doing so, I dont know how to go about completing the project.  I am specifically worried about IE.  Should I complete my project in a more graceful browser then hack it to work in IE, or should I simultaneously build my program up in both environments?</p>

答:
OOoooo, good question:

here's my take:

Decide which browsers you are supporting. I suggest IE 7 + 8, FF, Chrome and Safari as in order of importance. (only support IE6 if you absolutely have to!).  It helps if you know your userbase here.

Use a css reset. Different browsers have different default styles. a css reset gives you a consistent base.

Keep your markup as simple as possible.  Follow Standards (and see progressive enhancement on Stephen's answer).

Test every step of the way on your target browsers.  That way you can correct problems right away. http://crossbrowsertesting.com/ is the best resource for this, but there are free ones for screenshots as well.

Avoid Hacks as much as possible.  Most cross-browser issues these days can be solved without resorting to hacks.

Ask questions here when you get stuck.  If this is your first project dealing with browsers, you will get bewildered by inconsistencies.  We all face these issues, and are glad to help.

Be ok with the fact that webpages are not going to look exactly the same in all browsers.  (once again, see progressive enhancement).

Good luck coding!


问:
Declaring a Task Property and awaiting it
I'm stuck in something I thought so simple that it drives me out of myself.

I need to declare a Task in some point and run it later, I thought of:

```<code>Task T1 { get; set; }

public async Task CreateAndAwaitAsync()
{
    T1 = new Task(() => {
        // time consuming work like:
        System.Threading.Thread.Sleep(1000);
    }

    await T1;
}
</code>```

Of course the body of the lambda AND the method are just for the sake of this example (as I said I need to run it later), but no matter what, with await T1 I just cannot make it into the lambda! What am I missing?? I feel stupid because I have been using the async-await paradigm for quite the few years already that I didn't even imagine this wouldn't work!

答:
I thought it can be answered in comment but better to provide more info.

await means "wait for this task to complete, then do the rest stuff". Task from your example is not started. await will not start it for you, so the whole method will just stuck at await until you start the task.

Even with your current code, if you later do T1.Start() - it will run your lambda and after it is completed - your task returned by CreateAndAwaitAsync will also complete.

Otherwise - either start task right when creating it (Task.Run) or just return Task directly without any async\await:

```<code>public Task CreateAndAwaitAsync()
{
    T1 = new Task(() => {
        // time consuming work like:
        System.Threading.Thread.Sleep(1000);
    }
    // if you need to start it somewhere, do T1.Start();
    return T1;
}
</code>```

Body:
I'm stuck in something I thought so simple that it drives me out of myself.

I need to declare a Task in some point and run it later, I thought of:

Task T1 { get; set; }

public async Task CreateAndAwaitAsync()
{
    T1 = new Task(() => {
        // time consuming work like:
        System.Threading.Thread.Sleep(1000);
    }

    await T1;
}

Of course the body of the lambda AND the method are just for the sake of this example (as I said I need to run it later), but no matter what, with await T1 I just cannot make it into the lambda! What am I missing?? I feel stupid because I have been using the async-await paradigm for quite the few years already that I didn't even imagine this wouldn't work!

Body:
I thought it can be answered in comment but better to provide more info.

await means "wait for this task to complete, then do the rest stuff". Task from your example is not started. await will not start it for you, so the whole method will just stuck at await until you start the task.

Even with your current code, if you later do T1.Start() - it will run your lambda and after it is completed - your task returned by CreateAndAwaitAsync will also complete.

Otherwise - either start task right when creating it (Task.Run) or just return Task directly without any async\await:

public Task CreateAndAwaitAsync()
{
    T1 = new Task(() => {
        // time consuming work like:
        System.Threading.Thread.Sleep(1000);
    }
    // if you need to start it somewhere, do T1.Start();
    return T1;
}


问:
Number of fields in a structure
I'm new in abap development .
Actually, I'm looking for the Number of fields of a table or structure

any suggestion please

答:
For counting the components of a structure, better use RTTS as we don't want to access the database for result we already have in our environment.</p>

```<code>DATA(lwa_struct) = VALUE kna1( ). " your structure e.g. kna1

DATA(lo_descr) = CAST cl_abap_structdescr( cl_abap_datadescr=>describe_by_data( lwa_struct ) ).

DATA(lw_all_fields) = LINES( lo_descr->components ). " => 184
</code>```

Title: Number of fields in a structure

Body:
For counting the components of a structure, better use RTTS as we don't want to access the database for result we already have in our environment.

DATA(lwa_struct) = VALUE kna1( ). " your structure e.g. kna1

DATA(lo_descr) = CAST cl_abap_structdescr( cl_abap_datadescr=>describe_by_data( lwa_struct ) ).

DATA(lw_all_fields) = LINES( lo_descr->components ). " => 184


答:
Like @Evk said, you need to call T1.Start()</p>

```<code>public async Task CreateAndAwaitAsync()
    {
        T1 = new Task(() =>
        {
            // time consuming work like:
            System.Threading.Thread.Sleep(1000);
        });

        T1.Start();
        await T1;
    }
</code>```

Title: Declaring a Task Property and awaiting it

Body:
Like @Evk said, you need to call T1.Start()

public async Task CreateAndAwaitAsync()
    {
        T1 = new Task(() =>
        {
            // time consuming work like:
            System.Threading.Thread.Sleep(1000);
        });

        T1.Start();
        await T1;
    }


问:
How do I Append a string to a list using dynamodb sdk? (Java)
Pretty simple problem, but for some reason there is no correct documentation anywhere. Here is what I am implementing:

```<code>public static AttributeValue pushMessage(String ID,String message)
{
    Map<String, AttributeValue> itemKey = mapKey(KEY, new AttributeValue(ID));

    UpdateItemRequest request = new UpdateItemRequest();
    request.setTableName(TABLE_NAME);
    request.setKey(itemKey);
    /*I don't know what to put for the update expression*/
    //request.setUpdateExpression("ADD #"+LIST_NAME+" :append_value)");
    request.setUpdateExpression("list_append("+LIST_NAME+", :append_value)");
    request.setExpressionAttributeValues(Collections.singletonMap(":append_value", new AttributeValue(message)));

    UpdateItemResult result = dynamoDB.updateItem(request);
}
</code>```

I essentially just want to be able to append strings to a list I have in the items in my DB. I have tried everything the documentations have suggested(so basically 1 example) and numerous  threads, but nothing works.

The error I am currently getting is:

```<code>Exception in thread "main" com.amazonaws.AmazonServiceException: Invalid UpdateExpression: Syntax error; token: "list_append", near: "list_append(" (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException;
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1372)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:919)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:697)
at com.amazonaws.http.AmazonHttpClient.doExecute(AmazonHttpClient.java:449)
at com.amazonaws.http.AmazonHttpClient.executeWithTimer(AmazonHttpClient.java:411)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:360)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:2048)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:2018)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.updateItem(AmazonDynamoDBClient.java:1845)
at DBConnector.pushMessage(DBConnector.java:486)
at DBConnector.main(DBConnector.java:506)
</code>```

答:
Use the following UpdateExpression:</p>

```<code>String.format("SET %s = list_append(%s, :append_value)", LIST_NAME, LIST_NAME)
</code>```

Body:
Pretty simple problem, but for some reason there is no correct documentation anywhere. Here is what I am implementing:

public static AttributeValue pushMessage(String ID,String message)
{
    Map<String, AttributeValue> itemKey = mapKey(KEY, new AttributeValue(ID));

    UpdateItemRequest request = new UpdateItemRequest();
    request.setTableName(TABLE_NAME);
    request.setKey(itemKey);
    /*I don't know what to put for the update expression*/
    //request.setUpdateExpression("ADD #"+LIST_NAME+" :append_value)");
    request.setUpdateExpression("list_append("+LIST_NAME+", :append_value)");
    request.setExpressionAttributeValues(Collections.singletonMap(":append_value", new AttributeValue(message)));

    UpdateItemResult result = dynamoDB.updateItem(request);
}

I essentially just want to be able to append strings to a list I have in the items in my DB. I have tried everything the documentations have suggested(so basically 1 example) and numerous  threads, but nothing works.

The error I am currently getting is:

Exception in thread "main" com.amazonaws.AmazonServiceException: Invalid UpdateExpression: Syntax error; token: "list_append", near: "list_append(" (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException;
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1372)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:919)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:697)
at com.amazonaws.http.AmazonHttpClient.doExecute(AmazonHttpClient.java:449)
at com.amazonaws.http.AmazonHttpClient.executeWithTimer(AmazonHttpClient.java:411)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:360)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:2048)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:2018)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.updateItem(AmazonDynamoDBClient.java:1845)
at DBConnector.pushMessage(DBConnector.java:486)
at DBConnector.main(DBConnector.java:506)

Body:
Use the following UpdateExpression:

String.format("SET %s = list_append(%s, :append_value)", LIST_NAME, LIST_NAME)


问:
listening for emitted error on fs.createReadStream
If I understand Node correctly, a listener will only receive events that occur after it's attached. Suppose missing.txt is a missing file. This works:

```<code>'use strict';
const fs = require( 'fs' );
var rs = fs.createReadStream( 'missing.txt' );
rs.on('error', (err) => console.log('error ' + err) );
</code>```

It produces: error Error: ENOENT: no such file or directory, open ...\missing.txt

Why does that work? Changing the fourth line as follows also works:

```<code>setTimeout( () => rs.on('error', (err) => console.log('error ' + err)) , 1);
</code>```

But change the timeout to 5ms, and the error is thrown as an unhandled event.

Am I setting up a race that happens to catch the emitted error if the delay to add the event listener is short enought? Does that mean I really should do an explicit check for the existence of the file before opening it as a stream? But that could create another race, as the Node docs state with respect to fs.exists: "other processes may change the file's state between the two calls."
Moroeover, the event listener is convenient because it will catch other errors.

Is it best practice to just assume that, without introducing an explicit delay, the event listener will be added fast enough to hear an error from attempting to stream a non-existent file?

答:
This error occur when there no such location exists or creating permission are not with user program.

This might be helpful:

```<code>var filename = __dirname+req.url;

var readStream = fs.createReadStream(filename);
  readStream.on('open', function () {
  readStream.pipe(res);
});

readStream.on('error', function(err) {
  res.end(err);
});
</code>```

Why are you listening error on timeout ?

Thanks

Body:
If I understand Node correctly, a listener will only receive events that occur after it's attached. Suppose missing.txt is a missing file. This works:

'use strict';
const fs = require( 'fs' );
var rs = fs.createReadStream( 'missing.txt' );
rs.on('error', (err) => console.log('error ' + err) );

It produces: error Error: ENOENT: no such file or directory, open ...\missing.txt

Why does that work? Changing the fourth line as follows also works:

setTimeout( () => rs.on('error', (err) => console.log('error ' + err)) , 1);

But change the timeout to 5ms, and the error is thrown as an unhandled event.

Am I setting up a race that happens to catch the emitted error if the delay to add the event listener is short enought? Does that mean I really should do an explicit check for the existence of the file before opening it as a stream? But that could create another race, as the Node docs state with respect to fs.exists: "other processes may change the file's state between the two calls."
Moroeover, the event listener is convenient because it will catch other errors.

Is it best practice to just assume that, without introducing an explicit delay, the event listener will be added fast enough to hear an error from attempting to stream a non-existent file?

Body:
This error occur when there no such location exists or creating permission are not with user program.

This might be helpful:

var filename = __dirname+req.url;

var readStream = fs.createReadStream(filename);
  readStream.on('open', function () {
  readStream.pipe(res);
});

readStream.on('error', function(err) {
  res.end(err);
});

Why are you listening error on timeout ?

Thanks


问:
How to install Kivy on Windows?
I have downloaded the package 'Kivy-1.9.0-py3.4-win32-x64' from their website. I extracted it and gives me a folder with gstreamer, kivy34, MinGW, etc. As I have searched to some tutorials I clicked the kivy-3.4.bat file to set the paths. Now I'm lost, what to do next?

I wanted to do Kivy applications through Python IDLE. Help!

答:
Make sure you have PIP installed (it gives the option to install when you download python). Then, open a command shell (CMD on Windows; enter the search bar and type in 'cmd') and type pip install kivy.

Some would recommend setting up a virtualenv and stuff but as a quick answer this should work.

Title: How to install Kivy on Windows?


问:
Render a single react component in a html file (webpack)
I'm trying to render a simple react component to a html page, but can't figure out how to do it.

```<code>// hello.js
import React from 'react';
import ReactDOM from 'react-dom';

export default class Hello extends React.Component {
  render() {
    return (
        <h1>Hello {this.props.name}</h1>
    )
  }
}

// index.html
<html>
<body>
</body>
<head>

    <!-- HTML code -->

    <!-- RENDER HERE -->

</head>
</html>
</code>```

webpack and babel:

```<code>// index.js
import Hello from './hello.js'
</code>```

If i put this line at the end of Hello.js:

```<code>ReactDOM.render(<Hello/>, document.getElementById('hello'));
</code>```

I can render the component with:

```<code>// index.html
<div id="hello"></div>
<script src="bundle.js"></script>
</code>```

However, There are times where I don't want to render the component, or render it after a certain time interval. If I remove the div i get an error:

```<code>Target container is not a DOM element
</code>```

I guess I want to do something like this (Which doesn't work)

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

    <!-- HTML code -->

    <!-- RENDER HERE -->
    <div id="hello"></div>

    <script src="bundle.js"></script>

    <script>
        setTimeout(function() {
            ReactDOM.render(<Hello/>, document.getElementById('hello'));
        },1000);

        // or

        if (true) {
            ReactDOM.render(<Hello/>, document.getElementById('hello'));
        }
    </script>
</head>
</html>
</code>```

What am I doing wrong here?
And question nr 2. How do I pass props to the component?

答:
You should start with this CodePen and do some experiments first to get comfortable with React.

React example on Codepen

There are times where I don't want to render the component, or render it after a certain time interval.

If you use React the right way, you would achieve this behavior by using States or Props. Each time a State or a Prop changes, all affected Components are re-rendered automatically.

How do I pass props to the component?

This is as simple as this:

```<code><MyComponent firstProp={true} secondProp={new Date()} />
</code>```

And to access this inside MyComponent:

```<code>render() {

console.log( this.props.firstProp );

...

}
</code>```

You should also check out 8 no-Flux strategies for React component communication. This guide helped me a lot, when I first started with ReactJS.

Body:
I'm trying to render a simple react component to a html page, but can't figure out how to do it.

// hello.js
import React from 'react';
import ReactDOM from 'react-dom';

export default class Hello extends React.Component {
  render() {
    return (

Hello {this.props.name}

    )
  }
}

// index.html

webpack and babel:

// index.js
import Hello from './hello.js'

If i put this line at the end of Hello.js:

ReactDOM.render(<Hello/>, document.getElementById('hello'));

I can render the component with:

// index.html

However, There are times where I don't want to render the component, or render it after a certain time interval. If I remove the div i get an error:

Target container is not a DOM element

I guess I want to do something like this (Which doesn't work)

What am I doing wrong here?
And question nr 2. How do I pass props to the component?

Body:
You should start with this CodePen and do some experiments first to get comfortable with React.

React example on Codepen

There are times where I don't want to render the component, or render it after a certain time interval.

If you use React the right way, you would achieve this behavior by using States or Props. Each time a State or a Prop changes, all affected Components are re-rendered automatically.

How do I pass props to the component?

This is as simple as this:

<MyComponent firstProp={true} secondProp={new Date()} />

And to access this inside MyComponent:

render() {

console.log( this.props.firstProp );

...

}

You should also check out 8 no-Flux strategies for React component communication. This guide helped me a lot, when I first started with ReactJS.


问:
how to find the commit message by author?
How can I find the commit message by a specific author?

For example, if we are both working on a project and I want to find the line added by another author for the file hello.java.

答:
```<code>git blame hello.java
</code>```

Body: git blame hello.java


问:
onTestComplete function
Basically the first script runs correctly on the Web (Action 1) . This inputted information is transferred from the web to a terminal emulator (backend non QTP related). → Done

A second action is then used on the terminal emulator to complete/test information.

So in effect, there are two scripts:

Action 1 for the web,

Action 2 for the emulator

The script for the terminal emulator also runs fine.

So the problem is this:
I don't want to call the Action 2 until Action 1 is complete (simple I arrange the actions in order they are to fire). → Done

However, I want the Action 2 to run off the datasheet from Action 1. I don't want to have to copy all the information manually from Action 1 to Action 2. Usually this is simple, as I can use the setRow(), getRow() methods. But the Action 2 datasheet is blank (as Action 1 has all the data). I can't run the Action 2, because there are no literation to run (again the datasheet in Action 2 is blank). QTP just reverts back to Action 1, because it thinks as there are now entries on Action 2, then Action 2 is complete.

All I want to do is associate Action 2 directly with the datasheet in Action 1. I don't want to simply extend the code to Action 1, because users will be moving consistently between Action 1 and Action 2.
So in a nut shell, is there

a code to copy all datasheet contents from Action 1 to Action 2 (but do this only once, not on every iteration) so that Action two can run on what ever row I choose from?

a simple way to associate the code of Action 2 to the Datasheet data of Action 1?

a way to use a library function file rather than action to run the datasheet information associated with  Action 1?

答: I used similar to the above. Using the datatable.getCurrentRow method allowed me to access the correct row on the second spreadsheet</p>

Title: onTestComplete function


问:
Overlay element over ContentControl's ContentPresenter
I am trying to get this seemingly simple scenario to work.
I have a ContentControl MyControl, and I would like one of it's elements to overflow on top of the ContentPresenter while remaining an element of a border.

```<code><Page
    x:Class="Playground.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Playground"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:controls="using:Playground"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Page.Resources>
        <Style TargetType="local:MyControl" >
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="local:MyControl">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="100"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>

                            <Border Grid.Row="0" BorderBrush="GreenYellow" BorderThickness="1">
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*"/>
                                        <ColumnDefinition Width="2*"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <Rectangle Grid.Column="0" Width="50" Height="50" Fill="Silver" HorizontalAlignment="Center"/>
                                    <Rectangle x:Name="Overflow" Grid.Column="1" Width="100" Height="200" Fill="Gold" HorizontalAlignment="Center"/>
                                    <Rectangle Grid.Column="2" Width="50" Height="50" Fill="Silver" HorizontalAlignment="Center"/>
                                </Grid>
                            </Border>

                            <ContentPresenter Grid.Row="1"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Page.Resources>

    <controls:MyControl Grid.Row="0" BorderBrush="Gold" BorderThickness="1">
        <Ellipse Fill="Silver"/>
    </controls:MyControl>
</Page>
</code>```

I have tried playing with Canvas.ZIndex but I cannot get this particular scenario to work. Just to re-iterate, I would like the gold rectangle to overflow over all of the content in the ContentPresenter, but I would like the border and two squares to remain as they are.

Edit: The source for this project is here if anybody s interested in playing with it.

答:
So you want the middle rectangle to be a part of your border but it should go out of the border bounds?

For this you can only use negative Margin.

In order to overlay the content you border should be the second child of the the parents Grid.

sumarizing everithing we have:

```<code><Style TargetType="local:MyControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyControl">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="100" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>

                    <ContentPresenter Grid.Row="1" />

                    <Border
                        Grid.Row="0"
                        BorderBrush="GreenYellow"
                        BorderThickness="1">
                        <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="2*" />
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>
                                <Rectangle
                                    Grid.Column="0"
                                    Width="50"
                                    Height="50"
                                    HorizontalAlignment="Center"
                                    Fill="Silver" />
                                <!--Pay attention to Margin="0,0,0,-100"-->
                                <Rectangle
                                    x:Name="Overflow"
                                    Grid.Column="1"
                                    Width="100"
                                    Height="200"
                                    Margin="0,0,0,-100"
                                    HorizontalAlignment="Center"
                                    Fill="Gold" />
                                <Rectangle
                                    Grid.Column="2"
                                    Width="50"
                                    Height="50"
                                    HorizontalAlignment="Center"
                                    Fill="Silver" />
                        </Grid>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Body:
I am trying to get this seemingly simple scenario to work.
I have a ContentControl MyControl, and I would like one of it's elements to overflow on top of the ContentPresenter while remaining an element of a border.

<Page
    x:Class="Playground.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Playground"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:controls="using:Playground"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Page.Resources>

    </Page.Resources>

    <controls:MyControl Grid.Row="0" BorderBrush="Gold" BorderThickness="1">
        <Ellipse Fill="Silver"/>
    </controls:MyControl>
</Page>

I have tried playing with Canvas.ZIndex but I cannot get this particular scenario to work. Just to re-iterate, I would like the gold rectangle to overflow over all of the content in the ContentPresenter, but I would like the border and two squares to remain as they are.

Edit: The source for this project is here if anybody s interested in playing with it.

Body:
So you want the middle rectangle to be a part of your border but it should go out of the border bounds?

For this you can only use negative Margin.

In order to overlay the content you border should be the second child of the the parents Grid.

sumarizing everithing we have:

<Style TargetType="local:MyControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyControl">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="100" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>

                    <ContentPresenter Grid.Row="1" />

                    <Border
                        Grid.Row="0"
                        BorderBrush="GreenYellow"
                        BorderThickness="1">
                        <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="2*" />
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>
                                <Rectangle
                                    Grid.Column="0"
                                    Width="50"
                                    Height="50"
                                    HorizontalAlignment="Center"
                                    Fill="Silver" />
                                <!--Pay attention to Margin="0,0,0,-100"-->
                                <Rectangle
                                    x:Name="Overflow"
                                    Grid.Column="1"
                                    Width="100"
                                    Height="200"
                                    Margin="0,0,0,-100"
                                    HorizontalAlignment="Center"
                                    Fill="Gold" />
                                <Rectangle
                                    Grid.Column="2"
                                    Width="50"
                                    Height="50"
                                    HorizontalAlignment="Center"
                                    Fill="Silver" />
                        </Grid>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


问:
Haskell remove trailing and leading whitespace from a file
Let's say I have a file

```<code>mary had a little lamb
         It's fleece was white as snow
Everywhere
    the child went
   The lamb, the lamb was sure to go, yeah
</code>```

How would I read the file as a string, and remove the trailing and leading whitespace? It could be spaces or tabs. It would print like this after removing whitespace:

```<code>mary had a little lamb
It's fleece was white as snow
Everywhere
the child went
The lamb, the lamb was sure to go, yeah
</code>```

Here's what I have currently:

```<code>import Data.Text as T

readTheFile = do
    handle <- openFile "mary.txt" ReadMode
    contents <- hGetContents handle
    putStrLn contents
    hClose handle
    return(contents)

main :: IO ()
main = do
    file <- readTheFile
    file2 <- (T.strip file)
    return()
</code>```

答:
Here is a possible solution for what you are looking for:

```<code>import qualified Data.Text as T

main = do
  trimedFile <- (T.unlines . map T.strip . T.lines) <$> T.readFile "mary.txt"
  T.putStr trimedFile
</code>```

strip from Data.Text is doing the job.

Body:
Let's say I have a file

mary had a little lamb
         It's fleece was white as snow
Everywhere
    the child went
   The lamb, the lamb was sure to go, yeah

How would I read the file as a string, and remove the trailing and leading whitespace? It could be spaces or tabs. It would print like this after removing whitespace:

mary had a little lamb
It's fleece was white as snow
Everywhere
the child went
The lamb, the lamb was sure to go, yeah

Here's what I have currently:

import Data.Text as T

readTheFile = do
    handle <- openFile "mary.txt" ReadMode
    contents <- hGetContents handle
    putStrLn contents
    hClose handle
    return(contents)

main :: IO ()
main = do
    file <- readTheFile
    file2 <- (T.strip file)
    return()

Body:
Here is a possible solution for what you are looking for:

import qualified Data.Text as T

main = do
  trimedFile <- (T.unlines . map T.strip . T.lines) <$> T.readFile "mary.txt"
  T.putStr trimedFile

strip from Data.Text is doing the job.


问:
AWS S3 copy to bucket from remote location
There is a large dataset on a public server (~0.5TB, multi-part here), which I would like to copy into my own s3 buckets. It seems like aws s3 cp is only for local files or files based in S3 buckets?

How can I copy that file (either single or multi-part) into S3? Can I use the AWS CLI or do i need to something else?

答:
There's no way to upload it directly to S3 from the remote location. But you can stream the contents of the remote files to your machine and then up to S3. This means that you will have downloaded the entire 0.5TB of data, but your computer will only ever hold a tiny fraction of that data in memory at a time (it will not be persisted to disc either). Here is a simple implementation in javascript:

const request = require('request')
const async = require('async')
const AWS = require('aws-sdk')
const s3 = new AWS.S3()
const Bucket = 'nyu_depth_v2'
const baseUrl = 'http://horatio.cs.nyu.edu/mit/silberman/nyu_depth_v2/'
const parallelLimit = 5
const parts = [
  'basements.zip',
  'bathrooms_part1.zip',
  'bathrooms_part2.zip',
  'bathrooms_part3.zip',
  'bathrooms_part4.zip',
  'bedrooms_part1.zip',
  'bedrooms_part2.zip',
  'bedrooms_part3.zip',
  'bedrooms_part4.zip',
  'bedrooms_part5.zip',
  'bedrooms_part6.zip',
  'bedrooms_part7.zip',
  'bookstore_part1.zip',
  'bookstore_part2.zip',
  'bookstore_part3.zip',
  'cafe.zip',
  'classrooms.zip',
  'dining_rooms_part1.zip',
  'dining_rooms_part2.zip',
  'furniture_stores.zip',
  'home_offices.zip',
  'kitchens_part1.zip',
  'kitchens_part2.zip',
  'kitchens_part3.zip',
  'libraries.zip',
  'living_rooms_part1.zip',
  'living_rooms_part2.zip',
  'living_rooms_part3.zip',
  'living_rooms_part4.zip',
  'misc_part1.zip',
  'misc_part2.zip',
  'office_kitchens.zip',
  'offices_part1.zip',
  'offices_part2.zip',
  'playrooms.zip',
  'reception_rooms.zip',
  'studies.zip',
  'study_rooms.zip'
]

async.eachLimit(parts, parallelLimit, (Key, cb) => {
  s3.upload({
    Key,
    Bucket,
    Body: request(baseUrl + Key)
  }, cb)
}, (err) => {
  if (err) console.error(err)
  else console.log('Done')
})
```