问:
Automation testing for dynamic coordinates appearing in map using TestCafe or codeceptjs or cypress
I would like to automate the testing using testcafe or codeceptjs for a test case in which an item is displayed on correct address in map after clicking on it.
expected behavior for test case: User is taken to correct address on map after clicking the specific item</p>

答: Here is an example of how to test a Leaflet-based map using TestCafe: How to test leaflet based maps using testcafe?.</p>


来源: stackexchange

问:
How can I split a HAML template into different partials/includes in PHP?
I am a PHP dev trying to start using HAML, using this implementation:
http://phphaml.sourceforge.net/

HAML looks awesome, but I don't understand if/how it supports partials (or includes, as they are called in the PHP world).

I would like to have a master template HAML file that then goes and loads up a bunch of partials for all the little pieces. (Then I can reuse those pieces in other templates too.)

In PHP or Ruby this would be really easy, is there any way to do this with HAML? thanks!

dylan

答:
Quite an old question, but I've updated the source code of phpHaml to reflect this new functionality!

Check out the commit @github
https://github.com/endorama/phphaml/commit/8d95d5ebff06275db8b14438e566c6e41ec91b7f

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Python plotly: Dates in other languages
I've inserted a dataset in plotly in order to plot a time-series graph. Plotly converted it into a datetime object adequately but the display is in english and I need it to be in spanish. Can I do that? How?

Here's the code:

trace1 = Scatter(
  x=['2015-01-01', '2015-01-02'],
  y=['14.7414', '14.7414'],
  name='Precio del dlar',
  error_y=ErrorY(
    color='rgb(0,116,217)',
    thickness=1, width=1
  ),
  error_x=ErrorX(
    copy_ystyle=True
  ),
  marker=Marker(
    color='rgb(0,116,217)',
    size=8,
    symbol='circle'
  ),
  line=Line(
    color='rgb(0,116,217)',
    width=2
  ),
  xsrc='rafaeles:2294:78082d',
  ysrc='rafaeles:2294:7b41b5'
)
```

The date format that I inserted is x. Plotly coded it as Jan 15, but I need that to be in spanish.

答:
This is an old question but maybe it might be useful for someone with the same problem than Rafael and me. I had this problem and I asked to the Plotly Community about how I can change the date language and the answers has been really helpful.

Note that I edited your question to insert your code in a code block to ease the reading of it.

First of all try to check what is your current locale settings with the locale module of Python:

import locale
locale.getlocale()
```

<p>If you get something different than the one you want to use, you can set the one you want for dates and time with <code>locale.setlocale()</code>. For example:</p>

<pre class="lang-py prettyprint-override"><code>locale.setlocale(locale.LC_TIME, 'es_ES')
</code>```

You can test this new locale works fine testing it with the datetime module as follows:

```<code>import datetime
today = datetime.datetime.now()

datetime.datetime(2020, 2, 14, 10, 33, 56, 487228)

today.strftime('%A %d de %B, %Y')

'viernes 14 de febrero, 2020'
</code>```

Then you can try to reformat your data using datetime and strftime. In your case it might be something similar to:

dates = [datetime.datetime(2015, 1, 1).strftime('%A %d de %B, %Y'),
         datetime.datetime(2015, 1, 2).strftime('%A %d de %B, %Y')]
```

<p>This works for me on iPython:</p>

```In [1]: import locale

In [2]: locale.setlocale(locale.LC_TIME, "es_ES.utf8")
Out[2]: 'es_ES.utf8'

In [3]: import datetime

In [4]: dates = [datetime.datetime(2015, 1, 1).strftime('%A %d de %B, %Y'),
   ...:          datetime.datetime(2015, 1, 2).strftime('%A %d de %B, %Y')]

In [5]: dates
Out[5]: ['jueves 01 de enero, 2015', 'viernes 02 de enero, 2015']
```

<p>Then if you want to use it in <code>x</code> axis, you can call <code>dates</code> inside <code>x</code>:</p>

<pre class="lang-py prettyprint-override"><code>trace1 = Scatter(
  x=dates,
  y=['14.7414', '14.7414'],
  ...
)
</code>```

It works for me! And I hope it works for you too.

If you need a different format for the date I recommend you to read the documentation about date-time microformats of D3. I also recommend you to read the thread How to change date language? I opened on Plotly Community Forum, because the answers are very useful and are the ones which helped me to solve my issue and to answer this question. You can also check this notebook shared in the thread, in which one of the users who answer me show how to solve the issue if you are using a pandas dataframe.

Excuse me for a lot of this stuff I am linking, but it might be very useful too to read about the methods to update axis in Plotly documentation, because you can update the format of the axis you want with as follows:

fig.update_xaxes(tickformat='%d-%b-%Y')
```

I want to credit to empet and eliasdabbas, users of the Plotly Community, for their answers!

ContentLicense: CC BY-SA 4.0

Title: Python plotly: Dates in other languages

Body:
I've inserted a dataset in plotly in order to plot a time-series graph. Plotly converted it into a datetime object adequately but the display is in english and I need it to be in spanish. Can I do that? How?

Here's the code:

trace1 = Scatter(
  x=['2015-01-01', '2015-01-02'],
  y=['14.7414', '14.7414'],
  name='Precio del dlar',
  error_y=ErrorY(
    color='rgb(0,116,217)',
    thickness=1, width=1
  ),
  error_x=ErrorX(
    copy_ystyle=True
  ),
  marker=Marker(
    color='rgb(0,116,217)',
    size=8,
    symbol='circle'
  ),
  line=Line(
    color='rgb(0,116,217)',
    width=2
  ),
  xsrc='rafaeles:2294:78082d',
  ysrc='rafaeles:2294:7b41b5'
)

The date format that I inserted is x. Plotly coded it as Jan 15, but I need that to be in spanish.

Body:
This is an old question but maybe it might be useful for someone with the same problem than Rafael and me. I had this problem and I asked to the Plotly Community about how I can change the date language and the answers has been really helpful.

Note that I edited your question to insert your code in a code block to ease the reading of it.

First of all try to check what is your current locale settings with the locale module of Python:

import locale
locale.getlocale()

If you get something different than the one you want to use, you can set the one you want for dates and time with locale.setlocale(). For example:

locale.setlocale(locale.LC_TIME, 'es_ES')

You can test this new locale works fine testing it with the datetime module as follows:

import datetime
today = datetime.datetime.now()

datetime.datetime(2020, 2, 14, 10, 33, 56, 487228)

today.strftime('%A %d de %B, %Y')

'viernes 14 de febrero, 2020'

Then you can try to reformat your data using datetime and strftime. In your case it might be something similar to:

dates = [datetime.datetime(2015, 1, 1).strftime('%A %d de %B, %Y'),
         datetime.datetime(2015, 1, 2).strftime('%A %d de %B, %Y')]

This works for me on iPython:

In [1]: import locale

In [2]: locale.setlocale(locale.LC_TIME, "es_ES.utf8")
Out[2]: 'es_ES.utf8'

In [3]: import datetime

In [4]: dates = [datetime.datetime(2015, 1, 1).strftime('%A %d de %B, %Y'),
   ...:          datetime.datetime(2015, 1, 2).strftime('%A %d de %B, %Y')]

In [5]: dates
Out[5]: ['jueves 01 de enero, 2015', 'viernes 02 de enero, 2015']

Then if you want to use it in x axis, you can call dates inside x:

trace1 = Scatter(
  x=dates,
  y=['14.7414', '14.7414'],
  ...
)

It works for me! And I hope it works for you too.

If you need a different format for the date I recommend you to read the documentation about date-time microformats of D3. I also recommend you to read the thread How to change date language? I opened on Plotly Community Forum, because the answers are very useful and are the ones which helped me to solve my issue and to answer this question. You can also check this notebook shared in the thread, in which one of the users who answer me show how to solve the issue if you are using a pandas dataframe.

Excuse me for a lot of this stuff I am linking, but it might be very useful too to read about the methods to update axis in Plotly documentation, because you can update the format of the axis you want with as follows:

fig.update_xaxes(tickformat='%d-%b-%Y')

I want to credit to empet and eliasdabbas, users of the Plotly Community, for their answers!


问:
Dropdown angular
I want to do a drop down in angular, but I received only the first item from the list in the drop down.

```<code><div class="form-group">
     <h4>Projects</h4>
     <div *ngFor="let project of projects">
         {{project.projectName}}
     </div>

    <!-- Example single danger button -->
        <div class="btn-group">
          <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Projects
          </button>
          <div *ngFor="let project of projects" class="dropdown-menu">
             <a class="dropdown-item" href="#">{{project.projectName}} </a>
          </div>
        </div>
 </div>
</code>```

In the first *ngFor I received the correct values but in the second *ngFor I received only the first item from the list. Example in the picture bellow.

Can you help me to solve this problem ?

答:
Here is the correct code to solve this issue:-

```<code><div  class="dropdown-menu">
       <a class="dropdown-item" href="#" *ngFor="let project of projects">{{project.projectName}} </a>
</div>
</code>```

You are applying ngfor at wrong place.

Title: Dropdown angular

Body:
I want to do a drop down in angular, but I received only the first item from the list in the drop down.

Projects

         {{project.projectName}}

          <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Projects
          </button>

             {{project.projectName}}

In the first *ngFor I received the correct values but in the second *ngFor I received only the first item from the list. Example in the picture bellow.

Can you help me to solve this problem ?

Body:
Here is the correct code to solve this issue:-

<div  class="dropdown-menu">
       <a class="dropdown-item" href="#" *ngFor="let project of projects">{{project.projectName}} </a>
</div>

You are applying ngfor at wrong place.


问:
does DateTime keep itself updated in C#?
I am trying to create a folder based off of the current month/day using DateTime. After i initialize a new DateTime( 2011, 5, 16, 1, 1, 30); will this keep itself updated or reset every time the program is ran?</p>

答:
A DateTime object is immutable and once created will never change.  DateTime.Now creates a new DateTime based on the current time, and will be correct at the time of creation, but the returned instance will not update.  You can always call DateTime.Now again to get the latest time, but don't keep a reference around and expect it to update.

```<code>        DateTime dt = DateTime.Now;
        Thread.Sleep(1000);
        DateTime dt2 = DateTime.Now;
        TimeSpan elapsed = dt2 - dt;
        Console.WriteLine(elapsed.TotalMilliseconds);
        // Printed 1000.4 when I last ran it, depends on CPU timings
</code>```

As you can see dt and dt2 are different because dt did not keep updated, it was only the time when that line of code was executed.

Body:
A DateTime object is immutable and once created will never change.  DateTime.Now creates a new DateTime based on the current time, and will be correct at the time of creation, but the returned instance will not update.  You can always call DateTime.Now again to get the latest time, but don't keep a reference around and expect it to update.

        DateTime dt = DateTime.Now;
        Thread.Sleep(1000);
        DateTime dt2 = DateTime.Now;
        TimeSpan elapsed = dt2 - dt;
        Console.WriteLine(elapsed.TotalMilliseconds);
        // Printed 1000.4 when I last ran it, depends on CPU timings

As you can see dt and dt2 are different because dt did not keep updated, it was only the time when that line of code was executed.


问:
how does one call a function from a diffrent module in a thread?
I'm trying to create a multi threaded server using sockets. each user opens a new thread. this thread runs a function which eventually needs to call another function from a diffrent module, yet I always get a runtime error when it reaches the function it should call. any ideas?

```<code>    void Server::accept()
{
    // notice that we step out to the global namespace
    // for the resolution of the function accept

    // this accepts the client and create a specific socket from server to this client
    SOCKET client_socket = ::accept(_serverSocket, NULL, NULL);

    if (client_socket == INVALID_SOCKET)
        throw std::exception(__FUNCTION__);

    std::cout << "Client accepted. Server and client can speak" << std::endl;

    // the function that handle the conversation with the client

    std::thread lol(&Server::clientHandler, this, std::ref(client_socket));
    lol.detach();
}

void Server::clientHandler(SOCKET clientSocket)
{
    try
    {
        std::cout << "IM HERE";
        int userMessageType = 0;
        int sizeOfUserName = 0;
        int totalUserLen = 0;
        std::string loginReply = "";
        std::set<std::string> ::iterator itr;
        std::string allNames = "";
        while (userMessageType != MT_CLIENT_EXIT)
        {
            char buffer[2048];
            std::cout << "IM HERE";
            buffer[2047] = 0;
            std::cout << "IM HERE";
            userMessageType = Helper::getMessageTypeCode(clientSocket); // code crashes here!!
            std::cout << "ASDSAD";
            std::cout << "CODE " << userMessageType << std::endl;
            switch (userMessageType)
            {
            case MT_CLIENT_LOG_IN:
            {
                sizeOfUserName = Helper::getIntPartFromSocket(clientSocket, 2);
                std::string user = Helper::getStringPartFromSocket(clientSocket, sizeOfUserName);
                std::cout << user << std::endl;
                loginReply += "1010000000";
                for (itr = onlineUsers.begin(); itr != onlineUsers.end(); itr++)
                {
                    totalUserLen = totalUserLen + (int)(((*itr).length()));
                    allNames += *itr;
                    allNames += "&";
                    std::cout << "\n" << allNames << "\n";
                }
                if (totalUserLen != 0)
                {
                    std::cout << "ASD" << allNames.size();
                    allNames[allNames.size() - 1] = '\0';
                    std::cout << "ASD";
                    allNames = allNames.substr(0, allNames.size() - 1);
                    std::cout <<"\n" << allNames << "qqq";
                    for (int i = 0; i < 5 - allNames.length(); i++)
                    {

                    }
                    loginReply += std::to_string(allNames.length());
                    std::cout << loginReply;
                    Helper::sendData(clientSocket, loginReply);
                }
                else
                {
                    loginReply += "00000";
                    Helper::sendData(clientSocket, loginReply);
                    std::cout << "ASD";
                }
                onlineUsers.insert(user);
            }
            case MT_CLIENT_UPDATE:
            {
                std::string;
            }
            case MT_CLIENT_EXIT:
            {
                closesocket(clientSocket);
                return;
            }
            }
        }
        closesocket(clientSocket);
    }
    catch (const std::exception& e)
    {
        closesocket(clientSocket);
    }

}
</code>```

minimal reproductive example:
helper:

```<code>#include "Helper.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>

using std::string;

// recieves the type code of the message from socket (3 bytes)
// and returns the code. if no message found in the socket returns 0 (which means the client disconnected)
int Helper::getMessageTypeCode(SOCKET sc)
{
    char* s = getPartFromSocket(sc, 3);
    std::string msg(s);

    if (msg == "")
        return 0;

    int res = std::atoi(s);
    delete s;
    return  res;
}

void Helper::send_update_message_to_client(SOCKET sc, const string& file_content, const string& second_username, const string &all_users)
{
    //TRACE("all users: %s\n", all_users.c_str())
    const string code = std::to_string(MT_SERVER_UPDATE);
    const string current_file_size = getPaddedNumber(file_content.size(), 5);
    const string username_size = getPaddedNumber(second_username.size(), 2);
    const string all_users_size = getPaddedNumber(all_users.size(), 5);
    const string res = code + current_file_size + file_content + username_size + second_username + all_users_size + all_users;
    //TRACE("message: %s\n", res.c_str());
    sendData(sc, res);
}

// recieve data from socket according byteSize
// returns the data as int
int Helper::getIntPartFromSocket(SOCKET sc, int bytesNum)
{
    char* s = getPartFromSocket(sc, bytesNum, 0);
    return atoi(s);
}

// recieve data from socket according byteSize
// returns the data as string
string Helper::getStringPartFromSocket(SOCKET sc, int bytesNum)
{
    char* s = getPartFromSocket(sc, bytesNum, 0);
    string res(s);
    return res;
}

// return string after padding zeros if necessary
string Helper::getPaddedNumber(int num, int digits)
{
    std::ostringstream ostr;
    ostr << std::setw(digits) << std::setfill('0') << num;
    return ostr.str();

}

// recieve data from socket according byteSize
// this is private function
char* Helper::getPartFromSocket(SOCKET sc, int bytesNum)
{
    return getPartFromSocket(sc, bytesNum, 0);
}

char* Helper::getPartFromSocket(SOCKET sc, int bytesNum, int flags)
{
    if (bytesNum == 0)
    {
        return (char*)"";
    }

    char* data = new char[bytesNum + 1];
    int res = recv(sc, data, bytesNum, flags);

    if (res == INVALID_SOCKET)
    {
        std::string s = "Error while recieving from socket: ";
        s += std::to_string(sc);
        throw std::exception(s.c_str());
    }

    data[bytesNum] = 0;
    return data;
}

// send data to socket
// this is private function
void Helper::sendData(SOCKET sc, std::string message)
{
    const char* data = message.c_str();

    if (send(sc, data, message.size(), 0) == INVALID_SOCKET)
    {
        throw std::exception("Error while sending message to client");
    }
}
</code>```

答:
SOCKET is a typedef to an integral type so you should replace std::ref( client_socket ) part with client_socket.

Also thread accesses to Server::clientHandler are not syncronized. It is not a good solution but to prevent race-condition you might do the below.

```<code>void Server::clientHandler(SOCKET clientSocket)
{
     static std::mutex thread_safe;
      // Guarantees that only one thread proceeds at a time
     std::lock_guard<std::mutex> lock { thread_safe };
     ....
     ....
</code>```

Body:
I'm trying to create a multi threaded server using sockets. each user opens a new thread. this thread runs a function which eventually needs to call another function from a diffrent module, yet I always get a runtime error when it reaches the function it should call. any ideas?

    void Server::accept()
{
    // notice that we step out to the global namespace
    // for the resolution of the function accept

    // this accepts the client and create a specific socket from server to this client
    SOCKET client_socket = ::accept(_serverSocket, NULL, NULL);

    if (client_socket == INVALID_SOCKET)
        throw std::exception(__FUNCTION__);

    std::cout << "Client accepted. Server and client can speak" << std::endl;

    // the function that handle the conversation with the client

    std::thread lol(&Server::clientHandler, this, std::ref(client_socket));
    lol.detach();
}

void Server::clientHandler(SOCKET clientSocket)
{
    try
    {
        std::cout << "IM HERE";
        int userMessageType = 0;
        int sizeOfUserName = 0;
        int totalUserLen = 0;
        std::string loginReply = "";
        std::set<std::string> ::iterator itr;
        std::string allNames = "";
        while (userMessageType != MT_CLIENT_EXIT)
        {
            char buffer[2048];
            std::cout << "IM HERE";
            buffer[2047] = 0;
            std::cout << "IM HERE";
            userMessageType = Helper::getMessageTypeCode(clientSocket); // code crashes here!!
            std::cout << "ASDSAD";
            std::cout << "CODE " << userMessageType << std::endl;
            switch (userMessageType)
            {
            case MT_CLIENT_LOG_IN:
            {
                sizeOfUserName = Helper::getIntPartFromSocket(clientSocket, 2);
                std::string user = Helper::getStringPartFromSocket(clientSocket, sizeOfUserName);
                std::cout << user << std::endl;
                loginReply += "1010000000";
                for (itr = onlineUsers.begin(); itr != onlineUsers.end(); itr++)
                {
                    totalUserLen = totalUserLen + (int)(((*itr).length()));
                    allNames += *itr;
                    allNames += "&";
                    std::cout << "\n" << allNames << "\n";
                }
                if (totalUserLen != 0)
                {
                    std::cout << "ASD" << allNames.size();
                    allNames[allNames.size() - 1] = '\0';
                    std::cout << "ASD";
                    allNames = allNames.substr(0, allNames.size() - 1);
                    std::cout <<"\n" << allNames << "qqq";
                    for (int i = 0; i < 5 - allNames.length(); i++)
                    {

                    }
                    loginReply += std::to_string(allNames.length());
                    std::cout << loginReply;
                    Helper::sendData(clientSocket, loginReply);
                }
                else
                {
                    loginReply += "00000";
                    Helper::sendData(clientSocket, loginReply);
                    std::cout << "ASD";
                }
                onlineUsers.insert(user);
            }
            case MT_CLIENT_UPDATE:
            {
                std::string;
            }
            case MT_CLIENT_EXIT:
            {
                closesocket(clientSocket);
                return;
            }
            }
        }
        closesocket(clientSocket);
    }
    catch (const std::exception& e)
    {
        closesocket(clientSocket);
    }

}

minimal reproductive example:
helper:

#include "Helper.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>

using std::string;

// recieves the type code of the message from socket (3 bytes)
// and returns the code. if no message found in the socket returns 0 (which means the client disconnected)
int Helper::getMessageTypeCode(SOCKET sc)
{
    char* s = getPartFromSocket(sc, 3);
    std::string msg(s);

    if (msg == "")
        return 0;

    int res = std::atoi(s);
    delete s;
    return  res;
}

void Helper::send_update_message_to_client(SOCKET sc, const string& file_content, const string& second_username, const string &all_users)
{
    //TRACE("all users: %s\n", all_users.c_str())
    const string code = std::to_string(MT_SERVER_UPDATE);
    const string current_file_size = getPaddedNumber(file_content.size(), 5);
    const string username_size = getPaddedNumber(second_username.size(), 2);
    const string all_users_size = getPaddedNumber(all_users.size(), 5);
    const string res = code + current_file_size + file_content + username_size + second_username + all_users_size + all_users;
    //TRACE("message: %s\n", res.c_str());
    sendData(sc, res);
}

// recieve data from socket according byteSize
// returns the data as int
int Helper::getIntPartFromSocket(SOCKET sc, int bytesNum)
{
    char* s = getPartFromSocket(sc, bytesNum, 0);
    return atoi(s);
}

// recieve data from socket according byteSize
// returns the data as string
string Helper::getStringPartFromSocket(SOCKET sc, int bytesNum)
{
    char* s = getPartFromSocket(sc, bytesNum, 0);
    string res(s);
    return res;
}

// return string after padding zeros if necessary
string Helper::getPaddedNumber(int num, int digits)
{
    std::ostringstream ostr;
    ostr << std::setw(digits) << std::setfill('0') << num;
    return ostr.str();

}

// recieve data from socket according byteSize
// this is private function
char* Helper::getPartFromSocket(SOCKET sc, int bytesNum)
{
    return getPartFromSocket(sc, bytesNum, 0);
}

char* Helper::getPartFromSocket(SOCKET sc, int bytesNum, int flags)
{
    if (bytesNum == 0)
    {
        return (char*)"";
    }

    char* data = new char[bytesNum + 1];
    int res = recv(sc, data, bytesNum, flags);

    if (res == INVALID_SOCKET)
    {
        std::string s = "Error while recieving from socket: ";
        s += std::to_string(sc);
        throw std::exception(s.c_str());
    }

    data[bytesNum] = 0;
    return data;
}

// send data to socket
// this is private function
void Helper::sendData(SOCKET sc, std::string message)
{
    const char* data = message.c_str();

    if (send(sc, data, message.size(), 0) == INVALID_SOCKET)
    {
        throw std::exception("Error while sending message to client");
    }
}

Body:
SOCKET is a typedef to an integral type so you should replace std::ref( client_socket ) part with client_socket.

Also thread accesses to Server::clientHandler are not syncronized. It is not a good solution but to prevent race-condition you might do the below.

void Server::clientHandler(SOCKET clientSocket)
{
     static std::mutex thread_safe;
      // Guarantees that only one thread proceeds at a time
     std::lock_guard<std::mutex> lock { thread_safe };
     ....
     ....


问:
setState will not rebuild
This is the build method of a stateful widget.
When i click the button i expect it to count up to 10. It does not. It only rebuilds when the number reaches 10. Why is that and what can i do to fix it?</p>

```<code>int number = 0;
@override
Widget build(BuildContext context) {
    return Scaffold(
        body: RaisedButton(
            onPressed: () {
                while(number < 10) {
                    setState(() {
                        number = number += 1;
                    });
                    sleep(Duration(milliseconds: 100));
                }
            },
            child: Text(number.toString()),
        ),
    );
}
</code>```

答:
You can achieve by using Future.</p>

```<code>int number = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () async {
            while (number < 10) {
              setState(() {
                number = number += 1;
              });
              await Future.delayed(Duration(milliseconds: 100));
            }
          },
          child: Text(number.toString()),
        ),
      ),
    );
  }
</code>```

Title: setState will not rebuild

Body:
This is the build method of a stateful widget.
When i click the button i expect it to count up to 10. It does not. It only rebuilds when the number reaches 10. Why is that and what can i do to fix it?

int number = 0;
@override
Widget build(BuildContext context) {
    return Scaffold(
        body: RaisedButton(
            onPressed: () {
                while(number < 10) {
                    setState(() {
                        number = number += 1;
                    });
                    sleep(Duration(milliseconds: 100));
                }
            },
            child: Text(number.toString()),
        ),
    );
}

Body:
You can achieve by using Future.

int number = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () async {
            while (number < 10) {
              setState(() {
                number = number += 1;
              });
              await Future.delayed(Duration(milliseconds: 100));
            }
          },
          child: Text(number.toString()),
        ),
      ),
    );
  }


问:
Parser with LEX and YACC
i'm trying to implement a time parser with LEX & YACC.
I'm a complete newbie to those tools and C programming.

The program has to print a message (Valid time format 1: input ) when one of those formats is entered: 4pm, 7:38pm, 23:42, 3:16, 3:16am, otherwise a "Invalid character" message is printed.

lex file time.l :

```<code>%{
#include <stdio.h>
#include "y.tab.h"
%}

%%

[0-9]+                {yylval=atoi(yytext); return digit;}
"am"                   { return am;}
"pm"                   { return pm;}
[ \t\n]               ;
[:]                    { return colon;}
.                     { printf ("Invalid character\n");}

%%
</code>```

yacc file time.y:

```<code>%{
void yyerror (char *s);
int yylex();
#include <stdio.h>
#include <string.h>

%}

%start time
%token digit
%token am
%token pm
%token colon

%%

time        :  hour ampm           {printf ("Valid time format 1 : %s%s\n ", $1, $2);}
            |  hour colon minute   {printf ("Valid time format 2 : %s:%s\n",$1, $3);}
            |  hour colon minute ampm {printf ("Valid time format 3 : %s:%s%s\n",$1, $3, $4); }
            ;

ampm        :   am               {$$ = "am";}
            |   pm               {$$ = "pm";}
            ;

hour        :   digit digit             {$$ = $1 * 10 + $2;}
            |   digit             { $$ = $1;}
            ;

minute      :   digit digit         {$$ =  $1 * 10 + $2;}
            ;

%%
int yywrap()
{
        return 1;
}

int main (void) {

  return yyparse();
}

void yyerror (char *s) {fprintf (stderr, "%s\n", s);}
</code>```

compiling with this command:

```<code>yacc -d time.y && lex time.l && cc lex.yy.c y.tab.c -o time
</code>```

I'm getting some warnings:

```<code>time.y:17:47: warning: format specifies type 'char *' but the argument has type
      'YYSTYPE' (aka 'int') [-Wformat]
    {printf ("Valid time format 1 : %s%s\n ", (yyvsp[(1) - (2)]), (yyvsp.
</code>```

This warning appears for all the variables in printf statements.
The values are all char, because even the number in the time string is converted with the atoi function.

Executing the program with a valid input throws this error:

```<code>./time

1pm

[1]    2141 segmentation fault  ./time
</code>```

Can someone help me?
Thanks in advance.

答:
For byte parsing
in lex file
0x[0-9a-f]{8}   { yylval.number = strtoll(yytext+2, NULL, 16); return BYTE_4; }
In yacc file
You need to declear this number as part of union.</p>

Title: Parser with LEX and YACC

Body:
i'm trying to implement a time parser with LEX & YACC.
I'm a complete newbie to those tools and C programming.

The program has to print a message (Valid time format 1: input ) when one of those formats is entered: 4pm, 7:38pm, 23:42, 3:16, 3:16am, otherwise a "Invalid character" message is printed.

lex file time.l :

%{
#include <stdio.h>
#include "y.tab.h"
%}

%%

[0-9]+                {yylval=atoi(yytext); return digit;}
"am"                   { return am;}
"pm"                   { return pm;}
[ \t\n]               ;
[:]                    { return colon;}
.                     { printf ("Invalid character\n");}

%%

yacc file time.y:

%{
void yyerror (char *s);
int yylex();
#include <stdio.h>
#include <string.h>

%}

%start time
%token digit
%token am
%token pm
%token colon

%%

time        :  hour ampm           {printf ("Valid time format 1 : %s%s\n ", $1, $2);}
            |  hour colon minute   {printf ("Valid time format 2 : %s:%s\n",$1, $3);}
            |  hour colon minute ampm {printf ("Valid time format 3 : %s:%s%s\n",$1, $3, $4); }
            ;

ampm        :   am               {$$ = "am";}
            |   pm               {$$ = "pm";}
            ;

hour        :   digit digit             {$$ = $1 * 10 + $2;}
            |   digit             { $$ = $1;}
            ;

minute      :   digit digit         {$$ =  $1 * 10 + $2;}
            ;

%%
int yywrap()
{
        return 1;
}

int main (void) {

  return yyparse();
}

void yyerror (char *s) {fprintf (stderr, "%s\n", s);}

compiling with this command:

yacc -d time.y && lex time.l && cc lex.yy.c y.tab.c -o time

I'm getting some warnings:

time.y:17:47: warning: format specifies type 'char *' but the argument has type
      'YYSTYPE' (aka 'int') [-Wformat]
    {printf ("Valid time format 1 : %s%s\n ", (yyvsp[(1) - (2)]), (yyvsp.

This warning appears for all the variables in printf statements.
The values are all char, because even the number in the time string is converted with the atoi function.

Executing the program with a valid input throws this error:

./time

1pm

[1]    2141 segmentation fault  ./time

Can someone help me?
Thanks in advance.


问:
Disable zoom in WKWebView?
Does anyone know a nice simple way to disable double-click and pinch zooming in a WKWebView? Nothing I've tried works:

```<code>Webview.scrollView.allowsMagnification = false;    // Error: value of type WKWebView has no member allowsMagnification

Webview.scrollView.isMultipleTouchEnabled = false; // doesn't do anything
</code>```

In the html:

```<code><meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> // pile of crap, does nothing
</code>```

答:
it's works on iOS 13

```<code>NSString *javascript = @"var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);";
// you should use WKUserScript, `evaluateJavaScript` is not working
WKUserScript *us = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];[wkWebView.configuration.userContentController addUserScript:us];
</code>```

not working

```<code>- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return nil;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view {
    scrollView.pinchGestureRecognizer.enabled = NO;
}

</code>```

Title: Disable zoom in WKWebView?

Body:
Does anyone know a nice simple way to disable double-click and pinch zooming in a WKWebView? Nothing I've tried works:

Webview.scrollView.allowsMagnification = false;    // Error: value of type WKWebView has no member allowsMagnification

Webview.scrollView.isMultipleTouchEnabled = false; // doesn't do anything

In the html:

<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> // pile of crap, does nothing

Body:
it's works on iOS 13

NSString *javascript = @"var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);";
// you should use WKUserScript, `evaluateJavaScript` is not working
WKUserScript *us = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];[wkWebView.configuration.userContentController addUserScript:us];

not working

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return nil;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view {
    scrollView.pinchGestureRecognizer.enabled = NO;
}


问:
Links leak through semi-transparent DIV overlays in IE8
I just noticed something with IE8. I have a photo that is a link, and there's an partially transparent div over the image (just the bottom third of it or so) that is using this CSS code:

```<code>background: rgba(0, 0, 0, 0.7); /* handles the proper browsers */
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#b2000000,endColorstr=#b2000000); /* for IE */
</code>```

Unfortunately, when mousing over the div, the cursor is a pointer and clicking leads to the img's link. If I get rid of that filter and just make the background #000, it works fine and the overlay prevents any clicking. This behavior does not happen in Firefox or Chrome.

How can I work around this bug?

EDIT: Please note, this is not the same as an entire div with its opacity set to 0.7! That would cause the text inside of it (which I have) to also fade. This is strictly background color alpha.

Fiddle here: http://jsfiddle.net/csaltyj/dxTdq/

答:
I have had the SAME problem. You have to use an opaque color in the style and apply transparency via jquery

OR

make a semi-transparent .png as the background of the div

Body:
I just noticed something with IE8. I have a photo that is a link, and there's an partially transparent div over the image (just the bottom third of it or so) that is using this CSS code:

background: rgba(0, 0, 0, 0.7); /* handles the proper browsers */
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#b2000000,endColorstr=#b2000000); /* for IE */

Unfortunately, when mousing over the div, the cursor is a pointer and clicking leads to the img's link. If I get rid of that filter and just make the background #000, it works fine and the overlay prevents any clicking. This behavior does not happen in Firefox or Chrome.

How can I work around this bug?

EDIT: Please note, this is not the same as an entire div with its opacity set to 0.7! That would cause the text inside of it (which I have) to also fade. This is strictly background color alpha.

Fiddle here: http://jsfiddle.net/csaltyj/dxTdq/


问:
Is there any way to make a second LOGIN_REDIRECT_URL in settings.py in Django?
I am creating an app in Django which have two external users:
1. Teacher
2. Student

I have to create total of 3 apps, one the base app that contains home.html template, other the student app that contains student.html template and third teacher app that contains teacher.html template.

I have just created two apps for now, base app and student app, I have created login, logout and register pages for student app, now I am successfully able to redirect the user (student) to the student.html whenever the student logs into the system and I did this by putting LOGIN_REDIRECT_URL = 'student' in my settings.py.

I want to do the same for Teacher app as well but I want to redirect teacher to the teacher.html.

Is there any way that I can create the second LOGIN_REDIRECT_URL in settings.py to fulfil this purpose or it will be done any other way?

My Project Structure

django_project

|__esacp(main system)

|_____migrations

|_____templates

|________esacp

|__________base.html

|__________home.html

|__________student.html

|__________teacher.html

|_____apps.py

|_____forms.py

|_____models.py

|_____views.py

|__django_project

|__student

|_____migrations

|_____templates

|________student

|___________login.html

|___________logout.html

|___________register.html

|_____apps.py

|_____forms.py

|_____models.py

|_____views.py

|__teacher

|__db.sqlite3

|__manage.py

Code of models.py of esacp app

```<code>from django.db import models
from django.utils import timezone

class StudentType(models.Model):
    studenttype_id = models.IntegerField(primary_key=True)
    type_title = models.CharField(max_length=50)

    def __str__(self):
        return self.type_title

class StudentDetails(models.Model):
    name = models.CharField(max_length=50)
    username = models.CharField(max_length=50, primary_key=True)
    password = models.CharField(max_length=50)
    email_id = models.CharField(max_length=100)
    contact = models.CharField(max_length=100)
    studenttype = models.ForeignKey(StudentType, on_delete=models.CASCADE)
    registration_date = models.DateTimeField(default=timezone.now)
    modify_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name
</code>```

Code of urls.py of esacp app

```<code>from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='esacp-home'),
    path('student', views.student, name='student'),
]
</code>```

Code of urls.py of main project

```<code>from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from users import views as user_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', user_views.register, name='register'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('tlogin/', auth_views.LoginView.as_view(template_name='teacher/tlogin.html'), name='tlogin'),
    path('tlogout/', auth_views.LogoutView.as_view(template_name='teacher/tlogout.html'), name='tlogout'),
    path('esacp/', include('esacp.urls')),
</code>```

Code of views.py of teacher app

```<code>from django.shortcuts import render
from django.contrib.auth.views import LoginView

class MyLoginView():

    def get_success_url(self):
        url = self.get_redirect_url()
        return url
</code>```

Code of views.py of esacp app

```<code>from django.shortcuts import render
from django.contrib.auth.decorators import login_required

def home(request):
    return render(request, 'esacp/home.html')

@login_required
def student(request):
    return render(request, 'esacp/student.html')
</code>```

and below I have the statement in setting.py

```<code>LOGIN_REDIRECT_URL = 'student'
</code>```

答:
You have two login URLs. Therefore you can use a different login view for each one, and override get_success_url so that you are redirected to the correct page after login.

For example, the teacher login view would look something like:

```<code>from django.contrib.auth.views import LoginView

class TeacherLoginView(LoginView):
    template_name = 'teacher/tlogin.html'

    def get_success_url(self):
        url = self.get_redirect_url()
        return url or '/teacher/' # FIXME use reverse here instead of hardcoding the URL
</code>```

Then use that view instead of TeacherView in your URL patterns.

```<code>path('login/', TeacherLoginView.as_view(), name='login'),
</code>```

Body:
I am creating an app in Django which have two external users:
1. Teacher
2. Student

I have to create total of 3 apps, one the base app that contains home.html template, other the student app that contains student.html template and third teacher app that contains teacher.html template.

I have just created two apps for now, base app and student app, I have created login, logout and register pages for student app, now I am successfully able to redirect the user (student) to the student.html whenever the student logs into the system and I did this by putting LOGIN_REDIRECT_URL = 'student' in my settings.py.

I want to do the same for Teacher app as well but I want to redirect teacher to the teacher.html.

Is there any way that I can create the second LOGIN_REDIRECT_URL in settings.py to fulfil this purpose or it will be done any other way?

My Project Structure

django_project

|__esacp(main system)

|_____migrations

|_____templates

|________esacp

|__________base.html

|__________home.html

|__________student.html

|__________teacher.html

|_____apps.py

|_____forms.py

|_____models.py

|_____views.py

|__django_project

|__student

|_____migrations

|_____templates

|________student

|___________login.html

|___________logout.html

|___________register.html

|_____apps.py

|_____forms.py

|_____models.py

|_____views.py

|__teacher

|__db.sqlite3

|__manage.py

Code of models.py of esacp app

from django.db import models
from django.utils import timezone

class StudentType(models.Model):
    studenttype_id = models.IntegerField(primary_key=True)
    type_title = models.CharField(max_length=50)

    def __str__(self):
        return self.type_title

class StudentDetails(models.Model):
    name = models.CharField(max_length=50)
    username = models.CharField(max_length=50, primary_key=True)
    password = models.CharField(max_length=50)
    email_id = models.CharField(max_length=100)
    contact = models.CharField(max_length=100)
    studenttype = models.ForeignKey(StudentType, on_delete=models.CASCADE)
    registration_date = models.DateTimeField(default=timezone.now)
    modify_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

Code of urls.py of esacp app

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='esacp-home'),
    path('student', views.student, name='student'),
]

Code of urls.py of main project

from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from users import views as user_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', user_views.register, name='register'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('tlogin/', auth_views.LoginView.as_view(template_name='teacher/tlogin.html'), name='tlogin'),
    path('tlogout/', auth_views.LogoutView.as_view(template_name='teacher/tlogout.html'), name='tlogout'),
    path('esacp/', include('esacp.urls')),

Code of views.py of teacher app

from django.shortcuts import render
from django.contrib.auth.views import LoginView

class MyLoginView():

    def get_success_url(self):
        url = self.get_redirect_url()
        return url

Code of views.py of esacp app

from django.shortcuts import render
from django.contrib.auth.decorators import login_required

def home(request):
    return render(request, 'esacp/home.html')

@login_required
def student(request):
    return render(request, 'esacp/student.html')

and below I have the statement in setting.py

LOGIN_REDIRECT_URL = 'student'

Body:
You have two login URLs. Therefore you can use a different login view for each one, and override get_success_url so that you are redirected to the correct page after login.

For example, the teacher login view would look something like:

from django.contrib.auth.views import LoginView

class TeacherLoginView(LoginView):
    template_name = 'teacher/tlogin.html'

    def get_success_url(self):
        url = self.get_redirect_url()
        return url or '/teacher/' # FIXME use reverse here instead of hardcoding the URL

Then use that view instead of TeacherView in your URL patterns.

path('login/', TeacherLoginView.as_view(), name='login'),


问:
React Router Re-render when go back not using redux
I don't want to re-render the component if the customer goes and back from a browser or pressing back button from web app. Please help me with this. I am stuck, You can view the functionality from the link

Also if change pickup location with typehead, it cannot change in drop locations as typehead not changed the default value.

答:
I did by show hide div above the component in render functions like below </p>

```<code> import React, { Component } from "react";
 import App from "./App";
 import Book from "./components/book/book";

class Root extends Component {
  state = { page: "searchBooking" };
  changePage = page => {
    this.setState({ page: page });
  };
  constructor(props) {
    super(props);
    let obj = this;
    window.addEventListener(
      "hashchange",
      function() {
        //console.log("The hash has changed!");
        if (window.location.hash === "#book") {
          obj.setState({ page: "book" });
        } else {
          obj.setState({ page: "search" });
        }
        return;
      },
      true
    );
  }
  render() {
    return (
      <div>
        <div
          style={{
            display:
              this.state.page === "searchBooking" ||
              this.state.page === "search"
                ? "block"
                : "none"
          }}
        >
          <App changePage={this.changePage} page={this.state.page} />
        </div>
        <div style={{ display: this.state.page === "book" ? "block" : "none" }}>
          <Book changePage={this.changePage} page={this.state.page} />
        </div>
      </div>
    );
  }
}

export default Root;
</code>```

Body:
I don't want to re-render the component if the customer goes and back from a browser or pressing back button from web app. Please help me with this. I am stuck, You can view the functionality from the <a href="https://www.myrentalcar.com/v3/search_booking.php?country_des=133&pick_up=14583&pick_up_hour=10&pick_up_minute=00&country_drop=133&drop_off=14583&drop_off_hour=10&drop_off_minute=00&country_chk=on&country=163&age_chk=on&age_driver=30&pickupdates=07-04-2020&dropoffdates=14-04-2020&discount_code=&shwtrw=&is_airport=4&city=Bugibba&fromemail=&country_des=133&country_drop=133&car_group_type=all&pick_up_day=07&pick_up_mon=04&pick_up_year=2020&drop_off_day=14&drop_off_mon=04&drop_off_year=2020&lan=en&only_trw=&currency=PKR&book_log_id=25432532&filter_car_id=#search_booking" rel="nofollow noreferrer">link

Also if change pickup location with typehead, it cannot change in drop locations as typehead not changed the default value.

Body:
I did by show hide div above the component in render functions like below

 import React, { Component } from "react";
 import App from "./App";
 import Book from "./components/book/book";

class Root extends Component {
  state = { page: "searchBooking" };
  changePage = page => {
    this.setState({ page: page });
  };
  constructor(props) {
    super(props);
    let obj = this;
    window.addEventListener(
      "hashchange",
      function() {
        //console.log("The hash has changed!");
        if (window.location.hash === "#book") {
          obj.setState({ page: "book" });
        } else {
          obj.setState({ page: "search" });
        }
        return;
      },
      true
    );
  }
  render() {
    return (
      <div>
        <div
          style={{
            display:
              this.state.page === "searchBooking" ||
              this.state.page === "search"
                ? "block"
                : "none"
          }}
        >
          <App changePage={this.changePage} page={this.state.page} />
        </div>
        <div style={{ display: this.state.page === "book" ? "block" : "none" }}>
          <Book changePage={this.changePage} page={this.state.page} />
        </div>
      </div>
    );
  }
}

export default Root;


问:
Formatting large XML-Files in C# (without XDocument)
I have very huge XML files that i have to format. The files can be up to 10GB big.

I couldnt find any solution that doesnt include XDocument. XDocument loads the whole file into the RAM which obviously will be problematic with a 10GB file. Especially in 32 bit systems

Writing an XML formatter from scratch that works with a stream kind of feels like reinventing the wheel to me. I cant imagine me being the first person who had to work with something like this. If possible I would like to use an existing solution.

Does anyone know anything i can work with other than writing everything myself?

Thank you

.Net Framework 4.8

C#8

答:
You can use the XmlReader class.

This class does not load the entire document into memory, as opposed to the XDocument implementation.


问:
Delete request works but doesn't delete from database
when i'm trying to delete an item by FindByIdAndDelete it doesn't delete anything.
when i make the delete request in postman i don't get no errors just the item's in the db.
happens the same with my put request.

that's my code:

router.delete("/", (req, res) => {
  Appointment.find({}, (err, data) => {
    if (err) {
      return res.status(500).json();
    } else {
      return res.json(data);
    }
  });
});

router.delete("/:id", (req, res) => {
  const id = req.params.id;

  Appointment.findByIdAndDelete(id, (err, data) => {
    if (err) {
      return res.status(500).json();
    } else {
      return res.json(data);
    }
  });
});
```

<p>that's the body i put in my request :</p>

```{
"id": "5e3ef4950e1b4027201e73bf"
}
```

what am i doing wrong?

答:
findByIdAndDelete doesn't throw exception when it doesn't find the document to be deleted. You need to check if data is null or not.

Also your first route must be a GET route instead of DELETE.

router.get("/", (req, res) => {
  Appointment.find({}, (err, data) => {
    if (err) {
      return res.status(500).json();
    } else {
      return res.json(data);
    }
  });
});

router.delete("/:id", (req, res) => {
  const id = req.params.id;

  Appointment.findByIdAndDelete(id, (err, data) => {
    if (err) {
      return res.status(500).json();
    } else {
      if (data) {
        return res.json(data);
      } else {
        return res.status(400).send("Document not found, check id");
      }
    }
  });
});
```

Body:
when i'm trying to delete an item by FindByIdAndDelete it doesn't delete anything.
when i make the delete request in postman i don't get no errors just the item's in the db.
happens the same with my put request.

that's my code:

router.delete("/", (req, res) => {
  Appointment.find({}, (err, data) => {
    if (err) {
      return res.status(500).json();
    } else {
      return res.json(data);
    }
  });
});

router.delete("/:id", (req, res) => {
  const id = req.params.id;

  Appointment.findByIdAndDelete(id, (err, data) => {
    if (err) {
      return res.status(500).json();
    } else {
      return res.json(data);
    }
  });
});

that's the body i put in my request :

{
"id": "5e3ef4950e1b4027201e73bf"
}

what am i doing wrong?


问:
Partial Update Mutations(GraphQL)
How can I be able to update a node with only one field change and leave the rest of the fields alone?

My User Type

```<code>type User {
        id: ID!
        user_id: String!
        username: String!
        email: String!
        role: Role!
        isVerified: Boolean!
    }
</code>```

My Input Types

```<code>input UserUpdateInput {
    user_id: String
    username: String
    email: String
    password: String
    role: Role
    isVerified: Boolean
    }
</code>```

```<code>input UserWhereUniqueInput {
    id: ID
    user_id: String
    email: String
    }
</code>```

My Mutation type

```<code>type Mutation {
        updateUser(data: UserUpdateInput!, where: UserWhereUniqueInput): User
    }
</code>```

My Resolver

```<code>function updateUser(root, args, context, info){
    return context.db.mutation.updateUser({
      data: args.data,
      where: {
      id: args.where.id
      }
    }, info)
  }
</code>```

This is the request am sending on the GraphQL playground

```<code>mutation{
    updateUser(
    data: {
      isVerified: true
    }
    where:{
    user_id :  "afc485b"
        }
    )
  {
    isVerified
  }
}
</code>```

This is the error am getting

```<code>{
  "errors": [
    {
      "message": "Cannot read property 'mutation' of undefined",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "updateUser"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "TypeError: Cannot read property 'mutation' of undefined"
</code>```

Someone help me. What am I missing?
After updating my server as suggested by Daniel Rearden on the answer section, am getting a new error

```<code>    {
      "message": "Cannot read property 'updateUser' of undefined",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "updateUser"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "TypeError: Cannot read property 'updateUser' of undefined"
</code>```

答:
The error is the result of not correctly adding the db property to you context. Assuming you're still using version 1, your code should look something like this:

```<code>const { prisma } = require('./generated/prisma-client')

const server = new ApolloServer({
  ...
  context: {
    db: prisma,
  },
})
</code>```

Title: Partial Update Mutations(GraphQL)

Body:
How can I be able to update a node with only one field change and leave the rest of the fields alone?

My User Type

type User {
        id: ID!
        user_id: String!
        username: String!
        email: String!
        role: Role!
        isVerified: Boolean!
    }

My Input Types

input UserUpdateInput {
    user_id: String
    username: String
    email: String
    password: String
    role: Role
    isVerified: Boolean
    }

input UserWhereUniqueInput {
    id: ID
    user_id: String
    email: String
    }

My Mutation type

type Mutation {
        updateUser(data: UserUpdateInput!, where: UserWhereUniqueInput): User
    }

My Resolver

function updateUser(root, args, context, info){
    return context.db.mutation.updateUser({
      data: args.data,
      where: {
      id: args.where.id
      }
    }, info)
  }

This is the request am sending on the GraphQL playground

mutation{
    updateUser(
    data: {
      isVerified: true
    }
    where:{
    user_id :  "afc485b"
        }
    )
  {
    isVerified
  }
}

This is the error am getting

{
  "errors": [
    {
      "message": "Cannot read property 'mutation' of undefined",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "updateUser"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "TypeError: Cannot read property 'mutation' of undefined"

Someone help me. What am I missing?
After updating my server as suggested by Daniel Rearden on the answer section, am getting a new error

    {
      "message": "Cannot read property 'updateUser' of undefined",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "updateUser"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "TypeError: Cannot read property 'updateUser' of undefined"

Body:
The error is the result of not correctly adding the db property to you context. Assuming you're still using version 1, your code should look something like this:

const { prisma } = require('./generated/prisma-client')

const server = new ApolloServer({
  ...
  context: {
    db: prisma,
  },
})


问:
ModalBox open on page load
I am using ModalBox (http://okonet.ru/projects/modalbox/index.html) on my website.  It is set up and works fine, but I would like to make it open on page load in certain circumstances.  In particular, I would like to have it open with a message when users log out.  Right now when users log out, it goes to my homepage with a message in the page (I do this by loading index.php?loggedout=true when users log out and have the text show when the variable is true.  Using this method (having ?loggedout=true) but loading with a ModalBox open instead of just text in the page body.  Alternatively, if it could detect what page it came from without the variable and open then, that would be nice too.

tl;dr: How can I have a ModalBox open automatically on page load.

Edit: I tried putting

```<code><script type="text/javascript">
if(window.location.search.indexOf('loggedout=true') !== -1) {
Modalbox.show('/data/loggedout',{width: 576, title: 'Logged Out'}); return false;
}
</script>
</code>```

On my page, but that didn't work.

答:
I achieved my desired result using</p>

```<code><?php
if ($loggedout=="true") { ?>
<body class="slider-header" onload="Modalbox.show('/data/loggedout',{width: 576, title: 'Logged Out'}); return false;">
<?php } else { ?>
<body class="slider-header">
<?php }; ?>
</code>```

Title: ModalBox open on page load

Body:
I am using ModalBox (http://okonet.ru/projects/modalbox/index.html) on my website.  It is set up and works fine, but I would like to make it open on page load in certain circumstances.  In particular, I would like to have it open with a message when users log out.  Right now when users log out, it goes to my homepage with a message in the page (I do this by loading index.php?loggedout=true when users log out and have the text show when the variable is true.  Using this method (having ?loggedout=true) but loading with a ModalBox open instead of just text in the page body.  Alternatively, if it could detect what page it came from without the variable and open then, that would be nice too.

tl;dr: How can I have a ModalBox open automatically on page load.

Edit: I tried putting

On my page, but that didn't work.

Body:
I achieved my desired result using

<?php
if ($loggedout=="true") { ?>
<body class="slider-header" onload="Modalbox.show('/data/loggedout',{width: 576, title: 'Logged Out'}); return false;">
<?php } else { ?>
<body class="slider-header">
<?php }; ?>


问:
Access graphics from drawable folder of a dynamic feature module from main module
I'm getting my feet wet with dynamic module split API delivery in order to break up my game app into Instant and Installable versions. I've been following the Codelabs tutorial here https://codelabs.developers.google.com/codelabs/on-demand-dynamic-delivery/index.html#0. Unfortunately it uses Kotlin for the MainActivity code, which is less specific than Java, but still fairly followable if you've done a Kotlin tutorial. The example includes accessing a text tile in an 'assets' folder in an 'assets' feature module with the following:

```<code>private const val packageName = "com.google.android.samples.dynamicfeatures.ondemand"

val assetManager = createPackageContext(packageName, 0).assets
// Now treat it like any other asset file.
val assets = assetManager.open("assets.txt")
val assetContent = assets.bufferedReader()
           .use {
               it.readText()
           }
</code>```

For now I just want to access graphic files in a drawable folder of my dynamic feature module. I'll only be using my dynamic feature module to store large graphics that would take me over the 10 MG limit for an Instant app download. What would be the cleanest way to do this?

Main 'app' module:

Java code in 'app':

```<code>loadTexture(R.drawable.aaa_image);

Bitmap bitmap;
public void loadTexture(final int resourceId){
    bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);
    ***
</code>```

Dynamically delivered 'installationassets' module:

Still java code in 'app', won't reach:

```<code> loadTexture(R.drawable.testgraphic);
 cannot resolve symbol 'testgraphic'
</code>```

答:
I found a working solution to load drawables from a feature module resources. The trick is to use the correct package name for the module.

Example:

base module package name is "com.project"

feature module name defined in build.gradle "FeatureModule"

feature module package name "com.project.FeatureModule"

build.gradle

dynamicFeatures = [":FeatureModule"]

Java

```<code>int drawableResId = context.getResources().getIdentifier("your_drawable_name", "drawable", "com.project.FeatureModule");
context.getDrawable(drawableResId);
</code>```

Reference article

Body:
I'm getting my feet wet with dynamic module split API delivery in order to break up my game app into Instant and Installable versions. I've been following the Codelabs tutorial here https://codelabs.developers.google.com/codelabs/on-demand-dynamic-delivery/index.html#0. Unfortunately it uses Kotlin for the MainActivity code, which is less specific than Java, but still fairly followable if you've done a Kotlin tutorial. The example includes accessing a text tile in an 'assets' folder in an 'assets' feature module with the following:

private const val packageName = "com.google.android.samples.dynamicfeatures.ondemand"

val assetManager = createPackageContext(packageName, 0).assets
// Now treat it like any other asset file.
val assets = assetManager.open("assets.txt")
val assetContent = assets.bufferedReader()
           .use {
               it.readText()
           }

For now I just want to access graphic files in a drawable folder of my dynamic feature module. I'll only be using my dynamic feature module to store large graphics that would take me over the 10 MG limit for an Instant app download. What would be the cleanest way to do this?

Main 'app' module:

Java code in 'app':

loadTexture(R.drawable.aaa_image);

Bitmap bitmap;
public void loadTexture(final int resourceId){
    bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);
    ***

Dynamically delivered 'installationassets' module:

Still java code in 'app', won't reach:

 loadTexture(R.drawable.testgraphic);
 cannot resolve symbol 'testgraphic'

Body:
I found a working solution to load drawables from a feature module resources. The trick is to use the correct package name for the module.

Example:

base module package name is "com.project"

feature module name defined in build.gradle "FeatureModule"

feature module package name "com.project.FeatureModule"

build.gradle

dynamicFeatures = [":FeatureModule"]

Java

int drawableResId = context.getResources().getIdentifier("your_drawable_name", "drawable", "com.project.FeatureModule");
context.getDrawable(drawableResId);

Reference article


问:
Ensure a service is finished before closing App (without retry)
I am new to Android. I am developing an application which a service that makes three requests to my backend and I need to ensure that requests are finished before close app.

I read about use START_STICKY on onStartCommand method but this option makes the service to retry causing repeated requests if, for example, app is closed when service have maked first request only:

Run service...

Make request 1

Close APP

Retry service by START_STICKY config ...

Make request 1 (repeated)

Make request 2

Make request 3

Is there any other way to ensure that the service finishes its execution before closing?

答:
Well it seems that your want your task to be reliable and send the data to server but time doesn't matter that much(as you said you can retry so specific time not matter)

For this particulate requirement you get Android's latest WorkManager

When you hand a task request to WorkManager then it run based on when the work's conditions (like network availability and power) are satisfied, it make sure that your task get done in certain time interval.

According docs and also a complete step by step guide about WorkManager

WorkManager is intended for tasks that are deferrable—that is, not
required to run immediately—and required to run reliably even if the
app exits or the device restarts.

For example:

Sending logs or analytics to backend services Periodically syncing

application data with a server

Please check this doc and follow the guide to learn more about it


问:
Random numbers from specific range
I want to display random numbers specific range [from, to]. Following code writes out the value but something is not working properly:

```<code>#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int draw(int from_to, int to_from)
{
    return (rand()%to_from)+from_to;
}
int main()
{
    srand(time(NULL));
    int start,stop;
    cout << "First number: " << endl;
    cin >> start;
    cout << "Last number: " << endl;
    cin >> stop;
    int x=20;
    do
    {
        cout << draw(start,stop) << endl;
        x--;
    } while(x>0);

    return 0;
}
</code>```

答:
Try C++11 features for generating random number from specified range:

#include <random>
#include <iostream>

int main() {
    int from = 0;
    int to   = 100;

    std::random_device device;
    std::mt19937 generator(device());
    std::uniform_int_distribution<std::mt19937::result_type> distribution(from, to);

    std::cout << distribution(generator) << std::endl;
}
```

Demo

Title: Random numbers from specific range

Body:
I want to display random numbers specific range [from, to]. Following code writes out the value but something is not working properly:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int draw(int from_to, int to_from)
{
    return (rand()%to_from)+from_to;
}
int main()
{
    srand(time(NULL));
    int start,stop;
    cout << "First number: " << endl;
    cin >> start;
    cout << "Last number: " << endl;
    cin >> stop;
    int x=20;
    do
    {
        cout << draw(start,stop) << endl;
        x--;
    } while(x>0);

    return 0;
}

Body:
Try C++11 features for generating random number from specified range:

#include <random>
#include <iostream>

int main() {
    int from = 0;
    int to   = 100;

    std::random_device device;
    std::mt19937 generator(device());
    std::uniform_int_distribution<std::mt19937::result_type> distribution(from, to);

    std::cout << distribution(generator) << std::endl;
}

<a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:2,endLineNumber:13,positionColumn:1,positionLineNumber:1,selectionStartColumn:2,selectionStartLineNumber:13,startColumn:1,startLineNumber:1),source:'%23include+%3Crandom%3E%0A%23include+%3Ciostream%3E%0A%0Aint+main()+%7B%0A++++int+from+%3D+0%3B%0A++++int+to+++%3D+100%3B%0A%0A++++std::random_device+device%3B%0A++++std::mt19937+generator(device())%3B%0A++++std::uniform_int_distribution%3Cstd::mt19937::result_type%3E+distribution(from,+to)%3B%0A%0A++++std::cout+%3C%3C+distribution(generator)+%3C%3C+std::endl%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:49.85494633014216,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:g92,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:2,lang:c%2B%2B,libs:!(),options:'-std%3Dc%2B%2B17',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+gcc+9.2+(Editor+%231,+Compiler+%232)+C%2B%2B',t:'0')),k:50.145053669857845,l:'4',m:50,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:2,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%232+with+x86-64+gcc+9.2',t:'0')),header:(),l:'4',m:50,n:'0',o:'',s:0,t:'0')),k:50.145053669857845,l:'3',n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="noreferrer">Demo


问:
Unable to map LUIS intent while using the Bot Framework v4 code
I am running botframework v4 code and testing it using chatbot emulator . Curently i am unable to reach the code flow where the luis intent code is present in [MainDialog.cs][1] .

Below is the line in MainDialog.cs file:

 var luisResult = await _luisRecognizer.RecognizeAsync<FlightBooking>(stepContext.Context, cancellationToken);
```

<p>But ,when i enter some message in ChatBot ,every time flow ends at [FlightBookingRecognizer.cs][2] and below is the line where i am expecting luis intent to be matched/fetched. </p>

<pre class="lang-cs prettyprint-override"><code>public virtual async Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext, CancellationToken cancellationToken)
    => await _recognizer.RecognizeAsync(turnContext, cancellationToken);

public virtual async Task<T> RecognizeAsync<T>(ITurnContext turnContext, CancellationToken cancellationToken)
     where T : IRecognizerConvert, new()
    => await _recognizer.RecognizeAsync<T>(turnContext, cancellationToken);
</code>```

turnContext has the message which we enter in chatbot.
And i am expecting the LUIS result in _recognizer.RecognizeAsync ,but there is no relevant data in this .
I am trying to do something like below:-

But, my code flow ends here and i get error in ChatBot emulator as attached in screenshot.[![enter image description here][3]][3]

Steps to reproduce:
1. Download or pull the project from github and then Open the CoreBot.csproj  in Visual studio from this link .
[CoreBot Project][4]

2. Then select CoreBot and build it (Don't forget to add luis app id,key and host in csharp_dotnetcore\13.core-bot\appsettings.json file).
In Luis you can import this file csharp_dotnetcore\13.core-bot\CognitiveModels\FlightBooking.json and then train and publish it.
In Luis.ai go to My apps, and click Import App. Choose the file JSON file for the app you want to import and click Import.

3. Also put debug breakpoints in MainDialog.cs class (line 67 jus before switch statement) and FlightBookingRecognizer.cs class (last 2 lines ) .

4.Run the project in IIS browser mode and not in console mode ,it will open in browser you will see this link  http://localhost:3978/

5. In chatbot Emulator open this link http://localhost:3979/api/messages

6. You will see cards in chatbot as per attached screenshot.

7. Enter a message which is given in chatbot example i.e "Flight to paris"

8. You will see debug point ends at FlightRecognizer.cs class last line and turnContext has your message but _recognizer.RecognizeAsync doesn't carry any information about the Luis intent .

9.Also,it is not clear that LUIS intent is matched from local file or luis.ai

More info can be found here [Microsoft documentation about this v4 code][5]
Please Help.

  [1]: https://github.com/microsoft/BotBuilder-Samples/blob/master/samples/csharp_dotnetcore/13.core-bot/Dialogs/MainDialog.cs
  [2]: https://github.com/microsoft/BotBuilder-Samples/blob/master/samples/csharp_dotnetcore/13.core-bot/FlightBookingRecognizer.cs
  [3]: https://i.stack.imgur.com/05Rbg.png
  [4]: https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/13.core-bot
  [5]: https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-luis?view=azure-bot-service-4.0&tabs=csharp
```

答:
This issue is resolved now.I am able to get the intent from Luis.
When i used Luis host which is configured in appsettings.json in format https://xxxx.xxxx.xxxx
I was not getting Luis Intent,but after removing https:// ,i am getting the result now.
Thanks everybody for your efforts.</p>

Body:
I am running botframework v4 code and testing it using chatbot emulator . Curently i am unable to reach the code flow where the luis intent code is present in [MainDialog.cs][1] .

Below is the line in MainDialog.cs file:

 var luisResult = await _luisRecognizer.RecognizeAsync<FlightBooking>(stepContext.Context, cancellationToken);

But ,when i enter some message in ChatBot ,every time flow ends at [FlightBookingRecognizer.cs][2] and below is the line where i am expecting luis intent to be matched/fetched.

public virtual async Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext, CancellationToken cancellationToken)
    => await _recognizer.RecognizeAsync(turnContext, cancellationToken);

public virtual async Task<T> RecognizeAsync<T>(ITurnContext turnContext, CancellationToken cancellationToken)
     where T : IRecognizerConvert, new()
    => await _recognizer.RecognizeAsync<T>(turnContext, cancellationToken);

turnContext has the message which we enter in chatbot.
And i am expecting the LUIS result in _recognizer.RecognizeAsync ,but there is no relevant data in this .
I am trying to do something like below:-

But, my code flow ends here and i get error in ChatBot emulator as attached in screenshot.[![enter image description here][3]][3]

Steps to reproduce:
1. Download or pull the project from github and then Open the CoreBot.csproj  in Visual studio from this link .
[CoreBot Project][4]

2. Then select CoreBot and build it (Don't forget to add luis app id,key and host in csharp_dotnetcore\13.core-bot\appsettings.json file).
In Luis you can import this file csharp_dotnetcore\13.core-bot\CognitiveModels\FlightBooking.json and then train and publish it.
In Luis.ai go to My apps, and click Import App. Choose the file JSON file for the app you want to import and click Import.

3. Also put debug breakpoints in MainDialog.cs class (line 67 jus before switch statement) and FlightBookingRecognizer.cs class (last 2 lines ) .

4.Run the project in IIS browser mode and not in console mode ,it will open in browser you will see this link  http://localhost:3978/

5. In chatbot Emulator open this link http://localhost:3979/api/messages

6. You will see cards in chatbot as per attached screenshot.

7. Enter a message which is given in chatbot example i.e "Flight to paris"

8. You will see debug point ends at FlightRecognizer.cs class last line and turnContext has your message but _recognizer.RecognizeAsync doesn't carry any information about the Luis intent .

9.Also,it is not clear that LUIS intent is matched from local file or luis.ai

More info can be found here [Microsoft documentation about this v4 code][5]
Please Help.

  [1]: https://github.com/microsoft/BotBuilder-Samples/blob/master/samples/csharp_dotnetcore/13.core-bot/Dialogs/MainDialog.cs
  [2]: https://github.com/microsoft/BotBuilder-Samples/blob/master/samples/csharp_dotnetcore/13.core-bot/FlightBookingRecognizer.cs
  [3]: https://i.stack.imgur.com/05Rbg.png
  [4]: https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/13.core-bot
  [5]: https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-luis?view=azure-bot-service-4.0&tabs=csharp


问:
C# Rest API File upload
I am trying too upload a file with C# by an API.

The StreamUtils dont work, I am getting error: "Cannot convert lambda expression to type 'string' because it is not a delegate type".

Any idea on how to upload the file?
It is around 100MB.

```<code> public void UploadModel(string ProjectId, string filename, Stream fileStream)
        {

            string access_token_string = Read_Json_Values("access_token");
            string webstring = String.Format("https://api.test.com/v2/projects/{0}/revisions", ProjectId);

            var client = new RestClient(webstring);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", "Bearer " + access_token_string);
            request.AddHeader("Content-Type", "application/ifc");
            request.AddHeader("xxx-Params", "{\"callbackUri\": \"https://example.com\", \"filename\": \"mk337.ifc\", \"comment\": \"From Postman\", \"model\": \"21312312312312\"}");
            request.AddFile("file", s => StreamUtils.CopyStream(fileStream, s), filename);

            IRestResponse response = client.Execute(request);
            Console.WriteLine("Model is uploaded!");
        }
</code>```

```<code>internal static class StreamUtils
        {
            private const int STREAM_BUFFER_SIZE = 128 * 1024; // 128KB

            public static void CopyStream(Stream source, Stream target)
            { CopyStream(source, target, new byte[STREAM_BUFFER_SIZE]); }

            public static void CopyStream(Stream source, Stream target, byte[] buffer)
            {
                if (source == null) throw new ArgumentNullException("source");
                if (target == null) throw new ArgumentNullException("target");

                if (buffer == null) buffer = new byte[STREAM_BUFFER_SIZE];
                int bufferLength = buffer.Length;
                int bytesRead = 0;
                while ((bytesRead = source.Read(buffer, 0, bufferLength)) > 0)
                    target.Write(buffer, 0, bytesRead);
            }
</code>```

答:
I think you can convert your input file to Base64 and then send it.
See also the answers of other professors what they think.</p>

Title: C# Rest API File upload

Body:
I am trying too upload a file with C# by an API.

The StreamUtils dont work, I am getting error: "Cannot convert lambda expression to type 'string' because it is not a delegate type".

Any idea on how to upload the file?
It is around 100MB.

 public void UploadModel(string ProjectId, string filename, Stream fileStream)
        {

            string access_token_string = Read_Json_Values("access_token");
            string webstring = String.Format("https://api.test.com/v2/projects/{0}/revisions", ProjectId);

            var client = new RestClient(webstring);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", "Bearer " + access_token_string);
            request.AddHeader("Content-Type", "application/ifc");
            request.AddHeader("xxx-Params", "{\"callbackUri\": \"https://example.com\", \"filename\": \"mk337.ifc\", \"comment\": \"From Postman\", \"model\": \"21312312312312\"}");
            request.AddFile("file", s => StreamUtils.CopyStream(fileStream, s), filename);

            IRestResponse response = client.Execute(request);
            Console.WriteLine("Model is uploaded!");
        }

internal static class StreamUtils
        {
            private const int STREAM_BUFFER_SIZE = 128 * 1024; // 128KB

            public static void CopyStream(Stream source, Stream target)
            { CopyStream(source, target, new byte[STREAM_BUFFER_SIZE]); }

            public static void CopyStream(Stream source, Stream target, byte[] buffer)
            {
                if (source == null) throw new ArgumentNullException("source");
                if (target == null) throw new ArgumentNullException("target");

                if (buffer == null) buffer = new byte[STREAM_BUFFER_SIZE];
                int bufferLength = buffer.Length;
                int bytesRead = 0;
                while ((bytesRead = source.Read(buffer, 0, bufferLength)) > 0)
                    target.Write(buffer, 0, bytesRead);
            }


问:
Python queue only 1 item
I want to store only one item (the latest). I would do it as follows:

```<code>thread 1:
queue.queue.clear()
queue.put (DATA, block = False, timeout = 2)

thread 2:
queue.get()
</code>```

But what if thread 2 get at the same time when thread 1 clears the queue?

The second idea is to clear the thread 2 queue immediately after  get, but I do not want the queue to grow, it is unknown what size when thread 2 does not download ...

Thanks for Help!

答:
You want to prevent anyone else from accessing the queue between clearing it and putting a new value in the queue. You can accomplish this using a lock.

```<code>lock = threading.Lock()

def clear_and_put(queue):
    with lock.acquire():
        queue.clear()
        queue.put(DATA)

def get(queue):
    with lock.acquire():
        return queue.get()
</code>```

If thread1 calls clear_and_put, it will either immediately get the lock, or wait until thread2's call to get completes. Once it acquires the lock, any call to get will block until the queue has been updated and the lock is released.

Title: Python queue only 1 item

Body:
I want to store only one item (the latest). I would do it as follows:

thread 1:
queue.queue.clear()
queue.put (DATA, block = False, timeout = 2)

thread 2:
queue.get()

But what if thread 2 get at the same time when thread 1 clears the queue?

The second idea is to clear the thread 2 queue immediately after  get, but I do not want the queue to grow, it is unknown what size when thread 2 does not download ...

Thanks for Help!

Body:
You want to prevent anyone else from accessing the queue between clearing it and putting a new value in the queue. You can accomplish this using a lock.

lock = threading.Lock()

def clear_and_put(queue):
    with lock.acquire():
        queue.clear()
        queue.put(DATA)

def get(queue):
    with lock.acquire():
        return queue.get()

If thread1 calls clear_and_put, it will either immediately get the lock, or wait until thread2's call to get completes. Once it acquires the lock, any call to get will block until the queue has been updated and the lock is released.


问:
Execute a function after rendering of Graph completes
I want to execute a function after the successful rendering of a Graph. SuccessfulRendering() is running before the display completes. Any Idea how can we do this? I want to take the screenshot of the screen in SuccessfulRendering() function after the display completes, that's why I've to wait for the graph to be rendered completely.

Code:

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import HighchartsReact from 'highcharts-react-official';
import Highcharts from 'highcharts';

class LineChart extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // To avoid unnecessary update keep all options in the state.
      chartOptions: {
        xAxis: {
          categories: ['A', 'B', 'C'],
        },
        series: [
          { data: [1, 2, 3] }
        ]
      },
      hoverData: null
    };
  }

  SuccessfulRendering=()=>{
    console.log('Successfully rendered!!')
  }

  updateSeries = () => {
    // The chart is updated only with new options.
    this.setState({
      chartOptions: {
        series: [
          { data: [Math.random() * 5, 2, 1]}
        ]
      }
    },()=>{
      this.SuccessfulRendering()
    });

  }

  render() {
    const { chartOptions, hoverData } = this.state;

    return (
      <div>
        <HighchartsReact
          highcharts={Highcharts}
          options={chartOptions}
        />
      <h3>Hovering over {hoverData}</h3>
      <button onClick={this.updateSeries.bind(this)}>Update Series</button>
      </div>
    )
  }
}

render(<LineChart />, document.getElementById('root'),()=>{
});

</code>```

答:
I think that a problem which you are struggling to is related to the animation. In this case, you should disable it or delay the calling of the SuccessfulRendering function by using setTimeout.

Demo without animation after the chart update: https://codesandbox.io/s/highcharts-react-demo-2volr

API: https://api.highcharts.com/highcharts/chart.animation

Body:
I want to execute a function after the successful rendering of a Graph. SuccessfulRendering() is running before the display completes. Any Idea how can we do this? I want to take the screenshot of the screen in SuccessfulRendering() function after the display completes, that's why I've to wait for the graph to be rendered completely.

Code:

import React, { Component } from 'react';
import { render } from 'react-dom';
import HighchartsReact from 'highcharts-react-official';
import Highcharts from 'highcharts';

class LineChart extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // To avoid unnecessary update keep all options in the state.
      chartOptions: {
        xAxis: {
          categories: ['A', 'B', 'C'],
        },
        series: [
          { data: [1, 2, 3] }
        ]
      },
      hoverData: null
    };
  }

  SuccessfulRendering=()=>{
    console.log('Successfully rendered!!')
  }

  updateSeries = () => {
    // The chart is updated only with new options.
    this.setState({
      chartOptions: {
        series: [
          { data: [Math.random() * 5, 2, 1]}
        ]
      }
    },()=>{
      this.SuccessfulRendering()
    });

  }

  render() {
    const { chartOptions, hoverData } = this.state;

    return (

        <HighchartsReact
          highcharts={Highcharts}
          options={chartOptions}
        />

Hovering over {hoverData}

      <button onClick={this.updateSeries.bind(this)}>Update Series</button>

    )
  }
}

render(<LineChart />, document.getElementById('root'),()=>{
});


问:
Why result starts diverging after certain number for Fibonacci sequence?
I'm puzzled with results of computing sequence by different ways:

```<code>(defun fig-square-p (n)
  "Check if the given N is a perfect square number.

 A000290 in the OEIS"
  (check-type n (integer 0 *))
  (= (floor (sqrt n)) (ceiling (sqrt n))))

(defun fibonaccip (n)
  "Check if the given number N is a Fibonacci number."
  (check-type n (integer 0 *))
  (or (fig-square-p (+ (* 5 (expt n 2)) 4))
      (fig-square-p (- (* 5 (expt n 2)) 4))))

(defun fibonacci (n)
  "Compute N's Fibonacci number."
  (check-type n (integer 0 *))
  (loop :for f1 = 0 :then f2
     :and f2 = 1 :then (+ f1 f2)
     :repeat n :finally (return f1)))

(defun seq-fibonaccies (n)
  "Return sequence of Fibonacci numbers upto N."
  (check-type n (integer 0 *))
  (loop :for i :from 1 :upto n
     :collect (fib i)))
</code>```

```<code>CL-USER> (loop :for i :from 0 :upto 7070 :when (fibonaccip i) :collect i)
(0 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 2889 3876 4181 5473
 6765 7070)
CL-USER> (seq-fibonaccies 21)
(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946)
</code>```

And when I increasing the limit of the loop the results start diverging much more.

```<code>~$ sbcl --version
SBCL 1.4.14-3.fc31
</code>```

答:
As someone else already mentioned, rounding errors accumulate quickly,
so you should stick with the integer arithmetics, using
isqrt:

```<code>(defun squarep (n)
  "Check if the given N is a perfect square number.
https://oeis.org/A000290"
  (check-type n (integer 0 *))
  (let ((sqrt (isqrt n)))
    (= n (* sqrt sqrt))))
</code>```

Also, you have a typo in seq-fibonaccies (fib instead of fibonacci).

Finally, seq-fibonaccies is quadratic in its argument, while it only
have to be linear.

Body:
I'm puzzled with results of computing sequence by different ways:

(defun fig-square-p (n)
  "Check if the given N is a perfect square number.

 A000290 in the OEIS"
  (check-type n (integer 0 *))
  (= (floor (sqrt n)) (ceiling (sqrt n))))

(defun fibonaccip (n)
  "Check if the given number N is a Fibonacci number."
  (check-type n (integer 0 *))
  (or (fig-square-p (+ (* 5 (expt n 2)) 4))
      (fig-square-p (- (* 5 (expt n 2)) 4))))

(defun fibonacci (n)
  "Compute N's Fibonacci number."
  (check-type n (integer 0 *))
  (loop :for f1 = 0 :then f2
     :and f2 = 1 :then (+ f1 f2)
     :repeat n :finally (return f1)))

(defun seq-fibonaccies (n)
  "Return sequence of Fibonacci numbers upto N."
  (check-type n (integer 0 *))
  (loop :for i :from 1 :upto n
     :collect (fib i)))

CL-USER> (loop :for i :from 0 :upto 7070 :when (fibonaccip i) :collect i)
(0 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 2889 3876 4181 5473
 6765 7070)
CL-USER> (seq-fibonaccies 21)
(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946)

And when I increasing the limit of the loop the results start diverging much more.

~$ sbcl --version
SBCL 1.4.14-3.fc31

Body:
As someone else already mentioned, rounding errors accumulate quickly,
so you should stick with the integer arithmetics, using
isqrt:

(defun squarep (n)
  "Check if the given N is a perfect square number.
https://oeis.org/A000290"
  (check-type n (integer 0 *))
  (let ((sqrt (isqrt n)))
    (= n (* sqrt sqrt))))

Also, you have a typo in seq-fibonaccies (fib instead of fibonacci).

Finally, seq-fibonaccies is quadratic in its argument, while it only
have to be linear.


问:
dyld: Library not loaded ... Reason: no suitable image found Xcode Swift
I'm with a problem that I can't run any project on my iPhone.
I can run in the simulator and others iPhones.

This is what happened:

1 - I was running many apps on my iPhone

2 - In a certain moment, I couldn't run because my iPhone reached the limit of provisioning profiles on the device

3 - So I deleted the provisioning profile on the device by the mac (libraries>mobileDevice> provisiongProfiles)

4 - After that, any project with an external library (Alamofire, Firebase, etc) is crashing when opening

5 -  This is the error:

```<code>dyld: Library not loaded: @rpath/NMAKit.framework/NMAKit
Referenced from: /private/var/containers/Bundle/Application/55619F73-FDCC-452B-B834-
CC22C78A190E/navigation_poc.app/navigation_pocReason: no suitable image found.  Did find:
/private/var/containers/Bundle/Application/55619F73-FDCC-452B-B834-
CC22C78A190E/navigation_poc.app/Frameworks/NMAKit.framework/NMAKit: code signature invalid
for '/private/var/containers/Bundle/Application/55619F73-FDCC-452B-B834-
CC22C78A190E/navigation_poc.app/Frameworks/NMAKit.framework/NMAKit'
</code>```

Atention: I don't have an apple developer account, I use xcode automatically Team an Provisioning Profile

I use an Iphone 8 and Xcode 11.3

答:
I have tried many things and nothing worked
(reinstall provisioning profiles, change appleId, change build configurations, write line commands on terminal, restart and reinstall everything, Keychain settings to "Use System Defaults" , etc)

Finally something worked for me:

I'm using CocoaPods, and for me this fixes the error ->

1- Open the podfile

2- Comment out use_frameworks!

3- Add use_modular_headers!

4- In Terminal, do a pod update -> pod install

5- In Xcode, Clean (Command-Shift-K) -> Build and Run.

Source: https://github.com/Alamofire/Alamofire/issues/3051

Body:
I'm with a problem that I can't run any project on my iPhone.
I can run in the simulator and others iPhones.

This is what happened:

1 - I was running many apps on my iPhone

2 - In a certain moment, I couldn't run because my iPhone reached the limit of provisioning profiles on the device

3 - So I deleted the provisioning profile on the device by the mac (libraries>mobileDevice> provisiongProfiles)

4 - After that, any project with an external library (Alamofire, Firebase, etc) is crashing when opening

5 -  This is the error:

dyld: Library not loaded: @rpath/NMAKit.framework/NMAKit
Referenced from: /private/var/containers/Bundle/Application/55619F73-FDCC-452B-B834-
CC22C78A190E/navigation_poc.app/navigation_pocReason: no suitable image found.  Did find:
/private/var/containers/Bundle/Application/55619F73-FDCC-452B-B834-
CC22C78A190E/navigation_poc.app/Frameworks/NMAKit.framework/NMAKit: code signature invalid
for '/private/var/containers/Bundle/Application/55619F73-FDCC-452B-B834-
CC22C78A190E/navigation_poc.app/Frameworks/NMAKit.framework/NMAKit'

Atention: I don't have an apple developer account, I use xcode automatically Team an Provisioning Profile

I use an Iphone 8 and Xcode 11.3


答:
Assuming your desired range of calculation is between from_to and to_from, your calculation looks a bit odd:

```<code>int draw(int from_to, int to_from) {
    return (rand()%to_from)+from_to;
}
</code>```

When we fill in the values 5 and 10, we get the following formula:

```<code>(rand()% 5) + 10
</code>```

This would have a big change of exceeding the boundary of from_to, which in this case is 10. In order to fix this, you can use the following formula instead:

```<code>return rand() % (to_from-from_to + 1) + from_to;
</code>```

Title: Random numbers from specific range

Body:
Assuming your desired range of calculation is between from_to and to_from, your calculation looks a bit odd:

int draw(int from_to, int to_from) {
    return (rand()%to_from)+from_to;
}

When we fill in the values 5 and 10, we get the following formula:

(rand()% 5) + 10

This would have a big change of exceeding the boundary of from_to, which in this case is 10. In order to fix this, you can use the following formula instead:

return rand() % (to_from-from_to + 1) + from_to;