问:
How do I count the number of records that have one or more associated object?
I have a Property model that has_many :photos. I want to count the number of properties that have one or more photo.

How do I do that?

I have tried the simple:

```<code>> Property.where('properties.photos.count > ?', 0).count

   (3.1ms)  SELECT COUNT(*) FROM "properties" WHERE (properties.photos.count > 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
                                                  ^
: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos.count > 0)
from /ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
</code>```

to:

```<code>> Property.joins(:photos).where('photos.count > ?', 0).count

   (3.7ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
</code>```

to the more advanced:

```<code>>Property.includes(:photos).group(['property.id', 'photos.id']).order('COUNT(photos.id) DESC').count

(0.6ms)  SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
                                                             ^
: SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
</code>```

and a few other variations, and they all produce similar errors.

What am I doing wrong?

Note: All I want is the count of properties that have photos.count > 0. I don't want a hash of all the properties and the count of photos. In other words, if there are 5000 properties in my db, I want to build a scope that returns just the properties that actually have photos.

答:
```<code>Property.includes(:photos).where("SELECT count(photos.id) > 0 FROM photos WHERE property_id = properties.id")
</code>```

As a scope:

```<code>scope :with_photos, -> { where("SELECT count(photos.id) > 0 FROM photos WHERE property_id = properties.id") }
</code>```

Body:
I have a Property model that has_many :photos. I want to count the number of properties that have one or more photo.

How do I do that?

I have tried the simple:

> Property.where('properties.photos.count > ?', 0).count

   (3.1ms)  SELECT COUNT(*) FROM "properties" WHERE (properties.photos.count > 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
                                                  ^
: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos.count > 0)
from /ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....

to:

> Property.joins(:photos).where('photos.count > ?', 0).count

   (3.7ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...

to the more advanced:

>Property.includes(:photos).group(['property.id', 'photos.id']).order('COUNT(photos.id) DESC').count

(0.6ms)  SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
                                                             ^
: SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...

and a few other variations, and they all produce similar errors.

What am I doing wrong?

Note: All I want is the count of properties that have photos.count > 0. I don't want a hash of all the properties and the count of photos. In other words, if there are 5000 properties in my db, I want to build a scope that returns just the properties that actually have photos.

Body:
Property.includes(:photos).where("SELECT count(photos.id) > 0 FROM photos WHERE property_id = properties.id")

As a scope:

scope :with_photos, -> { where("SELECT count(photos.id) > 0 FROM photos WHERE property_id = properties.id") }


来源: stackexchange

问:
Eloquent relationships question between 3 tables
I have these 4 tables:

```<code>events (id, name, date)
drivers (id, first_name, last_name)
participants (id, number, event_id, driver_id, codriver_id)
penalties (id, event_id, participant_id)
</code>```

How I can get the driver/codriver first_name and last_name when show the penalties table?

I tried with this, but not works:

```<code>$grid->participant()->driver()->full_name();
$grid->participant()->codriver()->full_name();
</code>```

Penalty model:

```<code>public function participant()
    {
        return $this->belongsTo(Participant::class);
    }
</code>```

Participant model:

```<code>public function driver()
    {
        return $this->belongsTo(Driver::class);
    }

    public function codriver()
    {
        return $this->belongsTo(Driver::class);
    }
</code>```

Driver model:

```<code>public function getFullNameAttribute()
    {
        return $this->first_name . ' ' . $this->last_name;
    }
</code>```

How can I do?

Thanks

答:
->relation_name() returns relation query builder:

To get relation object/objects you should call relation as property, not as function (same with full_name attribute):

```<code>$grid->participant->driver->full_name;
</code>```

It is equel to:

```<code>$grid->participant()->first()->driver()->first()->full_name;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have these 4 tables:

events (id, name, date)
drivers (id, first_name, last_name)
participants (id, number, event_id, driver_id, codriver_id)
penalties (id, event_id, participant_id)

How I can get the driver/codriver first_name and last_name when show the penalties table?

I tried with this, but not works:

$grid->participant()->driver()->full_name();
$grid->participant()->codriver()->full_name();

Penalty model:

public function participant()
    {
        return $this->belongsTo(Participant::class);
    }

Participant model:

public function driver()
    {
        return $this->belongsTo(Driver::class);
    }

    public function codriver()
    {
        return $this->belongsTo(Driver::class);
    }

Driver model:

public function getFullNameAttribute()
    {
        return $this->first_name . ' ' . $this->last_name;
    }

How can I do?

Thanks

Body:
->relation_name() returns relation query builder:

To get relation object/objects you should call relation as property, not as function (same with full_name attribute):

$grid->participant->driver->full_name;

It is equel to:

$grid->participant()->first()->driver()->first()->full_name;


问:
Shift the maximum value
Difficult to formulate a question. I think everything is clear on the screenshot.

There are 3 columns. The percentage change in value with an offset of 1, 2, 3.
How to get the maximum value of the change?
I use Google translator. Sorry!

enter image description here

答:
I see at your table, and to find the max_pct_change you can use DataFrame.max and try the following code:

```<code>df=pd.DataFrame({'shift1':[np.nan,0.1549,-0.1012,0.0563,0.0731],
                'shift2':[np.nan,np.nan,0.0535,-0.0450,0.1295],
                'shift3':[np.nan,np.nan,np.nan,0.1098,0.0281]})
print(df)
df['max_pct_change']=df.apply(max, axis=1)
print(df)
</code>```

Output:

```<code>   shift1  shift2  shift3
0     NaN     NaN     NaN
1  0.1549     NaN     NaN
2 -0.1012  0.0535     NaN
3  0.0563 -0.0450  0.1098
4  0.0731  0.1295  0.0281

   shift1  shift2  shift3  max_pct_change
0     NaN     NaN     NaN             NaN
1  0.1549     NaN     NaN          0.1549
2 -0.1012  0.0535     NaN          0.0535
3  0.0563 -0.0450  0.1098          0.1098
4  0.0731  0.1295  0.0281          0.1295
</code>```

Hope this can help you.

Title: Shift the maximum value

Body:
I see at your table, and to find the max_pct_change you can use DataFrame.max and try the following code:

df=pd.DataFrame({'shift1':[np.nan,0.1549,-0.1012,0.0563,0.0731],
                'shift2':[np.nan,np.nan,0.0535,-0.0450,0.1295],
                'shift3':[np.nan,np.nan,np.nan,0.1098,0.0281]})
print(df)
df['max_pct_change']=df.apply(max, axis=1)
print(df)

Output:

   shift1  shift2  shift3
0     NaN     NaN     NaN
1  0.1549     NaN     NaN
2 -0.1012  0.0535     NaN
3  0.0563 -0.0450  0.1098
4  0.0731  0.1295  0.0281

   shift1  shift2  shift3  max_pct_change
0     NaN     NaN     NaN             NaN
1  0.1549     NaN     NaN          0.1549
2 -0.1012  0.0535     NaN          0.0535
3  0.0563 -0.0450  0.1098          0.1098
4  0.0731  0.1295  0.0281          0.1295

Hope this can help you.


问:
I'm having trouble understanding how .next(), .nextInt(), and .hasNextInt() all work in relation to one another in java?
I've looked at the documentation for the methods but I still can't quite understand how they work. Here are my questions: .hasNextInt() checks the next integer value and doesn't consume anything, yet in my code below the first time it appears it allows a user to enter a value; why is that? Afterwards I have to use .next() to clear the current value of the scanner object I'm using and will not be prompted for a new value if I remove this from the while loop.

As for .nextInt(), it's only on the first iteration in the code that it checks for the last integer value in the scanner object, but when I enter it again it allows me to enter in a new value. This all seems very inconsistent and I'm having a hard time understanding what's going on under the hood.

```<code>    int integer=0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter an integer");

    while(!scan.hasNextInt())
    {
        System.out.println("Wrong");
        scan.next();
    }

    integer = scan.nextInt();
    System.out.println(integer);

    int newNumber = scan.nextInt();
    System.out.println(newNumber);
</code>```

答:
You can consider Scanner as Iterator. Iterator has two methods hasNext() which returns is there is some data but doesn't make any changes, and next() which returns an Object.

The same with Scanner. all next*() return something from a buffer, but has*() methods only check a possibility to retrieve the particular object from the buffer.

Body:
I've looked at the documentation for the methods but I still can't quite understand how they work. Here are my questions: .hasNextInt() checks the next integer value and doesn't consume anything, yet in my code below the first time it appears it allows a user to enter a value; why is that? Afterwards I have to use .next() to clear the current value of the scanner object I'm using and will not be prompted for a new value if I remove this from the while loop.

As for .nextInt(), it's only on the first iteration in the code that it checks for the last integer value in the scanner object, but when I enter it again it allows me to enter in a new value. This all seems very inconsistent and I'm having a hard time understanding what's going on under the hood.

    int integer=0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter an integer");

    while(!scan.hasNextInt())
    {
        System.out.println("Wrong");
        scan.next();
    }

    integer = scan.nextInt();
    System.out.println(integer);

    int newNumber = scan.nextInt();
    System.out.println(newNumber);


问:
Date separator issue
I have the following code

```<code>DateTime.Now.ToString("MM/dd/yyyy")
</code>```

It always gives me this output : "04.13.2011" instead of "04/13/2011". May I know why I am getting this weird issue?

答:
You're almost certainly in a culture where that's the default date separator. If you want to force / you can quote it in the format string:

```<code>string x = DateTime.Now.ToString("MM'/'dd'/'yyyy")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Date separator issue

Body:
I have the following code

DateTime.Now.ToString("MM/dd/yyyy")

It always gives me this output : "04.13.2011" instead of "04/13/2011". May I know why I am getting this weird issue?

Body:
You're almost certainly in a culture where that's the default date separator. If you want to force / you can quote it in the format string:

string x = DateTime.Now.ToString("MM'/'dd'/'yyyy")


问:
Assign temp file from cgi and read it in .sh
I have .cgi file and .sh file. The cgi is calling the script which is the .sh file.

How will assign the tempfile created from .cgi and pass it to the .sh file?

Example below:

(on my CGI, $tmpfile is created)

#! /usr/local/bin/perl

use CGI qw/:standard :html3/;
use CGI::Carp qw(fatalsToBrowser);

my $tmpfile = "$dir/output.$$";
```

<p>(on my .sh file, i want to use the <code>$tmpfile</code> from cgi)</p>

```#! /bin/csh -fb
umask 0

set tmpfile2 = $tmpfile  #not working
```

答:
Either, as @muru said, put it into the environment:

$ENV{tmpfile}= $tmpfile;

Or pass it to the script as a parameter. This would be much cleaner than littering the environment.

OwnerDisplayName: impitnin

Body:
I have .cgi file and .sh file. The cgi is calling the script which is the .sh file.

How will assign the tempfile created from .cgi and pass it to the .sh file?

Example below:

(on my CGI, $tmpfile is created)

#! /usr/local/bin/perl

use CGI qw/:standard :html3/;
use CGI::Carp qw(fatalsToBrowser);

my $tmpfile = "$dir/output.$$";

(on my .sh file, i want to use the $tmpfile from cgi)

#! /bin/csh -fb
umask 0

set tmpfile2 = $tmpfile  #not working


问:
XML / XSLT 1.0 - How to use XSL Template Match for a string of text?
I have a piece of code within an XSLT 1.0 document that I am having trouble getting to work.

How do I correctly get XSLT 1.0 to identify/match a string?

In the case below, Description holds the text string which in this example is English (AAC) (2.0 ch) however it will not always be this (or the same number of characters in the string).

Sometimes the string could be: English (E-AC3) (2.0 ch) for example

I have tried:

```<code><xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 0 and (ScannedTrack/Description = "English (AAC) (2.0 ch)")]">
</code>```

but it is not working for me.

Can someone please help?

答:
It should be 'English (AAC) (2.0 ch)' , thus:

```<code><xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 0 and (ScannedTrack/Description = 'English (AAC) (2.0 ch)')]">
</code>```

using single quotation marks

Body:
I have a piece of code within an XSLT 1.0 document that I am having trouble getting to work.

How do I correctly get XSLT 1.0 to identify/match a string?

In the case below, Description holds the text string which in this example is English (AAC) (2.0 ch) however it will not always be this (or the same number of characters in the string).

Sometimes the string could be: English (E-AC3) (2.0 ch) for example

I have tried:

<xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 0 and (ScannedTrack/Description = "English (AAC) (2.0 ch)")]">

but it is not working for me.

Can someone please help?

Body:
It should be 'English (AAC) (2.0 ch)' , thus:

<xsl:template match="AudioTrack[ScannedTrack/TrackNumber > 0 and (ScannedTrack/Description = 'English (AAC) (2.0 ch)')]">

using single quotation marks


问:
python tensorflow import dll load failed
I installed latest python 3.6.4 x64 version

and then installed tensorflow for cpu-only with pip3

```<code>C:\>pip3 install tensorflow
</code>```

however when I tried to import tensorflow in python

it showed me the error below

I am sure that I have installed Microsoft Visual C++ 2015 Redistributable(x64)

so it wll not be the problem of dll msvcp140.dll lost

it say that "DLL load failed with error code -1073741795"

so what is exactly the problem here

i cannot find any other information about this error code

my os : windows 7 enterprise with service pack 1 / 64 bit / intel core i5 M 540

```<code>>>> import tensorflow
Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 571, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 571, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_probl
ems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

答:
Probably, your CPU does not have the instructions for AVX (needed for all tensorflow binaries since 1.6). You can check that with some tool like CPU-Z. If that is the case, you can donwload the correct wheel here (use SSE2 binaries):

tensorflow-windows-wheel

Body:
I installed latest python 3.6.4 x64 version

and then installed tensorflow for cpu-only with pip3

C:\>pip3 install tensorflow

however when I tried to import tensorflow in python

it showed me the error below

I am sure that I have installed Microsoft Visual C++ 2015 Redistributable(x64)

so it wll not be the problem of dll msvcp140.dll lost

it say that "DLL load failed with error code -1073741795"

so what is exactly the problem here

i cannot find any other information about this error code

my os : windows 7 enterprise with service pack 1 / 64 bit / intel core i5 M 540

>>> import tensorflow
Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 571, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 571, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_probl
ems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.


问:
unnest (explode) multiple list 2.0
Background

The following code is modified from here
Efficient way to unnest (explode) multiple list columns in a pandas DataFrame

I create a dataframe

```<code>import pandas as pd
df = pd.DataFrame({'App': ['x1','x2','x3', 'x4'], 'Ban':['v1','v2','v3','v4'], 'C':[['c2'],['c3','c4'],['c5','c6'],['c7','c8']],'D':[['d1','d2'],['d3','d4'],['d5','d6'],['d7','d8']], 'E':[['e1','e2'],['e3','e4'],['e5','e6'],['e7','e8']]})
df
</code>```

which looks like the following

```<code>   App Ban    C             D         E
0   x1  v1  [c2]        [d1, d2]    [e1, e2]
1   x2  v2  [c3, c4]    [d3, d4]    [e3, e4]
2   x3  v3  [c5, c6]    [d5, d6]    [e5, e6]
3   x4  v4  [c7, c8]    [d7, d8]    [e7, e8]
</code>```

I then use the following code

```<code>(df.set_index('Ban')
              .apply(lambda x: x.apply(pd.Series).stack())
              .reset_index()
              .drop('level_1', 1))
</code>```

Which creates the following

```<code>    Ban App C   D   E
0   v1  x1  c2  d1  e1
1   v1  NaN NaN d2  e2
2   v2  x2  c3  d3  e3
3   v2  NaN c4  d4  e4
4   v3  x3  c5  d5  e5
5   v3  NaN c6  d6  e6
6   v4  x4  c7  d7  e7
7   v4  NaN c8  d8  e8
</code>```

Desired Output

This is close to what I want. But my desired output is this (no NaN but instead having the appropriate App and C name:

```<code>    Ban App C   D   E
0   v1  x1  c2  d1  e1
1   v1  x1  c2  d2  e2
2   v2  x2  c3  d3  e3
3   v2  x2  c4  d4  e4
4   v3  x3  c5  d5  e5
5   v3  x3  c6  d6  e6
6   v4  x4  c7  d7  e7
7   v4  x4  c8  d8  e8
</code>```

Question

How do I get my desired output?

答:
Just fix your output by adding ffill

```<code>df.set_index('Ban').apply(lambda x: x.apply(pd.Series).stack()).groupby(level=0).ffill().reset_index(drop=True)
Out[794]:
  Ban App   C   D   E
0  v1  x1  c2  d1  e1
1  v1  x1  c2  d2  e2
2  v2  x2  c3  d3  e3
3  v2  x2  c4  d4  e4
4  v3  x3  c5  d5  e5
5  v3  x3  c6  d6  e6
6  v4  x4  c7  d7  e7
7  v4  x4  c8  d8  e8
</code>```

Title: unnest (explode) multiple list 2.0

Body:
Background

The following code is modified from here
Efficient way to unnest (explode) multiple list columns in a pandas DataFrame

I create a dataframe

import pandas as pd
df = pd.DataFrame({'App': ['x1','x2','x3', 'x4'], 'Ban':['v1','v2','v3','v4'], 'C':[['c2'],['c3','c4'],['c5','c6'],['c7','c8']],'D':[['d1','d2'],['d3','d4'],['d5','d6'],['d7','d8']], 'E':[['e1','e2'],['e3','e4'],['e5','e6'],['e7','e8']]})
df

which looks like the following

   App Ban    C             D         E
0   x1  v1  [c2]        [d1, d2]    [e1, e2]
1   x2  v2  [c3, c4]    [d3, d4]    [e3, e4]
2   x3  v3  [c5, c6]    [d5, d6]    [e5, e6]
3   x4  v4  [c7, c8]    [d7, d8]    [e7, e8]

I then use the following code

(df.set_index('Ban')
              .apply(lambda x: x.apply(pd.Series).stack())
              .reset_index()
              .drop('level_1', 1))

Which creates the following

    Ban App C   D   E
0   v1  x1  c2  d1  e1
1   v1  NaN NaN d2  e2
2   v2  x2  c3  d3  e3
3   v2  NaN c4  d4  e4
4   v3  x3  c5  d5  e5
5   v3  NaN c6  d6  e6
6   v4  x4  c7  d7  e7
7   v4  NaN c8  d8  e8

Desired Output

This is close to what I want. But my desired output is this (no NaN but instead having the appropriate App and C name:

    Ban App C   D   E
0   v1  x1  c2  d1  e1
1   v1  x1  c2  d2  e2
2   v2  x2  c3  d3  e3
3   v2  x2  c4  d4  e4
4   v3  x3  c5  d5  e5
5   v3  x3  c6  d6  e6
6   v4  x4  c7  d7  e7
7   v4  x4  c8  d8  e8

Question

How do I get my desired output?

Body:
Just fix your output by adding ffill

df.set_index('Ban').apply(lambda x: x.apply(pd.Series).stack()).groupby(level=0).ffill().reset_index(drop=True)
Out[794]:
  Ban App   C   D   E
0  v1  x1  c2  d1  e1
1  v1  x1  c2  d2  e2
2  v2  x2  c3  d3  e3
3  v2  x2  c4  d4  e4
4  v3  x3  c5  d5  e5
5  v3  x3  c6  d6  e6
6  v4  x4  c7  d7  e7
7  v4  x4  c8  d8  e8


问:
Ionic 2 / cordova-plugin-file File.writeFile() refuses to create binary file correctly (png image)
In summary

File.writeFile() creates a PNG file of 0 bytes when trying to write a Blob made from base64 data.

In my application, I am trying to create a file that consists of base64 data stored in the db. The rendered equivalent of the data is a small anti-aliased graph curve in black on a transparent background (never more that 300 x 320 pixels) that has previously been created and stored from a canvas element. I have independently verified that the stored base64 data is indeed correct by rendering it at one of various base64 encoders/decoders available online.

Output from "Ionic Info"

```<code>--------------------------------
Your system information:

Cordova CLI: 6.3.1
Gulp version:  CLI version 3.9.1
Gulp local:
Ionic Framework Version: 2.0.0-rc.2
Ionic CLI Version: 2.1.1
Ionic App Lib Version: 2.1.1
Ionic App Scripts Version: 0.0.39
OS:
Node Version: v6.7.0
--------------------------------
</code>```

The development platform is Windows 10, and I've been testing directly on a Samsung Galaxy S7 and S4 so far.

I know that the base64 data has to be converted into binary data (as a Blob) first, as File does not yet support writing base64 directly in to an image file. I found various techniques with which to do this, and the code which seems to suit my needs the most (and reflects a similar way I would have done it in java is illustrated below):

Main code from constructor:

```<code>this.platform.ready().then(() => {
      this.graphDataService.getDataItem(this.job.id).then((data) =>{
        console.log("getpic:");

        let imgWithMeta = data.split(",")
        // base64 data
        let imgData = imgWithMeta[1].trim();
        // content type
        let imgType = imgWithMeta[0].trim().split(";")[0].split(":")[1];

        console.log("imgData:",imgData);
        console.log("imgMeta:",imgType);
        console.log("aftergetpic:");

        // this.fs is correctly set to cordova.file.externalDataDirectory
        let folderpath = this.fs;
        let filename = "dotd_test.png";

        File.resolveLocalFilesystemUrl(this.fs).then( (dirEntry) => {
            console.log("resolved dir with:", dirEntry);
            this.savebase64AsImageFile(dirEntry.nativeURL,filename,imgData,imgType);
        });
      });

    });
</code>```

Helper to convert base64 to Blob:

```<code>// convert base64 to Blob
b64toBlob(b64Data, contentType, sliceSize) {

          //console.log("data packet:",b64Data);
          //console.log("content type:",contentType);
          //console.log("slice size:",sliceSize);

          let byteCharacters = atob(b64Data);

          let byteArrays = [];

          for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
              let slice = byteCharacters.slice(offset, offset + sliceSize);

              let byteNumbers = new Array(slice.length);
              for (let i = 0; i < slice.length; i++) {
                  byteNumbers[i] = slice.charCodeAt(i);
              }

              let byteArray = new Uint8Array(byteNumbers);

              byteArrays.push(byteArray);

          }

        console.log("size of bytearray before blobbing:", byteArrays.length);
        console.log("blob content type:", contentType);

        let blob = new Blob(byteArrays, {type: contentType});

        // alternative way WITHOUT chunking the base64 data
        // let blob = new Blob([atob(b64Data)],  {type: contentType});

        return blob;
  }
</code>```

save the image with File.writeFile()

```<code>// save the image with File.writeFile()
savebase64AsImageFile(folderpath,filename,content,contentType){

      // Convert the base64 string in a Blob
      let data:Blob = this.b64toBlob(content,contentType,512);

      console.log("file location attempt is:",folderpath + filename);

      File.writeFile(
        folderpath,
        filename,
        data,
        {replace: true}
      ).then(
        _ => console.log("write complete")
      ).catch(
        err => console.log("file create failed:",err);
      );
  }
</code>```

I have tried dozens of different decoding techniques, but the effect is the same. However, if I hardcode simple text data into the writeFile() section, like so:

```<code>File.writeFile(
        folderpath,
        "test.txt",
        "the quick brown fox jumps over the lazy dog",
        {replace: true}
      )
</code>```

A text file IS created correctly in the expected location with the text string above in it.

However, I've noticed that whether the file is the 0 bytes PNG, or the working text file above, in both cases the ".then()" consequence clause of the File Promise never fires.

Additionally, I swapped the above method and used the Ionic 2 native Base64-To-Gallery library to create the images, which worked without a problem. However, having the images in the user's picture gallery or camera roll is not an option for me as I do not wish to risk a user's own pictures while marshalling / packing / transmitting / deleting the data-rendered images. The images should be created and managed as part of the app.

User marcus-robinson seems to have experienced a similar issue outlined here, but it was across all file types, and not just binary types as seems to be the case here. Also, the issue seems to have been closed:

https://github.com/driftyco/ionic/issues/5638

Anybody experiencing something similar, or possibly spot some error I might have caused? I've tried dozens of alternatives but none seem to work.

答:
I had similar behaviour saving media files which worked perfectly on iOS. Nonetheless, I had the issue of 0 bytes file creation on some Android devices in release build (dev build works perfectly). After very long search, I followed the following solution

I moved the polyfills.js script tag to the top of the index.html in the ionic project before the cordova.js tag. This re-ordering somehow the issue is resolved.

So the order should look like:

```<code><script src="build/polyfills.js"></script>
<script type="text/javascript" src="cordova.js"></script>
</code>```

Works on ionic 3 and ionic 4.

The credits go to 1

Body:
In summary

File.writeFile() creates a PNG file of 0 bytes when trying to write a Blob made from base64 data.

In my application, I am trying to create a file that consists of base64 data stored in the db. The rendered equivalent of the data is a small anti-aliased graph curve in black on a transparent background (never more that 300 x 320 pixels) that has previously been created and stored from a canvas element. I have independently verified that the stored base64 data is indeed correct by rendering it at one of various base64 encoders/decoders available online.

Output from "Ionic Info"

--------------------------------
Your system information:

Cordova CLI: 6.3.1
Gulp version:  CLI version 3.9.1
Gulp local:
Ionic Framework Version: 2.0.0-rc.2
Ionic CLI Version: 2.1.1
Ionic App Lib Version: 2.1.1
Ionic App Scripts Version: 0.0.39
OS:
Node Version: v6.7.0
--------------------------------

The development platform is Windows 10, and I've been testing directly on a Samsung Galaxy S7 and S4 so far.

I know that the base64 data has to be converted into binary data (as a Blob) first, as File does not yet support writing base64 directly in to an image file. I found various techniques with which to do this, and the code which seems to suit my needs the most (and reflects a similar way I would have done it in java is illustrated below):

Main code from constructor:

this.platform.ready().then(() => {
      this.graphDataService.getDataItem(this.job.id).then((data) =>{
        console.log("getpic:");

        let imgWithMeta = data.split(",")
        // base64 data
        let imgData = imgWithMeta[1].trim();
        // content type
        let imgType = imgWithMeta[0].trim().split(";")[0].split(":")[1];

        console.log("imgData:",imgData);
        console.log("imgMeta:",imgType);
        console.log("aftergetpic:");

        // this.fs is correctly set to cordova.file.externalDataDirectory
        let folderpath = this.fs;
        let filename = "dotd_test.png";

        File.resolveLocalFilesystemUrl(this.fs).then( (dirEntry) => {
            console.log("resolved dir with:", dirEntry);
            this.savebase64AsImageFile(dirEntry.nativeURL,filename,imgData,imgType);
        });
      });

    });

Helper to convert base64 to Blob:

// convert base64 to Blob
b64toBlob(b64Data, contentType, sliceSize) {

          //console.log("data packet:",b64Data);
          //console.log("content type:",contentType);
          //console.log("slice size:",sliceSize);

          let byteCharacters = atob(b64Data);

          let byteArrays = [];

          for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
              let slice = byteCharacters.slice(offset, offset + sliceSize);

              let byteNumbers = new Array(slice.length);
              for (let i = 0; i < slice.length; i++) {
                  byteNumbers[i] = slice.charCodeAt(i);
              }

              let byteArray = new Uint8Array(byteNumbers);

              byteArrays.push(byteArray);

          }

        console.log("size of bytearray before blobbing:", byteArrays.length);
        console.log("blob content type:", contentType);

        let blob = new Blob(byteArrays, {type: contentType});

        // alternative way WITHOUT chunking the base64 data
        // let blob = new Blob([atob(b64Data)],  {type: contentType});

        return blob;
  }

save the image with File.writeFile()

// save the image with File.writeFile()
savebase64AsImageFile(folderpath,filename,content,contentType){

      // Convert the base64 string in a Blob
      let data:Blob = this.b64toBlob(content,contentType,512);

      console.log("file location attempt is:",folderpath + filename);

      File.writeFile(
        folderpath,
        filename,
        data,
        {replace: true}
      ).then(
        _ => console.log("write complete")
      ).catch(
        err => console.log("file create failed:",err);
      );
  }

I have tried dozens of different decoding techniques, but the effect is the same. However, if I hardcode simple text data into the writeFile() section, like so:

File.writeFile(
        folderpath,
        "test.txt",
        "the quick brown fox jumps over the lazy dog",
        {replace: true}
      )

A text file IS created correctly in the expected location with the text string above in it.

However, I've noticed that whether the file is the 0 bytes PNG, or the working text file above, in both cases the ".then()" consequence clause of the File Promise never fires.

Additionally, I swapped the above method and used the Ionic 2 native Base64-To-Gallery library to create the images, which worked without a problem. However, having the images in the user's picture gallery or camera roll is not an option for me as I do not wish to risk a user's own pictures while marshalling / packing / transmitting / deleting the data-rendered images. The images should be created and managed as part of the app.

User marcus-robinson seems to have experienced a similar issue outlined here, but it was across all file types, and not just binary types as seems to be the case here. Also, the issue seems to have been closed:

https://github.com/driftyco/ionic/issues/5638

Anybody experiencing something similar, or possibly spot some error I might have caused? I've tried dozens of alternatives but none seem to work.

Body:
I had similar behaviour saving media files which worked perfectly on iOS. Nonetheless, I had the issue of 0 bytes file creation on some Android devices in release build (dev build works perfectly). After very long search, I followed the following solution

I moved the polyfills.js script tag to the top of the index.html in the ionic project before the cordova.js tag. This re-ordering somehow the issue is resolved.

So the order should look like:

<script src="build/polyfills.js"></script>
<script type="text/javascript" src="cordova.js"></script>

Works on ionic 3 and ionic 4.

The credits go to 1


问:
Show an element... unless the user has javascript turned on, then fade it in nice and pretty?
I have an element which shows important text to the user, as such I'd like to animate it in to the pane (motion draws the eye) rather than just have it somewhere where the user may miss it.

How can I have it showing by default (for the 1% or so of users who surf with javascript off), but animated in for the rest?

Using

```<code>    $(document).ready(function(){
        $('#messagecenter').hide();
        $('#messagecenter').show('fade', 'slow');
    })
</code>```

Causes the element to load visible, then disapear, then fade.

```<code>display:hidden;

    $(document).ready(function(){
        $('#messagecenter').show('fade', 'slow');
    })
</code>```

Will of course hide it for users with no Javascript.

Is there any good way to do this?

答:
You can go with your second option of using display: none;, and include your text again inside a noscript tag.

Not exactly the cleanest thing though, since you'll be duplicating your element/text.

Body:
I have an element which shows important text to the user, as such I'd like to animate it in to the pane (motion draws the eye) rather than just have it somewhere where the user may miss it.

How can I have it showing by default (for the 1% or so of users who surf with javascript off), but animated in for the rest?

Using

    $(document).ready(function(){
        $('#messagecenter').hide();
        $('#messagecenter').show('fade', 'slow');
    })

Causes the element to load visible, then disapear, then fade.

display:hidden;

    $(document).ready(function(){
        $('#messagecenter').show('fade', 'slow');
    })

Will of course hide it for users with no Javascript.

Is there any good way to do this?


问:
Yii2, Custom css style for Kartik export
I'm trying to apply custom css styles to exported files such as pdf.

For example how can applying custom css style in pdf export?

I changed some font styles in styleOptions but nothing happen.

```<code>        <?= ExportMenu::widget([
        'target' => ExportMenu::TARGET_SELF,
        'dataProvider' => $dataProvider,
        'columns' => $report_columns,
        'fontAwesome' => true,
        'dropdownOptions' => [
            'label' => Yii::t('app','Export All'),
            'class' => 'btn btn-default'
        ],
        'styleOptions' => [
            'font' => [
                'size' => '24px',
                'bold' => true,
                'color' => [
                    'argb' => 'FFFFFFFF',
                ],
            ],
            'fill' => [
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => [
                    'argb' => '00000000',
                ],
            ],
        ],
        'exportConfig' => [

            ExportMenu::FORMAT_CSV => false,
            ExportMenu::FORMAT_EXCEL => false,
            ExportMenu::FORMAT_EXCEL_X => false,
            ExportMenu::FORMAT_TEXT => false,
            //ExportMenu::FORMAT_PDF => false,
            //ExportMenu::FORMAT_HTML => false
        ]
        ]) . "<hr>\n".
        GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => $columns,
            'pjax' => true,
            'summary' => '',
            'options' => ['class' => 'xxx', 'style'=>'padding-right:10px']
        ]);
    ?>
</code>```

答:
The styleOptions must be setup as an associative array, as it was updated in the documentation for export menu styleOptions settings:
http://demos.krajee.com/export#option-styleOptions

```<code>'styleOptions' => [
    ExportMenu::FORMAT_EXCEL_X => [
        'font' => [
            'size' => '24px',
            'bold' => true,
            'color' => [
                'argb' => 'FFFFFFFF',
            ],
        ],
        'fill' => [
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => [
                'argb' => '00000000',
            ],
        ],
    ],
],
</code>```

And ensure you are importing PHPExcel_Style_Fill correctly.

Body:
I'm trying to apply custom css styles to exported files such as pdf.

For example how can applying custom css style in pdf export?

I changed some font styles in styleOptions but nothing happen.

        <?= ExportMenu::widget([
        'target' => ExportMenu::TARGET_SELF,
        'dataProvider' => $dataProvider,
        'columns' => $report_columns,
        'fontAwesome' => true,
        'dropdownOptions' => [
            'label' => Yii::t('app','Export All'),
            'class' => 'btn btn-default'
        ],
        'styleOptions' => [
            'font' => [
                'size' => '24px',
                'bold' => true,
                'color' => [
                    'argb' => 'FFFFFFFF',
                ],
            ],
            'fill' => [
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => [
                    'argb' => '00000000',
                ],
            ],
        ],
        'exportConfig' => [

            ExportMenu::FORMAT_CSV => false,
            ExportMenu::FORMAT_EXCEL => false,
            ExportMenu::FORMAT_EXCEL_X => false,
            ExportMenu::FORMAT_TEXT => false,
            //ExportMenu::FORMAT_PDF => false,
            //ExportMenu::FORMAT_HTML => false
        ]
        ]) . "
\n".
        GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => $columns,
            'pjax' => true,
            'summary' => '',
            'options' => ['class' => 'xxx', 'style'=>'padding-right:10px']
        ]);
    ?>

Body:
The styleOptions must be setup as an associative array, as it was updated in the documentation for export menu styleOptions settings:
http://demos.krajee.com/export#option-styleOptions

'styleOptions' => [
    ExportMenu::FORMAT_EXCEL_X => [
        'font' => [
            'size' => '24px',
            'bold' => true,
            'color' => [
                'argb' => 'FFFFFFFF',
            ],
        ],
        'fill' => [
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => [
                'argb' => '00000000',
            ],
        ],
    ],
],

And ensure you are importing PHPExcel_Style_Fill correctly.


问:
How do I use the live-code feature in sbcl?
I am trying to get live-coding to work in lisp. i have the file t.cl which contains only this line: (loop(write(- 2 1))). Now, when i run the file in bash with sbcl --load t.cl --eval '(quit)', it runs the line, but when I try to edit the file in another terminal and save it while it runs, nothing changes ..

答:
Why your example fails

When running sbcl --load t.cl --eval '(quit)' in a shell, what this does is spin-up a SBCL Lisp image in a process, compile the file and run it. You then modify the file and save it to your disk. This last action is of no concern to the already running SBCL process, which has already compiled the previous file. SBCL read the file once when you asked it to, once it has the compiled instructions to run, it has no reason to look at the file again unless you explicitly ask it to.

A 'live' example with Emacs+SLIME

In order to perform 'live' changes to your running program, you must interact with the already running Lisp image. This is easily doable with Emacs+Slime. You can, for example, have a loop like so:

(defun foo (x) (+ x 3))

(dotimes (it 20)
  (format t "~A~%" (foo it))
  (sleep 1))
```

<p>and then recompile <code>foo</code> during execution within the REPL with a new definition:</p>

<pre class="lang-lisp prettyprint-override"><code>(defun foo (x) (+ x 100))
</code>```

Another thread will be used to recompile the function. The new function will be used for future calls as soon as its compilation is finished.
The output in the REPL will look like:

```<code>3
4
5
CL-USER> (defun foo (x) (+ x 100))
WARNING: redefining COMMON-LISP-USER::FOO in DEFUN
FOO
103
104
105
...
</code>```

This would also work with the new definition of foo being compiled from another file as opposed to being entered directly in the REPL.

Working from the system shell

While you can already use the example above for development purposes, you might want to interact with a running SBCL Lisp image from the shell. I am not aware of how to do that. For your exact example, you want to get SBCL to reload eventual files that you have modified. A brief look at the SBCL manual doesn't seem to provide ways to pipe lisp code to an already running SBCL process.

Body:
Why your example fails

When running sbcl --load t.cl --eval '(quit)' in a shell, what this does is spin-up a SBCL Lisp image in a process, compile the file and run it. You then modify the file and save it to your disk. This last action is of no concern to the already running SBCL process, which has already compiled the previous file. SBCL read the file once when you asked it to, once it has the compiled instructions to run, it has no reason to look at the file again unless you explicitly ask it to.

A 'live' example with Emacs+SLIME

In order to perform 'live' changes to your running program, you must interact with the already running Lisp image. This is easily doable with Emacs+Slime. You can, for example, have a loop like so:

(defun foo (x) (+ x 3))

(dotimes (it 20)
  (format t "~A~%" (foo it))
  (sleep 1))

and then recompile foo during execution within the REPL with a new definition:

(defun foo (x) (+ x 100))

Another thread will be used to recompile the function. The new function will be used for future calls as soon as its compilation is finished.
The output in the REPL will look like:

3
4
5
CL-USER> (defun foo (x) (+ x 100))
WARNING: redefining COMMON-LISP-USER::FOO in DEFUN
FOO
103
104
105
...

This would also work with the new definition of foo being compiled from another file as opposed to being entered directly in the REPL.

Working from the system shell

While you can already use the example above for development purposes, you might want to interact with a running SBCL Lisp image from the shell. I am not aware of how to do that. For your exact example, you want to get SBCL to reload eventual files that you have modified. A brief look at the SBCL manual doesn't seem to provide ways to pipe lisp code to an already running SBCL process.


问:
Unit test error throw in a block
I'm facing some warning issues in the following case:

```<code>let expect = expectation(description: "Async network call")
SomeManager.executeCall { result in
    do {
        /// 1.
        XCTAssertThrowsError(try CoreManager.method())
        expect.fulfill()
    } catch {}
}

waitForExpectations(timeout: 15.0, handler: nil)
</code>```

At 1. the compiler gives an error that

catch block in unreachable because no errors are thrown in do block

and if I remove the do-catch an error is given, that:

Invalid conversion from throwing function type to non-throwing function type...

答:
Swift 3 and 4

I am sorry for the late answer, but the throwing test method needs to be in a block, for the XCTAssertNoThrow and XCTAssertThrowsError to work correctly, i.e. without the do{}catch{}.

So, your code will become, note the { } :

```<code>let expect = expectation(description: "Async network call")
SomeManager.executeCall { result in
    XCTAssertThrowsError({try CoreManager.method()}, "The method didn't throw")
    expect.fulfill()
}
waitForExpectations(timeout: 15.0, handler: nil)
</code>```

Title: Unit test error throw in a block

Body:
I'm facing some warning issues in the following case:

let expect = expectation(description: "Async network call")
SomeManager.executeCall { result in
    do {
        /// 1.
        XCTAssertThrowsError(try CoreManager.method())
        expect.fulfill()
    } catch {}
}

waitForExpectations(timeout: 15.0, handler: nil)

At 1. the compiler gives an error that

catch block in unreachable because no errors are thrown in do block

and if I remove the do-catch an error is given, that:

Invalid conversion from throwing function type to non-throwing function type...

Body:
Swift 3 and 4

I am sorry for the late answer, but the throwing test method needs to be in a block, for the XCTAssertNoThrow and XCTAssertThrowsError to work correctly, i.e. without the do{}catch{}.

So, your code will become, note the { } :

let expect = expectation(description: "Async network call")
SomeManager.executeCall { result in
    XCTAssertThrowsError({try CoreManager.method()}, "The method didn't throw")
    expect.fulfill()
}
waitForExpectations(timeout: 15.0, handler: nil)


问:
Eclipse Java Missing required source folder: 'src'
I imported a jar file into workspace and this is the error I get:

Description   Resource    Path    Location    Type

  Project 'Interpreter1' is missing required source folder: 'src'   Interpreter1        Build path  Build Path Problem

How can i get rid of this error?

答: Edit your .classpath file. (Or via the project build path).</p>


问:
How to fix System.Xml.Linq.XContainer.Element(...) returned null
I am Trying to Write and Read data to and From XML file, Writing is working fine but while reading I am getting System.Xml.Linq.XContainer.Element(...) returned null. error. I am First taking the input from the user through form saving it in XML and then fetching the data from XML and displaying it in listview

Writing code

```<code>private void Btn_addproduct_Click(object sender, RoutedEventArgs e)
        {
            i++;
            XDocument doc = XDocument.Load("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
            doc.Root.Add(new XElement("Project",
                new XElement("ProjectId", i),
                new XElement("ProjectTitle", projectTitle.Text),
                new XElement("ProjectDescription", projectDescription.Text),
                new XElement("StartDate", startDate.Text),
                new XElement("EndDate", endDate.Text),
                new XElement("ToDoLimit", toDoLimit.Text),
                new XElement("WorkInProgressLimit", workInProgressLimit.Text),
                new XElement("DoneLimit", doneLimit.Text)
                ));
            doc.Save("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
        }
</code>```

Reading Code

```<code> private void Btn_productlist_Click(object sender, RoutedEventArgs e)
        {
            XDocument doc = XDocument.Load("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
            var result=doc.Descendants("Projects").Select(x=>new
            {
                projectid = x.Element("ProjectId").Value,
                projecttitle = x.Element("ProjectTitle").Value,
                projectdescription = x.Element("ProjectDescription").Value,
                startdate = x.Element("StartDate").Value,
                enddate = x.Element("EndDate").Value,
                todolimit = x.Element("ToDoLimit").Value,
                workinprogresslimit = x.Element("WorkInProgressLimit").Value,
                donelimit = x.Element("DoneLimit").Value,
            });

            Projectlistview.ItemsSource = result;

        }
</code>```

答:
Descendants(name) method returns a collection of the descendant elements for the given document. (Only the elements that have a matching name will be included in the collection)

It is giving null because it couldn't find an element having name Projects.

```<code> XDocument doc = XDocument.Load("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
 var result = doc.Descendants("Projects").Select(x => new //Should be Project
 //rest of the code
</code>```

Body:
I am Trying to Write and Read data to and From XML file, Writing is working fine but while reading I am getting System.Xml.Linq.XContainer.Element(...) returned null. error. I am First taking the input from the user through form saving it in XML and then fetching the data from XML and displaying it in listview

Writing code

private void Btn_addproduct_Click(object sender, RoutedEventArgs e)
        {
            i++;
            XDocument doc = XDocument.Load("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
            doc.Root.Add(new XElement("Project",
                new XElement("ProjectId", i),
                new XElement("ProjectTitle", projectTitle.Text),
                new XElement("ProjectDescription", projectDescription.Text),
                new XElement("StartDate", startDate.Text),
                new XElement("EndDate", endDate.Text),
                new XElement("ToDoLimit", toDoLimit.Text),
                new XElement("WorkInProgressLimit", workInProgressLimit.Text),
                new XElement("DoneLimit", doneLimit.Text)
                ));
            doc.Save("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
        }

Reading Code

 private void Btn_productlist_Click(object sender, RoutedEventArgs e)
        {
            XDocument doc = XDocument.Load("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
            var result=doc.Descendants("Projects").Select(x=>new
            {
                projectid = x.Element("ProjectId").Value,
                projecttitle = x.Element("ProjectTitle").Value,
                projectdescription = x.Element("ProjectDescription").Value,
                startdate = x.Element("StartDate").Value,
                enddate = x.Element("EndDate").Value,
                todolimit = x.Element("ToDoLimit").Value,
                workinprogresslimit = x.Element("WorkInProgressLimit").Value,
                donelimit = x.Element("DoneLimit").Value,
            });

            Projectlistview.ItemsSource = result;

        }

Body:
Descendants(name) method returns a collection of the descendant elements for the given document. (Only the elements that have a matching name will be included in the collection)

It is giving null because it couldn't find an element having name Projects.

 XDocument doc = XDocument.Load("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
 var result = doc.Descendants("Projects").Select(x => new //Should be Project
 //rest of the code


问:
Cannot apply font setting to google chart
I'm trying to change the font to Roboto on a Google chart (gantt chart) In the console I get the error: ReferenceError: Roboto is not defined

I followed instructions on the Google Fonts site, but I'm a beginner so probably missed something, I can't figure it out.

HTML:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="style.css">
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">
    google.charts.load('current', {'packages':['gantt']});
    google.charts.setOnLoadCallback(drawChart);

    function daysToMilliseconds(days) {
      return days * 24 * 60 * 60 * 1000;
    }

    function drawChart() {

      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Task ID');
      data.addColumn('string', 'Task Name');
      data.addColumn('date', 'Start Date');
      data.addColumn('date', 'End Date');
      data.addColumn('number', 'Duration');
      data.addColumn('number', 'Percent Complete');
      data.addColumn('string', 'Dependencies');

      data.addRows([
        ['Research', 'Find sources',
         new Date(2015, 0, 1), new Date(2015, 0, 5), null,  100,  null],
        ['Write', 'Write paper',
         null, new Date(2015, 0, 9), daysToMilliseconds(3), 25, 'Research,Outline'],
        ['Cite', 'Create bibliography',
         null, new Date(2015, 0, 7), daysToMilliseconds(1), 20, 'Research'],
        ['Complete', 'Hand in paper',
         null, new Date(2015, 0, 10), daysToMilliseconds(1), 0, 'Cite,Write'],
        ['Outline', 'Outline paper',
         null, new Date(2015, 0, 6), daysToMilliseconds(1), 100, 'Research']
      ]);

        var options = {
        height: 275,
        gantt: {
          labelStyle: {
            fontName: Roboto,
            fontSize: 14,
            color: '#757575'
          }
        }
      };

      var chart = new google.visualization.Gantt(document.getElementById('chart_div'));

      chart.draw(data, options);
    }
  </script>
</head>
<body>
  <div id="chart_div"></div>
</body>
</html>
</code>```

CSS:

```<code>#chart_div {
font-family: 'Roboto', sans-serif;
}
</code>```

When I run the site, the chart doesn't load. In the console I see the error:
ReferenceError: Roboto is not defined

答:
You see the error ReferenceError: Can't find variable: Roboto because you must to include the quotes on "fontName". In this case "Roboto" it's a string with the font name, not a variable.

So, you should use in your script:

```<code>labelStyle: {
  fontName: 'Roboto',
  fontSize: 14,
  color: '#757575'
}
</code>```

Body:
I'm trying to change the font to Roboto on a Google chart (gantt chart) In the console I get the error: ReferenceError: Roboto is not defined

I followed instructions on the Google Fonts site, but I'm a beginner so probably missed something, I can't figure it out.

HTML:

<!DOCTYPE html>

<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="style.css">

CSS:

#chart_div {
font-family: 'Roboto', sans-serif;
}

When I run the site, the chart doesn't load. In the console I see the error:
ReferenceError: Roboto is not defined

Body:
You see the error ReferenceError: Can't find variable: Roboto because you must to include the quotes on "fontName". In this case "Roboto" it's a string with the font name, not a variable.

So, you should use in your script:

labelStyle: {
  fontName: 'Roboto',
  fontSize: 14,
  color: '#757575'
}


问:
MySQL Where Clause Issues
```<code>SELECT `location`.`building`, `location`.`classroom` FROM `schools`
LEFT OUTER JOIN `location`
ON `location`.`location_serial` = `classroom`.`location_serial`
LEFT OUTER JOIN `rack_info`
ON `classroom_info`.`location_serial` = `classroom`.`location_serial`
WHERE (
    (((`location`.`building` LIKE 'SCH%')))
    AND
    (`classroom_info`.`status` NOT IN (1, 2))
    AND
    (
        (
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '99')
            AND
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '34')
        )
    )
)
</code>```

I'm having a problem in my WHERE clause.

Let's say location.building can be SCH1, SCH2, SCH3, SCH4, CAB1, CAB2. I'm trying to select all of the SCH classrooms, where some classroom statuses are 1 & 2.

This all works fine

The problem arises when I try to further filter my results to exclude instances when the building is SCH1 and the classroom ID is 99, and when the building is SCH1 and the classroom ID is 34. I want to show all other classrooms across all SCH buildings (including SCH1, e.g. SCH1.98) but exclude the two specific classrooms mentioned in the SQL query above (SCH1.99 and SCH1.34)

I may also want to exclude other SCH rooms, like SCH2.24, SCH3.33 - but I want all the other classrooms to appear.

I've been looking for hours and I think I've reached the limits of my ability - all help welcome.

答:
The condition:

exclude instances when the building is SCH1 and the classroom ID is 99

can be written as:

```<code>NOT (`location`.`building` = 'SCH1' AND `location`.`classroom` = '99')
</code>```

or:

```<code>(`location`.`building` <> 'SCH1' OR `location`.`classroom` <> '99')
</code>```

So do this:

```<code>SELECT `location`.`building`, `location`.`classroom` FROM `schools`
LEFT OUTER JOIN `location`
ON `location`.`location_serial` = `classroom`.`location_serial`
LEFT OUTER JOIN `rack_info`
ON `classroom_info`.`location_serial` = `classroom`.`location_serial`
WHERE
    `location`.`building` LIKE 'SCH%'
    AND
    `classroom_info`.`status` NOT IN (1, 2)
    AND
    (`location`.`building` <> 'SCH1' OR `location`.`classroom` <> '99')
    AND
    (`location`.`building` <> 'SCH1' OR `location`.`classroom` <> '34')
</code>```

Title: MySQL Where Clause Issues

Body:
SELECT `location`.`building`, `location`.`classroom` FROM `schools`
LEFT OUTER JOIN `location`
ON `location`.`location_serial` = `classroom`.`location_serial`
LEFT OUTER JOIN `rack_info`
ON `classroom_info`.`location_serial` = `classroom`.`location_serial`
WHERE (
    (((`location`.`building` LIKE 'SCH%')))
    AND
    (`classroom_info`.`status` NOT IN (1, 2))
    AND
    (
        (
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '99')
            AND
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '34')
        )
    )
)

I'm having a problem in my WHERE clause.

Let's say location.building can be SCH1, SCH2, SCH3, SCH4, CAB1, CAB2. I'm trying to select all of the SCH classrooms, where some classroom statuses are 1 & 2.

This all works fine

The problem arises when I try to further filter my results to exclude instances when the building is SCH1 and the classroom ID is 99, and when the building is SCH1 and the classroom ID is 34. I want to show all other classrooms across all SCH buildings (including SCH1, e.g. SCH1.98) but exclude the two specific classrooms mentioned in the SQL query above (SCH1.99 and SCH1.34)

I may also want to exclude other SCH rooms, like SCH2.24, SCH3.33 - but I want all the other classrooms to appear.

I've been looking for hours and I think I've reached the limits of my ability - all help welcome.

Body:
The condition:

exclude instances when the building is SCH1 and the classroom ID is 99

can be written as:

NOT (`location`.`building` = 'SCH1' AND `location`.`classroom` = '99')

or:

(`location`.`building` <> 'SCH1' OR `location`.`classroom` <> '99')

So do this:

SELECT `location`.`building`, `location`.`classroom` FROM `schools`
LEFT OUTER JOIN `location`
ON `location`.`location_serial` = `classroom`.`location_serial`
LEFT OUTER JOIN `rack_info`
ON `classroom_info`.`location_serial` = `classroom`.`location_serial`
WHERE
    `location`.`building` LIKE 'SCH%'
    AND
    `classroom_info`.`status` NOT IN (1, 2)
    AND
    (`location`.`building` <> 'SCH1' OR `location`.`classroom` <> '99')
    AND
    (`location`.`building` <> 'SCH1' OR `location`.`classroom` <> '34')


问:
Why the sentence "The expression can be used only as the left-hand operand of a member function call" in [expr.ref]p(6.3.2)?
[expr.ref]p(6.3.2):

Otherwise, if E1.E2 refers to a non-static member function and the
  type of E2 is “function of parameter-type-list cv
  ref-qualifieropt returning T”, then E1.E2 is a prvalue. The expression designates a non-static member function. The
  expression can be used only as the left-hand operand of a member
  function call ([class.mfct]). [ Note: Any redundant set of
  parentheses surrounding the expression is ignored ([expr.prim.paren]).
  — end note ] The type of E1.E2 is “function of parameter-type-list
  cv returning T”.

For example the second statement in main below doesn't compile, probably because of the highlighted sentence above. But why is the language set up to work this way?

```<code>#include<iostream>
void g();
struct S { void f(); };
S s;

int main(){
    std::cout << "decltype(g) == void() ? " << std::is_same<decltype(g), void()>::value << '\n';            // Ok
    std::cout << "decltype(s.f) == void() ? " << std::is_same<decltype(s.f), void()>::value << '\n';        // Doesn't compile probably because of the sentence hihlighted above in [expr.ref]p(6.3.2).
}
</code>```

答:
The stat_result.st_mtime syntax was inherited from C, where it always has a value (more particularly, an lvalue).  It is therefore syntactically an expression even in the case of a method call, but it has no value because it is evaluated in concert with its associated call expression.

It is (as you quoted) given the type of the member function so as to satisfy the requirement that a function be called via an expression of the correct type.  It would, however, be misleading to define decltype for it since it cannot be a full-expression (as is every unevaluated operand) and common expression SFINAE with decltype would not prevent a hard error from the guarded instantiation.

Note that a non-static member function can be named in an unevaluated operand, but that allows S::f (or just f within the class, although that is arguably rewritten to be (*this).f in a member function), not s.f.  That expression has the same type but is itself restricted (to appearing with & to form a pointer to member [function]) for the same reason: if it were to be used otherwise, it would be usable as a normal [function] pointer, which is impossible.

Body:
[expr.ref]p(6.3.2):

Otherwise, if E1.E2 refers to a non-static member function and the
  type of E2 is “function of parameter-type-list cv
  ref-qualifieropt returning T”, then E1.E2 is a prvalue. The expression designates a non-static member function. The
  expression can be used only as the left-hand operand of a member
  function call ([class.mfct]). [ Note: Any redundant set of
  parentheses surrounding the expression is ignored ([expr.prim.paren]).
  — end note ] The type of E1.E2 is “function of parameter-type-list
  cv returning T”.

For example the second statement in main below doesn't compile, probably because of the highlighted sentence above. But why is the language set up to work this way?

#include<iostream>
void g();
struct S { void f(); };
S s;

int main(){
    std::cout << "decltype(g) == void() ? " << std::is_same<decltype(g), void()>::value << '\n';            // Ok
    std::cout << "decltype(s.f) == void() ? " << std::is_same<decltype(s.f), void()>::value << '\n';        // Doesn't compile probably because of the sentence hihlighted above in [expr.ref]p(6.3.2).
}


问:
ref with String in mongoose
I have two models

```<code> var Passenger = mongoose.model('passengers', new Schema({
        username: {
            type: String,
            ref: 'users'
        },
        company: String,
        baggage: String,
        note: String,
        owner: String
    }));

    var User = mongoose.model('users', new Schema({
        username: String,
        first: String,
        last: String,
        email: String,
        password: String
    }));
</code>```

I really would like to get a full user instead of a passenger with a username.  I thought ref and populate would be the way to do this.

```<code>Trip.find({
        request: true
    }).populate('flights.users').exec(function (err, trips) {

});
</code>```

The top level document is Trip and Flights is an array under Trips and Passengers is an array under Flights.

Is this not possible.  Would I have to give my users all ID's instead?

Thanks for the help.

Title: ref with String in mongoose

Body:
I have two models

 var Passenger = mongoose.model('passengers', new Schema({
        username: {
            type: String,
            ref: 'users'
        },
        company: String,
        baggage: String,
        note: String,
        owner: String
    }));

    var User = mongoose.model('users', new Schema({
        username: String,
        first: String,
        last: String,
        email: String,
        password: String
    }));

I really would like to get a full user instead of a passenger with a username.  I thought ref and populate would be the way to do this.

Trip.find({
        request: true
    }).populate('flights.users').exec(function (err, trips) {

});

The top level document is Trip and Flights is an array under Trips and Passengers is an array under Flights.

Is this not possible.  Would I have to give my users all ID's instead?

Thanks for the help.

Body: type: mongoose.Schema.Types.ObjectId


问:
(VB.net) Find specified text on an entire line (not just beginning characters) in a listbox
I have a listbox where each line contains a short 3-4 character model number followed by a tab and then the product name the model number corresponds to.  I also have a textbox which I am using to search the listbox.

The code I am using so far works somewhat, just not exactly how I would like.  If I enter search text it will highlight the results in the listbox but only for the first characters, is there anyway to search the text of an entire line (index) of a listbox?

Right now I am using the following:

```<code>Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged

    ListBox.SelectedIndex = ListBox.FindString(txtSearch.Text)

End Sub
</code>```

答:
I got it to work by looping through and using contains.  Issues with upper and lower case were giving me incorrect results so I converted the criteria to all lower.</p>

```<code>For i = 0 To ListBox.Items.Count - 1

     If ListBox.Items(i).ToString.ToLower.Contains(Trim(LCase(txtSearch.Text))) Then
          ListBox.SelectedIndex = i
          Exit For
     End If

Next
</code>```

Body:
I have a listbox where each line contains a short 3-4 character model number followed by a tab and then the product name the model number corresponds to.  I also have a textbox which I am using to search the listbox.

The code I am using so far works somewhat, just not exactly how I would like.  If I enter search text it will highlight the results in the listbox but only for the first characters, is there anyway to search the text of an entire line (index) of a listbox?

Right now I am using the following:

Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged

    ListBox.SelectedIndex = ListBox.FindString(txtSearch.Text)

End Sub

Body:
I got it to work by looping through and using contains.  Issues with upper and lower case were giving me incorrect results so I converted the criteria to all lower.

For i = 0 To ListBox.Items.Count - 1

     If ListBox.Items(i).ToString.ToLower.Contains(Trim(LCase(txtSearch.Text))) Then
          ListBox.SelectedIndex = i
          Exit For
     End If

Next


问:
How to limit a IP address range using FILTER_VALIDATE_IP
I need to implement an IP address filtering system so only authorised IP addresses can access certain resources. I currently use FILTER_VALIDATE_IP and filter_var to validate the IP address.

The problem I am facing is that start and end ip can be 1.1.1.1.1 and the 99.99.99.99 which obviously defeats the who reason for the filtering system. What I need is for the starting IP address for example to be 1.1.1.1.1 but then only the last digit for the ending IP address can be changed e.g 1.1.1.9 otherwise it cannot be saved.

I have included some of the code below:

```<code>if($_POST["lastip"]=='unavailable'  || $_POST['lastip']==''  || filter_var($_POST['lastip'], FILTER_VALIDATE_IP)) {
if($_POST["startip"]=='unavailable' || $_POST['startip']=='' || filter_var($_POST['startip'], FILTER_VALIDATE_IP)){

        $this->db->update("user", array("startip" => "?"), array("id" =>$user->id ), array($_POST['startip']));

        Main::redirect("user/tools", array("success", "Your authorisation settings have been updated successfully."));
    }else{
  Main::redirect("user/tools", array("danger", "The starting authorised IP address is not valid. Please try again."));
    }
}else{
Main::redirect("user/tools", array("danger", "The ending authorised IP address is not valid. Please try again."));
</code>```

答:
code:

```<code><?php

function inIpRagne($ip, $ipLowerRange, $ipUpperRange) {
    $pattern = '/(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)/';

    preg_match($pattern, $ip, $ipArr);
    preg_match($pattern, $ipLowerRange, $ipLowerRangeArr);
    preg_match($pattern, $ipUpperRange, $ipUpperRangeArr);

    array_shift($ipArr);
    array_shift($ipLowerRangeArr);
    array_shift($ipUpperRangeArr);

    foreach($ipArr as $index => $digit) {
        if($digit < $ipLowerRangeArr[$index] || $digit > $ipUpperRangeArr[$index]) {
            return false;
        }
    }

    return true;
}

//ip not in range = false
$ip = '1.2.3.4.5';
$ipLowerRange = '1.1.1.1.1';
$ipUpperRange = '1.1.1.1.1';
$result = inIpRagne($ip, $ipLowerRange, $ipUpperRange);
var_dump($result);

//ip in range = true
$ip = '1.2.3.4.5';
$ipLowerRange = '1.1.1.1.1';
$ipUpperRange = '1.2.3.4.5';
$result = inIpRagne($ip, $ipLowerRange, $ipUpperRange);
var_dump($result);

//ip not in range = false
$ip = '1.1.1.1.10';
$ipLowerRange = '1.1.1.1.1';
$ipUpperRange = '1.1.1.1.9';
$result = inIpRagne($ip, $ipLowerRange, $ipUpperRange);
var_dump($result);

//ip in range = tue
$ip = '1.1.1.1.9';
$ipLowerRange = '1.1.1.1.1';
$ipUpperRange = '1.1.1.1.9';
$result = inIpRagne($ip, $ipLowerRange, $ipUpperRange);
var_dump($result);
</code>```

result:

```<code>bool(false)
bool(true)
bool(false)
bool(true)
</code>```

how to use:

```<code>if(inIpRagne($ip, $ipLowerRange, $ipUpperRange)) {
    //ip is allowed - do your stuff

} else {
    //ip is not allowed
}
</code>```

Body:
I need to implement an IP address filtering system so only authorised IP addresses can access certain resources. I currently use FILTER_VALIDATE_IP and filter_var to validate the IP address.

The problem I am facing is that start and end ip can be 1.1.1.1.1 and the 99.99.99.99 which obviously defeats the who reason for the filtering system. What I need is for the starting IP address for example to be 1.1.1.1.1 but then only the last digit for the ending IP address can be changed e.g 1.1.1.9 otherwise it cannot be saved.

I have included some of the code below:

if($_POST["lastip"]=='unavailable'  || $_POST['lastip']==''  || filter_var($_POST['lastip'], FILTER_VALIDATE_IP)) {
if($_POST["startip"]=='unavailable' || $_POST['startip']=='' || filter_var($_POST['startip'], FILTER_VALIDATE_IP)){

        $this->db->update("user", array("startip" => "?"), array("id" =>$user->id ), array($_POST['startip']));

        Main::redirect("user/tools", array("success", "Your authorisation settings have been updated successfully."));
    }else{
  Main::redirect("user/tools", array("danger", "The starting authorised IP address is not valid. Please try again."));
    }
}else{
Main::redirect("user/tools", array("danger", "The ending authorised IP address is not valid. Please try again."));

Body:
code:

<?php

function inIpRagne($ip, $ipLowerRange, $ipUpperRange) {
    $pattern = '/(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)/';

    preg_match($pattern, $ip, $ipArr);
    preg_match($pattern, $ipLowerRange, $ipLowerRangeArr);
    preg_match($pattern, $ipUpperRange, $ipUpperRangeArr);

    array_shift($ipArr);
    array_shift($ipLowerRangeArr);
    array_shift($ipUpperRangeArr);

    foreach($ipArr as $index => $digit) {
        if($digit < $ipLowerRangeArr[$index] || $digit > $ipUpperRangeArr[$index]) {
            return false;
        }
    }

    return true;
}

//ip not in range = false
$ip = '1.2.3.4.5';
$ipLowerRange = '1.1.1.1.1';
$ipUpperRange = '1.1.1.1.1';
$result = inIpRagne($ip, $ipLowerRange, $ipUpperRange);
var_dump($result);

//ip in range = true
$ip = '1.2.3.4.5';
$ipLowerRange = '1.1.1.1.1';
$ipUpperRange = '1.2.3.4.5';
$result = inIpRagne($ip, $ipLowerRange, $ipUpperRange);
var_dump($result);

//ip not in range = false
$ip = '1.1.1.1.10';
$ipLowerRange = '1.1.1.1.1';
$ipUpperRange = '1.1.1.1.9';
$result = inIpRagne($ip, $ipLowerRange, $ipUpperRange);
var_dump($result);

//ip in range = tue
$ip = '1.1.1.1.9';
$ipLowerRange = '1.1.1.1.1';
$ipUpperRange = '1.1.1.1.9';
$result = inIpRagne($ip, $ipLowerRange, $ipUpperRange);
var_dump($result);

result:

bool(false)
bool(true)
bool(false)
bool(true)

how to use:

if(inIpRagne($ip, $ipLowerRange, $ipUpperRange)) {
    //ip is allowed - do your stuff

} else {
    //ip is not allowed
}


问:
Module parse failed: Octal literal in strict mode
I am working in angular 7 and validating contact number using

```<code>"^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$"
</code>```

regular expression but it is throwing the following error : Module parse failed: Octal literal in strict mode (10:76)

I have already tried \\ instead of \ because as per my finding the problem is with \ character.

```<code>registerForm = this.fb.group(
{
  email:['', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+.com$')]],
  contact:['',[Validators.required, Validators.pattern('/^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$/')]],
  password:['',[Validators.required]],
  confirmPassword:['',[Validators.required]]
},{ validator: PasswordMatchValidator });
</code>```

Is there any way to replace \ character to make it work?

答:
The following regular expressions will allow you to match or replace backslashes:

/\\/    // (1) matches one backslash (the 1st occurrence only)

/\\/g   // (2) matches any occurrence of backslash (global search)

re1 = new RegExp("\\\\","")   // same as (1), with RegExp constructor

re2 = new RegExp("\\\\","g")  // same as (2), with RegExp constructor

based on this article.

According to Angular docs, the Validators.pattern method is accepting string | RegExp. In your case it converts the string to RegExp before using it. Therefore, you would need \\\\ backslashes to get a regular \ backslash.

Body:
I am working in angular 7 and validating contact number using

"^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$"

regular expression but it is throwing the following error : Module parse failed: Octal literal in strict mode (10:76)

I have already tried \\ instead of \ because as per my finding the problem is with \ character.

registerForm = this.fb.group(
{
  email:['', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+.com$')]],
  contact:['',[Validators.required, Validators.pattern('/^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$/')]],
  password:['',[Validators.required]],
  confirmPassword:['',[Validators.required]]
},{ validator: PasswordMatchValidator });

Is there any way to replace \ character to make it work?


问:
How can I call a function that is defined below where it is called?
I'm making an endless text based game in C++ and have multiple functions that need to be able call eachother. I don't seem to be able to do this, because functions need to be defined above where they are called to work, and I can't have them both defined above eachother. How do I make it able to call a function defined below it?

I've tried moving the definition of the functions above eachother, but since one of them needs to call a function defined below it, it  won't work.

```<code>#include <iostream>

void function_one()
{
    int user_selection = 0;
    std::cout << "Enter \"1\" to call function 2.\n";

    switch (user_selection) {
        case 1:
            function_two();
            break;
    }

}

void function_two()
{

    int user_selection = 0;
    std::cout << "Enter \"1\" to call function 1.\n";

    switch (user_selection) {
        case 1:
            function_one();
            break;
    }

}

int main()
{
    function_one();
    return 0;
}
</code>```

I'm using MS Visual Studio 2019, and the error I get is "C3861 'function_one': identifier not found."

答:
Simply declare the functions on the top, and then you can define them later:</p>

```<code>#include <iostream>

void function_one();
void function_two();

int main()
{
    function_one();
    return 0;
}

void function_one()
{
    int user_selection = 0;
    std::cout << "Enter \"1\" to call function 2.\n";

    switch (user_selection) {
        case 1:
            function_two();
            break;
    }
}

void function_two()
{
    int user_selection = 0;
    std::cout << "Enter \"1\" to call function 1.\n";

    switch (user_selection) {
        case 1:
            function_one();
            break;
    }
}
</code>```

Body:
I'm making an endless text based game in C++ and have multiple functions that need to be able call eachother. I don't seem to be able to do this, because functions need to be defined above where they are called to work, and I can't have them both defined above eachother. How do I make it able to call a function defined below it?

I've tried moving the definition of the functions above eachother, but since one of them needs to call a function defined below it, it  won't work.

#include <iostream>

void function_one()
{
    int user_selection = 0;
    std::cout << "Enter \"1\" to call function 2.\n";

    switch (user_selection) {
        case 1:
            function_two();
            break;
    }

}

void function_two()
{

    int user_selection = 0;
    std::cout << "Enter \"1\" to call function 1.\n";

    switch (user_selection) {
        case 1:
            function_one();
            break;
    }

}

int main()
{
    function_one();
    return 0;
}

I'm using MS Visual Studio 2019, and the error I get is "C3861 'function_one': identifier not found."

Body:
Simply declare the functions on the top, and then you can define them later:

#include <iostream>

void function_one();
void function_two();

int main()
{
    function_one();
    return 0;
}

void function_one()
{
    int user_selection = 0;
    std::cout << "Enter \"1\" to call function 2.\n";

    switch (user_selection) {
        case 1:
            function_two();
            break;
    }
}

void function_two()
{
    int user_selection = 0;
    std::cout << "Enter \"1\" to call function 1.\n";

    switch (user_selection) {
        case 1:
            function_one();
            break;
    }
}


问:
Comparing two dictionaries with numpy matrices as values
I want to assert that two Python dictionaries are equal (that means: equal amount of keys, and each mapping from key to value is equal; order is not important). A simple way would be assert A==B, however, this does not work if the values of the dictionaries are numpy arrays. How can I write a function to check in general if two dictionaries are equal?

```<code>>>> import numpy as np
>>> A = {1: np.identity(5)}
>>> B = {1: np.identity(5) + np.ones([5,5])}
>>> A == B
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

EDIT I am aware that numpy matrices shall be checked for equality with .all(). What I am looking for is a general way to check for this, without having to check isinstance(np.ndarray). Would this be possible?

Related topics without numpy arrays:

Comparing two dictionaries in Python

Comparing/combining two dictionaries

答:
I'm going to answer the half-question hidden in your question's title and first half, because frankly, this is a much more common problem to be solved and the existing answers don't address it very well. This question is "How do I compare two dicts of numpy arrays for equality"?

The first part of the problem is checking the dicts "from afar": see that their keys are the same. If all the keys are the same, the second part is comparing each corresponding value.

Now the subtle issue is that a lot of numpy arrays are not integer-valued, and double-precision is imprecise. So unless you have integer-valued (or other non-float-like) arrays you will probably want to check that the values are almost the same, i.e. within machine precision. So in this case you wouldn't use np.array_equal (which checks exact numerical equality), but rather np.allclose (which uses a finite tolerance for the relative and absolute error between two arrays).

The first one and a half parts of the problem are straightforward: check that the keys of the dicts agree, and use a generator comprehension to compare every value (and use all outside the comprehension to verify that each item is the same):

```<code>import numpy as np

# some dummy data

# these are equal exactly
dct1 = {'a': np.array([2, 3, 4])}
dct2 = {'a': np.array([2, 3, 4])}

# these are equal _roughly_
dct3 = {'b': np.array([42.0, 0.2])}
dct4 = {'b': np.array([42.0, 3*0.1 - 0.1])}  # still 0.2, right?

def compare_exact(first, second):
    """Return whether two dicts of arrays are exactly equal"""
    if first.keys() != second.keys():
        return False
    return all(np.array_equal(first[key], second[key]) for key in first)

def compare_approximate(first, second):
    """Return whether two dicts of arrays are roughly equal"""
    if first.keys() != second.keys():
        return False
    return all(np.allclose(first[key], second[key]) for key in first)

# let's try them:
print(compare_exact(dct1, dct2))  # True
print(compare_exact(dct3, dct4))  # False
print(compare_approximate(dct3, dct4))  # True
</code>```

As you can see in the above example, the integer arrays compare fine exactly, and depending on what you're doing (or if you're lucky) it could even work for floats. But if your floats are the result of any kind of arithmetic (linear transformations for instance?) you should definitely use an approximate check. For a complete description of the latter option please see the docs of numpy.allclose (and its elementwise friend, numpy.isclose), with special regard to the rtol and atol keyword arguments.

Body:
I want to assert that two Python dictionaries are equal (that means: equal amount of keys, and each mapping from key to value is equal; order is not important). A simple way would be assert A==B, however, this does not work if the values of the dictionaries are numpy arrays. How can I write a function to check in general if two dictionaries are equal?

>>> import numpy as np
>>> A = {1: np.identity(5)}
>>> B = {1: np.identity(5) + np.ones([5,5])}
>>> A == B
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

EDIT I am aware that numpy matrices shall be checked for equality with .all(). What I am looking for is a general way to check for this, without having to check isinstance(np.ndarray). Would this be possible?

Related topics without numpy arrays:

Comparing two dictionaries in Python

Comparing/combining two dictionaries

Body:
I'm going to answer the half-question hidden in your question's title and first half, because frankly, this is a much more common problem to be solved and the existing answers don't address it very well. This question is "How do I compare two dicts of numpy arrays for equality"?

The first part of the problem is checking the dicts "from afar": see that their keys are the same. If all the keys are the same, the second part is comparing each corresponding value.

Now the subtle issue is that a lot of numpy arrays are not integer-valued, and double-precision is imprecise. So unless you have integer-valued (or other non-float-like) arrays you will probably want to check that the values are almost the same, i.e. within machine precision. So in this case you wouldn't use np.array_equal (which checks exact numerical equality), but rather np.allclose (which uses a finite tolerance for the relative and absolute error between two arrays).

The first one and a half parts of the problem are straightforward: check that the keys of the dicts agree, and use a generator comprehension to compare every value (and use all outside the comprehension to verify that each item is the same):

import numpy as np

# some dummy data

# these are equal exactly
dct1 = {'a': np.array([2, 3, 4])}
dct2 = {'a': np.array([2, 3, 4])}

# these are equal _roughly_
dct3 = {'b': np.array([42.0, 0.2])}
dct4 = {'b': np.array([42.0, 3*0.1 - 0.1])}  # still 0.2, right?

def compare_exact(first, second):
    """Return whether two dicts of arrays are exactly equal"""
    if first.keys() != second.keys():
        return False
    return all(np.array_equal(first[key], second[key]) for key in first)

def compare_approximate(first, second):
    """Return whether two dicts of arrays are roughly equal"""
    if first.keys() != second.keys():
        return False
    return all(np.allclose(first[key], second[key]) for key in first)

# let's try them:
print(compare_exact(dct1, dct2))  # True
print(compare_exact(dct3, dct4))  # False
print(compare_approximate(dct3, dct4))  # True

As you can see in the above example, the integer arrays compare fine exactly, and depending on what you're doing (or if you're lucky) it could even work for floats. But if your floats are the result of any kind of arithmetic (linear transformations for instance?) you should definitely use an approximate check. For a complete description of the latter option please see the docs of numpy.allclose (and its elementwise friend, numpy.isclose), with special regard to the rtol and atol keyword arguments.