问:
Designing a recipe database
I'm making a simple recipe app that allows user to create and save their recipes. I'm using SQLite if that makes any difference.

My database knowledge is a bit rusty so I've been looking around for inspiration in order to design an appropriate database.

One example that users here seem to point to is the following schema by Barry Williams: http://www.databaseanswers.org/data_models/recipes/index.htm
This db is overly detailed so I decided to used only the following tables:

```<code>Recipe                 (recipe_id(PK), name, description)
Ingredient             (ingredient_id(PK), name)
Recipe_Steps           (recipe_id(PF), step_number(PK), instructions)
Recipe_Step_Ingredients(recipe_id(PF), step_number(PF), ingredient_id(PF), amount)
</code>```

From my understanding, each ingredient is associated to a step in the recipe whereas I feel like each ingredient should be associated directly to a recipe and that the steps could be an attribute of the recipe table or in a Step table directly related to Recipe. Here would be my design:

```<code>Recipe                 (recipe_id(PK), name, description)
Ingredient             (ingredient_id(PK), name)
Recipe_Steps           (recipe_id(PF), step_number(PK), instructions)
Recipe_Ingredients     (recipe_id(PF), ingredient_id(PF), amount)
</code>```

Mr. Williams knows much more about databases than I do so I don't know if I'm misunderstanding his schema and screwing it up with my version or if this all comes down to personal preference in design.

Is my version of the schema correct, if not, would you please be able to guide me towards the appropriate answer?

Thanks in advance.

答:
Here is the database schema I used to implement the AnyMeal recipe software:</p>

```<code>PRAGMA user_version = 1;
BEGIN;
CREATE TABLE recipes(id INTEGER PRIMARY KEY, title VARCHAR(60) NOT NULL, servings INTEGER NOT NULL, servingsunit VARCHAR(40) NOT NULL);
CREATE TABLE categories(id INTEGER PRIMARY KEY, name VARCHAR(40) UNIQUE NOT NULL);
CREATE TABLE category(recipeid INTEGER NOT NULL, categoryid INTEGER NOT NULL, PRIMARY KEY(recipeid, categoryid), FOREIGN KEY(recipeid) REFERENCES recipes(id), FOREIGN KEY(categoryid) REFERENCES categories(id));
CREATE TABLE ingredients(id INTEGER PRIMARY KEY, name VARCHAR(60) UNIQUE NOT NULL);
CREATE TABLE ingredient(recipeid INTEGER NOT NULL, line INTEGER NOT NULL, amountint INTEGER NOT NULL, amountnum INTEGER NOT NULL, amountdenom INTEGER NOT NULL, amountfloat REAL NOT NULL, unit CHARACTER(2) NOT NULL, ingredientid INTEGER NOT NULL, PRIMARY KEY(recipeid, line), FOREIGN KEY(recipeid) REFERENCES recipes(id), FOREIGN KEY(ingredientid) REFERENCES ingredients(id));
CREATE TABLE instruction(recipeid INTEGER NOT NULL, line INTEGER NOT NULL, txt TEXT NOT NULL, PRIMARY KEY(recipeid, line), FOREIGN KEY(recipeid) REFERENCES recipes(id));
CREATE TABLE ingredientsection(recipeid INTEGER NOT NULL, line INTEGER NOT NULL, title VARCHAR(60) NOT NULL, PRIMARY KEY (recipeid, line), FOREIGN KEY(recipeid) REFERENCES recipes(id));
CREATE TABLE instructionsection(recipeid INTEGER NOT NULL, line INTEGER NOT NULL, title VARCHAR(60) NOT NULL, PRIMARY KEY (recipeid, line), FOREIGN KEY(recipeid) REFERENCES recipes(id));
COMMIT;
</code>```

Title: Designing a recipe database

Body:
I'm making a simple recipe app that allows user to create and save their recipes. I'm using SQLite if that makes any difference.

My database knowledge is a bit rusty so I've been looking around for inspiration in order to design an appropriate database.

One example that users here seem to point to is the following schema by Barry Williams: http://www.databaseanswers.org/data_models/recipes/index.htm
This db is overly detailed so I decided to used only the following tables:

Recipe                 (recipe_id(PK), name, description)
Ingredient             (ingredient_id(PK), name)
Recipe_Steps           (recipe_id(PF), step_number(PK), instructions)
Recipe_Step_Ingredients(recipe_id(PF), step_number(PF), ingredient_id(PF), amount)

From my understanding, each ingredient is associated to a step in the recipe whereas I feel like each ingredient should be associated directly to a recipe and that the steps could be an attribute of the recipe table or in a Step table directly related to Recipe. Here would be my design:

Recipe                 (recipe_id(PK), name, description)
Ingredient             (ingredient_id(PK), name)
Recipe_Steps           (recipe_id(PF), step_number(PK), instructions)
Recipe_Ingredients     (recipe_id(PF), ingredient_id(PF), amount)

Mr. Williams knows much more about databases than I do so I don't know if I'm misunderstanding his schema and screwing it up with my version or if this all comes down to personal preference in design.

Is my version of the schema correct, if not, would you please be able to guide me towards the appropriate answer?

Thanks in advance.

Body:
Here is the database schema I used to implement the AnyMeal recipe software:

PRAGMA user_version = 1;
BEGIN;
CREATE TABLE recipes(id INTEGER PRIMARY KEY, title VARCHAR(60) NOT NULL, servings INTEGER NOT NULL, servingsunit VARCHAR(40) NOT NULL);
CREATE TABLE categories(id INTEGER PRIMARY KEY, name VARCHAR(40) UNIQUE NOT NULL);
CREATE TABLE category(recipeid INTEGER NOT NULL, categoryid INTEGER NOT NULL, PRIMARY KEY(recipeid, categoryid), FOREIGN KEY(recipeid) REFERENCES recipes(id), FOREIGN KEY(categoryid) REFERENCES categories(id));
CREATE TABLE ingredients(id INTEGER PRIMARY KEY, name VARCHAR(60) UNIQUE NOT NULL);
CREATE TABLE ingredient(recipeid INTEGER NOT NULL, line INTEGER NOT NULL, amountint INTEGER NOT NULL, amountnum INTEGER NOT NULL, amountdenom INTEGER NOT NULL, amountfloat REAL NOT NULL, unit CHARACTER(2) NOT NULL, ingredientid INTEGER NOT NULL, PRIMARY KEY(recipeid, line), FOREIGN KEY(recipeid) REFERENCES recipes(id), FOREIGN KEY(ingredientid) REFERENCES ingredients(id));
CREATE TABLE instruction(recipeid INTEGER NOT NULL, line INTEGER NOT NULL, txt TEXT NOT NULL, PRIMARY KEY(recipeid, line), FOREIGN KEY(recipeid) REFERENCES recipes(id));
CREATE TABLE ingredientsection(recipeid INTEGER NOT NULL, line INTEGER NOT NULL, title VARCHAR(60) NOT NULL, PRIMARY KEY (recipeid, line), FOREIGN KEY(recipeid) REFERENCES recipes(id));
CREATE TABLE instructionsection(recipeid INTEGER NOT NULL, line INTEGER NOT NULL, title VARCHAR(60) NOT NULL, PRIMARY KEY (recipeid, line), FOREIGN KEY(recipeid) REFERENCES recipes(id));
COMMIT;


来源: stackexchange

问:
Getting original message from Camel route after splitting
I have a camel route which reads in messages in batches from a queue, processes the message and proceeds to send them one by one to an api and awaits the api response.

I am having issue with retrieving the original message recieved at the start when a 500 response is thrown.

I thought that the splitter returns the original message?

Here is my route:

```<code>    from(gatewayRouteConfig.getInputQueueEndpoint())
            .process(process1)
            .process(process2)
            .setExchangePattern(ExchangePattern.InOnly)
            .choice()
            .when().jsonpath("Message", true)
            .setBody(MESSAGE_WRAPPER_EXTRACTOR)
            .end()
            .split().method(messageSplitter, "splitMessages")
            .log(INFO, "Received Message : ${body}")
            .process(process3)
            .process(validate)
            .process(identity)
            .process(requestProcessor) //where the exception is thrown and the original message that is used in the exception handler is picking up
            .process(someService::gatewayResponseTimeStop)
            .process(someService::endToEndResponseStop)
            .process(someService::markGatewayDeliveryAsSuccess)
            .log("Completed processing...");
</code>```

and here is my exception handler in the same class:

```<code>    private void configureExceptionHandlers() {

        onException(ProviderException.class) //thrown when 500 error occurs
            .useOriginalMessage() //picks message in the form the process(requestProcessor) method recieves it instead of start of route
            .handled(true)
            .log(ERROR, LOGGER, EXCEPTION_MESSAGE_WITH_STACKTRACE)
            .to(DLQ);
</code>```

答:
Solved by adding shareUnitOfWork </p>

```<code>.split().method(activityMessageSplitter, "splitActivityMessages").shareUnitOfWork()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a camel route which reads in messages in batches from a queue, processes the message and proceeds to send them one by one to an api and awaits the api response.

I am having issue with retrieving the original message recieved at the start when a 500 response is thrown.

I thought that the splitter returns the original message?

Here is my route:

    from(gatewayRouteConfig.getInputQueueEndpoint())
            .process(process1)
            .process(process2)
            .setExchangePattern(ExchangePattern.InOnly)
            .choice()
            .when().jsonpath("Message", true)
            .setBody(MESSAGE_WRAPPER_EXTRACTOR)
            .end()
            .split().method(messageSplitter, "splitMessages")
            .log(INFO, "Received Message : ${body}")
            .process(process3)
            .process(validate)
            .process(identity)
            .process(requestProcessor) //where the exception is thrown and the original message that is used in the exception handler is picking up
            .process(someService::gatewayResponseTimeStop)
            .process(someService::endToEndResponseStop)
            .process(someService::markGatewayDeliveryAsSuccess)
            .log("Completed processing...");

and here is my exception handler in the same class:

    private void configureExceptionHandlers() {

        onException(ProviderException.class) //thrown when 500 error occurs
            .useOriginalMessage() //picks message in the form the process(requestProcessor) method recieves it instead of start of route
            .handled(true)
            .log(ERROR, LOGGER, EXCEPTION_MESSAGE_WITH_STACKTRACE)
            .to(DLQ);

Body:
Solved by adding shareUnitOfWork

.split().method(activityMessageSplitter, "splitActivityMessages").shareUnitOfWork()


问:
How to calculate order-complexity of the following algorithm
I'm trying to calculate the time complexity of this code that sums the odd numbers of an array. I have done two methods and now I need to calculate the order complexity O(n)

This one is done by weak post-condition.

```<code>private static int sumaImparDebilit(int t[], int desde, int hasta) {
    if (desde==hasta) {
        if ((t[desde] % 2) == 1) {
            return t[desde];
        }
        return 0;
    }
    if (t[desde]%2 == 1) {
        return (t[desde] + sumaImparDebilit(t,(desde+1),hasta));
    }
    return (sumaImparDebilit(t,(desde+1),hasta));

}
</code>```

This one is done by strong pre-condition.

```<code>private static int sumaImparFortalec(int t[], int hasta, int limite, int parcial) {
    if (hasta <= limite) {
        if ((t[hasta] % 2) == 1) {
            return sumaImparFortalec(t,(hasta + 1),limite,(parcial + t[hasta]));
        } else {
            return sumaImparFortalec(t,(hasta + 1),limite,(parcial));
        }
    }
    else {
        return parcial;
    }
}
</code>```

答:
I don’t know what you mean by “weak” and “strong” conditions, but both have time complexity O(n) and employ (for no good reason) recursion.

Surely this is simplest, and fastest:

```<code>int sum = 0;
for (int i = 0; i < t.length; i++)
    if (t[i] % 2 == 1)
        sum += t[i];
</code>```

Body:
I'm trying to calculate the time complexity of this code that sums the odd numbers of an array. I have done two methods and now I need to calculate the order complexity O(n)

This one is done by weak post-condition.

private static int sumaImparDebilit(int t[], int desde, int hasta) {
    if (desde==hasta) {
        if ((t[desde] % 2) == 1) {
            return t[desde];
        }
        return 0;
    }
    if (t[desde]%2 == 1) {
        return (t[desde] + sumaImparDebilit(t,(desde+1),hasta));
    }
    return (sumaImparDebilit(t,(desde+1),hasta));

}

This one is done by strong pre-condition.

private static int sumaImparFortalec(int t[], int hasta, int limite, int parcial) {
    if (hasta <= limite) {
        if ((t[hasta] % 2) == 1) {
            return sumaImparFortalec(t,(hasta + 1),limite,(parcial + t[hasta]));
        } else {
            return sumaImparFortalec(t,(hasta + 1),limite,(parcial));
        }
    }
    else {
        return parcial;
    }
}

Body:
I don’t know what you mean by “weak” and “strong” conditions, but both have time complexity O(n) and employ (for no good reason) recursion.

Surely this is simplest, and fastest:

int sum = 0;
for (int i = 0; i < t.length; i++)
    if (t[i] % 2 == 1)
        sum += t[i];


问:
Google Drive API Webhook
I have set up a google drive webhook through the "watch property"(https://developers.google.com/drive/api/v2/reference/files/watch) and it is working well and submitting a response as soon as any changes are detected on the watch file. However, the request body (i.e.posted_data=request.get_data( )) as below comes back empty (i.e. None). I have tried other options such as request.json but still empty. Does anyone have any ideas on what I am possibly doing wrong? My Python Flask webhook code is below and works well (i.e. any file updates are posted) except that it returns an empty data type (i.e.posted_data=request.get_data( ) is None). Any suggestions are highly appreciated!</p>

```<code>  from datetime import datetime
  from flask import Flask, request, jsonify
  import pytz

  def get_timestamp():
     dt=datetime.now(pytz.timezone('US/Central'))
     return dt.strftime(("%Y-%m-%d %H:%M:%S"))

  app = Flask(__name__)

  @app.route('/webhook', methods=['POST','GET'])
  def webhook():
      if request.method=='GET':
          return '<h1> This is a webhook listener!</h1>'
      if request.method == 'POST':
          posted_data=request.get_data( )
          print("We have received a request =====>",posted_data)
          cur_date=get_timestamp()
          print("Date and time of update ====>",cur_date)
          http_status=jsonify({'status':'success'}),200
      else:
          http_status='',400
      return http_status

  if __name__ == '__main__':
      app.run(port=5000)
</code>```

答:
The above code works except that google will post their response as headers (i.e. request.headers). See updated code below.</p>

```<code>from datetime import datetime
from flask import Flask, request, jsonify
import pytz

def get_timestamp():
    dt=datetime.now(pytz.timezone('US/Central'))
    return dt.strftime(("%Y-%m-%d %H:%M:%S"))

app = Flask(__name__)

@app.route('/webhook', methods=['POST','GET'])
def webhook():
    if request.method=='GET':
        return '<h1> This is a webhook listener!</h1>'
    if request.method == 'POST':
        print(request.headers)
        cur_date=get_timestamp()
        print("Date and time of update ====>",cur_date)
        http_status=jsonify({'status':'success'}),200
    else:
        http_status='',400
    return http_status

if __name__ == '__main__':
    app.run(port=5000)
</code>```

Title: Google Drive API Webhook

Body:
I have set up a google drive webhook through the "watch property"(https://developers.google.com/drive/api/v2/reference/files/watch) and it is working well and submitting a response as soon as any changes are detected on the watch file. However, the request body (i.e.posted_data=request.get_data( )) as below comes back empty (i.e. None). I have tried other options such as request.json but still empty. Does anyone have any ideas on what I am possibly doing wrong? My Python Flask webhook code is below and works well (i.e. any file updates are posted) except that it returns an empty data type (i.e.posted_data=request.get_data( ) is None). Any suggestions are highly appreciated!

  from datetime import datetime
  from flask import Flask, request, jsonify
  import pytz

  def get_timestamp():
     dt=datetime.now(pytz.timezone('US/Central'))
     return dt.strftime(("%Y-%m-%d %H:%M:%S"))

  app = Flask(__name__)

  @app.route('/webhook', methods=['POST','GET'])
  def webhook():
      if request.method=='GET':
          return '
 This is a webhook listener!
'
      if request.method == 'POST':
          posted_data=request.get_data( )
          print("We have received a request =====>",posted_data)
          cur_date=get_timestamp()
          print("Date and time of update ====>",cur_date)
          http_status=jsonify({'status':'success'}),200
      else:
          http_status='',400
      return http_status

  if __name__ == '__main__':
      app.run(port=5000)

Body:
The above code works except that google will post their response as headers (i.e. request.headers). See updated code below.

from datetime import datetime
from flask import Flask, request, jsonify
import pytz

def get_timestamp():
    dt=datetime.now(pytz.timezone('US/Central'))
    return dt.strftime(("%Y-%m-%d %H:%M:%S"))

app = Flask(__name__)

@app.route('/webhook', methods=['POST','GET'])
def webhook():
    if request.method=='GET':
        return '<h1> This is a webhook listener!</h1>'
    if request.method == 'POST':
        print(request.headers)
        cur_date=get_timestamp()
        print("Date and time of update ====>",cur_date)
        http_status=jsonify({'status':'success'}),200
    else:
        http_status='',400
    return http_status

if __name__ == '__main__':
    app.run(port=5000)


问:
JavaFX: How to change the focus traversal policy?
Is it possible in JavaFX to change the focus traversal policy, like in AWT?

Because the traversal order for two of my HBoxes is wrong.

答:
I had a problem in which a JavaFX Slider was capturing right and left arrow keystrokes that I wanted to be handled by my method keyEventHandler (which handled key events for the Scene).  What worked for me was to add the following line to the code that initialized the Slider:

```<code>slider.setOnKeyPressed(keyEventHandler);
</code>```

and to add

```<code>keyEvent.consume();
</code>```

at the end of keyEventHandler.

ContentLicense: CC BY-SA 3.0

Body:
I had a problem in which a JavaFX Slider was capturing right and left arrow keystrokes that I wanted to be handled by my method keyEventHandler (which handled key events for the Scene).  What worked for me was to add the following line to the code that initialized the Slider:

slider.setOnKeyPressed(keyEventHandler);

and to add

keyEvent.consume();

at the end of keyEventHandler.


问:
Padding missing on one side of scrollable div
Take a look at my snippet.
The parent div has a scrollbar and a child div.
Why is the padding (5px) missing on the right side?

#moh
{
  background:red;
  overflow-x:auto;
  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="moh">
    <div></div>
</div></code>```

To get the bounty I want to know the reason for the missing padding. Maybe there is a name for this phenomenon. Or may it be a browser bug?

It would be excellent to know the part in the CSS or HTML specification which is responsible for the missing padding. But this is not required to get the bounty (Because I know it's hard to find).

答:
It's because of the html behavior of block element like DIV and css overflow property.

By default html elements flow from left to right.

Browsers by Default behavior is -

If parent DIV have any width property (or specific width
inherited) and no css overflow rule is defined, and if child DIV
have defined width which is more than the parent can accommodate,
then it will overflow and will grow beyond the right edge of parent.

To control how Parent Div will deal with overflowing, css overflow
property can be used. overflow:hidden will instruct browser to crop
the exceeding width div at the edge.

overflow-x:auto will instruct browser that, when child element
exceeded width beyond the edge then add scrollbar at x-axis.

So, in the example case above, the child div is having greater width than parent and it is exceeding of the parent. And parent div is having 'overflow-x:auto' rule defined, the scrollbar is appearing upto the edge of parent.

Since padding is inside the edge of the div, it does not considered.

If you want to have padding on all side of the parent div.

Treat the parent div as a grandparent by adding one more div inside a parent and moving child div in it.

On grandparent div you can add required padding and width.
3 On new parent set width:100% which will expand to fit in a grandparent and setting overflow-x:autorule will add scrollbar when the child div expand beyond the parent width.

So, the code will be something like -

#moh
{
  background:red;

  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}

div{
  box-sizing:border-box;
}

#moh div.moh-container{
  width:100%;
  overflow-x:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Grand parent Div for padding and width -->
<div id="moh">
<!-- Parent Div  width 100% to fit in grandparent and overflow rule -->
   <div class='moh-container'>
   <!-- child element with exceeding width -->
     <div></div>
   </div>
</div></code>```

Fiddle -

```<code>https://jsfiddle.net/guruling/471ka569/13/
</code>```

Body:
Take a look at my snippet.
The parent div has a scrollbar and a child div.
Why is the padding (5px) missing on the right side?

#moh
{
  background:red;
  overflow-x:auto;
  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}

To get the bounty I want to know the reason for the missing padding. Maybe there is a name for this phenomenon. Or may it be a browser bug?

It would be excellent to know the part in the CSS or HTML specification which is responsible for the missing padding. But this is not required to get the bounty (Because I know it's hard to find).

Body:
It's because of the html behavior of block element like DIV and css overflow property.

By default html elements flow from left to right.

Browsers by Default behavior is -

If parent DIV have any width property (or specific width
inherited) and no css overflow rule is defined, and if child DIV
have defined width which is more than the parent can accommodate,
then it will overflow and will grow beyond the right edge of parent.

To control how Parent Div will deal with overflowing, css overflow
property can be used. overflow:hidden will instruct browser to crop
the exceeding width div at the edge.

overflow-x:auto will instruct browser that, when child element
exceeded width beyond the edge then add scrollbar at x-axis.

So, in the example case above, the child div is having greater width than parent and it is exceeding of the parent. And parent div is having 'overflow-x:auto' rule defined, the scrollbar is appearing upto the edge of parent.

Since padding is inside the edge of the div, it does not considered.

If you want to have padding on all side of the parent div.

Treat the parent div as a grandparent by adding one more div inside a parent and moving child div in it.

On grandparent div you can add required padding and width.
3 On new parent set width:100% which will expand to fit in a grandparent and setting overflow-x:autorule will add scrollbar when the child div expand beyond the parent width.

So, the code will be something like -

#moh
{
  background:red;

  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}

div{
  box-sizing:border-box;
}

#moh div.moh-container{
  width:100%;
  overflow-x:auto;
}

<!-- Grand parent Div for padding and width -->
<div id="moh">
<!-- Parent Div  width 100% to fit in grandparent and overflow rule -->
   <div class='moh-container'>
   <!-- child element with exceeding width -->
     <div></div>
   </div>
</div>

Fiddle -

https://jsfiddle.net/guruling/471ka569/13/


问:
Fuse Filesystem to communicate with FTP
I am working on a project to create a fuse filesystem in C that communicates with FTP server(only read files not write). I have implemented getattr, read and readdir fuse functions and also added libcurl functionality to it by assuming the path it receives as arguement in the function is the URL of the FTP server. But I don't understand how to pass URL of the ftp server in command line so that fuse_main() function will be called from main function and it will pass the URL as path arguement to those fuse functions.</p>

答:
The simplest thing will be to parse this argument as part of the arguments to your program main function, and then to hand it to the fuse functions. You can even keep it as a static global variable as it's probably not supposed to change. See how it's done the basic "hello" example from the libfuse examples:

https://github.com/libfuse/libfuse/blob/master/example/hello.c#L45

Title: Fuse Filesystem to communicate with FTP


问:
How to pass a boost asio tcp socket to a thread for sending heartbeat to client or server
I am writing a client/server program in boost TCP in which I want to send a HEARTBEAT message to the client every 2 seconds for which I am trying to create a new thread by which I can send it easily but unable to solve it. I am creating thread using boost::thread t(hearbeatSender,sock); this. but giving lots of errors. I also use bind to bind function name with the socket but not resolved the error.

```<code>void process(boost::asio::ip::tcp::socket & sock);
std::string read_data(boost::asio::ip::tcp::socket & sock);
void write_data(boost::asio::ip::tcp::socket & sock,std::string);
void hearbeatSender(boost::asio::ip::tcp::socket & sock);
int main()
{

    unsigned short port_num = 3333;
    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), port_num);
    boost::asio::io_service io;
    try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        boost::asio::ip::tcp::socket sock(io);
        acceptor.accept(sock);
        boost::thread t(hearbeatSender,sock);
        process(sock);
        t.join();

    }
    catch (boost::system::system_error &e)
    {
        std::cout << "Error occured! Error code = " << e.code()
        << ". Message: " << e.what();

        return e.code().value();
    }
  return 0;

}
void process(boost::asio::ip::tcp::socket & sock)
{
    while(1){
    std::string data = read_data(sock);
    std::cout<<"Client's request is: "<<data<<std::endl;
    write_data(sock,data);
    }
}
std::string read_data(boost::asio::ip::tcp::socket & sock)
{
    boost::asio::streambuf buf;
    boost::asio::read_until(sock, buf, "\n");
    std::string data = boost::asio::buffer_cast<const char*>(buf.data());
    return data;
}
void write_data(boost::asio::ip::tcp::socket & sock,std::string data)
{
    boost::system::error_code error;
    std::string msg;
    int ch = data[0]-'0';
    switch(ch)
    {
        case 1: msg = "Case 1\n"; break;
        case 2: msg = "Case 2\n"; break;
        case 3: msg = "Case 3\n"; break;
        case 4: msg = "Case 4\n"; break;
        default: msg  = "Case default\n"; break;
    }
    boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
     if( !error ) {
        std::cout << "Server sent hello message!" << std::endl;
     }
     else {
        std::cout << "send failed: " << error.message() << std::endl;
     }
}
void hearbeatSender(boost::asio::ip::tcp::socket & sock)
{
    boost::system::error_code error;
    std::string msg = "HEARTBEAT";
    while(1)
    {
        sleep(2);
        std::cout<<msg<<std::endl;
        boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
        if( !error ) {
        std::cout << "Server sent HEARTBEAT message!" << std::endl;
        }
        else {
            std::cout << "send failed: " << error.message() << std::endl;
        }
    }
}

</code>```

This is a server-side code for responding to the message of the client and sending heartbeat to the client. This is a synchronous TCP server.

答:
It's more than a little weird to use a heartbeat... "sender" thread with async IO.

What's more, there is no synchronization on the socket object, so that's a data race which is Undefined Behavior.

Finally, this is unsafe:

```<code>    std::string data = boost::asio::buffer_cast<const char*>(buf.data());
</code>```

It assumes that the data() will be NUL-terminated (which isn't true).

Typical, Single Threaded ASIO

You would not spawn threads for timers, but use e.g. boost::asio::deadline_timer or boost::asio::highresolution_timer. It can wait asynchronously, so you can do other tasks on the IO service until it expires.

Similarly you can do the request/response reading/writing asynchronously. The only "complicating" factor is that asynchronous calls don't complete before returning, so you have to make sure the buffers live long enough (they should not be a local variable).

Now, you already have a logical "unit" of lifetime that practically JUMPS out of the code at you:

That just screams to be rewritten as

```<code>struct LifeTimeUnit {
    boost::asio::ip::tcp::socket sock;

    void process();
    std::string read_data();
    void write_data(std::string);
    void hearbeatSender(sock);
};
</code>```

Of course LifeTimeUnit is a funny name, so let's think of a better one: Session seems meaningful!

Now that we have a unit of lifetime, it can handsomely contain other things like buffers and the timer:

```<code>struct Session {
    Session(tcp::socket&& s) : sock(std::move(s)) {}

    void start() {
        hb_wait();
        req_loop();
    }

    void cancel() {
        hbtimer.cancel();
        sock.cancel(); // or shutdown() e.g.
    }

  private:
    bool checked(error_code ec, std::string const& msg = "error") {
        if (ec) {
            std::clog << msg << ": " << ec.message() << "\n";
            cancel();
        }
        return !ec.failed();;
    }

    void req_loop(error_code ec = {}) {
        if (!checked(ec, "req_loop")) {
            async_read_until(sock, buf, "\n",
                    [this](error_code ec, size_t xfr) { on_request(ec, xfr); });
        }
    }

    void on_request(error_code ec, size_t n) {
        if (checked(ec, "on_request")) {
            request.resize(n);
            buf.sgetn(request.data(), n);

            response = "Case " + std::to_string(request.at(0) - '0') + "\n";
            async_write(sock, buffer(response),
                    [this](error_code ec, size_t) { req_loop(ec); });
        }
    }

    void hb_wait(error_code ec = {}) {
        if (checked(ec, "hb_wait")) {
            hbtimer.expires_from_now(2s);
            hbtimer.async_wait([this](error_code ec) { hb_send(ec); });
        }
    }

    void hb_send(error_code ec) {
        if (checked(ec, "hb_send")) {
            async_write(sock, buffer(hbmsg), [this](error_code ec, size_t) { hb_wait(ec); });
        }
    }

    tcp::socket sock;
    boost::asio::high_resolution_timer hbtimer { sock.get_executor() };
    const std::string hbmsg = "HEARTBEAT\n";
    boost::asio::streambuf buf;
    std::string request, response;
};
</code>```

The only public things are start() (actually we don't have a need for cancel() for now, but you know).

The main program can be much un-altered:

```<code>tcp::acceptor acceptor(io, tcp::v4());
acceptor.bind({{}, 3333});
acceptor.listen();

tcp::socket sock(io);
acceptor.accept(sock);

Session sess(std::move(sock));
sess.start(); // does both request loop and the heartbeat

io.run();
</code>```

No more threads, perfect asynchrony! Using bash and netcat to test:

```<code>while sleep 4; do printf "%d request\n" {1..10}; done | netcat localhost 3333
</code>```

Prints:

```<code>host 3333
HEARTBEAT
Case 1
Case 2
Case 3
Case 4
Case 5
Case 6
Case 7
Case 8
Case 9
Case 1
HEARTBEAT
HEARTBEAT
HEARTBEAT
Case 1
Case 2
Case 3
Case 4
Case 5
Case 6
Case 7
Case 8
Case 9
Case 1
^C
</code>```

After stopping the client, the server exits with

```<code>on_request: End of file
hb_send: Operation canceled
</code>```

Single-Thread / Multi-Session

A big advantage is that now you can accept multiple clients on a single server thread. In fact, thousands of them concurrently without a problem.

```<code>int main() {
    boost::asio::thread_pool io(1);
    try {
        tcp::acceptor acceptor(io, tcp::v4());
        acceptor.bind({{}, 3333});
        acceptor.listen();

        std::list<Session> sessions;

        while (true) {
            tcp::socket sock(io);
            acceptor.accept(sock);

            auto& sess = sessions.emplace_back(std::move(sock));
            sess.start(); // does both request loop and the heartbeat

            sessions.remove_if([](Session& s) { return !s.is_active(); });
        }

        io.join();
    } catch (boost::system::system_error& e) {
        std::cout << "Error occured! Error code = " << e.code() << ". Message: " << e.code().message() << "\n";
        return e.code().value();
    }
}
</code>```

Note how we subtly changed our execution-context to a singleton thread pool.
This means we still run all sessions on a single thread, but that's a different thread than running main(), meaning we can continue to accept connections.

To avoid ever-increasing sessions list, we weed out the inactive ones using a trivially implemented is_active() property.

Note that we can ALMOST force a shutdown by doing

```<code>for (auto& sess: sessions)
    sess.cancel();
</code>```

That's ALMOST, because it requires posting the cancel operations on the pool thread:

```<code>for (auto& sess: sessions)
    post(io, [&sess] { sess.cancel(); });
</code>```

This is to avoid racing with any tasks on the IO pool

Since only the main thread ever touches sessions there is no need for locking.

Live On Coliru

Testing with

```<code>struct LifeTimeUnit {
    boost::asio::ip::tcp::socket sock;

    void process();
    std::string read_data();
    void write_data(std::string);
    void hearbeatSender(sock);
};
</code>```0

Prints:

```<code>struct LifeTimeUnit {
    boost::asio::ip::tcp::socket sock;

    void process();
    std::string read_data();
    void write_data(std::string);
    void hearbeatSender(sock);
};
</code>```1

Multi-Threading For The Win?

Now we could add multi-threading. The changes are mild:

we want to associate the socket with a strand (see Why do I need strand per connection when using boost::asio?)

note we already use sock's executor to run the timer

We have to take extra precautions to make all of the public interface in Session thread-safe:

post actions from start() and cancel() on the strand

make the active flag atomic_bool

next up, we simply increase the number of threads in the pool from 1 to, say 10

Note, in practice it rarely makes sense to use more threads than logical cores. Also, in this simple example everything is IO bound, so a single thread probably already serves as well. This is just for demonstration

Live On Coliru

```<code>struct LifeTimeUnit {
    boost::asio::ip::tcp::socket sock;

    void process();
    std::string read_data();
    void write_data(std::string);
    void hearbeatSender(sock);
};
</code>```2

And the changes in Session:

```<code>   void start() {
        active = true;
        post(sock.get_executor(), [this]{
            hb_wait();
            req_loop();
        });
    }

    void cancel() {
        post(sock.get_executor(), [this]{
            hbtimer.cancel();
            sock.cancel(); // or shutdown() e.g.
            active = false;
        });
    }

// ....

    std::atomic_bool active {false};
}
</code>```

Body:
I am writing a client/server program in boost TCP in which I want to send a HEARTBEAT message to the client every 2 seconds for which I am trying to create a new thread by which I can send it easily but unable to solve it. I am creating thread using boost::thread t(hearbeatSender,sock); this. but giving lots of errors. I also use bind to bind function name with the socket but not resolved the error.

void process(boost::asio::ip::tcp::socket & sock);
std::string read_data(boost::asio::ip::tcp::socket & sock);
void write_data(boost::asio::ip::tcp::socket & sock,std::string);
void hearbeatSender(boost::asio::ip::tcp::socket & sock);
int main()
{

    unsigned short port_num = 3333;
    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), port_num);
    boost::asio::io_service io;
    try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        boost::asio::ip::tcp::socket sock(io);
        acceptor.accept(sock);
        boost::thread t(hearbeatSender,sock);
        process(sock);
        t.join();

    }
    catch (boost::system::system_error &e)
    {
        std::cout << "Error occured! Error code = " << e.code()
        << ". Message: " << e.what();

        return e.code().value();
    }
  return 0;

}
void process(boost::asio::ip::tcp::socket & sock)
{
    while(1){
    std::string data = read_data(sock);
    std::cout<<"Client's request is: "<<data<<std::endl;
    write_data(sock,data);
    }
}
std::string read_data(boost::asio::ip::tcp::socket & sock)
{
    boost::asio::streambuf buf;
    boost::asio::read_until(sock, buf, "\n");
    std::string data = boost::asio::buffer_cast<const char*>(buf.data());
    return data;
}
void write_data(boost::asio::ip::tcp::socket & sock,std::string data)
{
    boost::system::error_code error;
    std::string msg;
    int ch = data[0]-'0';
    switch(ch)
    {
        case 1: msg = "Case 1\n"; break;
        case 2: msg = "Case 2\n"; break;
        case 3: msg = "Case 3\n"; break;
        case 4: msg = "Case 4\n"; break;
        default: msg  = "Case default\n"; break;
    }
    boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
     if( !error ) {
        std::cout << "Server sent hello message!" << std::endl;
     }
     else {
        std::cout << "send failed: " << error.message() << std::endl;
     }
}
void hearbeatSender(boost::asio::ip::tcp::socket & sock)
{
    boost::system::error_code error;
    std::string msg = "HEARTBEAT";
    while(1)
    {
        sleep(2);
        std::cout<<msg<<std::endl;
        boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
        if( !error ) {
        std::cout << "Server sent HEARTBEAT message!" << std::endl;
        }
        else {
            std::cout << "send failed: " << error.message() << std::endl;
        }
    }
}

This is a server-side code for responding to the message of the client and sending heartbeat to the client. This is a synchronous TCP server.

Body:
It's more than a little weird to use a heartbeat... "sender" thread with async IO.

What's more, there is no synchronization on the socket object, so that's a data race which is Undefined Behavior.

Finally, this is unsafe:

    std::string data = boost::asio::buffer_cast<const char*>(buf.data());

It assumes that the data() will be NUL-terminated (which isn't true).

Typical, Single Threaded ASIO

You would not spawn threads for timers, but use e.g. boost::asio::deadline_timer or boost::asio::highresolution_timer. It can wait asynchronously, so you can do other tasks on the IO service until it expires.

Similarly you can do the request/response reading/writing asynchronously. The only "complicating" factor is that asynchronous calls don't complete before returning, so you have to make sure the buffers live long enough (they should not be a local variable).

Now, you already have a logical "unit" of lifetime that practically JUMPS out of the code at you:

That just screams to be rewritten as

struct LifeTimeUnit {
    boost::asio::ip::tcp::socket sock;

    void process();
    std::string read_data();
    void write_data(std::string);
    void hearbeatSender(sock);
};

Of course LifeTimeUnit is a funny name, so let's think of a better one: Session seems meaningful!

Now that we have a unit of lifetime, it can handsomely contain other things like buffers and the timer:

struct Session {
    Session(tcp::socket&& s) : sock(std::move(s)) {}

    void start() {
        hb_wait();
        req_loop();
    }

    void cancel() {
        hbtimer.cancel();
        sock.cancel(); // or shutdown() e.g.
    }

  private:
    bool checked(error_code ec, std::string const& msg = "error") {
        if (ec) {
            std::clog << msg << ": " << ec.message() << "\n";
            cancel();
        }
        return !ec.failed();;
    }

    void req_loop(error_code ec = {}) {
        if (!checked(ec, "req_loop")) {
            async_read_until(sock, buf, "\n",
                    [this](error_code ec, size_t xfr) { on_request(ec, xfr); });
        }
    }

    void on_request(error_code ec, size_t n) {
        if (checked(ec, "on_request")) {
            request.resize(n);
            buf.sgetn(request.data(), n);

            response = "Case " + std::to_string(request.at(0) - '0') + "\n";
            async_write(sock, buffer(response),
                    [this](error_code ec, size_t) { req_loop(ec); });
        }
    }

    void hb_wait(error_code ec = {}) {
        if (checked(ec, "hb_wait")) {
            hbtimer.expires_from_now(2s);
            hbtimer.async_wait([this](error_code ec) { hb_send(ec); });
        }
    }

    void hb_send(error_code ec) {
        if (checked(ec, "hb_send")) {
            async_write(sock, buffer(hbmsg), [this](error_code ec, size_t) { hb_wait(ec); });
        }
    }

    tcp::socket sock;
    boost::asio::high_resolution_timer hbtimer { sock.get_executor() };
    const std::string hbmsg = "HEARTBEAT\n";
    boost::asio::streambuf buf;
    std::string request, response;
};

The only public things are start() (actually we don't have a need for cancel() for now, but you know).

The main program can be much un-altered:

tcp::acceptor acceptor(io, tcp::v4());
acceptor.bind({{}, 3333});
acceptor.listen();

tcp::socket sock(io);
acceptor.accept(sock);

Session sess(std::move(sock));
sess.start(); // does both request loop and the heartbeat

io.run();

No more threads, perfect asynchrony! Using bash and netcat to test:

while sleep 4; do printf "%d request\n" {1..10}; done | netcat localhost 3333

Prints:

host 3333
HEARTBEAT
Case 1
Case 2
Case 3
Case 4
Case 5
Case 6
Case 7
Case 8
Case 9
Case 1
HEARTBEAT
HEARTBEAT
HEARTBEAT
Case 1
Case 2
Case 3
Case 4
Case 5
Case 6
Case 7
Case 8
Case 9
Case 1
^C

After stopping the client, the server exits with

on_request: End of file
hb_send: Operation canceled

Single-Thread / Multi-Session

A big advantage is that now you can accept multiple clients on a single server thread. In fact, thousands of them concurrently without a problem.

int main() {
    boost::asio::thread_pool io(1);
    try {
        tcp::acceptor acceptor(io, tcp::v4());
        acceptor.bind({{}, 3333});
        acceptor.listen();

        std::list<Session> sessions;

        while (true) {
            tcp::socket sock(io);
            acceptor.accept(sock);

            auto& sess = sessions.emplace_back(std::move(sock));
            sess.start(); // does both request loop and the heartbeat

            sessions.remove_if([](Session& s) { return !s.is_active(); });
        }

        io.join();
    } catch (boost::system::system_error& e) {
        std::cout << "Error occured! Error code = " << e.code() << ". Message: " << e.code().message() << "\n";
        return e.code().value();
    }
}

Note how we subtly changed our execution-context to a singleton thread pool.
This means we still run all sessions on a single thread, but that's a different thread than running main(), meaning we can continue to accept connections.

To avoid ever-increasing sessions list, we weed out the inactive ones using a trivially implemented is_active() property.

Note that we can ALMOST force a shutdown by doing

for (auto& sess: sessions)
    sess.cancel();

That's ALMOST, because it requires posting the cancel operations on the pool thread:

for (auto& sess: sessions)
    post(io, [&sess] { sess.cancel(); });

This is to avoid racing with any tasks on the IO pool

Since only the main thread ever touches sessions there is no need for locking.

Live On Coliru

Testing with

for a in 3 2 1; do (sleep $a; echo "$a request" | nc 127.0.0.1 3333)& done; time wait

Prints:

Case 1
Case 2
Case 3
HEARTBEAT
HEARTBEAT
...

Multi-Threading For The Win?

Now we could add multi-threading. The changes are mild:

we want to associate the socket with a strand (see Why do I need strand per connection when using boost::asio?)

note we already use sock's executor to run the timer

We have to take extra precautions to make all of the public interface in Session thread-safe:

post actions from start() and cancel() on the strand

make the active flag atomic_bool

next up, we simply increase the number of threads in the pool from 1 to, say 10

Note, in practice it rarely makes sense to use more threads than logical cores. Also, in this simple example everything is IO bound, so a single thread probably already serves as well. This is just for demonstration

Live On Coliru

boost::asio::thread_pool io(10);
try {
    tcp::acceptor acceptor(io, tcp::v4());
    acceptor.set_option(tcp::acceptor::reuse_address(true));
    acceptor.bind({{}, 3333});
    acceptor.listen();

    std::list<Session> sessions;

    while (true) {

        tcp::socket sock(make_strand(io)); // NOTE STRAND!
// ...
// ...

    io.join();

And the changes in Session:

   void start() {
        active = true;
        post(sock.get_executor(), [this]{
            hb_wait();
            req_loop();
        });
    }

    void cancel() {
        post(sock.get_executor(), [this]{
            hbtimer.cancel();
            sock.cancel(); // or shutdown() e.g.
            active = false;
        });
    }

// ....

    std::atomic_bool active {false};
}


问:
Rotating cubes to face the origin using Quaternions
I'm in the process of setting up a relatively simple voxel-based world for a game. The high level idea is to first generate voxel locations following a fibonacci grid, then rotate the cubes such that the outer surface of the fibonacci grid resembles a sphere, and finally size the cubes such that they roughly cover the surface of the sphere (overlap is fine). See below the code for generating the voxels along the fibonacci grid:

```<code>    public static Voxel[] CreateInitialVoxels(int numberOfPoints, int radius)
    {
        float goldenRatio = (1 + Mathf.Sqrt(5)) / 2;
        Voxel[] voxels = new Voxel[numberOfPoints];
        for (int i = 0; i < numberOfPoints; i++)
        {
            float n = i - numberOfPoints / 2;  // Center at zero
            float theta = 2 * Mathf.PI * n / goldenRatio;
            float phi = (Mathf.PI / 2) + Mathf.Asin(2 * n / numberOfPoints);
            voxels[i] = new Voxel(new Location(theta, phi, radius));
        }
        return voxels;
    }
</code>```

This generates a sphere that looks roughly like a staircase

So, my current approach to get this looking a bit more spherical is to basically rotate each cube in each pair of axes, then combine all of the rotations:

```<code>private void DrawVoxel(Voxel voxel, GameObject voxelContainer)
{
    GameObject voxelObject = Instantiate<GameObject>(GetVoxelPrefab());

    voxelObject.transform.position = voxel.location.cartesianCoordinates;
    voxelObject.transform.parent = voxelContainer.transform;

    Vector3 norm = voxel.location.cartesianCoordinates.normalized;

    float xyRotationDegree = Mathf.Atan(norm.y / norm.x) * (180 / Mathf.PI);
    float zxRotationDegree = Mathf.Atan(norm.z / norm.x) * (180 / Mathf.PI);
    float yzRotationDegree = Mathf.Atan(norm.z / norm.y) * (180 / Mathf.PI);

    Quaternion xyRotation = Quaternion.AngleAxis(xyRotationDegree, new Vector3(0, 0, 1));
    Quaternion zxRotation = Quaternion.AngleAxis(zxRotationDegree, new Vector3(0, 1, 0));
    Quaternion yzRotation = Quaternion.AngleAxis(yzRotationDegree, new Vector3(1, 0, 0));

    voxelObject.transform.rotation = zxRotation * yzRotation * xyRotation;
}
</code>```

The primary thing that I am getting caught on is that each of these rotations seems to work fine for me in isolation, but when combining them things tend to go a bit haywire (pictures below) I'm not sure exactly what the issue is. My best guess is that I've made some sign/rotation mismatch in my rotations so they don't combine right. I can get two working, but never all three together.

Above are the pictures of one and two successful rotations, followed by the error mode when I attempt to combine them. Any help either on telling me that the approach I'm following is too convoluted, or helping me understand what the right way to combine these rotations would be would be very helpful. Cartesian coordinate conversion below for reference.

```<code>[System.Serializable]
public struct Location
{
    public float theta, phi, r;
    public Vector3 polarCoordinates;

    public float x, y, z;
    public Vector3 cartesianCoordinates;

    public Location(float theta, float phi, float r)
    {
        this.theta = theta;
        this.phi = phi;
        this.r= r;
        this.polarCoordinates = new Vector3(theta, phi, r);

        this.x = r * Mathf.Sin(phi) * Mathf.Cos(theta);
        this.y = r * Mathf.Sin(phi) * Mathf.Sin(theta);
        this.z = r * Mathf.Cos(phi);
        this.cartesianCoordinates = new Vector3(x, y, z);
    }
}
</code>```

答:
I managed to find a solution to this problem, though it's still not clear to me what the issue with the above code is.

Unity has an extremely handy function called Quaternion.FromToRotation that will generate the appropriate rotation if you simply pass in the appropriate destination vector.

In my case I was able to just do:
voxelObject.transform.rotation = Quaternion.FromToRotation(new Vector3(0, 0, 1), voxel.location.cartesianCoordinates);

Body:
I'm in the process of setting up a relatively simple voxel-based world for a game. The high level idea is to first generate voxel locations following a fibonacci grid, then rotate the cubes such that the outer surface of the fibonacci grid resembles a sphere, and finally size the cubes such that they roughly cover the surface of the sphere (overlap is fine). See below the code for generating the voxels along the fibonacci grid:

    public static Voxel[] CreateInitialVoxels(int numberOfPoints, int radius)
    {
        float goldenRatio = (1 + Mathf.Sqrt(5)) / 2;
        Voxel[] voxels = new Voxel[numberOfPoints];
        for (int i = 0; i < numberOfPoints; i++)
        {
            float n = i - numberOfPoints / 2;  // Center at zero
            float theta = 2 * Mathf.PI * n / goldenRatio;
            float phi = (Mathf.PI / 2) + Mathf.Asin(2 * n / numberOfPoints);
            voxels[i] = new Voxel(new Location(theta, phi, radius));
        }
        return voxels;
    }

This generates a sphere that looks roughly like a staircase

So, my current approach to get this looking a bit more spherical is to basically rotate each cube in each pair of axes, then combine all of the rotations:

private void DrawVoxel(Voxel voxel, GameObject voxelContainer)
{
    GameObject voxelObject = Instantiate<GameObject>(GetVoxelPrefab());

    voxelObject.transform.position = voxel.location.cartesianCoordinates;
    voxelObject.transform.parent = voxelContainer.transform;

    Vector3 norm = voxel.location.cartesianCoordinates.normalized;

    float xyRotationDegree = Mathf.Atan(norm.y / norm.x) * (180 / Mathf.PI);
    float zxRotationDegree = Mathf.Atan(norm.z / norm.x) * (180 / Mathf.PI);
    float yzRotationDegree = Mathf.Atan(norm.z / norm.y) * (180 / Mathf.PI);

    Quaternion xyRotation = Quaternion.AngleAxis(xyRotationDegree, new Vector3(0, 0, 1));
    Quaternion zxRotation = Quaternion.AngleAxis(zxRotationDegree, new Vector3(0, 1, 0));
    Quaternion yzRotation = Quaternion.AngleAxis(yzRotationDegree, new Vector3(1, 0, 0));

    voxelObject.transform.rotation = zxRotation * yzRotation * xyRotation;
}

The primary thing that I am getting caught on is that each of these rotations seems to work fine for me in isolation, but when combining them things tend to go a bit haywire (pictures below) I'm not sure exactly what the issue is. My best guess is that I've made some sign/rotation mismatch in my rotations so they don't combine right. I can get two working, but never all three together.

Above are the pictures of one and two successful rotations, followed by the error mode when I attempt to combine them. Any help either on telling me that the approach I'm following is too convoluted, or helping me understand what the right way to combine these rotations would be would be very helpful. Cartesian coordinate conversion below for reference.

[System.Serializable]
public struct Location
{
    public float theta, phi, r;
    public Vector3 polarCoordinates;

    public float x, y, z;
    public Vector3 cartesianCoordinates;

    public Location(float theta, float phi, float r)
    {
        this.theta = theta;
        this.phi = phi;
        this.r= r;
        this.polarCoordinates = new Vector3(theta, phi, r);

        this.x = r * Mathf.Sin(phi) * Mathf.Cos(theta);
        this.y = r * Mathf.Sin(phi) * Mathf.Sin(theta);
        this.z = r * Mathf.Cos(phi);
        this.cartesianCoordinates = new Vector3(x, y, z);
    }
}


问:
Is it possible to display WP posts that only have both categories
I have a rather challenging project where a finance magazine using WP wishes to digitalize their print offering. As you could expect all articles are uploaded manually by them and divided into various subcategories (e.g. economy, politics etc.). These are then displayed on various category pages. The articles uploaded consist mainly of all the articles that are also found in that months issue.

The aim is to display a table of contents for that issue, allowing readers to directly see a list of the articles published. Basically an identical copy of Bloombergs businessweek: https://www.bloomberg.com/magazine/businessweek/20_23 (side question: anyone can guess how BB does this?)

Now lets say all articles belonging to that issue are given an extra category or possibly term, such as issue 20/05, using a wp_query you could pull in a list of all articles from that issue. In order to then divide them into subcategories, which already exist since thats how they are displayed online, I could then have an extra loop that would pull in all articles that contain the term 20/05, as well as economy.
Is that possible using:
'taxonomy' => 'category',
'term' => 'category-1'
As techincally the term would be the parent category.

This method would require the page to be duplicated and the new term inserted every month, but apart from that its quite easy. Very new to php and wondering if this challenge is maybe beyond me. Any pointers or tips much appreciated.

答:
If I understand correctly, you need to use categories in their default way but also group them by another taxonomy "Issue", for example.
You could register a custom taxonomy: https://developer.wordpress.org/reference/functions/register_taxonomy/ and call it "Issues" for example and then each post can belong to one of the issues.

Then you can use tax_query to filter posts that belong to specific issue:
https://developer.wordpress.org/reference/classes/wp_tax_query/

You can also have a Taxonomy archive template https://developer.wordpress.org/themes/template-files-section/taxonomy-templates/ where you can display issues.


问:
Checking if float is equivalent to an integer value in python
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

```<code>import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num
</code>```

Or do I need to do check within a tolerance instead?

```<code>epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon
</code>```

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

答: Python still uses the same floating point representation and operations C does, so the second one is the correct way.</p>

Body:
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num

Or do I need to do check within a tolerance instead?

epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.


问:
How can I access functions whose names have been shadowed?
I'm creating a subclass of NSDocument. From within the methods of this class, I am unable to call the print(_:String) function that writes to stdout, because it is being shadowed by NSDocument's func print(withSettings: [NSPrintInfo.AttributeKey : Any], showPrintPanel: Bool, delegate: Any?, didPrint: Selector?, contextInfo: UnsafeMutableRawPointer?).

I thought it might be possible to access print by prefixing it with its module name (or using something like global:: in C#), but I was unable to figure out which module it belongs to. The documentation states that print is included in the Swift Standard Library.

How can I access the commonly used print function in this case, and shadowed functions in general?

答: I think that is currently a bug as something similar happened. It was in NSURLSession where some of the datatask functions is inaccessible since it was being over shadowed by functions with the same name start but has different arguments. This is in Xcode 11 swift 5+.


问:
TYPO3 Add Copy and Paste icons to Content Elements
Is it possible to add icons to the left or right side for Content Elements? I would like to move some of the functionality from the contextMenu to the icon bar, is that possible? Perhaps by TSConfig ? See attachment.

答:
I personaly wouldn't add too many button visible by default on the top right of each content, because it will unnecessarily overloads the amount of information on the page module with action buttons that are not the most often used.

In particular, the "paste" button should only appears when there is something in the clipboard, and it now appears everywhere you can paste (you can see one above the content in your screenshot).

Cheers,
Rachel


问:
not able to get user input in javascript from html
I know that I should use document.getelemtbyID but for some reason it has not worked for me. I am trying to build a simple rock paper scissor game where I have a rock paper scissor class and one index.js, I have to pass the username as a function to my class but I am unable to get it working.

Here is my Javascript code -

const userName = document.getElementById(`username`).value;
```

<p>and then i pass it to the class -</p>

```let game=new RockPaperScissors(userName)
game.play(userName); (which is a function in the class)
```

<p>Here is my HTML for taking in username - </p>

```

           <form id="name-form">

                   Your name
                   <input type="text" id="username" class="form-control"
                          name="username" placeholder="Enter Name Here...">
                   <button type="button" id="start-game-button"
                           class="btn btn-primary">Start Game!</button>

           </form>
```

I tried several ways to be able to log in the username in my javascript but it's not working, I tried logging it in console and i still don't see a result.

答:
Try adding type=submit to the button.

```<code><button type="submit" id="start-game-button" class="btn btn-primary">Start Game!</button>
</code>```

Body:
I know that I should use document.getelemtbyID but for some reason it has not worked for me. I am trying to build a simple rock paper scissor game where I have a rock paper scissor class and one index.js, I have to pass the username as a function to my class but I am unable to get it working.

Here is my Javascript code -

const userName = document.getElementById(`username`).value;

and then i pass it to the class -

let game=new RockPaperScissors(userName)
game.play(userName); (which is a function in the class)

Here is my HTML for taking in username -

           <form id="name-form">

                   Your name
                   <input type="text" id="username" class="form-control"
                          name="username" placeholder="Enter Name Here...">
                   <button type="button" id="start-game-button"
                           class="btn btn-primary">Start Game!</button>

           </form>

I tried several ways to be able to log in the username in my javascript but it's not working, I tried logging it in console and i still don't see a result.

Body:
Try adding type=submit to the button.

<button type="submit" id="start-game-button" class="btn btn-primary">Start Game!</button>


问:
Firebase cloud function performance profiler
Is it possible to profile a Firebase cloud function with tools like ClinicJs or the builtin V8 profiler, both locally or remote (deployed)?</p>

答:
There is currently no support in Cloud Functions for profiling tools with deployed functions.

You could certainly try to set up something for local profiling.  I suggest giving it a shot, and if it doesn't work, post an explanation of what you've done and how it's not working the way you expect.


问:
Convert from English Digits to Arabic ones in html page
I need to convert all English numbers that appear in a given HTML page to Arabic ones (to be independent from the user browser encoding). I prefer to use javascript or it will be great if this can be handled using CSS.

I found some pages doing this but I found that the Arabic letters are added with their ASCII representation in the source code. Does it mean that they are applying some sort of a java script function?

Any clue how can I do something like this?

答:
Give this JavaScript function  a string number and it will help you in converting  english to arabic        </p>

```<code>function GetArabicNumber(number) {
            var charIndex = 0;
            var NumericArabic = "";

            while (charIndex < number.length) {
                switch (number[(charIndex)]) {
                    case '.':
                        NumericArabic += ".";
                        break;

                    case '0':
                        NumericArabic += "٠";
                        break;

                    case '1':
                        NumericArabic += "١";
                        break;

                    case '2':
                        NumericArabic += "٢";
                        break;

                    case '3':
                        NumericArabic += "٣";
                        break;

                    case '4':
                        NumericArabic += "٤";
                        break;

                    case '5':
                        NumericArabic += "٥";
                        break;

                    case '6':
                        NumericArabic += "٦";
                        break;

                    case '7':
                        NumericArabic += "٧";
                        break;

                    case '8':
                        NumericArabic += "٨";
                        break;

                    case '9':
                        NumericArabic += "٩";
                        break;

                    default:
                        NumericArabic += number[(charIndex)];
                        break;
                }

                charIndex++;
            }

            return NumericArabic;
        }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Give this JavaScript function  a string number and it will help you in converting  english to arabic

function GetArabicNumber(number) {
            var charIndex = 0;
            var NumericArabic = "";

            while (charIndex < number.length) {
                switch (number[(charIndex)]) {
                    case '.':
                        NumericArabic += ".";
                        break;

                    case '0':
                        NumericArabic += "٠";
                        break;

                    case '1':
                        NumericArabic += "١";
                        break;

                    case '2':
                        NumericArabic += "٢";
                        break;

                    case '3':
                        NumericArabic += "٣";
                        break;

                    case '4':
                        NumericArabic += "٤";
                        break;

                    case '5':
                        NumericArabic += "٥";
                        break;

                    case '6':
                        NumericArabic += "٦";
                        break;

                    case '7':
                        NumericArabic += "٧";
                        break;

                    case '8':
                        NumericArabic += "٨";
                        break;

                    case '9':
                        NumericArabic += "٩";
                        break;

                    default:
                        NumericArabic += number[(charIndex)];
                        break;
                }

                charIndex++;
            }

            return NumericArabic;
        }


问:
How to append text to a div element?
I’m using AJAX to append data to a
 element, where I fill the
 from JavaScript. How can I append new data to the
 without losing the previous data found in it?

答:
The following method is less general than others however it's great when you are sure that your last child node of the div is already a text node. In this way you won't create a new text node using appendData MDN Reference AppendData

```<code>let mydiv = document.getElementById("divId");
let lastChild = mydiv.lastChild;

if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
   lastChild.appendData("YOUR TEXT CONTENT");
</code>```

Title: How to append text to a div element?

Body:
The following method is less general than others however it's great when you are sure that your last child node of the div is already a text node. In this way you won't create a new text node using appendData MDN Reference AppendData

let mydiv = document.getElementById("divId");
let lastChild = mydiv.lastChild;

if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
   lastChild.appendData("YOUR TEXT CONTENT");


答:
You'll want to do the latter. In Programming in Python 3 the following example is given as the most accurate way to compare

```<code>def equal_float(a, b):
    #return abs(a - b) <= sys.float_info.epsilon
    return abs(a - b) <= chosen_value #see edit below for more info
</code>```

Also, since epsilon is the "smallest difference the machine can distinguish between two floating-point numbers", you'll want to use <= in your function.

Edit: After reading the comments below I have looked back at the book and it specifically says "Here is a simple function for comparing floats for equality to the limit of the machines accuracy". I believe this was just an example for comparing floats to extreme precision but the fact that error is introduced with many float calculations this should rarely if ever be used. I characterized it as the "most accurate" way to compare in my answer, which in some sense is true, but rarely what is intended when comparing floats or integers to floats. Choosing a value (ex: 0.00000000001) based on the "problem domain" of the function instead of using sys.float_info.epsilon is the correct approach.

Thanks to S.Lott and Sven Marnach for their corrections, and I apologize if I led anyone down the wrong path.

Title: Checking if float is equivalent to an integer value in python

Body:
You'll want to do the latter. In Programming in Python 3 the following example is given as the most accurate way to compare

def equal_float(a, b):
    #return abs(a - b) <= sys.float_info.epsilon
    return abs(a - b) <= chosen_value #see edit below for more info

Also, since epsilon is the "smallest difference the machine can distinguish between two floating-point numbers", you'll want to use <= in your function.

Edit: After reading the comments below I have looked back at the book and it specifically says "Here is a simple function for comparing floats for equality to the limit of the machines accuracy". I believe this was just an example for comparing floats to extreme precision but the fact that error is introduced with many float calculations this should rarely if ever be used. I characterized it as the "most accurate" way to compare in my answer, which in some sense is true, but rarely what is intended when comparing floats or integers to floats. Choosing a value (ex: 0.00000000001) based on the "problem domain" of the function instead of using sys.float_info.epsilon is the correct approach.

Thanks to S.Lott and Sven Marnach for their corrections, and I apologize if I led anyone down the wrong path.


问:
Python resource_tracker: process died unexpectedly when using multiprocessing 'spawn' method in clear environment
TL;DR: Is this expected behavior?

Not at all similar to Python multiprocessing with start method 'spawn' doesn't work, which is the closest existing question I could find.

To be precise, here is a MWI I am using to test:

import multiprocessing as mp

def fun_computation(x, output):
    acc = 0
    for i in range(x):
        acc += i * i
        output.value = acc

def main():
    shared = mp.Value("i", -1)
    proc = mp.Process(target=fun_computation, args=(100, shared))
    proc.start()
    proc.join()
    assert(shared.value >= 0)
    print(shared.value)

if __name__ == "__main__":
    mp.set_start_method('spawn')
    main()
```

<p>And this is the output I get:</p>

<pre class="lang-sh prettyprint-override"><code>❯ python mptest.py
328350
❯ env -i python mptest.py
/usr/lib/python3.8/multiprocessing/resource_tracker.py:96: UserWarning: resource_tracker: process died unexpectedly, relaunching.  Some resources might leak.
  warnings.warn('resource_tracker: process died unexpectedly, '
Traceback (most recent call last):
  File "mptest.py", line 19, in <module>
    main()
  File "mptest.py", line 14, in main
    assert(shared.value >= 0)
AssertionError
❯ python -V
Python 3.8.3
</code>```

This was tested on an up-to-date Arch Linux installation (at the time of writing). I have yet to test it on Windows and do not have access to macOS. Normal python scripts (e.g., calling fun_computation w/o the multiprocessing) work fine.

Sorry if this example seems a little convoluted; the real error is a byproduct of many more systems interfacing together, but this demonstrates the issue I am having.

TL;DR: Is this expected behavior?

答:
From python >3.x, you can use multiprocessing.get_context() in order to gain a context object to use multiple start methods:

Please try these solutions:

```<code>if __name__ == '__main__':
    shared = mp.Value("i", -1)
    ctx = mp.get_context('spawn')
    q = ctx.Queue() #here q=100
    p = ctx.Process(target=fun_computation, args=(q,shared))
    p.start()
    print(q.get())
    p.join()
</code>```

Or:

```<code>if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=7)
    pool.apply_async(fun_computation, args=(q,shared))
    pool.close()
    pool.join()
</code>```

Body:
TL;DR: Is this expected behavior?

Not at all similar to Python multiprocessing with start method 'spawn' doesn't work, which is the closest existing question I could find.

To be precise, here is a MWI I am using to test:

import multiprocessing as mp

def fun_computation(x, output):
    acc = 0
    for i in range(x):
        acc += i * i
        output.value = acc

def main():
    shared = mp.Value("i", -1)
    proc = mp.Process(target=fun_computation, args=(100, shared))
    proc.start()
    proc.join()
    assert(shared.value >= 0)
    print(shared.value)

if __name__ == "__main__":
    mp.set_start_method('spawn')
    main()

And this is the output I get:

❯ python mptest.py
328350
❯ env -i python mptest.py
/usr/lib/python3.8/multiprocessing/resource_tracker.py:96: UserWarning: resource_tracker: process died unexpectedly, relaunching.  Some resources might leak.
  warnings.warn('resource_tracker: process died unexpectedly, '
Traceback (most recent call last):
  File "mptest.py", line 19, in <module>
    main()
  File "mptest.py", line 14, in main
    assert(shared.value >= 0)
AssertionError
❯ python -V
Python 3.8.3

This was tested on an up-to-date Arch Linux installation (at the time of writing). I have yet to test it on Windows and do not have access to macOS. Normal python scripts (e.g., calling fun_computation w/o the multiprocessing) work fine.

Sorry if this example seems a little convoluted; the real error is a byproduct of many more systems interfacing together, but this demonstrates the issue I am having.

TL;DR: Is this expected behavior?

Body:
From python >3.x, you can use multiprocessing.get_context() in order to gain a context object to use multiple start methods:

Please try these solutions:

if __name__ == '__main__':
    shared = mp.Value("i", -1)
    ctx = mp.get_context('spawn')
    q = ctx.Queue() #here q=100
    p = ctx.Process(target=fun_computation, args=(q,shared))
    p.start()
    print(q.get())
    p.join()

Or:

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=7)
    pool.apply_async(fun_computation, args=(q,shared))
    pool.close()
    pool.join()


问:
Why cant Puppeteer find this link element on page?
^^UPDATE^^

Willing to pay someone to walk me through this, issue posted on codeMentor.io: https://www.codementor.io/u/dashboard/my-requests/9j42b83f0p

I've been looking to click on the element:

```<code><a id="isc_LinkItem_1$20j" href="javascript:void" target="javascript" tabindex="2"
onclick="if(window.isc_LinkItem_1) return isc_LinkItem_1.$30i(event);"
$9a="$9d">Reporting</a>
</code>```

In: https://stackblitz.com/edit/js-nzhhbk
(I haven't included the acutal page because its behind a username & pass)

seems easy enough

----------------------------------------------------------------------

solution1:

```<code>page.click('[id=isc_LinkItem_1$20j]') //not a valid selector
</code>```

solution2:

```<code>const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
} //link not found
</code>```

----------------------------------------------------------------------

I have looked at every which way to select and click it and it says it isn't in the document even though it clearly is (verified by inspecting the html in chrome dev tools and calling:page.evaluate(() => document.body.innerHTML))

**tried to see if it was in an iframe

**tried to select by id

**tried to select by inner text

**tried to console log the body in the browser (console logging not               working verified on the inspect _element) //nothing happens

**tried to create an alert with body text by using:
 _evaluate(() => alert(document)) // nothing happens

**tried to create an alert to test to see if javascript can be injected by:
 _evaluate(() => alert('works')) // nothing happens

**also tried this: How to select elements within an iframe element in Puppeteer // doesn't work

Here is the code I have built so far

```<code>const page = await browser.newPage();

const login1url =
    'https://np3.nextiva.com/NextOSPortal/ncp/landing/landing-platform';
await page.goto(login1url);
await page.waitFor(1000);
await page.type('[name=loginUserName', 'itsaSecretLol');
await page.type('[name=loginPassword]', 'nopeHaha');
await page.click('[type=submit]');
await page.waitForNavigation();
const login3url = 'https://np3.nextiva.com/NextOSPortal/ncp/admin/dashboard';
await page.goto(login3url);
await page.click('[id=hdr_users]');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/manageUsers');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/garrettmrg');
await page.waitFor(2000);
await page.click('[id=loginAsUser]');
await page.waitFor(2000);
await page.click('[id=react-select-5--value');
await page.waitFor(1000);
await page.click('[id=react-select-5--option-0]');
await page.waitFor(20000);
const elementHandle = await page.$('iframe[id=callcenter]');
const frame = await elementHandle.contentFrame();
const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
}
</code>```

答:
It turns out that the previous click triggered a new tab. Puppeteer doesn't move to the new tab, all previous code was being executed on the old tab. To fix all we had to do was find the new tab, select it and execute code, here is the function we wrote to select for the tab:</p>

```<code>async function getTab(regex, browser, targets) {
let pages = await browser.pages();
if (targets) pages = await browser.targets();
let newPage;
for (let i = 0; i < pages.length; i++) {
    const url = await pages[i].url();
    console.log(url);
    if (url.search(regex) !== -1) {
        newPage = pages[i];
        console.log('***');
        console.log(url);
        console.log('***');
        break;
    }
}
console.log('finished');
return newPage;
}
</code>```

Body:
^^UPDATE^^

Willing to pay someone to walk me through this, issue posted on codeMentor.io: https://www.codementor.io/u/dashboard/my-requests/9j42b83f0p

I've been looking to click on the element:

Reporting

In: https://stackblitz.com/edit/js-nzhhbk
(I haven't included the acutal page because its behind a username & pass)

seems easy enough

----------------------------------------------------------------------

solution1:

page.click('[id=isc_LinkItem_1$20j]') //not a valid selector

solution2:

const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
} //link not found

----------------------------------------------------------------------

I have looked at every which way to select and click it and it says it isn't in the document even though it clearly is (verified by inspecting the html in chrome dev tools and calling:page.evaluate(() => document.body.innerHTML))

**tried to see if it was in an iframe

**tried to select by id

**tried to select by inner text

**tried to console log the body in the browser (console logging not               working verified on the inspect _element) //nothing happens

**tried to create an alert with body text by using:
 _evaluate(() => alert(document)) // nothing happens

**tried to create an alert to test to see if javascript can be injected by:
 _evaluate(() => alert('works')) // nothing happens

**also tried this: How to select elements within an iframe element in Puppeteer // doesn't work

Here is the code I have built so far

const page = await browser.newPage();

const login1url =
    'https://np3.nextiva.com/NextOSPortal/ncp/landing/landing-platform';
await page.goto(login1url);
await page.waitFor(1000);
await page.type('[name=loginUserName', 'itsaSecretLol');
await page.type('[name=loginPassword]', 'nopeHaha');
await page.click('[type=submit]');
await page.waitForNavigation();
const login3url = 'https://np3.nextiva.com/NextOSPortal/ncp/admin/dashboard';
await page.goto(login3url);
await page.click('[id=hdr_users]');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/manageUsers');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/garrettmrg');
await page.waitFor(2000);
await page.click('[id=loginAsUser]');
await page.waitFor(2000);
await page.click('[id=react-select-5--value');
await page.waitFor(1000);
await page.click('[id=react-select-5--option-0]');
await page.waitFor(20000);
const elementHandle = await page.$('iframe[id=callcenter]');
const frame = await elementHandle.contentFrame();
const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
}

Body:
It turns out that the previous click triggered a new tab. Puppeteer doesn't move to the new tab, all previous code was being executed on the old tab. To fix all we had to do was find the new tab, select it and execute code, here is the function we wrote to select for the tab:

async function getTab(regex, browser, targets) {
let pages = await browser.pages();
if (targets) pages = await browser.targets();
let newPage;
for (let i = 0; i < pages.length; i++) {
    const url = await pages[i].url();
    console.log(url);
    if (url.search(regex) !== -1) {
        newPage = pages[i];
        console.log('***');
        console.log(url);
        console.log('***');
        break;
    }
}
console.log('finished');
return newPage;
}


问:
Constantly read updated XML file with Javascript
I want to constantly observe the content of a changing XML file by setting an interval, which calls the reader.readAsText() function. I can access the data, till the XML file gets updated the first time.

From then the reader throws a DOMException named "NotReadableError", when trying to read the file. Then I have to reopen the file via the open file dialog, which I don't want to.

Any suggestions? Is this even possible?

Simplified code looks like this:

```<code>window.onload = function() {
  setInterval(checkFile, 200);
}

function checkFile() {
  var input = document.getElementById("file");
  var file = input.files[0];
  var reader = new FileReader();
  reader.onload = function(event) {
      //stuff
    };
    reader.readAsText(file);
  }
}
</code>```

best regards.

答:
There are two reasons for a NotReadableError:

the snapshot state of a File or a Blob does not match the state of the underlying storage, this is the SnapshotState failure reason.

It appears this could mean that if the state of a File changes after being picked in the browser changes, then it can no-longer be read.

The error can also happen if:

the File or Blob cannot be read, typically due due to permission problems that occur after a snapshot state has been established (e.g. concurrent lock on the underlying storage with another application) then this is the FileLock failure reason.

Perhaps you're also hitting this case, since you're trying to read the file as it's being updated, and your operating system could be employing file locks.

It's unclear which of these cases is what you're encountering, and there doesn't appear to be anything in spec to figure out which reason caused this error. I suspect the snapshot issue is what you're encountering, and the browser API for File is not going to allow you to do what you're hoping to do. Perhaps there's another solution to the root thing you're trying to solve.

Body:
I want to constantly observe the content of a changing XML file by setting an interval, which calls the reader.readAsText() function. I can access the data, till the XML file gets updated the first time.

From then the reader throws a DOMException named "NotReadableError", when trying to read the file. Then I have to reopen the file via the open file dialog, which I don't want to.

Any suggestions? Is this even possible?

Simplified code looks like this:

window.onload = function() {
  setInterval(checkFile, 200);
}

function checkFile() {
  var input = document.getElementById("file");
  var file = input.files[0];
  var reader = new FileReader();
  reader.onload = function(event) {
      //stuff
    };
    reader.readAsText(file);
  }
}

best regards.


问:
Terraform and AWS: modify an existing policy
I have an existing IAM policy attached to a role. Each time a new secret is created in the Secrets Manager, I need to append the new ARN to the policy. Can this be done with Terraform? I've managed to import the policy into the terraform.state file, but I don't know how to:
1) Append a new ARN inside the "Resources" list
2) Push the change to AWS

This is how the policy looks now:

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "secretsmanager:GetSecretValue",
        "Resource": [
            "SECRET_ARN_1",
            "SECRET_ARN_2",
            "SECRET_ARN_3"
        ]
    },
    {
        "Effect": "Allow",
        "Action": "kms:Decrypt",
        "Resource": "KMS_ARN"
    }
]
</code>```

}

And this is how I need it to look:

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "secretsmanager:GetSecretValue",
        "Resource": [
            "SECRET_ARN_1",
            "SECRET_ARN_2",
            "SECRET_ARN_3",
            "MY_BRAND_NEW_SECRET_ARN"
        ]
    },
    {
        "Effect": "Allow",
        "Action": "kms:Decrypt",
        "Resource": "KMS_ARN"
    }
]
</code>```

}

The following import is working by importing the existing policy to the object aws_iam_policy.mysimplepolicy, but I don't know how to proceed from here.

```<code>terraform import aws_iam_policy.mysimplepolicy <MY_POLICY_ARN>
</code>```

答: Another, possibly easier, option would be to use tag based authorization. That is to say, modify the policy to only grant access to secrets with a specific tag and then when you create the secret add that tag. There are also example docs for doing this.</p>

Body:
I have an existing IAM policy attached to a role. Each time a new secret is created in the Secrets Manager, I need to append the new ARN to the policy. Can this be done with Terraform? I've managed to import the policy into the terraform.state file, but I don't know how to:
1) Append a new ARN inside the "Resources" list
2) Push the change to AWS

This is how the policy looks now:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "secretsmanager:GetSecretValue",
        "Resource": [
            "SECRET_ARN_1",
            "SECRET_ARN_2",
            "SECRET_ARN_3"
        ]
    },
    {
        "Effect": "Allow",
        "Action": "kms:Decrypt",
        "Resource": "KMS_ARN"
    }
]

}

And this is how I need it to look:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "secretsmanager:GetSecretValue",
        "Resource": [
            "SECRET_ARN_1",
            "SECRET_ARN_2",
            "SECRET_ARN_3",
            "MY_BRAND_NEW_SECRET_ARN"
        ]
    },
    {
        "Effect": "Allow",
        "Action": "kms:Decrypt",
        "Resource": "KMS_ARN"
    }
]

}

The following import is working by importing the existing policy to the object aws_iam_policy.mysimplepolicy, but I don't know how to proceed from here.

terraform import aws_iam_policy.mysimplepolicy <MY_POLICY_ARN>


问:
How can I tell what is taking my request so long?
So here's the final line of my request:

```<code>Completed in 9209ms (View: 358, DB: 1582)
</code>```

So I need to figure out what's holding up the request.  This request can get to be upwards of a minute, so I really need to figure this one out.  If the DB and View take 1.9 seconds, then that means there's 7.2 seconds that are unaccounted for in the log.  How can I further analyze other parts of the code?  It would be great to know if, say, there was a single callback that's largely responsible for the delay.

答:
Are you materializing a lot of records from the database?  Query time might not be much, but if, say, I selected 10,000 records from the database using a very simple and fast query, I'd still expect my page load time to be high, since it would spend a considerable amount of time hydrating the large recordset.

I'd suggest running some profiling tests (rake test:profile).  These should give you an indication of where most of the time is being spent.  You'll probably find it's just one or two method calls that are being invoked with excessive frequency.

Body:
So here's the final line of my request:

Completed in 9209ms (View: 358, DB: 1582)

So I need to figure out what's holding up the request.  This request can get to be upwards of a minute, so I really need to figure this one out.  If the DB and View take 1.9 seconds, then that means there's 7.2 seconds that are unaccounted for in the log.  How can I further analyze other parts of the code?  It would be great to know if, say, there was a single callback that's largely responsible for the delay.


问:
MongoDB Aggregation function
I have the following JSON Documents in Mongo collection named "Movies"

```<code>{
      "_id": "5ed0c9700b9e8b0e2c542054",
      "movie_name": "Jake 123",
      "score": 20,
      "director": "Jake"
    },
    {
      "_id": "5ed0a9840b9e8b0e2c542053",
      "movie_name": "Avatar",
      "director": "James Cameroon",
      "score": 50,
      "boxoffice": [
        {
          "territory": "US",
          "gross": 2000
        },
        {
          "territory": "UK",
          "gross": 1000
        }
      ]
    },
    {
      "_id": "5ed0a9630b9e8b0e2c542052",
      "movie_name": "Titanic",
      "score": 100,
      "director": "James Cameroon",
      "boxoffice": [
        {
          "territory": "US",
          "gross": 1000
        },
        {
          "territory": "UK",
          "gross": 500
        }
      ],
      "actors": [
        "Kate Winselet",
        "Leonardo De Caprio",
        "Rajinikanth",
        "Kamalhaasan"
      ]
    }
</code>```

I run the below query which finds the maximum collection of a country of various movies. My intention is to find the maximum collection and the corresponding territory.

```<code>db.movies.aggregate([
    {$match: {"boxoffice" : { $exists: true, $ne : []}}},
    {$project: {
                "title":"$movie_name", "max_boxoffice": {$max : "$boxoffice.gross"},
                "territory" : "$boxoffice.territory" } }
          ])
</code>```

I get the result as follows. How do I get the correct territory that corresponds to the collection?

```<code>{
    "_id" : ObjectId("5ed0a9630b9e8b0e2c542052"),
    "title" : "Titanic",
    "max_boxoffice" : 1000,
    "territory" : [
        "US",
        "UK"
    ]
},
{
    "_id" : ObjectId("5ed0a9840b9e8b0e2c542053"),
    "title" : "Avatar",
    "max_boxoffice" : 2000,
    "territory" : [
        "US",
        "UK"
    ]
}
</code>```

Expected output:

Avatar and Titanic has collected more money in US. I wanted territories to display the values of them

```<code>{
        "_id" : ObjectId("5ed0a9630b9e8b0e2c542052"),
        "title" : "Titanic",
        "max_boxoffice" : 1000,
        "territory" : "US"
    },
    {
        "_id" : ObjectId("5ed0a9840b9e8b0e2c542053"),
        "title" : "Avatar",
        "max_boxoffice" : 2000,
        "territory" : "US"

    }
</code>```

答:
For this specific requirement, you can use $set (aggregation). $set appends new fields to existing documents. and we can include one or more $set stages in an aggregation operation to achieve this like:

```<code>db.movies.aggregate([
  {
    $match: { "boxoffice": { $exists: true, $ne: [] } }
  },
  {
    $set: {
      boxoffice: {
        $filter: {
          input: "$boxoffice",
          cond: { $eq: ["$$this.gross", { $max: "$boxoffice.gross" }]}
        }
      }
    }
  },
  {
    $set: {
      boxoffice: { $arrayElemAt: ["$boxoffice", 0] }
    }
  },
  {
    $project: {
      "title": "$movie_name",
      "max_boxoffice": "$boxoffice.gross",
      "territory": "$boxoffice.territory"
    }
  }
])
</code>```

Mongo Playground

Title: MongoDB Aggregation function

Body:
I have the following JSON Documents in Mongo collection named "Movies"

{
      "_id": "5ed0c9700b9e8b0e2c542054",
      "movie_name": "Jake 123",
      "score": 20,
      "director": "Jake"
    },
    {
      "_id": "5ed0a9840b9e8b0e2c542053",
      "movie_name": "Avatar",
      "director": "James Cameroon",
      "score": 50,
      "boxoffice": [
        {
          "territory": "US",
          "gross": 2000
        },
        {
          "territory": "UK",
          "gross": 1000
        }
      ]
    },
    {
      "_id": "5ed0a9630b9e8b0e2c542052",
      "movie_name": "Titanic",
      "score": 100,
      "director": "James Cameroon",
      "boxoffice": [
        {
          "territory": "US",
          "gross": 1000
        },
        {
          "territory": "UK",
          "gross": 500
        }
      ],
      "actors": [
        "Kate Winselet",
        "Leonardo De Caprio",
        "Rajinikanth",
        "Kamalhaasan"
      ]
    }

I run the below query which finds the maximum collection of a country of various movies. My intention is to find the maximum collection and the corresponding territory.

db.movies.aggregate([
    {$match: {"boxoffice" : { $exists: true, $ne : []}}},
    {$project: {
                "title":"$movie_name", "max_boxoffice": {$max : "$boxoffice.gross"},
                "territory" : "$boxoffice.territory" } }
          ])

I get the result as follows. How do I get the correct territory that corresponds to the collection?

{
    "_id" : ObjectId("5ed0a9630b9e8b0e2c542052"),
    "title" : "Titanic",
    "max_boxoffice" : 1000,
    "territory" : [
        "US",
        "UK"
    ]
},
{
    "_id" : ObjectId("5ed0a9840b9e8b0e2c542053"),
    "title" : "Avatar",
    "max_boxoffice" : 2000,
    "territory" : [
        "US",
        "UK"
    ]
}

Expected output:

Avatar and Titanic has collected more money in US. I wanted territories to display the values of them

{
        "_id" : ObjectId("5ed0a9630b9e8b0e2c542052"),
        "title" : "Titanic",
        "max_boxoffice" : 1000,
        "territory" : "US"
    },
    {
        "_id" : ObjectId("5ed0a9840b9e8b0e2c542053"),
        "title" : "Avatar",
        "max_boxoffice" : 2000,
        "territory" : "US"

    }

Body:
For this specific requirement, you can use $set (aggregation). $set appends new fields to existing documents. and we can include one or more $set stages in an aggregation operation to achieve this like:

db.movies.aggregate([
  {
    $match: { "boxoffice": { $exists: true, $ne: [] } }
  },
  {
    $set: {
      boxoffice: {
        $filter: {
          input: "$boxoffice",
          cond: { $eq: ["$$this.gross", { $max: "$boxoffice.gross" }]}
        }
      }
    }
  },
  {
    $set: {
      boxoffice: { $arrayElemAt: ["$boxoffice", 0] }
    }
  },
  {
    $project: {
      "title": "$movie_name",
      "max_boxoffice": "$boxoffice.gross",
      "territory": "$boxoffice.territory"
    }
  }
])

Mongo Playground


问:
Splitting a string using a next line regex followed by a digit (JAVA)
I have the following string which I need to split on space, commas, and next line character.
Sample string: "./homework2 3,phone3,desc3,brand4\n4,phone4,desc4,brand4\n5,phone5,desc5,brand5"

I am using split function as: .split("[,\\s+\\n+]"); but I am unable to get the required out put. The program keeps reading brand4\n4 as one substring.

Help would be appreciated.

答:
Try this, it should work the way you want:

```<code>.split(" |,|\\n");
</code>```

This splits the string at a space (" "), a comma, or a next line character. Use the or operator to add more entries if needed.

Body:
Try this, it should work the way you want:

.split(" |,|\\n");

This splits the string at a space (" "), a comma, or a next line character. Use the or operator to add more entries if needed.


问:
Implementation of ceil() and floor()
Just curious how are these implemented. I can't see where I would start. Do they work directly on the float's/double's bits?

Also where can I find the source code of functions from math.h? All I find are either headers with prototypes or files with functions that call other functions from somewhere else.

EDIT: Part of the message was lost after editing the title. What I meant in particular were the ceil() and floor() functions.

答:
If you're interested in seeing source code for algorithms for this kind of thing, then fdlibm - the "Freely Distributable libm", originally from Sun, and the reference implementation for Java's math libraries - might be a good place to start.  (For casual browsing, it's certainly a better place to start than GNU libc, where the pieces are scattered around various subdirectories - math/, sysdeps/ieee754/, etc.)

fdlibm assumes that it's working with an IEEE 754 format double, and if you look at the implementations - for example, the core of the implementation of log() - you'll see that they use all sorts of clever tricks, often using a mixture of both standard double arithmetic, and knowledge of the bit representation of a double.

(And if you're interested in algorithms for supporting basic IEEE 754 floating point arithmetic, such as might be used for processors without hardware floating point support, take a look at John R. Hauser's SoftFloat.)

As for your edit: in general, ceil() and floor() might well be implemented in hardware; for example, on x86, GCC (with optimisations enabled) generates code using the frndint instruction with appropriate fiddling of the FPU control word to set the rounding mode.  But fdlibm's pure software implementations (s_ceil.c, s_floor.c) do work using the bit representation directly.

Title: Implementation of ceil() and floor()


问:
Export Logs From Azure Log Analytics
So I am building a application in azure and I am using Azure Log Analytics and I am trying to find s good way for people on my team that dont have access to azure but need to be able to access the Logs. Does anyone have simple fast ways to create something like this. Good techinologies good ways to give people access to it?</p>

答:
So there are a few ways to do this:

You can use the ALA api to generate a home grown log portal

There are multiple SAS options out there

DataDog

Splunk

AppDynamics

Power Bi

Not specifically logs but prometheus and grafa for matrics and alerts and its dirt cheap compared to app insights

Title: Export Logs From Azure Log Analytics