问:
Heroku Node deployment "internal server error"
I have my app deployed to heroku. Once I go to the user signup page and enter my credentials the site immediately crashes, displaying internal server error in the browser, and giving me this in the heroku logs.

I'm not sure what might be the issue so I don't know which code to give? I don't think it has to do with MySQL but considering it's mentioned in the error report, it might be? Either way here is my connection.js:

```<code>const mysql = require('mysql');
let connection;

if (process.env.JAWSDB_URL) {
    connection = mysql.createConnection(process.env.JAWSDB_URL);
} else {
    connection = mysql.createConnection({
        host: 'localhost',
        port: 3306,
        user: 'root',
        password: '',
        database: 'trythis_db'
    });
};

connection.connect(function(err) {
    if (err) {
        console.log(err);
    } else {
        console.log('mysql is connected');
    };
});

module.exports = connection;
</code>```

This is my error code:

```<code>2017-12-04T04:58:51.486756+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306
2017-12-04T04:58:51.486150+00:00 app[web.1]: POST /signup 302 287.664 ms - 46
2017-12-04T04:58:51.486758+00:00 app[web.1]:     at Object._errnoException (util.js:1024:11)
2017-12-04T04:58:51.486758+00:00 app[web.1]:     at _exceptionWithHostPort (util.js:1046:20)
2017-12-04T04:58:51.486759+00:00 app[web.1]:     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
2017-12-04T04:58:51.486760+00:00 app[web.1]:     --------------------
2017-12-04T04:58:51.486761+00:00 app[web.1]:     at Protocol._enqueue (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:145:48)
2017-12-04T04:58:51.486762+00:00 app[web.1]:     at Protocol.handshake (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:52:23)
2017-12-04T04:58:51.486763+00:00 app[web.1]:     at PoolConnection.connect (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Connection.js:130:18)
2017-12-04T04:58:51.486763+00:00 app[web.1]:     at Pool.getConnection (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:48:16)
2017-12-04T04:58:51.486764+00:00 app[web.1]:     at Pool.query (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:202:8)
2017-12-04T04:58:51.486765+00:00 app[web.1]:     at MySQLStore.set (/app/node_modules/express-mysql-session/lib/index.js:192:19)
2017-12-04T04:58:51.486766+00:00 app[web.1]:     at Session.save (/app/node_modules/express-session/session/session.js:72:25)
2017-12-04T04:58:51.486766+00:00 app[web.1]:     at Session.save (/app/node_modules/express-session/index.js:381:15)
2017-12-04T04:58:51.486767+00:00 app[web.1]:     at ServerResponse.end (/app/node_modules/express-session/index.js:330:21)
2017-12-04T04:58:51.486768+00:00 app[web.1]:     at ServerResponse.redirect (/app/node_modules/express/lib/response.js:947:10)
2017-12-04T04:58:51.638706+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306
2017-12-04T04:58:51.638708+00:00 app[web.1]:     at Object._errnoException (util.js:1024:11)
2017-12-04T04:58:51.638709+00:00 app[web.1]:     at _exceptionWithHostPort (util.js:1046:20)
2017-12-04T04:58:51.638710+00:00 app[web.1]:     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
2017-12-04T04:58:51.638710+00:00 app[web.1]:     --------------------
2017-12-04T04:58:51.638711+00:00 app[web.1]:     at Protocol._enqueue (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:145:48)
2017-12-04T04:58:51.638712+00:00 app[web.1]:     at Protocol.handshake (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:52:23)
2017-12-04T04:58:51.638713+00:00 app[web.1]:     at PoolConnection.connect (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Connection.js:130:18)
2017-12-04T04:58:51.638713+00:00 app[web.1]:     at Pool.getConnection (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:48:16)
2017-12-04T04:58:51.638714+00:00 app[web.1]:     at Pool.query (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:202:8)
2017-12-04T04:58:51.638802+00:00 app[web.1]:     at session (/app/node_modules/express-session/index.js:460:11)
2017-12-04T04:58:51.638800+00:00 app[web.1]:     at MySQLStore.get (/app/node_modules/express-mysql-session/lib/index.js:130:19)
2017-12-04T04:58:51.638803+00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2017-12-04T04:58:51.638804+00:00 app[web.1]:     at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13)
2017-12-04T04:58:51.638804+00:00 app[web.1]:     at /app/node_modules/express/lib/router/index.js:284:7
</code>```

答:
Make sure you have added JAWSDB_URL under project config variables.

(Heroku project -> settings -> config variables -> reveal variables -> your var)

Body:
I have my app deployed to heroku. Once I go to the user signup page and enter my credentials the site immediately crashes, displaying internal server error in the browser, and giving me this in the heroku logs.

I'm not sure what might be the issue so I don't know which code to give? I don't think it has to do with MySQL but considering it's mentioned in the error report, it might be? Either way here is my connection.js:

const mysql = require('mysql');
let connection;

if (process.env.JAWSDB_URL) {
    connection = mysql.createConnection(process.env.JAWSDB_URL);
} else {
    connection = mysql.createConnection({
        host: 'localhost',
        port: 3306,
        user: 'root',
        password: '',
        database: 'trythis_db'
    });
};

connection.connect(function(err) {
    if (err) {
        console.log(err);
    } else {
        console.log('mysql is connected');
    };
});

module.exports = connection;

This is my error code:

2017-12-04T04:58:51.486756+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306
2017-12-04T04:58:51.486150+00:00 app[web.1]: POST /signup 302 287.664 ms - 46
2017-12-04T04:58:51.486758+00:00 app[web.1]:     at Object._errnoException (util.js:1024:11)
2017-12-04T04:58:51.486758+00:00 app[web.1]:     at _exceptionWithHostPort (util.js:1046:20)
2017-12-04T04:58:51.486759+00:00 app[web.1]:     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
2017-12-04T04:58:51.486760+00:00 app[web.1]:     --------------------
2017-12-04T04:58:51.486761+00:00 app[web.1]:     at Protocol._enqueue (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:145:48)
2017-12-04T04:58:51.486762+00:00 app[web.1]:     at Protocol.handshake (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:52:23)
2017-12-04T04:58:51.486763+00:00 app[web.1]:     at PoolConnection.connect (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Connection.js:130:18)
2017-12-04T04:58:51.486763+00:00 app[web.1]:     at Pool.getConnection (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:48:16)
2017-12-04T04:58:51.486764+00:00 app[web.1]:     at Pool.query (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:202:8)
2017-12-04T04:58:51.486765+00:00 app[web.1]:     at MySQLStore.set (/app/node_modules/express-mysql-session/lib/index.js:192:19)
2017-12-04T04:58:51.486766+00:00 app[web.1]:     at Session.save (/app/node_modules/express-session/session/session.js:72:25)
2017-12-04T04:58:51.486766+00:00 app[web.1]:     at Session.save (/app/node_modules/express-session/index.js:381:15)
2017-12-04T04:58:51.486767+00:00 app[web.1]:     at ServerResponse.end (/app/node_modules/express-session/index.js:330:21)
2017-12-04T04:58:51.486768+00:00 app[web.1]:     at ServerResponse.redirect (/app/node_modules/express/lib/response.js:947:10)
2017-12-04T04:58:51.638706+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306
2017-12-04T04:58:51.638708+00:00 app[web.1]:     at Object._errnoException (util.js:1024:11)
2017-12-04T04:58:51.638709+00:00 app[web.1]:     at _exceptionWithHostPort (util.js:1046:20)
2017-12-04T04:58:51.638710+00:00 app[web.1]:     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
2017-12-04T04:58:51.638710+00:00 app[web.1]:     --------------------
2017-12-04T04:58:51.638711+00:00 app[web.1]:     at Protocol._enqueue (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:145:48)
2017-12-04T04:58:51.638712+00:00 app[web.1]:     at Protocol.handshake (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:52:23)
2017-12-04T04:58:51.638713+00:00 app[web.1]:     at PoolConnection.connect (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Connection.js:130:18)
2017-12-04T04:58:51.638713+00:00 app[web.1]:     at Pool.getConnection (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:48:16)
2017-12-04T04:58:51.638714+00:00 app[web.1]:     at Pool.query (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:202:8)
2017-12-04T04:58:51.638802+00:00 app[web.1]:     at session (/app/node_modules/express-session/index.js:460:11)
2017-12-04T04:58:51.638800+00:00 app[web.1]:     at MySQLStore.get (/app/node_modules/express-mysql-session/lib/index.js:130:19)
2017-12-04T04:58:51.638803+00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2017-12-04T04:58:51.638804+00:00 app[web.1]:     at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13)
2017-12-04T04:58:51.638804+00:00 app[web.1]:     at /app/node_modules/express/lib/router/index.js:284:7


来源: stackexchange

问:
Language translate grammar
I am trying to add another language for my project.

We know that languages can show differences in subject and predicate.
For example:

English: Mustafa went to the cinema with his friend ahmet today.

Turkish: Mustafa bugün arkadaşı ahmet ile birlikte sinemaya gitti.

English   -  Turkish

today     =>     bugün

sinema    =>     cinema

birlikte  =>     with

gitti     =>     went

Mustafa and ahmet is username from users table. My question is how can I show the words with good grammars?

If I want to add my example word in my language table what should I do? I am asking this because of this example:

```<code>$username => Mustafa,

$friendname => ahmet
</code>```

English: <?php echo $username;?> went to the cinema with his friend <?php echo $friendname;?> today.

Turkish: <?php echo $username;?> bugün arkadaşı <?php echo $friendname;?> ile birlikte sinemaya gitti.

As you can see, the special names are in different places. How can I show the usernames from the table without echoing it?

答:
Why dont use placeholder on defined sentences.

```<code>$sentences = array();
$sentences[ "en" ] = "{{USERNAME}} went to the cinema with his friend {{FRIENDNAME}} today.";
$sentences[ "tu" ] = "{{USERNAME}} bugün arkadaşı {{FRIENDNAME}} ile birlikte sinemaya gitti.";
</code>```

Put the name and placeholders on array

```<code>$placeHolder    = [ "{{USERNAME}}", "{{FRIENDNAME}}" ];
$name           = [ "Mustafa", "ahmet" ];
</code>```

If you choose to print EN

```<code>echo str_replace($placeHolder, $name, $sentences[ "en" ]);
</code>```

Will result to: Mustafa went to the cinema with his friend ahmet today.

If you choose to print TU

```<code>echo str_replace($placeHolder, $name, $sentences[ "tu" ]);
</code>```

Will result to: Mustafa bugün arkadaşı ahmet ile birlikte sinemaya gitti.

ContentLicense: CC BY-SA 4.0

Title: Language translate grammar

Body:
I am trying to add another language for my project.

We know that languages can show differences in subject and predicate.
For example:

English: Mustafa went to the cinema with his friend ahmet today.

Turkish: Mustafa bugün arkadaşı ahmet ile birlikte sinemaya gitti.

English   -  Turkish

today     =>     bugün

sinema    =>     cinema

birlikte  =>     with

gitti     =>     went

Mustafa and ahmet is username from users table. My question is how can I show the words with good grammars?

If I want to add my example word in my language table what should I do? I am asking this because of this example:

$username => Mustafa,

$friendname => ahmet

English: <?php echo $username;?> went to the cinema with his friend <?php echo $friendname;?> today.

Turkish: <?php echo $username;?> bugün arkadaşı <?php echo $friendname;?> ile birlikte sinemaya gitti.

As you can see, the special names are in different places. How can I show the usernames from the table without echoing it?

Body:
Why dont use placeholder on defined sentences.

$sentences = array();
$sentences[ "en" ] = "{{USERNAME}} went to the cinema with his friend {{FRIENDNAME}} today.";
$sentences[ "tu" ] = "{{USERNAME}} bugün arkadaşı {{FRIENDNAME}} ile birlikte sinemaya gitti.";

Put the name and placeholders on array

$placeHolder    = [ "{{USERNAME}}", "{{FRIENDNAME}}" ];
$name           = [ "Mustafa", "ahmet" ];

If you choose to print EN

echo str_replace($placeHolder, $name, $sentences[ "en" ]);

Will result to: Mustafa went to the cinema with his friend ahmet today.

If you choose to print TU

echo str_replace($placeHolder, $name, $sentences[ "tu" ]);

Will result to: Mustafa bugün arkadaşı ahmet ile birlikte sinemaya gitti.

ContentLicense: CC BY-SA 3.0


问:
Searching through a 2D array in python 2.7 if a char is in that position
Hi im trying to search through my array if a particular char is in that position and then printing it to the console.

this is my code so far.

```<code>students = [['Gary','Y'],['Steve','N'],['Tom','Y']]

for i in range (len(students)):
        if students[i,1] == 'Y':
            print (students(i,0))
</code>```

答:
You can do it like this :

```<code>for student in students:
    if student[1] == 'Y':
        print(student[0])
</code>```

If you're looking for a one liner then :

```<code>print [student[0] for student in students if student[1]=='Y']
</code>```

Body:
Hi im trying to search through my array if a particular char is in that position and then printing it to the console.

this is my code so far.

students = [['Gary','Y'],['Steve','N'],['Tom','Y']]

for i in range (len(students)):
        if students[i,1] == 'Y':
            print (students(i,0))

Body:
You can do it like this :

for student in students:
    if student[1] == 'Y':
        print(student[0])

If you're looking for a one liner then :

print [student[0] for student in students if student[1]=='Y']


问:
Capistrano + Nginx + Passenger = 403
I have spent the last few days trying to solve this problem, and I'm just not making any headway. I actually just created a stackoverflow account specifically to ask this question. It seems that this issue is pretty common, but none of the solutions I found solve the problem for me.

Yesterday I came across this tutorial: http://blog.ninjahideout.com/posts/a-guide-to-a-nginx-passenger-and-rvm-server

I had hoped started from scratch using this tutorial would work, but no dice. Either way, if you view the tutorial you can see what steps I have taken.

Here is essentially what I have going on.

I have a VPS account on linode.com

Server OS is Ubuntu 10.04

Local OS (shouldn't matter, but just so you know) used to deploy with Capistrano is Snow Leopard 10.6.6

I use RVM on the server. Version is 1.2.2

I was previously on ruby-1.9.2-p0 [ i386 ], but per the tutorial listed above I switched to ree-1.8.7-2010.02 [ i386 ].

Running 'which ruby' from the command line verifies that I am using 1.8.7 with the following output: /usr/local/rvm/rubies/ree-1.8.7-2010.02/bin/ruby

passenger -v prints the following: Phusion Passenger version 3.0.2

I'm not sure how to tell what my nginx version is, but it should be the most recent one as I installed it yesterday via the passenger installer commands listed in the tutorial above.

I have two users dealing with the install. root which I used to install everything, and deployer which is a user I created specifically to for deploying my applications

My web app directory is in the deployer user's home directory as follows: /home/deployer/webapps/mysite.com/public

Per Capistrano default deploy, a symbolic link called current is created in the public folder, and points to /home/deployer/webapps/mysite.com/public/releases/most_current_release

I have chmodded the deployer directory recursively to 777

/opt/nginx permissions: rwxr-xr-x

/usr/local/rvm/gems/ree-1.8.7-2010.02/gems/passenger-3.0.2 permissions: rwxrwsrwx

My nginx config file has gone through just short of eternity variations, but currently looks like this:

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

```<code>worker_processes  1;

events {
    worker_connections  1024;
}

http {
    passenger_root /usr/local/rvm/gems/ree-1.8.7-2010.02/gems/passenger-3.0.2;
    passenger_ruby /usr/local/rvm/bin/passenger_ruby;

    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

    server {
       # listen      *:80;
        server_name mysite.com www.mysite.com;
        root   /home/deployer/webapps/mysite.com/public/current;

        passenger_enabled on;
        passenger_friendly_error_pages on;

        access_log logs/mysite.com/server.log;
        error_log logs/mysite.com/error.log info;

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
</code>```

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

I bounce nginx, hit the site, and boom. 403, and logs say directory index of /home/deployer... is forbidden

As others with a similar problem have said, you can drop an index.html into the public/releases/current_release and it will render. But rails no worky.

That's basically it. At this point I have just about completely exhausted every possible solution attempt I can think of. I am a programmer and definitely not a sysadmin, so I am 99% sure this has something to do with permissions that I have hosed, but for the life of me I just can't figure out where.

If anyone can help I would really really appreciate it. If there's any specific permission things you want me to check (ie groups/permissions), can you please include the commands to do so as well. Hopefully this will help others in the future who read this post.

Let me know if there is any other information I can provide, and thanks in advance!!!

答:
'nginx -v' outputs the version (or, client-side, view headers in your browser).

Slicehost has excellent articles for this sort of thing that you might compare with your own configuration, or even follow from the beginning. [I use Linode too but prefer Slicehost's tutorials. ;)]

http://articles.slicehost.com/tags/nginx

The nginx tutorials definitely cover permission settings, which sounds like the cause of the problem you're describing.

They also have articles covering Rails and Capistrano.

ContentLicense: CC BY-SA 2.5

Title: Capistrano + Nginx + Passenger = 403

Body:
I have spent the last few days trying to solve this problem, and I'm just not making any headway. I actually just created a stackoverflow account specifically to ask this question. It seems that this issue is pretty common, but none of the solutions I found solve the problem for me.

Yesterday I came across this tutorial: http://blog.ninjahideout.com/posts/a-guide-to-a-nginx-passenger-and-rvm-server

I had hoped started from scratch using this tutorial would work, but no dice. Either way, if you view the tutorial you can see what steps I have taken.

Here is essentially what I have going on.

I have a VPS account on linode.com

Server OS is Ubuntu 10.04

Local OS (shouldn't matter, but just so you know) used to deploy with Capistrano is Snow Leopard 10.6.6

I use RVM on the server. Version is 1.2.2

I was previously on ruby-1.9.2-p0 [ i386 ], but per the tutorial listed above I switched to ree-1.8.7-2010.02 [ i386 ].

Running 'which ruby' from the command line verifies that I am using 1.8.7 with the following output: /usr/local/rvm/rubies/ree-1.8.7-2010.02/bin/ruby

passenger -v prints the following: Phusion Passenger version 3.0.2

I'm not sure how to tell what my nginx version is, but it should be the most recent one as I installed it yesterday via the passenger installer commands listed in the tutorial above.

I have two users dealing with the install. root which I used to install everything, and deployer which is a user I created specifically to for deploying my applications

My web app directory is in the deployer user's home directory as follows: /home/deployer/webapps/mysite.com/public

Per Capistrano default deploy, a symbolic link called current is created in the public folder, and points to /home/deployer/webapps/mysite.com/public/releases/most_current_release

I have chmodded the deployer directory recursively to 777

/opt/nginx permissions: rwxr-xr-x

/usr/local/rvm/gems/ree-1.8.7-2010.02/gems/passenger-3.0.2 permissions: rwxrwsrwx

My nginx config file has gone through just short of eternity variations, but currently looks like this:

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

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    passenger_root /usr/local/rvm/gems/ree-1.8.7-2010.02/gems/passenger-3.0.2;
    passenger_ruby /usr/local/rvm/bin/passenger_ruby;

    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

    server {
       # listen      *:80;
        server_name mysite.com www.mysite.com;
        root   /home/deployer/webapps/mysite.com/public/current;

        passenger_enabled on;
        passenger_friendly_error_pages on;

        access_log logs/mysite.com/server.log;
        error_log logs/mysite.com/error.log info;

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

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

I bounce nginx, hit the site, and boom. 403, and logs say directory index of /home/deployer... is forbidden

As others with a similar problem have said, you can drop an index.html into the public/releases/current_release and it will render. But rails no worky.

That's basically it. At this point I have just about completely exhausted every possible solution attempt I can think of. I am a programmer and definitely not a sysadmin, so I am 99% sure this has something to do with permissions that I have hosed, but for the life of me I just can't figure out where.

If anyone can help I would really really appreciate it. If there's any specific permission things you want me to check (ie groups/permissions), can you please include the commands to do so as well. Hopefully this will help others in the future who read this post.

Let me know if there is any other information I can provide, and thanks in advance!!!


问:
Mongoose Save Callback is not working
I'm building a server for a simple web app that uses a MongoDB backend for storing data. I instantiate a new mongoose connection using:

```<code>mongoose.connect('mongodb://localhost:27017/callback-newsfeed-db')
</code>```

My MongoDB output seems fine:

```<code>2017-12-02T21:00:53.277-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52027 #86 (1 connection now open)
2017-12-02T21:00:53.291-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52028 #87 (2 connections now open)
2017-12-02T21:00:53.291-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52029 #88 (3 connections now open)
2017-12-02T21:00:53.292-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52030 #89 (4 connections now open)
2017-12-02T21:00:53.292-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52031 #90 (5 connections now open)
</code>```

I also defined a Model as follows:

```<code>const postSchema = mongoose.Schema({
  api: String,
  source: String,
  title: String,
  upvotes: Number
})

const Post = mongoose.model('Post', postSchema)
</code>```

In one of my server endpoints, I have the following code:

```<code>server.post('/posts', (request, response) => {
  console.log("INSIDE POSTS POST")
  const newapi = request.body.api
  const newsource = request.body.source
  const newtitle = request.body.title

  if(!newapi){
    response.send(422, "MUST PROVIDE API TYPE")
    return
  }else if(!newsource){
    response.send(422, "MUST PROVIDE RESOURCE SOURCE")
    return
  }else if(!newtitle){
    response.send(422, "MUST PROVIDE RESOURCE TITLE")
    return
 }

// Add a new post
  const newPost = new post.Post({
      api: newapi,
      source: newsource,
      title: newtitle,
      upvotes: UPVOTE_DEFAULT
  })
  console.log("ABOUT TO SAVE")

  // Save to DB and send to client
  newPost.save(error => {
      console.log("SAVE ERROR " )
      console.log(error)
      if(error){
          console.log("ERROR IN NEWPOST")
          throw error
      }else{
          console.log("STATUS OK")
          response.status(STATUS_OK)
          response.set({'Content-type': 'application/json'})
          response.send(JSON.stringify(newPost))
      }
      console.log("SAVE HAS COMPLETED")
  })
  console.log("AFTER NEW POST")
  })
</code>```

Now when I run my app, I see the following output in the console:

```<code>INSIDE POSTS POST
ABOUT TO SAVE
AFTER NEW POST
</code>```

However, for some reason (regardless of how long I wait) no part of the newPost.save() callback ever seems to get called.  The MongoDB output doesn't indicate an obvious error, so I'm a bit lost. Why could that be happening?

I'm pretty new to node so any thoughts on how to even go about debugging this or thinking about possible bug culprits would be greatly appreciated!

答: It turns out the issue appears to have been an incompatibility between the version of MongoDB I was using and mongoose. Once I upgraded my mongodb version via a call to npm upgrade mongodb, the save operation appears to have started working</p>

Title: Mongoose Save Callback is not working

Body:
I'm building a server for a simple web app that uses a MongoDB backend for storing data. I instantiate a new mongoose connection using:

mongoose.connect('mongodb://localhost:27017/callback-newsfeed-db')

My MongoDB output seems fine:

2017-12-02T21:00:53.277-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52027 #86 (1 connection now open)
2017-12-02T21:00:53.291-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52028 #87 (2 connections now open)
2017-12-02T21:00:53.291-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52029 #88 (3 connections now open)
2017-12-02T21:00:53.292-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52030 #89 (4 connections now open)
2017-12-02T21:00:53.292-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52031 #90 (5 connections now open)

I also defined a Model as follows:

const postSchema = mongoose.Schema({
  api: String,
  source: String,
  title: String,
  upvotes: Number
})

const Post = mongoose.model('Post', postSchema)

In one of my server endpoints, I have the following code:

server.post('/posts', (request, response) => {
  console.log("INSIDE POSTS POST")
  const newapi = request.body.api
  const newsource = request.body.source
  const newtitle = request.body.title

  if(!newapi){
    response.send(422, "MUST PROVIDE API TYPE")
    return
  }else if(!newsource){
    response.send(422, "MUST PROVIDE RESOURCE SOURCE")
    return
  }else if(!newtitle){
    response.send(422, "MUST PROVIDE RESOURCE TITLE")
    return
 }

// Add a new post
  const newPost = new post.Post({
      api: newapi,
      source: newsource,
      title: newtitle,
      upvotes: UPVOTE_DEFAULT
  })
  console.log("ABOUT TO SAVE")

  // Save to DB and send to client
  newPost.save(error => {
      console.log("SAVE ERROR " )
      console.log(error)
      if(error){
          console.log("ERROR IN NEWPOST")
          throw error
      }else{
          console.log("STATUS OK")
          response.status(STATUS_OK)
          response.set({'Content-type': 'application/json'})
          response.send(JSON.stringify(newPost))
      }
      console.log("SAVE HAS COMPLETED")
  })
  console.log("AFTER NEW POST")
  })

Now when I run my app, I see the following output in the console:

INSIDE POSTS POST
ABOUT TO SAVE
AFTER NEW POST

However, for some reason (regardless of how long I wait) no part of the newPost.save() callback ever seems to get called.  The MongoDB output doesn't indicate an obvious error, so I'm a bit lost. Why could that be happening?

I'm pretty new to node so any thoughts on how to even go about debugging this or thinking about possible bug culprits would be greatly appreciated!


问:
Apple Mach -O Linker (Id) Error?
I am trying to build this xcode workspace which was built from Unity. And after modifying the project a little bit when I getting to the very end of building the project (linking) I get the Apple Mach -O Linker (Id) Error. I can't open the error tab to see what exactly is causing the error. All it says is "Linker command failed with exit code 1 (use -v to see invocation). There are also two Apple Mach -O Linker (Id) Errors which occur but I have no idea how to solve them.

Any help is greatly appreciated!

I can't expand these tabs.. this is all I get told
This is the warning tab expanded, the two Apple Mach -O Linker (Id) warnings are the same

答: For me it was missing frameworks. Try searching the errors you get on Google and find out which frameworks they're part of, then import them in the Build phases tab. </p>

Title: Apple Mach -O Linker (Id) Error?


问:
how to get client_id and client_secret code in cloud foundry using api's
In cloud foundry how can I get the client_id and client_secret code.

This will be used in Basic authentication instead of passing the user and password for respective api calls

答:
You will need admin role to be able to create a client or get its details.
Refer https://docs.cloudfoundry.org/api/uaa/version/4.7.1/index.html#clients to see various api to manage and create clients.
You can also use the uaa client to get the client details.
Refer https://docs.cloudfoundry.org/uaa/uaa-user-management.html for more info.</p>


问:
sunspot index using dynamic attributes
I am trying to integrate sunspot Solr in my Ruby application
I am using dynamic_string for indexing additional data with my model.
However I am getting error

```<code>searchable do
    text :name
    integer :id
    text :thumbnail_ref
    integer :health_condition_id
    dynamic_string :standard_codes, stored: true do
      st_codes().inject({}) do |hash, e|
        logger.info e.standard
         logger.info e.standard_code
         hash.merge(e.standard.to_sym => e.standard_code)
        logger.info hash
      end
    end

  end

  def st_codes()
    Standard.find_standards_by_health_condition(198)
  end
</code>```

NoMethodError (undefined method merge' for true:TrueClass):
  app/models/content.rb:35:inblock (3 levels) in '
  app/models/content.rb:32:in `block (2 levels) in '

I am not clear about this error.Any help here is very much appreciated.

答:
when you inject you have to return the injected hash for the following iterations.
atm you get a boolean True from logger.info.

change to this

```<code>  st_codes().inject({}) do |hash, e|
     logger.info e.standard
     logger.info e.standard_code
     hash.merge!(e.standard.to_sym => e.standard_code)
     logger.info hash
     hash
  end
</code>```

Title: sunspot index using dynamic attributes

Body:
I am trying to integrate sunspot Solr in my Ruby application
I am using dynamic_string for indexing additional data with my model.
However I am getting error

searchable do
    text :name
    integer :id
    text :thumbnail_ref
    integer :health_condition_id
    dynamic_string :standard_codes, stored: true do
      st_codes().inject({}) do |hash, e|
        logger.info e.standard
         logger.info e.standard_code
         hash.merge(e.standard.to_sym => e.standard_code)
        logger.info hash
      end
    end

  end

  def st_codes()
    Standard.find_standards_by_health_condition(198)
  end

NoMethodError (undefined method merge' for true:TrueClass):
  app/models/content.rb:35:inblock (3 levels) in '
  app/models/content.rb:32:in `block (2 levels) in '

I am not clear about this error.Any help here is very much appreciated.

Body:
when you inject you have to return the injected hash for the following iterations.
atm you get a boolean True from logger.info.

change to this

  st_codes().inject({}) do |hash, e|
     logger.info e.standard
     logger.info e.standard_code
     hash.merge!(e.standard.to_sym => e.standard_code)
     logger.info hash
     hash
  end


问:
combine blocks of code to one function
How can I make one function to do something like this</p>

```<code>$('#check_express').is(':checked') ? $('#form_express').show() : $('#form_express').hide();

$('#check_express').on('change', function(){
    $(this).is(':checked') ? $('#form_express').show() :
    $('#form_express').hide();
});

$('#check_standard').is(':checked') ? $('#form_standard').show() : $('#form_standard').hide();

$('#check_standard').on('change', function(){
    $(this).is(':checked') ? $('#form_standard').show() :
    $('#form_standard').hide();
});
</code>```

答:
You can use toggle like following :

$('#check_express').on('change', function() {
  $('#form_express').toggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check_express" />
<div id="form_express" style="display: none">
  Hello, world.
</div></code>```

Title: combine blocks of code to one function

Body:
How can I make one function to do something like this

$('#check_express').is(':checked') ? $('#form_express').show() : $('#form_express').hide();

$('#check_express').on('change', function(){
    $(this).is(':checked') ? $('#form_express').show() :
    $('#form_express').hide();
});

$('#check_standard').is(':checked') ? $('#form_standard').show() : $('#form_standard').hide();

$('#check_standard').on('change', function(){
    $(this).is(':checked') ? $('#form_standard').show() :
    $('#form_standard').hide();
});

Body:
You can use toggle like following :

$('#check_express').on('change', function() {
  $('#form_express').toggle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check_express" />
<div id="form_express" style="display: none">
  Hello, world.
</div>


问:
Javascript - Replace all with regex
I want to replace some spaces between some parenthesis with regex. If I use regex only replace some spaces (only unique pairs).

The string may be have others spaces, but I want only the spaces between paranthesis.

```<code>var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/\)\s\)/g, "))");
console.log(mystring);
</code>```

Output is:

```<code>) ) ) ) ) )
)) )) ))
</code>```

But I want to have this output:

```<code>) ) ) ) ) )
))))))
</code>```

答:
Move the last ) to a positive lookahead and replace with a single ):

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/\)\s+(?=\))/g, ")");
console.log(mystring); // => ))))))```

See the regex demo.

Pattern details

\) - a )

\s+ - 1+ whitespaces

(?=\)) - a positive lookahead that requires a ) immediately to the right of the current location (after 1+ whitespaces).

Title: Javascript - Replace all with regex

Body:
I want to replace some spaces between some parenthesis with regex. If I use regex only replace some spaces (only unique pairs).

The string may be have others spaces, but I want only the spaces between paranthesis.

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/\)\s\)/g, "))");
console.log(mystring);

Output is:

) ) ) ) ) )
)) )) ))

But I want to have this output:

) ) ) ) ) )
))))))

Body:
Move the last ) to a positive lookahead and replace with a single ):

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/\)\s+(?=\))/g, ")");
console.log(mystring); // => ))))))

See the regex demo.

Pattern details

\) - a )

\s+ - 1+ whitespaces

(?=\)) - a positive lookahead that requires a ) immediately to the right of the current location (after 1+ whitespaces).


答:
Possibly:</p>

```<code>students = [['Gary','Y'],['Steve','N'],['Tom','Y']]

for i in range (len(students)):
        if students[i[2]] == 'Y':
            print (students[i])
</code>```

Title: Searching through a 2D array in python 2.7 if a char is in that position

Body:
Possibly:

students = [['Gary','Y'],['Steve','N'],['Tom','Y']]

for i in range (len(students)):
        if students[i[2]] == 'Y':
            print (students[i])


问:
How to add font awesome to ASP.NET Core Angular 2 application in Visual Studio 2017 with SpaTemplates
I am using the Single Page Application Template in Visual Studio 2017 in order to create an Angular 2 application.

```<code>dotnet new --install Microsoft.AspNetCore.SpaTemplates::*
</code>```

And then created the application like this:

```<code>dotnet new angular
</code>```

What is the reccommended way of importing third Party libraries like font awesome into the Angular 2 application?

答:
Credit original post

This is for .NET Core 2, after you create a SPA Project using dotnet new angular:

Go to the root of the project and install the package: npm install font-awesome --save. You should now see it in package.json dependencies.

After that go to webpack.config.vendor.js and add font awesome to the array under non tree shakable modules:

const nonTreeShakableModules = [
    'bootstrap',
    'bootstrap/dist/css/bootstrap.css',
    'es6-promise',
    'es6-shim',
    'event-source-polyfill',
    'font-awesome/css/font-awesome.css',
    'jquery',
];

Now we need to tell the webpack that we added this new package. So if you haven't done so before install this in the root of project with npm install --save-dev npm-install-webpack-plugin.

Finally, run this command in the root of project: webpack --config webpack.config.vendor.js

Body:
I am using the Single Page Application Template in Visual Studio 2017 in order to create an Angular 2 application.

dotnet new --install Microsoft.AspNetCore.SpaTemplates::*

And then created the application like this:

dotnet new angular

What is the reccommended way of importing third Party libraries like font awesome into the Angular 2 application?


问:
How can I display "Closed" or "Open" based on time in vue js html?
This is my json data to show the Hours of operation of the shop:

```<code>{
    "status": true,
    "data": {
        "pid": 1,
        "bussinessName": "ard",
        "services": "looking for passionate",
        "inventory": [],
        "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM"
    }
}
</code>```

My vuejs code is:

```<code><script>
    new Vue({
        el: '#feed' ,
        data: {
            data: [],
        },
        mounted() {
            this.$nextTick(function() {
                var self = this;
                var id = 1;
                console.log(id)
                $.ajax({
                    url: "https://n2s.herokuapp.com/api/post/get/"+{{pid}},
                method: "GET",
                    dataType: "JSON",
                    success: function (e) {
                    if (e.status == 1) {
                        self.data = e.data;
                        console.log(e.data)

                        const workHour = e.data.workHr.split(',').map((val) => {
                            const obj = val.split(':');
                        const time = val.replace(`${obj[0]}:`, '');
                        return {
                            day: obj[0],
                            time,
                        }
                    });
                    }
                    else
                    {
                        console.log('Error occurred');}
                }, error: function(){
                    console.log('Error occurred');
                }
            });
            })
        },
    })
</script>
</code>```

I display today's hours of operations using the following code:

```<code><div v-for="(item,key) in data.workHr" :key="key">
  <span v-if="new Date().getDay()-1==key">  <img src="/static/assets/img/timer.png">Today :  {{item.time}}</span>
 </div>
</code>```

In addition to their hours of operation, I also need to display "Closed" or "Open" based on whether it is within their working hours or not. How can I implement this?

答:
First of all, your JSON schema seems incorrect due to some typo mistake. I fixed the JSON schema and hardcoded it in the code and remove the AJAX call to make the code workable. Hope you can replace it will AJAX call by yourself.

Explanation

I have used two libraries to manipulate date/time. First one is momentjs and other one is it's plugin moment-range. Then, I have formatted your dates in JavaScript instead of doing it on template and used range method to calculate the OPENED and CLOSED status. I have also added parseTime function to parse the time for handling AM/PM.

window['moment-range'].extendMoment(moment);

function parseTime(time, format) {
  var add12 = false;
  if (time.indexOf('PM') > -1) {
    add12 = true;
  }
  time = moment(time.replace('AM', '').replace('PM', ''), 'hh:mm');
  if (add12) {
    time.add(12, 'hours')
  }
  return time;
}

new Vue({
  el: '#feed',
  data: {
    data: [],
  },
  mounted() {
    this.$nextTick(function() {
      var self = this;
      var id = 1;
      self.today_open = false;
      var e = {
        "status": true,
        "data": {
          "pid": 1,
          "bussinessName": "ard",
          "services": "looking for passionate",
          "inventory": [],
          "workHr": "Monday :9:00AM to 10:00PM,Tuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Thursday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM"
        }
      }
      self.data = e.data;
      const workHour = e.data.workHr.split(',').map((val) => {
        const obj = val.split(':');
        const time = val.replace(`${obj[0]}:`, '');
        const time_from = time.split('to')[0].trim();
        const time_to = time.split('to')[1].trim();
        var timeWindow = moment.range(parseTime(time_from), parseTime(time_to));
        return {
          day: obj[0],
          time_from: parseTime(time_from).format('hh:mm A'),
          time_to: parseTime(time_to).format('hh:mm A'),
          today_open: timeWindow.contains(new Date())
        }
      });
      self.data.workHr = workHour
    });
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script src="https://npmcdn.com/moment@2.14.1/moment.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment-range/3.0.3/moment-range.js"></script>

<div id="feed">
  <div v-for="(item,key) in data.workHr" :key="key">
    <span v-if="new Date().getDay()-1==key">  Today :  {{item.time_from}} to {{item.time_to}} <span v-if="item.today_open">OPENED</span><span v-if="!item.today_open">CLOSED</span></span>
  </div>
</div></code>```

Body:
This is my json data to show the Hours of operation of the shop:

{
    "status": true,
    "data": {
        "pid": 1,
        "bussinessName": "ard",
        "services": "looking for passionate",
        "inventory": [],
        "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM"
    }
}

My vuejs code is:

I display today's hours of operations using the following code:

    Today :  {{item.time}}

In addition to their hours of operation, I also need to display "Closed" or "Open" based on whether it is within their working hours or not. How can I implement this?

Body:
First of all, your JSON schema seems incorrect due to some typo mistake. I fixed the JSON schema and hardcoded it in the code and remove the AJAX call to make the code workable. Hope you can replace it will AJAX call by yourself.

Explanation

I have used two libraries to manipulate date/time. First one is momentjs and other one is it's plugin moment-range. Then, I have formatted your dates in JavaScript instead of doing it on template and used range method to calculate the OPENED and CLOSED status. I have also added parseTime function to parse the time for handling AM/PM.

window['moment-range'].extendMoment(moment);

function parseTime(time, format) {
  var add12 = false;
  if (time.indexOf('PM') > -1) {
    add12 = true;
  }
  time = moment(time.replace('AM', '').replace('PM', ''), 'hh:mm');
  if (add12) {
    time.add(12, 'hours')
  }
  return time;
}

new Vue({
  el: '#feed',
  data: {
    data: [],
  },
  mounted() {
    this.$nextTick(function() {
      var self = this;
      var id = 1;
      self.today_open = false;
      var e = {
        "status": true,
        "data": {
          "pid": 1,
          "bussinessName": "ard",
          "services": "looking for passionate",
          "inventory": [],
          "workHr": "Monday :9:00AM to 10:00PM,Tuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Thursday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM"
        }
      }
      self.data = e.data;
      const workHour = e.data.workHr.split(',').map((val) => {
        const obj = val.split(':');
        const time = val.replace(`${obj[0]}:`, '');
        const time_from = time.split('to')[0].trim();
        const time_to = time.split('to')[1].trim();
        var timeWindow = moment.range(parseTime(time_from), parseTime(time_to));
        return {
          day: obj[0],
          time_from: parseTime(time_from).format('hh:mm A'),
          time_to: parseTime(time_to).format('hh:mm A'),
          today_open: timeWindow.contains(new Date())
        }
      });
      self.data.workHr = workHour
    });
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script src="https://npmcdn.com/moment@2.14.1/moment.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment-range/3.0.3/moment-range.js"></script>

<div id="feed">
  <div v-for="(item,key) in data.workHr" :key="key">
    <span v-if="new Date().getDay()-1==key">  Today :  {{item.time_from}} to {{item.time_to}} <span v-if="item.today_open">OPENED</span><span v-if="!item.today_open">CLOSED</span></span>
  </div>
</div>


问:
Unable to upload picture from Android to java server
I've been trying to implement profile photo upload feature by Android Retrofit + SpringMVC. Java server unable to respond Retrofit API call. Related code snippet is given below:

ApiInterface

```<code>@Multipart
@POST("user/profileImage")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part image, @Part("name") RequestBody name);
</code>```

uploadToServer

```<code>public void uploadToServer(){
    //Get retrofit client
    Retrofit retrofit = ApiClient.getClient();
    //Get API interface
    ApiInterface apiInterface = retrofit.create(ApiInterface.class);
    // Get image parts
    MultipartBody.Part imageParts = bitmapToMultipart(imageBitmap);
    //Get image name
    RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "ProfileImage");
    //Call image upload API
    Call<ResponseBody> call = apiInterface.uploadImage(imageParts,name);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            ResponseBody body = response.body();
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            t.printStackTrace();
        }
    });
}
</code>```

bitmapToMultipart

```<code>public MultipartBody.Part bitmapToMultipart(Bitmap imageBitmap){
    File file = null;
    try {
        //create a file to write bitmap data
        file = new File(this.getCacheDir(), "imageBitmap");
        file.createNewFile();

        //Convert bitmap to byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 0 /*ignored for PNG*/, bos);
        byte[] bitmapdata = bos.toByteArray();

        //write the bytes in file
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bitmapdata);
        fos.flush();
        fos.close();
    }catch(IOException e){
        e.printStackTrace();
    }
    RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
    MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);

    return body;
}
</code>```

Java SpringMVC controller

```<code>@Controller
@RequestMapping("/user")
public class UserController{
    @RequestMapping(value = "/profileImage", method = RequestMethod.POST)
    public  @ResponseBody String imageUploader(@RequestParam("image") MultipartFile image, @RequestBody RequestBody name)throws Exception{
        return "";
    }
}
</code>```

Problem is: Request not even reaching to java server.

答:
first you should check android client upload file is OK.eg:use compress quality 80

imageBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);

change  MediaType and debug at client RequestBody have data

Debug at server check receive request data

Body:
I've been trying to implement profile photo upload feature by Android Retrofit + SpringMVC. Java server unable to respond Retrofit API call. Related code snippet is given below:

ApiInterface

@Multipart
@POST("user/profileImage")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part image, @Part("name") RequestBody name);

uploadToServer

public void uploadToServer(){
    //Get retrofit client
    Retrofit retrofit = ApiClient.getClient();
    //Get API interface
    ApiInterface apiInterface = retrofit.create(ApiInterface.class);
    // Get image parts
    MultipartBody.Part imageParts = bitmapToMultipart(imageBitmap);
    //Get image name
    RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "ProfileImage");
    //Call image upload API
    Call<ResponseBody> call = apiInterface.uploadImage(imageParts,name);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            ResponseBody body = response.body();
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            t.printStackTrace();
        }
    });
}

bitmapToMultipart

public MultipartBody.Part bitmapToMultipart(Bitmap imageBitmap){
    File file = null;
    try {
        //create a file to write bitmap data
        file = new File(this.getCacheDir(), "imageBitmap");
        file.createNewFile();

        //Convert bitmap to byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 0 /*ignored for PNG*/, bos);
        byte[] bitmapdata = bos.toByteArray();

        //write the bytes in file
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bitmapdata);
        fos.flush();
        fos.close();
    }catch(IOException e){
        e.printStackTrace();
    }
    RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
    MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);

    return body;
}

Java SpringMVC controller

@Controller
@RequestMapping("/user")
public class UserController{
    @RequestMapping(value = "/profileImage", method = RequestMethod.POST)
    public  @ResponseBody String imageUploader(@RequestParam("image") MultipartFile image, @RequestBody RequestBody name)throws Exception{
        return "";
    }
}

Problem is: Request not even reaching to java server.


问:
Scheme (DrRacket) lambda expression
I do not understand the following program code. Can anyone explain it to me?

```<code>(define myFunction
  (lambda (f x y z)
    (f x y z)))
</code>```

How can I simplify it?

答:
lambda ... creates a function which expects 4 arguments, the first of which (f) should itself be a function. (f x y z) applies this f to the other 3 arguments.

define gives the name myFunction to the lambda.

Title: Scheme (DrRacket) lambda expression

Body:
I do not understand the following program code. Can anyone explain it to me?

(define myFunction
  (lambda (f x y z)
    (f x y z)))

How can I simplify it?


问:
Xcode 9.1 cant start the Iphone simulator
I just installed Xcode 9.1,before Xcode 9.1,when I click the "Play" button on top,the Iphone simulator start automatically.But after install Xcode 9.1,the iPhone simulator didnt start,no error,no phone appear on screen,only Xcode show build success.

Can somebody tell me how to solve this?So I can test the project on Iphone simulator.

Edit

After looking for a question in So,I able to start the simulator,by doing

Click on Target next to Play Button -> Edit Scheme -> Run -> Change
  the Executable to "My Project"

The iphone simulator can start,but it give me this error

Any idea?

答:
There seems to be a issue with iPhone simulator.You can see this issue in fastlane's git hub page as well. Happens more often when you are using command line tools.

Solution : Simply tap command + space opens hot search, type simulator and hit enter,

your simulator might not load and show an error thats fine. Now go to actions select simulator and say Reset Content and Settings.

Now go back to your Xcode and re run the code. Hope this resolves the issue


问:
SQL INSERT INTO from multiple tables
this is my table 1:

```<code>NAME       AGE        SEX        CITY             ID

Clara      22         f          New York         1
Bob        33         m          Washington       2
Sam        25         m          Boston           3
</code>```

this is my table 2:

```<code>NUMBER       ID
555-1111     1
555-2222     2
555-3333     3
</code>```

and now I want a table 3 which shows me all information:

```<code>NAME       AGE        SEX        CITY             ID        NUMBER

Clara      22         f          New York         1         555-1111
Bob        33         m          Washington       2         555-2222
Sam        25         m          Boston           3         555-3333
</code>```

I tried first to insert into table 3 only the values from table 1 and then I inserted into table 3 the values from table 2 with an inner join where Id = Id is.

```<code>INSERT INTO table3 { name, age, sex, city, id}
SELECT name, age, sex, city, id
FROM table 1

INSERT INTO table3 { name, age, sex, city, id, number}
SELECT name, age, sex, city, id, number
FROM table 2 p
INNER JOIN table 3 c ON c.Id = p.Id
</code>```

But all I get is a duplication of my values. instead of having 3 entries, I have like 9 entries, which some have number null, some have only the number and the rest null, and some are correct.

I hope someone can help me

EDIT

If I am having now a third Table like this one:

```<code>NATIONALITY       ID

Canadian          1
American          2
French            3
</code>```

How could I merge all 3 tables into one Table?

答:
Here is an example if multiple tables don't have common Id, you can create yourself, I use 1 as commonId to create common id so that I can inner join them:

```<code>Insert Into #TempResult
select CountA, CountB, CountC  from

(
select Count(A_Id) as CountA, 1 as commonId from tableA
  where ....
  and  ...
  and   ...
) as tempA

inner join
(
select Count(B_Id) as CountB, 1 as commonId from tableB
  where ...
  and ...
  and  ...
 ) as tempB

on tempA.commonId = tempB.commonId

inner join
(
select Count(C_ID) as CountC, 1 as commonId from tableC
where ...
and   ...
) as tempC

on tmepB.commonId = tempC.commonId

--view insert result
select * from #TempResult
</code>```

Title: SQL INSERT INTO from multiple tables

Body:
this is my table 1:

NAME       AGE        SEX        CITY             ID

Clara      22         f          New York         1
Bob        33         m          Washington       2
Sam        25         m          Boston           3

this is my table 2:

NUMBER       ID
555-1111     1
555-2222     2
555-3333     3

and now I want a table 3 which shows me all information:

NAME       AGE        SEX        CITY             ID        NUMBER

Clara      22         f          New York         1         555-1111
Bob        33         m          Washington       2         555-2222
Sam        25         m          Boston           3         555-3333

I tried first to insert into table 3 only the values from table 1 and then I inserted into table 3 the values from table 2 with an inner join where Id = Id is.

INSERT INTO table3 { name, age, sex, city, id}
SELECT name, age, sex, city, id
FROM table 1

INSERT INTO table3 { name, age, sex, city, id, number}
SELECT name, age, sex, city, id, number
FROM table 2 p
INNER JOIN table 3 c ON c.Id = p.Id

But all I get is a duplication of my values. instead of having 3 entries, I have like 9 entries, which some have number null, some have only the number and the rest null, and some are correct.

I hope someone can help me

EDIT

If I am having now a third Table like this one:

NATIONALITY       ID

Canadian          1
American          2
French            3

How could I merge all 3 tables into one Table?

Body:
Here is an example if multiple tables don't have common Id, you can create yourself, I use 1 as commonId to create common id so that I can inner join them:

Insert Into #TempResult
select CountA, CountB, CountC  from

(
select Count(A_Id) as CountA, 1 as commonId from tableA
  where ....
  and  ...
  and   ...
) as tempA

inner join
(
select Count(B_Id) as CountB, 1 as commonId from tableB
  where ...
  and ...
  and  ...
 ) as tempB

on tempA.commonId = tempB.commonId

inner join
(
select Count(C_ID) as CountC, 1 as commonId from tableC
where ...
and   ...
) as tempC

on tmepB.commonId = tempC.commonId

--view insert result
select * from #TempResult


问:
C# to format @Url.Action("DisplayMeeting", "Home", new { meetingId = @item.meetingId, meetingType = @kvp.Key}) in Model property
I have a model as below

```<code>public class Node
{
    public string text { get; set; }
    public string href { get; set; }
    public Guid meetingId { get; set; }
    public Guid meetingType { get; set; }
}
</code>```

Here is the code for the controller where I am binding the respective value to the model object

```<code>bootstrapTree.nodes.Add(new Node
{
    text = val.meetingDate != null ? val.meetingDate.Value.ToString("dd MMMM, yyyy") : "",
    meetingId = val.meetingId,
    meetingType = val.meetingType,
    href =string.Format("{0}{1}{2}{3}", "/Home/DisplayMeeting?meetingId=", val.meetingId, "&meetingType=", bootstrapTree.text)
});
</code>```

The current code to bind the data to the href is using to string. Now I, want to bind the data to href as

```<code>@Url.Action("DisplayMeeting", "Home", new { meetingId = @item.meetingId, meetingType = @kvp.Key})`
</code>```

How can I, modify the existing code to @Url.Action() or any other better option do I have to bind to href.

答:
UrlHelper is available in the Controller and View. If you need it in a ViewModel, you can create an UrlHelper from the HttpContext. If you need it in another class, inject it.

```<code>var url = new UrlHelper(HttpContext.Current.Request.RequestContext);
var href = url.Action("DisplayMeeting", "Home" new { meetingId = val.meetingId, meetingType = val.meetingType })
</code>```

Body:
I have a model as below

public class Node
{
    public string text { get; set; }
    public string href { get; set; }
    public Guid meetingId { get; set; }
    public Guid meetingType { get; set; }
}

Here is the code for the controller where I am binding the respective value to the model object

bootstrapTree.nodes.Add(new Node
{
    text = val.meetingDate != null ? val.meetingDate.Value.ToString("dd MMMM, yyyy") : "",
    meetingId = val.meetingId,
    meetingType = val.meetingType,
    href =string.Format("{0}{1}{2}{3}", "/Home/DisplayMeeting?meetingId=", val.meetingId, "&meetingType=", bootstrapTree.text)
});

The current code to bind the data to the href is using to string. Now I, want to bind the data to href as

@Url.Action("DisplayMeeting", "Home", new { meetingId = @item.meetingId, meetingType = @kvp.Key})`

How can I, modify the existing code to @Url.Action() or any other better option do I have to bind to href.

Body:
UrlHelper is available in the Controller and View. If you need it in a ViewModel, you can create an UrlHelper from the HttpContext. If you need it in another class, inject it.

var url = new UrlHelper(HttpContext.Current.Request.RequestContext);
var href = url.Action("DisplayMeeting", "Home" new { meetingId = val.meetingId, meetingType = val.meetingType })


问:
Android setContentView or Intents?
I have a very simple 2 screen android app.

Is there any downside to simply switching out the layouts via setContentView or should i be using intents?Don't want to bugger up my app if something is wrong with this.

答: Another thing to consider is that activities form a stack. If you want to be able to go back to the previous activity via the 'back' button, then you need to use activity. But if it is something simple like a 'loading' screen when your app starts and you don't have to go back to it again, setting content view would be a much better idea.</p>

Title: Android setContentView or Intents?


问:
Running mulitple process in Node JS
Okay so I'm trying to build a web service for twitter automation. I have build bots before that works only for a single account.

The service that I'm looking to build will enable users to register and then set up some preference (like follow users that tweets #ILoveProgramming).

My main question is - right now if I need to run the bot I just type "node bot.js" and the bot will run. How do I run multiple process for all the hundred users that'll be using my Web Service ?

答: Running a process for every user will not be a scalable way to achieve this. You can try using async.each to run the same function for every user in parallel.</p>

Title: Running mulitple process in Node JS


问:
woocommerce_before_calculate_totals fires twice
Writing an addition to the site, want to modify the price in the cart. Have the following code:

```<code>function apd_product_custom_price($cart_item_data, $product_id)
{
    if (isset($_POST['use_rewards']) && !empty($_POST['use_rewards']))
    {
       $cart_item_data['use_rewards'] = $_POST['use_rewards'];
    }
    return $cart_item_data;
}

add_filter('woocommerce_add_cart_item_data', 'apd_product_custom_price', 99, 2);

function apd_apply_custom_price_to_cart_item($cart_object)
{
   if( !WC()->session->__isset( 'reload_checkout' )) {
        foreach ($cart_object->cart_contents as $value) {
            if(isset($value['use_rewards'])) {
                $price = $value['data']->get_price() -
   $value['use_rewards'];
                $value['data']->set_price($price);
            }
        }
    }

}
add_action('woocommerce_before_calculate_totals', 'apd_apply_custom_price_to_cart_item',10);
</code>```

By some reason the hook woocommerce_before_calculate_totals fires twice. if I replace the code in the function apd_apply_custom_price_to_cart_item($cart_object) with just echo 1; it displays 11 in the cart page. Can some please help?

答:
Most likely some other plugins hooks to 'woocommerce_before_calculate_totals' action.

Try to disable plugins one by one and see witch one is causing this behaviour.

In my case I found that WooCommerce-multilingual plugin hooks to woocommerce_before_calculate_totals action.

So I did this:

```<code>add_action( 'woocommerce_before_calculate_totals', '_wm_ponc_upte_prc', 99 );
function _wm_ponc_upte_prc( $cart_object ) {
    if ( !WC()->session->__isset( "reload_checkout" ) ) {
        foreach ( WC()->cart->get_cart() as $key => $value ) {
            // checking if user checked checkbox (optional)
            if ( isset( $value['wm_ponc_fee'] ) && ( $value[ 'wm_ponc_fee' ] === 'yes' ) ) {
                // your calculations ....
                // and Remove your action after you are done.
                remove_action( 'woocommerce_before_calculate_totals', '_wm_ponc_upte_prc', 99 );
            }
        }
    }
}
</code>```

I have removed action after custom calculations. And that's it.

Body:
Writing an addition to the site, want to modify the price in the cart. Have the following code:

function apd_product_custom_price($cart_item_data, $product_id)
{
    if (isset($_POST['use_rewards']) && !empty($_POST['use_rewards']))
    {
       $cart_item_data['use_rewards'] = $_POST['use_rewards'];
    }
    return $cart_item_data;
}

add_filter('woocommerce_add_cart_item_data', 'apd_product_custom_price', 99, 2);

function apd_apply_custom_price_to_cart_item($cart_object)
{
   if( !WC()->session->__isset( 'reload_checkout' )) {
        foreach ($cart_object->cart_contents as $value) {
            if(isset($value['use_rewards'])) {
                $price = $value['data']->get_price() -
   $value['use_rewards'];
                $value['data']->set_price($price);
            }
        }
    }

}
add_action('woocommerce_before_calculate_totals', 'apd_apply_custom_price_to_cart_item',10);

By some reason the hook woocommerce_before_calculate_totals fires twice. if I replace the code in the function apd_apply_custom_price_to_cart_item($cart_object) with just echo 1; it displays 11 in the cart page. Can some please help?

Body:
Most likely some other plugins hooks to 'woocommerce_before_calculate_totals' action.

Try to disable plugins one by one and see witch one is causing this behaviour.

In my case I found that WooCommerce-multilingual plugin hooks to woocommerce_before_calculate_totals action.

So I did this:

add_action( 'woocommerce_before_calculate_totals', '_wm_ponc_upte_prc', 99 );
function _wm_ponc_upte_prc( $cart_object ) {
    if ( !WC()->session->__isset( "reload_checkout" ) ) {
        foreach ( WC()->cart->get_cart() as $key => $value ) {
            // checking if user checked checkbox (optional)
            if ( isset( $value['wm_ponc_fee'] ) && ( $value[ 'wm_ponc_fee' ] === 'yes' ) ) {
                // your calculations ....
                // and Remove your action after you are done.
                remove_action( 'woocommerce_before_calculate_totals', '_wm_ponc_upte_prc', 99 );
            }
        }
    }
}

I have removed action after custom calculations. And that's it.


问:
Error rendering html img in iphone screens
I am experiencing a bug in the web i am developing.

In an ordinary grid of projects, bits of images appear on top of other html img placeholders in the nearby, with erratic behaviour on scrolling or zooming.

It only happens on certain iphones, not all of them, but when it happens it's on both safari and chrome ios. Everything is ok in desktop.

The error does not happen immediately, but after navigating a while. Once the error occurs, it persists even after refreshing the page.
This video shows it best: https://vimeo.com/245343214

The code seems ok: jorgevidal.eu

At first i thought it could be related to isotope (masonry), but disabling it would not fix the error.

Screenshots from 2017 iPhone 7:

答:
The error was fixed deleting the css affecting the filters on images.

So the code

```<code>@media (max-width:1024px){

        img{filter:none; -webkit-filter: contrast(1) grayscale(0%);}

}
</code>```

was causing the bug.

Body:
The error was fixed deleting the css affecting the filters on images.

So the code

@media (max-width:1024px){

        img{filter:none; -webkit-filter: contrast(1) grayscale(0%);}

}

was causing the bug.


答:
How about a lookbehind:

```<code>var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/(?<=\))\s(?=\))/g, "");
console.log(mystring);
</code>```

Demo:

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/(?<=\))\s(?=\))/g, "");
console.log(mystring);```

This will remove all spaces between ) )

Title: Javascript - Replace all with regex

Body:
How about a lookbehind:

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/(?<=\))\s(?=\))/g, "");
console.log(mystring);

Demo:

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/(?<=\))\s(?=\))/g, "");
console.log(mystring);

This will remove all spaces between ) )


问:
Wrong camera position playing 360 degree video, using SceneKit and CoreMotion
I am playing around with a 360 degree video player using SpriteKit, SceneKit and CoreMotion. The player is working so far, but the video is always zoomed-in a bit. It looks like the camera position is not at (0,0,0), but somehow wrong on the Z axis. Unfortunately, I have not found a way to adjust that. To reproduce the behavior just tap the screen, when the video is playing and pinch-zoom-out. This enables camera control with gestures, double tapping returns to camera control with the device.

```<code>import UIKit
import SceneKit
import CoreMotion
import SpriteKit
import AVFoundation

class Video360VC: UIViewController {
let motionManager = CMMotionManager()
let cameraNode = SCNNode()
@IBOutlet weak var sceneView: SCNView!

@IBAction func exitBtnClicked(_ sender: Any) {
performSegueToReturnBack()
}

func createSphereNode(material: AnyObject?) -> SCNNode {
    let sphere = SCNSphere(radius: 20.0)
    sphere.firstMaterial!.isDoubleSided = true
    sphere.firstMaterial!.diffuse.contents = material
    let sphereNode = SCNNode(geometry: sphere)
    sphereNode.position = SCNVector3Make(0,0,0)
    sphereNode.rotation = SCNVector4Make(1, 0, 0, Float.pi)
    return sphereNode
}

func configureScene(node sphereNode: SCNNode) {
    // Set the scene
    let scene = SCNScene()
    sceneView.scene = scene
    sceneView.showsStatistics = true
    sceneView.allowsCameraControl = true

    // Camera, ...
    cameraNode.camera = SCNCamera()
    cameraNode.position = SCNVector3Make(0, 0, 0)
    scene.rootNode.addChildNode(sphereNode)
    scene.rootNode.addChildNode(cameraNode)
}

func startCameraTracking() {
    motionManager.deviceMotionUpdateInterval = 1.0 / 60.0
    motionManager.startDeviceMotionUpdates(to: OperationQueue.main) {
        [weak self](data: CMDeviceMotion?, error: Error?) in
        guard let data = data else { return }
        let attitude: CMAttitude = data.attitude

        self?.cameraNode.eulerAngles = SCNVector3Make(-   Float(attitude.roll + Double.pi/2), Float(attitude.yaw), -Float(attitude.pitch))
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    guard let fileURL = Bundle.main.url(forResource: "360Test2", withExtension: "mp4") else {
        print("Video File not found")
        return
    }

    let player = AVPlayer(url: fileURL)
    let videoNode = SKVideoNode(avPlayer: player)
    let size = CGSize(width: 1280, height: 720)
    videoNode.size = size
    videoNode.position = CGPoint(x: size.width/2, y: size.height/2)

    let spriteScene = SKScene(size: size)
    spriteScene.scaleMode = .resizeFill
    spriteScene.addChild(videoNode)

    let sphereNode = createSphereNode(material:spriteScene)
    configureScene(node: sphereNode)
    guard motionManager.isDeviceMotionAvailable else {
        fatalError("Device motion is not available")
    }
    startCameraTracking()
    player.play()
}

override func viewWillAppear(_ animated: Bool) {
    self.sceneView.play(self)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}
</code>```

I used this video for testing, which can also be downloaded here.
Thanks a lot !

答: From what i can gather from your explanation is, that you have a problem with the so called Field of View. It may look like the camera is zoomed but actually it is not. Look for the FOV settings in your camera try settings like 90 degree.

Body:
I am playing around with a 360 degree video player using SpriteKit, SceneKit and CoreMotion. The player is working so far, but the video is always zoomed-in a bit. It looks like the camera position is not at (0,0,0), but somehow wrong on the Z axis. Unfortunately, I have not found a way to adjust that. To reproduce the behavior just tap the screen, when the video is playing and pinch-zoom-out. This enables camera control with gestures, double tapping returns to camera control with the device.

import UIKit
import SceneKit
import CoreMotion
import SpriteKit
import AVFoundation

class Video360VC: UIViewController {
let motionManager = CMMotionManager()
let cameraNode = SCNNode()
@IBOutlet weak var sceneView: SCNView!

@IBAction func exitBtnClicked(_ sender: Any) {
performSegueToReturnBack()
}

func createSphereNode(material: AnyObject?) -> SCNNode {
    let sphere = SCNSphere(radius: 20.0)
    sphere.firstMaterial!.isDoubleSided = true
    sphere.firstMaterial!.diffuse.contents = material
    let sphereNode = SCNNode(geometry: sphere)
    sphereNode.position = SCNVector3Make(0,0,0)
    sphereNode.rotation = SCNVector4Make(1, 0, 0, Float.pi)
    return sphereNode
}

func configureScene(node sphereNode: SCNNode) {
    // Set the scene
    let scene = SCNScene()
    sceneView.scene = scene
    sceneView.showsStatistics = true
    sceneView.allowsCameraControl = true

    // Camera, ...
    cameraNode.camera = SCNCamera()
    cameraNode.position = SCNVector3Make(0, 0, 0)
    scene.rootNode.addChildNode(sphereNode)
    scene.rootNode.addChildNode(cameraNode)
}

func startCameraTracking() {
    motionManager.deviceMotionUpdateInterval = 1.0 / 60.0
    motionManager.startDeviceMotionUpdates(to: OperationQueue.main) {
        [weak self](data: CMDeviceMotion?, error: Error?) in
        guard let data = data else { return }
        let attitude: CMAttitude = data.attitude

        self?.cameraNode.eulerAngles = SCNVector3Make(-   Float(attitude.roll + Double.pi/2), Float(attitude.yaw), -Float(attitude.pitch))
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    guard let fileURL = Bundle.main.url(forResource: "360Test2", withExtension: "mp4") else {
        print("Video File not found")
        return
    }

    let player = AVPlayer(url: fileURL)
    let videoNode = SKVideoNode(avPlayer: player)
    let size = CGSize(width: 1280, height: 720)
    videoNode.size = size
    videoNode.position = CGPoint(x: size.width/2, y: size.height/2)

    let spriteScene = SKScene(size: size)
    spriteScene.scaleMode = .resizeFill
    spriteScene.addChild(videoNode)

    let sphereNode = createSphereNode(material:spriteScene)
    configureScene(node: sphereNode)
    guard motionManager.isDeviceMotionAvailable else {
        fatalError("Device motion is not available")
    }
    startCameraTracking()
    player.play()
}

override func viewWillAppear(_ animated: Bool) {
    self.sceneView.play(self)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}

I used this video for testing, which can also be downloaded here.
Thanks a lot !


问:
Can a class with all private members be a POD class?
I've heard before that POD types cannot have private data -- but according to the C++0x draft I have the requirement is looser (emphasis mine):

has the same access control (Clause 11) for all non-static data members

which seems to suggest that private data is okay so long as it's all private. I don't have a copy of C++03 though to check...

Would then, WindowsApi::Uuid be a POD class?

```<code>namespace WindowsApi
{
    class Uuid
    {
        union
        {
            ::UUID asUuid; //Win32's UUID struct
            unsigned __int64 asInt64s[2];
            unsigned __int32 asInt32s[4];
        };
    public:
        Uuid() {}
        Uuid(::UUID sourceStructure) : asUuid(sourceStructure) {}
        operator ::UUID() { return asUuid; }
    };
}
</code>```

答:
I've heard before that POD types cannot have private data

In C++03 POD types cannot have private data (see AndreyT's answer).

However the definition of POD has been changed in C++0x (See 9/10).

As per n3225

A POD struct is a class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types).

  ...
  ...

A POD class is a class that is either a POD struct or a POD union.

That means

```<code>struct demo
{
   private:
      int a, b;
};
</code>```

is POD in C++0x because demo is both trivial and standard layout.

The definition of Standard layout is in section 9/7

A standard-layout class is a class that:

has no non-static data members of type non-standard-layout class (or array of such types) or reference,

has no virtual functions (10.3) and no virtual base classes (10.1),

has the same access control (Clause 11) for all non-static data members,

has no non-standard-layout base classes,

either has no non-static data members in the most-derived class and at most one base class with
  non-static data members, or has no base classes with non-static data members, and

has no base classes of the same type as the ﬁrst non-static data member.11

.

Would then, WindowsApi::Uuid be a POD class?

Nopes! WindowsApi::Uuid is neither POD in C++03 nor in C++0x. A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable. WindowsApi::Uuid has a non trivial default constructor.

So this rule got relaxed in C++0x then?

Yes! (Considering Clause 11)

Also check out the FAQ entry on Aggregates and PODs

Body:
I've heard before that POD types cannot have private data -- but according to the C++0x draft I have the requirement is looser (emphasis mine):

has the same access control (Clause 11) for all non-static data members

which seems to suggest that private data is okay so long as it's all private. I don't have a copy of C++03 though to check...

Would then, WindowsApi::Uuid be a POD class?

namespace WindowsApi
{
    class Uuid
    {
        union
        {
            ::UUID asUuid; //Win32's UUID struct
            unsigned __int64 asInt64s[2];
            unsigned __int32 asInt32s[4];
        };
    public:
        Uuid() {}
        Uuid(::UUID sourceStructure) : asUuid(sourceStructure) {}
        operator ::UUID() { return asUuid; }
    };
}

Body:
I've heard before that POD types cannot have private data

In C++03 POD types cannot have private data (see AndreyT's answer).

However the definition of POD has been changed in C++0x (See 9/10).

As per n3225

A POD struct is a class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types).

  ...
  ...

A POD class is a class that is either a POD struct or a POD union.

That means

struct demo
{
   private:
      int a, b;
};

is POD in C++0x because demo is both trivial and standard layout.

The definition of Standard layout is in section 9/7

A standard-layout class is a class that:

has no non-static data members of type non-standard-layout class (or array of such types) or reference,

has no virtual functions (10.3) and no virtual base classes (10.1),

has the same access control (Clause 11) for all non-static data members,

has no non-standard-layout base classes,

either has no non-static data members in the most-derived class and at most one base class with
  non-static data members, or has no base classes with non-static data members, and

has no base classes of the same type as the ﬁrst non-static data member.11

.

Would then, WindowsApi::Uuid be a POD class?

Nopes! WindowsApi::Uuid is neither POD in C++03 nor in C++0x. A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable. WindowsApi::Uuid has a non trivial default constructor.

So this rule got relaxed in C++0x then?

Yes! (Considering Clause 11)

Also check out the FAQ entry on Aggregates and PODs


答:
You can probably merge them as:</p>

```<code>$('#check_standard,#check_express').on('change', function() {
  var selectedId = this.id;
  var getName = selectedId.split('_');
  $(this).is(':checked') ? $('#form_' + getName[1]).show() :
    $('#form_' + getName[1]).hide();
});
</code>```

Title: combine blocks of code to one function

Body:
How can I make one function to do something like this

$('#check_express').is(':checked') ? $('#form_express').show() : $('#form_express').hide();

$('#check_express').on('change', function(){
    $(this).is(':checked') ? $('#form_express').show() :
    $('#form_express').hide();
});

$('#check_standard').is(':checked') ? $('#form_standard').show() : $('#form_standard').hide();

$('#check_standard').on('change', function(){
    $(this).is(':checked') ? $('#form_standard').show() :
    $('#form_standard').hide();
});

Body:
You can probably merge them as:

$('#check_standard,#check_express').on('change', function() {
  var selectedId = this.id;
  var getName = selectedId.split('_');
  $(this).is(':checked') ? $('#form_' + getName[1]).show() :
    $('#form_' + getName[1]).hide();
});


问:
Best approach for hosting multiple applications on AWS with SSL
I have several applications (nodejs & angular) that I am moving to AWS. I have set up my clients using CloudFront. However, I'm not quite sure how to go about setting up my backends on AWS.

Let's say I have five domains a.com, b.com, d.com, d.com, and e.com

These are small applications so I don't necessarily want to have five different EC2 instances. Currently they are all running on a single EC2 instance on different ports.

I'm not sure how to set up https:// routing to all these instances. For example I need to make requests from my clients to https://a.com, https://b.com and so on.

What is the recommended approach to accomplish a set up like this?

答:
One can have different domain on AWS provided these are small applications.
Just simply have different directory root mention the virtual host eg :

```<code><VirtualHost *:80>
    ServerAdmin webmaster@a.com
    DocumentRoot /home/a/public/
    ServerName a.com
    ServerAlias www.a.com
</VirtualHost>
</code>```

Similarly you can have for b,c d and e domain.

Also you can install ssl for each 5 domains.
All you have to do is install SSL and configure the virtual host eg :

```<code><VirtualHost *:443>
  ServerAdmin webmaster@a.com
  DocumentRoot /home/a/public/
  ServerName a.com
  ServerAlias www.a.com
  SSLEngine on
  SSLCertificateFile /etc/httpd/ssl/".crt file name"
  SSLCertificateKeyFile /etc/httpd/ssl/"key file name"
  SSLCertificateChainFile /etc/httpd/ssl/"IntermediateCA_.crt file"
</VirtualHost>
</code>```

If you want always redirect http://a.com to https://a.com
Need to rewrite the rule as follows

```<code>RewriteEngine on
#Redirect everything to https:
Redirect permanent / https://a.com/
RewriteRule ^(.*)$ https://a.com$1 [R=301,L]
</code>```

Similarly for other 4 domains.

Body:
One can have different domain on AWS provided these are small applications.
Just simply have different directory root mention the virtual host eg :

<VirtualHost *:80>
    ServerAdmin webmaster@a.com
    DocumentRoot /home/a/public/
    ServerName a.com
    ServerAlias www.a.com
</VirtualHost>

Similarly you can have for b,c d and e domain.

Also you can install ssl for each 5 domains.
All you have to do is install SSL and configure the virtual host eg :

<VirtualHost *:443>
  ServerAdmin webmaster@a.com
  DocumentRoot /home/a/public/
  ServerName a.com
  ServerAlias www.a.com
  SSLEngine on
  SSLCertificateFile /etc/httpd/ssl/".crt file name"
  SSLCertificateKeyFile /etc/httpd/ssl/"key file name"
  SSLCertificateChainFile /etc/httpd/ssl/"IntermediateCA_.crt file"
</VirtualHost>

If you want always redirect http://a.com to https://a.com
Need to rewrite the rule as follows

RewriteEngine on
#Redirect everything to https:
Redirect permanent / https://a.com/
RewriteRule ^(.*)$ https://a.com$1 [R=301,L]

Similarly for other 4 domains.


问:
How do I programmatically find out the schedule of a delayed mailer job with Resque Mailer and Resque scheduler?
I am trying to display the next time an email is scheduled using any or all of the below arguments as inputs. I'm using resque, resque-scheduler and resque-mailer.

For example, above are the delayed jobs as displayed in the resque web interface. So I'd like to input "game_starting_reminder" and/or 226 and/or "Beat Box" and be able to then display the timestamp as such:

"Next scheduled email: 2017-10-31 at 9:30 pm".

However, when I try to call for the information in the console, the below is the output I receive

I've tried extending the delay_extensions and methods and using the find_delayed_selection method but that doesn't seem to work.
For example this:

```<code>    [18] pry(main)> Resque.find_delayed_selection { |job| job["class"] == QuizMailer}
TypeError: no implicit conversion of String into Integer
</code>```

Or this:

```<code>[32] pry(main)> Resque.find_delayed_selection { {
[32] pry(main)*     "class": "QuizMailer",
[32] pry(main)*     "args": ["game_starting_reminder", [226, "Beat Box"]],
[32] pry(main)*     "queue": "mailer"
[32] pry(main)* }}
=> ["{\"class\":\"QuizMailer\",\"args\":[\"game_starting_reminder\",[226,\"Beat Box\"]],\"queue\":\"mailer\"}",
 "{\"class\":\"QuizMailer\",\"args\":[\"game_ending_reminder\",[226,\"Beat Box\"]],\"queue\":\"mailer\"}"]
</code>```

Any other method I can use here? Or tips.
 Thank you!

答:
Figured it out. The scheduled_at method is the best candidate here for the job.

First step is to add the DelayingExtensions module to the project.  I just added the file from the resque source code on Github to initializers and then in resque.rb added the line:

```<code> #resque.rb
rails_root = ENV['RAILS_ROOT'] || File.dirname(__FILE__) + '/../..'
rails_env = ENV['RAILS_ENV'] || 'development'

resque_config = YAML.load_file(rails_root + '/config/resque.yml')
Resque.redis = resque_config[rails_env]
include DelayingExtensions
</code>```

I modified the scheduled_at method from the github source code slightly because I couldn't get it to work as is and changed the name of the method to scheduled_for_time

```<code>   #delaying_extensions.rb
   def scheduled_for_time(klass, *args)
    args = args[0]
    search = encode(job_to_hash(klass, args))
    redis.smembers("timestamps:#{search}").map do |key|
      key.tr('delayed:', '').to_i
    end
   end
</code>```

In this case, we can do the following in the console:

```<code>    [2] pry(main)> klass =QuizMailer
    => QuizMailer
    [4] pry(main)> args = ["game_starting_reminder", [230, "Beat Box"]]
    => ["game_starting_reminder", [230, "Beat Box"]]
    [5] pry(main)> Resque.scheduled_for_time(QuizMailer, args)
    => [1515081600]
    [6] pry(main)> Time.at(_.first)
     => 2018-01-04 21:30:00 +0530
</code>```

Voila!

Body:
I am trying to display the next time an email is scheduled using any or all of the below arguments as inputs. I'm using resque, resque-scheduler and resque-mailer.

For example, above are the delayed jobs as displayed in the resque web interface. So I'd like to input "game_starting_reminder" and/or 226 and/or "Beat Box" and be able to then display the timestamp as such:

"Next scheduled email: 2017-10-31 at 9:30 pm".

However, when I try to call for the information in the console, the below is the output I receive

I've tried extending the delay_extensions and methods and using the find_delayed_selection method but that doesn't seem to work.
For example this:

    [18] pry(main)> Resque.find_delayed_selection { |job| job["class"] == QuizMailer}
TypeError: no implicit conversion of String into Integer

Or this:

[32] pry(main)> Resque.find_delayed_selection { {
[32] pry(main)*     "class": "QuizMailer",
[32] pry(main)*     "args": ["game_starting_reminder", [226, "Beat Box"]],
[32] pry(main)*     "queue": "mailer"
[32] pry(main)* }}
=> ["{\"class\":\"QuizMailer\",\"args\":[\"game_starting_reminder\",[226,\"Beat Box\"]],\"queue\":\"mailer\"}",
 "{\"class\":\"QuizMailer\",\"args\":[\"game_ending_reminder\",[226,\"Beat Box\"]],\"queue\":\"mailer\"}"]

Any other method I can use here? Or tips.
 Thank you!

Body:
Figured it out. The scheduled_at method is the best candidate here for the job.

First step is to add the DelayingExtensions module to the project.  I just added the file from the resque source code on Github to initializers and then in resque.rb added the line:

 #resque.rb
rails_root = ENV['RAILS_ROOT'] || File.dirname(__FILE__) + '/../..'
rails_env = ENV['RAILS_ENV'] || 'development'

resque_config = YAML.load_file(rails_root + '/config/resque.yml')
Resque.redis = resque_config[rails_env]
include DelayingExtensions

I modified the scheduled_at method from the github source code slightly because I couldn't get it to work as is and changed the name of the method to scheduled_for_time

   #delaying_extensions.rb
   def scheduled_for_time(klass, *args)
    args = args[0]
    search = encode(job_to_hash(klass, args))
    redis.smembers("timestamps:#{search}").map do |key|
      key.tr('delayed:', '').to_i
    end
   end

In this case, we can do the following in the console:

    [2] pry(main)> klass =QuizMailer
    => QuizMailer
    [4] pry(main)> args = ["game_starting_reminder", [230, "Beat Box"]]
    => ["game_starting_reminder", [230, "Beat Box"]]
    [5] pry(main)> Resque.scheduled_for_time(QuizMailer, args)
    => [1515081600]
    [6] pry(main)> Time.at(_.first)
     => 2018-01-04 21:30:00 +0530

Voila!


问:
Searching through a 2D array in python 2.7 if a char is in that position
Hi im trying to search through my array if a particular char is in that position and then printing it to the console.

this is my code so far.

```<code>students = [['Gary','Y'],['Steve','N'],['Tom','Y']]

for i in range (len(students)):
        if students[i,1] == 'Y':
            print (students(i,0))
</code>```

答:
You are not using indexing correctly.
For python you need to use it as follows:</p>

```<code>for i in range (len(students)):
      if students[i][1] == 'Y':
          print (students[i][0])
</code>```

Body:
Hi im trying to search through my array if a particular char is in that position and then printing it to the console.

this is my code so far.

students = [['Gary','Y'],['Steve','N'],['Tom','Y']]

for i in range (len(students)):
        if students[i,1] == 'Y':
            print (students(i,0))

Body:
You are not using indexing correctly.
For python you need to use it as follows:

for i in range (len(students)):
      if students[i][1] == 'Y':
          print (students[i][0])


问:
Override whole class in java/scala
I have a library, already provided, which has two Scala classes:

```<code>class EvaluationFunction (data:DataHolder) {
    def calculate(params:ParamHolder) = {...}
}
</code>```

And

```<code>class Regression {
    def train(data:DataHolder) = {
        ...
        val costFunction = new EvaluationFunction(data)

        //find params to minimize costFunction.calculate(params)
        ....
    }
}
</code>```

I want to make my own regression class, which behaves exactly like the original regression, but uses a different evaluation function. However, the only way I can think of to do that would involve extending Regression and overwriting the whole train method. But it contains pretty much all the logic in the Regression class - I may as well write it from scratch!

Is there a better way? For example, somehow tell my extended regression class to invoke another class every time the original invokes EvaluationFunction?

答:
The code you show would not compile: the data does not have a datatype.

That aside - the structure of the Regression class is strange. It should have the EvaluationFunction as overridable. As it stands it is built into the train method. That is why you need to override (/rewrite) the entire class. It is a problem with the class structure.

Title: Override whole class in java/scala

Body:
I have a library, already provided, which has two Scala classes:

class EvaluationFunction (data:DataHolder) {
    def calculate(params:ParamHolder) = {...}
}

And

class Regression {
    def train(data:DataHolder) = {
        ...
        val costFunction = new EvaluationFunction(data)

        //find params to minimize costFunction.calculate(params)
        ....
    }
}

I want to make my own regression class, which behaves exactly like the original regression, but uses a different evaluation function. However, the only way I can think of to do that would involve extending Regression and overwriting the whole train method. But it contains pretty much all the logic in the Regression class - I may as well write it from scratch!

Is there a better way? For example, somehow tell my extended regression class to invoke another class every time the original invokes EvaluationFunction?


问:
Get first date of current month in java
I am trying to get to and from date where ToDate will have previous date and FromDate will have first date of the current month. For January it would be 1/1/2013 and so on. How to get the first date of the current month correctly? I am not able to do it.

```<code>today.add(Calendar.DAY_OF_MONTH, -1);
java.util.Date previousDay=today.getTime();
ToDate = sdfFile1.format(newjava.sql.Date(previousDay.getTime()));
today.add(Calendar.DATE, 1);
java.util.Date nextDay=today.getTime();
FromDate = sdfFile1.format(new java.sql.Date(nextDay.getTime()));
</code>```

答:
If you also want the time is set to 0 the code is:

```<code>import java.util.*;
import java.text.*;

public class DateCalculations {
  public static void main(String[] args) {

    Calendar aCalendar = Calendar.getInstance();

    aCalendar.set(Calendar.DATE, 1);
    aCalendar.set(Calendar.HOUR_OF_DAY, 0);
    aCalendar.set(Calendar.MINUTE, 0);
    aCalendar.set(Calendar.SECOND, 0);

    Date firstDateOfCurrentMonth = aCalendar.getTime();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zZ");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    String dayFirst = sdf.format(firstDateOfCurrentMonth);
    System.out.println(dayFirst);
  }
}
</code>```

You can check online easily without compiling by using:
http://www.browxy.com/

Title: Get first date of current month in java

Body:
I am trying to get to and from date where ToDate will have previous date and FromDate will have first date of the current month. For January it would be 1/1/2013 and so on. How to get the first date of the current month correctly? I am not able to do it.

today.add(Calendar.DAY_OF_MONTH, -1);
java.util.Date previousDay=today.getTime();
ToDate = sdfFile1.format(newjava.sql.Date(previousDay.getTime()));
today.add(Calendar.DATE, 1);
java.util.Date nextDay=today.getTime();
FromDate = sdfFile1.format(new java.sql.Date(nextDay.getTime()));

Body:
If you also want the time is set to 0 the code is:

import java.util.*;
import java.text.*;

public class DateCalculations {
  public static void main(String[] args) {

    Calendar aCalendar = Calendar.getInstance();

    aCalendar.set(Calendar.DATE, 1);
    aCalendar.set(Calendar.HOUR_OF_DAY, 0);
    aCalendar.set(Calendar.MINUTE, 0);
    aCalendar.set(Calendar.SECOND, 0);

    Date firstDateOfCurrentMonth = aCalendar.getTime();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zZ");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    String dayFirst = sdf.format(firstDateOfCurrentMonth);
    System.out.println(dayFirst);
  }
}

You can check online easily without compiling by using:
http://www.browxy.com/


问:
Why do nullable numbers not preserve identity?
In kotlin nullable values are not preserving identity but equality:

```<code>val a: Int = 10000
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
print(boxedA == anotherBoxedA) // Prints 'true'
</code>```

Why is this different ?

答:
Referential equality means that two references point to the same
  object.

Document, Referential equality is checked by the === operation (and its negated counterpart !==). a === b evaluates to true if and only if a and b point to the same object.

Body:
In kotlin nullable values are not preserving identity but equality:

val a: Int = 10000
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
print(boxedA == anotherBoxedA) // Prints 'true'

Why is this different ?