问:
when call router.post method from url get error 404 not found in express.js
I have got a problem with Express, I am trying to use the app.post() function but it's not working and I don't know why...

Even though I have included the bodyParser()...

It returns 404 page not found error

```<code>var express = require('express');

var MongoClient = require('mongodb').MongoClient;

var router = express.Router();

router.post("/hello",(req, res) => {
        res.send('POST CALL');
    });

/* GET home page. */
router.get('/', function(req, res, next) {
    MongoClient.connect('mongodb://localhost:27017/nicky', function (err, client) {
        if (err) throw err

        var db = client.db('nicky')

        db.collection('student').find().toArray(function (err, result) {
            if (err) throw err
            res.send(JSON.stringify(result));
        })
    })
});
module.exports = router;
</code>```

GET is working properly, but POST is not.

答:
Maybe you haven't required and initialized body-parser!
Just confirm once if you have included this:</p>

```<code>  const bodyParser = require('body-parser');
  // support parsing of application/json type post data
  app.use(bodyParser.json());

  //support parsing of application/x-www-form-urlencoded post data
  app.use(bodyParser.urlencoded({ extended: true }));
</code>```

Body:
I have got a problem with Express, I am trying to use the app.post() function but it's not working and I don't know why...

Even though I have included the bodyParser()...

It returns 404 page not found error

var express = require('express');

var MongoClient = require('mongodb').MongoClient;

var router = express.Router();

router.post("/hello",(req, res) => {
        res.send('POST CALL');
    });

/* GET home page. */
router.get('/', function(req, res, next) {
    MongoClient.connect('mongodb://localhost:27017/nicky', function (err, client) {
        if (err) throw err

        var db = client.db('nicky')

        db.collection('student').find().toArray(function (err, result) {
            if (err) throw err
            res.send(JSON.stringify(result));
        })
    })
});
module.exports = router;

GET is working properly, but POST is not.

Body:
Maybe you haven't required and initialized body-parser!
Just confirm once if you have included this:

  const bodyParser = require('body-parser');
  // support parsing of application/json type post data
  app.use(bodyParser.json());

  //support parsing of application/x-www-form-urlencoded post data
  app.use(bodyParser.urlencoded({ extended: true }));


来源: stackexchange

问:
Does not direct to page in Microsoft Edge due to selenium.WebDriverException: Unable to parse remote response: Unknown error
I initiated web driver and try to connect a URL and it returns an exception
What happens is: Open the web browser but does not direct to given Url and print error on the console log.

My code is below:

```<code>Webdriver driver  = new EdgeDriver();
driver.get("https://learn.microsoft.com/en-us/welcome-to-docs");
</code>```

Error log:

org.openqa.selenium.WebDriverException: Unable to parse remote response: Unknown error

at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:115)

at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:74)

at  org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)

I enabled developer mode

I already installed WebDriver using below command in (C:\WINDOWS\system32>):
DISM.exe /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0

I use the below versions:

selenium version: '3.141.59'

Browser: Microsoft Edge, Version 80.0.361.50 (Official Build)
(64-bit)

os build: 18362.535

Windows Edition: 10 version 1903

Any Idea on this?

答:
DISM.exe /Online /Add-Capability
  /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0

Using the above command will install the Microsoft WebDriver for Microsoft Edge Legacy versions 18, it is not available for the Microsoft Edge Version 80.0.361.50 (Official Build) (64-bit).

You could download the related Microsoft Edge WebDriver from Here, based on the Edge version number to download the WebDriver.

Edit:

Try to use the EdgeOptions to set the webdriver path, code as below:

```<code>using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Remote;

        // EdgeOptions() requires using OpenQA.Selenium.Edge
        // Construct EdgeOptions with is_legacy = false
        EdgeOptions edgeOptions = new EdgeOptions(false);
        edgeOptions.BinaryLocation = @"C:\Program Files (x86)\Microsoft\Edge Beta\Application\msedge.exe";
        var msedgedriverDir = @"<download webdriver folder such as:D:\MicrosoftEdgeDriver\edgedriver_win64>";
        var msedgedriverExe = @"msedgedriver.exe";

        // Construct EdgeDriverService with is_legacy = false too
        var service = EdgeDriverService.CreateDefaultService(msedgedriverDir, msedgedriverExe, false);
        service.EnableVerboseLogging = true;

        var driver = new EdgeDriver(service, edgeOptions);

        driver.Navigate().GoToUrl("https://bing.com");
        Thread.Sleep(2000);

        driver.Close();
</code>```

More detail information about using Chromium version Edge WebDriver, please check this link:

WebDriver (Chromium)

ContentLicense: CC BY-SA 4.0

Body:
I initiated web driver and try to connect a URL and it returns an exception
What happens is: Open the web browser but does not direct to given Url and print error on the console log.

My code is below:

Webdriver driver  = new EdgeDriver();
driver.get("https://learn.microsoft.com/en-us/welcome-to-docs");

Error log:

org.openqa.selenium.WebDriverException: Unable to parse remote response: Unknown error

at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:115)

at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:74)

at  org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)

I enabled developer mode

I already installed WebDriver using below command in (C:\WINDOWS\system32>):
DISM.exe /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0

I use the below versions:

selenium version: '3.141.59'

Browser: Microsoft Edge, Version 80.0.361.50 (Official Build)
(64-bit)

os build: 18362.535

Windows Edition: 10 version 1903

Any Idea on this?

Body:
DISM.exe /Online /Add-Capability
  /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0

Using the above command will install the Microsoft WebDriver for Microsoft Edge Legacy versions 18, it is not available for the Microsoft Edge Version 80.0.361.50 (Official Build) (64-bit).

You could download the related Microsoft Edge WebDriver from Here, based on the Edge version number to download the WebDriver.

Edit:

Try to use the EdgeOptions to set the webdriver path, code as below:

using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Remote;

        // EdgeOptions() requires using OpenQA.Selenium.Edge
        // Construct EdgeOptions with is_legacy = false
        EdgeOptions edgeOptions = new EdgeOptions(false);
        edgeOptions.BinaryLocation = @"C:\Program Files (x86)\Microsoft\Edge Beta\Application\msedge.exe";
        var msedgedriverDir = @"<download webdriver folder such as:D:\MicrosoftEdgeDriver\edgedriver_win64>";
        var msedgedriverExe = @"msedgedriver.exe";

        // Construct EdgeDriverService with is_legacy = false too
        var service = EdgeDriverService.CreateDefaultService(msedgedriverDir, msedgedriverExe, false);
        service.EnableVerboseLogging = true;

        var driver = new EdgeDriver(service, edgeOptions);

        driver.Navigate().GoToUrl("https://bing.com");
        Thread.Sleep(2000);

        driver.Close();

More detail information about using Chromium version Edge WebDriver, please check this link:

WebDriver (Chromium)


问:
I can't seem to get the msvc linker to work properly on vscode
I have this really simple program that's made up of 2 files.
main.cpp has the main function:

```<code>[main.cpp]
#include <iostream>
#include <string>
#include "calculator.h"

using namespace std;

int main() {
    Calculator calc;
    do {
        string op, left, right;
        float out;

        cout << endl << "insert an operator and two numbers: ";
        cin >> op;
        if (calc.isOperator(op)) {
            cin >> left;
            cin >> right;
            out = calc.doOp(op, left, right);
            cout << endl << "result: " << endl;
        }
        else
            cout << endl << "invalid operator" << endl;

    } while(true);
}
</code>```

calculator.cpp has the Calculator class and calculator.h has a declaration for the class and every function or variable in it.

```<code>[calculator.cpp]
#include <iostream>
#include <cmath>
#include <vector>
#include <string>

using namespace std;

class Calculator {
    vector<float>* mem_stack;

public:
    Calculator() {
        mem_stack = new vector<float>();
    }

    ~Calculator() {
        delete mem_stack;
    }

    float memPeek() {
        return (*mem_stack).back();
    }

    float memPeek(const int& age) {
        return (*mem_stack)[(*mem_stack).size() - age];
    }

    float doOp(const string& op, string& left, string& right) {
        float a, b;

        if (left[0] == 'r') {
            left = left.substr(1, left.size() - 1);
            a = memPeek(stoi(left));
        }
        else
            a = stoi(left);

        if (right[0] == 'r') {
            right = right.substr(1, right.size() - 1);
            b = memPeek(stoi(right));
        }
        else
            b = stoi(right);

        float out;
        if (op == "+")
            out = a + b;
        else if (op == "-")
            out = a - b;
        else if (op == "*")
            out = a * b;
        else if (op == "/")
            out = a / b;
        (*mem_stack).push_back(out);

        return memPeek();
    }

    bool isOperator(const string& op) {
        bool out;
        out = op == "+" && op == "-" && op == "*" && op == "/";
        return out;
    }
};
</code>```

```<code>[calculator.h]
#pragma once
#include <vector>
#include <string>

class Calculator {
private:
    std::vector<float>* mem_stack;
public:
    Calculator();
    ~Calculator();
    float memPeek();
    float memPeek(const int& age);
    float doOp(const std::string& op, std::string& left, std::string& right);
    bool isOperator(const std::string& op);
};
</code>```

When I try to compile the program I get unresolved linking errors in the main function. They all look like this:

```<code>main.obj : error LNK2019: unresolved external symbol
</code>```

I get them for every function from calculator.cpp called in main, including the constructor and destructor
I have looked up everything I could find on this but I still get those errors. Could anybody help me?
I'm still just a rookie.

答:
Welcome to StackOverflow!

You may have solved this in the meantime, but your problem is pretty simple: in your Calculator.cpp file, you're basically redeclaring another Calculator class, which shadows the original one, that ends up with no functions defined for it (just the declarations in the .h file). To solve this, you instead declare your member functions with ClassName::functionName() in the .cpp instead.

Didn't try compiling, but this should work:

```<code>[calculator.cpp]
#include <iostream>
#include <cmath>
#include <vector>
#include <string>

using namespace std;

Calculator::Calculator() {
    mem_stack = new vector<float>();
}

Calculator::~Calculator() {
    delete mem_stack;
}

float Calculator::memPeek() {
    return (*mem_stack).back();
}

float Calculator::memPeek(const int& age) {
    return (*mem_stack)[(*mem_stack).size() - age];
}

float Calculator::doOp(const string& op, string& left, string& right) {
    float a, b;

    if (left[0] == 'r') {
        left = left.substr(1, left.size() - 1);
        a = memPeek(stoi(left));
    }
    else
        a = stoi(left);

    if (right[0] == 'r') {
        right = right.substr(1, right.size() - 1);
        b = memPeek(stoi(right));
    }
    else
        b = stoi(right);

    float out;
    if (op == "+")
        out = a + b;
    else if (op == "-")
        out = a - b;
    else if (op == "*")
        out = a * b;
    else if (op == "/")
        out = a / b;
    (*mem_stack).push_back(out);

    return memPeek();
}

bool Calculator::isOperator(const string& op) {
    bool out;
    out = op == "+" && op == "-" && op == "*" && op == "/";
    return out;
}
</code>```

As a side note, I don't know of your programming background, but one thing struck me out as very odd in your code. Maybe you've come from Java or C#, where you always have to initialize object member variables; C++ is a bit more like C in this respect, in that it allows you to hold objects by value, and not only reference. Which means you don't have to have a pointer to your vector<float>, nor allocate/deallocate it yourself; let the compiler do the work for you and use it by value.

So, instead of doing std::vector<float>* mem_stack;, simply do std::vector<float> mem_stack;; this makes operations like (*mem_stack).push_back(out); (or the alternative mem_stack->push_back(out);, using the -> deference operator) much cleaner: mem_stack.push_back(out);

Body:
I have this really simple program that's made up of 2 files.
main.cpp has the main function:

[main.cpp]
#include <iostream>
#include <string>
#include "calculator.h"

using namespace std;

int main() {
    Calculator calc;
    do {
        string op, left, right;
        float out;

        cout << endl << "insert an operator and two numbers: ";
        cin >> op;
        if (calc.isOperator(op)) {
            cin >> left;
            cin >> right;
            out = calc.doOp(op, left, right);
            cout << endl << "result: " << endl;
        }
        else
            cout << endl << "invalid operator" << endl;

    } while(true);
}

calculator.cpp has the Calculator class and calculator.h has a declaration for the class and every function or variable in it.

[calculator.cpp]
#include <iostream>
#include <cmath>
#include <vector>
#include <string>

using namespace std;

class Calculator {
    vector<float>* mem_stack;

public:
    Calculator() {
        mem_stack = new vector<float>();
    }

    ~Calculator() {
        delete mem_stack;
    }

    float memPeek() {
        return (*mem_stack).back();
    }

    float memPeek(const int& age) {
        return (*mem_stack)[(*mem_stack).size() - age];
    }

    float doOp(const string& op, string& left, string& right) {
        float a, b;

        if (left[0] == 'r') {
            left = left.substr(1, left.size() - 1);
            a = memPeek(stoi(left));
        }
        else
            a = stoi(left);

        if (right[0] == 'r') {
            right = right.substr(1, right.size() - 1);
            b = memPeek(stoi(right));
        }
        else
            b = stoi(right);

        float out;
        if (op == "+")
            out = a + b;
        else if (op == "-")
            out = a - b;
        else if (op == "*")
            out = a * b;
        else if (op == "/")
            out = a / b;
        (*mem_stack).push_back(out);

        return memPeek();
    }

    bool isOperator(const string& op) {
        bool out;
        out = op == "+" && op == "-" && op == "*" && op == "/";
        return out;
    }
};

[calculator.h]
#pragma once
#include <vector>
#include <string>

class Calculator {
private:
    std::vector<float>* mem_stack;
public:
    Calculator();
    ~Calculator();
    float memPeek();
    float memPeek(const int& age);
    float doOp(const std::string& op, std::string& left, std::string& right);
    bool isOperator(const std::string& op);
};

When I try to compile the program I get unresolved linking errors in the main function. They all look like this:

main.obj : error LNK2019: unresolved external symbol

I get them for every function from calculator.cpp called in main, including the constructor and destructor
I have looked up everything I could find on this but I still get those errors. Could anybody help me?
I'm still just a rookie.

Body:
Welcome to StackOverflow!

You may have solved this in the meantime, but your problem is pretty simple: in your Calculator.cpp file, you're basically redeclaring another Calculator class, which shadows the original one, that ends up with no functions defined for it (just the declarations in the .h file). To solve this, you instead declare your member functions with ClassName::functionName() in the .cpp instead.

Didn't try compiling, but this should work:

[calculator.cpp]
#include <iostream>
#include <cmath>
#include <vector>
#include <string>

using namespace std;

Calculator::Calculator() {
    mem_stack = new vector<float>();
}

Calculator::~Calculator() {
    delete mem_stack;
}

float Calculator::memPeek() {
    return (*mem_stack).back();
}

float Calculator::memPeek(const int& age) {
    return (*mem_stack)[(*mem_stack).size() - age];
}

float Calculator::doOp(const string& op, string& left, string& right) {
    float a, b;

    if (left[0] == 'r') {
        left = left.substr(1, left.size() - 1);
        a = memPeek(stoi(left));
    }
    else
        a = stoi(left);

    if (right[0] == 'r') {
        right = right.substr(1, right.size() - 1);
        b = memPeek(stoi(right));
    }
    else
        b = stoi(right);

    float out;
    if (op == "+")
        out = a + b;
    else if (op == "-")
        out = a - b;
    else if (op == "*")
        out = a * b;
    else if (op == "/")
        out = a / b;
    (*mem_stack).push_back(out);

    return memPeek();
}

bool Calculator::isOperator(const string& op) {
    bool out;
    out = op == "+" && op == "-" && op == "*" && op == "/";
    return out;
}

As a side note, I don't know of your programming background, but one thing struck me out as very odd in your code. Maybe you've come from Java or C#, where you always have to initialize object member variables; C++ is a bit more like C in this respect, in that it allows you to hold objects by value, and not only reference. Which means you don't have to have a pointer to your vector<float>, nor allocate/deallocate it yourself; let the compiler do the work for you and use it by value.

So, instead of doing std::vector<float>* mem_stack;, simply do std::vector<float> mem_stack;; this makes operations like (*mem_stack).push_back(out); (or the alternative mem_stack->push_back(out);, using the -> deference operator) much cleaner: mem_stack.push_back(out);


问:
Shared VPC and VPC Peering mix
On Google cloud, I have setup new three projects - dev, research and prod. So, then created an Shared VPC Host and three Service Projects as listed above. Also intend to have separate VPCs for each of these service projects (to add more security layer), hence also intend to use now VPC Peering. But confused here  can we configure both Shared VPCs and VPC Peering on same set of Projects?.  If so then i do not find any links on this and also is this an right thing to do?</p>

答:
Peering and Shared have their own usage. With peering, you are limited to 25 per project and the transitivity isn't possible.

For example, with peering, if you set up a peering between dev and research and between research and prod; dev can't reach the prod (transitivity is forbidden), you have to set up a peering between dev and prod for this. The peering can be interesting when you want to share a VPN or Interconnect endpoint. You perform a peering between the interconnect project and these that want to reuse this connexion.

With share VPC, you don't have the transitivity limitation, all the VM can be in the same VPC, even if they are in different projects.

However, with this config, you break the project strong isolation, your dev project can access to the prod without limitation!

Thereby I recommend you to set up VM network with at least "2 legs": 1 in the shared VPC, the other in a project dedicated VPC. And then to set up the correct firewalls rules on your VPC network for limiting interactions in the shared VPC, but by keeping an unrestricted limitation at project level with the leg in the VPC project.

Title: Shared VPC and VPC Peering mix


问:
How can I convert a regular WAV file to a 4bit WAV file using ffmpeg?
I have tried something along the lines of

C:\ffmpeg\ffmpeg -i "Blip_Select2.wav" -c:a wav -sample_fmt u8 "Blip_Select2_8bit.wav"

but I cannot figure out how to access a 4bit conversion.

I am using the audio for a c# project, 4 bit is sufficient and I prefer wav so I won't have to distribute a possibly restricted usage decoder with my files.

答:
Ok, so I did manage to find a solution for this. It's a great command line utility similar to ffmpeg, called (Sound eXchange) SoX. It can be found here:

http://sox.sourceforge.net/

The command line that achieves converting to 4 bit wav is this:

```<code>sox "sound.wav" -b 4 "sound_4bit.wav"
</code>```

It works perfectly and I did not notice any quality drop as the sampling rate is still 44100, while the size drops to 1/4.

An important note. This works well only if your audio is clean and not recorded too loud, such as correctly recorded voice speech (this is what I am using it for), but also works for music as long as it's not too loud.

Body:
Ok, so I did manage to find a solution for this. It's a great command line utility similar to ffmpeg, called (Sound eXchange) SoX. It can be found here:

http://sox.sourceforge.net/

The command line that achieves converting to 4 bit wav is this:

sox "sound.wav" -b 4 "sound_4bit.wav"

It works perfectly and I did not notice any quality drop as the sampling rate is still 44100, while the size drops to 1/4.

An important note. This works well only if your audio is clean and not recorded too loud, such as correctly recorded voice speech (this is what I am using it for), but also works for music as long as it's not too loud.


问:
MongoDB sub-document query limit/skip results?
I have an aggregate query that extracts sub-documents from a database in mongodb:

```<code>    [
      {
        $match: {
          username: query.username,
        },
      },
      {
        $project: {
          connections: {
            $filter: {
              input: '$connections',
              as: 'connections',
              cond: {
                $eq: ['$$connections.state', query.state],
              },
            },
          },
        },
      }
    ]
</code>```

The document schema looks as the following (from typegoose, but fairly self explanatory):

```<code>export class Connection {
  @prop({ default: () => new Date() })
  public updated?: Date;

  @prop({ required: true, enum: ConnectionStateEnum })
  public state: ConnectionStateEnum;

  @prop({ required: true })
  public username: string;

  @prop()
  public requestIP?: string;

  @prop()
  public requestBrowserString?: string;
}

@modelOptions({
  schemaOptions: {
    collection: 'connections',
    timestamps: true,
  },
})
export class UserConnections {
  @prop({ default: v1 })
    /* tslint:disable */
  _id: string;
  /* tslint: enable */

  @prop({ unique: true })
  username: string;

  @prop({ required: true })
  lastConnectionActivityWithUsername: string;

  @arrayProp({ items: Connection })
  connections: Connection[];
}
</code>```

The idea is a user has 1 doc containing their connections, thus the connections attribute is an array of connection objects.

If i add a $skip or $limit to the aggregate query this will not change the result of the query as this limits the qty of docs returned, but as there is a macth on a unique field the doc count will always be 1.

Is it possible to limit/skip the number of connection objects to return from a single doc within the query, or can this only be done post query?

(eg a user has 20 connections, but i only want to return 10 connections from the doc)

Based on the answer below I arrived at mixin slice and filter into a $let aggregation pipeline operator as using slice next $filter failed with an error of:

MongoError: Invalid $project :: caused by :: an expression specification must contain exactly one field, the name of the expression. Found 2 fields in { $filter: { input: "$connections", as: "connections", cond: { $eq: [ "$$connections.state", "requestSentAccepted" ] } }, $slice: [ "$$connections", 0, 20 ] }, while parsing object { connections: { $filter: { input: "$connections", as: "connections", cond: { $eq: [ "$$connections.state", "requestSentAccepted" ] } }, $slice: [ "$$connections", 0, 20 ] }

This worked though:

```<code>{
        $project: {
          connections: {
            $let: {
              vars: {
                connections: {
                  $filter: {
                    input: '$connections',
                    as: 'connections',
                    cond: {
                      $eq: ['$$connections.state', query.state],
                    },
                  },
                },
              },
              in: {
                $slice: ['$$connections', offset, limit],
              },
            },
          },
        },
      },
</code>```

答:
You could use $slice for that:

```<code>...
{
  $project: {
    connections: {
      $slice: [ "$connections", skip, limit ]
    }
  }
}
</code>```

Body:
I have an aggregate query that extracts sub-documents from a database in mongodb:

    [
      {
        $match: {
          username: query.username,
        },
      },
      {
        $project: {
          connections: {
            $filter: {
              input: '$connections',
              as: 'connections',
              cond: {
                $eq: ['$$connections.state', query.state],
              },
            },
          },
        },
      }
    ]

The document schema looks as the following (from typegoose, but fairly self explanatory):

export class Connection {
  @prop({ default: () => new Date() })
  public updated?: Date;

  @prop({ required: true, enum: ConnectionStateEnum })
  public state: ConnectionStateEnum;

  @prop({ required: true })
  public username: string;

  @prop()
  public requestIP?: string;

  @prop()
  public requestBrowserString?: string;
}

@modelOptions({
  schemaOptions: {
    collection: 'connections',
    timestamps: true,
  },
})
export class UserConnections {
  @prop({ default: v1 })
    /* tslint:disable */
  _id: string;
  /* tslint: enable */

  @prop({ unique: true })
  username: string;

  @prop({ required: true })
  lastConnectionActivityWithUsername: string;

  @arrayProp({ items: Connection })
  connections: Connection[];
}

The idea is a user has 1 doc containing their connections, thus the connections attribute is an array of connection objects.

If i add a $skip or $limit to the aggregate query this will not change the result of the query as this limits the qty of docs returned, but as there is a macth on a unique field the doc count will always be 1.

Is it possible to limit/skip the number of connection objects to return from a single doc within the query, or can this only be done post query?

(eg a user has 20 connections, but i only want to return 10 connections from the doc)

Based on the answer below I arrived at mixin slice and filter into a $let aggregation pipeline operator as using slice next $filter failed with an error of:

MongoError: Invalid $project :: caused by :: an expression specification must contain exactly one field, the name of the expression. Found 2 fields in { $filter: { input: "$connections", as: "connections", cond: { $eq: [ "$$connections.state", "requestSentAccepted" ] } }, $slice: [ "$$connections", 0, 20 ] }, while parsing object { connections: { $filter: { input: "$connections", as: "connections", cond: { $eq: [ "$$connections.state", "requestSentAccepted" ] } }, $slice: [ "$$connections", 0, 20 ] }

This worked though:

{
        $project: {
          connections: {
            $let: {
              vars: {
                connections: {
                  $filter: {
                    input: '$connections',
                    as: 'connections',
                    cond: {
                      $eq: ['$$connections.state', query.state],
                    },
                  },
                },
              },
              in: {
                $slice: ['$$connections', offset, limit],
              },
            },
          },
        },
      },

Body:
You could use $slice for that:

...
{
  $project: {
    connections: {
      $slice: [ "$connections", skip, limit ]
    }
  }
}


问:
How to set default variable in JSX for const with selector
I am fairly experienced with PHP and Wordpress theming, but now struggling with the new Gutenberg editor. I have created a custom block plugin, which involves a lot of JS (React). To the latter I am a bit new.

The block is creating a simple wrapper div with a html lang attribute assigned to it based on the input of a selector. The following code is working fine, however only when the selector is changed. By default the langCode variable remains empty. Any idea what goes wrong?

```<code>registerBlockType( 'lang-group-block/lang-group', {
    // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
    title: __( 'Language group', 'lang-group-block' ), // Block title.
    icon: 'flag', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
    category: 'layout', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
    keywords: [
        __( 'Language', 'lang-group-block' ),
        __( 'Group', 'lang-group-block' ),
    ],

    attributes: {
        // Register langCode attribute to save the chosen language
        langCode: {
            type: 'string',
        },
    },

    edit( { attributes, setAttributes, className } ) {
        const {
            langCode = 'en',
        } = attributes;

        const groupIndicatorStyle = {
            fontSize: 14,
            color: "#ff0000",
            textAlign: "center",
            paddingTop: "40px",
        }

        return (
            <Fragment>
                <InspectorControls>
                    <PanelBody
                        title={ __( 'Language', 'rapp2020-lang-group-block' ) }
                        initialOpen={ true }
                    >
                        <SelectControl
                            label={ __( 'Language', 'rapp2020-lang-group-block' ) }
                            value={ langCode }
                            options={ [
                                {
                                    value: 'en',
                                    label: __( 'EN', 'rapp2020-lang-group-block' ),
                                },
                                {
                                    value: 'nl',
                                    label: __( 'NL', 'rapp2020-lang-group-block' ),
                                },
                                {
                                    value: 'de',
                                    label: __( 'DE', 'rapp2020-lang-group-block' ),
                                },
                            ] }
                            onChange={ ( selectedOption ) => setAttributes( { langCode: selectedOption } ) }
                        />
                    </PanelBody>
                </InspectorControls>
                <div style={ groupIndicatorStyle }>
                    language group: { langCode }
                </div>
                <div
                    className={ className }
                    lang={ langCode }
                >
                    <InnerBlocks />
                </div>
            </Fragment>
        );
    },

    save( { attributes, className } ) {
        const {
            langCode = '',
        } = attributes;

        let classes = className;
        if ( '' == langCode ) {
            { langCode: 'en' }
        }

        return (
            <div
                className={ classes }
                lang={ langCode }
            >
                <InnerBlocks.Content />
            </div>
        );
    },
} );
</code>```

答:
This should be working:

```<code>save( { attributes, className } ) {
    const { langCode } = attributes;
    let classes = className;

    return (
        <div
            className={ classes }
            lang={ langCode || 'en' }
        >
            <InnerBlocks.Content />
        </div>
    );
},
</code>```

EDIT: Couldn't reproduce the still existing error. So here's the complete block already with createElements. Another suggestion: you're setting using 'en' as default. Why not setting it as such?

```<code>;( function ( wp ) {

    const el = wp.element.createElement;
    const __ = wp.i18n.__;

    const { Fragment } = wp.element;
    const { InspectorControls , InnerBlocks } = wp.blockEditor;
    const { PanelBody , SelectControl } = wp.components;

    wp.blocks.registerBlockType( 'lang-group-block/lang-group', {
        // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
        title: __( 'Language group', 'lang-group-block' ), // Block title.
        icon: 'flag', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
        category: 'layout', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
        keywords: [
            __( 'Language', 'lang-group-block' ),
            __( 'Group', 'lang-group-block' ),
        ],

        attributes: {
            // Register langCode attribute to save the chosen language
            langCode: {
                type: 'string',
                default : 'en'
            },
        },

        edit( { attributes, setAttributes, className } ) {

            const groupIndicatorStyle = {
                fontSize: 14,
                color: '#ff0000',
                textAlign: 'center',
                paddingTop: '40px',
            }

            return el( Fragment, null ,
                el( InspectorControls, null,
                  el( PanelBody,
                    { title: __('Language', 'rapp2020-lang-group-block'), initialOpen: true },
                    el(SelectControl, {
                      label: __('Language', 'rapp2020-lang-group-block'),
                      value: attributes.langCode,
                      options: [
                        { value: 'en', label: __('EN', 'rapp2020-lang-group-block') },
                        { value: 'nl', label: __('NL', 'rapp2020-lang-group-block') },
                        { value: 'de', label: __('DE', 'rapp2020-lang-group-block') }
                      ],
                      onChange: function onChange(selectedOption) { return setAttributes({ langCode: selectedOption }); }
                    })
                  )
                ),
                el( 'div', { style: groupIndicatorStyle }, 'language group: ', attributes.langCode  ),
                el( 'div', { className: className, lang: attributes.langCode }, el(InnerBlocks, null) )
              );
        },

        save( { attributes, className } ) {
            return el( 'div', { className: className, lang: attributes.langCode || 'en' }, el(InnerBlocks.Content, null) );
        },
    } );

} )( window.wp );
</code>```

Body:
I am fairly experienced with PHP and Wordpress theming, but now struggling with the new Gutenberg editor. I have created a custom block plugin, which involves a lot of JS (React). To the latter I am a bit new.

The block is creating a simple wrapper div with a html lang attribute assigned to it based on the input of a selector. The following code is working fine, however only when the selector is changed. By default the langCode variable remains empty. Any idea what goes wrong?

registerBlockType( 'lang-group-block/lang-group', {
    // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
    title: __( 'Language group', 'lang-group-block' ), // Block title.
    icon: 'flag', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
    category: 'layout', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
    keywords: [
        __( 'Language', 'lang-group-block' ),
        __( 'Group', 'lang-group-block' ),
    ],

    attributes: {
        // Register langCode attribute to save the chosen language
        langCode: {
            type: 'string',
        },
    },

    edit( { attributes, setAttributes, className } ) {
        const {
            langCode = 'en',
        } = attributes;

        const groupIndicatorStyle = {
            fontSize: 14,
            color: "#ff0000",
            textAlign: "center",
            paddingTop: "40px",
        }

        return (
            <Fragment>
                <InspectorControls>
                    <PanelBody
                        title={ __( 'Language', 'rapp2020-lang-group-block' ) }
                        initialOpen={ true }
                    >
                        <SelectControl
                            label={ __( 'Language', 'rapp2020-lang-group-block' ) }
                            value={ langCode }
                            options={ [
                                {
                                    value: 'en',
                                    label: __( 'EN', 'rapp2020-lang-group-block' ),
                                },
                                {
                                    value: 'nl',
                                    label: __( 'NL', 'rapp2020-lang-group-block' ),
                                },
                                {
                                    value: 'de',
                                    label: __( 'DE', 'rapp2020-lang-group-block' ),
                                },
                            ] }
                            onChange={ ( selectedOption ) => setAttributes( { langCode: selectedOption } ) }
                        />
                    </PanelBody>
                </InspectorControls>

                    language group: { langCode }

                    <InnerBlocks />

            </Fragment>
        );
    },

    save( { attributes, className } ) {
        const {
            langCode = '',
        } = attributes;

        let classes = className;
        if ( '' == langCode ) {
            { langCode: 'en' }
        }

        return (

                <InnerBlocks.Content />

        );
    },
} );

Body:
This should be working:

save( { attributes, className } ) {
    const { langCode } = attributes;
    let classes = className;

    return (
        <div
            className={ classes }
            lang={ langCode || 'en' }
        >
            <InnerBlocks.Content />
        </div>
    );
},

EDIT: Couldn't reproduce the still existing error. So here's the complete block already with createElements. Another suggestion: you're setting using 'en' as default. Why not setting it as such?

;( function ( wp ) {

    const el = wp.element.createElement;
    const __ = wp.i18n.__;

    const { Fragment } = wp.element;
    const { InspectorControls , InnerBlocks } = wp.blockEditor;
    const { PanelBody , SelectControl } = wp.components;

    wp.blocks.registerBlockType( 'lang-group-block/lang-group', {
        // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
        title: __( 'Language group', 'lang-group-block' ), // Block title.
        icon: 'flag', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
        category: 'layout', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
        keywords: [
            __( 'Language', 'lang-group-block' ),
            __( 'Group', 'lang-group-block' ),
        ],

        attributes: {
            // Register langCode attribute to save the chosen language
            langCode: {
                type: 'string',
                default : 'en'
            },
        },

        edit( { attributes, setAttributes, className } ) {

            const groupIndicatorStyle = {
                fontSize: 14,
                color: '#ff0000',
                textAlign: 'center',
                paddingTop: '40px',
            }

            return el( Fragment, null ,
                el( InspectorControls, null,
                  el( PanelBody,
                    { title: __('Language', 'rapp2020-lang-group-block'), initialOpen: true },
                    el(SelectControl, {
                      label: __('Language', 'rapp2020-lang-group-block'),
                      value: attributes.langCode,
                      options: [
                        { value: 'en', label: __('EN', 'rapp2020-lang-group-block') },
                        { value: 'nl', label: __('NL', 'rapp2020-lang-group-block') },
                        { value: 'de', label: __('DE', 'rapp2020-lang-group-block') }
                      ],
                      onChange: function onChange(selectedOption) { return setAttributes({ langCode: selectedOption }); }
                    })
                  )
                ),
                el( 'div', { style: groupIndicatorStyle }, 'language group: ', attributes.langCode  ),
                el( 'div', { className: className, lang: attributes.langCode }, el(InnerBlocks, null) )
              );
        },

        save( { attributes, className } ) {
            return el( 'div', { className: className, lang: attributes.langCode || 'en' }, el(InnerBlocks.Content, null) );
        },
    } );

} )( window.wp );


问:
Image throws 404 Error when using app on server
Hi I checked several answers around the web but none of these worked yet, I located the image where it supposed to be by the most answers. The problem is that I have a loader component which contains a loader that pops up when doing something in my application and it needs some time to load. In local it works perfectly but when I use it on server it throws GET 404 error for the image that needs to be shown inside the loader circle. I'm using Angular 7.

Currently I have the image here: src/assets/image/logo.jpg

And this is how it looks in the component:

my workspace is like this: src --> app --> loader --> loadingComponent

What can cause the problem that it works good in local but doesn't work when I run the app on Tomcat server

答:
Change your image src to absolute path.

```<code><img src="/assets/image/logo.jpg">
</code>```

You should consider situation, when you use your component somewhere deeper in your app. This would brake your relative path, so absolute path is better solution.

/assets directory is served from root path by default, so you have nothing to worry about.

Body:
Change your image src to absolute path.

<img src="/assets/image/logo.jpg">

You should consider situation, when you use your component somewhere deeper in your app. This would brake your relative path, so absolute path is better solution.

/assets directory is served from root path by default, so you have nothing to worry about.


问:
Why can't I connect to http server on localhost through a browser?
I wrote a very simple Java http server for exercising purposes. I test it with cURL and everything seems to work fine but when I try to send a request from a browser

```<code>http://localhost:6666/
</code>```

the server does not respond. I even put a marking System.out.println() at the point when the server socket accepts a connection which doesn't seem to fire when i try to hit the server through a browser. Please help me out with this.
Thanks :)

EDIT:
Part of the code:

```<code>public class Server {

    private ServerSocket serverSocket;
    private Socket socket;
    public Server() {
        try {
            serverSocket = new ServerSocket(6666);
            while (true) {
                socket = serverSocket.accept();
                System.out.println("Whoop! Connection!");
                Request request = new Request(socket);
                request.run();
            }
        } catch (IOException e) {
            e.printStackTrace();
          }
    }
}
</code>```

Where Request is a class which extends Thread in order to handle multiple requests

答:
Looks like port 6666 is considered unsafe by many browsers for security reasons.
Please try some other ports may be port 3000 or 5000(I am just throwing a number here) it should work.</p>

ContentLicense: CC BY-SA 3.0

Body:
I wrote a very simple Java http server for exercising purposes. I test it with cURL and everything seems to work fine but when I try to send a request from a browser

http://localhost:6666/

the server does not respond. I even put a marking System.out.println() at the point when the server socket accepts a connection which doesn't seem to fire when i try to hit the server through a browser. Please help me out with this.
Thanks :)

EDIT:
Part of the code:

public class Server {

    private ServerSocket serverSocket;
    private Socket socket;
    public Server() {
        try {
            serverSocket = new ServerSocket(6666);
            while (true) {
                socket = serverSocket.accept();
                System.out.println("Whoop! Connection!");
                Request request = new Request(socket);
                request.run();
            }
        } catch (IOException e) {
            e.printStackTrace();
          }
    }
}

Where Request is a class which extends Thread in order to handle multiple requests


问:
Deletes Headings when deleting rows with different criteria
I have an issue when deleting rows with certain conditions because it deletes my headers too, also ¿ is there a way to improving the deleting of rows with different criteria ?

```<code>Sub RO_FilterDelete()
Dim RowToTest As Long

For RowToTest = Cells(Rows.Count, 2).End(xlUp).row To 2 Step -1

With Cells(RowToTest, 1)
    If .Value <> "ONLINE" _
    Then _
    Rows(RowToTest).EntireRow.Delete
End With

Next RowToTest

Dim RowToTest2 As Long

For RowToTest2 = Cells(Rows.Count, 2).End(xlUp).row To 2 Step -1

With Cells(RowToTest2, 6)
    If .Value <> "CONFIRMACIÓN DE INFORMACIÓN DE CONTRATO" _
    And .Value <> "ACTUALIZACIÓN DE INFORMACIÓN DE CONTRATO" _
    Then _
    Rows(RowToTest2).EntireRow.Delete
End With

Next RowToTest2
End Sub
</code>```

The error comes from the macro that paste the data into the worksheet, it pastes it from A1 instead of A2, that's why the filter doesn't work.

```<code>Sub RechazosOnline()
Dim rsh As Worksheet, wb As Workbook
Dim wbCopyFrom As Workbook, wsCopyFrom As Worksheet

Set wb = Workbooks("2. Detalle_Transacciones_pendientes_rechazadas_MDM_27Ene20.xlsx")
Set wbCopyFrom = Workbooks("1. ReporteGeneral_TransaccionesDiariasMDM_20200115")
Set wsCopyFrom = wbCopyFrom.Worksheets("Detalle")
wsCopyFrom.Range("A2:I" & wsCopyFrom.Range("A" & Rows.Count).End(xlUp).row).Copy

For Each rsh In wb.Sheets
         rsh.Range("A2:I" & rsh.Range("A" & rsh.Cells.Rows.Count).End(xlUp).row).PasteSpecial xlPasteValues
     Next
End Sub
</code>```

答:
The both loop of your code are working for me.
As Variatus sugested, maybe your header aren't on the first row.

Have a nice day !

Body:
I have an issue when deleting rows with certain conditions because it deletes my headers too, also ¿ is there a way to improving the deleting of rows with different criteria ?

Sub RO_FilterDelete()
Dim RowToTest As Long

For RowToTest = Cells(Rows.Count, 2).End(xlUp).row To 2 Step -1

With Cells(RowToTest, 1)
    If .Value <> "ONLINE" _
    Then _
    Rows(RowToTest).EntireRow.Delete
End With

Next RowToTest

Dim RowToTest2 As Long

For RowToTest2 = Cells(Rows.Count, 2).End(xlUp).row To 2 Step -1

With Cells(RowToTest2, 6)
    If .Value <> "CONFIRMACIÓN DE INFORMACIÓN DE CONTRATO" _
    And .Value <> "ACTUALIZACIÓN DE INFORMACIÓN DE CONTRATO" _
    Then _
    Rows(RowToTest2).EntireRow.Delete
End With

Next RowToTest2
End Sub

The error comes from the macro that paste the data into the worksheet, it pastes it from A1 instead of A2, that's why the filter doesn't work.

Sub RechazosOnline()
Dim rsh As Worksheet, wb As Workbook
Dim wbCopyFrom As Workbook, wsCopyFrom As Worksheet

Set wb = Workbooks("2. Detalle_Transacciones_pendientes_rechazadas_MDM_27Ene20.xlsx")
Set wbCopyFrom = Workbooks("1. ReporteGeneral_TransaccionesDiariasMDM_20200115")
Set wsCopyFrom = wbCopyFrom.Worksheets("Detalle")
wsCopyFrom.Range("A2:I" & wsCopyFrom.Range("A" & Rows.Count).End(xlUp).row).Copy

For Each rsh In wb.Sheets
         rsh.Range("A2:I" & rsh.Range("A" & rsh.Cells.Rows.Count).End(xlUp).row).PasteSpecial xlPasteValues
     Next
End Sub


问:
Generate all combinations of an unknown number of variables
I have a list of variables, the number of which can change. Each variable has a lower limit, upper limit and an increment value. For example:

```<code>variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}
</code>```

Where for key "a", 1 is the lower limit, 10 is the upper limit and 1 is the increment amount.

```<code>"a" would go from 1 through 10, incrementing by 1
"b" would go from 50 through 200, incrementing by 5
"c" would go from 50 through 300, incrementing by 10
... there can be more or less such keys.
</code>```

I need to create a list of all possible combinations of a, b and c, without hard coding nested loops, as there are an unknown number of variables/keys, and just cannot wrap my head around it. I'm using Python 3.7

The output would ideally be a table of combinations of each variable, perhaps comma separated values. For example.

```<code>a  b  c
x  y  z
x  y  z
x  y  z
x  y  z
</code>```

However, anything will do, as long as I can collate the output into a format where each combination can be accessed as a set. Such as a list of tuples.

```<code>[
  (x, y, z)
  (x, y, z)
]
...
</code>```

答:
You can use itertools:

```<code>import numpy as np
import itertools

a = np.arange(1, 10, 1)
b = np.arange(50, 200, 5)
c = np.arange(50,300,10)

results = itertools.product(a, b, c)
for item in results:
    print(item)
</code>```

Output:

```<code>(1, 50, 50)
(1, 50, 60)
...
...
(9, 195, 270)
(9, 195, 280)
(9, 195, 290)
</code>```

Body:
I have a list of variables, the number of which can change. Each variable has a lower limit, upper limit and an increment value. For example:

variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}

Where for key "a", 1 is the lower limit, 10 is the upper limit and 1 is the increment amount.

"a" would go from 1 through 10, incrementing by 1
"b" would go from 50 through 200, incrementing by 5
"c" would go from 50 through 300, incrementing by 10
... there can be more or less such keys.

I need to create a list of all possible combinations of a, b and c, without hard coding nested loops, as there are an unknown number of variables/keys, and just cannot wrap my head around it. I'm using Python 3.7

The output would ideally be a table of combinations of each variable, perhaps comma separated values. For example.

a  b  c
x  y  z
x  y  z
x  y  z
x  y  z

However, anything will do, as long as I can collate the output into a format where each combination can be accessed as a set. Such as a list of tuples.

[
  (x, y, z)
  (x, y, z)
]
...

Body:
You can use itertools:

import numpy as np
import itertools

a = np.arange(1, 10, 1)
b = np.arange(50, 200, 5)
c = np.arange(50,300,10)

results = itertools.product(a, b, c)
for item in results:
    print(item)

Output:

(1, 50, 50)
(1, 50, 60)
...
...
(9, 195, 270)
(9, 195, 280)
(9, 195, 290)


问:
How can I pass more than one enum to a method that receives only one?
I'm wondering if the following is possible:

The method Regex.Match can receive an enum, so I can specify:

```<code>RegexOptions.IgnoreCase
RegexOptions.IgnorePatternWhiteSpace
RegexOptions.Multiline
</code>```

What if I need to specify more than just one? (eg. I want my regex to be Multiline and I want it to ignore the pattern whitespace).

Could I use | operator like in C/C++?

答:
You need to annotate it with [Flags] attribute and use | operator to combine them.

In the case you mentioned, you can do that because RegexOptions enum is annotated with it.

More References:

A helpful way to use the FlagsAttribute with enumerations

Example Snippet from above CodeProject article:

Definition:

```<code>[FlagsAttribute]
public enum NewsCategory : int
{
    TopHeadlines =1,
    Sports=2,
    Business=4,
    Financial=8,
    World=16,
    Entertainment=32,
    Technical=64,
    Politics=128,
    Health=256,
    National=512
}
</code>```

Use:

```<code>mon.ContentCategories = NewsCategory.Business |
                        NewsCategory.Entertainment |
                        NewsCategory.Politics;
</code>```

Body:
I'm wondering if the following is possible:

The method Regex.Match can receive an enum, so I can specify:

RegexOptions.IgnoreCase
RegexOptions.IgnorePatternWhiteSpace
RegexOptions.Multiline

What if I need to specify more than just one? (eg. I want my regex to be Multiline and I want it to ignore the pattern whitespace).

Could I use | operator like in C/C++?

Body:
You need to annotate it with [Flags] attribute and use | operator to combine them.

In the case you mentioned, you can do that because RegexOptions enum is annotated with it.

More References:

A helpful way to use the FlagsAttribute with enumerations

Example Snippet from above CodeProject article:

Definition:

[FlagsAttribute]
public enum NewsCategory : int
{
    TopHeadlines =1,
    Sports=2,
    Business=4,
    Financial=8,
    World=16,
    Entertainment=32,
    Technical=64,
    Politics=128,
    Health=256,
    National=512
}

Use:

mon.ContentCategories = NewsCategory.Business |
                        NewsCategory.Entertainment |
                        NewsCategory.Politics;


答:
Your image src should be relative to the root of the app.

I assume your assets folder is in the root, as per the standard Angular build.

If so, your image element should look like this:

```<code><img src="/assets/image/logo.jpg">
</code>```

This has the effect of forming the full url

```<code>http://myapp.com/assets/image/logo.jpg
</code>```

If that still fails, try to load the image in your browser using the full url, and reverse engineer it to your image src.

Title: Image throws 404 Error when using app on server

Body:
Hi I checked several answers around the web but none of these worked yet, I located the image where it supposed to be by the most answers. The problem is that I have a loader component which contains a loader that pops up when doing something in my application and it needs some time to load. In local it works perfectly but when I use it on server it throws GET 404 error for the image that needs to be shown inside the loader circle. I'm using Angular 7.

Currently I have the image here: src/assets/image/logo.jpg

And this is how it looks in the component:

my workspace is like this: src --> app --> loader --> loadingComponent

What can cause the problem that it works good in local but doesn't work when I run the app on Tomcat server

Body:
Your image src should be relative to the root of the app.

I assume your assets folder is in the root, as per the standard Angular build.

If so, your image element should look like this:

<img src="/assets/image/logo.jpg">

This has the effect of forming the full url

http://myapp.com/assets/image/logo.jpg

If that still fails, try to load the image in your browser using the full url, and reverse engineer it to your image src.


问:
How to make two divs inline react

// Get a hook function
const {useState, useEffect} = React;

const Slider = props => {
const { innerWidth: width, innerHeight: height } = window;
  const urls = [
    "https://www.imb.com.au/templates/client/images/header/IMB-logo.svg",
    "https://www.mkmcapital.com.au/wp-content/uploads/2016/08/MKM_logo-2.png",
    "https://www.pnbank.com.au/Static/Theme/assets/images/pnbank-logo-narrow--7465fe2f1d3e10cf7acfc008991cebef.svg",
    "https://www.provident.com.au/images/logo-blue.png",
    "https://www.adelaidebank.com.au/globalassets/globalresources/brand-logos/abl-logo.png",
    "https://www.amp.com.au/content/dam/amp-au/data/icons/amp-logo-reversed.svg",
    "https://www.anz.com.au//content/dam/anzconz/images/common/promopages/logo-promo-anz-small.png",
    "https://www.bt.com.au//content/dam/public/btfg-bt/images/logo/bt_financial_group_logo_mob-2x1.png",
    "https://www.commbank.com.au/content/dam/commbank/commBank-logo.svg",
    "https://www.collinshomeloans.com.au/hs-fs/hubfs/collins-logo-shedow.png?width=230&name=collins-logo-shedow.png",
    "https://depositpower.com.au/wp-content/uploads/2019/01/DepositPower_stacked_white.png",
    "https://www.latrobefinancial.com.au//Images/Logos/Logo-LTF_v2.jpg",
    "https://d2ttwt9gu7swv4.cloudfront.net/assets/images/logo.svg",
    "https://www.mebank.com.au/MEBank/Assets/Images/me-logo.svg",
    "https://www.nab.com.au//etc/designs/nabrwd/clientlibs/images/logo.png",
    "https://www.pepper.com.au//siteassets/logos/pepper-money-logo.png",
    "https://www.suncorp.com.au//content/dam/suncorp/corporate/images/logos/Suncorp_New_Logo_2x.png",
    "https://www.equifax.com.au/sites/all/themes/vedacorporate/logo.png"
  ];
  let totalWidth = urls.length * 120;
  let [ left, setLeft ] = useState(0);
  let [ secondLeft, setSecondLeft ] = useState(-(width+300));

  useEffect(() => {
    const interval = setInterval(() => {
      setLeft(left => left + 1);
      setSecondLeft(secondLeft => secondLeft + 1);
      //console.log('left ' + left + ' sleft ' + secondLeft);
      if (left == 0) {
        setSecondLeft(-(totalWidth))
      }
      if(secondLeft == 0){
          setLeft(-(totalWidth))
      }
    }, 5);
    return () => {
      clearInterval(interval);
    };
  }, [left, secondLeft]);

  return (

        {urls.map((u, i) => {
          return (

          );
        })}

        {urls.map((u, i) => {
          return (

          );
        })}

  );
};

// Render it
ReactDOM.render(
  <Slider/>,
  document.getElementById("react")
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div></code>```

Its like this one below another

But I want it to be in one line. How can I do that

答:
Use marquee tag,</p>

```<code><marquee direction="left" style={{ display:'inline'}}>
  <span
    style={{
      width: { totalWidth },
      display: 'inline-block'
    }}
  >
    {urls.map((u, i) => {
      return (
        <span style={{ padding: "10px" }}>
          <img src={u} width="100px" />
        </span>
      );
    })}
  </span>
  <span
    style={{
      width: { totalWidth },
      display: 'inline-block'

    }}
  >
    {urls.map((u, i) => {
      return (
        <span style={{ padding: "10px" }}>
          <img src={u} width="100px" />
        </span>
      );
    })}
  </span>
</marquee>
</code>```

Title: How to make two divs inline react

Body:
// Get a hook function
const {useState, useEffect} = React;

const Slider = props => {
const { innerWidth: width, innerHeight: height } = window;
  const urls = [
    "https://www.imb.com.au/templates/client/images/header/IMB-logo.svg",
    "https://www.mkmcapital.com.au/wp-content/uploads/2016/08/MKM_logo-2.png",
    "https://www.pnbank.com.au/Static/Theme/assets/images/pnbank-logo-narrow--7465fe2f1d3e10cf7acfc008991cebef.svg",
    "https://www.provident.com.au/images/logo-blue.png",
    "https://www.adelaidebank.com.au/globalassets/globalresources/brand-logos/abl-logo.png",
    "https://www.amp.com.au/content/dam/amp-au/data/icons/amp-logo-reversed.svg",
    "https://www.anz.com.au//content/dam/anzconz/images/common/promopages/logo-promo-anz-small.png",
    "https://www.bt.com.au//content/dam/public/btfg-bt/images/logo/bt_financial_group_logo_mob-2x1.png",
    "https://www.commbank.com.au/content/dam/commbank/commBank-logo.svg",
    "https://www.collinshomeloans.com.au/hs-fs/hubfs/collins-logo-shedow.png?width=230&name=collins-logo-shedow.png",
    "https://depositpower.com.au/wp-content/uploads/2019/01/DepositPower_stacked_white.png",
    "https://www.latrobefinancial.com.au//Images/Logos/Logo-LTF_v2.jpg",
    "https://d2ttwt9gu7swv4.cloudfront.net/assets/images/logo.svg",
    "https://www.mebank.com.au/MEBank/Assets/Images/me-logo.svg",
    "https://www.nab.com.au//etc/designs/nabrwd/clientlibs/images/logo.png",
    "https://www.pepper.com.au//siteassets/logos/pepper-money-logo.png",
    "https://www.suncorp.com.au//content/dam/suncorp/corporate/images/logos/Suncorp_New_Logo_2x.png",
    "https://www.equifax.com.au/sites/all/themes/vedacorporate/logo.png"
  ];
  let totalWidth = urls.length * 120;
  let [ left, setLeft ] = useState(0);
  let [ secondLeft, setSecondLeft ] = useState(-(width+300));

  useEffect(() => {
    const interval = setInterval(() => {
      setLeft(left => left + 1);
      setSecondLeft(secondLeft => secondLeft + 1);
      //console.log('left ' + left + ' sleft ' + secondLeft);
      if (left == 0) {
        setSecondLeft(-(totalWidth))
      }
      if(secondLeft == 0){
          setLeft(-(totalWidth))
      }
    }, 5);
    return () => {
      clearInterval(interval);
    };
  }, [left, secondLeft]);

  return (

        {urls.map((u, i) => {
          return (

          );
        })}

        {urls.map((u, i) => {
          return (

          );
        })}

  );
};

// Render it
ReactDOM.render(
  <Slider/>,
  document.getElementById("react")
);

Its like this one below another

But I want it to be in one line. How can I do that

Body:
Use marquee tag,

<marquee direction="left" style={{ display:'inline'}}>
  <span
    style={{
      width: { totalWidth },
      display: 'inline-block'
    }}
  >
    {urls.map((u, i) => {
      return (
        <span style={{ padding: "10px" }}>
          <img src={u} width="100px" />
        </span>
      );
    })}
  </span>
  <span
    style={{
      width: { totalWidth },
      display: 'inline-block'

    }}
  >
    {urls.map((u, i) => {
      return (
        <span style={{ padding: "10px" }}>
          <img src={u} width="100px" />
        </span>
      );
    })}
  </span>
</marquee>


问:
How do I go about implementing a strange "class" notation
I'm writing an overengineered matrix calculator in C++ and don't know what this means:

I've never seen something like the box with Valuation = std::map in a class diagram before and don't really know what to look up either. Do i write it as a constructor or what?
And why is there no connection between IntElement and Valuation even though IntElement Clearly uses it?

I have this in the header right now is it what the diagram is looking for?

```<code>class Valuation{

    Valuation(std::map<char,int>);

};
</code>```

答:
Let's see what the UML 2.5 spec says.

9.2.4.1 Classifiers (p. 99)

The default notation for a Classifier is a solid-outline rectangle containing the Classifier’s name, and with compartments separated by horizontal lines below the name. The name of the Classifier should be centered in boldface. For those languages that distinguish between uppercase and lowercase characters, Classifier names should begin with an uppercase character.

I could not find any point in the UML spec that limits names to any given set of (unicode) characters. Maybe for the reason that you would need another book for that. So all we can take from the above is that

Valuation = std::map<char,int>

is an identifier in the same way as e.g.

wiec8736b(/&& 3l?!blurb

would be a (weird) identifier. But in no way it would be some operator clause where you can interpret the character = either as assignment or equality.

tl;dr This is rubbish. Go and ask the author what he meant. Tell him to use either a comment and understandable textual description or to stick to a valid UML notation.

As a side note: The author of that UML diagram uses a notation in the operations compartment which is not defined.

9.6.4 Notation (p. 115)

If shown in a diagram, an Operation is shown as a text string of the form:

```<code>[<visibility>] <name> ‘(‘ [<parameter-list>] ‘)’
   [‘:’ [<return-type>] [‘[‘ <multiplicity-range> ‘]’]
   [‘{‘ <oper-property> [‘,’ <oper-property>]* ‘}’]]
</code>```

where:

<visibility> is the visibility of the Operation (see 7.4).

<visibility> ::= ‘+’ | ‘-‘ | ‘#’ | ‘~’

/ is no defined visibility. Most likely the author took the freedom to use // as common for a comment. That's probably acceptable, but it does not render valid UML.

And as a 2nd side note: that n*n top right also looks suspicios. It's probably a multiplicity and in that format invalid as well. But that's just speculation.

Body:
I'm writing an overengineered matrix calculator in C++ and don't know what this means:

I've never seen something like the box with Valuation = std::map in a class diagram before and don't really know what to look up either. Do i write it as a constructor or what?
And why is there no connection between IntElement and Valuation even though IntElement Clearly uses it?

I have this in the header right now is it what the diagram is looking for?

class Valuation{

    Valuation(std::map<char,int>);

};

Body:
Let's see what the UML 2.5 spec says.

9.2.4.1 Classifiers (p. 99)

The default notation for a Classifier is a solid-outline rectangle containing the Classifier’s name, and with compartments separated by horizontal lines below the name. The name of the Classifier should be centered in boldface. For those languages that distinguish between uppercase and lowercase characters, Classifier names should begin with an uppercase character.

I could not find any point in the UML spec that limits names to any given set of (unicode) characters. Maybe for the reason that you would need another book for that. So all we can take from the above is that

Valuation = std::map<char,int>

is an identifier in the same way as e.g.

wiec8736b(/&& 3l?!blurb

would be a (weird) identifier. But in no way it would be some operator clause where you can interpret the character = either as assignment or equality.

tl;dr This is rubbish. Go and ask the author what he meant. Tell him to use either a comment and understandable textual description or to stick to a valid UML notation.

As a side note: The author of that UML diagram uses a notation in the operations compartment which is not defined.

9.6.4 Notation (p. 115)

If shown in a diagram, an Operation is shown as a text string of the form:

[<visibility>] <name> ‘(‘ [<parameter-list>] ‘)’
   [‘:’ [<return-type>] [‘[‘ <multiplicity-range> ‘]’]
   [‘{‘ <oper-property> [‘,’ <oper-property>]* ‘}’]]

where:

<visibility> is the visibility of the Operation (see 7.4).

<visibility> ::= ‘+’ | ‘-‘ | ‘#’ | ‘~’

/ is no defined visibility. Most likely the author took the freedom to use // as common for a comment. That's probably acceptable, but it does not render valid UML.

And as a 2nd side note: that n*n top right also looks suspicios. It's probably a multiplicity and in that format invalid as well. But that's just speculation.


问:
Pattern match string from column in spark dataframe
I have column in spark dataframe, where i need to search the data with only string containing "xyz" and to stored in new column.

```<code>Input   (need the only field from column having xyz )
col A      colB
A          bid:76563,bid:76589,bid:76591,ms:ms15-097,xyz:3089656
B          xyz:4462915,xyz:4462917,xyz:4462918

Required Output
col A      colB                                                        colC
A          bid:76563,bid:76589,bid:76591,ms:ms15-097,xyz:3089656      xyz:3089656
B          xyz:4462915,xyz:4462917,xyz:4462918                        xyz:4462915,xyz:4462917,xyz:4462918
</code>```

I have 100k rows and cannot used groupby on colA  using collect_list, can you please to get the required output.

Body:
I have column in spark dataframe, where i need to search the data with only string containing "xyz" and to stored in new column.

Input   (need the only field from column having xyz )
col A      colB
A          bid:76563,bid:76589,bid:76591,ms:ms15-097,xyz:3089656
B          xyz:4462915,xyz:4462917,xyz:4462918

Required Output
col A      colB                                                        colC
A          bid:76563,bid:76589,bid:76591,ms:ms15-097,xyz:3089656      xyz:3089656
B          xyz:4462915,xyz:4462917,xyz:4462918                        xyz:4462915,xyz:4462917,xyz:4462918

I have 100k rows and cannot used groupby on colA  using collect_list, can you please to get the required output.

Body:
If you are using Spark 2.4+ then you can split the colB with comma , and use built in functions as expressions

import org.apache.spark.sql.functions._

import spark.implicits._
val df = Seq(
  ("A", "bid:76563,bid:76589,bid:76591,ms:ms15-097,xyz:3089656"),
  ("B", "xyz:4462915,xyz:4462917,xyz:4462918")
).toDF("colA", "colB")

val newDF = df.withColumn("split", split($"colB", ","))
  .selectExpr("*", "filter(split, x -> x LIKE 'xyz%' ) filteredB")
  .withColumn("colC", concat_ws(",", $"filteredB"))
  .drop("split", "filteredB")

newDF.show(false)

Output:

+----+-----------------------------------------------------+-----------------------------------+
|colA|colB                                                 |colC                               |
+----+-----------------------------------------------------+-----------------------------------+
|A   |bid:76563,bid:76589,bid:76591,ms:ms15-097,xyz:3089656|xyz:3089656                        |
|B   |xyz:4462915,xyz:4462917,xyz:4462918                  |xyz:4462915,xyz:4462917,xyz:4462918|
+----+-----------------------------------------------------+-----------------------------------+


问:
Escape characters for XML tags allowed? In what cases?
Is following the valid UPnP Control response? Do they have to escape these characters in the value of <OutProfile>? UPnP device architecture1.1(sec 3.2.4) says that argument value should be escaped if it contains characters like <, & etc. But I think it should not, if its xml. Can anyone refer some standard document that can clear this confusion? My point is that using escaped characters in following case is unnecessary and makes debugging difficult. But I need to explain this point with solid references to my peers.

```<code><?xml version="1.0"?><s:Envelope
xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:SetABCResponse
xmlns:u="urn:schemas-upnp-org:service:Client:1"><OutProfile><cProfile>
 <cID>0</cID>
 <iconPreference>
  <mimetype>image/bmp</mimetype>
  <width>32</width>
  <height>32</height>
  <depth>24</depth>
 </iconPreference>
</cProfile>
</OutProfile></u:SetABCResponse></s:Body></s:Envelope>
</code>```

答:
First, the XML document you posted is well-formed XML.

Second, reading section 3.2.4 of the PDF document you referenced does not allow to infer that your sample XML document violates that UPnP spec. (On the other hand, I cannot say that it conforms to anything in it, because I won't read it.)

Third, the content of <OutProfile> is a text node, or in other words, a character string.

Fourth, when extracted and serizalized without output escaping, it is another well-formed XML document.

```<code><?xml version="1.0"?>
<cProfile>
 <cID>0</cID>
 <iconPreference>
    <mimetype>image/bmp</mimetype>
    <width>32</width>
    <height>32</height>
    <depth>24</depth>
 </iconPreference>
</cProfile>
</code>```

So fifth, it is not unlikely that your fellow developers misunderstood some requirement. On the other hand, there could be application reasons why they want the doc to be exactly like this.

Finally, it you want to embed markup as a text node in an XML document, it's preferable to use CDATA sections because that's easier on the eye. On the other hand, there's no hard reason not to go with character escaping.

Body:
Is following the valid UPnP Control response? Do they have to escape these characters in the value of <OutProfile>? UPnP device architecture1.1(sec 3.2.4) says that argument value should be escaped if it contains characters like <, & etc. But I think it should not, if its xml. Can anyone refer some standard document that can clear this confusion? My point is that using escaped characters in following case is unnecessary and makes debugging difficult. But I need to explain this point with solid references to my peers.

<?xml version="1.0"?><s:Envelope
xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><OutProfile><cProfile>
 <cID>0</cID>
 <iconPreference>
  <mimetype>image/bmp</mimetype>
  <width>32</width>
  <height>32</height>
  <depth>24</depth>
 </iconPreference>
</cProfile>
</OutProfile></s:Body></s:Envelope>

Body:
First, the XML document you posted is well-formed XML.

Second, reading section 3.2.4 of the PDF document you referenced does not allow to infer that your sample XML document violates that UPnP spec. (On the other hand, I cannot say that it conforms to anything in it, because I won't read it.)

Third, the content of <OutProfile> is a text node, or in other words, a character string.

Fourth, when extracted and serizalized without output escaping, it is another well-formed XML document.

<?xml version="1.0"?>
<cProfile>
 <cID>0</cID>
 <iconPreference>
    <mimetype>image/bmp</mimetype>
    <width>32</width>
    <height>32</height>
    <depth>24</depth>
 </iconPreference>
</cProfile>

So fifth, it is not unlikely that your fellow developers misunderstood some requirement. On the other hand, there could be application reasons why they want the doc to be exactly like this.

Finally, it you want to embed markup as a text node in an XML document, it's preferable to use CDATA sections because that's easier on the eye. On the other hand, there's no hard reason not to go with character escaping.


问:
Bulk Insert Error using Knex.js: bind message supplies X parameters, but prepared statement "" requires Y
When using Knex.js to do a large INSERT to PostgreSQL 11.2,

```<code>await knex(myTable).insert(largeArray);
</code>```

we get the error

bind message supplies 47078 parameters, but prepared statement "" requires 9353190

Question: Is there a way to do large inserts in Knex.js without the use of binding? Or is there a parameter in PostgreSQL that we can change to allow large inserts like these?

I believe I have used Sequelize.js ORM to perform similarly sized inserts (1/2 the size of this) without such errors, but prefer not to use an ORM for our current purposes.

Using knex 0.20.9, Node.js 12.14.1, PostgreSQL 11.2, TimescaleDB 1.6.0, Ubuntu 18.04.3

答:
You need to add the data in batches. There is utility function called batchInsert() in knex for helping to do it. Databases has limited statement size / number of bindings. Sequelize probably does batching internally, since it cannot override the limits casted by database server.

If you prefer not to use ORM you could try objection.js it is more like an advanced helper library on top of knex for commonly needed stuff instead of real ORM.

Body:
When using Knex.js to do a large INSERT to PostgreSQL 11.2,

await knex(myTable).insert(largeArray);

we get the error

bind message supplies 47078 parameters, but prepared statement "" requires 9353190

Question: Is there a way to do large inserts in Knex.js without the use of binding? Or is there a parameter in PostgreSQL that we can change to allow large inserts like these?

I believe I have used Sequelize.js ORM to perform similarly sized inserts (1/2 the size of this) without such errors, but prefer not to use an ORM for our current purposes.

Using knex 0.20.9, Node.js 12.14.1, PostgreSQL 11.2, TimescaleDB 1.6.0, Ubuntu 18.04.3


问:
Shortcut for joining two lines
What's the keyboard shortcut for joining two lines in VS Code?

If the cursor is anywhere in the first line of

```<code>    f(foo,
      bar)
</code>```

then when I hit the shortcut, I want to get

```<code>    f(foo, bar)
</code>```

答:
You can simply:

Select the lines to be joined.

Hit Ctrl+Shift+P or F1.

Type join lines.

Title: Shortcut for joining two lines

Body:
What's the keyboard shortcut for joining two lines in VS Code?

If the cursor is anywhere in the first line of

    f(foo,
      bar)

then when I hit the shortcut, I want to get

    f(foo, bar)


问:
Is Php + Java an insane idea or could it be a good choice?
I've been working on web apps for a while now, using php and then Java. Of course I prefere coding in Java, it gives more flexibility, performance and lots of professional components and libraries. But I don't like JSPs very much, PHP was more easy if only limited to front-end and simple Controller functionalities, moreover, PHP is well accepted by designers. So I'm thinking of using Php for View + Some simple controller tasks and Java for the rest of controller code + model. To implement this I would use apache for php and tomcat for J2EE stuff.

What do you think, is this an unnecessary waste of resources? Or does it make sense? How would you bridge the two?

答:
I use both Java and PHP in my daily work, but I've never mixed them as you suggest. I can't really see how it will make an application better, and even though it makes sense to you it probably won't make sense to any other programmer who might end up maintaining your code at some point in the future.

I use PHP for web development due to the fact that PHP has one of the highest "market shares". There's a wide range of CMS systems you can use to develop upon. I like to use Drupal myself, due to the fact that everything that has to do with session handling, user management, database connections and a lot more already is taken care of. All i need to do is to develop a new module. Some might say that Drupal is overkill for small solutions, but I'd say that the user won't notice the difference and you'll save oceans of development time.

I'd stick to the true and tried technology combos!


问:
Is there any C++ function to sort a Map?
I want to know that how can I sort an ordered_map in C++ on the basis of values. Is there any function to do it?

答:
You cannot rearrange elements of (ordered_)map(/set).

You might copy values (and/or keys) into std::vector and std::sort that.


问:
Alternative of Confluent REST Proxy
We have some applications which want to communicate with Kafka using REST API calls to both consume and produce messages. If we do not want to use Confluent REST Proxy, what are the options ?</p>

答:
One possible alternative is the Strimzi Kafka Bridge (https://github.com/strimzi/strimzi-kafka-bridge).
It's part of the broader Strimzi project about running Kafka on Kubernetes but work even running as standalone (when your Kafka cluster is on bare metal).
Of course it's open source and Apache 2.0 licensed.</p>

Title: Alternative of Confluent REST Proxy


问:
R RSelenium/seleniumPipes Unknown error: cannot find Chrome binary
I try to connect with Selenium in R using the Chrome browser on Win10.

I installed Chrome 74.0.3729.61 and added the chrome.exe path to the Environment Variables.

```<code>devtools::install_github("johndharrison/seleniumPipes")
devtools::install_github("ropensci/Rselenium")

#start selenium
selServ <- selenium()
# check ports
selServ$log()$stderr
# conect using port
sel <- remoteDr(browserName = "chrome", port = 4567)
</code>```

gives me the following error message:

```<code>Called  newSession  - Try no:  1  of  3

Called  newSession  - Try no:  2  of  3

Called  newSession  - Try no:  3  of  3
Error detected:
Response status code : 500
Selenium Status code:  13
Selenium Status summary:  UnknownError
Selenium Status detail:  An unknown server-side error occurred while processing the command.
Selenium message:  unknown error: cannot find Chrome binary
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17134 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 40 milliseconds
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: ... , os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_201'
Driver info: driver.version: unknown
Please check the response with errorResponse()
Please check the content returned with errorContent()
</code>```

I found some guidance for Python (Cannot find Chrome binary with Selenium in Python for older versions of Google Chrome) and c# (Selenium WebDriver - Could not find Chrome binary), however, I do not know how to implement it in R.

答:
IMHO you need to download and run chomedriver.exe(if you are using Windows 10, as you mentioned) before to use selenium.

Could you try below solution?

Solution 1. on command window

java -Dwebdriver.chrome.driver="C:/{yourPath}/selenium/chromedriver.exe" -jar "C:/{yourPath}/selenium/selenium-server-standalone-3.141.59.jar" -port 4567

or

Solution 2. direct use R script

rstudioapi::terminalExecute('java -Dwebdriver.chrome.driver="C:/{yourPath}/selenium/chromedriver.exe" -jar "C:/{yourPath}/selenium/selenium-server-standalone-3.141.59.jar" -port 4567')
```

Yes, both are same command exactly. You are able to use anyone you want.

Body:
I try to connect with Selenium in R using the Chrome browser on Win10.

I installed Chrome 74.0.3729.61 and added the chrome.exe path to the Environment Variables.

devtools::install_github("johndharrison/seleniumPipes")
devtools::install_github("ropensci/Rselenium")

#start selenium
selServ <- selenium()
# check ports
selServ$log()$stderr
# conect using port
sel <- remoteDr(browserName = "chrome", port = 4567)

gives me the following error message:

Called  newSession  - Try no:  1  of  3

Called  newSession  - Try no:  2  of  3

Called  newSession  - Try no:  3  of  3
Error detected:
Response status code : 500
Selenium Status code:  13
Selenium Status summary:  UnknownError
Selenium Status detail:  An unknown server-side error occurred while processing the command.
Selenium message:  unknown error: cannot find Chrome binary
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17134 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 40 milliseconds
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: ... , os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_201'
Driver info: driver.version: unknown
Please check the response with errorResponse()
Please check the content returned with errorContent()

I found some guidance for Python (Cannot find Chrome binary with Selenium in Python for older versions of Google Chrome) and c# (Selenium WebDriver - Could not find Chrome binary), however, I do not know how to implement it in R.

Body:
IMHO you need to download and run chomedriver.exe(if you are using Windows 10, as you mentioned) before to use selenium.

Could you try below solution?

Solution 1. on command window

java -Dwebdriver.chrome.driver="C:/{yourPath}/selenium/chromedriver.exe" -jar "C:/{yourPath}/selenium/selenium-server-standalone-3.141.59.jar" -port 4567

or

Solution 2. direct use R script

rstudioapi::terminalExecute('java -Dwebdriver.chrome.driver="C:/{yourPath}/selenium/chromedriver.exe" -jar "C:/{yourPath}/selenium/selenium-server-standalone-3.141.59.jar" -port 4567')

Yes, both are same command exactly. You are able to use anyone you want.


问:
Translation into react nodes
Instead of a translation like in this basic example

```<code>{
    "key": "{{what}} is {{how}}"
}

i18next.t('key', { what: 'i18next', how: 'great' });
// -> "i18next is great"
</code>```

I need a result like

```<code><i>i18next</i> is <i>great</i>
</code>```

as a react node to be rendered as

i18next is great

I could generate the string "i18next is great" and use it with dangerouslySetInnerHTML, but that's ugly and dangerous.

I could split the key like

```<code>{
    "key1": "{{what}}",
    "key2": "is",
    "key3": "{{how}},
}
</code>```

and use

```<code>const params = { what: 'i18next', how: 'great' };
return <>
   <i>{i18next.t('key1', params)}</i>
   {i18next.t('key2', params);}
   <i>{i18next.t('key3', params)}</i>
<>
</code>```

which is safe, but even uglier. Moreover, in general, it requires to split every key with n arguments into 2*n+1 parts, which are related by nothing but a naming convention.

We'd like to apply some formatting (not necessarily ; this was just an example) to all parameters, so we need a better solution. I'm not looking for a library, i18next was just an example. Any idea?

答:
You could try to use the Trans Component

A key looking like

```<code>key: "<0>{{what}}</0> is <2>{{how}}</2>"
</code>```

can be used with

```<code>//  const what = "Pizza";
//  const how = "great";

<Trans i18nKey="key">
  <strong>{{ what }}</strong> is <i>{{ how }}</i>
</Trans>
</code>```

and will produce: Pizza is great

Here is a playground codesandbox

Hope it helps!

Other libraries do it differently - ex: react-intl can handle tags in the lang definitions - this example

Title: Translation into react nodes

Body:
Instead of a translation like in this basic example

{
    "key": "{{what}} is {{how}}"
}

i18next.t('key', { what: 'i18next', how: 'great' });
// -> "i18next is great"

I need a result like

i18next is great

as a react node to be rendered as

i18next is great

I could generate the string "i18next is great" and use it with dangerouslySetInnerHTML, but that's ugly and dangerous.

I could split the key like

{
    "key1": "{{what}}",
    "key2": "is",
    "key3": "{{how}},
}

and use

const params = { what: 'i18next', how: 'great' };
return <>
   {i18next.t('key1', params)}
   {i18next.t('key2', params);}
   {i18next.t('key3', params)}
<>

which is safe, but even uglier. Moreover, in general, it requires to split every key with n arguments into 2*n+1 parts, which are related by nothing but a naming convention.

We'd like to apply some formatting (not necessarily ; this was just an example) to all parameters, so we need a better solution. I'm not looking for a library, i18next was just an example. Any idea?

Body:
You could try to use the Trans Component

A key looking like

key: "<0>{{what}}</0> is <2>{{how}}</2>"

can be used with

//  const what = "Pizza";
//  const how = "great";

<Trans i18nKey="key">
  <strong>{{ what }}</strong> is <i>{{ how }}</i>
</Trans>

and will produce: Pizza is great

Here is a playground codesandbox

Hope it helps!

Other libraries do it differently - ex: react-intl can handle tags in the lang definitions - this example


问:
Application not running from production web server
I have to run a tool from our internal website. There are few inputs that user will provide from UI and then I want to run the tool with user credential. My code works fine when I run it from my local machine, but when I deploy it to production server and try to execute it from there it does not start anything.

Here is my code, any advice will be greatly appreciated.

```<code>            System.Diagnostics.ProcessStartInfo PSI = new System.Diagnostics.ProcessStartInfo(@"D:\run.bat");
            PSI.UserName = "username";
            PSI.Domain = "domain";
            System.Security.SecureString securePwd = new System.Security.SecureString();
            string password = "password";
            foreach (char c in password)
            {
                // Append the character to the password.
                securePwd.AppendChar(c);
            }
            PSI.Password = securePwd;
            PSI.UseShellExecute = false;
            process.StartInfo = PSI;
            PSI.Arguments = SiteId.Text + " " + WebServiceUrl.Text + " " +LogFile.Text;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.Start();
</code>```

答:
I want to close this thread as my problem of running an application from production server solved. But I'm facing issue to run that application using specific user name & password. It always run with whatever identity is set in apppool. So for now if I only use this line it works on app pool default identity

```<code>Process.Start("notepad");
</code>```

But if I use this line of code it don't even start a notepad in that server

```<code>            string password = "XXXXX";
            System.Security.SecureString securePwd = new System.Security.SecureString();
            foreach (char c in password)
            {
                // Append the character to the password.
                securePwd.AppendChar(c);
            }
            Process.Start("notepad", "username", securePwd, "domain");
</code>```

I'm going to ask a separate question on this. Thanks for all who replied.

Body:
I have to run a tool from our internal website. There are few inputs that user will provide from UI and then I want to run the tool with user credential. My code works fine when I run it from my local machine, but when I deploy it to production server and try to execute it from there it does not start anything.

Here is my code, any advice will be greatly appreciated.

            System.Diagnostics.ProcessStartInfo PSI = new System.Diagnostics.ProcessStartInfo(@"D:\run.bat");
            PSI.UserName = "username";
            PSI.Domain = "domain";
            System.Security.SecureString securePwd = new System.Security.SecureString();
            string password = "password";
            foreach (char c in password)
            {
                // Append the character to the password.
                securePwd.AppendChar(c);
            }
            PSI.Password = securePwd;
            PSI.UseShellExecute = false;
            process.StartInfo = PSI;
            PSI.Arguments = SiteId.Text + " " + WebServiceUrl.Text + " " +LogFile.Text;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.Start();

Body:
I want to close this thread as my problem of running an application from production server solved. But I'm facing issue to run that application using specific user name & password. It always run with whatever identity is set in apppool. So for now if I only use this line it works on app pool default identity

Process.Start("notepad");

But if I use this line of code it don't even start a notepad in that server

            string password = "XXXXX";
            System.Security.SecureString securePwd = new System.Security.SecureString();
            foreach (char c in password)
            {
                // Append the character to the password.
                securePwd.AppendChar(c);
            }
            Process.Start("notepad", "username", securePwd, "domain");

I'm going to ask a separate question on this. Thanks for all who replied.


问:
How to store messages in /mosquitto/data MQTT mosquitto?
I am running Docker in AWS ECS and inside the docker container in ECS instance i am running eclipse-mosquitto

I need to store the messages in /mosquitto/data

What i tried

docker exec -it [container name] sh navigated to /mosquitto/config/mosquitto.conf

Modified the mosquitto.conf file and added these lines :

```<code>persistence true
persistence_location /mosquitto/data/
listener 1883
listener 9001
protocol websockets
</code>```

NOTE

I have mounted EFS on /mosquitto so i expect the configuration file to persist and i expect it to use that configuration file next time the container restarts

What i expect

Whenever i am publishing/subscribing to a topic it should store the relevant data under mosquitto/data

答:
First

Logging into a running container and editing the config file won't change the running brokers behaviour.

You would normally need to restart the container (which will revert the changes to the config file)

You can mount your own config file into the container at start time with the following command line option (described on the docker hub page)

```<code>$ docker run -it -p 1883:1883 -p 9001:9001 -v mosquitto.conf:/mosquitto/config/mosquitto.conf eclipse-mosquitto
</code>```

Secondly

mosquitto will not store all messages in the persistence file, that is not what it's for. The file is only used to store QOS 1 or 2 messages that are in flight and retained messages. These messages are normally kept in memory, but are written to the file at regular intervals or at broker shutdown so they can be restored when the broker restarts. Also the format of the persistence file is a custom binary format, it's not something you can easily read.

Body:
I am running Docker in AWS ECS and inside the docker container in ECS instance i am running eclipse-mosquitto

I need to store the messages in /mosquitto/data

What i tried

docker exec -it [container name] sh navigated to /mosquitto/config/mosquitto.conf

Modified the mosquitto.conf file and added these lines :

persistence true
persistence_location /mosquitto/data/
listener 1883
listener 9001
protocol websockets

NOTE

I have mounted EFS on /mosquitto so i expect the configuration file to persist and i expect it to use that configuration file next time the container restarts

What i expect

Whenever i am publishing/subscribing to a topic it should store the relevant data under mosquitto/data

Body:
First

Logging into a running container and editing the config file won't change the running brokers behaviour.

You would normally need to restart the container (which will revert the changes to the config file)

You can mount your own config file into the container at start time with the following command line option (described on the docker hub page)

$ docker run -it -p 1883:1883 -p 9001:9001 -v mosquitto.conf:/mosquitto/config/mosquitto.conf eclipse-mosquitto

Secondly

mosquitto will not store all messages in the persistence file, that is not what it's for. The file is only used to store QOS 1 or 2 messages that are in flight and retained messages. These messages are normally kept in memory, but are written to the file at regular intervals or at broker shutdown so they can be restored when the broker restarts. Also the format of the persistence file is a custom binary format, it's not something you can easily read.


问:
How do you toggle a boolean in a postgres table using knex in one query?
Is it possible to toggle a boolean value in a postgres table using knex in a single query and return the new value?</p>

答:
```<code>await knex('table').update({
    boolCol: knex.raw('NOT ??',  ['boolCol])
  }).returning('boolCol');
</code>```


问:
Python odeint with array in differential equation
I have next first order differential equation (example):

dn/dt=A*n; n(0)=28

When A is constant, it is perfectly solved with python odeint.
But i have an array of different values of A from .txt file [not function,just an array of values]

```<code>A = [0.1,0.2,0.3,-0.4,0.7,...,0.0028]
</code>```

And i want that in each iteration (or in each moment of time t) of solving ode A is a new value from array.
I mean that:
First iteration (or t=0) - A=0.1
Second iteration (or t=1) - A=0.2 and etc from array.

How can i do it with using python odeint?

答:
Yes, you can to that, but not directly in odeint, as that has no event mechanism, and what you propose needs an event-action mechanism.

But you can separate your problem into steps, use inside each step odeint with the now constant A parameter, and then in the end join the steps.

```<code>T = [[0]]
N = [[n0]]
for k in range(len(A)):
    t = np.linspan(k,k+1,11);
    n = odeint(lambda u,t: A[k]*u, [n0],t)
    n0 = n[-1]
    T.append(t[1:])
    N.append(n[1:])

T = np.concatenate(T)
N = np.concatenate(N)
</code>```

If you are satisfied with less efficiency, both in the evaluation of the ODE and in the number of internal steps, you can also implement the parameter as a piecewise constant function.

```<code>tA = np.arange(len(A));
A_func = interp1d(tA, A, kind="zero", fill_value="extrapolate")
T = np.linspace(0,len(A)+1, 10*len(A)+11);
N = odeint(lambda u,t: A_func(t)*u, [n0], T)
</code>```

The internal step size controller works on the assumption that the ODE function is well differentiable to 5th or higher order. The jumps are then seen via the implicit numerical differentiation inherent in the step error calculation as highly oscillatory events, requiring a very small step size. There is some mitigation inside the code that usually allows the solver to eventually step over such a jump, but it will require much more internal steps and thus function evaluations than the first variant above.

Body:
I have next first order differential equation (example):

dn/dt=A*n; n(0)=28

When A is constant, it is perfectly solved with python odeint.
But i have an array of different values of A from .txt file [not function,just an array of values]

A = [0.1,0.2,0.3,-0.4,0.7,...,0.0028]

And i want that in each iteration (or in each moment of time t) of solving ode A is a new value from array.
I mean that:
First iteration (or t=0) - A=0.1
Second iteration (or t=1) - A=0.2 and etc from array.

How can i do it with using python odeint?

Body:
Yes, you can to that, but not directly in odeint, as that has no event mechanism, and what you propose needs an event-action mechanism.

But you can separate your problem into steps, use inside each step odeint with the now constant A parameter, and then in the end join the steps.

T = [[0]]
N = [[n0]]
for k in range(len(A)):
    t = np.linspan(k,k+1,11);
    n = odeint(lambda u,t: A[k]*u, [n0],t)
    n0 = n[-1]
    T.append(t[1:])
    N.append(n[1:])

T = np.concatenate(T)
N = np.concatenate(N)

If you are satisfied with less efficiency, both in the evaluation of the ODE and in the number of internal steps, you can also implement the parameter as a piecewise constant function.

tA = np.arange(len(A));
A_func = interp1d(tA, A, kind="zero", fill_value="extrapolate")
T = np.linspace(0,len(A)+1, 10*len(A)+11);
N = odeint(lambda u,t: A_func(t)*u, [n0], T)

The internal step size controller works on the assumption that the ODE function is well differentiable to 5th or higher order. The jumps are then seen via the implicit numerical differentiation inherent in the step error calculation as highly oscillatory events, requiring a very small step size. There is some mitigation inside the code that usually allows the solver to eventually step over such a jump, but it will require much more internal steps and thus function evaluations than the first variant above.