问:
Draw a curve line going through the blobs in OpenCV C++
I am trying to draw a line that goes through the given blobs. The following is a given example

I want a curve line that goes through multiple blobs in horizontal direction as shown below.

答:
Just for fun, and employing the Perl philosophy of TMTOWTDI ("There's More Than One Way to Do It)", I extracted all the white points of your contours into a file called points.dat and fed that into gnuplot to fit a curve, which gave me a formula for a best fit line of:

```<code>y=3.10869110524588e-07*x*x*x -0.000972406154863963*x*x + 0.861790477479291*x + 307.220397010312
</code>```

And then I plotted that in red on your original contours using awk and ImageMagick.

```<code>#!/bin/bash
convert contours.jpg -colorspace gray -threshold 50% txt: | awk -F: '/white/{print $1}' | tr ',' ' ' > points.dat
{ echo 'f(x) = a*x**3 + b*x**2 + c*x + d'; \
  echo 'fit f(x) "points.dat" via a, b, c, d'; \
  echo 'print a,"*u^3 + ",b,"*u^2 + ",c,"*u + ",d'; \
} | gnuplot 2>&1 | tail -1

awk 'BEGIN{
     for(x=0;x<1504;x++){
        y=3.10869110524588e-07*x*x*x -0.000972406154863963*x*x + 0.861790477479291*x + 307.220397010312
        y=int(y)
        print "point ",x,y
     }
     }' /dev/null > p.mvg

convert contours.jpg -draw @p.mvg z.png
</code>```

The start of points.dat looks like this:

```<code>769 453
770 453
771 453
772 453
773 453
769 454
765 455
766 455
767 455
768 455
...
...
</code>```

The start of p.mvg looks like this:

```<code>fill red
point  0 307
point  1 308
point  2 308
point  3 309
point  4 310
point  5 311
point  6 312
point  7 313
point  8 314
...
...
</code>```

Body:
Just for fun, and employing the Perl philosophy of TMTOWTDI ("There's More Than One Way to Do It)", I extracted all the white points of your contours into a file called points.dat and fed that into gnuplot to fit a curve, which gave me a formula for a best fit line of:

y=3.10869110524588e-07*x*x*x -0.000972406154863963*x*x + 0.861790477479291*x + 307.220397010312

And then I plotted that in red on your original contours using awk and ImageMagick.

#!/bin/bash
convert contours.jpg -colorspace gray -threshold 50% txt: | awk -F: '/white/{print $1}' | tr ',' ' ' > points.dat
{ echo 'f(x) = a*x**3 + b*x**2 + c*x + d'; \
  echo 'fit f(x) "points.dat" via a, b, c, d'; \
  echo 'print a,"*u^3 + ",b,"*u^2 + ",c,"*u + ",d'; \
} | gnuplot 2>&1 | tail -1

awk 'BEGIN{
     for(x=0;x<1504;x++){
        y=3.10869110524588e-07*x*x*x -0.000972406154863963*x*x + 0.861790477479291*x + 307.220397010312
        y=int(y)
        print "point ",x,y
     }
     }' /dev/null > p.mvg

convert contours.jpg -draw @p.mvg z.png

The start of points.dat looks like this:

769 453
770 453
771 453
772 453
773 453
769 454
765 455
766 455
767 455
768 455
...
...

The start of p.mvg looks like this:

fill red
point  0 307
point  1 308
point  2 308
point  3 309
point  4 310
point  5 311
point  6 312
point  7 313
point  8 314
...
...


来源: stackexchange

问:
Issue with a SELECT statement within a IN
I'm trying to select a bunch of rows from my first table depending of values from my second table.

To realize that, I came up with the following query :

```<code>SELECT *

FROM table2 t2
WHERE t2.id IN(

    SELECT subquery.id

    FROM
    (

        SELECT id

        FROM table1 t1
        WHERE (t1.property=10 AND t1.value=0)

    ) AS subquery

    INNER JOIN
    (

        SELECT id

        FROM table1 t1
        WHERE (t1.property=20 AND i.value=1)

    ) AS subquery2

    on subquery.id=subquery2.id

)
</code>```

Depending of the property and value from table1, a specific list of id will be selected to be used as a condition for the final SELECT with the table2.

The subquery in itself is working, I tested it and I could retrieve the good  id.

```<code>+------+
|  id  |
|------|
|  18  |
|  55  |
¦      ¦
</code>```

Problem is, the IN isn't working, at the end of the final SELECT I retrieved all the rows from table2 instead of the ones respecting the condition of having the same id as the subquery retrieved earlier.

```<code>+------+------+---
|  id  | name |
|------|------|---
|  1   |  xx  |
|  2   |  yy  |
¦      ¦      ¦
</code>```

So my question is :

Why is the subquery ignored in my IN statement and is there a way to bypass that problem ?

EDIT

Here is a SQLFiddle as requested, but strangely, the code I posted is working here but not for my database.

答:
try like the following; if you are having any null values in the columnn you won't get the expected result.

```<code>common_id not in
(
  select common_id from Table1
  where common_id is not null
)
</code>```

SQL "select where not in subquery" returns no results

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to select a bunch of rows from my first table depending of values from my second table.

To realize that, I came up with the following query :

SELECT *

FROM table2 t2
WHERE t2.id IN(

    SELECT subquery.id

    FROM
    (

        SELECT id

        FROM table1 t1
        WHERE (t1.property=10 AND t1.value=0)

    ) AS subquery

    INNER JOIN
    (

        SELECT id

        FROM table1 t1
        WHERE (t1.property=20 AND i.value=1)

    ) AS subquery2

    on subquery.id=subquery2.id

)

Depending of the property and value from table1, a specific list of id will be selected to be used as a condition for the final SELECT with the table2.

The subquery in itself is working, I tested it and I could retrieve the good  id.

+------+
|  id  |
|------|
|  18  |
|  55  |
¦      ¦

Problem is, the IN isn't working, at the end of the final SELECT I retrieved all the rows from table2 instead of the ones respecting the condition of having the same id as the subquery retrieved earlier.

+------+------+---
|  id  | name |
|------|------|---
|  1   |  xx  |
|  2   |  yy  |
¦      ¦      ¦

So my question is :

Why is the subquery ignored in my IN statement and is there a way to bypass that problem ?

EDIT

Here is a SQLFiddle as requested, but strangely, the code I posted is working here but not for my database.

Body:
try like the following; if you are having any null values in the columnn you won't get the expected result.

common_id not in
(
  select common_id from Table1
  where common_id is not null
)

SQL "select where not in subquery" returns no results


问:
How to insert into bigQuery partition table using nodeJS library
I have tried to specify partition decoration in form of [TABLE_ID]$YYYYMMDD when calling table.get() :

```<code>var table = dataSet.table(tableId + '$' + partition);
return table.get({autoCreate: false})
</code>```

Also I have tried specifying the configuration.load.destinationTable.tableId in same way , and it did not work.
any one have a clue on how to load to the specific partition with the nodejs biqQuery lib ?

答: to answer my own question , I found there is no need to call table.get() since I only want to use createWriteStream to load the data. I specify the partition decoration in tableId for dataset.table(tableId) and for the createWriteStream I supply the options with destinationTable.tableId with the partition decoration.</p>

Body:
I have tried to specify partition decoration in form of [TABLE_ID]$YYYYMMDD when calling table.get() :

var table = dataSet.table(tableId + '$' + partition);
return table.get({autoCreate: false})

Also I have tried specifying the configuration.load.destinationTable.tableId in same way , and it did not work.
any one have a clue on how to load to the specific partition with the nodejs biqQuery lib ?


问:
delete if key = value Groovy
I have a ruby script that I need to convert to Groovy, its a simple case of removing a collection if key: value.

So in my setup I make a request to the github api

```<code>def jsonParse(def json) {
  new groovy.json.JsonSlurperClassic().parseText(json)
}

def request = sh script: """curl https://api.github.com/repos/org/${repo}/releases?access_token=${env.TOKEN}""", returnStdout: true
def list = jsonParse(request)
return list
</code>```

This returns output like so

```<code>[
  [prerelease: 'true', author: [surname: 'surname', book: 'title'], surname: 'surname'],
  [prerelease: 'false', author: [surname: 'surname', book: 'title'], surname: 'surname']
]
</code>```

In Ruby i would do the following

```<code>array.delete_if { |key| key['prerelease'] == true }
</code>```

How would I approach this with Groovy, if an explanation could be provided that would also be great so i can learn from it

Update

Using the approach from @Rao my list is exactly the same

```<code>def request = sh script: """curl https://api.github.com/repos/org/${repo}/releases?access_token=${env.TOKEN}""", returnStdout: true
def list = jsonParse(request)
list.removeAll(list.findAll{it.prerelease == 'true'})
return list
</code>```

Raw response

```<code>[
  {"prerelease": true, "author": [ {"surname": "surname", "book": "title"}, "surname": "surname"],
  {"prerelease": false, "author": [ {"surname": "surname", "book": "title"}, "surname": "surname"]
]
</code>```

答:
The sample data is list of maps.

Need to remove the items from the list by filtering prerelease is equal to true. Hope this is string only as embedded between the quotes.

Here is the script which results filtered list.

```<code>def list = [
  [prerelease: 'true', author: [surname: 'surname', book: 'title'], surname: 'surname'],
  [prerelease: 'true', author: [surname: 'surname', book: 'title'], surname: 'surname'],
  [prerelease: 'false', author: [surname: 'surname', book: 'title'], surname: 'surname']
]

//Remove all those elements(map) from list if matching the condition
list.removeAll(list.findAll{it.prerelease == 'true'})

//Show the updated list
println list
</code>```

You can quickly try it online Demo

EDIT: based on OP comment.

Isn't this below output what you want?

EDIT2: Based on OP changed response as Json

```<code>def json = """[
  {"prerelease": true, "author": [ {"surname": "surname", "book": "title"}]},
  {"prerelease": false, "author": [ {"surname": "surname", "book": "title"}]}
]"""
list = new groovy.json.JsonSlurper().parseText(json)
println new groovy.json.JsonBuilder(list.findAll{ it.prerelease != true }).toPrettyString()
</code>```

Title: delete if key = value Groovy

Body:
I have a ruby script that I need to convert to Groovy, its a simple case of removing a collection if key: value.

So in my setup I make a request to the github api

def jsonParse(def json) {
  new groovy.json.JsonSlurperClassic().parseText(json)
}

def request = sh script: """curl https://api.github.com/repos/org/${repo}/releases?access_token=${env.TOKEN}""", returnStdout: true
def list = jsonParse(request)
return list

This returns output like so

[
  [prerelease: 'true', author: [surname: 'surname', book: 'title'], surname: 'surname'],
  [prerelease: 'false', author: [surname: 'surname', book: 'title'], surname: 'surname']
]

In Ruby i would do the following

array.delete_if { |key| key['prerelease'] == true }

How would I approach this with Groovy, if an explanation could be provided that would also be great so i can learn from it

Update

Using the approach from @Rao my list is exactly the same

def request = sh script: """curl https://api.github.com/repos/org/${repo}/releases?access_token=${env.TOKEN}""", returnStdout: true
def list = jsonParse(request)
list.removeAll(list.findAll{it.prerelease == 'true'})
return list

Raw response

[
  {"prerelease": true, "author": [ {"surname": "surname", "book": "title"}, "surname": "surname"],
  {"prerelease": false, "author": [ {"surname": "surname", "book": "title"}, "surname": "surname"]
]

Body:
The sample data is list of maps.

Need to remove the items from the list by filtering prerelease is equal to true. Hope this is string only as embedded between the quotes.

Here is the script which results filtered list.

def list = [
  [prerelease: 'true', author: [surname: 'surname', book: 'title'], surname: 'surname'],
  [prerelease: 'true', author: [surname: 'surname', book: 'title'], surname: 'surname'],
  [prerelease: 'false', author: [surname: 'surname', book: 'title'], surname: 'surname']
]

//Remove all those elements(map) from list if matching the condition
list.removeAll(list.findAll{it.prerelease == 'true'})

//Show the updated list
println list

You can quickly try it online Demo

EDIT: based on OP comment.

Isn't this below output what you want?

EDIT2: Based on OP changed response as Json

def json = """[
  {"prerelease": true, "author": [ {"surname": "surname", "book": "title"}]},
  {"prerelease": false, "author": [ {"surname": "surname", "book": "title"}]}
]"""
list = new groovy.json.JsonSlurper().parseText(json)
println new groovy.json.JsonBuilder(list.findAll{ it.prerelease != true }).toPrettyString()


问:
Jquery - optgroup hide() does not refresh the dropdown until clicked
I am trying to hide an optgroup in a dropdown based on the value selected from a radio button. It all works fine except the dropdown does not get refreshed immediately (it may already have a preselected value from earlier, irrespective of the optgroup it falls in).

```<code>$('input[id*="school_type"]').on("change",function(){
        if ($(this).is(':checked')) {
          var selectedVal=($(this).next().text());
          $("#id_school_sub_type > optgroup").hide();
          $('#id_school_sub_type > optgroup[label="'+selectedVal+'"]').show();
        }
    });
</code>```

JS Fiddle

The optgroup is hidden or shown only when the user clicks on the subsequent dropdown. Is it possible to "refresh" it immediately?

答:
Remove selection of that item before hide:

```<code>$('input[id*="school_type"]').on("change",function(){
    if ($(this).is(':checked')) {
      var selectedVal=($(this).next().text()); // using next() so we can get the verbose value from the <span> next to <input>
      $("#id_school_sub_type").val('');
      $("#id_school_sub_type > optgroup").hide();
      $('#id_school_sub_type > optgroup[label="'+selectedVal+'"]').show();
    }
});
</code>```

Add following line if want to made selection too:

```<code>$("#id_school_sub_type").val($('#id_school_sub_type optgroup[label="'+selectedVal+'"] option:first').val());
</code>```

Fiddle

Body:
I am trying to hide an optgroup in a dropdown based on the value selected from a radio button. It all works fine except the dropdown does not get refreshed immediately (it may already have a preselected value from earlier, irrespective of the optgroup it falls in).

$('input[id*="school_type"]').on("change",function(){
        if ($(this).is(':checked')) {
          var selectedVal=($(this).next().text());
          $("#id_school_sub_type > optgroup").hide();
          $('#id_school_sub_type > optgroup[label="'+selectedVal+'"]').show();
        }
    });

JS Fiddle

The optgroup is hidden or shown only when the user clicks on the subsequent dropdown. Is it possible to "refresh" it immediately?

Body:
Remove selection of that item before hide:

$('input[id*="school_type"]').on("change",function(){
    if ($(this).is(':checked')) {
      var selectedVal=($(this).next().text()); // using next() so we can get the verbose value from the <span> next to <input>
      $("#id_school_sub_type").val('');
      $("#id_school_sub_type > optgroup").hide();
      $('#id_school_sub_type > optgroup[label="'+selectedVal+'"]').show();
    }
});

Add following line if want to made selection too:

$("#id_school_sub_type").val($('#id_school_sub_type optgroup[label="'+selectedVal+'"] option:first').val());

Fiddle


问:
Why does my app crash on iOS 10 when repeatedly presenting and using UIImagePickerControllers?
An app that we developed several years ago has started crashing since iOS 10 became available. The app repeatedly presents UIImagePickerControllers to allow a user to capture several photos of a subject. After doing this 40+ times, the app crashes. This is reproducible on all of the devices we've tested on, but did not happen prior to the introduction of iOS 10. We do have the NSCameraUsageDescription and NSPhotoLibraryUsageDescription keys in the Info.plist file.

I've created a minimal sample app that demonstrates the problem. Here's the code that eventually results in the crash:

```<code>- (IBAction) cameraPressed:(id) sender {
    self.picker = [[UIImagePickerController alloc] init];
    self.picker.sourceType =  UIImagePickerControllerSourceTypeCamera;
    self.picker.delegate = self;
    self.picker.allowsEditing = NO;
    [self presentViewController:self.picker animated:YES completion:nil];
}
</code>```

When the user repeatedly uses the camera button that is connected to this IBAction, it eventually starts to slow down (presentation of the picker begins taking longer), and eventually crashes (usually after 50+ uses of the camera). No crash log is produced, although when connected to Xcode, output like this appears in the console leading up to the crash:

```<code>2016-11-04 20:30:11.884984 WLPBeta[2747:275474] [MC] Invalidating cache
2016-11-04 20:30:11.890776 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:30:13.017608 WLPBeta[2747:275091] [MC] Invalidating cache
2016-11-04 20:30:13.018312 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:30:19.271720 WLPBeta[2747:276311] [MC] Invalidating cache
2016-11-04 20:30:19.279462 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:08.229294 WLPBeta[2747:278515] [MC] Invalidating cache
2016-11-04 20:32:08.273941 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:09.335711 WLPBeta[2747:278514] [MC] Invalidating cache
2016-11-04 20:32:09.342161 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:14.193376 WLPBeta[2747:278515] [MC] Invalidating cache
2016-11-04 20:32:14.213902 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:47.944657 WLPBeta[2747:275091] [MC] Invalidating cache
2016-11-04 20:32:47.972053 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:48.550934 WLPBeta[2747:279485] [MC] Invalidating cache
2016-11-04 20:32:48.575065 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:50.855308 WLPBeta[2747:279485] [MC] Invalidating cache
2016-11-04 20:32:50.856329 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:52.201535 WLPBeta[2747:275091] [GatekeeperXPC] Connection to assetsd was interrupted or assetsd died
</code>```

I've also posted a bug report to Apple, and added it to open radar: http://www.openradar.me/radar?id=4941109843197952

Has anyone encountered this issue? Is there a fix that would allow us to move past this without recompiling the app using Xcode 8? Unfortunately we are using third party libraries that are not yet ready for Xcode 8 and the iOS 10 SDK, so we are still building the app using Xcode 7.3.1.

EDIT: here's a link to a Github repo containing an example app that can be used to demonstrate the problem.

https://github.com/lolay/ImagePickerTest

EDIT 2: If I change the code so that I allocate and initialize the picker in viewDidLoad, it still crashes after about the same number of uses of the camera button.

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    self.picker = [[UIImagePickerController alloc] init];
    self.picker.sourceType =  UIImagePickerControllerSourceTypeCamera;
    self.picker.allowsEditing = NO;
}

- (IBAction) cameraPressed:(id) sender {
    [self presentViewController:self.picker animated:YES completion:nil];
}
</code>```

答:
Have you tried declaring the Imagepicker variable inside the cameraPressed() function</p>

```<code>- (IBAction) cameraPressed:(id) sender {
   UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType =  UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    picker.allowsEditing = NO;
    [self presentViewController:self.picker animated:YES completion:nil];
}
</code>```

Body:
An app that we developed several years ago has started crashing since iOS 10 became available. The app repeatedly presents UIImagePickerControllers to allow a user to capture several photos of a subject. After doing this 40+ times, the app crashes. This is reproducible on all of the devices we've tested on, but did not happen prior to the introduction of iOS 10. We do have the NSCameraUsageDescription and NSPhotoLibraryUsageDescription keys in the Info.plist file.

I've created a minimal sample app that demonstrates the problem. Here's the code that eventually results in the crash:

- (IBAction) cameraPressed:(id) sender {
    self.picker = [[UIImagePickerController alloc] init];
    self.picker.sourceType =  UIImagePickerControllerSourceTypeCamera;
    self.picker.delegate = self;
    self.picker.allowsEditing = NO;
    [self presentViewController:self.picker animated:YES completion:nil];
}

When the user repeatedly uses the camera button that is connected to this IBAction, it eventually starts to slow down (presentation of the picker begins taking longer), and eventually crashes (usually after 50+ uses of the camera). No crash log is produced, although when connected to Xcode, output like this appears in the console leading up to the crash:

2016-11-04 20:30:11.884984 WLPBeta[2747:275474] [MC] Invalidating cache
2016-11-04 20:30:11.890776 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:30:13.017608 WLPBeta[2747:275091] [MC] Invalidating cache
2016-11-04 20:30:13.018312 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:30:19.271720 WLPBeta[2747:276311] [MC] Invalidating cache
2016-11-04 20:30:19.279462 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:08.229294 WLPBeta[2747:278515] [MC] Invalidating cache
2016-11-04 20:32:08.273941 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:09.335711 WLPBeta[2747:278514] [MC] Invalidating cache
2016-11-04 20:32:09.342161 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:14.193376 WLPBeta[2747:278515] [MC] Invalidating cache
2016-11-04 20:32:14.213902 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:47.944657 WLPBeta[2747:275091] [MC] Invalidating cache
2016-11-04 20:32:47.972053 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:48.550934 WLPBeta[2747:279485] [MC] Invalidating cache
2016-11-04 20:32:48.575065 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:50.855308 WLPBeta[2747:279485] [MC] Invalidating cache
2016-11-04 20:32:50.856329 WLPBeta[2747:273019] [MC] Reading from public effective user settings.
2016-11-04 20:32:52.201535 WLPBeta[2747:275091] [GatekeeperXPC] Connection to assetsd was interrupted or assetsd died

I've also posted a bug report to Apple, and added it to open radar: http://www.openradar.me/radar?id=4941109843197952

Has anyone encountered this issue? Is there a fix that would allow us to move past this without recompiling the app using Xcode 8? Unfortunately we are using third party libraries that are not yet ready for Xcode 8 and the iOS 10 SDK, so we are still building the app using Xcode 7.3.1.

EDIT: here's a link to a Github repo containing an example app that can be used to demonstrate the problem.

https://github.com/lolay/ImagePickerTest

EDIT 2: If I change the code so that I allocate and initialize the picker in viewDidLoad, it still crashes after about the same number of uses of the camera button.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.picker = [[UIImagePickerController alloc] init];
    self.picker.sourceType =  UIImagePickerControllerSourceTypeCamera;
    self.picker.allowsEditing = NO;
}

- (IBAction) cameraPressed:(id) sender {
    [self presentViewController:self.picker animated:YES completion:nil];
}

Body:
Have you tried declaring the Imagepicker variable inside the cameraPressed() function

- (IBAction) cameraPressed:(id) sender {
   UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType =  UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    picker.allowsEditing = NO;
    [self presentViewController:self.picker animated:YES completion:nil];
}


问:
Expand outer nested div to 100%
I have this code

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
</div></code>```

https://jsfiddle.net/jcb5mdqa/

It looks like

but I want the outer to have a width of 100% like in .css written.

Expected result

What do I need to change?

答:
Use clearfix

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;

}
.clearfix:after {
  content: "";
  display: table;
  clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer clearfix">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
</div></code>```

Title: Expand outer nested div to 100%

Body:
I have this code

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;

}

    test1
 test1

    test2
 test2

https://jsfiddle.net/jcb5mdqa/

It looks like

but I want the outer to have a width of 100% like in .css written.

Expected result

What do I need to change?

Body:
Use clearfix

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;

}
.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

<div class="outer clearfix">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
</div>


问:
D3.js v3 to v4 Brush changes
I'm looking to migrate from d3v3 to d3v4.
In particular i'm having difficulties in migrating brushes.

Can someone please have a look at below link and let me know the changes?
http://bl.ocks.org/zanarmstrong/ddff7cd0b1220bc68a58

Some changes i have identified:

d3.time.format -> d3.timeFormat

d3.time.scale -> d3.scaleTime

Facing issues in migrating:

d3.svg.brush -> d3.brushX

Thanks & Regards,

Naishav

答:
Quick guide for migrating d3-brush from D3 v3 to D3 v4 (example for brushX)

Replace d3.svg.brush() with d3.brushX().

Rename brushstart event to start, brushend to end.

Don't pass scale to .x(xScale), this method is now missing. Pass brush borders as .extent([[xScale.range()[0], 0], [xScale.range()[1], brushHeight]]).

In event handler you can get selection as d3.event.selection, for getting selected values use d3.event.selection.map(xScale.invert).

To setup selection do .move(brushContainer, selectedDomain.map(xScale)). To clear selection do .move(brushContainer, null). Note that this will fire event handlers.

.empty() method is now missing, use d3.event.selection === null.

Update your CSS, .extent is now .selection, .resize is .handle and became a rect instead of g containing rect.

Title: D3.js v3 to v4 Brush changes


问:
How do I capture a GTK window and write it to a PNG file?
Here's what I tried:

```<code>#include <gtk/gtk.h>

static GtkWidget *window, *drawing_area;

static gboolean drawCallback(GtkWidget *widget, cairo_t *cr, gpointer arg) {

    cairo_set_source_rgb(cr, 1.0, 0, 0);
    cairo_arc(cr, 200.0, 150.0, 50.0, 0, 2*G_PI);
    cairo_fill(cr);
}

static gboolean savePNG(gpointer arg) {

    cairo_surface_t *surface = cairo_image_surface_create(
        CAIRO_FORMAT_RGB24, 400, 300
    );
    cairo_t *cr = cairo_create(surface);

    gdk_cairo_set_source_window(
        cr,
        gtk_widget_get_window(GTK_WIDGET(window)),
        0, 0
    );

    printf("cairo_status(cr): %s\ncairo_surface_status(surface): %s\n",
        cairo_status_to_string(cairo_status(cr)),
        cairo_status_to_string(cairo_surface_status(surface)));

    cairo_surface_write_to_png(surface, "test.png");
}

static void app_activate(GtkApplication *app, gpointer user_data) {

    window = gtk_application_window_new(app);
    gtk_window_set_title(GTK_WINDOW(window), "Sandbox");
    gtk_widget_set_size_request(GTK_WIDGET(window), 400, 300);
    gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);

    drawing_area = gtk_drawing_area_new();
    gtk_container_add(GTK_CONTAINER(window), drawing_area);
    g_signal_connect(G_OBJECT(drawing_area), "draw", G_CALLBACK(drawCallback), NULL);

    gtk_widget_show_all(window);
    gtk_window_move(GTK_WINDOW(window), 10, 10);
}

int main(int argc, char **argv) {

    GtkApplication *app;
    int status;

    app = gtk_application_new("the.application.id", G_APPLICATION_FLAGS_NONE);
    g_signal_connect(app, "activate", G_CALLBACK(app_activate), NULL);

    g_timeout_add(1000, savePNG, NULL);

    status = g_application_run(G_APPLICATION(app), argc, argv);

    g_object_unref(app);
    return status;
}
</code>```

The window shows a red circle, but the test.png file that is created contains an all black image.

Here's the output:

```<code>cairo_status(cr): no error has occurred
cairo_surface_status(surface): no error has occurred
</code>```

This answer suggested the pattern that I used.

答:
You forgot to paint anything into your surface before saving.

```<code>static gboolean savePNG(gpointer arg)
{
  cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_RGB24, 300, 200);  // <<= Reduced size to get only a part of the window.
  cairo_t *cr = cairo_create(surface);

  cairo_translate(cr, -50.0, -50.0);  // <<= Move the part we want to copy from source into position....

  gdk_cairo_set_source_window(
      cr,
      gtk_widget_get_window(GTK_WIDGET(window)),
      0, 0
  );
  cairo_paint(cr);  // <<= DO IT! ;)
  cairo_surface_write_to_png(surface, "test.png");
}
</code>```

EDIT:

I updated the code to only copy a part of the window to the file.
You need to move the source to the new starting point of your desired part of the window. Of course then your surface also needs to be smaller.

Body:
Here's what I tried:

#include <gtk/gtk.h>

static GtkWidget *window, *drawing_area;

static gboolean drawCallback(GtkWidget *widget, cairo_t *cr, gpointer arg) {

    cairo_set_source_rgb(cr, 1.0, 0, 0);
    cairo_arc(cr, 200.0, 150.0, 50.0, 0, 2*G_PI);
    cairo_fill(cr);
}

static gboolean savePNG(gpointer arg) {

    cairo_surface_t *surface = cairo_image_surface_create(
        CAIRO_FORMAT_RGB24, 400, 300
    );
    cairo_t *cr = cairo_create(surface);

    gdk_cairo_set_source_window(
        cr,
        gtk_widget_get_window(GTK_WIDGET(window)),
        0, 0
    );

    printf("cairo_status(cr): %s\ncairo_surface_status(surface): %s\n",
        cairo_status_to_string(cairo_status(cr)),
        cairo_status_to_string(cairo_surface_status(surface)));

    cairo_surface_write_to_png(surface, "test.png");
}

static void app_activate(GtkApplication *app, gpointer user_data) {

    window = gtk_application_window_new(app);
    gtk_window_set_title(GTK_WINDOW(window), "Sandbox");
    gtk_widget_set_size_request(GTK_WIDGET(window), 400, 300);
    gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);

    drawing_area = gtk_drawing_area_new();
    gtk_container_add(GTK_CONTAINER(window), drawing_area);
    g_signal_connect(G_OBJECT(drawing_area), "draw", G_CALLBACK(drawCallback), NULL);

    gtk_widget_show_all(window);
    gtk_window_move(GTK_WINDOW(window), 10, 10);
}

int main(int argc, char **argv) {

    GtkApplication *app;
    int status;

    app = gtk_application_new("the.application.id", G_APPLICATION_FLAGS_NONE);
    g_signal_connect(app, "activate", G_CALLBACK(app_activate), NULL);

    g_timeout_add(1000, savePNG, NULL);

    status = g_application_run(G_APPLICATION(app), argc, argv);

    g_object_unref(app);
    return status;
}

The window shows a red circle, but the test.png file that is created contains an all black image.

Here's the output:

cairo_status(cr): no error has occurred
cairo_surface_status(surface): no error has occurred

This answer suggested the pattern that I used.

Body:
You forgot to paint anything into your surface before saving.

static gboolean savePNG(gpointer arg)
{
  cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_RGB24, 300, 200);  // <<= Reduced size to get only a part of the window.
  cairo_t *cr = cairo_create(surface);

  cairo_translate(cr, -50.0, -50.0);  // <<= Move the part we want to copy from source into position....

  gdk_cairo_set_source_window(
      cr,
      gtk_widget_get_window(GTK_WIDGET(window)),
      0, 0
  );
  cairo_paint(cr);  // <<= DO IT! ;)
  cairo_surface_write_to_png(surface, "test.png");
}

EDIT:

I updated the code to only copy a part of the window to the file.
You need to move the source to the new starting point of your desired part of the window. Of course then your surface also needs to be smaller.


问:
Overriding css only visible on some pages
our site has a stylesheet.css and a custom.css - on our platform, I only have access to the custom.css.

I have some overrides in the custom.css, but they only show on some pages.

See http://www.daysjewelers.com (background, etc. controlled by custom.css)
see http://www.daysjewelers.com/category/engagement_rings_and_wedding_rings.do and the css overrides are not there.

Here are the overrides:

```<code>body.main {
background: #fff url(http://www.daysjewelers.com/images/en_US/global/globalgraphics/main_bg.gif) repeat;
}

.mainLayoutTable {
background: #fff;
padding: 10px;
border: 1px dashed #c0ddea;
margin-top: 15px;
}
</code>```

and I have refreshed my browser cache, thoughts?

答: Jason, I'm noticing that in the second page that isn't working correctly - the generated source (using Firebug) reports the as having additional attributes - like bgcolor, right on the tag. I'm not really sure where that's coming from. Also if you are trying to overwrite attributes from the other template, you might consider adding !important on the declarations to ensure the attribute you want takes priority.</p>

ContentLicense: CC BY-SA 2.5

Body:
our site has a stylesheet.css and a custom.css - on our platform, I only have access to the custom.css.

I have some overrides in the custom.css, but they only show on some pages.

See http://www.daysjewelers.com (background, etc. controlled by custom.css)
see http://www.daysjewelers.com/category/engagement_rings_and_wedding_rings.do and the css overrides are not there.

Here are the overrides:

body.main {
background: #fff url(http://www.daysjewelers.com/images/en_US/global/globalgraphics/main_bg.gif) repeat;
}

.mainLayoutTable {
background: #fff;
padding: 10px;
border: 1px dashed #c0ddea;
margin-top: 15px;
}

and I have refreshed my browser cache, thoughts?


问:
FormatException using WebClient to upload to FTP
When using WebClient I can specify a URL as the address when connecting to an FTP server, but when specifying an IP address it throws a FormatException inside mscorlib. Basically, to demonstrate:

```<code>using (WebClient client = new WebClient())
{
    client.UploadFile("ftp://localhost/test.dat", "STOR", "test.dat"); // No exception
    client.UploadFile("ftp://127.0.0.1/test.dat", "STOR", "test.dat"); // FormatException
}
</code>```

The exception detail says "Input string was not in a correct format" and claims to be coming from System.Number.StringToNumber

I have tried it with and without the ":21" port number, but it makes no difference.

How can I use an IP Address with the WebClient class to upload a file to an FTP server?

答: The issue was with the FTP server being used. Smallftpd returns non-compliant responses which fail to be parsed by WebClient, resulting in obscure number conversion errors. The answer was to switch to a different server software.</p>

Body:
When using WebClient I can specify a URL as the address when connecting to an FTP server, but when specifying an IP address it throws a FormatException inside mscorlib. Basically, to demonstrate:

using (WebClient client = new WebClient())
{
    client.UploadFile("ftp://localhost/test.dat", "STOR", "test.dat"); // No exception
    client.UploadFile("ftp://127.0.0.1/test.dat", "STOR", "test.dat"); // FormatException
}

The exception detail says "Input string was not in a correct format" and claims to be coming from System.Number.StringToNumber

I have tried it with and without the ":21" port number, but it makes no difference.

How can I use an IP Address with the WebClient class to upload a file to an FTP server?


问:
ios youtube embedded video frame issue
I am trying to embed a video from youtube with the following code:

```<code>func setUpVideo() {
    let width = webView.frame.width
    let height = webView.frame.height
    let frame = 0
    bmiWebView.allowsInlineMediaPlayback = true
    let videoUrl = "https://www.youtube.com/embed/GCALWdwKr48"
    let htmlUrl = "<html><body><iframe width=\(width) height=\(height) src=\(videoUrl)?&playsinline = 1 frameborder=\(frame) allowfullscreen></iframe></body></html>"
    webView.loadHTMLString(htmlUrl, baseURL: NSBundle.mainBundle().bundleURL)
}
</code>```

I'm able to load the video initially with white background but when it loads it looks like below. I'm not sure why there is a white background. If someone can tell me how to remove that will be really helpful. Thank you.

答:
The white background is the margin on the body of the HTML of your UIWebView.

Add some CSS to set the margin to 0 like so:

```

Title: ios youtube embedded video frame issue

Body:
I am trying to embed a video from youtube with the following code:

func setUpVideo() {
    let width = webView.frame.width
    let height = webView.frame.height
    let frame = 0
    bmiWebView.allowsInlineMediaPlayback = true
    let videoUrl = "https://www.youtube.com/embed/GCALWdwKr48"
    let htmlUrl = ""
    webView.loadHTMLString(htmlUrl, baseURL: NSBundle.mainBundle().bundleURL)
}

I'm able to load the video initially with white background but when it loads it looks like below. I'm not sure why there is a white background. If someone can tell me how to remove that will be really helpful. Thank you.

Body:
The white background is the margin on the body of the HTML of your UIWebView.

Add some CSS to set the margin to 0 like so:

<html>
<head>
<style>body{margin:0px;}</style>
</head>
<body>
<iframe width=\(width) height=\(height) src=\(videoUrl)?&playsinline = 1 frameborder=\(frame) allowfullscreen></iframe>
</body>
</html>


问:
Class with two constructors taking different objects as parents
I want to create a new class, which has to be able to take two different types of objects (with nearly the same functions and variables). I am trying to use two constructors for this. Since both possible argument classes have nearly the same variables in them, I want to refer to them with the same variable named parent.

What I tried:

class Segment{
  float phi;
  float theta;
  float len;
  Base parent;
  Segment parent;

  public Segment(Base parent, float len, float phi, float theta) {
    this.len = len;
    this.phi = phi;
    this.theta = theta;

    this.parent = parent;
  }

  public Segment(Segment parent, float len, float phi, float theta) {
    this.len = len;
    this.phi = phi;
    this.theta = theta;

    this.parent = parent;
  }

  // ... functions calling parent.variableName
}
```

This is not possible because parent is a duplicate, what would be a way to solve this?

Edit

The only thing Segment and Base have in common are some variables telling the start end end points, to connect new Segments to.
Other than that the Base is standing still, and the Segment's are moving

答: Let base and segment implement the same interface. Now change the parent's  type to that interface (and remove the other parent field)</p>

Body:
I want to create a new class, which has to be able to take two different types of objects (with nearly the same functions and variables). I am trying to use two constructors for this. Since both possible argument classes have nearly the same variables in them, I want to refer to them with the same variable named parent.

What I tried:

class Segment{
  float phi;
  float theta;
  float len;
  Base parent;
  Segment parent;

  public Segment(Base parent, float len, float phi, float theta) {
    this.len = len;
    this.phi = phi;
    this.theta = theta;

    this.parent = parent;
  }

  public Segment(Segment parent, float len, float phi, float theta) {
    this.len = len;
    this.phi = phi;
    this.theta = theta;

    this.parent = parent;
  }

  // ... functions calling parent.variableName
}

This is not possible because parent is a duplicate, what would be a way to solve this?

Edit

The only thing Segment and Base have in common are some variables telling the start end end points, to connect new Segments to.
Other than that the Base is standing still, and the Segment's are moving


问:
Hide login/register button when logged in and hide logout button when logged out
i'm kinda new in PHP and I have some issues. When I'm logged in on my website I want to hide the 'Login' and 'Register' button, and when I'm logged out I want to hide the 'logout' button.

This is my login.php page:

```<code><?php
    include "navbar.php";
?>
<?php
    include_once "check.php";

    $error = ""; //Variable for storing our errors.
    if(isset($_POST["submit"]))
    {
        if(empty($_POST["username"]) || empty($_POST["password"]))
        {
            $error = "Both fields are required.";
        }else
        {
            // Define $username and $password
            $username=$_POST['username'];
            $password=$_POST['password'];

            // To protect from MySQL injection
            $username = stripslashes($username);
            $password = stripslashes($password);
            $username = mysqli_real_escape_string($db, $username);
            $password = mysqli_real_escape_string($db, $password);
            $password = md5($password);

            //Check username and password from database
            $sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
            $result=mysqli_query($db,$sql);
            $row=mysqli_fetch_array($result,MYSQLI_ASSOC);

            //If username and password exist in our database then create a session.
            //Otherwise echo error.

            if(mysqli_num_rows($result) == 1)
            {
                $_SESSION['username'] = $username;
                header("location: index.php");
            }else
            {
                $error = "Incorrect username or password.";
            }

        }
    }

?>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="assets/css/acc.css">
        <link rel="stylesheet" type="text/css" href="assets/css/acc2.css">
        <link rel="stylesheet" type="text/css" href="assets/css/navbar.css">
        <title>Login | Peerbolte-ICT</title>
    </head>
    </body>
        <section>
        <p style="color:red;"><?php echo $error; ?> </p>
            <form method="POST" action="">
                <div class="accPanel">
                <h1 style="color: black; padding-bottom: 5%;">Login</h1>
                <form method="POST" action="">
                    <div class="login-input">
                        <label class="accLabel"><b>Username<span style="color:red;">*</span></b></label>
                        <input type="text" placeholder="Enter Username" name="username" required>

                        <label class="accLabel"><b>Password<span style="color:red;">*</span></b></label>
                        <input type="password" placeholder="Enter Password" name="password" required>

                        <button class="submitButton" type="submit" name="submit">Login</button>
                    </div>
                </form>
            </div>
        </section>
    </body>
</html>
</code>```

And this is my navbar.php where the buttons are:

```<code><ul>
  <li><a href="index.php">Home</a></li>
  <li><a href="#bannerTwo">Services</a></li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Our Work</a>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Account</a>
    <div class="dropdown-content">
      <a href="login.php">Login</a>
      <a href="register.php">Register</a>
      <a href="logout.php">Logout</a>
    </div>
  </li>
</ul>
</code>```

Thanks

答:
You can try something like this:</p>

```<code>    <?php if (isset($_SESSION['username']) && empty($error): ?>

        here you display your logout button

   <?php else: ?>

        display login button

   <?php endif; ?>
</code>```

Body:
i'm kinda new in PHP and I have some issues. When I'm logged in on my website I want to hide the 'Login' and 'Register' button, and when I'm logged out I want to hide the 'logout' button.

This is my login.php page:

<?php
    include "navbar.php";
?>
<?php
    include_once "check.php";

    $error = ""; //Variable for storing our errors.
    if(isset($_POST["submit"]))
    {
        if(empty($_POST["username"]) || empty($_POST["password"]))
        {
            $error = "Both fields are required.";
        }else
        {
            // Define $username and $password
            $username=$_POST['username'];
            $password=$_POST['password'];

            // To protect from MySQL injection
            $username = stripslashes($username);
            $password = stripslashes($password);
            $username = mysqli_real_escape_string($db, $username);
            $password = mysqli_real_escape_string($db, $password);
            $password = md5($password);

            //Check username and password from database
            $sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
            $result=mysqli_query($db,$sql);
            $row=mysqli_fetch_array($result,MYSQLI_ASSOC);

            //If username and password exist in our database then create a session.
            //Otherwise echo error.

            if(mysqli_num_rows($result) == 1)
            {
                $_SESSION['username'] = $username;
                header("location: index.php");
            }else
            {
                $error = "Incorrect username or password.";
            }

        }
    }

?>

        <link rel="stylesheet" type="text/css" href="assets/css/acc.css">
        <link rel="stylesheet" type="text/css" href="assets/css/acc2.css">
        <link rel="stylesheet" type="text/css" href="assets/css/navbar.css">
        <title>Login | Peerbolte-ICT</title>

<?php echo $error; ?>

            <form method="POST" action="">

Login

                <form method="POST" action="">

                        Username*
                        <input type="text" placeholder="Enter Username" name="username" required>

                        Password*
                        <input type="password" placeholder="Enter Password" name="password" required>

                        <button class="submitButton" type="submit" name="submit">Login</button>

                </form>

And this is my navbar.php where the buttons are:

Home

Services

    Our Work

      Link 1
      Link 2
      Link 3

    Account

      Login
      Register
      Logout

Thanks

Body:
You can try something like this:

    <?php if (isset($_SESSION['username']) && empty($error): ?>

        here you display your logout button

   <?php else: ?>

        display login button

   <?php endif; ?>


问:
Converting a date to a (non human-readable) string in Swift 3
I have a Date object, like so:

```<code> 2017-06-08 08:36:16 +0000
</code>```

I need to convert this to a string, in this form:

```<code>"2017-06-08T08:36:16Z"
</code>```

The REST api I am posting to only accepts dates as strings.

Most info I find online is about converting dates to human readable formats. If possible, I could probably even just "stringify" my date object, however trying to cast it as such obviously fails. There are tons of "convert date to string" questions out there, but haven't ran across any like this yet.

Any idea how to do this?

答:
All you have to do is changing the date format (DateFormatter) to the desired one.

Note that the format of your given date (2017-06-08 08:36:16 +0000) is:

yyyy-MM-dd HH:mm:ss Z

For instance, consider that the given date value is today, you could read it -as a string- like this:

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"

let givenDate = Date()
let stringGivenDate = dateFormatter.string(from: givenDate) // 2017-06-08 12:10:23 +0300
</code>```

thus, changing the date format to:

```<code>dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:SS'Z'"
let stringGivenDateWithDesiredFormat = dateFormatter.string(from: givenDate) // 2017-06-08T12:11:75Z
</code>```

As per the code snippet above, your given desired format (2017-06-08T08:36:16Z) is:

yyyy-MM-dd'T'HH:mm:SS'Z'

Body:
I have a Date object, like so:

 2017-06-08 08:36:16 +0000

I need to convert this to a string, in this form:

"2017-06-08T08:36:16Z"

The REST api I am posting to only accepts dates as strings.

Most info I find online is about converting dates to human readable formats. If possible, I could probably even just "stringify" my date object, however trying to cast it as such obviously fails. There are tons of "convert date to string" questions out there, but haven't ran across any like this yet.

Any idea how to do this?

Body:
All you have to do is changing the date format (DateFormatter) to the desired one.

Note that the format of your given date (2017-06-08 08:36:16 +0000) is:

yyyy-MM-dd HH:mm:ss Z

For instance, consider that the given date value is today, you could read it -as a string- like this:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"

let givenDate = Date()
let stringGivenDate = dateFormatter.string(from: givenDate) // 2017-06-08 12:10:23 +0300

thus, changing the date format to:

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:SS'Z'"
let stringGivenDateWithDesiredFormat = dateFormatter.string(from: givenDate) // 2017-06-08T12:11:75Z

As per the code snippet above, your given desired format (2017-06-08T08:36:16Z) is:

yyyy-MM-dd'T'HH:mm:SS'Z'


问:
how to get rid of Unsupported module in scripts: http for jsreport
```<code>Error occured - Error during rendering report: Unsupported module in scripts: http. To enable require on particular module, you need to update the configuration as {"scripts": { "allowedModules": ["http"] } } ... Alternatively you can also set "*" to allowedModules to enable everything
</code>```

Stak - Error: Unsupported module in scripts: http. To enable require on particular module, you need to update the configuration as {"scripts": { "allowedModules": ["http"] } } ... Alternatively you can also set "*" to allowedModules to enable everything
    at _require (/Users/ravikirankk/Projects/I-Team/srdm/jsreport/node_modules/jsreport-scripts/lib/scriptEvalChild.js:44:11)
    at evalmachine.:2:12
    at ContextifyScript.Script.runInContext (vm.js:32:29)
    at ContextifyScript.Script.runInNewContext (vm.js:38:15)
    at Object.runInNewContext (vm.js:91:38)
    at module.exports (/Users/ravikirankk/Projects/I-Team/srdm/jsreport/node_modules/jsreport-scripts/lib/scriptEvalChild.js:123:6)
    at process. (/Users/ravikirankk/Projects/I-Team/srdm/jsreport/node_modules/script-manager/lib/worker-processes.js:48:36)
    at emitTwo (events.js:106:13)
    at process.emit (events.js:194:7)
    at process.nextTick (internal/child_process.js:766:12)

答:
```<code>require('jsreport')({ "scripts": {
"allowedModules" : ["http"]
</code>```

}
})

Update the require statement in server.js file

Body:
Error occured - Error during rendering report: Unsupported module in scripts: http. To enable require on particular module, you need to update the configuration as {"scripts": { "allowedModules": ["http"] } } ... Alternatively you can also set "*" to allowedModules to enable everything

Stak - Error: Unsupported module in scripts: http. To enable require on particular module, you need to update the configuration as {"scripts": { "allowedModules": ["http"] } } ... Alternatively you can also set "*" to allowedModules to enable everything
    at _require (/Users/ravikirankk/Projects/I-Team/srdm/jsreport/node_modules/jsreport-scripts/lib/scriptEvalChild.js:44:11)
    at evalmachine.:2:12
    at ContextifyScript.Script.runInContext (vm.js:32:29)
    at ContextifyScript.Script.runInNewContext (vm.js:38:15)
    at Object.runInNewContext (vm.js:91:38)
    at module.exports (/Users/ravikirankk/Projects/I-Team/srdm/jsreport/node_modules/jsreport-scripts/lib/scriptEvalChild.js:123:6)
    at process. (/Users/ravikirankk/Projects/I-Team/srdm/jsreport/node_modules/script-manager/lib/worker-processes.js:48:36)
    at emitTwo (events.js:106:13)
    at process.emit (events.js:194:7)
    at process.nextTick (internal/child_process.js:766:12)

Body:
require('jsreport')({ "scripts": {
"allowedModules" : ["http"]

}
})

Update the require statement in server.js file


问:
import() equivalent of import { something } from 'somewhere';
I've got a file that exports few components that can be imported easily via

```<code>import { component1, component2 } from './components'
</code>```

However now need to load them asynchronously and webpack allows us to split files into nice chunks using import() but I can't figure out if I can import() just a single component from ./components. Alternative would be to place them into separate files, but wanted to check if it is possible via import() first.

答:
Although import() does give you all exports by default, you can use destructuring to pick the imports you want:

```<code>import("./components")
    .then(({ component1 }) => {
        console.log(component1);
    });
</code>```

Bundlers should be able to apply tree shaking against this code and determine that only component1 is used - however I'm not entirely sure if the current version of Webpack does this. It will definitely create a separate chunk for ./components at the very least.

Body:
I've got a file that exports few components that can be imported easily via

import { component1, component2 } from './components'

However now need to load them asynchronously and webpack allows us to split files into nice chunks using import() but I can't figure out if I can import() just a single component from ./components. Alternative would be to place them into separate files, but wanted to check if it is possible via import() first.

Body:
Although import() does give you all exports by default, you can use destructuring to pick the imports you want:

import("./components")
    .then(({ component1 }) => {
        console.log(component1);
    });

Bundlers should be able to apply tree shaking against this code and determine that only component1 is used - however I'm not entirely sure if the current version of Webpack does this. It will definitely create a separate chunk for ./components at the very least.


答:
.outer has width 100% already because it's a block element. It lacks height because the content is floated. To give .outer the height of the content, add overflow: auto to the class definition:

.outer {
  background-color: #ff00ff;
  overflow: auto;
}

.outer div {
  float: left;
  background-color: #0000ff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
</div></code>```

Title: Expand outer nested div to 100%

Body:
I have this code

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;

}

    test1
 test1

    test2
 test2

https://jsfiddle.net/jcb5mdqa/

It looks like

but I want the outer to have a width of 100% like in .css written.

Expected result

What do I need to change?

Body:
.outer has width 100% already because it's a block element. It lacks height because the content is floated. To give .outer the height of the content, add overflow: auto to the class definition:

.outer {
  background-color: #ff00ff;
  overflow: auto;
}

.outer div {
  float: left;
  background-color: #0000ff;
}

<div class="outer">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
</div>


问:
iOS Swift 3: implementing chain of notifications emulating Android's AlarmManager
I'm implementing an app with an internal calendar, fetched from a remote web service. I want to send a local notification to the user when an event of interest is scheduled in the calendar, at a specific time chosen by him. Just like the iOS calendar app, when you can create an event and ask to be notified X hours/days before it happens. The main difference is that you can't create events: they are downloaded from a pre-populated remote calendar.

In Android I've solved the problem by using AlarmManager, while in iOS with Swift 3 the closest I've got to porting the same solution was via opportunistic background data fetch. The main difference between the two solutions is that background data fetch doesn't work when the app has been killed.

It would be really important for me that local notifications worked even when the app is killed. I think users expect apps notifications to work even when the app is closed, like it happens with WhatsApp or Facebook. I know that those notifications are triggered by someone writing something and therefore they are Push Notifications, but the average user just expects notifications to keep working even when the app is closed.

What would be the most elegant solution to "emulate" the behaviour of Android's AlarmManager in iOS?

Scheduling a bunch of notifications in advance hoping that the user will eventually open the app before all of them are dequeued looks a badly designed solution.

Also, delegating all the work to the server and push the notifications to the subscribed devices looks quite bad too as it requires much more work on the server side. Plus it requires a server which is able to awake itself to send push notifications, which is something that I don't have. I only have a simple webserver which answers to HTTP requests.

EDIT : The ideal solution I'm looking for isn't any of the previous 2 options, since I find them more like workarounds than actual elegant solutions to what I perceive being a fairly common problem. There has to be a third option...

答:
In iOS there is no way to achieve this. Looking at the documentation of application(_:didReceiveRemoteNotification:fetchCompletionHandler:), it states that

the system does not automatically launch your app if the user has force-quit it. In that situation, the user must relaunch your app or restart the device before the system attempts to launch your app automatically again.

You can receive push notifications, but no code will be executed until the user launches your app. So unless you are sending remote push notifications from a server, you cannot set up new local notifications until the user opens your app.


问:
How to copy column values from one excel and write to another excel?
I have an Excel say "A" with column name Name, Email, and Address.  I need to copy this to another excel it has the order Email, Name, and Address. How can I do this with PHP Excel Class? Please help</p>

答:
```<code> function  stack(){
    Include 'PHPExcel_IOFactory';
    include 'PHPExcel/IOFactory.php';
    $inputFileName = '/example1.xls';

    //  Read your Excel workbook
    try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcelOri = $objReader->load($inputFileName);
    } catch(Exception $e) {
        die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
    }

    //  Get worksheet dimensions
    $sheet = $objPHPExcelOri->getSheet(0);
    $highestRow = $sheet->getHighestRow();
    $highestColumn = $sheet->getHighestColumn();

    //  Loop through each row of the worksheet in turn
    for ($row = 1; $row <= $highestRow; $row++){
        //  Read a row of data into an array
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                                        NULL,
                                        TRUE,
                                        FALSE);
        //  Save data in Array
        $dataOri[$row]=$rowData[0];
    }

    //NEW EXCEL
    self::$objPHPExcel->createSheet();
    self::$objPHPExcel->setActiveSheetIndex();

    $rowNew = 1;
    foreach ($dataOri as $key => $data) {
          self::$objPHPExcel->getActiveSheet()->setCellValue(  'A' . $rowNew , $data[1] );
          self::$objPHPExcel->getActiveSheet()->setCellValue(  'B' . $rowNew , $data[0] );
          self::$objPHPExcel->getActiveSheet()->setCellValue(  'C' . $rowNew++ , $data[2] );
    }

    //Download EXCEL
    $filename = 'ExcelNew';
    $format = 'Excel2007';
    $this->saveExcelDownload($format, $filename);

}
</code>```


问:
How to properly test against certain values in NSEventModifierFlags via Swift?
When using the flagsChanged(with event: NSEvent) method of the NSResponder class, how do I test against the event.modifierFlags option set for individual modifier keys being pressed/released?

答:
I have found a solution, here I check for the shift key:

```<code>override func flagsChanged(with event: NSEvent)
{
    if event.modifierFlags.contains(.shift)
    {
        // shift pressed
    }
    if event.modifierFlags.contains(.shift) == false
    {
        // shift released
    }
}
</code>```

Body:
I have found a solution, here I check for the shift key:

override func flagsChanged(with event: NSEvent)
{
    if event.modifierFlags.contains(.shift)
    {
        // shift pressed
    }
    if event.modifierFlags.contains(.shift) == false
    {
        // shift released
    }
}


答:
Put a check using session on the top of login/logout button like:

```<code>if( isset($_SESSION['username']) && !empty($_SESSION['username']) )
{
    // User is logged in, show logout menu here
}
else
{
    // User is not logged in, show login menu here
}
</code>```

Explanation: $_SESSION['username'] is set only when the user login is successful after checking the login credentials and removed on logout.

Title: Hide login/register button when logged in and hide logout button when logged out

Body:
Put a check using session on the top of login/logout button like:

if( isset($_SESSION['username']) && !empty($_SESSION['username']) )
{
    // User is logged in, show logout menu here
}
else
{
    // User is not logged in, show login menu here
}

Explanation: $_SESSION['username'] is set only when the user login is successful after checking the login credentials and removed on logout.


问:
TYPO3 TypoScript mark navigation active
How can I mark a navigation active in TypoScript?

Navigation TypoScript looks like this:

```<code>NAVIMAIN = HMENU
NAVIMAIN.entryLevel = 0
#NAVIMAIN.excludeUidList =

NAVIMAIN {
    1 = TMENU
    1 {
        expAll = 1
        wrap = <ul class="cf">|</ul>

        noBlur = 1
        NO = 1
        NO.ATagTitle.field = title
        NO.wrapItemAndSub = <li>|</li>
        NO.wrapItemAndSub = <li>|</li>

        ACT = 1
        ACT.ATagParams = class="act"
        ACT.wrapItemAndSub = <li> |</li>
    }
}
</code>```

Thanks at all

答:
```<code>NAVIMAIN = HMENU
NAVIMAIN {
    entryLevel = 0
    1 = TMENU
    1 {
        expAll = 1
        wrap = <ul class="cf">|</ul>

        noBlur = 1
        NO = 1
        NO {
            ATagTitle.field = title
            wrapItemAndSub = <li>|</li>
        }
        ACT < .NO
        ACT {
            wrapItemAndSub = <li class="active">|</li>
        }
    }
}
</code>```

Title: TYPO3 TypoScript mark navigation active

Body:
How can I mark a navigation active in TypoScript?

Navigation TypoScript looks like this:

NAVIMAIN = HMENU
NAVIMAIN.entryLevel = 0
#NAVIMAIN.excludeUidList =

NAVIMAIN {
    1 = TMENU
    1 {
        expAll = 1
        wrap =
|

        noBlur = 1
        NO = 1
        NO.ATagTitle.field = title
        NO.wrapItemAndSub =
|

        NO.wrapItemAndSub =
|

        ACT = 1
        ACT.ATagParams = class="act"
        ACT.wrapItemAndSub =
 |

    }
}

Thanks at all


问:
Laravel localization files with database
I want to make multilanguage site with laravel with [en:es] language. I created  en and es folders  in lang folder. Then i created translate.php file in those folder. File looks like.

```<code><?php

return [
    'identificator' => 'text',
];
</code>```

How to import all identificators and text to database table for CRUD and export'em back to translate.php file?

答:
The solution is here in Github

The content in the languages table is:

```<code>| id | locale | name    |
-------------------------
| 1  | en     | english |
| 2  | es     | spanish |
</code>```

The relevant content in the language_entries table is:

```<code>| id | locale | namespace | group       | item            | text                    |
-------------------------------------------------------------------------------------
| 1  | en     | *         | validations | missing.name    | Name is missing         |
| 2  | en     | *         | validations | missing.surname | Surname is missing      |
| 3  | en     | *         | validations | min_number      | Number is too small     |
| 4  | es     | *         | validations | missing.name    | Falta nombre            |
| 5  | es     | *         | validations | missing.surname | Falta apellido          |
</code>```

Output for different keys with es locale:

```<code>    trans('validations.missing.name');   //    'Falta nombre'
    trans('validations.min_number');     //    'Number is too small'
    trans('validations.missing.email');  //    'missing_email'
</code>```

Body:
I want to make multilanguage site with laravel with [en:es] language. I created  en and es folders  in lang folder. Then i created translate.php file in those folder. File looks like.

<?php

return [
    'identificator' => 'text',
];

How to import all identificators and text to database table for CRUD and export'em back to translate.php file?

Body:
The solution is here in Github

The content in the languages table is:

| id | locale | name    |
-------------------------
| 1  | en     | english |
| 2  | es     | spanish |

The relevant content in the language_entries table is:

| id | locale | namespace | group       | item            | text                    |
-------------------------------------------------------------------------------------
| 1  | en     | *         | validations | missing.name    | Name is missing         |
| 2  | en     | *         | validations | missing.surname | Surname is missing      |
| 3  | en     | *         | validations | min_number      | Number is too small     |
| 4  | es     | *         | validations | missing.name    | Falta nombre            |
| 5  | es     | *         | validations | missing.surname | Falta apellido          |

Output for different keys with es locale:

    trans('validations.missing.name');   //    'Falta nombre'
    trans('validations.min_number');     //    'Number is too small'
    trans('validations.missing.email');  //    'missing_email'


问:
Ungoogleble machine-code or otherwise hard to read EUID part
Not sure whether obfuscated, machine-code or something else. Please, let me know what the part is for and how to read it. The part is from the file.

```<code>###############################################################################
# Set prompt based on EUID
################################################################################
if (( EUID == 0 )); then
    PROMPT=$'%{\e[01;31m%}%n@%m%{\e[0m%}[%{\e[01;34m%}%3~%{\e[0;m%}]$(pc_scm_f)%# '
else
    PROMPT=$'%{\e[01;32m%}%n@%m%{\e[0m%}[%{\e[01;34m%}%3~%{\e[0;m%}]$(pc_scm_f)%% '
fi
</code>```

could someone break it a bit more into parts?

What does the conditional EUID == 0 do?

I get an error about pc_scm_f, using OBSD, is it some sort of value in other OS?

the \e starts some sort of logical part, what do the rest do?

答: Looks like ANSI escape sequences to me.</p>

Body:
Not sure whether obfuscated, machine-code or something else. Please, let me know what the part is for and how to read it. The part is from the file.

###############################################################################
# Set prompt based on EUID
################################################################################
if (( EUID == 0 )); then
    PROMPT=$'%{\e[01;31m%}%n@%m%{\e[0m%}[%{\e[01;34m%}%3~%{\e[0;m%}]$(pc_scm_f)%# '
else
    PROMPT=$'%{\e[01;32m%}%n@%m%{\e[0m%}[%{\e[01;34m%}%3~%{\e[0;m%}]$(pc_scm_f)%% '
fi

could someone break it a bit more into parts?

What does the conditional EUID == 0 do?

I get an error about pc_scm_f, using OBSD, is it some sort of value in other OS?

the \e starts some sort of logical part, what do the rest do?

Body: Looks like ANSI escape sequences to me.


问:
Angular2 - ContentChild query does not find nested components
I am trying to set up an Angular2 component that automatically focuses an input element that is inserted via content projection.

The solution I am using is based off of this answer. I have an additional requirement that the input element might be nested inside another component. However, I am finding that the ContentChild query is not able to detect elements buried deep inside ng-content tags.

@Component({
  selector: 'inner-feature',
  template: "<input auto-focus>",
  directives: [AutoFocus]
})
export class InnerFeature { }

@Component({
  selector: 'feature',
  template: `

      <ng-content></ng-content>

  `
})
export class Feature {
  @ContentChild(AutoFocus)
  private _autoFocus: AutoFocus;

  private _show: boolean = false;

  @Input()
  get show() {
    return this._show;
  }
  set show(show: boolean) {
    this._show = show;
    if (show && this._autoFocus) {
      setTimeout(() => this._autoFocus.focus());
    }
  }
}

@Component({
  selector: 'my-app',
  template: `

      <button (click)="toggleFeature()">Toggle</button>
      <feature [show]="showFeature">
        <inner-feature></inner-feature>
      </feature>

  `,
  directives: [Feature, InnerFeature]
})
export class App {
  showFeature: boolean = false;

  toggleFeature() {
    this.showFeature = !this.showFeature;
  }
}
```

The _autoFocus property never gets populated. Contrast that with the case where the auto-focus directive is not nested inside another component and it works fine. Is there a way to make this work?

(I have not pasted the code for AutoFocus since it's not crucial to this example.)

See Plunker for a demo.

UPDATED code above to fix a missing directive.

答:
Use ContentChildren with descendants set to true

```<code>@ContentChildren(AutoFocus, { descendants: true })
</code>```

Body:
I am trying to set up an Angular2 component that automatically focuses an input element that is inserted via content projection.

The solution I am using is based off of this answer. I have an additional requirement that the input element might be nested inside another component. However, I am finding that the ContentChild query is not able to detect elements buried deep inside ng-content tags.

@Component({
  selector: 'inner-feature',
  template: "<input auto-focus>",
  directives: [AutoFocus]
})
export class InnerFeature { }

@Component({
  selector: 'feature',
  template: `

      <ng-content></ng-content>

  `
})
export class Feature {
  @ContentChild(AutoFocus)
  private _autoFocus: AutoFocus;

  private _show: boolean = false;

  @Input()
  get show() {
    return this._show;
  }
  set show(show: boolean) {
    this._show = show;
    if (show && this._autoFocus) {
      setTimeout(() => this._autoFocus.focus());
    }
  }
}

@Component({
  selector: 'my-app',
  template: `

      <button (click)="toggleFeature()">Toggle</button>
      <feature [show]="showFeature">
        <inner-feature></inner-feature>
      </feature>

  `,
  directives: [Feature, InnerFeature]
})
export class App {
  showFeature: boolean = false;

  toggleFeature() {
    this.showFeature = !this.showFeature;
  }
}

The _autoFocus property never gets populated. Contrast that with the case where the auto-focus directive is not nested inside another component and it works fine. Is there a way to make this work?

(I have not pasted the code for AutoFocus since it's not crucial to this example.)

See Plunker for a demo.

UPDATED code above to fix a missing directive.

Body:
Use ContentChildren with descendants set to true

@ContentChildren(AutoFocus, { descendants: true })


问:
How to display items of linked model
I have 2 models ("Offence" and "OffenceType") with a has_many relationship managed by a join table "lk_offence_types".

In the index.html.erb of "Offence" I'm not able to display an OffenceType item. (I've tried with delegation but it seems not work with has_many..)

Offence model:

```<code>class Offence < ApplicationRecord
    has_many :lk_offence_types, inverse_of: :offence, dependent: :destroy
    has_many :offence_types, through: :lk_offence_types

    #delegate :offence_type_description, to: :offence_type
end
</code>```

OffenceType model:

```<code>class OffenceType < ApplicationRecord
    has_many :lk_offence_types
    has_many :offences, through: :lk_offence_types
end
</code>```

LkOffenceType model:

```<code>class LkOffenceType < ApplicationRecord
  belongs_to :offence_type, inverse_of: :lk_offence_types
  belongs_to :offence, inverse_of: :lk_offence_types
end
</code>```

Offence's index.html.erb:

```<code><% @offences.each do |offence| %>
<tr>
<td><%= offence.offence_description %></td>
<td><%= offence.offence_types.offence_type_description %></td>
<% end %>
</code>```

<%= offence.offence_types.offence_type_description %> gives me an error.
I've also tried with:
<%= offence.offence_type_description %> and other siyntaxes...

What am I missing?

(I'm using Ruby 2.3 and Rails 5.0.2)

Thanks

答:
You need to loop over offence types as well. You may need to fix the styling, this is just to give you the idea of what's missing.

```<code><% offence.offence_types.each do |ot| %>
 <td><%= ot.offence_type_description %></td>
<% end %>
</code>```

Title: How to display items of linked model

Body:
I have 2 models ("Offence" and "OffenceType") with a has_many relationship managed by a join table "lk_offence_types".

In the index.html.erb of "Offence" I'm not able to display an OffenceType item. (I've tried with delegation but it seems not work with has_many..)

Offence model:

class Offence < ApplicationRecord
    has_many :lk_offence_types, inverse_of: :offence, dependent: :destroy
    has_many :offence_types, through: :lk_offence_types

    #delegate :offence_type_description, to: :offence_type
end

OffenceType model:

class OffenceType < ApplicationRecord
    has_many :lk_offence_types
    has_many :offences, through: :lk_offence_types
end

LkOffenceType model:

class LkOffenceType < ApplicationRecord
  belongs_to :offence_type, inverse_of: :lk_offence_types
  belongs_to :offence, inverse_of: :lk_offence_types
end

Offence's index.html.erb:

<% @offences.each do |offence| %>

<%= offence.offence_description %>
<%= offence.offence_types.offence_type_description %>
<% end %>

<%= offence.offence_types.offence_type_description %> gives me an error.
I've also tried with:
<%= offence.offence_type_description %> and other siyntaxes...

What am I missing?

(I'm using Ruby 2.3 and Rails 5.0.2)

Thanks

Body:
You need to loop over offence types as well. You may need to fix the styling, this is just to give you the idea of what's missing.

<% offence.offence_types.each do |ot| %>
 <td><%= ot.offence_type_description %></td>
<% end %>


问:
PhantomJS Memory Exhausted error when using JavaScript
I've searched all over the web for a solution with no luck so far. I know this is a documented issue, but I am only trying to load a single web page and all the responses have been "this happens trying to do tests on 200 pages".

I have tried:

page.settings.loadImages = true;
 page.settings.loadplugins = false;

I added the ``page.close()` even though like I said, it's only with one URL right now.

I've tried setting loadImages to false as well. It works fine when I remove my one line of JavaScript (for example replacing it with document.title but as soon as that line is there, the memory usage rockets to 1000MB and then it quits.

My only goal is to check if a certain element exists on the page. How can I resolve this issue? None of the solutions I've found online are working for me.

The code in question:

```<code>var system = require('system');
var page = require('webpage').create();
page.settings.userAgent = 'Chrome/52.0.2743.116';
var url = 'http://www.example.com/';
var ending = system.args[1];
ending = encodeURIComponent(ending);
url = url + ending;

page.settings.loadImages = false;
page.settings.loadplugins = false;

page.viewportSize = { width: 1680, height: 1050 };

page.open(url, function(status) {
setTimeout(function(){
  var elem = page.evaluate(function() {
    return $(".primary-info")[0];
  });
  if(!elem){
    console.log('no image found');
    page.render(ending+'.png');
      }
    page.close();
    phantom.exit();
      }, 5000);
});
</code>```

答:
Don't just return the whole object, there could be quite a lot of its attributes. Only take what is necessary:</p>

```<code>  var elem = page.evaluate(function() {
    var data = {};
    var item = $(".primary-info")[0];
    data.title = item.value;
    data.color = item.style.color;
    return data;
  });
</code>```

Body:
I've searched all over the web for a solution with no luck so far. I know this is a documented issue, but I am only trying to load a single web page and all the responses have been "this happens trying to do tests on 200 pages".

I have tried:

page.settings.loadImages = true;
 page.settings.loadplugins = false;

I added the ``page.close()` even though like I said, it's only with one URL right now.

I've tried setting loadImages to false as well. It works fine when I remove my one line of JavaScript (for example replacing it with document.title but as soon as that line is there, the memory usage rockets to 1000MB and then it quits.

My only goal is to check if a certain element exists on the page. How can I resolve this issue? None of the solutions I've found online are working for me.

The code in question:

var system = require('system');
var page = require('webpage').create();
page.settings.userAgent = 'Chrome/52.0.2743.116';
var url = 'http://www.example.com/';
var ending = system.args[1];
ending = encodeURIComponent(ending);
url = url + ending;

page.settings.loadImages = false;
page.settings.loadplugins = false;

page.viewportSize = { width: 1680, height: 1050 };

page.open(url, function(status) {
setTimeout(function(){
  var elem = page.evaluate(function() {
    return $(".primary-info")[0];
  });
  if(!elem){
    console.log('no image found');
    page.render(ending+'.png');
      }
    page.close();
    phantom.exit();
      }, 5000);
});

Body:
Don't just return the whole object, there could be quite a lot of its attributes. Only take what is necessary:

  var elem = page.evaluate(function() {
    var data = {};
    var item = $(".primary-info")[0];
    data.title = item.value;
    data.color = item.style.color;
    return data;
  });


问:
dialog has not dismiss() in onitemclick listener
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
has not (or not showing) dismiss() method under setOnItemClickListener() ??

particularly this is my code.

```<code>AlertDialog.Builder dialog = new AlertDialog.Builder(getApplicationContext());
dialog.setTitle("TITLE");
dialog.setView(view);
dialog.show();

listView.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int pos,
        long id) {
    dialog.dismiss() // dismiss is not there.

    }
});
</code>```

thanks.

答:
This is what always do in these handlers:

Create the dialog and have a member variable at the class/activity level

Create a private method in the class/activity to dismiss the dialog

Call this private method in your handler

What you are creating is not a Dialog, it is DialogBuilder. You need to create it as below:

```<code>AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle("...");
builder.setMessage("message");
builder.setNegativeButton("OK", null);
AlertDialog dlg = builder.create();
</code>```

Body:
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
has not (or not showing) dismiss() method under setOnItemClickListener() ??

particularly this is my code.

AlertDialog.Builder dialog = new AlertDialog.Builder(getApplicationContext());
dialog.setTitle("TITLE");
dialog.setView(view);
dialog.show();

listView.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int pos,
        long id) {
    dialog.dismiss() // dismiss is not there.

    }
});

thanks.

Body:
This is what always do in these handlers:

Create the dialog and have a member variable at the class/activity level

Create a private method in the class/activity to dismiss the dialog

Call this private method in your handler

What you are creating is not a Dialog, it is DialogBuilder. You need to create it as below:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle("...");
builder.setMessage("message");
builder.setNegativeButton("OK", null);
AlertDialog dlg = builder.create();


问:
CUDA fft different results from MATLAB fft
I have tried to do a simple fft and compare the results between MATLAB and CUDA.

MATLAB:
Vector of 9 numbers 1-9

```<code>I = [1 2 3 4 5 6 7 8 9];
</code>```

and use this code:

```<code>fft(I)
</code>```

gives the results:

```<code>  45.0000 + 0.0000i
  -4.5000 +12.3636i
  -4.5000 + 5.3629i
  -4.5000 + 2.5981i
  -4.5000 + 0.7935i
  -4.5000 - 0.7935i
  -4.5000 - 2.5981i
  -4.5000 - 5.3629i
  -4.5000 -12.3636i
</code>```

And CUDA code:

```<code>int FFT_Test_Function() {

    int n = 9;

    double* in = new double[n];
    Complex* out = new Complex[n];

    for (int i = 0; i<n; i++)
    {
        in[i] = i + 1;
    }

    // Allocate the buffer
    cufftDoubleReal *d_in;
    cufftDoubleComplex *d_out;
    unsigned int out_mem_size = sizeof(cufftDoubleComplex)*n;
    unsigned int in_mem_size = sizeof(cufftDoubleReal)*n;
    cudaMalloc((void **)&d_in, in_mem_size);
    cudaMalloc((void **)&d_out, out_mem_size);

    // Save time stamp
    milliseconds timeStart = getCurrentTimeStamp();

    cufftHandle plan;
    cufftResult res = cufftPlan1d(&plan, n, CUFFT_D2Z, 1);
    if (res != CUFFT_SUCCESS) { cout << "cufft plan error: " << res << endl; return 1; }
    cudaCheckErrors("cuda malloc fail");

    cudaMemcpy(d_in, in, in_mem_size, cudaMemcpyHostToDevice);
    cudaCheckErrors("cuda memcpy H2D fail");

    res = cufftExecD2Z(plan, d_in, d_out);
    if (res != CUFFT_SUCCESS) { cout << "cufft exec error: " << res << endl; return 1; }
    cudaMemcpy(out, d_out, out_mem_size, cudaMemcpyDeviceToHost);
    cudaCheckErrors("cuda memcpy D2H fail");

    milliseconds timeEnd = getCurrentTimeStamp();
    milliseconds totalTime = timeEnd - timeStart;
    std::cout << "Total time: " << totalTime.count() << std::endl;

    return 0;
}
</code>```

In this CUDA code i got the result:

You can see that CUDA gives 4 zero's (cells 5-9).

What am i missed?

Thank you very much for your attention!

答:
CUFFT_D2Z is a real-to-complex FFT, so the top N/2 - 1 points in the output data are redundant - they are just the complex conjugate of the bottom half of the transform (you can see this in the MATLAB output if you compare pairs of terms which are mirrored about the mid-point).

You can fill in these "missing" terms if you need them, by just taking the complex conjugate of each corresponding term, but usually there isn't much point in doing this.

Body:
I have tried to do a simple fft and compare the results between MATLAB and CUDA.

MATLAB:
Vector of 9 numbers 1-9

I = [1 2 3 4 5 6 7 8 9];

and use this code:

fft(I)

gives the results:

  45.0000 + 0.0000i
  -4.5000 +12.3636i
  -4.5000 + 5.3629i
  -4.5000 + 2.5981i
  -4.5000 + 0.7935i
  -4.5000 - 0.7935i
  -4.5000 - 2.5981i
  -4.5000 - 5.3629i
  -4.5000 -12.3636i

And CUDA code:

int FFT_Test_Function() {

    int n = 9;

    double* in = new double[n];
    Complex* out = new Complex[n];

    for (int i = 0; i<n; i++)
    {
        in[i] = i + 1;
    }

    // Allocate the buffer
    cufftDoubleReal *d_in;
    cufftDoubleComplex *d_out;
    unsigned int out_mem_size = sizeof(cufftDoubleComplex)*n;
    unsigned int in_mem_size = sizeof(cufftDoubleReal)*n;
    cudaMalloc((void **)&d_in, in_mem_size);
    cudaMalloc((void **)&d_out, out_mem_size);

    // Save time stamp
    milliseconds timeStart = getCurrentTimeStamp();

    cufftHandle plan;
    cufftResult res = cufftPlan1d(&plan, n, CUFFT_D2Z, 1);
    if (res != CUFFT_SUCCESS) { cout << "cufft plan error: " << res << endl; return 1; }
    cudaCheckErrors("cuda malloc fail");

    cudaMemcpy(d_in, in, in_mem_size, cudaMemcpyHostToDevice);
    cudaCheckErrors("cuda memcpy H2D fail");

    res = cufftExecD2Z(plan, d_in, d_out);
    if (res != CUFFT_SUCCESS) { cout << "cufft exec error: " << res << endl; return 1; }
    cudaMemcpy(out, d_out, out_mem_size, cudaMemcpyDeviceToHost);
    cudaCheckErrors("cuda memcpy D2H fail");

    milliseconds timeEnd = getCurrentTimeStamp();
    milliseconds totalTime = timeEnd - timeStart;
    std::cout << "Total time: " << totalTime.count() << std::endl;

    return 0;
}

In this CUDA code i got the result:

You can see that CUDA gives 4 zero's (cells 5-9).

What am i missed?

Thank you very much for your attention!


问:
Get progress of omxplayer
Is there a way to get the second omxplayer has already played (e.g for a Progressbar)?

If I press p, the video pauses. Is there a key like this for the progress?

I am using omxplayer in a terminal.

答:
```<code>omxplayer -s
</code>```

will send state information including seconds

```<code>M: 8516603 V: -8.52s      0k/     0k A:  4.67   4.63s/  6.07s Cv:     0k Ca:   180k
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get progress of omxplayer

Body:
omxplayer -s

will send state information including seconds

M: 8516603 V: -8.52s      0k/     0k A:  4.67   4.63s/  6.07s Cv:     0k Ca:   180k


问:
How to wait for setState in componentDidMount to resolve when testing with enzyme?
I am trying to test a React component that runs some asynchronous code and calls setState in componentDidMount.

Here is my react component that I want to test:

```<code>/**
*
* AsyncComponent
*
*/

import React from 'react';

class AsyncComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loaded: false,
      component: null,
    };
  }
  componentDidMount() {
    this.props.component.then(component => {
       this.setState({
         loaded: true,
         component: component.default ? component.default : component,
       });
    });
  }
  render() {
    if (!this.state.loaded) {
      return null;
    }

    const Component = this.state.component;

    const { component, ...rest } = this.props;

    return <Component {...rest} />;
  }
}

export default AsyncComponent;
</code>```

Here is the test case. I am using jest and enzyme.

```<code>import React from 'react';
import { mount } from 'enzyme';

import AsyncComponent from '../index';

const TestComponent = () => <div>Hello</div>;

describe('<AsyncComponent />', () => {
  it('Should render loaded component.', () => {
    const promise = Promise.resolve(TestComponent);
    const rendered = mount(<AsyncComponent component={promise} />);
    expect(rendered.state().loaded).toBe(true);
  });
});
</code>```

The test fails because state.loaded is still set to false. Is there a way I can make sure that AsyncComponent has fully loaded before calling expect?

I can get it to work if I wrap the expect assertion in a setTimeout, but that seems like a rather hacky way to do it. How should I go about doing this?

答:
You need to notify jest about the promise either by using async/await or return the promise from the test, have a look at the docs

```<code>describe('<AsyncComponent />', () => {
  it('Should render loaded component.', async() => {
    const promise = Promise.resolve(TestComponent);
    const rendered = mount(<AsyncComponent component={promise} />);
    await promise
    expect(rendered.state().loaded).toBe(true);
  });
});
</code>```

Body:
I am trying to test a React component that runs some asynchronous code and calls setState in componentDidMount.

Here is my react component that I want to test:

/**
*
* AsyncComponent
*
*/

import React from 'react';

class AsyncComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loaded: false,
      component: null,
    };
  }
  componentDidMount() {
    this.props.component.then(component => {
       this.setState({
         loaded: true,
         component: component.default ? component.default : component,
       });
    });
  }
  render() {
    if (!this.state.loaded) {
      return null;
    }

    const Component = this.state.component;

    const { component, ...rest } = this.props;

    return <Component {...rest} />;
  }
}

export default AsyncComponent;

Here is the test case. I am using jest and enzyme.

import React from 'react';
import { mount } from 'enzyme';

import AsyncComponent from '../index';

const TestComponent = () =>
Hello
;

describe('<AsyncComponent />', () => {
  it('Should render loaded component.', () => {
    const promise = Promise.resolve(TestComponent);
    const rendered = mount(<AsyncComponent component={promise} />);
    expect(rendered.state().loaded).toBe(true);
  });
});

The test fails because state.loaded is still set to false. Is there a way I can make sure that AsyncComponent has fully loaded before calling expect?

I can get it to work if I wrap the expect assertion in a setTimeout, but that seems like a rather hacky way to do it. How should I go about doing this?

Body:
You need to notify jest about the promise either by using async/await or return the promise from the test, have a look at the docs

describe('<AsyncComponent />', () => {
  it('Should render loaded component.', async() => {
    const promise = Promise.resolve(TestComponent);
    const rendered = mount(<AsyncComponent component={promise} />);
    await promise
    expect(rendered.state().loaded).toBe(true);
  });
});


问:
Show this element without having code repeating each time
I'm showing / hidding data from Json on click of a marker which is working totally great.</p>

答:
You can do it by looping over the properties in your json object like so</p>

```<code>var json = {
  "France": [{
    "image": "img/ausralia.jpg",
    "description": "number django 1"
  }],
  "Australia": [{
    "image": "img/ausralia.jpg",
    "description": "number django 2"
  }]
}

$(document).ready(function() {
  // iterate all properties in the json object
  for (var prop in json) {
    if (json.hasOwnProperty(prop)) {
      // add the marker items
      $(".marker." + prop.toLowerCase()).on("click", function( country ) {
        $("#show").html(
          "Image : <img src=" + json[country][0].image + ">" +
          "| Description : <h1>" + json[country][0].description) + "</h1>";
      }.bind( this, prop) ); // prop needs to be bound so that the correct country is triggered
    }
  }
});
</code>```

Body:
You can do it by looping over the properties in your json object like so

var json = {
  "France": [{
    "image": "img/ausralia.jpg",
    "description": "number django 1"
  }],
  "Australia": [{
    "image": "img/ausralia.jpg",
    "description": "number django 2"
  }]
}

$(document).ready(function() {
  // iterate all properties in the json object
  for (var prop in json) {
    if (json.hasOwnProperty(prop)) {
      // add the marker items
      $(".marker." + prop.toLowerCase()).on("click", function( country ) {
        $("#show").html(
          "Image : <img src=" + json[country][0].image + ">" +
          "| Description : <h1>" + json[country][0].description) + "</h1>";
      }.bind( this, prop) ); // prop needs to be bound so that the correct country is triggered
    }
  }
});


问:
Expand outer nested div to 100%
I have this code

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
</div></code>```

https://jsfiddle.net/jcb5mdqa/

It looks like

but I want the outer to have a width of 100% like in .css written.

Expected result

What do I need to change?

答:
Use overflow:auto

.outer {
  background-color: #ff00ff;
  width: 100%;
  overflow:auto;
}

.outer div {
  float: left;
  background-color: #0000ff;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
</div></code>```

Title: Expand outer nested div to 100%

Body:
I have this code

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;

}

    test1
 test1

    test2
 test2

https://jsfiddle.net/jcb5mdqa/

It looks like

but I want the outer to have a width of 100% like in .css written.

Expected result

What do I need to change?

Body:
Use overflow:auto

.outer {
  background-color: #ff00ff;
  width: 100%;
  overflow:auto;
}

.outer div {
  float: left;
  background-color: #0000ff;

}

<div class="outer">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
</div>