问:
Queuing URLs and Asynchronous Code
I have the following code that I use with wappalyzer to scrape the technology data of a website.

```<code>const wappalyzer = require('wappalyzer');
var fs = require('fs');

var myArray =[http://www.url1.com, http://www.url2.com ...]   // it's a very
long array of URLs

var dataSlice = myArray.slice(0, 1000);

console.log(dataSlice);
fs.appendFileSync('webData.json', '[', 'utf8');

var done = {};
var count = 0;
for(i = 0; i < dataSlice.length; i++) {
  (function(i){
    wappalyzer.run([dataSlice[i], '--quiet'], function(stdout, stderr) {
      //Keep track of when all urls are done

      if(!done[i]){
        done[i] = true;
        count++;

        if ( stdout ) {
          var arr = stdout.split('\n');
          stdout  = arr.filter(function(elem, pos) {
              return arr.indexOf(elem) == pos;
          });
          stdout = stdout.join('');
          stdout = count >= dataSlice.length ? (stdout + ']') : (stdout +
',');
          fs.appendFileSync('WebData.json', stdout, 'utf8');
        }

      }

      if ( stderr ) {
        process.stderr.write(stderr);
      }
    });
  })(i);
}
</code>```

The problem is I have a very large list of URLs that I run through this loop so I slice the array into smaller sections to do ~1000 at a time however, when I do any more the systemfreezes as it uses quite a bit of CPU, how would I run this code asynchronously and queue up URLs? Also is there a simple NPM package to intall? I've had a look around and haven't found anything easy to work with.

答:
you can do a ring buffer.

the idea is to have an array of pending task, have one loop (in node the loop must be async to not block the engine) which does the job to refill and start jobs, with callbacks you can watch for begin/end of tasks.

beware to not overwrite ring in a callback, as you ll see i always copy it from call to call and write it in sync.

if i m correct, below should do the job.

```<code>// concurrent/async job processing.
function main() {

  var consumer = function(todo, done){ // execute whatever to do.
    console.log("start ", todo.id, todo.duration);
    setTimeout(function(){
      done();
      console.log("done ", todo.id, todo.duration);
    }, todo.duration);
  };

  var id = 0;
  function reader(len) { // a dummy function that provides n new jobs
    var ret = []
    for(i=0;i<len;i++){
      ret.push({
        id: id,
        duration:getRandomInt(250, 1000),
        about: "whatever todo",
        status: "todo"
      });
      id+=1;
    }
    return ret
  };

  var ring = []; // the ring contains the element being processed
  var loop = function(){ // is async
    ring = processor(ring, 10, reader, consumer);
    logger(ring);
    setTimeout(loop, 100); // loop here.
  };loop();

};process.nextTick(main);

function processor(ring, concurrency, reader, consumer){
  ring = ring.filter(notStatus('done')); // remove done jobs
  var delta = concurrency-ring.length;
  if(delta>0) { // refill the ring until it is full
    ring = ring.concat(reader(delta))
  }
  ring.filter(byStatus('todo')).forEach(function(todo){ // select those todo
    todo.status = 'started';
    consumer(todo, function(){
      todo.status = "done";
    })
  })
  return ring
}

function logger(ring){
  console.log("   ring");
  ring.forEach(function(todo){
    console.log("   ", todo.status, todo.id, todo.duration);
  });
}

function byStatus(s){
  return function(todo){return todo.status==s}
}

function notStatus(s){
  return function(todo){return todo.status!=s}
}

// .... still not std ?
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
</code>```

Title: Queuing URLs and Asynchronous Code

Body:
I have the following code that I use with wappalyzer to scrape the technology data of a website.

const wappalyzer = require('wappalyzer');
var fs = require('fs');

var myArray =[http://www.url1.com, http://www.url2.com ...]   // it's a very
long array of URLs

var dataSlice = myArray.slice(0, 1000);

console.log(dataSlice);
fs.appendFileSync('webData.json', '[', 'utf8');

var done = {};
var count = 0;
for(i = 0; i < dataSlice.length; i++) {
  (function(i){
    wappalyzer.run([dataSlice[i], '--quiet'], function(stdout, stderr) {
      //Keep track of when all urls are done

      if(!done[i]){
        done[i] = true;
        count++;

        if ( stdout ) {
          var arr = stdout.split('\n');
          stdout  = arr.filter(function(elem, pos) {
              return arr.indexOf(elem) == pos;
          });
          stdout = stdout.join('');
          stdout = count >= dataSlice.length ? (stdout + ']') : (stdout +
',');
          fs.appendFileSync('WebData.json', stdout, 'utf8');
        }

      }

      if ( stderr ) {
        process.stderr.write(stderr);
      }
    });
  })(i);
}

The problem is I have a very large list of URLs that I run through this loop so I slice the array into smaller sections to do ~1000 at a time however, when I do any more the systemfreezes as it uses quite a bit of CPU, how would I run this code asynchronously and queue up URLs? Also is there a simple NPM package to intall? I've had a look around and haven't found anything easy to work with.

Body:
you can do a ring buffer.

the idea is to have an array of pending task, have one loop (in node the loop must be async to not block the engine) which does the job to refill and start jobs, with callbacks you can watch for begin/end of tasks.

beware to not overwrite ring in a callback, as you ll see i always copy it from call to call and write it in sync.

if i m correct, below should do the job.

// concurrent/async job processing.
function main() {

  var consumer = function(todo, done){ // execute whatever to do.
    console.log("start ", todo.id, todo.duration);
    setTimeout(function(){
      done();
      console.log("done ", todo.id, todo.duration);
    }, todo.duration);
  };

  var id = 0;
  function reader(len) { // a dummy function that provides n new jobs
    var ret = []
    for(i=0;i<len;i++){
      ret.push({
        id: id,
        duration:getRandomInt(250, 1000),
        about: "whatever todo",
        status: "todo"
      });
      id+=1;
    }
    return ret
  };

  var ring = []; // the ring contains the element being processed
  var loop = function(){ // is async
    ring = processor(ring, 10, reader, consumer);
    logger(ring);
    setTimeout(loop, 100); // loop here.
  };loop();

};process.nextTick(main);

function processor(ring, concurrency, reader, consumer){
  ring = ring.filter(notStatus('done')); // remove done jobs
  var delta = concurrency-ring.length;
  if(delta>0) { // refill the ring until it is full
    ring = ring.concat(reader(delta))
  }
  ring.filter(byStatus('todo')).forEach(function(todo){ // select those todo
    todo.status = 'started';
    consumer(todo, function(){
      todo.status = "done";
    })
  })
  return ring
}

function logger(ring){
  console.log("   ring");
  ring.forEach(function(todo){
    console.log("   ", todo.status, todo.id, todo.duration);
  });
}

function byStatus(s){
  return function(todo){return todo.status==s}
}

function notStatus(s){
  return function(todo){return todo.status!=s}
}

// .... still not std ?
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


来源: stackexchange

问:
Lua - calculating if a time is between two time stamps
Given the following examples:

```<code>--Test current     start     end     between
--1    10:00       09:00     12:00   true
--2    01:00       07:34     09:54   false
--3    17:00       16:00     03:00   true
--4    10:00       10:00     15:00   true
--5    10:30       10:00     10:30   true
</code>```

In Lua, how is it best to create a function that I can call:

```<code>BetweenTimes ("10:00", "09:00","12:00")
</code>```

and in this case (Test 1) return true.  The issue I have is will Test case 3.

I can assume that the first time is always before the second time.

I think this might be it:

```<code>local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return os.time{hour = hour, min = min, day = 1, month = 1, year = 1970}
end

local function BetweenTimes(between, start, stop)
   between = parse_time(between)
   start   = parse_time(start)
   stop    = parse_time(stop)

   if stop < start then
      return (start <= between) or (between <= stop)
   else
      return (start <= between) and (between <= stop)
   end
end

print(BetweenTimes("10:00", "09:00", "12:00")) -- true
print(BetweenTimes("15:00", "09:00", "12:00")) -- false
print(BetweenTimes("15:00", "09:00", "01:00")) -- true
print(BetweenTimes("10:00", "10:00", "11:00")) -- true
print(BetweenTimes("11:00", "10:00", "11:00")) -- true
print(BetweenTimes("19:00", "17:00", "03:30")) -- true
print(BetweenTimes("03:00", "04:00", "05:30")) -- false
print(BetweenTimes("03:00", "02:00", "05:30")) -- true
print(BetweenTimes("01:00", "09:00", "02:30")) -- true
</code>```

or even just the following should work to remove os.time():

```<code>local function BetweenTimes(between, start, stop)
   local start   = string.gsub(start,":", "")
   local between = string.gsub(between,":", "")
   local stop    = string.gsub(stop,":", "")

   if stop < start then
      return (start <= between) or (between <= stop)
   else
      return (start <= between) and (between <= stop)
   end
end
</code>```

答:
Why are you even using the date when you only have hours and minutes? Unless you expect to handle any other time units in future, a simple multiplication will suffice.

```<code>local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return min * 60 + hour
end
</code>```

I won't copy BetweenTimes from Henri Menke's answer - it is exactly the same with the only change inside wrapping handling because my parse_time returns minutes, not seconds:

```<code>stop = stop + 24*60
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given the following examples:

--Test current     start     end     between
--1    10:00       09:00     12:00   true
--2    01:00       07:34     09:54   false
--3    17:00       16:00     03:00   true
--4    10:00       10:00     15:00   true
--5    10:30       10:00     10:30   true

In Lua, how is it best to create a function that I can call:

BetweenTimes ("10:00", "09:00","12:00")

and in this case (Test 1) return true.  The issue I have is will Test case 3.

I can assume that the first time is always before the second time.

I think this might be it:

local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return os.time{hour = hour, min = min, day = 1, month = 1, year = 1970}
end

local function BetweenTimes(between, start, stop)
   between = parse_time(between)
   start   = parse_time(start)
   stop    = parse_time(stop)

   if stop < start then
      return (start <= between) or (between <= stop)
   else
      return (start <= between) and (between <= stop)
   end
end

print(BetweenTimes("10:00", "09:00", "12:00")) -- true
print(BetweenTimes("15:00", "09:00", "12:00")) -- false
print(BetweenTimes("15:00", "09:00", "01:00")) -- true
print(BetweenTimes("10:00", "10:00", "11:00")) -- true
print(BetweenTimes("11:00", "10:00", "11:00")) -- true
print(BetweenTimes("19:00", "17:00", "03:30")) -- true
print(BetweenTimes("03:00", "04:00", "05:30")) -- false
print(BetweenTimes("03:00", "02:00", "05:30")) -- true
print(BetweenTimes("01:00", "09:00", "02:30")) -- true

or even just the following should work to remove os.time():

local function BetweenTimes(between, start, stop)
   local start   = string.gsub(start,":", "")
   local between = string.gsub(between,":", "")
   local stop    = string.gsub(stop,":", "")

   if stop < start then
      return (start <= between) or (between <= stop)
   else
      return (start <= between) and (between <= stop)
   end
end

Body:
Why are you even using the date when you only have hours and minutes? Unless you expect to handle any other time units in future, a simple multiplication will suffice.

local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return min * 60 + hour
end

I won't copy BetweenTimes from Henri Menke's answer - it is exactly the same with the only change inside wrapping handling because my parse_time returns minutes, not seconds:

stop = stop + 24*60


问:
What is happening when you assign a pointer to another pointer?
Code:

```<code>int x = 2;
int* pointerone = &x;
int* pointertwo = pointerone;
</code>```

So the address of pointerone is assigned to pointertwo, but is the copy constructor being called and the object that holds the address is copied into the address object of the other pointer, like all the default copy constructors on other types performing a shallow copy. If it is as I expect, how does the copy constructor of a pointer look like?

答:
There are no constructors involved here. In fact this code is pure C code.

```<code>int x = 2;

// pointerone points to the memory address of x
int* pointerone = &x;

// pointertwo points to the same address than pointerone,
// therefore it points also to the memory address of x
int* pointertwo = pointerone;
</code>```

That's all.

And even in C++, pointers don't have constructors, exactly as the int type doesn't have a constructor.

Body:
Code:

int x = 2;
int* pointerone = &x;
int* pointertwo = pointerone;

So the address of pointerone is assigned to pointertwo, but is the copy constructor being called and the object that holds the address is copied into the address object of the other pointer, like all the default copy constructors on other types performing a shallow copy. If it is as I expect, how does the copy constructor of a pointer look like?

Body:
There are no constructors involved here. In fact this code is pure C code.

int x = 2;

// pointerone points to the memory address of x
int* pointerone = &x;

// pointertwo points to the same address than pointerone,
// therefore it points also to the memory address of x
int* pointertwo = pointerone;

That's all.

And even in C++, pointers don't have constructors, exactly as the int type doesn't have a constructor.


问:
are instance reference variables(object) with assigned objects instantly created on the heap?
Let's say we have an instance reference variable assigned to an object.

```<code>public class Player {
     private Object object = new Object();
}
</code>```

whenever I create a new Player instance.

```<code>Player player = new Player();
</code>```

As far as I have learned, might be wrong I'm pretty new to this. The heap allocates memory for the instance primitive variables and stores these in the objects.

If it does the same for the instance reference variable which is assigned to an object, doesn't this instantly create a new instance or does this only occur when calling the reference variable?

答: If I'm understanding your question correctly, instantiating a new Player instance (on the heap) also instantiates a new Object (on the heap), and the Player instance holds a reference to the Object instance. Java doesn't do "lazy" instantiation.</p>

Body:
Let's say we have an instance reference variable assigned to an object.

public class Player {
     private Object object = new Object();
}

whenever I create a new Player instance.

Player player = new Player();

As far as I have learned, might be wrong I'm pretty new to this. The heap allocates memory for the instance primitive variables and stores these in the objects.

If it does the same for the instance reference variable which is assigned to an object, doesn't this instantly create a new instance or does this only occur when calling the reference variable?


问:
Wait Until another function finish
I have a problem. Two function are called from one event almost on the same time. Function1 is doing some asynchronous staff  :

```<code>function1 (callback_Data){
   //some other callbacks here
}

function2 (){

}
</code>```

I want function2 to wait until all callbacks which are in function1 to finish and then to start.

答:
Call function2() at the very end of function1. Please be careful if there are any asyncronous callbacks. In this case call function2 at the end of the last callback.</p>

```<code>function1 (callback_Data) {
  // some logic here

  // async function
  asyncFunction(param1, param2, function() {
    // the logic that is executed, when asyncFunction is completed
    function2();
  });
}

function2() {
  // some other logic
}
</code>```

Title: Wait Until another function finish

Body:
I have a problem. Two function are called from one event almost on the same time. Function1 is doing some asynchronous staff  :

function1 (callback_Data){
   //some other callbacks here
}

function2 (){

}

I want function2 to wait until all callbacks which are in function1 to finish and then to start.

Body:
Call function2() at the very end of function1. Please be careful if there are any asyncronous callbacks. In this case call function2 at the end of the last callback.

function1 (callback_Data) {
  // some logic here

  // async function
  asyncFunction(param1, param2, function() {
    // the logic that is executed, when asyncFunction is completed
    function2();
  });
}

function2() {
  // some other logic
}


问:
Typical network socket timeout
I'm interested to know, what is the typical network socket timeout value, used in production today.

I'm currently using 30 seconds in our Java application, but would like to hear what other using, especially for Internet communications.

Thanks.

答: As a rule of thumb you can use double the expected response time for the transaction. But there is certainly no such thing as a 'typical' timeout.</p>

ContentLicense: CC BY-SA 2.5

Title: Typical network socket timeout


问:
How to use `jsonb_set` on column with null values
I am using Postgres 9.6 and I have a JSONB column in which some rows have NULL value and some have dict values like {"notify": false}.

I want to update the column values with more dictionary key/value pairs.

```<code>UPDATE accounts SET notifications =  jsonb_set(notifications, '{"alerts"}', 'false');
</code>```

Does work for the cases where I already have values like {"notify": false}. The end result becomes as expected {"alerts": false, "notifications": false}.

But the value I'm trying to update us NULL, nothing is updated in the db.

Can you give me any ideas how I can update the NULL values as well, so the end result for them will be values like {"notify": false}. The end result becomes as expected {"alerts": false}

答:
Use coalesce():

```<code>UPDATE accounts
SET notifications =  jsonb_set(coalesce(notifications, '{}'), '{"alerts"}', 'false')
</code>```

or even simpler:

```<code>UPDATE accounts
SET notifications =  coalesce(notifications, '{}') || '{"alerts": false}'
</code>```

Body:
I am using Postgres 9.6 and I have a JSONB column in which some rows have NULL value and some have dict values like {"notify": false}.

I want to update the column values with more dictionary key/value pairs.

UPDATE accounts SET notifications =  jsonb_set(notifications, '{"alerts"}', 'false');

Does work for the cases where I already have values like {"notify": false}. The end result becomes as expected {"alerts": false, "notifications": false}.

But the value I'm trying to update us NULL, nothing is updated in the db.

Can you give me any ideas how I can update the NULL values as well, so the end result for them will be values like {"notify": false}. The end result becomes as expected {"alerts": false}

Body:
Use coalesce():

UPDATE accounts
SET notifications =  jsonb_set(coalesce(notifications, '{}'), '{"alerts"}', 'false')

or even simpler:

UPDATE accounts
SET notifications =  coalesce(notifications, '{}') || '{"alerts": false}'


问:
How do I set up multiple https virtual server blocks with Nginx on Ubuntu 16.04?
I have tried following several on-line tutorials with no avail.
Here are the files I have:

/etc/nginx/sites-available/default:

```<code># HTTP - redirect all traffic to HTTPS
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    return 301 https://$host$request_uri;
}

# HTTPS - proxy all requests to the Node app
server {
    # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name codytpatterson.com;

    # Use the Let's Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/codytpatterson.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/codytpatterson.com/privkey.pem;

    # Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://localhost:5000/;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}
</code>```

/etc/nginx/sites-available/mobile.codytpatterson.com:

```<code># HTTP - redirect all traffic to HTTPS
server {
    listen 80;
    listen [::]:80 ipv6only=on;
    return 301 https://$host$request_uri;
}

# HTTPS - proxy all requests to the Node app
server {
    # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name mobile.codytpatterson.com;

    # Use the Let's Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/mobile.codytpatterson.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mobile.codytpatterson.com/privkey.pem;

    # Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://localhost:6000/;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}
</code>```

Both of these files have symbolic links in /etc/nginx/sites-enabled/. When I run sudo nginx -t I am told that I have duplicate applications attempting to listen to the same port (which I thought would not happen because I only have one server file listed as the default) I feel like there is something I am missing that I don't know. Perhaps it has to do with the proxy? Anybody who is experienced in nginx care to enlighten me? Here is my nginx config file just in case it is also of any use:

/etc/nginx/nginx.conf:

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

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

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}
</code>```

Perhaps also there is a better way to do this if I'm just wanting a subdomain for the time being. But eventually I would like to be able to host multiple websites on this server so it would be helpful to know how to do it the way I'm doing it (with separate files) as well as setting up an additional subdomain in a single file if that is the easier way to accomplish this.

答: I believe the issue is that your redirects for port 80 are missing the server_name config, so they're effectively duplicates. Try adding that and see if it makes a difference.

Body:
I have tried following several on-line tutorials with no avail.
Here are the files I have:

/etc/nginx/sites-available/default:

# HTTP - redirect all traffic to HTTPS
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    return 301 https://$host$request_uri;
}

# HTTPS - proxy all requests to the Node app
server {
    # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name codytpatterson.com;

    # Use the Let's Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/codytpatterson.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/codytpatterson.com/privkey.pem;

    # Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://localhost:5000/;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}

/etc/nginx/sites-available/mobile.codytpatterson.com:

# HTTP - redirect all traffic to HTTPS
server {
    listen 80;
    listen [::]:80 ipv6only=on;
    return 301 https://$host$request_uri;
}

# HTTPS - proxy all requests to the Node app
server {
    # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name mobile.codytpatterson.com;

    # Use the Let's Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/mobile.codytpatterson.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mobile.codytpatterson.com/privkey.pem;

    # Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://localhost:6000/;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}

Both of these files have symbolic links in /etc/nginx/sites-enabled/. When I run sudo nginx -t I am told that I have duplicate applications attempting to listen to the same port (which I thought would not happen because I only have one server file listed as the default) I feel like there is something I am missing that I don't know. Perhaps it has to do with the proxy? Anybody who is experienced in nginx care to enlighten me? Here is my nginx config file just in case it is also of any use:

/etc/nginx/nginx.conf:

user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

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

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

Perhaps also there is a better way to do this if I'm just wanting a subdomain for the time being. But eventually I would like to be able to host multiple websites on this server so it would be helpful to know how to do it the way I'm doing it (with separate files) as well as setting up an additional subdomain in a single file if that is the easier way to accomplish this.


问:
What is the merit of the "function" type (not "pointer to function")
Reading the C++ Standard, i see that there are "function" types and "pointer to function" types:

```<code>typedef int func(int);     // function
typedef int (*pfunc)(int); // pointer to function
typedef func* pfunc;       // same as above
</code>```

I have never seen the function types used outside of examples (or maybe i didn't recognize their usage?). Some examples:

```<code>func increase, decrease;            // declares two functions
int increase(int), decrease(int);   // same as above

int increase(int x) {return x + 1;} // cannot use the typedef when defining functions
int decrease(int x) {return x - 1;} // cannot use the typedef when defining functions

struct mystruct
{
    func add, subtract, multiply;   // declares three member functions
    int member;
};

int mystruct::add(int x) {return x + member;} // cannot use the typedef
int mystruct::subtract(int x) {return x - member;}

int main()
{
    func k; // the syntax is correct but the variable k is useless!
    mystruct myobject;
    myobject.member = 4;

    cout << increase(5) << ' ' << decrease(5) << '\n'; // outputs 6 and 4
    cout << myobject.add(5) << ' ' << myobject.subtract(5) << '\n'; // 9 and 1
}
</code>```

Seeing that the function types support syntax that doesn't appear in C (declaring member functions), i guess they are not just a part of C baggage that C++ has to support for backward compatibility.

So is there any use for function types, other than demonstrating some funky syntax?

答:
boost:function uses that syntax, called "preferred" syntax.

Seems that kind of syntax is not widely used? Comparing to function pointer.

Body:
Reading the C++ Standard, i see that there are "function" types and "pointer to function" types:

typedef int func(int);     // function
typedef int (*pfunc)(int); // pointer to function
typedef func* pfunc;       // same as above

I have never seen the function types used outside of examples (or maybe i didn't recognize their usage?). Some examples:

func increase, decrease;            // declares two functions
int increase(int), decrease(int);   // same as above

int increase(int x) {return x + 1;} // cannot use the typedef when defining functions
int decrease(int x) {return x - 1;} // cannot use the typedef when defining functions

struct mystruct
{
    func add, subtract, multiply;   // declares three member functions
    int member;
};

int mystruct::add(int x) {return x + member;} // cannot use the typedef
int mystruct::subtract(int x) {return x - member;}

int main()
{
    func k; // the syntax is correct but the variable k is useless!
    mystruct myobject;
    myobject.member = 4;

    cout << increase(5) << ' ' << decrease(5) << '\n'; // outputs 6 and 4
    cout << myobject.add(5) << ' ' << myobject.subtract(5) << '\n'; // 9 and 1
}

Seeing that the function types support syntax that doesn't appear in C (declaring member functions), i guess they are not just a part of C baggage that C++ has to support for backward compatibility.

So is there any use for function types, other than demonstrating some funky syntax?


答:
Promise States

A promise can be in one of 3 states:

Pending  the promise’s outcome hasn’t yet been determined, because the asynchronous operation that will produce its result hasn’t completed yet.
Fulfilled - the asynchronous operation has completed, and the promise has a value.
Rejected - the asynchronous operation failed, and the promise will never be fulfilled. In the rejected state, a promise has a reason that indicates why the operation failed.

```<code>var greetingPromise = sayHello();
greetingPromise.then(function (greeting) {
   console.log(greeting);    // 'hello world’
 });
</code>```

This block can help you to execute the first function 1 then after it will goes to function 2.

Title: Wait Until another function finish

Body:
Promise States

A promise can be in one of 3 states:

Pending  the promise’s outcome hasn’t yet been determined, because the asynchronous operation that will produce its result hasn’t completed yet.
Fulfilled - the asynchronous operation has completed, and the promise has a value.
Rejected - the asynchronous operation failed, and the promise will never be fulfilled. In the rejected state, a promise has a reason that indicates why the operation failed.

var greetingPromise = sayHello();
greetingPromise.then(function (greeting) {
   console.log(greeting);    // 'hello world’
 });

This block can help you to execute the first function 1 then after it will goes to function 2.


问:
How to prevent matching two routes with react-router v4?
I have the following two routes: /items and /items/buy.

Each route corresponds to a Tab in a single view. Both routes are rendered with an exact prop, but still, two tabs are being marked as active when navigating to /items/buy.

I already tried using withRouter, but I noticed changing /items to /items/sell fixes the problem, but I don't wanna have that route.

I understand rrv4 is matching the first part of my route /items and the other route too /items/buy, but I think that shouldn't be happening if I'm using exact. Any clues on why this is happening?

Ahh I forgot to say I am already using a Switch.

Thanks for your help!

答: The problem was I was wrapping a NavItem with a LinkContainer and the LinkContainer did not have an exact prop. Adding the exact prop solved the issue!</p>


问:
Cutting a text file into multiple parts in Emacs
I am using the GNU Emacs 23 editor. I have this huge text file containing about 10,000 lines which I want to chop into multiple files. Using the mouse to select the required text to paste in another file is the really painful.  Also this is prone to errors too.

If I want to divide the text file according to the line numbers into say 4 file where
first file:lines 1-2500
second file:lines 2500-5000
third file :lines 5000-7500
fourth file: lines: 7500-10000

how do I do this? At  the very least, is there any efficient way to copy large regions of the file just by specifying line numbers

答:
The following should work:</p>

```<code>M-<           (go to start of file)
C-space       (set mark at current cursor position)
ESC 2500 down (go down 2500 lines)
C-w           (delete between mark and cursor, and put it in cut buffer)
...           (open new file, using your favourite method)
C-Y           (paste contents of cut buffer)
</code>```

Body:
The following should work:

M-<           (go to start of file)
C-space       (set mark at current cursor position)
ESC 2500 down (go down 2500 lines)
C-w           (delete between mark and cursor, and put it in cut buffer)
...           (open new file, using your favourite method)
C-Y           (paste contents of cut buffer)


问:
CSS styling in GTKSharp
I'm converting a C/GTK+ GUI application to C# using GTKSharp in VS2017. I've installed this package https://www.nuget.org/packages/GtkSharp/3.1.3 via NuGet.

Here's how I load up the CSS (the application uses a Glade file to define the interface):

```<code>    static void Main(string[] args)
    {
        new Program(args);
    }

    public Program(string[] args)
    {
        Application.Init();

        builder = new Builder();
        Gtk.CssProvider provider = new CssProvider();
        builder.AddFromFile("interface.glade");
        provider.LoadFromPath("style.css");
        builder.Autoconnect(this);

        Gtk.Window window = (Gtk.Window)builder.GetObject("start");
        Gtk.StyleContext.AddProviderForScreen(Gdk.Screen.Default, provider, 800); // couldn't find the equivalent to GTK_STYLE_PROVIDER_PRIORITY_USER so I set the priority to a random number
        window.Show();

        Application.Run();
    }
</code>```

The selector names seem to be different from GTK+. For example,

```<code>    window {
     ...
    }
</code>```

works in C/GTK+ but not in C#, whereas

```<code>    GtkWindow {
     ...
    }
</code>```

works in C# but not in C/GTK+. Then there are a few widgets I can't seem to style at all. For example,

```<code>    button {
     ...
    }
</code>```

works in GTK+ but

```<code>    GtkButton {
     ...
    }
</code>```

does not work in C#. I couldn't find any documentation regarding how GTK# handles CSS styling so I thought it'd be the same as GTK+. Any pointers?

答:
It was a version issue.

Version 3.22 of GTK# detects the GtkButton selector correctly. I was using GTK 3.14's native libraries. There is one unlisted NuGet package that provides win32 libraries for the 3.22 version. Strangely enough, that version detects the old "button", "window"... instead of the "GtkButton", "GtkWindow"... tags.

Title: CSS styling in GTKSharp

Body:
I'm converting a C/GTK+ GUI application to C# using GTKSharp in VS2017. I've installed this package https://www.nuget.org/packages/GtkSharp/3.1.3 via NuGet.

Here's how I load up the CSS (the application uses a Glade file to define the interface):

    static void Main(string[] args)
    {
        new Program(args);
    }

    public Program(string[] args)
    {
        Application.Init();

        builder = new Builder();
        Gtk.CssProvider provider = new CssProvider();
        builder.AddFromFile("interface.glade");
        provider.LoadFromPath("style.css");
        builder.Autoconnect(this);

        Gtk.Window window = (Gtk.Window)builder.GetObject("start");
        Gtk.StyleContext.AddProviderForScreen(Gdk.Screen.Default, provider, 800); // couldn't find the equivalent to GTK_STYLE_PROVIDER_PRIORITY_USER so I set the priority to a random number
        window.Show();

        Application.Run();
    }

The selector names seem to be different from GTK+. For example,

    window {
     ...
    }

works in C/GTK+ but not in C#, whereas

    GtkWindow {
     ...
    }

works in C# but not in C/GTK+. Then there are a few widgets I can't seem to style at all. For example,

    button {
     ...
    }

works in GTK+ but

    GtkButton {
     ...
    }

does not work in C#. I couldn't find any documentation regarding how GTK# handles CSS styling so I thought it'd be the same as GTK+. Any pointers?


问:
Angular - Async call
In my app, I'm calling a service :

```<code>getEnv(): Promise<string>{
        return this.http.get(this.url + 'Home/GetEnv')
        .toPromise()
        .then(response => response.json().environment)
        .catch(this.handleError);
    }
</code>```

to return to a component

```<code>getEnvironnement(): string {

      this.appService.getEnv().then(url => {
          this.url = url;
      })

      return this.url;
  }
</code>```

The problem is the following. When I'm calling MyComponent.getEnvironnement(), the result is undefined, because the call to my service is async, I know all this stuff. But.. Is there a way to wait before returning this.url ?

Thanks !

答:
You can use async-await to write your code in a sequential style, while still retaining the benefits of non-blocking async HTTP requests:</p>

```<code>async getEnvironnement(): Promise<string> {
  this.url = await this.appService.getEnv();
  return this.url;
}
</code>```

Title: Angular - Async call

Body:
In my app, I'm calling a service :

getEnv(): Promise<string>{
        return this.http.get(this.url + 'Home/GetEnv')
        .toPromise()
        .then(response => response.json().environment)
        .catch(this.handleError);
    }

to return to a component

getEnvironnement(): string {

      this.appService.getEnv().then(url => {
          this.url = url;
      })

      return this.url;
  }

The problem is the following. When I'm calling MyComponent.getEnvironnement(), the result is undefined, because the call to my service is async, I know all this stuff. But.. Is there a way to wait before returning this.url ?

Thanks !

Body:
You can use async-await to write your code in a sequential style, while still retaining the benefits of non-blocking async HTTP requests:

async getEnvironnement(): Promise<string> {
  this.url = await this.appService.getEnv();
  return this.url;
}


问:
get all fields in object that have given word and transform all values of these fields
I have an object. like this, for example

{
    startDate: 2141242141,
    adress: '',
    endDate: 2141242141,
    billings: {
        startBillingDate: 2142421421421,
        endBillingDate: 2142421421421
    }
    amount: 100
}```

I need to get all fields those contain word "Date" (or "date") and convert them all into string date format.

Who can help please.

答:
I would create a function to iterate object's properties recursively, and later I would call the whole function to produce the whole transformations:

function forEachProperty(obj, actionFn) {
  Object.keys(obj).forEach(
    property => {
      actionFn(obj, property);

      if (typeof obj[property] == "object") {
        forEachProperty(obj[property], actionFn);
      }
    }
  );
}

var obj = {
  startDate: 2141242141,
  adress: '',
  endDate: 2141242141,
  billings: {
    startBillingDate: 2142421421421,
    endBillingDate: 2142421421421
  },
  amount: 100
};

forEachProperty(obj, (obj, property) => {
  if (property.toLowerCase().includes("date")) {
    obj[property] = new Date(obj[property]);
  }
});

console.log(JSON.stringify(obj));```

Body:
I have an object. like this, for example

{
    startDate: 2141242141,
    adress: '',
    endDate: 2141242141,
    billings: {
        startBillingDate: 2142421421421,
        endBillingDate: 2142421421421
    }
    amount: 100
}

I need to get all fields those contain word "Date" (or "date") and convert them all into string date format.

Who can help please.


问:
Python function scope
I have a question about the scope in python functions. I've included an example that demonstrates the issue I am having.

fun0 redefines the first entry in varible c's list. This change is reflected outside of fun0, even when I don't return any values from fun0.

fun1 redefines the variable c entirely, but the change isn't reflected outside of fun1. Similarly, fun2 redefines c, and the change isn't reflected outside of fun2.

My question is, why does fun0 modify val3 in the main function, while fun1 and fun2 don't modify val4 and val7, respectively?

```<code>def fun0(a, b, c):
    c[0] = a[0] + b[0]
    return

def fun1(a, b, c):
    c = a[0] + b[0]
    return

def fun2(a, b, c):
    c = a + b
    return

def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print val3

    val4 = []
    fun1(val1, val2, val4)
    print val4

    val5 = 1
    val6 = 1
    val7 = 0
    fun2(val5, val6, val7)
    print val7
    return

if __name__=='__main__':
    main()
</code>```

答: It has to do with the way lists and variables are stored. You can modify a list within a function because they are mutable objects. However, if you do c = a[0] + b[0], you are creating a local variable within fun1 and fun2, which stays within the function scope.

Title: Python function scope

Body:
I have a question about the scope in python functions. I've included an example that demonstrates the issue I am having.

fun0 redefines the first entry in varible c's list. This change is reflected outside of fun0, even when I don't return any values from fun0.

fun1 redefines the variable c entirely, but the change isn't reflected outside of fun1. Similarly, fun2 redefines c, and the change isn't reflected outside of fun2.

My question is, why does fun0 modify val3 in the main function, while fun1 and fun2 don't modify val4 and val7, respectively?

def fun0(a, b, c):
    c[0] = a[0] + b[0]
    return

def fun1(a, b, c):
    c = a[0] + b[0]
    return

def fun2(a, b, c):
    c = a + b
    return

def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print val3

    val4 = []
    fun1(val1, val2, val4)
    print val4

    val5 = 1
    val6 = 1
    val7 = 0
    fun2(val5, val6, val7)
    print val7
    return

if __name__=='__main__':
    main()


问:
Collapse view if can't fit it's intrinsic size in AutoLayout
I have UILabel and UIButton inside view which can have different size, and I want label to be hidden completely if it can't fit all the content within current frame using only AutoLayout. So basically I want it to follow it's intrinsic size, and if it shrink, it should shrink straight to zero without any middle width. Desired example:

Instead, I'm having it shrinking and trying to display as much as possible:

Is it possible to do only using AutoLayout? If not, why?

I tried to add zero-width constraint on label and set it's priority to be less than compression resistance of the label, but this does not work. I thought that once Autolayout engine broke intristic size rule, mine zero-width will be followed, but it seems I'm missing something.

EDIT: I would accept to embed label in some UIView subclass that can check intristic sizes of subviews and do layout in code, but I'm searching for most clean solution in general.

You can check out xib source in this gist

答:
I know you solved your issue, but just to provide a little color on Auto Layout: I had the same requirement to "collapse" a view that can't meet it's intrinsic content size and tried the same zero-width constraint technique. The problem with that technique is described in this portion of the Auto Layout documentation:

After solving for the required constraints, Auto Layout tries to solve all the optional constraints in priority order from highest to lowest. If it cannot solve for an optional constraint, it tries to come as close as possible to the desired result, and then moves on to the next constraint.

Apparently Auto Layout would rather get close to satisfying a constraint than satisfy a lower priority constraint. That's a bit weird to me because if I want a width to be >= 100 then it's not clear that 90 is "better" than 80. That said, I'm sure doing it this way results in more intuitive behavior in the vast majority of cases.

Unfortunately, this makes it impossible to use lower priority constraints as "fall-back" constraints for cases where higher priority constraints can't be satisfied. I suppose Apple's view is that the only purpose of lower priority constraints is to make the layout more specific when the higher priority constraints result in an under constrained layout.


问:
AWS public IPv4 in userdata script
I need to dynamically discover the ip4v address of my instance (during userdata script execution and use it to replace some XML. I've tried the following but it doesn't work. Presumably because networking isn't available at the time we the instance runs the userdata script?

Also, to add complexity, assume this instance has no external internet access (so other solutions suggesting curl http://checkip.amazonaws.com/ won't work).

sudo sed -i -e "s,<listenaddress address=\",<listenaddress address=\"$(wget -qO- http://instance-data/latest/meta-data/public-ipv4),g" /tmp/my.config.xml

I'm using the default Amazon AMI (Amazon Linux AMI 2017.03.1 (HVM), SSD Volume Type - ami-ed100689)

Any ideas?

Edit: Full userdata script

```<code>#!/bin/bash
# This script starts a extra small service with 512MB heap.
# USE ONLY FOR DEMOS
sudo useradd myuser
sudo groupadd myuser
sudo usermod -a -G myuser myuser
sudo yum update -y
sudo yum install java-1.8.0-openjdk wget -y
sudo wget https://files.mysite.com/downloads/service/whatever.jar -P /opt
sudo /usr/bin/java8 -jar /opt/whatever.jar -b 64 -t /opt/software
sudo chown -R myuser:myuser /opt/software
sudo cp /opt/software/init.d/serviceFile /etc/init.d

# Other SED commands on /etc/init.d/serviceFile which ARE working

sudo chkconfig --add /etc/init.d/serviceFile

# Start service to generate XML config file
sudo service serviceFile start

# Stop service to release file locks
sudo service serviceFile stop

# Lookup IP and do replacement <-- Problem here
sudo sed -i -e "s,<listenaddress address=\",<listenaddress address=\"$(wget -qO- http://instance-data/latest/meta-data/public-ipv4),g" /opt/software/conf/collector.config.xml

# Restart service
sudo service serviceFile start
</code>```

答:
```<code>curl http://169.254.169.254/latest/meta-data/public-ipv4
</code>```

You can fetch a bunch of data about current instance from this ip

Title: AWS public IPv4 in userdata script

Body:
I need to dynamically discover the ip4v address of my instance (during userdata script execution and use it to replace some XML. I've tried the following but it doesn't work. Presumably because networking isn't available at the time we the instance runs the userdata script?

Also, to add complexity, assume this instance has no external internet access (so other solutions suggesting curl http://checkip.amazonaws.com/ won't work).

sudo sed -i -e "s,<listenaddress address=\",<listenaddress address=\"$(wget -qO- http://instance-data/latest/meta-data/public-ipv4),g" /tmp/my.config.xml

I'm using the default Amazon AMI (Amazon Linux AMI 2017.03.1 (HVM), SSD Volume Type - ami-ed100689)

Any ideas?

Edit: Full userdata script

#!/bin/bash
# This script starts a extra small service with 512MB heap.
# USE ONLY FOR DEMOS
sudo useradd myuser
sudo groupadd myuser
sudo usermod -a -G myuser myuser
sudo yum update -y
sudo yum install java-1.8.0-openjdk wget -y
sudo wget https://files.mysite.com/downloads/service/whatever.jar -P /opt
sudo /usr/bin/java8 -jar /opt/whatever.jar -b 64 -t /opt/software
sudo chown -R myuser:myuser /opt/software
sudo cp /opt/software/init.d/serviceFile /etc/init.d

# Other SED commands on /etc/init.d/serviceFile which ARE working

sudo chkconfig --add /etc/init.d/serviceFile

# Start service to generate XML config file
sudo service serviceFile start

# Stop service to release file locks
sudo service serviceFile stop

# Lookup IP and do replacement <-- Problem here
sudo sed -i -e "s,<listenaddress address=\",<listenaddress address=\"$(wget -qO- http://instance-data/latest/meta-data/public-ipv4),g" /opt/software/conf/collector.config.xml

# Restart service
sudo service serviceFile start

Body:
curl http://169.254.169.254/latest/meta-data/public-ipv4

You can fetch a bunch of data about current instance from this ip


问:
vector<string> or vector<char *>?
Question:

What is the difference between:

vector<string> and vector<char *>?

How would I pass a value of data type: string to a function, that specifically accepts:

const char *?

For instance:

```<code> vector<string> args(argv, argv + argc);

 vector<string>::iterator i;

 void foo (const char *); //*i
</code>```

I understand using vector<char *>: I'll have to copy the data, as well as the pointer

Edit:

Thanks for input!

答: char* is actually a pointer to a value of type char, which defines what can and can't be done with that value. You could make an int* number and number references the pointer to the block of memory where this value is stored, and will assume it is an int and will lock in that type for that memory block. But you can store a char 'C' in that memory block but it will throw a compilation error because it says you cant perform those int functions on that char.

OwnerDisplayName: Atklin

Title: vector<string> or vector<char *>?

Body:
Question:

What is the difference between:

vector<string> and vector<char *>?

How would I pass a value of data type: string to a function, that specifically accepts:

const char *?

For instance:

 vector<string> args(argv, argv + argc);

 vector<string>::iterator i;

 void foo (const char *); //*i

I understand using vector<char *>: I'll have to copy the data, as well as the pointer

Edit:

Thanks for input!

LastEditorDisplayName: Atklin


问:
How to setup webpack to copy files in VS Code
I have started a new personal project in VS Code.  I am new to VS Code, and webpack.

I created a new angular project by running the following commands:

```<code>npm install -g @angular/cli
ng new CyclingApp
</code>```

This resulted in the following file structure:

I have read that the node_modules should never be referenced by for instance, a script tag to include the minified .js files.

I would like to take the minified files out of node_modules and place it into a public folder, for instance, ./scripts.

At the moment, when I want to run my app, I use the following command ng serve --open.

When I run this, I can see that webpack is active, and is doing some stuff (Will need to go read up on this more).

Where does it get this build commands from?  I would like to go and set my 'copying commands' there as well, but I do not see any webpack.config.js file?

答:
You don't need to copy minified files out node_modules as webpack will automatically do this for you. webpack is not a task runner like gulp or grunt but a asset bundler.

Firstly have a quick read on ES6 modules then look at how webpack works.

In very simplified way this is what webpack does;

You define a configuration file in which you specify a main file of your app. Webpack will read this file and look for any import or require statements that import modules. If it does find any then it will bundle these into one file. For each module included it will also look for more import statements.

Body:
I have started a new personal project in VS Code.  I am new to VS Code, and webpack.

I created a new angular project by running the following commands:

npm install -g @angular/cli
ng new CyclingApp

This resulted in the following file structure:

I have read that the node_modules should never be referenced by for instance, a script tag to include the minified .js files.

I would like to take the minified files out of node_modules and place it into a public folder, for instance, ./scripts.

At the moment, when I want to run my app, I use the following command ng serve --open.

When I run this, I can see that webpack is active, and is doing some stuff (Will need to go read up on this more).

Where does it get this build commands from?  I would like to go and set my 'copying commands' there as well, but I do not see any webpack.config.js file?


问:
Protractor-CucumberJS - Tagged scenarios - Browser Launched for Scenarios not Tagged
We have a Protractor-CucumberJS framework using BDD feature files and need to create a suite of sanity tests by tagging the relevant scenarios as '@sanity' in feature files and run only the scenarios with this tag.

With this setup, Protractor launches the browser for each feature file one by one, checks if it contains the '@sanity' tag and closes the browser if tag not found and so on.

This will take up a lot of time as there are close to 200 feature files and hence we want the the browser to launch only if the feature file contains the required tag and not otherwise.

Is there a way to achieve that.

Config file -

```<code>exports.config = {
    seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
    framework: 'custom',
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    specs: [../features/*.feature]
    cucumberOpts: {
        require: [
            '../step-definitions/**/*_Steps.js',
            'generateJsonReport.js'
        ],
        format: 'pretty',
        tags: ['@sanity'],
    },

    multiCapabilities: [{
        browserName: 'chrome',
        shardTestFiles: true,
    }
    ],

    onPrepare: function () {
        browser.driver.manage().window().setSize(1600, 800);
    }
 };
</code>```

答: Use tags:'@sanity', in Conf file, This will call only Sanity features</p>

Body:
We have a Protractor-CucumberJS framework using BDD feature files and need to create a suite of sanity tests by tagging the relevant scenarios as '@sanity' in feature files and run only the scenarios with this tag.

With this setup, Protractor launches the browser for each feature file one by one, checks if it contains the '@sanity' tag and closes the browser if tag not found and so on.

This will take up a lot of time as there are close to 200 feature files and hence we want the the browser to launch only if the feature file contains the required tag and not otherwise.

Is there a way to achieve that.

Config file -

exports.config = {
    seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
    framework: 'custom',
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    specs: [../features/*.feature]
    cucumberOpts: {
        require: [
            '../step-definitions/**/*_Steps.js',
            'generateJsonReport.js'
        ],
        format: 'pretty',
        tags: ['@sanity'],
    },

    multiCapabilities: [{
        browserName: 'chrome',
        shardTestFiles: true,
    }
    ],

    onPrepare: function () {
        browser.driver.manage().window().setSize(1600, 800);
    }
 };


问:
SQL - Showing time passed since specific record created (new column)
I have create some code that allows me to show every record that I have in my data after a specific subsymptom

```<code>SELECT
ID,
Received,
Closed,
Subsymptom,
DATEDIFF(HOUR, received, COALESCE(closed, GETDATE())) AS 'HoursOpen'
FROM
   vw_UserView_OpenAndClosed A
WHERE closed >
(SELECT  MAX(closed)
FROM
    vw_UserView_OpenAndClosed SUB
WHERE
    Subsymptom = 'INSTALL'
    AND received >= '2017-06-01'
    AND SUB.name = A.name)
</code>```

The data looks like this

```<code>ID      received    closed      Subsymptom            HoursOpen
1306438 2017-06-20  2017-06-21  ISSUES                19
1305393 2017-06-18  2017-06-19  REQUEST               12
1299203 2017-06-05  2017-06-05  REQUEST               0
1299415 2017-06-05  2017-06-06  SPECIFIC FAILURE      2
</code>```

What I want to be able to do is create a new column that tells me how much time has passed since the original subsymptom named 'INSTALL' was raised.

ID may have gaps and I will have more than one 'Name'

I have tried a Select Max(closed) Join but I cant get it to work at all and I think I am on the totally wrong track and have some mind fuzz.

Example Data

```<code>ID      Received    Closed     Subsymptom       Name
1306438 2017-06-20  2017-06-21 ISSUES           BROOM
1299203 2017-06-05  2017-06-05 REQUEST          BROOM
1305393 2017-06-18  2017-06-19 REQUEST          CHIVE
1299415 2017-06-06  2017-06-06 SPECIFIC FAILURE BROOM
1299222 2017-06-05  2017-06-05 ISSUES           BROOM
1299112 2017-06-05  2017-06-05 CONTACTLESS      BROOM
1279168 2017-06-01  2017-06-03 INSTALL          BROOM
1287965 2017-06-10  2017-06-10 INSTALL          CHIVE
</code>```

Results Desired

```<code>ID      Received    Closed     Subsymptom       Name     HoursOpen  Days Received since Install Closed
1306438 2017-06-20  2017-06-21 ISSUES           BROOM    19         17
1299203 2017-06-05  2017-06-05 REQUEST          BROOM    0          2
1305393 2017-06-18  2017-06-19 REQUEST          CHIVE    12         21
1299415 2017-06-06  2017-06-06 SPECIFIC FAILURE BROOM    2          3
1299222 2017-06-05  2017-06-05 ISSUES           BROOM    0          2
1299112 2017-06-05  2017-06-05 ISSUES           BROOM    0          2
</code>```

Days received since install closed - calculates the amount of days from the INSTALL close date to the RECEIVED date.

(later this will be graphed to show that after an INSTALL new records were received on Day 0, 1, 2, 3 etc)

答:
EDIT:  Thank you for clarifying with your comments and adding the requested sample data.  It was a breeze once I had that.  So, in the future, please make sure to add it when posting your question to ensure the fastest response!

Here is the code:

```<code>DECLARE @Table TABLE (ID bigint, Received DATETIME, Closed DATETIME, Subsymptom varchar(50), [Name] varchar(50))
DECLARE @Now DateTime = GETDATE()

INSERT INTO @Table
VALUES
(1306438 , '2017-06-20', '2017-06-21', 'ISSUES', 'BROOM'),
(1299203 , '2017-06-05', '2017-06-05', 'REQUEST', 'BROOM'),
(1305393 , '2017-06-18', '2017-06-19', 'REQUEST', 'CHIVE'),
(1299415 , '2017-06-06', '2017-06-06', 'SPECIFIC FAILURE', 'BROOM'),
(1299222 , '2017-06-05', '2017-06-05', 'ISSUES', 'BROOM'),
(1299112, '2017-06-05', '2017-06-05', 'CONTACTLESS', 'BROOM'),
(1279168 , '2017-06-01', '2017-06-03', 'INSTALL', 'BROOM'),
(1287965 , '2017-06-10', '2017-06-10', 'INSTALL', 'CHIVE')

SELECT  T.ID,
        T.Received,
        T.Closed,
        T.Subsymptom,
        T.[Name],
        DATEDIFF(HH, T.Received, COALESCE(T.Closed, @Now)) AS 'HoursOpen',
        DATEDIFF(DD, T2.Closed, T.Received) AS [Days Received since Install Closed]
FROM @Table T
JOIN @Table T2
    ON T.[Name] = T2.[Name]
    AND T2.Subsymptom = 'INSTALL'
WHERE T.Closed > T2.Closed
</code>```

Here are the results:

```<code>(6 row(s) affected)
ID                   Received                Closed                  Subsymptom                                         Name                                               HoursOpen   Days Received since Install Closed
-------------------- ----------------------- ----------------------- -------------------------------------------------- -------------------------------------------------- ----------- ----------------------------------
1306438              2017-06-20 00:00:00.000 2017-06-21 00:00:00.000 ISSUES                                             BROOM                                              24          17
1299203              2017-06-05 00:00:00.000 2017-06-05 00:00:00.000 REQUEST                                            BROOM                                              0           2
1305393              2017-06-18 00:00:00.000 2017-06-19 00:00:00.000 REQUEST                                            CHIVE                                              24          8
1299415              2017-06-06 00:00:00.000 2017-06-06 00:00:00.000 SPECIFIC FAILURE                                   BROOM                                              0           3
1299222              2017-06-05 00:00:00.000 2017-06-05 00:00:00.000 ISSUES                                             BROOM                                              0           2
1299112              2017-06-05 00:00:00.000 2017-06-05 00:00:00.000 CONTACTLESS                                        BROOM                                              0           2

(6 row(s) affected)
</code>```

What you're guaranteeing is that there will only be ONE instance of an 'INSTALL' Subsymptom for each Name.  If that is the case, this query will always work.  The reason my results are different than yours is because you only provided dates (not DateTimes), so the calculations will be slightly off.  But, basically, you're just joining each record to its original install - grabbing that original record's closed time - and comparing it to the received time of the current record.  Very simple - and straightforward.

Please let me know if this isn't what you're looking for.

Body:
I have create some code that allows me to show every record that I have in my data after a specific subsymptom

SELECT
ID,
Received,
Closed,
Subsymptom,
DATEDIFF(HOUR, received, COALESCE(closed, GETDATE())) AS 'HoursOpen'
FROM
   vw_UserView_OpenAndClosed A
WHERE closed >
(SELECT  MAX(closed)
FROM
    vw_UserView_OpenAndClosed SUB
WHERE
    Subsymptom = 'INSTALL'
    AND received >= '2017-06-01'
    AND SUB.name = A.name)

The data looks like this

ID      received    closed      Subsymptom            HoursOpen
1306438 2017-06-20  2017-06-21  ISSUES                19
1305393 2017-06-18  2017-06-19  REQUEST               12
1299203 2017-06-05  2017-06-05  REQUEST               0
1299415 2017-06-05  2017-06-06  SPECIFIC FAILURE      2

What I want to be able to do is create a new column that tells me how much time has passed since the original subsymptom named 'INSTALL' was raised.

ID may have gaps and I will have more than one 'Name'

I have tried a Select Max(closed) Join but I cant get it to work at all and I think I am on the totally wrong track and have some mind fuzz.

Example Data

ID      Received    Closed     Subsymptom       Name
1306438 2017-06-20  2017-06-21 ISSUES           BROOM
1299203 2017-06-05  2017-06-05 REQUEST          BROOM
1305393 2017-06-18  2017-06-19 REQUEST          CHIVE
1299415 2017-06-06  2017-06-06 SPECIFIC FAILURE BROOM
1299222 2017-06-05  2017-06-05 ISSUES           BROOM
1299112 2017-06-05  2017-06-05 CONTACTLESS      BROOM
1279168 2017-06-01  2017-06-03 INSTALL          BROOM
1287965 2017-06-10  2017-06-10 INSTALL          CHIVE

Results Desired

ID      Received    Closed     Subsymptom       Name     HoursOpen  Days Received since Install Closed
1306438 2017-06-20  2017-06-21 ISSUES           BROOM    19         17
1299203 2017-06-05  2017-06-05 REQUEST          BROOM    0          2
1305393 2017-06-18  2017-06-19 REQUEST          CHIVE    12         21
1299415 2017-06-06  2017-06-06 SPECIFIC FAILURE BROOM    2          3
1299222 2017-06-05  2017-06-05 ISSUES           BROOM    0          2
1299112 2017-06-05  2017-06-05 ISSUES           BROOM    0          2

Days received since install closed - calculates the amount of days from the INSTALL close date to the RECEIVED date.

(later this will be graphed to show that after an INSTALL new records were received on Day 0, 1, 2, 3 etc)

Body:
EDIT:  Thank you for clarifying with your comments and adding the requested sample data.  It was a breeze once I had that.  So, in the future, please make sure to add it when posting your question to ensure the fastest response!

Here is the code:

DECLARE @Table TABLE (ID bigint, Received DATETIME, Closed DATETIME, Subsymptom varchar(50), [Name] varchar(50))
DECLARE @Now DateTime = GETDATE()

INSERT INTO @Table
VALUES
(1306438 , '2017-06-20', '2017-06-21', 'ISSUES', 'BROOM'),
(1299203 , '2017-06-05', '2017-06-05', 'REQUEST', 'BROOM'),
(1305393 , '2017-06-18', '2017-06-19', 'REQUEST', 'CHIVE'),
(1299415 , '2017-06-06', '2017-06-06', 'SPECIFIC FAILURE', 'BROOM'),
(1299222 , '2017-06-05', '2017-06-05', 'ISSUES', 'BROOM'),
(1299112, '2017-06-05', '2017-06-05', 'CONTACTLESS', 'BROOM'),
(1279168 , '2017-06-01', '2017-06-03', 'INSTALL', 'BROOM'),
(1287965 , '2017-06-10', '2017-06-10', 'INSTALL', 'CHIVE')

SELECT  T.ID,
        T.Received,
        T.Closed,
        T.Subsymptom,
        T.[Name],
        DATEDIFF(HH, T.Received, COALESCE(T.Closed, @Now)) AS 'HoursOpen',
        DATEDIFF(DD, T2.Closed, T.Received) AS [Days Received since Install Closed]
FROM @Table T
JOIN @Table T2
    ON T.[Name] = T2.[Name]
    AND T2.Subsymptom = 'INSTALL'
WHERE T.Closed > T2.Closed

Here are the results:

(6 row(s) affected)
ID                   Received                Closed                  Subsymptom                                         Name                                               HoursOpen   Days Received since Install Closed
-------------------- ----------------------- ----------------------- -------------------------------------------------- -------------------------------------------------- ----------- ----------------------------------
1306438              2017-06-20 00:00:00.000 2017-06-21 00:00:00.000 ISSUES                                             BROOM                                              24          17
1299203              2017-06-05 00:00:00.000 2017-06-05 00:00:00.000 REQUEST                                            BROOM                                              0           2
1305393              2017-06-18 00:00:00.000 2017-06-19 00:00:00.000 REQUEST                                            CHIVE                                              24          8
1299415              2017-06-06 00:00:00.000 2017-06-06 00:00:00.000 SPECIFIC FAILURE                                   BROOM                                              0           3
1299222              2017-06-05 00:00:00.000 2017-06-05 00:00:00.000 ISSUES                                             BROOM                                              0           2
1299112              2017-06-05 00:00:00.000 2017-06-05 00:00:00.000 CONTACTLESS                                        BROOM                                              0           2

(6 row(s) affected)

What you're guaranteeing is that there will only be ONE instance of an 'INSTALL' Subsymptom for each Name.  If that is the case, this query will always work.  The reason my results are different than yours is because you only provided dates (not DateTimes), so the calculations will be slightly off.  But, basically, you're just joining each record to its original install - grabbing that original record's closed time - and comparing it to the received time of the current record.  Very simple - and straightforward.

Please let me know if this isn't what you're looking for.


问:
sqlite select only first row with unique cell in column
I need to select from sqlite table based on column "categ" first row with unique name.
Here is what I have:

```<code>|id     |val    |categ
|1      |any1   |categ1
|2      |any2   |categ1
|3      |any3   |categ2
|4      |any4   |categ2
|5      |any5   |categ2
|6      |any6   |categ3
|7      |any7   |categ3
|8      |any8   |categ4
|9      |any9   |categ4
|10     |any10  |categ4
</code>```

And here is what I need as result:

```<code>|id     |val    |categ
|1      |any1   |categ1
|3      |any3   |categ2
|6      |any6   |categ3
|8      |any8   |categ4
</code>```

First row are column names. And filter should be done by column "categ".
I need to get as results 1 row from each categ.
The name of categs are just as example, in real table the "categ" names are person names (Example: John, Mary etc)

Any suggestion?

答:
You can use GROUP BY to get one row per category. In SQLite, you can use MIN() to control which row in a group to return:</p>

```<code>SELECT min(id) AS id, val, categ
FROM MyTable
GROUP BY categ;
</code>```

Body:
I need to select from sqlite table based on column "categ" first row with unique name.
Here is what I have:

|id     |val    |categ
|1      |any1   |categ1
|2      |any2   |categ1
|3      |any3   |categ2
|4      |any4   |categ2
|5      |any5   |categ2
|6      |any6   |categ3
|7      |any7   |categ3
|8      |any8   |categ4
|9      |any9   |categ4
|10     |any10  |categ4

And here is what I need as result:

|id     |val    |categ
|1      |any1   |categ1
|3      |any3   |categ2
|6      |any6   |categ3
|8      |any8   |categ4

First row are column names. And filter should be done by column "categ".
I need to get as results 1 row from each categ.
The name of categs are just as example, in real table the "categ" names are person names (Example: John, Mary etc)

Any suggestion?

Body:
You can use GROUP BY to get one row per category. In SQLite, you can use MIN() to control which row in a group to return:

SELECT min(id) AS id, val, categ
FROM MyTable
GROUP BY categ;


问:
Oracle SQL to Get output like that using cross tabulation
I've 2 tables named as emp & emp_history having records like that-

emp table-

```<code>emp_ID   ename
e001     abc
e002     pqr
e003     xyz
e004     lmn
</code>```

emp_history table-

```<code>sid    from_emp     to_emp
01      e001        e002
02      e002        e003
03      e003        e004
04      e004        e004
</code>```

Want to get output ename instead of emp_ID in emp_history table like that-

```<code>sid    from_emp     to_emp
01      abc         pqr
02      pqr         xyz
03      xyz         lmn
04      lmn         lmn
</code>```

答:
join the emp table twice to get those names.

```<code>select eh.sid,efrom.ename,eto.ename
from emp_history eh
join emp efrom on efrom.emp_id=eh.from_id
join emp eto on eto.emp_id=eh.to_date
</code>```

Body:
I've 2 tables named as emp & emp_history having records like that-

emp table-

emp_ID   ename
e001     abc
e002     pqr
e003     xyz
e004     lmn

emp_history table-

sid    from_emp     to_emp
01      e001        e002
02      e002        e003
03      e003        e004
04      e004        e004

Want to get output ename instead of emp_ID in emp_history table like that-

sid    from_emp     to_emp
01      abc         pqr
02      pqr         xyz
03      xyz         lmn
04      lmn         lmn

Body:
join the emp table twice to get those names.

select eh.sid,efrom.ename,eto.ename
from emp_history eh
join emp efrom on efrom.emp_id=eh.from_id
join emp eto on eto.emp_id=eh.to_date


问:
object-oriented shell for linux?
Is there anything similar to Microsoft Powershell (an object-oriented shell built on the .NET framework) for Linux (possibly built on Java, GObject, or its own object type/nothing)?

edit: especially if similar to bash or powershell or cmd etc. syntax (=''standard'' shell syntax)

答:
NodeJS can do that, in fact it's one of the samples included in the download. Use it interactively, or (probably more usefully) write shell scripts in JavaScript.

For example:

```<code>#!/usr/local/bin/node

var sys  = require('sys'),
    exec = require('child_process').exec;

// Run `ls`:
exec('ls -lh /usr', function(error, output, erroutput) {
    sys.print('output:    ' + output);
    sys.print('erroutput: ' + erroutput);
});
</code>```

...but that's just the high-level interface that buffers all the output for you, etc. You can get a lot more down and dirty than that if you like.

NodeJS takes asynchronicity as the normal state of affairs, and so if you want a "traditional" shell script, you may find it's not a good match as it doesn't (as of this writing, as far as I know) offer a synchronous version of exec. So an ad hoc series of serial statements becomes an exercise in callbacks:

```<code>exec('first_command', function(error) {
    if (error != null) {
        exec('second_command', function(error) {
            if (error != null) {
                // ....
            }
        });
    }
});
</code>```

...but of course, you can create a function that handles that for you and takes (say) an array of sequential statements to execute (and then install it as a module via Node's module sysstem). So for instance:

```<code>#!/usr/local/bin/node
var sys  = require('sys'),
    exec = require('child_process').exec;

execSeries([
    'ls -ld /usr',
    'foobar',
    'ls -ld /etc'
], {echo: true}, function(results) {
    sys.print("Done\n");
});

// ===> This would be in a module, not in the script itself <===
function execSeries(series, options, callback) {
    var index = 0,
        results = [];

    // Make 'options' optional
    if (!callback && typeof options === "function") {
        callback = options;
        options = undefined;
    }

    // Default options
    options = options || {};

    // Go
    callNext();

    function callNext() {
        if (index >= series.length) {
            // Done
            callback(results);
        }
        else {
            // Call the next one
            exec(series[index++], function(error, stdout, stderr) {
                // Record result
                results.push({error: error, stdout: stdout, stderr: stderr});

                // Echo?
                if (options.echo) {
                    if (error == null) {
                        sys.print(stdout);
                    }
                    else {
                        sys.print("Error: " + error + "\n");
                    }
                }

                // Stop on error?
                if (options.breakOnError && error != null) {
                    // Yes, and there was an error; stop
                    callback(results);
                }
                else {
                    // No, continue
                    callNext();
                }
            });
        }
    }
}
</code>```

Title: object-oriented shell for linux?

Body:
NodeJS can do that, in fact it's one of the samples included in the download. Use it interactively, or (probably more usefully) write shell scripts in JavaScript.

For example:

#!/usr/local/bin/node

var sys  = require('sys'),
    exec = require('child_process').exec;

// Run `ls`:
exec('ls -lh /usr', function(error, output, erroutput) {
    sys.print('output:    ' + output);
    sys.print('erroutput: ' + erroutput);
});

...but that's just the high-level interface that buffers all the output for you, etc. You can get a lot more down and dirty than that if you like.

NodeJS takes asynchronicity as the normal state of affairs, and so if you want a "traditional" shell script, you may find it's not a good match as it doesn't (as of this writing, as far as I know) offer a synchronous version of exec. So an ad hoc series of serial statements becomes an exercise in callbacks:

exec('first_command', function(error) {
    if (error != null) {
        exec('second_command', function(error) {
            if (error != null) {
                // ....
            }
        });
    }
});

...but of course, you can create a function that handles that for you and takes (say) an array of sequential statements to execute (and then install it as a module via Node's module sysstem). So for instance:

#!/usr/local/bin/node
var sys  = require('sys'),
    exec = require('child_process').exec;

execSeries([
    'ls -ld /usr',
    'foobar',
    'ls -ld /etc'
], {echo: true}, function(results) {
    sys.print("Done\n");
});

// ===> This would be in a module, not in the script itself <===
function execSeries(series, options, callback) {
    var index = 0,
        results = [];

    // Make 'options' optional
    if (!callback && typeof options === "function") {
        callback = options;
        options = undefined;
    }

    // Default options
    options = options || {};

    // Go
    callNext();

    function callNext() {
        if (index >= series.length) {
            // Done
            callback(results);
        }
        else {
            // Call the next one
            exec(series[index++], function(error, stdout, stderr) {
                // Record result
                results.push({error: error, stdout: stdout, stderr: stderr});

                // Echo?
                if (options.echo) {
                    if (error == null) {
                        sys.print(stdout);
                    }
                    else {
                        sys.print("Error: " + error + "\n");
                    }
                }

                // Stop on error?
                if (options.breakOnError && error != null) {
                    // Yes, and there was an error; stop
                    callback(results);
                }
                else {
                    // No, continue
                    callNext();
                }
            });
        }
    }
}


问:
C# Webclient returning error 404
I'm using below script to retrieve HTML from an URL.

```<code>string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower();
                using (WebClient client = new WebClient())
                {
                      string htmlCode = client.DownloadString(webURL);
                }
</code>```

The variable word can be any word. In case there is no WIKI page for the "word" be retrieved the code is ending in error with code 404, while retrievng the URL with a browser opens a WIKI page, saying there is no page for this item yet.

What I want is that the code always gets the HTML, also when the WIKI page says there is no info yet. I do not want to avoid the error 404 with a try and catch.

Does anyone has an idea why this is not working with a Webclient?

答:
try this. You can catch the 404 error content in a try catch block.</p>

```<code>        var word = Console.ReadLine();
        string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower();
        using (WebClient client = new WebClient() {  })
        {
            try
            {

                string htmlCode = client.DownloadString(webURL);

            }
            catch (WebException exception)
            {
                string responseText=string.Empty;

                var responseStream = exception.Response?.GetResponseStream();

                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        responseText = reader.ReadToEnd();
                    }
                }

                Console.WriteLine(responseText);
            }
        }

        Console.ReadLine();
</code>```

Title: C# Webclient returning error 404

Body:
I'm using below script to retrieve HTML from an URL.

string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower();
                using (WebClient client = new WebClient())
                {
                      string htmlCode = client.DownloadString(webURL);
                }

The variable word can be any word. In case there is no WIKI page for the "word" be retrieved the code is ending in error with code 404, while retrievng the URL with a browser opens a WIKI page, saying there is no page for this item yet.

What I want is that the code always gets the HTML, also when the WIKI page says there is no info yet. I do not want to avoid the error 404 with a try and catch.

Does anyone has an idea why this is not working with a Webclient?

Body:
try this. You can catch the 404 error content in a try catch block.

        var word = Console.ReadLine();
        string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower();
        using (WebClient client = new WebClient() {  })
        {
            try
            {

                string htmlCode = client.DownloadString(webURL);

            }
            catch (WebException exception)
            {
                string responseText=string.Empty;

                var responseStream = exception.Response?.GetResponseStream();

                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        responseText = reader.ReadToEnd();
                    }
                }

                Console.WriteLine(responseText);
            }
        }

        Console.ReadLine();


问:
Await all Tasks in the list, and after that update the list base on task result
I want to run all tasks with WhenAll (not one by one).
But after that I need to update list (LastReport property) base on result.

I think I have solution but I would like to check if there is better way.

Idea is to:

Run all tasks

Remember relation between configuration and task

Update configuration

My solution is:

```<code>var lastReportAllTasks = new List<Task<Dictionary<string, string>>>();
var configurationTaskRelation = new Dictionary<int, Task<Dictionary<string, string>>>();
foreach (var configuration in MachineConfigurations)
{
    var task = machineService.GetReports(configuration);
    lastReportAllTasks.Add(task);
    configurationTaskRelation.Add(configuration.Id, task);
}

await Task.WhenAll(lastReportAllTasks);
foreach (var configuration in MachineConfigurations)
{
    var lastReportTask = configurationTaskRelation[configuration.Id];
    configuration.LastReport = await lastReportTask;
}
</code>```

答:
The Select function can be asynchronous itself. You can await the report and return both the configuration and result in the same result object (anonymous type or tuple, whatever you prefer) :

```<code>var tasks=MachineConfigurations.Select(async conf=>{
                       var report= await machineService.GetReports(conf);
                       return new {conf,report});
var results=await Task.WhenAll(tasks);
foreach(var pair in results)
{
    pair.conf.LastReport=pair.report;
}
</code>```

EDIT - Loops and error handling

As Servy suggested, Task.WhenAll can be ommited and awaiting can be moved inside the loop :

```<code>foreach(var task in tasks)
{
    var pair=await task;
    pair.conf.LastReport=pair.report;
}
</code>```

The tasks will still execute concurrently. In case of exception though, some configuration objects will be modified and some not.

In general, this would be an ugly situation, requiring extra exception handling code to clean up the modified objects. Exception handling is a lot easier when modifications are done on-the-side and finalized/applied when the happy path completes. That's one reason why updating the Configuration objects inside the Select() requires careful consideration.

In this particular case though it may be better to "skip" the failed reports, possibly move them to an error queue and reprocess them at a later time. It may be better to have partial results than no results at all, as long as this behaviour is expected:

```<code>foreach(var task in tasks)
{
    try
    {
        var pair=await task;
        pair.conf.LastReport=pair.report;
    }
    catch(Exception exc)
    {
        //Make sure the error is logged
        Log.Error(exc);
        ErrorQueue.Enqueue(new ProcessingError(conf,ex);
    }
}
//Handle errors after the loop
</code>```

EDIT 2 - Dataflow

For completeness, I do have several thousand ticket reports to generate each day, and each GDS call (the service through which every travel agency sells tickets) takes considerable time. I can't run all requests at the same time - I start getting server serialization errors if I try more than 10 concurrent requests. I can't retry everything either.

In this case I used TPL DataFlow combined with some Railway oriented programming tricks. An ActionBlock with a DOP of 8 processes the ticket requests. The results are wrapped in a Success class and sent to the next block. Failed requests and exceptions are wrapped in a Failure class and sent to another block. Both classes inherit from IFlowEnvelope which has a Successful flag. Yes, that's F# Discriminated Union envy.

This is combined with some retry logic for timeouts etc.

In pseudocode the pipeline looks like this :

```<code>var reportingBlock=new TransformBlock<Ticket,IFlowEnvelope<TicketReport>(reportFunc,dopOptions);
var happyBlock = new ActionBlock<IFlowEnvelope<TicketReport>>(storeToDb);
var errorBlock = new ActionBlock<IFlowEnvelope<TicketReport>>(logError);

reportingBlock.LinkTo(happyBlock,linkOptions,msg=>msg.Success);
reportingBlock.LinkTo(errorBlock,linkOptions,msg=>!msg.Success);

foreach(var ticket in tickets)
{
    reportingBlock.Post(ticket);
}
</code>```

reportFunc catches any exceptions and wraps them as Failure<T> objects:

```<code>async Task<IFlowEnvelope<Ticket,TicketReport>> reportFunc(Ticket ticket)
{
    try
    {
        //Do the heavy processing
        return new Success<TicketReport>(report);
    }
    catch(Exception exc)
    {
        //Construct an error message, msg
        return new Failure<TicketReport>(report,msg);
    }
}
</code>```

The real pipeline includes steps that parse daily reports and individual tickets. Each call to the GDS takes 1-6 seconds so the complexity of the pipeline is justified.

Body:
I want to run all tasks with WhenAll (not one by one).
But after that I need to update list (LastReport property) base on result.

I think I have solution but I would like to check if there is better way.

Idea is to:

Run all tasks

Remember relation between configuration and task

Update configuration

My solution is:

var lastReportAllTasks = new List<Task<Dictionary<string, string>>>();
var configurationTaskRelation = new Dictionary<int, Task<Dictionary<string, string>>>();
foreach (var configuration in MachineConfigurations)
{
    var task = machineService.GetReports(configuration);
    lastReportAllTasks.Add(task);
    configurationTaskRelation.Add(configuration.Id, task);
}

await Task.WhenAll(lastReportAllTasks);
foreach (var configuration in MachineConfigurations)
{
    var lastReportTask = configurationTaskRelation[configuration.Id];
    configuration.LastReport = await lastReportTask;
}

Body:
The Select function can be asynchronous itself. You can await the report and return both the configuration and result in the same result object (anonymous type or tuple, whatever you prefer) :

var tasks=MachineConfigurations.Select(async conf=>{
                       var report= await machineService.GetReports(conf);
                       return new {conf,report});
var results=await Task.WhenAll(tasks);
foreach(var pair in results)
{
    pair.conf.LastReport=pair.report;
}

EDIT - Loops and error handling

As Servy suggested, Task.WhenAll can be ommited and awaiting can be moved inside the loop :

foreach(var task in tasks)
{
    var pair=await task;
    pair.conf.LastReport=pair.report;
}

The tasks will still execute concurrently. In case of exception though, some configuration objects will be modified and some not.

In general, this would be an ugly situation, requiring extra exception handling code to clean up the modified objects. Exception handling is a lot easier when modifications are done on-the-side and finalized/applied when the happy path completes. That's one reason why updating the Configuration objects inside the Select() requires careful consideration.

In this particular case though it may be better to "skip" the failed reports, possibly move them to an error queue and reprocess them at a later time. It may be better to have partial results than no results at all, as long as this behaviour is expected:

foreach(var task in tasks)
{
    try
    {
        var pair=await task;
        pair.conf.LastReport=pair.report;
    }
    catch(Exception exc)
    {
        //Make sure the error is logged
        Log.Error(exc);
        ErrorQueue.Enqueue(new ProcessingError(conf,ex);
    }
}
//Handle errors after the loop

EDIT 2 - Dataflow

For completeness, I do have several thousand ticket reports to generate each day, and each GDS call (the service through which every travel agency sells tickets) takes considerable time. I can't run all requests at the same time - I start getting server serialization errors if I try more than 10 concurrent requests. I can't retry everything either.

In this case I used TPL DataFlow combined with some Railway oriented programming tricks. An ActionBlock with a DOP of 8 processes the ticket requests. The results are wrapped in a Success class and sent to the next block. Failed requests and exceptions are wrapped in a Failure class and sent to another block. Both classes inherit from IFlowEnvelope which has a Successful flag. Yes, that's F# Discriminated Union envy.

This is combined with some retry logic for timeouts etc.

In pseudocode the pipeline looks like this :

var reportingBlock=new TransformBlock<Ticket,IFlowEnvelope<TicketReport>(reportFunc,dopOptions);
var happyBlock = new ActionBlock<IFlowEnvelope<TicketReport>>(storeToDb);
var errorBlock = new ActionBlock<IFlowEnvelope<TicketReport>>(logError);

reportingBlock.LinkTo(happyBlock,linkOptions,msg=>msg.Success);
reportingBlock.LinkTo(errorBlock,linkOptions,msg=>!msg.Success);

foreach(var ticket in tickets)
{
    reportingBlock.Post(ticket);
}

reportFunc catches any exceptions and wraps them as Failure<T> objects:

async Task<IFlowEnvelope<Ticket,TicketReport>> reportFunc(Ticket ticket)
{
    try
    {
        //Do the heavy processing
        return new Success<TicketReport>(report);
    }
    catch(Exception exc)
    {
        //Construct an error message, msg
        return new Failure<TicketReport>(report,msg);
    }
}

The real pipeline includes steps that parse daily reports and individual tickets. Each call to the GDS takes 1-6 seconds so the complexity of the pipeline is justified.


问:
How can I make Web API serialize DateTime in any object into number of milliseconds since 1970?
In my ASP.NET web service I need all my dates to be serialized to JSON as numbers which represent a number of milliseconds passed since 1970 please. I'm using Newtonsoft.Json serializer. What do I need to do to set it up this way?

UPDATE:
the available documentation (http://www.newtonsoft.com/json/help/html/DatesInJSON.htm) only mentions serializing a single object with custom settings, what i am looking for is the default serialization settings that would govern serialization of any object

答:
here is what worked:</p>

```<code>public class MyConverter: JsonConverter
{
    public override bool CanConvert(Type type)
    {
        return (type == typeof(DateTime) || type == typeof(DateTime?));
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return new NotSupportedException("An attempt to read a date using a write-only converter from DateTime -> number of milliseconds since 1970.");
    }

    static readonly long ticksTo1970 = new DateTime(1970, 1, 1).Ticks;

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is DateTime)
        {
            var date = (DateTime)value;
            var unixDateSpan = new TimeSpan(date.Ticks - ticksTo1970);
            var milliseconds = (long)unixDateSpan.TotalMilliseconds;
            writer.WriteValue(milliseconds);
        }
        else
        {
            throw new NotSupportedException("A value of unexpected type where a DateTime value is expected.");
        }
    }
}

public class BaseApiController : ApiController
{
    [NonAction]
    protected JsonResult<T> MyJson<T>(T data)
    {
        var result = this.Json(data);
        result.SerializerSettings.Converters.Insert(0, new MyConverter());
        return result;
    }
}
</code>```

Body:
here is what worked:

public class MyConverter: JsonConverter
{
    public override bool CanConvert(Type type)
    {
        return (type == typeof(DateTime) || type == typeof(DateTime?));
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return new NotSupportedException("An attempt to read a date using a write-only converter from DateTime -> number of milliseconds since 1970.");
    }

    static readonly long ticksTo1970 = new DateTime(1970, 1, 1).Ticks;

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is DateTime)
        {
            var date = (DateTime)value;
            var unixDateSpan = new TimeSpan(date.Ticks - ticksTo1970);
            var milliseconds = (long)unixDateSpan.TotalMilliseconds;
            writer.WriteValue(milliseconds);
        }
        else
        {
            throw new NotSupportedException("A value of unexpected type where a DateTime value is expected.");
        }
    }
}

public class BaseApiController : ApiController
{
    [NonAction]
    protected JsonResult<T> MyJson<T>(T data)
    {
        var result = this.Json(data);
        result.SerializerSettings.Converters.Insert(0, new MyConverter());
        return result;
    }
}


问:
Wait Until another function finish
I have a problem. Two function are called from one event almost on the same time. Function1 is doing some asynchronous staff  :

```<code>function1 (callback_Data){
   //some other callbacks here
}

function2 (){

}
</code>```

I want function2 to wait until all callbacks which are in function1 to finish and then to start.

答:
If something is executed asynchronously in function1 then furnction 2 will not be blocked until they finished, becaused they are scheduled to be execute.

You can initiate a promise, and pass function2 in then and when all executions are finished from function1 you can resolved that promise.

Title: Wait Until another function finish

Body:
I have a problem. Two function are called from one event almost on the same time. Function1 is doing some asynchronous staff  :

function1 (callback_Data){
   //some other callbacks here
}

function2 (){

}

I want function2 to wait until all callbacks which are in function1 to finish and then to start.


问:
How to select rows where date is greater than the date in another row?
I have a table with customer cards. A customer can have several cards. For every customer card there is one row. If a customer has several cards, there are several rows. There are  two different card types A and B. For every card the last_used date is stored.

I want to check if there are customers with both customer cards of type A and B, where the last_used date of card B is younger then the last_used date of card A.

This is my table CUSTOMER_CARDS.

```<code>card_id | customer_id | card_type | last_used
----------------------------------------------
      1 |          c1 |         A | 2017-07-07
      2 |          c1 |         B | 2016-04-01
      3 |          c2 |         A | 2017-06-04
      4 |          c2 |         B | 2017-07-03
      5 |          c3 |         A | 2016-02-23
      6 |          c3 |         B | 2017-04-17
</code>```

I need a select statement which selects the customer_id of customer c2, who has a card of type B which is younger then his cards of type A. How do I achieve this?

答:
```<code>select d1.cusid,d1.cardtyp,d1.lstusd
from democat d1
join democat d2 on d1.cusid = d2.cusid
where d1.lstusd < d2.lstusd and d1.cardtyp = 'B'
</code>```

Body:
I have a table with customer cards. A customer can have several cards. For every customer card there is one row. If a customer has several cards, there are several rows. There are  two different card types A and B. For every card the last_used date is stored.

I want to check if there are customers with both customer cards of type A and B, where the last_used date of card B is younger then the last_used date of card A.

This is my table CUSTOMER_CARDS.

card_id | customer_id | card_type | last_used
----------------------------------------------
      1 |          c1 |         A | 2017-07-07
      2 |          c1 |         B | 2016-04-01
      3 |          c2 |         A | 2017-06-04
      4 |          c2 |         B | 2017-07-03
      5 |          c3 |         A | 2016-02-23
      6 |          c3 |         B | 2017-04-17

I need a select statement which selects the customer_id of customer c2, who has a card of type B which is younger then his cards of type A. How do I achieve this?