问:
IllegalAccessError when adding Rampart to the POM's dependencies
We tried adding Rampart to our module's POM file and after doing so our ear can no longer start with the following exception:

```<code>java.lang.IllegalAccessError: tried to access method org.apache.log4j.Logger.<init>(Ljava/lang/String;)V from class org.apache.log4j.spi.RootLogger
        at org.apache.log4j.spi.RootLogger.<init>(RootLogger.java:43)
        at org.apache.log4j.LogManager.<clinit>(LogManager.java:78)
        at org.apache.log4j.xml.XMLWatchdog.doOnChange(DOMConfigurator.java:862)
        at org.apache.log4j.helpers.FileWatchdog.checkAndConfigure(FileWatchdog.java:88)
        at org.apache.log4j.helpers.FileWatchdog.<init>(FileWatchdog.java:57)
        at org.apache.log4j.xml.XMLWatchdog.<init>(DOMConfigurator.java:853)
        at org.apache.log4j.xml.DOMConfigurator.configureAndWatch(DOMConfigurator.java:584)
</code>```

org.apache.log4j.Logger is defined in two jars - log4j and log4j-over-slf4j.
In log4j - there is a constructor:

```<code>protected Logger(String name)
</code>```

In log4j-over-slf4j there is a constructor:

```<code>Logger(String name) //Package access only
</code>```

It seems that for some reason Rampart triggered a bad classpath order and placed log4j-over-slf4j before log4j.

However, the most troubling problem is that we were unable to change our ear's manifest to change the order - so eventually we "solved" it by adding the log4j jar to the System Classpath

My question has two parts:

Is the Rampart problem familiar and does it have a solution?

What reason could it be that
changing the manifest of the ear
would not effect the classpath? (I'm
not that experienced with
application servers - so obvious
answers are welcome)

We are using Weblogic 10.3, and Rampart 1.5.1. We are using Maven to compile and build the ear file - and I just learned today of a mar file, so any inputs about that will also be welcomed.

答: Eventually we modified the pom.xml manually and changed the order of dependencies to put log4j before rampart - which solved the classpath order problem.

Body:
We tried adding Rampart to our module's POM file and after doing so our ear can no longer start with the following exception:

java.lang.IllegalAccessError: tried to access method org.apache.log4j.Logger.<init>(Ljava/lang/String;)V from class org.apache.log4j.spi.RootLogger
        at org.apache.log4j.spi.RootLogger.<init>(RootLogger.java:43)
        at org.apache.log4j.LogManager.<clinit>(LogManager.java:78)
        at org.apache.log4j.xml.XMLWatchdog.doOnChange(DOMConfigurator.java:862)
        at org.apache.log4j.helpers.FileWatchdog.checkAndConfigure(FileWatchdog.java:88)
        at org.apache.log4j.helpers.FileWatchdog.<init>(FileWatchdog.java:57)
        at org.apache.log4j.xml.XMLWatchdog.<init>(DOMConfigurator.java:853)
        at org.apache.log4j.xml.DOMConfigurator.configureAndWatch(DOMConfigurator.java:584)

org.apache.log4j.Logger is defined in two jars - log4j and log4j-over-slf4j.
In log4j - there is a constructor:

protected Logger(String name)

In log4j-over-slf4j there is a constructor:

Logger(String name) //Package access only

It seems that for some reason Rampart triggered a bad classpath order and placed log4j-over-slf4j before log4j.

However, the most troubling problem is that we were unable to change our ear's manifest to change the order - so eventually we "solved" it by adding the log4j jar to the System Classpath

My question has two parts:

Is the Rampart problem familiar and does it have a solution?

What reason could it be that
changing the manifest of the ear
would not effect the classpath? (I'm
not that experienced with
application servers - so obvious
answers are welcome)

We are using Weblogic 10.3, and Rampart 1.5.1. We are using Maven to compile and build the ear file - and I just learned today of a mar file, so any inputs about that will also be welcomed.


来源: stackexchange

问:
Mysql UNION way to differ from which table result row is
Lets say I have below query.

```<code>SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
</code>```

Lest say there is one same city NY in both tables witch will give me:

```<code>| City     |
| -------- |
| NY       |
| NY       |
</code>```

I am fetching this in a HTML table, is there a way to differ from witch MySQL table result row is from, other then making another column in tables itself, for example column type.

Maybe is possible to append something to result set itself in query?

答:
I don't understand your results, because union removes duplicates, so it should produce only one row.

If you want to include the table name, I would advise using select distinct and union all:

```<code>SELECT DISTINCT 'customers' as type, City FROM Customers
UNION ALL
SELECT DISTINCT 'suppliers' as type, City FROM Suppliers
ORDER BY City;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Lets say I have below query.

SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

Lest say there is one same city NY in both tables witch will give me:

| City     |
| -------- |
| NY       |
| NY       |

I am fetching this in a HTML table, is there a way to differ from witch MySQL table result row is from, other then making another column in tables itself, for example column type.

Maybe is possible to append something to result set itself in query?

Body:
I don't understand your results, because union removes duplicates, so it should produce only one row.

If you want to include the table name, I would advise using select distinct and union all:

SELECT DISTINCT 'customers' as type, City FROM Customers
UNION ALL
SELECT DISTINCT 'suppliers' as type, City FROM Suppliers
ORDER BY City;


问:
conditional compiling three-file project
I have three files:
main.c

```<code>#include <stdio.h>
#include "file3.h"
#define PERMISSION

int main()
{
  #ifdef PERMISSION
  myfunction1();
  #else
  myfunction2();
  #endif // PERMISSION
return 0;
}
</code>```

file2.c

```<code>#include <stdio.h>
#include "file3.h"

#ifdef PERMISSION
void myfunction1()
{
    printf("Inside myfunction1 on file2.c \n");
}
#else
void myfunction2()
{
    printf("Inside myfunction2 on file2.c \n");
}
#endif
</code>```

file3.h

```<code>#ifndef FILE3_H_INCLUDED
#define FILE3_H_INCLUDED

#ifdef PERMISSION
void myfunction1();
#else
void myfunction2();

#endif
#endif
</code>```

I want to control the compilation of the 3-file project with the macro PERMISSION from the main or from the header file. If it is defined I should get all the myfunction1 parts compiled on all three files. If it is not, the myfunction2 parts. But I am getting an error when  ''#define PERMISSION''  is present wether I place it on main.c or on file3.h

Codeblocks shows me that file2 and file3 are defaulting to the else part, so they are not seeing PERMISSION defined. I don't want to put it on all files and modifify all of them when I want it not defined
Right now it's erroing with undefined reference to myfunction1
Maybe I shouldn't put the #ifdef in the header file file3.h but it doesn't work anyway.

How do I get it right?

答:
you need to #define PERMISSION in all files. Either

explixitly place is in each file

put it in a common header

pass it in the compiler -DPERMISSIONS (if you compiler allow s it)

Body:
I have three files:
main.c

#include <stdio.h>
#include "file3.h"
#define PERMISSION

int main()
{
  #ifdef PERMISSION
  myfunction1();
  #else
  myfunction2();
  #endif // PERMISSION
return 0;
}

file2.c

#include <stdio.h>
#include "file3.h"

#ifdef PERMISSION
void myfunction1()
{
    printf("Inside myfunction1 on file2.c \n");
}
#else
void myfunction2()
{
    printf("Inside myfunction2 on file2.c \n");
}
#endif

file3.h

#ifndef FILE3_H_INCLUDED
#define FILE3_H_INCLUDED

#ifdef PERMISSION
void myfunction1();
#else
void myfunction2();

#endif
#endif

I want to control the compilation of the 3-file project with the macro PERMISSION from the main or from the header file. If it is defined I should get all the myfunction1 parts compiled on all three files. If it is not, the myfunction2 parts. But I am getting an error when  ''#define PERMISSION''  is present wether I place it on main.c or on file3.h

Codeblocks shows me that file2 and file3 are defaulting to the else part, so they are not seeing PERMISSION defined. I don't want to put it on all files and modifify all of them when I want it not defined
Right now it's erroing with undefined reference to myfunction1
Maybe I shouldn't put the #ifdef in the header file file3.h but it doesn't work anyway.

How do I get it right?


问:
Can't start mysql ubuntu
I'm having trouble with mysql, I restarted the server, and then it doesn't want to start.

Journalctl give me :

```<code>-- Support: http://www.ubuntu.com/support
--
-- Unit mysql.service has failed.
--
-- The result is RESULT.
Jun 02 01:30:53 localhost systemd[1]: mysql.service: Service hold-off time over, scheduling restart.
Jun 02 01:30:53 localhost systemd[1]: mysql.service: Scheduled restart job, restart counter is at 5.
-- Subject: Automatic restarting of a unit has been scheduled
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Automatic restarting of the unit mysql.service has been scheduled, as the result for
-- the configured Restart= setting for the unit.
Jun 02 01:30:53 localhost systemd[1]: Stopped MySQL Community Server.
-- Subject: Unit mysql.service has finished shutting down
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Unit mysql.service has finished shutting down.
Jun 02 01:30:53 localhost systemd[1]: mysql.service: Start request repeated too quickly.
Jun 02 01:30:53 localhost systemd[1]: mysql.service: Failed with result 'exit-code'.
Jun 02 01:30:53 localhost systemd[1]: Failed to start MySQL Community Server.
-- Subject: Unit mysql.service has failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Unit mysql.service has failed.
--
-- The result is RESULT.
</code>```

In error log I have few things there...

```<code>2020-06-01T22:27:41.964914Z 0 [ERROR] InnoDB: Write to file ./ibtmp1failed at offset 10485760, 1048576 bytes should have been written, only 438272 were written. Operating system error number 28. Check that your OS and file system support files of this size. Check also that the disk is not full or a disk quota exceeded.
2020-06-01T22:27:41.964922Z 0 [ERROR] InnoDB: Error number 28 means 'No space left on device'
2020-06-01T22:27:41.964927Z 0 [Note] InnoDB: Some operating system error numbers are described at http://dev.mysql.com/doc/refman/5.7/en/operating-system-error-codes.html
2020-06-01T22:27:41.964932Z 0 [ERROR] InnoDB: Could not set the file size of './ibtmp1'. Probably out of disk space
2020-06-01T22:27:41.964937Z 0 [ERROR] InnoDB: Unable to create the shared innodb_temporary
2020-06-01T22:27:41.964942Z 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2020-06-01T22:27:42.467258Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2020-06-01T22:27:42.467282Z 0 [ERROR] Plugin 'InnoDB' init function returned error.
2020-06-01T22:27:42.467287Z 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2020-06-01T22:27:42.467293Z 0 [ERROR] Failed to initialize builtin plugins.
2020-06-01T22:27:42.467297Z 0 [ERROR] Aborting
</code>```

I also have some Table 'name' is marked as crashed and should be repaired in the same log file.

Lastly, maybe not relevant but maybe yes, I have some file '7' write error: No space left on device. Although I deleted thousands of picture which should have create space

df -h is

```<code>Filesystem             Size  Used Avail Use% Mounted on
udev                   963M     0  963M   0% /dev
tmpfs                  198M  792K  197M   1% /run
/dev/mapper/vg00-lv01   28G   27G     0 100% /
tmpfs                  986M     0  986M   0% /dev/shm
tmpfs                  5.0M     0  5.0M   0% /run/lock
tmpfs                  986M     0  986M   0% /sys/fs/cgroup
/dev/sda1              464M  113M  323M  26% /boot
tmpfs                  198M     0  198M   0% /run/user/1000
</code>```

df -hi is

```<code>Filesystem            Inodes IUsed IFree IUse% Mounted on
udev                    241K   422  241K    1% /dev
tmpfs                   247K   652  246K    1% /run
/dev/mapper/vg00-lv01   1.8M  166K  1.6M   10% /
tmpfs                   247K     1  247K    1% /dev/shm
tmpfs                   247K     4  247K    1% /run/lock
tmpfs                   247K    18  247K    1% /sys/fs/cgroup
/dev/sda1               122K   311  122K    1% /boot
tmpfs                   247K    10  247K    1% /run/user/1000
</code>```

答:
Your root partition / is 100% used/full.
Which is also reflected (hinted) by the error in mysql.

Try to remove files that will free at least few Gb on / and when df -h shows that you have some free space, then try starting mysql.

As mysql needs to create INNODB files that might be big in size.

Alternatively:

you can either buy more space, depending on your hosting plan, or you can add an additional drive, mount it to /var/lib/mysql so only mysql can utilize that drive.

But you still need to make sure your server can breath and have free space on /

Title: Can't start mysql ubuntu

Body:
I'm having trouble with mysql, I restarted the server, and then it doesn't want to start.

Journalctl give me :

-- Support: http://www.ubuntu.com/support
--
-- Unit mysql.service has failed.
--
-- The result is RESULT.
Jun 02 01:30:53 localhost systemd[1]: mysql.service: Service hold-off time over, scheduling restart.
Jun 02 01:30:53 localhost systemd[1]: mysql.service: Scheduled restart job, restart counter is at 5.
-- Subject: Automatic restarting of a unit has been scheduled
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Automatic restarting of the unit mysql.service has been scheduled, as the result for
-- the configured Restart= setting for the unit.
Jun 02 01:30:53 localhost systemd[1]: Stopped MySQL Community Server.
-- Subject: Unit mysql.service has finished shutting down
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Unit mysql.service has finished shutting down.
Jun 02 01:30:53 localhost systemd[1]: mysql.service: Start request repeated too quickly.
Jun 02 01:30:53 localhost systemd[1]: mysql.service: Failed with result 'exit-code'.
Jun 02 01:30:53 localhost systemd[1]: Failed to start MySQL Community Server.
-- Subject: Unit mysql.service has failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Unit mysql.service has failed.
--
-- The result is RESULT.

In error log I have few things there...

2020-06-01T22:27:41.964914Z 0 [ERROR] InnoDB: Write to file ./ibtmp1failed at offset 10485760, 1048576 bytes should have been written, only 438272 were written. Operating system error number 28. Check that your OS and file system support files of this size. Check also that the disk is not full or a disk quota exceeded.
2020-06-01T22:27:41.964922Z 0 [ERROR] InnoDB: Error number 28 means 'No space left on device'
2020-06-01T22:27:41.964927Z 0 [Note] InnoDB: Some operating system error numbers are described at http://dev.mysql.com/doc/refman/5.7/en/operating-system-error-codes.html
2020-06-01T22:27:41.964932Z 0 [ERROR] InnoDB: Could not set the file size of './ibtmp1'. Probably out of disk space
2020-06-01T22:27:41.964937Z 0 [ERROR] InnoDB: Unable to create the shared innodb_temporary
2020-06-01T22:27:41.964942Z 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2020-06-01T22:27:42.467258Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2020-06-01T22:27:42.467282Z 0 [ERROR] Plugin 'InnoDB' init function returned error.
2020-06-01T22:27:42.467287Z 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2020-06-01T22:27:42.467293Z 0 [ERROR] Failed to initialize builtin plugins.
2020-06-01T22:27:42.467297Z 0 [ERROR] Aborting

I also have some Table 'name' is marked as crashed and should be repaired in the same log file.

Lastly, maybe not relevant but maybe yes, I have some file '7' write error: No space left on device. Although I deleted thousands of picture which should have create space

df -h is

Filesystem             Size  Used Avail Use% Mounted on
udev                   963M     0  963M   0% /dev
tmpfs                  198M  792K  197M   1% /run
/dev/mapper/vg00-lv01   28G   27G     0 100% /
tmpfs                  986M     0  986M   0% /dev/shm
tmpfs                  5.0M     0  5.0M   0% /run/lock
tmpfs                  986M     0  986M   0% /sys/fs/cgroup
/dev/sda1              464M  113M  323M  26% /boot
tmpfs                  198M     0  198M   0% /run/user/1000

df -hi is

Filesystem            Inodes IUsed IFree IUse% Mounted on
udev                    241K   422  241K    1% /dev
tmpfs                   247K   652  246K    1% /run
/dev/mapper/vg00-lv01   1.8M  166K  1.6M   10% /
tmpfs                   247K     1  247K    1% /dev/shm
tmpfs                   247K     4  247K    1% /run/lock
tmpfs                   247K    18  247K    1% /sys/fs/cgroup
/dev/sda1               122K   311  122K    1% /boot
tmpfs                   247K    10  247K    1% /run/user/1000


问:
How to update datatable in real time of a database external to the laravel 5.5 application
I have implemented a Laravel 5.5 application for displaying data stored in an external database in a datatable. the external database is powered by an application that monitors the network. I would like to update my datatable in real time and from what I read on the network I understood that:

I cannot use Laravel model events because the table is powered by an
external application and not by Laravel.

I cannot launch a Laravel method from a trigger or store procedure
on MySQL because it is not allowed.

So I ask you who are reading if you can give me an idea on how to get a datatable update in real time or near real time.
I know, I could use the setinterval () function to continuously poll the database. I would like to avoid updating the datatable and would prefer to find a way to use the addRow methods. But I wonder if there is a smarter way to get the real time.

答:
Use  yajra / laravel-datatables package with custom queries. You can use Ajax sourced data for front end.

```<code>$(function() {
    $('#users-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '/user-data',
        columns: [
            { data: 'id', name: 'id' },
            { data: 'name', name: 'name' },
            { data: 'email', name: 'email' },
            { data: 'created_at', name: 'created_at' },
            { data: 'updated_at', name: 'updated_at' }
        ]
    });
});
</code>```

For backend,

```<code>use DB;
use DataTables;

Route::get('/user-data', function() {
    return Datatables::queryBuilder(DB::table('users'))->make(true);
});
</code>```

And you have to install and call  yajra / laravel-datatables package but it's real easy five minutes process. Also read here for more examples.

Body:
Use  yajra / laravel-datatables package with custom queries. You can use Ajax sourced data for front end.

$(function() {
    $('#users-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '/user-data',
        columns: [
            { data: 'id', name: 'id' },
            { data: 'name', name: 'name' },
            { data: 'email', name: 'email' },
            { data: 'created_at', name: 'created_at' },
            { data: 'updated_at', name: 'updated_at' }
        ]
    });
});

For backend,

use DB;
use DataTables;

Route::get('/user-data', function() {
    return Datatables::queryBuilder(DB::table('users'))->make(true);
});

And you have to install and call  yajra / laravel-datatables package but it's real easy five minutes process. Also read here for more examples.


问:
How to use max function in this query with sum after joining 3 tables
```<code>SELECT  s.seg_name, p.category,  SUM(t.item_qty * t.item_price) revenue
FROM segments s
JOIN transactions t
ON s.cust_id = t.cust_id
JOIN products p
ON p.prod_id = t.prod_id
WHERE s.active_flag = 'Y'
GROUP BY s.seg_name, p.category
</code>```

I want to use the max function or something else to select the highest revenue based on the given group columns in the query posted

答:
There is more than one way to understand your question.

If you want to top row in the resultset, use ORDER BY and LIMIT:

```<code>SELECT  s.seg_name, p.category,  SUM(t.item_qty * t.item_price) revenue
FROM segments s
JOIN transactions t  ON s.cust_id = t.cust_id
JOIN products p  ON p.prod_id = t.prod_id
WHERE s.active_flag = 'Y'
GROUP BY s.seg_name, p.category
ORDER BY revenue DESC
LIMIT 1
</code>```

On the other hand, if you want to keep all rows and add one column that show the top revenue over the whole dataset, then you can use window functions (available in MySQL 8.0 only):

```<code>SELECT
    s.seg_name,
    p.category,
    SUM(t.item_qty * t.item_price) revenue,
    MAX(SUM(t.item_qty * t.item_price)) OVER() max_revenue
FROM segments s
JOIN transactions t  ON s.cust_id = t.cust_id
JOIN products p  ON p.prod_id = t.prod_id
WHERE s.active_flag = 'Y'
GROUP BY s.seg_name, p.category
</code>```

Body:
SELECT  s.seg_name, p.category,  SUM(t.item_qty * t.item_price) revenue
FROM segments s
JOIN transactions t
ON s.cust_id = t.cust_id
JOIN products p
ON p.prod_id = t.prod_id
WHERE s.active_flag = 'Y'
GROUP BY s.seg_name, p.category

I want to use the max function or something else to select the highest revenue based on the given group columns in the query posted

Body:
There is more than one way to understand your question.

If you want to top row in the resultset, use ORDER BY and LIMIT:

SELECT  s.seg_name, p.category,  SUM(t.item_qty * t.item_price) revenue
FROM segments s
JOIN transactions t  ON s.cust_id = t.cust_id
JOIN products p  ON p.prod_id = t.prod_id
WHERE s.active_flag = 'Y'
GROUP BY s.seg_name, p.category
ORDER BY revenue DESC
LIMIT 1

On the other hand, if you want to keep all rows and add one column that show the top revenue over the whole dataset, then you can use window functions (available in MySQL 8.0 only):

SELECT
    s.seg_name,
    p.category,
    SUM(t.item_qty * t.item_price) revenue,
    MAX(SUM(t.item_qty * t.item_price)) OVER() max_revenue
FROM segments s
JOIN transactions t  ON s.cust_id = t.cust_id
JOIN products p  ON p.prod_id = t.prod_id
WHERE s.active_flag = 'Y'
GROUP BY s.seg_name, p.category


问:
How to use list comprehension in the following case?
I have a text file which has names of the universities. I want to clean this dataset - remove whitespaces and empty lines. I have achieved this with the following code. However, is there an efficient way of achieving this? May be using List Comprehensions?

Code:

```<code>txtfile = open('university_towns.txt', 'r')
lines = txtfile.readlines()
txtfile.close()

#Removing empty lines and whitespaces
new_lines = []
for line in lines:
    if not re.match(r'^\s*$', line):
        new_lines.append(line.strip())
lines = new_lines.copy()```
```

答:
Try this code with list comprehension.</p>

```<code>with open('university_towns.txt', 'r') as f:
    lines = [line.strip() for line in f.readlines() if not re.match(r'^\s*$', line)]
</code>```

Body:
I have a text file which has names of the universities. I want to clean this dataset - remove whitespaces and empty lines. I have achieved this with the following code. However, is there an efficient way of achieving this? May be using List Comprehensions?

Code:

txtfile = open('university_towns.txt', 'r')
lines = txtfile.readlines()
txtfile.close()

#Removing empty lines and whitespaces
new_lines = []
for line in lines:
    if not re.match(r'^\s*$', line):
        new_lines.append(line.strip())
lines = new_lines.copy()```

Body:
Try this code with list comprehension.

with open('university_towns.txt', 'r') as f:
    lines = [line.strip() for line in f.readlines() if not re.match(r'^\s*$', line)]


问:
Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response
I have come across CORS issues multiple times and can usually fix it but I want to really understand by seeing this from a MEAN stack paradigm.

Before I simply added middleware in my express server to catch these things, but it looks like there is some kind of pre-hook that is erroring out my requests.

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response

I assumed that I could do this:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers","*")
})
```

<p>or the equivalent but this doesn't seem to fix it. I also of course tried</p>

<pre class="lang-js prettyprint-override"><code>app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers","Access-Control-Allow-Headers")
})
</code>```

Still no luck.

答:
```<code>const express = require('express')
const cors = require('cors')
const app = express()

app.get('/with-cors', cors(), (req, res, next) => {
  res.json({ msg: 'WHOAH with CORS it works!  ' })
})
</code>```

<p>Adding cors in get function Is what worked for me </p>

Body:
I have come across CORS issues multiple times and can usually fix it but I want to really understand by seeing this from a MEAN stack paradigm.

Before I simply added middleware in my express server to catch these things, but it looks like there is some kind of pre-hook that is erroring out my requests.

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response

I assumed that I could do this:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers","*")
})

or the equivalent but this doesn't seem to fix it. I also of course tried

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers","Access-Control-Allow-Headers")
})

Still no luck.

Body:
const express = require('express')
const cors = require('cors')
const app = express()

app.get('/with-cors', cors(), (req, res, next) => {
  res.json({ msg: 'WHOAH with CORS it works!  ' })
})

Adding cors in get function Is what worked for me


问:
spacy Can't find model 'en_core_web_sm' on windows 10 and Python 3.5.3 :: Anaconda custom (64-bit)
what is difference between spacy.load('en_core_web_sm') and spacy.load('en')? This link explains different model sizes. But i am still not clear how spacy.load('en_core_web_sm') and spacy.load('en') differ

spacy.load('en') runs fine for me. But the spacy.load('en_core_web_sm') throws error

i have installed spacyas below. when i go to jupyter notebook and run command nlp = spacy.load('en_core_web_sm') I get the below error

```<code>---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-4-b472bef03043> in <module>()
      1 # Import spaCy and load the language library
      2 import spacy
----> 3 nlp = spacy.load('en_core_web_sm')
      4
      5 # Create a Doc object

C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\spacy\__init__.py in load(name, **overrides)
     13     if depr_path not in (True, False, None):
     14         deprecation_warning(Warnings.W001.format(path=depr_path))
---> 15     return util.load_model(name, **overrides)
     16
     17

C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\spacy\util.py in load_model(name, **overrides)
    117     elif hasattr(name, 'exists'):  # Path or Path-like to model data
    118         return load_model_from_path(name, **overrides)
--> 119     raise IOError(Errors.E050.format(name=name))
    120
    121

OSError: [E050] Can't find model 'en_core_web_sm'. It doesn't seem to be a shortcut link, a Python package or a valid path to a data directory.
</code>```

how I installed Spacy ---

```<code>(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>conda install -c conda-forge spacy
Fetching package metadata .............
Solving package specifications: .

Package plan for installation in environment C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder:

The following NEW packages will be INSTALLED:

    blas:           1.0-mkl
    cymem:          1.31.2-py35h6538335_0    conda-forge
    dill:           0.2.8.2-py35_0           conda-forge
    msgpack-numpy:  0.4.4.2-py_0             conda-forge
    murmurhash:     0.28.0-py35h6538335_1000 conda-forge
    plac:           0.9.6-py_1               conda-forge
    preshed:        1.0.0-py35h6538335_0     conda-forge
    pyreadline:     2.1-py35_1000            conda-forge
    regex:          2017.11.09-py35_0        conda-forge
    spacy:          2.0.12-py35h830ac7b_0    conda-forge
    termcolor:      1.1.0-py_2               conda-forge
    thinc:          6.10.3-py35h830ac7b_2    conda-forge
    tqdm:           4.29.1-py_0              conda-forge
    ujson:          1.35-py35hfa6e2cd_1001   conda-forge

The following packages will be UPDATED:

    msgpack-python: 0.4.8-py35_0                         --> 0.5.6-py35he980bc4_3 conda-forge

The following packages will be DOWNGRADED:

    freetype:       2.7-vc14_2               conda-forge --> 2.5.5-vc14_2

Proceed ([y]/n)? y

blas-1.0-mkl.t 100% |###############################| Time: 0:00:00   0.00  B/s
cymem-1.31.2-p 100% |###############################| Time: 0:00:00   1.65 MB/s
msgpack-python 100% |###############################| Time: 0:00:00   5.37 MB/s
murmurhash-0.2 100% |###############################| Time: 0:00:00   1.49 MB/s
plac-0.9.6-py_ 100% |###############################| Time: 0:00:00   0.00  B/s
pyreadline-2.1 100% |###############################| Time: 0:00:00   4.62 MB/s
regex-2017.11. 100% |###############################| Time: 0:00:00   3.31 MB/s
termcolor-1.1. 100% |###############################| Time: 0:00:00 187.81 kB/s
tqdm-4.29.1-py 100% |###############################| Time: 0:00:00   2.51 MB/s
ujson-1.35-py3 100% |###############################| Time: 0:00:00   1.66 MB/s
dill-0.2.8.2-p 100% |###############################| Time: 0:00:00   4.34 MB/s
msgpack-numpy- 100% |###############################| Time: 0:00:00   0.00  B/s
preshed-1.0.0- 100% |###############################| Time: 0:00:00   0.00  B/s
thinc-6.10.3-p 100% |###############################| Time: 0:00:00   5.49 MB/s
spacy-2.0.12-p 100% |###############################| Time: 0:00:10   7.42 MB/s

(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>python -V
Python 3.5.3 :: Anaconda custom (64-bit)

(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>python -m spacy download en
Collecting en_core_web_sm==2.0.0 from https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz#egg=en_core_web_sm==2.0.0
  Downloading https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz (37.4MB)
    100% |################################| 37.4MB ...
Installing collected packages: en-core-web-sm
  Running setup.py install for en-core-web-sm ... done
Successfully installed en-core-web-sm-2.0.0

    Linking successful
    C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\en_core_web_sm
    -->
    C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\spacy\data\en

    You can now load the model via spacy.load('en')

(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>
</code>```

答:
Anaconda Users

If you're using a conda virtual environment, be sure that its the same version of Python as that in your base environment. To verify this, run python --version in each environment. If not the same, create a new virtual environment with that version of Python (Ex. conda create --name myenv python=x.x.x).

Activate the virtual environment (conda activate myenv)

conda install -c conda-forge spacy

python -m spacy download en_core_web_sm

I just ran into this issue, and the above worked for me. This addresses the issue of the download occurring in an area that is not accessible to your current virtual environment.

You should then be able to run the following:

```<code>import spacy
nlp = spacy.load("en_core_web_sm")
</code>```

Body:
what is difference between spacy.load('en_core_web_sm') and spacy.load('en')? This link explains different model sizes. But i am still not clear how spacy.load('en_core_web_sm') and spacy.load('en') differ

spacy.load('en') runs fine for me. But the spacy.load('en_core_web_sm') throws error

i have installed spacyas below. when i go to jupyter notebook and run command nlp = spacy.load('en_core_web_sm') I get the below error

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-4-b472bef03043> in <module>()
      1 # Import spaCy and load the language library
      2 import spacy
----> 3 nlp = spacy.load('en_core_web_sm')
      4
      5 # Create a Doc object

C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\spacy\__init__.py in load(name, **overrides)
     13     if depr_path not in (True, False, None):
     14         deprecation_warning(Warnings.W001.format(path=depr_path))
---> 15     return util.load_model(name, **overrides)
     16
     17

C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\spacy\util.py in load_model(name, **overrides)
    117     elif hasattr(name, 'exists'):  # Path or Path-like to model data
    118         return load_model_from_path(name, **overrides)
--> 119     raise IOError(Errors.E050.format(name=name))
    120
    121

OSError: [E050] Can't find model 'en_core_web_sm'. It doesn't seem to be a shortcut link, a Python package or a valid path to a data directory.

how I installed Spacy ---

(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>conda install -c conda-forge spacy
Fetching package metadata .............
Solving package specifications: .

Package plan for installation in environment C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder:

The following NEW packages will be INSTALLED:

    blas:           1.0-mkl
    cymem:          1.31.2-py35h6538335_0    conda-forge
    dill:           0.2.8.2-py35_0           conda-forge
    msgpack-numpy:  0.4.4.2-py_0             conda-forge
    murmurhash:     0.28.0-py35h6538335_1000 conda-forge
    plac:           0.9.6-py_1               conda-forge
    preshed:        1.0.0-py35h6538335_0     conda-forge
    pyreadline:     2.1-py35_1000            conda-forge
    regex:          2017.11.09-py35_0        conda-forge
    spacy:          2.0.12-py35h830ac7b_0    conda-forge
    termcolor:      1.1.0-py_2               conda-forge
    thinc:          6.10.3-py35h830ac7b_2    conda-forge
    tqdm:           4.29.1-py_0              conda-forge
    ujson:          1.35-py35hfa6e2cd_1001   conda-forge

The following packages will be UPDATED:

    msgpack-python: 0.4.8-py35_0                         --> 0.5.6-py35he980bc4_3 conda-forge

The following packages will be DOWNGRADED:

    freetype:       2.7-vc14_2               conda-forge --> 2.5.5-vc14_2

Proceed ([y]/n)? y

blas-1.0-mkl.t 100% |###############################| Time: 0:00:00   0.00  B/s
cymem-1.31.2-p 100% |###############################| Time: 0:00:00   1.65 MB/s
msgpack-python 100% |###############################| Time: 0:00:00   5.37 MB/s
murmurhash-0.2 100% |###############################| Time: 0:00:00   1.49 MB/s
plac-0.9.6-py_ 100% |###############################| Time: 0:00:00   0.00  B/s
pyreadline-2.1 100% |###############################| Time: 0:00:00   4.62 MB/s
regex-2017.11. 100% |###############################| Time: 0:00:00   3.31 MB/s
termcolor-1.1. 100% |###############################| Time: 0:00:00 187.81 kB/s
tqdm-4.29.1-py 100% |###############################| Time: 0:00:00   2.51 MB/s
ujson-1.35-py3 100% |###############################| Time: 0:00:00   1.66 MB/s
dill-0.2.8.2-p 100% |###############################| Time: 0:00:00   4.34 MB/s
msgpack-numpy- 100% |###############################| Time: 0:00:00   0.00  B/s
preshed-1.0.0- 100% |###############################| Time: 0:00:00   0.00  B/s
thinc-6.10.3-p 100% |###############################| Time: 0:00:00   5.49 MB/s
spacy-2.0.12-p 100% |###############################| Time: 0:00:10   7.42 MB/s

(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>python -V
Python 3.5.3 :: Anaconda custom (64-bit)

(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>python -m spacy download en
Collecting en_core_web_sm==2.0.0 from https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz#egg=en_core_web_sm==2.0.0
  Downloading https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz (37.4MB)
    100% |################################| 37.4MB ...
Installing collected packages: en-core-web-sm
  Running setup.py install for en-core-web-sm ... done
Successfully installed en-core-web-sm-2.0.0

    Linking successful
    C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\en_core_web_sm
    -->
    C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\spacy\data\en

    You can now load the model via spacy.load('en')

(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>

Body:
Anaconda Users

If you're using a conda virtual environment, be sure that its the same version of Python as that in your base environment. To verify this, run python --version in each environment. If not the same, create a new virtual environment with that version of Python (Ex. conda create --name myenv python=x.x.x).

Activate the virtual environment (conda activate myenv)

conda install -c conda-forge spacy

python -m spacy download en_core_web_sm

I just ran into this issue, and the above worked for me. This addresses the issue of the download occurring in an area that is not accessible to your current virtual environment.

You should then be able to run the following:

import spacy
nlp = spacy.load("en_core_web_sm")


问:
Prevent React Router from routing a server API path
On the server an API only path has been set under /api.

When calling this path on the client-side, react-router takes over and responds with:

```<code>browser.js:49 Warning: [react-router] Location "/api/my_request" did not match any routes
</code>```

How can we tell react-router to bypass this and just send the request out to the server?

Update:

This is how the request is being sent:

```<code>const sock = new SockJS('http://localhost:3030/api')

sock.onopen = () => {
  console.log('open')
}
sock.onmessage = (e) => {
  console.log('message', e.data)
}
sock.onclose = () => {
  console.log('close')
}

sock.send('test')
</code>```

答:
Hi i had the same issue and this was my solution, this is my DefaultController the entry point of the React app.

```<code>class DefaultController extends AbstractController
{
   /**
   * @Route("/{reactRouting}", name="home", requirements={"reactRouting"="^(?!api).+"}, defaults={"reactRouting": null})
   */
  public function index()
  {
    return $this->render('default/index.html.twig', [
        'controller_name' => 'DefaultController',
    ]);
  }
}
</code>```

Notice that the "requirements" defines the regex for bypass /api path, and with this react router will ignore this route and the request will be handle by the server. I hope this works for you. Regards!

ContentLicense: CC BY-SA 3.0

Body:
On the server an API only path has been set under /api.

When calling this path on the client-side, react-router takes over and responds with:

browser.js:49 Warning: [react-router] Location "/api/my_request" did not match any routes

How can we tell react-router to bypass this and just send the request out to the server?

Update:

This is how the request is being sent:

const sock = new SockJS('http://localhost:3030/api')

sock.onopen = () => {
  console.log('open')
}
sock.onmessage = (e) => {
  console.log('message', e.data)
}
sock.onclose = () => {
  console.log('close')
}

sock.send('test')

Body:
Hi i had the same issue and this was my solution, this is my DefaultController the entry point of the React app.

class DefaultController extends AbstractController
{
   /**
   * @Route("/{reactRouting}", name="home", requirements={"reactRouting"="^(?!api).+"}, defaults={"reactRouting": null})
   */
  public function index()
  {
    return $this->render('default/index.html.twig', [
        'controller_name' => 'DefaultController',
    ]);
  }
}

Notice that the "requirements" defines the regex for bypass /api path, and with this react router will ignore this route and the request will be handle by the server. I hope this works for you. Regards!


问:
Python OpenCV live face detection crop saved
I have done tons of research into this , and I think my logic are worn out , almost there but can't seem to understand why nothing is display in the cv2.imshow() windows just a grey box , however good news is I am able to detect a face and crop that face then save it in the folder.

can you please shed some light of where I have gone wrong

```<code>#Author: Waheed Rafiq
#Research Student Birmingham City University
#Date: 03/11/2016
#Description :detect and Save capture face in a folder.

#Import library required for Capture face.

import cv2

#import the cascade for face detection
FaceClassifier =cv2.CascadeClassifier
('haarcascade_frontalface_default.xml')
# access the webcam (every webcam has
capture = cv2.VideoCapture(0)

   while(True):
     # Capture frame-by-frame

    ret, frame = capture.read()
    if not capture:
    print "Error opening webcam device"
    sys.exit(1)

    # to detect faces in video
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = FaceClassifier.detectMultiScale(gray, 1.3, 5)

    # Resize Image
    minisize = (frame.shape[1],frame.shape[0])
    miniframe = cv2.resize(frame, minisize)
    # Store detected frames in variable name faces
   faces =  FaceClassifier.detectMultiScale(miniframe)
   # Draw rectangle
   for f in faces:
    x, y, w, h = [ v for v in f ]
    cv2.rectangle(frame, (x,y), (x+w,y+h), (255,255,255))
    #Save just the rectangle faces in SubRecFaces
    sub_face = frame[y:y+h, x:x+w]
    FaceFileName = "unknowfaces/face_" + str(y) + ".jpg"
    cv2.imwrite(FaceFileName, sub_face)
    #Display the image
    cv2.imshow('Result',frame)

    break

    # When everything done, release the capture

    img.release()
    cv2.waitKey(20)
    cv2.destroyAllWindows()
</code>```

really would appericate your support

答:
It's the 'working' version of the code with Python 3.6 OpenCV 4+. You don't have to refer anyone, use it freely. </p>

```<code>import cv2
import os

classifier = cv2.CascadeClassifier(cv2.data.haarcascades+"haarcascade_frontalface_default.xml")

dirFace = 'cropped_face'

# Create if there is no cropped face directory
if not os.path.exists(dirFace):
    os.mkdir(dirFace)
    print("Directory " , dirFace ,  " Created ")
else:
    print("Directory " , dirFace ,  " has found.")

webcam = cv2.VideoCapture(0) # Camera 0 according to USB port
# video = cv2.VideoCapture(r"use full windows path") # video path

while (True):
    (f, im) = webcam.read() # f returns only True, False according to video access
    # (f, im) = video.read() # video

    if f != True:
       break

    # im=cv2.flip(im,1,0) #if you would like to give mirror effect

    # detectfaces
    faces = classifier.detectMultiScale(
        im, # stream
        scaleFactor=1.10, # change these parameters to improve your video processing performance
        minNeighbors=20,
        minSize=(30, 30) # min image detection size
        )

    # Draw rectangles around each face
    for (x, y, w, h) in faces:

        cv2.rectangle(im, (x, y), (x + w, y + h),(0,0,255),thickness=2)
        # saving faces according to detected coordinates
        sub_face = im[y:y+h, x:x+w]
        FaceFileName = "cropped_face/face_" + str(y+x) + ".jpg" # folder path and random name image
        cv2.imwrite(FaceFileName, sub_face)

    # Video Window
    cv2.imshow('Video Stream',im)
    key = cv2.waitKey(1) & 0xFF
    # q for exit
    if key == ord('q'):
        break
webcam.release()
</code>```

Body:
I have done tons of research into this , and I think my logic are worn out , almost there but can't seem to understand why nothing is display in the cv2.imshow() windows just a grey box , however good news is I am able to detect a face and crop that face then save it in the folder.

can you please shed some light of where I have gone wrong

#Author: Waheed Rafiq
#Research Student Birmingham City University
#Date: 03/11/2016
#Description :detect and Save capture face in a folder.

#Import library required for Capture face.

import cv2

#import the cascade for face detection
FaceClassifier =cv2.CascadeClassifier
('haarcascade_frontalface_default.xml')
# access the webcam (every webcam has
capture = cv2.VideoCapture(0)

   while(True):
     # Capture frame-by-frame

    ret, frame = capture.read()
    if not capture:
    print "Error opening webcam device"
    sys.exit(1)

    # to detect faces in video
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = FaceClassifier.detectMultiScale(gray, 1.3, 5)

    # Resize Image
    minisize = (frame.shape[1],frame.shape[0])
    miniframe = cv2.resize(frame, minisize)
    # Store detected frames in variable name faces
   faces =  FaceClassifier.detectMultiScale(miniframe)
   # Draw rectangle
   for f in faces:
    x, y, w, h = [ v for v in f ]
    cv2.rectangle(frame, (x,y), (x+w,y+h), (255,255,255))
    #Save just the rectangle faces in SubRecFaces
    sub_face = frame[y:y+h, x:x+w]
    FaceFileName = "unknowfaces/face_" + str(y) + ".jpg"
    cv2.imwrite(FaceFileName, sub_face)
    #Display the image
    cv2.imshow('Result',frame)

    break

    # When everything done, release the capture

    img.release()
    cv2.waitKey(20)
    cv2.destroyAllWindows()

really would appericate your support

Body:
It's the 'working' version of the code with Python 3.6 OpenCV 4+. You don't have to refer anyone, use it freely.

import cv2
import os

classifier = cv2.CascadeClassifier(cv2.data.haarcascades+"haarcascade_frontalface_default.xml")

dirFace = 'cropped_face'

# Create if there is no cropped face directory
if not os.path.exists(dirFace):
    os.mkdir(dirFace)
    print("Directory " , dirFace ,  " Created ")
else:
    print("Directory " , dirFace ,  " has found.")

webcam = cv2.VideoCapture(0) # Camera 0 according to USB port
# video = cv2.VideoCapture(r"use full windows path") # video path

while (True):
    (f, im) = webcam.read() # f returns only True, False according to video access
    # (f, im) = video.read() # video

    if f != True:
       break

    # im=cv2.flip(im,1,0) #if you would like to give mirror effect

    # detectfaces
    faces = classifier.detectMultiScale(
        im, # stream
        scaleFactor=1.10, # change these parameters to improve your video processing performance
        minNeighbors=20,
        minSize=(30, 30) # min image detection size
        )

    # Draw rectangles around each face
    for (x, y, w, h) in faces:

        cv2.rectangle(im, (x, y), (x + w, y + h),(0,0,255),thickness=2)
        # saving faces according to detected coordinates
        sub_face = im[y:y+h, x:x+w]
        FaceFileName = "cropped_face/face_" + str(y+x) + ".jpg" # folder path and random name image
        cv2.imwrite(FaceFileName, sub_face)

    # Video Window
    cv2.imshow('Video Stream',im)
    key = cv2.waitKey(1) & 0xFF
    # q for exit
    if key == ord('q'):
        break
webcam.release()


问:
Time difference in pandas (from string format to datetime)
I have the following column

```<code>Time
2:00
00:13
1:00
00:24
</code>```

in object format (strings). This time refers to hours and minutes ago from a time that I need to use as a start: 8:00 (it might change; in this example is 8:00).

Since the times in the column Time are referring to hours/minutes ago, what I would like to expect should be

```<code>Time
6:00
07:47
7:00
07:36
</code>```

calculated as time difference (e.g. 8:00 - 2:00).
However, I am having difficulties in doing this calculation and transform the result in a datetime (keeping only hours and minutes).
I hope you can help me.

答:
you can do it using pd.to_datetime.

```<code>ref = pd.to_datetime('08:00') #here define the hour of reference
s = ref-pd.to_datetime(df['Time'])
print (s)
0   06:00:00
1   07:47:00
2   07:00:00
3   07:36:00
Name: Time, dtype: timedelta64[ns]
</code>```

This return a series, that can be change to a dataframe with s.to_frame() for example

Body:
I have the following column

Time
2:00
00:13
1:00
00:24

in object format (strings). This time refers to hours and minutes ago from a time that I need to use as a start: 8:00 (it might change; in this example is 8:00).

Since the times in the column Time are referring to hours/minutes ago, what I would like to expect should be

Time
6:00
07:47
7:00
07:36

calculated as time difference (e.g. 8:00 - 2:00).
However, I am having difficulties in doing this calculation and transform the result in a datetime (keeping only hours and minutes).
I hope you can help me.

Body:
you can do it using pd.to_datetime.

ref = pd.to_datetime('08:00') #here define the hour of reference
s = ref-pd.to_datetime(df['Time'])
print (s)
0   06:00:00
1   07:47:00
2   07:00:00
3   07:36:00
Name: Time, dtype: timedelta64[ns]

This return a series, that can be change to a dataframe with s.to_frame() for example


问:
Spring Boot: Perform encryption/decryption using Annotation: MongoDB
I have a requirement where I have to encrypt a field before saving in the database and decrypt it while retrieving it. The fields that should be encrypted should be custom annotated.

I am using spring-boot with MongoDB for this.

Example:

```<code>Class Person {

Long ID;

String userName;

String password;

@EncryptThisField
String firstName;

@EncryptThisField
String lastName;

... SETTER and GETTERS

}
</code>```

Based on annotation my setter should set encrypted value(and save to database) and getter should return decrypted value(and retrieve from database).

Any pointers or suggestions?

答: you should create two functional-interface. One to encrypt and other decrypt. use the annotation on the setter and getter methods instead of on the field. </p>

Body:
I have a requirement where I have to encrypt a field before saving in the database and decrypt it while retrieving it. The fields that should be encrypted should be custom annotated.

I am using spring-boot with MongoDB for this.

Example:

Class Person {

Long ID;

String userName;

String password;

@EncryptThisField
String firstName;

@EncryptThisField
String lastName;

... SETTER and GETTERS

}

Based on annotation my setter should set encrypted value(and save to database) and getter should return decrypted value(and retrieve from database).

Any pointers or suggestions?


问:
"Incorrect Directory" while adding resource file in android studio
I am trying to add resource file in android studio by right clicking on res folder but it is showing an error "Incorrect Directory". I don't know what I am doing wrong. Any help is appreciated.

答: Same problem occurred with me. This problem occurs because of same directory already present in the res folder. All you have to do is to navigate to res folder in file explorer and you will see a folder created by you earlier OR a folder other than these folders:- drawable, minmap, layout, values. Delete other folders keeping these four folders untouched and try to create resource layout file again.


问:
How to see the rendered HTML page, not code, in Firefox
I wrote a simple HTML page, and when I open it in Firefox, it doesn’t show the web page but the code.

I think the problem is Vim because it’s like that doesn’t recognize characters such as comments(#) etc.

答:
My guess would be that the problem is not Vim, since its sole purpose is to be a plaintext editor. It allows you to edit a file, and doesn't really do much else (but boy, can it do that job well).

Are you sure the file has .html as its extension? Browsers tend to judge a file's characteristics almost exclusively on its extension, so if it's saved as a .txt file or something else then it will just show the plaintext.

I also just noticed your line about comments with a hash (#). These do not constitute comments in HTML, and will probably break things in more ways than one. If you're commenting something in HTML, make sure you use  as the delimiters, respectively.

Body:
My guess would be that the problem is not Vim, since its sole purpose is to be a plaintext editor. It allows you to edit a file, and doesn't really do much else (but boy, can it do that job well).

Are you sure the file has .html as its extension? Browsers tend to judge a file's characteristics almost exclusively on its extension, so if it's saved as a .txt file or something else then it will just show the plaintext.

I also just noticed your line about comments with a hash (#). These do not constitute comments in HTML, and will probably break things in more ways than one. If you're commenting something in HTML, make sure you use <!-- and --> as the delimiters, respectively.


问:
ImportError: No module named 'spacy.en'
I'm working on a codebase that uses Spacy. I installed spacy using:

```<code>sudo pip3 install spacy
</code>```

and then

```<code>sudo python3 -m spacy download en
</code>```

At the end of this last command, I got a message:

```<code>    Linking successful
/home/rayabhik/.local/lib/python3.5/site-packages/en_core_web_sm -->
/home/rayabhik/.local/lib/python3.5/site-packages/spacy/data/en

You can now load the model via spacy.load('en')
</code>```

Now, when I try running my code, on the line:

```<code>    from spacy.en import English
</code>```

it gives me the following error:

```<code>ImportError: No module named 'spacy.en'
</code>```

I've looked on Stackexchange and the closest is:  Import error with spacy: "No module named en"
which does not solve my problem.

Any help would be appreciated. Thanks.

Edit: I might have solved this by doing the following:

```<code> Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import spacy
>>> spacy.load('en')
<spacy.lang.en.English object at 0x7ff414e1e0b8>
</code>```

and then using:

```<code>from spacy.lang.en import English
</code>```

I'm still keeping this open in case there are any other answers.

Title: ImportError: No module named 'spacy.en'

Body:
I'm working on a codebase that uses Spacy. I installed spacy using:

sudo pip3 install spacy

and then

sudo python3 -m spacy download en

At the end of this last command, I got a message:

    Linking successful
/home/rayabhik/.local/lib/python3.5/site-packages/en_core_web_sm -->
/home/rayabhik/.local/lib/python3.5/site-packages/spacy/data/en

You can now load the model via spacy.load('en')

Now, when I try running my code, on the line:

    from spacy.en import English

it gives me the following error:

ImportError: No module named 'spacy.en'

I've looked on Stackexchange and the closest is:  Import error with spacy: "No module named en"
which does not solve my problem.

Any help would be appreciated. Thanks.

Edit: I might have solved this by doing the following:

 Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import spacy
>>> spacy.load('en')
<spacy.lang.en.English object at 0x7ff414e1e0b8>

and then using:

from spacy.lang.en import English

I'm still keeping this open in case there are any other answers.


问:
Any 3D geometry algorithms library in Java?
I need a library, that could perform some geometry operations with objects in 3D, like:

Find min distance between 2 triangles

Intersect two polygons

Intersect two wireframe objects and exctract their difference (hardest one).

Is there any such open-source library?

P.S. JTS is not an option, because it doesn't work with 3D :(

答: Have a look at Java3D. </p>

Body: Have a look at Java3D.


问:
Can I remove extra text in the tab name?
There's a change to the tab name when I receive a notification on social networking sites.

It'll change from Website to 3 Notifications | Website

I'm curious about ways on Firefox I can prevent that sort of change.

Is it possible to filter out certain words from tab names?

答:
You unfortunately cannot prevent tabs from updating the title in any modern browser. The only solution that I've seen, although not ideal, is to use a script to record the initial title of the page and keep the tab updated with that saved value. You can use a greasemonkey script for such a task:</p>

```<code>var script = document.createElement("script");
script.textContent = "(" + t.toString() + ")()";
document.body.appendChild(script);

var title = document.title;
var updateTitle = function ()
{
      document.title = title;
};
window.setInterval(updateTitle, 0);
</code>```

Body:
You unfortunately cannot prevent tabs from updating the title in any modern browser. The only solution that I've seen, although not ideal, is to use a script to record the initial title of the page and keep the tab updated with that saved value. You can use a greasemonkey script for such a task:

var script = document.createElement("script");
script.textContent = "(" + t.toString() + ")()";
document.body.appendChild(script);

var title = document.title;
var updateTitle = function ()
{
      document.title = title;
};
window.setInterval(updateTitle, 0);


问:
Read cookies inside a static method [ ASP MVC ]
I work on a ASP.NET MVC project, I create a Controller named AuthenticationController, this controller contains a static method called User_Access_Validation.

This method check some cookies values.

So that is method code :

```<code>public void User_Access_Validation()
{
 if (Request.Cookies["X_8"] == null || Request.Cookies["X_5"] == null || Request.Cookies["X_T"] == null)
   {
     Response.Redirect("/Login");
   }
}
</code>```

Everythings works good at now, but when I change this method to a static method I got these four errors in ErrorList in Visual Studio

```<code>Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property
</code>```

So please I need this method to be a static method, and fix this error

答:
Request and Response are instance properties - they belong to a specific instance of the Controller.

A static method doesn't belong to any specific instance of the class. From the documentation:

Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

I recommend reading more. For the purposes of this answer, you can't access Request and Response from a static method. What you can do, as the article says, is pass them as arguments to a static method. So you could do this:

```<code>public static void User_Access_Validation(HttpRequest request, HttpResponse response)
{
 if (request.Cookies["X_8"] == null || request.Cookies["X_5"] == null || request.Cookies["X_T"] == null)
   {
     response.Redirect("/Login");
   }
}
</code>```

Now the method isn't attempting to read those static properties. It's just using the methods passed to it. (Notice that request and response are lower-case. They're referring to the variables, not the properties which are capitalized.

You can call this static method from a non-static (instance) method. The instance method, which can access those properties, can pass them as arguments to the static method:

```<code>public static void User_Access_Validation(Request, Response);
</code>```

Here's another good answer that explains the difference between static and instance (non-static) methods. It has a simple but illuminating example.

Body:
I work on a ASP.NET MVC project, I create a Controller named AuthenticationController, this controller contains a static method called User_Access_Validation.

This method check some cookies values.

So that is method code :

public void User_Access_Validation()
{
 if (Request.Cookies["X_8"] == null || Request.Cookies["X_5"] == null || Request.Cookies["X_T"] == null)
   {
     Response.Redirect("/Login");
   }
}

Everythings works good at now, but when I change this method to a static method I got these four errors in ErrorList in Visual Studio

Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property

So please I need this method to be a static method, and fix this error

Body:
Request and Response are instance properties - they belong to a specific instance of the Controller.

A static method doesn't belong to any specific instance of the class. From the documentation:

Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

I recommend reading more. For the purposes of this answer, you can't access Request and Response from a static method. What you can do, as the article says, is pass them as arguments to a static method. So you could do this:

public static void User_Access_Validation(HttpRequest request, HttpResponse response)
{
 if (request.Cookies["X_8"] == null || request.Cookies["X_5"] == null || request.Cookies["X_T"] == null)
   {
     response.Redirect("/Login");
   }
}

Now the method isn't attempting to read those static properties. It's just using the methods passed to it. (Notice that request and response are lower-case. They're referring to the variables, not the properties which are capitalized.

You can call this static method from a non-static (instance) method. The instance method, which can access those properties, can pass them as arguments to the static method:

public static void User_Access_Validation(Request, Response);

Here's another good answer that explains the difference between static and instance (non-static) methods. It has a simple but illuminating example.


问:
Call function of every instance of a class
I am developing a small game and need some help. To check for collisions I created a class Block to create different shoes of obstacles. Now I plan to use the colliderect method of pygame to check for collision.

Is there a way to call a method not only for one class instance (e.g. block_1.check() but calling it for every instance of class Block? For example: Block.check() so it checks for block_1, block_2, ..., etc?

答:
Probably the easiest option is to maintain a list of references to each instance as a static variable of the class.  You would append to the list when the object is created, and remove from it once it's destroyed.

For example:

```<code>class Block:

    # Static variable; accessible as Block.blocks
    blocks = []

    def __init__(self):
        self.id = 1
        self.x = 0
        self.y = 0

        Block.blocks.append(self)

    def destroy(self):
        Block.blocks = [block for block in Block.blocks if block.id != self.id]
</code>```

Body:
Probably the easiest option is to maintain a list of references to each instance as a static variable of the class.  You would append to the list when the object is created, and remove from it once it's destroyed.

For example:

class Block:

    # Static variable; accessible as Block.blocks
    blocks = []

    def __init__(self):
        self.id = 1
        self.x = 0
        self.y = 0

        Block.blocks.append(self)

    def destroy(self):
        Block.blocks = [block for block in Block.blocks if block.id != self.id]


问:
How to include Socket io in external js file linked to html file?
I am using node js, socket io, and express to create a multiplayer web game.
When the server start I listen on port 2000.
When I go to localhost:2000, the file lobby.html is sent using

```<code>//app.js
const express = require('express');
const app = express();
const serv = require('http').Server(app);
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/Client/lobby.html');
});
serv.listen(2000);
var io = require(socket.io)(serv, {});
</code>```

I would include the js for the lobby.html file inside the html file instead of using
<script src='../app.js'></script>
```

Since the js was written in the html file and socket io was included on that html page I could use var socket = io(); in my js so I can communicate with the server(app.js).

However, I want the js that was written in lobby.html to be moved to a file called lobby.js using

答:
Simply add another route in your express code:

//app.js

// root route
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/Client/lobby.html');
});

// add this
app.get('/app.js', function(req, res) {
    res.setHeader('Content-Type', 'application/javascript');
    res.sendFile(__dirname + '/Client/app.js');
});
```

<p>and then add the script tag in your HTML:</p>

<pre class="lang-html prettyprint-override"><code><script src='/app.js'></script>
</code>```

Remember that every page represents more than one request to the server. Every CSS file, javascript file, image adds another request that the server needs to know how to handle.

Body:
I am using node js, socket io, and express to create a multiplayer web game.
When the server start I listen on port 2000.
When I go to localhost:2000, the file lobby.html is sent using

//app.js
const express = require('express');
const app = express();
const serv = require('http').Server(app);
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/Client/lobby.html');
});
serv.listen(2000);
var io = require(socket.io)(serv, {});

I would include the js for the lobby.html file inside the html file instead of using

Since the js was written in the html file and socket io was included on that html page I could use var socket = io(); in my js so I can communicate with the server(app.js).

However, I want the js that was written in lobby.html to be moved to a file called lobby.js using

Body:
Simply add another route in your express code:

//app.js

// root route
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/Client/lobby.html');
});

// add this
app.get('/app.js', function(req, res) {
    res.setHeader('Content-Type', 'application/javascript');
    res.sendFile(__dirname + '/Client/app.js');
});

and then add the script tag in your HTML:

<script src='/app.js'></script>

Remember that every page represents more than one request to the server. Every CSS file, javascript file, image adds another request that the server needs to know how to handle.


问:
(React) Selecing different dropdown values does not change anything
I have a dropdown menu, and selecting different values does not change anything. Previously, it did change just fine. Here is my code:

context.js:

```<code>import React, { useState, useEffect } from 'react'
import items from './data'

const RoomContext = React.createContext()

const RoomProvider = ({ children }) => {
    const [state, setState] = useState({
        rooms: [],
        sortedRooms: [],
        featuredRooms: [],
        loading: true,
        type: 'all',
        capacity: 1,
        price: 0,
        minPrice: 0,
        maxPrice: 0,
        minSize: 0,
        maxSize: 0,
        breakfast: false,
        pets: false
    })

    const formatData = items => {
        let tempItems = items.map(item => {
            let id = item.sys.id
            let images = item.fields.images.map(image => image.fields.file.url)
            let room = { ...item.fields, images, id }
            return room
        })
        return tempItems
    }

    const getRoom = slug => {
        let tempRooms = [...state.rooms]
        const room = tempRooms.find(room => room.slug === slug)
        return room
    }

    useEffect(() => {
        let rooms = formatData(items)
        let featuredRoomsTemp = state.rooms.filter(room => room.featured)
        let maxPrice = Math.max(...state.rooms.map(item => item.price))
        let maxSize = Math.max(...state.rooms.map(item => item.size))

        setState({
            ...state,
            rooms,
            featuredRooms: featuredRoomsTemp,
            sortedRooms: rooms,
            loading: false,
            price: maxPrice,
            maxPrice,
            maxSize
        })
    }, [])

      const handleChange = e => {
        const target = e.target
        const value = e.type === 'checkbox' ? target.checked : target.value
        const name = e.target.name

        setState({
            ...state,
            [name]: value
        })
        filterRooms()
    }

    const filterRooms = () => {
        console.log('reached')
        let { rooms, type, capacity, price, minSize, maxSize, breakfast, pets } = state

        let tempRooms = [...rooms]
        if (type !== 'all') {
            // console.log('NOT ALL')
            tempRooms = tempRooms.filter(room => room.type === type)
        }
        console.log('temprooms:' ,tempRooms)

        //ONLY AFTER ADDING THE BELOW SETSTATE,  AM I UNABLE TO CHANGE THE DROPDOWN VALUES. IF I REMOVE THE BELOW, I CAN CHANGE IT JUST FINE. Why would a setState make me unable to change the values?
        setState({
            ...state,
            sortedRooms: tempRooms
        })
    }

    return (
        <RoomContext.Provider value={{
            ...state,
            getRoom,
            handleChange
        }}>
            {children}
        </RoomContext.Provider>
    )
}

const RoomConsumer = RoomContext.Consumer

export function withRoomConsumer(Component) {
    return function ConsumerWrapper(props) {
        return <RoomConsumer>
            {value => <Component {...props} context={value} />}
        </RoomConsumer>
    }
}

export { RoomProvider, RoomConsumer, RoomContext }

</code>```

RoomsFilter.js

```<code>import React, { useContext } from 'react'
import { RoomContext } from '../context'
import Title from './Title'

const getUnique = (items, value) => {
    return [...new Set(items.map(item => item[value]))]
}

const RoomsFilter = ({ rooms }) => {
    const context = useContext(RoomContext)

    const { handleChange, type, capacity, price, minPrice, maxPrice, minSize, maxSize, breakfast, pets } = context

    let types = getUnique(rooms, 'type')
    types = ['all', ...types]

    types = types.map((item, i) => {
        return (
            <option value={item} key={i}>{item}</option>
        )
    })

    return (
        <section className='filter-container'>
            <Title title='Search rooms' />
            <form className='filter-form'>
                {/* select type */}
                <div className='form-group'>
                    <label htmlFor='type'>Room type</label>
                    <select name='type' id='type' value={type} className='form-control' onChange={handleChange}>
                        {types}
                    </select>
                </div>
                {/* end select type */}
            </form>
        </section>
    )
}

export default RoomsFilter
</code>```

==================================================================

As you can see, it is only when I added

```<code>setState({
            ...state,
            sortedRooms: tempRooms
        })
</code>```

in filterRooms (in context.js) that I am no longer able to change the dropdown value. Why would adding setState do this?

Please help, and thank you for reading!

===============UPDATE=====================

RoomsContainer is the one that contains the Dropdown menu(RoomsFilter) and the list of rooms below that dropdown menu(RoomsList).

RoomsFilter is the dropdown menu component

RoomsList is the component whose job is to render the rooms

Rooms Container:

```<code>import React from 'react'
import RoomsFilter from './RoomsFilter'
import RoomsList from './RoomsList'
import { withRoomConsumer } from '../context'
import Loading from './Loading'

function RoomContainer({ context }) {
const { loading, sortedRooms, rooms } = context
console.log(context)
if (loading) {
return <Loading />
}

return (
<div>
<RoomsFilter rooms={rooms} />
<RoomsList rooms={sortedRooms} />
</div>
)
}

export default withRoomConsumer(RoomContainer)
</code>```

RoomsFilter:

```<code>import React, { useContext } from 'react'
import { RoomContext } from '../context'
import Title from './Title'

const getUnique = (items, value) => {
return [...new Set(items.map(item => item[value]))]
}

const RoomsFilter = ({ rooms }) => {
const context = useContext(RoomContext)

const { handleChange, type, capacity, price, minPrice, maxPrice, minSize, maxSize, breakfast, pets } = context

let types = getUnique(rooms, 'type')
types = ['all', ...types]

types = types.map((item, i) => {
return (
<option value={item} key={i}>{item}</option>
)
})

return (
<section className='filter-container'>
<Title title='Search rooms' />
<form className='filter-form'>
{/* select type */}
<div className='form-group'>
<label htmlFor='type'>Room type</label>
<select name='type' id='type' value={type} className='form-control' onChange={handleChange}>
{types}
</select>
</div>
{/* end select type */}
</form>
</section>
)
}

export default RoomsFilter
</code>```

RoomsList

```<code>import React from 'react'
import Room from './Room'

const RoomsList = ({ rooms }) => {
console.log(rooms)
if (rooms.length === 0) {
return (
<div className='empty-search'>
<h3>Unfortunately no rooms match your search criteria</h3>
</div>
)
}

return (
<section className='roomslist'>
<div className='roomslist-center'>
{rooms.map(item => {
return <Room key={item.id} room={item} />
})}
</div>
</section>
)
}

export default RoomsList
</code>```

答:
The problem is that you have two different setState calls; one is in your handleChange function, and the other is inside of filterRooms. Both of those functions on a given change are using the previous state, but after the first:

```<code>setState({
  ...state,
  [name]: value
})
</code>```

...state is still going to have that same original value when you call:

```<code>setState({
  ...state,
  sortedRooms: tempRooms
})
</code>```

...so the second update is going to overwrite what the first setState did. As was already pointed out, you can use the callback version of setState for the second call so you're using the new previous state on that second call:

```<code>setState(state => ({
  ...state,
  sortedRooms: tempRooms
}));
</code>```

...but a better approach is to only call setState once on change instead of confusingly making two state updates. Instead of filterRooms calling setState, have it return the filtered Array, and do your update all in one call. Here's what filterRooms could do instead:

```<code>const getFilteredRooms = (type) => {
  let { rooms, capacity, price, minSize, maxSize, breakfast, pets } = state
  return type === 'all' ? rooms : rooms.filter(room => room.type === type)
}
</code>```

...and change your handleChange to:

```<code>const handleChange = e => {
  const target = e.target
  const value = e.type === 'checkbox' ? target.checked : target.value
  const name = e.target.name

  setState({
    ...state,
    [name]: value,
    sortedRooms: getFilteredRooms(value)
  })
}
</code>```

Body:
I have a dropdown menu, and selecting different values does not change anything. Previously, it did change just fine. Here is my code:

context.js:

import React, { useState, useEffect } from 'react'
import items from './data'

const RoomContext = React.createContext()

const RoomProvider = ({ children }) => {
    const [state, setState] = useState({
        rooms: [],
        sortedRooms: [],
        featuredRooms: [],
        loading: true,
        type: 'all',
        capacity: 1,
        price: 0,
        minPrice: 0,
        maxPrice: 0,
        minSize: 0,
        maxSize: 0,
        breakfast: false,
        pets: false
    })

    const formatData = items => {
        let tempItems = items.map(item => {
            let id = item.sys.id
            let images = item.fields.images.map(image => image.fields.file.url)
            let room = { ...item.fields, images, id }
            return room
        })
        return tempItems
    }

    const getRoom = slug => {
        let tempRooms = [...state.rooms]
        const room = tempRooms.find(room => room.slug === slug)
        return room
    }

    useEffect(() => {
        let rooms = formatData(items)
        let featuredRoomsTemp = state.rooms.filter(room => room.featured)
        let maxPrice = Math.max(...state.rooms.map(item => item.price))
        let maxSize = Math.max(...state.rooms.map(item => item.size))

        setState({
            ...state,
            rooms,
            featuredRooms: featuredRoomsTemp,
            sortedRooms: rooms,
            loading: false,
            price: maxPrice,
            maxPrice,
            maxSize
        })
    }, [])

      const handleChange = e => {
        const target = e.target
        const value = e.type === 'checkbox' ? target.checked : target.value
        const name = e.target.name

        setState({
            ...state,
            [name]: value
        })
        filterRooms()
    }

    const filterRooms = () => {
        console.log('reached')
        let { rooms, type, capacity, price, minSize, maxSize, breakfast, pets } = state

        let tempRooms = [...rooms]
        if (type !== 'all') {
            // console.log('NOT ALL')
            tempRooms = tempRooms.filter(room => room.type === type)
        }
        console.log('temprooms:' ,tempRooms)

        //ONLY AFTER ADDING THE BELOW SETSTATE,  AM I UNABLE TO CHANGE THE DROPDOWN VALUES. IF I REMOVE THE BELOW, I CAN CHANGE IT JUST FINE. Why would a setState make me unable to change the values?
        setState({
            ...state,
            sortedRooms: tempRooms
        })
    }

    return (
        <RoomContext.Provider value={{
            ...state,
            getRoom,
            handleChange
        }}>
            {children}
        </RoomContext.Provider>
    )
}

const RoomConsumer = RoomContext.Consumer

export function withRoomConsumer(Component) {
    return function ConsumerWrapper(props) {
        return <RoomConsumer>
            {value => <Component {...props} context={value} />}
        </RoomConsumer>
    }
}

export { RoomProvider, RoomConsumer, RoomContext }

RoomsFilter.js

import React, { useContext } from 'react'
import { RoomContext } from '../context'
import Title from './Title'

const getUnique = (items, value) => {
    return [...new Set(items.map(item => item[value]))]
}

const RoomsFilter = ({ rooms }) => {
    const context = useContext(RoomContext)

    const { handleChange, type, capacity, price, minPrice, maxPrice, minSize, maxSize, breakfast, pets } = context

    let types = getUnique(rooms, 'type')
    types = ['all', ...types]

    types = types.map((item, i) => {
        return (
            <option value={item} key={i}>{item}</option>
        )
    })

    return (

            <Title title='Search rooms' />
            <form className='filter-form'>
                {/* select type */}

                    Room type
                    <select name='type' id='type' value={type} className='form-control' onChange={handleChange}>
                        {types}
                    </select>

                {/* end select type */}
            </form>

    )
}

export default RoomsFilter

==================================================================

As you can see, it is only when I added

setState({
            ...state,
            sortedRooms: tempRooms
        })

in filterRooms (in context.js) that I am no longer able to change the dropdown value. Why would adding setState do this?

Please help, and thank you for reading!

===============UPDATE=====================

RoomsContainer is the one that contains the Dropdown menu(RoomsFilter) and the list of rooms below that dropdown menu(RoomsList).

RoomsFilter is the dropdown menu component

RoomsList is the component whose job is to render the rooms

Rooms Container:

import React from 'react'
import RoomsFilter from './RoomsFilter'
import RoomsList from './RoomsList'
import { withRoomConsumer } from '../context'
import Loading from './Loading'

function RoomContainer({ context }) {
const { loading, sortedRooms, rooms } = context
console.log(context)
if (loading) {
return <Loading />
}

return (

<RoomsFilter rooms={rooms} />
<RoomsList rooms={sortedRooms} />

)
}

export default withRoomConsumer(RoomContainer)

RoomsFilter:

import React, { useContext } from 'react'
import { RoomContext } from '../context'
import Title from './Title'

const getUnique = (items, value) => {
return [...new Set(items.map(item => item[value]))]
}

const RoomsFilter = ({ rooms }) => {
const context = useContext(RoomContext)

const { handleChange, type, capacity, price, minPrice, maxPrice, minSize, maxSize, breakfast, pets } = context

let types = getUnique(rooms, 'type')
types = ['all', ...types]

types = types.map((item, i) => {
return (
<option value={item} key={i}>{item}</option>
)
})

return (

<Title title='Search rooms' />
<form className='filter-form'>
{/* select type */}

Room type
<select name='type' id='type' value={type} className='form-control' onChange={handleChange}>
{types}
</select>

{/* end select type */}
</form>

)
}

export default RoomsFilter

RoomsList

import React from 'react'
import Room from './Room'

const RoomsList = ({ rooms }) => {
console.log(rooms)
if (rooms.length === 0) {
return (

Unfortunately no rooms match your search criteria

)
}

return (

{rooms.map(item => {
return <Room key={item.id} room={item} />
})}

)
}

export default RoomsList

Body:
The problem is that you have two different setState calls; one is in your handleChange function, and the other is inside of filterRooms. Both of those functions on a given change are using the previous state, but after the first:

setState({
  ...state,
  [name]: value
})

...state is still going to have that same original value when you call:

setState({
  ...state,
  sortedRooms: tempRooms
})

...so the second update is going to overwrite what the first setState did. As was already pointed out, you can use the callback version of setState for the second call so you're using the new previous state on that second call:

setState(state => ({
  ...state,
  sortedRooms: tempRooms
}));

...but a better approach is to only call setState once on change instead of confusingly making two state updates. Instead of filterRooms calling setState, have it return the filtered Array, and do your update all in one call. Here's what filterRooms could do instead:

const getFilteredRooms = (type) => {
  let { rooms, capacity, price, minSize, maxSize, breakfast, pets } = state
  return type === 'all' ? rooms : rooms.filter(room => room.type === type)
}

...and change your handleChange to:

const handleChange = e => {
  const target = e.target
  const value = e.type === 'checkbox' ? target.checked : target.value
  const name = e.target.name

  setState({
    ...state,
    [name]: value,
    sortedRooms: getFilteredRooms(value)
  })
}


问:
Extract sentences containing specific word(s)
I have a get_sentences (sentimentr) list, and need to extract only those sentences containing specific words.
This is how the data looks like:

```<code>> class(frasi_negative)
[1] "get_sentences"           "get_sentences_character" "list"
> frasi_negative[2:3]
[[1]]
[1] "Al mio cellulare (Xiaomi Redmi Note 5) si mostrano singolarmente, separate, quando cerco di connetterle."
[2] "O si connette alla destra, o alla sinistra, e in ogni caso il suono poi esce dalle casse del cellulare (nonostante aver dato alle cuffie tutti i permessi)."
[3] "Non capisco perché, data che la prima connessione era andata come si deve; spente e riaccese, hanno iniziato a comportarsi così."
[4] "Ho provato a riavviare sia loro che cellulare, a rimetterle nella scatoletta e ritoglierle, ma il problema persiste."
[5] "Non penso c'entri il mio cellulare (mai avuto problemi con prodotti simili), in ogni caso effettuo reso con rimborso."

[[2]]
[1] "Comprate due mesi fa."
[2] "All'inizio funzionavano perfettamente, ma dopo qualche settimana hanno iniziato a disconnettersi tra loro di tanto in tanto."
[3] "qualche giorno fa estraendo la sinistra dall'astuccio magnetico è saltata la saldatura che la teneva chiusa e questo è il risultato."
[4] "Usandole in chiamata rendono un suono non limpido."
[5] "Il suono è accettabile ma nulla di speciale."
[6] "Ormai sono inutilizzabili."
[7] "Per il prezzo mi aspettavo un prodotto migliore e più duraturo (avendo già provato auricolari wireless della stessa fascia di prezzo di altri brand)"
</code>```

As an example, if I search "wireless", only the [[2]][7] element should show up.

How can I achieve this?

Thank you in advance.

答:
You can try to iterate over the list using lapply and return the sentence which  matches a particular keyword using grep .

```<code>keyword <- 'wireless'
lapply(frasi_negative, function(x) grep(keyword, x, value = TRUE))
</code>```

Body:
I have a get_sentences (sentimentr) list, and need to extract only those sentences containing specific words.
This is how the data looks like:

> class(frasi_negative)
[1] "get_sentences"           "get_sentences_character" "list"
> frasi_negative[2:3]
[[1]]
[1] "Al mio cellulare (Xiaomi Redmi Note 5) si mostrano singolarmente, separate, quando cerco di connetterle."
[2] "O si connette alla destra, o alla sinistra, e in ogni caso il suono poi esce dalle casse del cellulare (nonostante aver dato alle cuffie tutti i permessi)."
[3] "Non capisco perché, data che la prima connessione era andata come si deve; spente e riaccese, hanno iniziato a comportarsi così."
[4] "Ho provato a riavviare sia loro che cellulare, a rimetterle nella scatoletta e ritoglierle, ma il problema persiste."
[5] "Non penso c'entri il mio cellulare (mai avuto problemi con prodotti simili), in ogni caso effettuo reso con rimborso."

[[2]]
[1] "Comprate due mesi fa."
[2] "All'inizio funzionavano perfettamente, ma dopo qualche settimana hanno iniziato a disconnettersi tra loro di tanto in tanto."
[3] "qualche giorno fa estraendo la sinistra dall'astuccio magnetico è saltata la saldatura che la teneva chiusa e questo è il risultato."
[4] "Usandole in chiamata rendono un suono non limpido."
[5] "Il suono è accettabile ma nulla di speciale."
[6] "Ormai sono inutilizzabili."
[7] "Per il prezzo mi aspettavo un prodotto migliore e più duraturo (avendo già provato auricolari wireless della stessa fascia di prezzo di altri brand)"

As an example, if I search "wireless", only the [[2]][7] element should show up.

How can I achieve this?

Thank you in advance.

Body:
You can try to iterate over the list using lapply and return the sentence which  matches a particular keyword using grep .

keyword <- 'wireless'
lapply(frasi_negative, function(x) grep(keyword, x, value = TRUE))


问:
Does an asynchronous call always create/call a new thread?
Does asynchronous call always create a new thread?

Example:

If JavaScript is single threaded then how can it do an async postback? Is it actually blocking until it gets a callback? If so, is this really an async call?

答:
A couple notes about JavaScript in particular:

XMLHttpRequests are non-blocking by default. The send() method returns immediately after the request has been relayed to the underlying network stack. A response from the server will schedule an invocation of your callback on the event loop as discussed by the other excellent answers.

This does not require a new thread. The underlying socket API is selectable, similar to java.nio.channels in Java.

It's possible to construct synchronous XMLHttpRequest objects by passing false as the third parameter to open(). This will cause the send() method to block until a response has been received from the server, thus placing the event loop at the mercy of network latency and potentially hanging the browser until network timeout. This is a Bad Thing™.

Firefox 3.5 will introduce honest-to-god multithreaded JavaScript with the Worker class. The background code runs in a completely separate environment and communicates with the browser window by scheduling callbacks on the event loop.

OwnerDisplayName: Ted Smith

LastEditorDisplayName: Harley

OwnerDisplayName: Matthew

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Matthew


问:
Saving/Loading OrderedDictionary to Session
I am trying to save the OrderedDictionary into the session and reload it.
basically, it is a "Last Played" game list.

for some reason, the dictionary is allays NEW .... anyone can pinpoint the reason?

```<code><%@ WebHandler Language="C#" Class="LastPlayed" %>

using System;
using System.Web;
using System.Web.SessionState;

public class LastPlayed : IHttpHandler, IReadOnlySessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/plain";

        string GameTitle = context.Request["gt"];
        string GameAlias = context.Request["ga"];

        System.Collections.Specialized.OrderedDictionary GamesDictionary = null;

        if (context.Session["LastPlayed"] != null)
        {
            // Load Dictionary from Session
            GamesDictionary = (System.Collections.Specialized.OrderedDictionary)context.Session["LastPlayed"];
            context.Response.Write("Loaded from Session");
        }
        else
        {
            // Creates and initializes a OrderedDictionary.
            GamesDictionary = new System.Collections.Specialized.OrderedDictionary();
            context.Response.Write("Created New Dictionary");
        }

        try
        {
            if (GamesDictionary.Count >= 5)
                // Remove the last entry from the OrderedDictionary
                GamesDictionary.RemoveAt(GamesDictionary.Count - 1);
            // Insert a new key to the beginning of the OrderedDictionary
            GamesDictionary.Insert(0, GameTitle, GameAlias);
            context.Session["LastPlayed"] = GamesDictionary;
            context.Response.Write("Added");
        }
        catch { context.Response.Write("Duplicate Found."); }
    }

}
</code>```

答:
Ok, so i found the problem,
i was using IReadOnlySessionState
Instead of IRequiresSessionState

```<code><%@ WebHandler Language="C#" Class="LastPlayed" %>

using System;
using System.Web;
using System.Web.SessionState;

public class LastPlayed : IHttpHandler, IRequiresSessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/plain";

        string GameTitle = context.Request["gt"];
        string GameAlias = context.Request["ga"];

        System.Collections.Specialized.OrderedDictionary GamesDictionary = (System.Collections.Specialized.OrderedDictionary)context.Session["LastPlayed"];

        if (context.Session["LastPlayed"] == null)
            // Creates and initializes a OrderedDictionary.
            GamesDictionary = new System.Collections.Specialized.OrderedDictionary();
        try
        {
            if (GamesDictionary.Count >= 5)
                // Remove the last entry from the OrderedDictionary
                GamesDictionary.RemoveAt(GamesDictionary.Count - 1);
            // Insert a new key to the beginning of the OrderedDictionary
            GamesDictionary.Insert(0, GameTitle, GameAlias);
            context.Session["LastPlayed"] = GamesDictionary;
            context.Response.Write("Added");
        }
        catch { context.Response.Write("Duplicate Found."); }

    }

}
</code>```

EDIT: Posted full working answer

Body:
I am trying to save the OrderedDictionary into the session and reload it.
basically, it is a "Last Played" game list.

for some reason, the dictionary is allays NEW .... anyone can pinpoint the reason?

<%@ WebHandler Language="C#" Class="LastPlayed" %>

using System;
using System.Web;
using System.Web.SessionState;

public class LastPlayed : IHttpHandler, IReadOnlySessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/plain";

        string GameTitle = context.Request["gt"];
        string GameAlias = context.Request["ga"];

        System.Collections.Specialized.OrderedDictionary GamesDictionary = null;

        if (context.Session["LastPlayed"] != null)
        {
            // Load Dictionary from Session
            GamesDictionary = (System.Collections.Specialized.OrderedDictionary)context.Session["LastPlayed"];
            context.Response.Write("Loaded from Session");
        }
        else
        {
            // Creates and initializes a OrderedDictionary.
            GamesDictionary = new System.Collections.Specialized.OrderedDictionary();
            context.Response.Write("Created New Dictionary");
        }

        try
        {
            if (GamesDictionary.Count >= 5)
                // Remove the last entry from the OrderedDictionary
                GamesDictionary.RemoveAt(GamesDictionary.Count - 1);
            // Insert a new key to the beginning of the OrderedDictionary
            GamesDictionary.Insert(0, GameTitle, GameAlias);
            context.Session["LastPlayed"] = GamesDictionary;
            context.Response.Write("Added");
        }
        catch { context.Response.Write("Duplicate Found."); }
    }

}

Body:
Ok, so i found the problem,
i was using IReadOnlySessionState
Instead of IRequiresSessionState

<%@ WebHandler Language="C#" Class="LastPlayed" %>

using System;
using System.Web;
using System.Web.SessionState;

public class LastPlayed : IHttpHandler, IRequiresSessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/plain";

        string GameTitle = context.Request["gt"];
        string GameAlias = context.Request["ga"];

        System.Collections.Specialized.OrderedDictionary GamesDictionary = (System.Collections.Specialized.OrderedDictionary)context.Session["LastPlayed"];

        if (context.Session["LastPlayed"] == null)
            // Creates and initializes a OrderedDictionary.
            GamesDictionary = new System.Collections.Specialized.OrderedDictionary();
        try
        {
            if (GamesDictionary.Count >= 5)
                // Remove the last entry from the OrderedDictionary
                GamesDictionary.RemoveAt(GamesDictionary.Count - 1);
            // Insert a new key to the beginning of the OrderedDictionary
            GamesDictionary.Insert(0, GameTitle, GameAlias);
            context.Session["LastPlayed"] = GamesDictionary;
            context.Response.Write("Added");
        }
        catch { context.Response.Write("Duplicate Found."); }

    }

}

EDIT: Posted full working answer


问:
How do I run an arbitrary shell command from Deno?
I want to run any arbitrary bash command from Deno, like I would with a child_process in Node. Is that possible in Deno?

答:
You can do that with the run like this:

// myscript.js
Deno.run({
  cmd: ["echo", "hello world"]
})
```
<p>You'll have to <code>--allow-run</code> when running the script in order for this to work:</p>
<pre class="lang-sh prettyprint-override"><code>deno run --allow-run ./myscript.js
</code>```

Body:
You can do that with the run like this:

// myscript.js
Deno.run({
  cmd: ["echo", "hello world"]
})

You'll have to --allow-run when running the script in order for this to work:

deno run --allow-run ./myscript.js


答:
Since the Time columns contains only Hour:Minute I suggest using timedelta instead of datetime:

```<code>df['Time'] = pd.to_timedelta(df.Time+':00')
df['Start_Time'] = pd.to_timedelta('8:00:00') - df['Time']
</code>```

Output:

```<code>      Time Start_Time
0 02:00:00   06:00:00
1 00:13:00   07:47:00
2 01:00:00   07:00:00
3 00:24:00   07:36:00
</code>```

Title: Time difference in pandas (from string format to datetime)

Body:
I have the following column

Time
2:00
00:13
1:00
00:24

in object format (strings). This time refers to hours and minutes ago from a time that I need to use as a start: 8:00 (it might change; in this example is 8:00).

Since the times in the column Time are referring to hours/minutes ago, what I would like to expect should be

Time
6:00
07:47
7:00
07:36

calculated as time difference (e.g. 8:00 - 2:00).
However, I am having difficulties in doing this calculation and transform the result in a datetime (keeping only hours and minutes).
I hope you can help me.

Body:
Since the Time columns contains only Hour:Minute I suggest using timedelta instead of datetime:

df['Time'] = pd.to_timedelta(df.Time+':00')
df['Start_Time'] = pd.to_timedelta('8:00:00') - df['Time']

Output:

      Time Start_Time
0 02:00:00   06:00:00
1 00:13:00   07:47:00
2 01:00:00   07:00:00
3 00:24:00   07:36:00