问:
python / django, where is the root of the namespace?
coming from php, the namespaces are always well defined in php, typically using psr-4 from composer

https://getcomposer.org/doc/04-schema.md#psr-4

e.g. you have a folder

src/Foo/Bar/Baz

you then define in the composer.json file that
src/Foo is where the namespace Foo starts

thereafter, all subfolders are by convention, a new sub namespace e.g.

src/Foo/Bar/Baz/MyClass.php turns into

Foo.Bar.Baz.MyClass

Say I want to drop a utility python class into my django project, that I want to use in all django "apps"

Where would I drop it, and how to properly define the namespace? what is the transparent way to understand namespaces in python?

答:
In Python, there is a search path for modules. It can be initialized from the command line with the PYTHONPATH environment variable and accessed programmatically via sys.path.

By default, the directory of the script you use to start the Python interpreter is the first entry in the search path.

Any module or package on the python path "starts a new namespace", to use your wording. Let's assume your project called mysite has an app called polls and has this structure:

```<code>mysite
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── utils.py
│   └── wsgi.py
├── polls
│   ├── __init__.py
│   ├── models.py
│   ├── utils.py
...
</code>```

If you start it with python manage.py runserver, the packages mysite and polls are available.

I'd say a good place for project-wide utils module is the project package mysite. So you do import mysite.utils in any of your apps. If it grows beyond a single file, you can turn it into a subpackage, so instead of a utils.py, you have a utils directory containing an __init__.py file.

The above structure clutters the global namespace a bit. So some people prefer a structure where all your apps are subpackages of your project package, like this:

```<code>mysite
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── utils.py
│   ├── wsgi.py
│   └── apps
│       └── polls
│           ├── __init__.py
│           ├── models.py
│           ├── utils.py
...
</code>```

Body:
In Python, there is a search path for modules. It can be initialized from the command line with the PYTHONPATH environment variable and accessed programmatically via sys.path.

By default, the directory of the script you use to start the Python interpreter is the first entry in the search path.

Any module or package on the python path "starts a new namespace", to use your wording. Let's assume your project called mysite has an app called polls and has this structure:

mysite
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── utils.py
│   └── wsgi.py
├── polls
│   ├── __init__.py
│   ├── models.py
│   ├── utils.py
...

If you start it with python manage.py runserver, the packages mysite and polls are available.

I'd say a good place for project-wide utils module is the project package mysite. So you do import mysite.utils in any of your apps. If it grows beyond a single file, you can turn it into a subpackage, so instead of a utils.py, you have a utils directory containing an __init__.py file.

The above structure clutters the global namespace a bit. So some people prefer a structure where all your apps are subpackages of your project package, like this:

mysite
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── utils.py
│   ├── wsgi.py
│   └── apps
│       └── polls
│           ├── __init__.py
│           ├── models.py
│           ├── utils.py
...


来源: stackexchange

问:
IBM Watson STT: How to use Websocket interface with multiple chunks?
I have developed an application for streaming speech recognition in c++ using another API and IBM Watson Speech to Text service API.

In both these programs, I am using the same file which contains this audio

several tornadoes touch down as a line of severe thunderstorms swept through Colorado on Sunday

This file is 641,680 bytes in size and I am sending 100,000 bytes (max) chunks at a time to the Speech to text servers.

Now, with the other API I am able to have everything recognized as a whole. With the IBM Watson API I couldn't. Here is what I have done:

Connect to IBM Watson web server (Speech to text API)

Send start frame {"action":"start","content-type":"audio/mulaw;rate=8000"}

Send binary 100,000 bytes

Send stop frame {"action":"stop"}

...Repeat binary and stop until the last byte.

The IBM Watson Speech API could only recognize the chunks individually

e.g.

several tornadoes touch down

     a line of severe thunder

     swept through Colorado

     Sunday

This seems to be the output of individual chunks and the words coming in between the chunk division (for eg here, "thunderstorm" is partially present in the end of a chunk and partially in the starting of the next chunk) are thus incorrectly recognized or dropped.

What am I doing wrong?

EDIT (I am using c++ with boost library for websocket interface)

```<code>//Do the websocket handshake
void IbmWebsocketSession::on_ssl_handshake(beast::error_code ec) {

    auto mToken = mSttServiceObject->GetToken(); // Get the authentication token

    //Complete the websocket handshake and call back the "send_start" function
    mWebSocket.async_handshake_ex(mHost, mUrlEndpoint, [mToken](request_type& reqHead) {reqHead.insert(http::field::authorization,mToken);},
            bind(&IbmWebsocketSession::send_start, shared_from_this(), placeholders::_1));
}

//Sent the start frame
void IbmWebsocketSession::send_start(beast::error_code ec) {

    //Send the START_FRAME and call back the "read_resp" function to receive the "state: listening" message
    mWebSocket.async_write(net::buffer(START_FRAME),
            bind(&IbmWebsocketSession::read_resp, shared_from_this(), placeholders::_1, placeholders::_2));
}

//Sent the binary data
void IbmWebsocketSession::send_binary(beast::error_code ec) {

    streamsize bytes_read = mFilestream.rdbuf()->sgetn(&chunk[0], chunk.size()); //gets the binary data chunks from a file (which is being written at run time

    // Send binary data
    if (bytes_read > mcMinsize) {  //Minimum size defined by IBM  is 100 bytes.
                                   // If chunk size is greater than 100 bytes, then send the data and then callback "send_stop" function
        mWebSocket.binary(true);

        /**********************************************************************
         *  Wait a second before writing the next chunk.
         **********************************************************************/
        this_thread::sleep_for(chrono::seconds(1));

        mWebSocket.async_write(net::buffer(&chunk[0], bytes_read),
                bind(&IbmWebsocketSession::send_stop, shared_from_this(), placeholders::_1));
    } else {                     //If chunk size is less than 100 bytes, then DO NOT send the data only call "send_stop" function
        shared_from_this()->send_stop(ec);
    }

}

void IbmWebsocketSession::send_stop(beast::error_code ec) {

    mWebSocket.binary(false);
    /*****************************************************************
     * Send the Stop message
     *****************************************************************/
    mWebSocket.async_write(net::buffer(mTextStop),
            bind(&IbmWebsocketSession::read_resp, shared_from_this(), placeholders::_1, placeholders::_2));
}

void IbmWebsocketSession::read_resp(beast::error_code ec, size_t bytes_transferred) {
    boost::ignore_unused(bytes_transferred);
        if(mWebSocket.is_open())
        {
            // Read the websocket response and call back the "display_buffer" function
            mWebSocket.async_read(mBuffer, bind(&IbmWebsocketSession::display_buffer, shared_from_this(),placeholders::_1));
        }
        else
            cerr << "Error: " << e->what() << endl;

}

void IbmWebsocketSession::display_buffer(beast::error_code ec) {

    /*****************************************************************
     * Get the buffer into stringstream
     *****************************************************************/
    msWebsocketResponse << beast::buffers(mBuffer.data());

    mResponseTranscriptIBM = ParseTranscript(); //Parse the response transcript

    mBuffer.consume(mBuffer.size()); //Clear the websocket buffer

    if ("Listening" == mResponseTranscriptIBM && true != mSttServiceObject->IsGstFileWriteDone()) { // IsGstFileWriteDone -> checks if the user has stopped speaking
        shared_from_this()->send_binary(ec);
    } else {
        shared_from_this()->close_websocket(ec, 0);
    }
}
</code>```

答:
IBM Watson Speech to Text has several APIs to transmit audio and receive transcribed text. Based on your description you seem to use the WebSocket Interface.

For the WebSocket Interface, you would open the connection (start), then send individual chunks of data, and - once everything has been transmitted - stop the recognition request.

You have not shared code, but it seems you are starting and stopping a request for each chunk. Only stop after the last chunk.

I would recommend to take a look at the API doc which contains samples in different languages. The Node.js sample shows how to register for events. There are also examples on GitHub like this WebSocket API with Python. And here is another one that shows the chunking.

ContentLicense: CC BY-SA 4.0

Body:
I have developed an application for streaming speech recognition in c++ using another API and IBM Watson Speech to Text service API.

In both these programs, I am using the same file which contains this audio

several tornadoes touch down as a line of severe thunderstorms swept through Colorado on Sunday

This file is 641,680 bytes in size and I am sending 100,000 bytes (max) chunks at a time to the Speech to text servers.

Now, with the other API I am able to have everything recognized as a whole. With the IBM Watson API I couldn't. Here is what I have done:

Connect to IBM Watson web server (Speech to text API)

Send start frame {"action":"start","content-type":"audio/mulaw;rate=8000"}

Send binary 100,000 bytes

Send stop frame {"action":"stop"}

...Repeat binary and stop until the last byte.

The IBM Watson Speech API could only recognize the chunks individually

e.g.

several tornadoes touch down

     a line of severe thunder

     swept through Colorado

     Sunday

This seems to be the output of individual chunks and the words coming in between the chunk division (for eg here, "thunderstorm" is partially present in the end of a chunk and partially in the starting of the next chunk) are thus incorrectly recognized or dropped.

What am I doing wrong?

EDIT (I am using c++ with boost library for websocket interface)

//Do the websocket handshake
void IbmWebsocketSession::on_ssl_handshake(beast::error_code ec) {

    auto mToken = mSttServiceObject->GetToken(); // Get the authentication token

    //Complete the websocket handshake and call back the "send_start" function
    mWebSocket.async_handshake_ex(mHost, mUrlEndpoint, [mToken](request_type& reqHead) {reqHead.insert(http::field::authorization,mToken);},
            bind(&IbmWebsocketSession::send_start, shared_from_this(), placeholders::_1));
}

//Sent the start frame
void IbmWebsocketSession::send_start(beast::error_code ec) {

    //Send the START_FRAME and call back the "read_resp" function to receive the "state: listening" message
    mWebSocket.async_write(net::buffer(START_FRAME),
            bind(&IbmWebsocketSession::read_resp, shared_from_this(), placeholders::_1, placeholders::_2));
}

//Sent the binary data
void IbmWebsocketSession::send_binary(beast::error_code ec) {

    streamsize bytes_read = mFilestream.rdbuf()->sgetn(&chunk[0], chunk.size()); //gets the binary data chunks from a file (which is being written at run time

    // Send binary data
    if (bytes_read > mcMinsize) {  //Minimum size defined by IBM  is 100 bytes.
                                   // If chunk size is greater than 100 bytes, then send the data and then callback "send_stop" function
        mWebSocket.binary(true);

        /**********************************************************************
         *  Wait a second before writing the next chunk.
         **********************************************************************/
        this_thread::sleep_for(chrono::seconds(1));

        mWebSocket.async_write(net::buffer(&chunk[0], bytes_read),
                bind(&IbmWebsocketSession::send_stop, shared_from_this(), placeholders::_1));
    } else {                     //If chunk size is less than 100 bytes, then DO NOT send the data only call "send_stop" function
        shared_from_this()->send_stop(ec);
    }

}

void IbmWebsocketSession::send_stop(beast::error_code ec) {

    mWebSocket.binary(false);
    /*****************************************************************
     * Send the Stop message
     *****************************************************************/
    mWebSocket.async_write(net::buffer(mTextStop),
            bind(&IbmWebsocketSession::read_resp, shared_from_this(), placeholders::_1, placeholders::_2));
}

void IbmWebsocketSession::read_resp(beast::error_code ec, size_t bytes_transferred) {
    boost::ignore_unused(bytes_transferred);
        if(mWebSocket.is_open())
        {
            // Read the websocket response and call back the "display_buffer" function
            mWebSocket.async_read(mBuffer, bind(&IbmWebsocketSession::display_buffer, shared_from_this(),placeholders::_1));
        }
        else
            cerr << "Error: " << e->what() << endl;

}

void IbmWebsocketSession::display_buffer(beast::error_code ec) {

    /*****************************************************************
     * Get the buffer into stringstream
     *****************************************************************/
    msWebsocketResponse << beast::buffers(mBuffer.data());

    mResponseTranscriptIBM = ParseTranscript(); //Parse the response transcript

    mBuffer.consume(mBuffer.size()); //Clear the websocket buffer

    if ("Listening" == mResponseTranscriptIBM && true != mSttServiceObject->IsGstFileWriteDone()) { // IsGstFileWriteDone -> checks if the user has stopped speaking
        shared_from_this()->send_binary(ec);
    } else {
        shared_from_this()->close_websocket(ec, 0);
    }
}


问:
Can two computers on different wifi networks have same local IP address? (ex. 192.168.0.1 for both systems on diff. network)
I have a validation in NodeJS where I need a IP of system to validate duplicate requests. Here, I'm confused about the uniqueness of the local IP addresses for the systems on different WIFI networks. Can they be same for both systems or are always unique?</p>

答:
Yes, two computers can have same IP on two contiguous networks in RFC 1918 address space, that is private range. Considering those two networks talk to each other using NAT, Network Address Translation.

Two computers cannot have same address when they are using IPs from public address space if they are connected to the Internet.


问:
QMap<int,QByteArray> return Wrong QByteArray
I am using

```<code>QMap < int, QByteArray> RegTable; (Seprate Class Variable)
</code>```

to storing Modbus Register Address and data received from  Serial Port. Everything working fine, data read from the serial port and fill to the QByteArray correctly.

```<code>qDebug() << Modbus->RegTable[RegAddr].toHex(' ');
</code>```

print the correct data. But if want to write variable using it then always the same value/Garbage stored in this variable.

```<code>    unsigned int unixTimeStamp = 0;
    qDebug() << Modbus->RegTable[RegAddr].toHex(' ');

    unixTimeStamp  = static_cast <unsigned int>Modbus->RegTable[RegAddr].at(4);
    unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(5)<<8;
    unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(6)<<16;
    unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(7)<<24;

    QDateTime timestamp;
    timestamp.setTime_t(unixTimeStamp  );
    qDebug() << timestamp.toString(Qt::SystemLocaleShortDate); //wrong time
</code>```

RegTable is Modbus Class variable, And I used it to the main class but always I get the wrong data or values.

答:
With

```<code>unixTimeStamp |= ...;
</code>```

you write to the same byte over and over again. You need to shift the values:

```<code>unixTimeStamp  = static_cast <unsigned int>Modbus->RegTable[RegAddr].at(4) << 24;
unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(5) << 16;
unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(6) <<  8;
unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(7);
</code>```

Of course, the shifts might have to be done in the opposite order depending on byte order.

Body:
I am using

QMap < int, QByteArray> RegTable; (Seprate Class Variable)

to storing Modbus Register Address and data received from  Serial Port. Everything working fine, data read from the serial port and fill to the QByteArray correctly.

qDebug() << Modbus->RegTable[RegAddr].toHex(' ');

print the correct data. But if want to write variable using it then always the same value/Garbage stored in this variable.

    unsigned int unixTimeStamp = 0;
    qDebug() << Modbus->RegTable[RegAddr].toHex(' ');

    unixTimeStamp  = static_cast <unsigned int>Modbus->RegTable[RegAddr].at(4);
    unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(5)<<8;
    unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(6)<<16;
    unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(7)<<24;

    QDateTime timestamp;
    timestamp.setTime_t(unixTimeStamp  );
    qDebug() << timestamp.toString(Qt::SystemLocaleShortDate); //wrong time

RegTable is Modbus Class variable, And I used it to the main class but always I get the wrong data or values.

Body:
With

unixTimeStamp |= ...;

you write to the same byte over and over again. You need to shift the values:

unixTimeStamp  = static_cast <unsigned int>Modbus->RegTable[RegAddr].at(4) << 24;
unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(5) << 16;
unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(6) <<  8;
unixTimeStamp |= static_cast <unsigned int>Modbus->RegTable[RegAddr].at(7);

Of course, the shifts might have to be done in the opposite order depending on byte order.


问:
Unable to take Input values from Tensorflow Serving client request
I am trying to deploy my tensorflow model in a tensorflow serving using tensorflow saved model. Input for my tf model is a string value and i have defined my signature as below

```<code>        prediction_signature = (
            tf.saved_model.signature_def_utils.build_signature_def(
                inputs={'input_path': tensor_info_input},
                outputs={'output_prediction': tensor_info_output},
                method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))

        builder.add_meta_graph_and_variables(
            sess, [tf.saved_model.tag_constants.SERVING],
            signature_def_map={
                'predict_images':
                    prediction_signature,
            })
</code>```

My objective is to read a image from the path specified in signature definition. How do i get the input_path from input definition and convert the tensor into actual string value to read the path

答:
I think you need to add some "reading operation" in your model file.

Like this:

```<code>def inference(image_path_string):
    # read image from a image path string
    image_file = tf.read_file(image_path_string)
    image_raw = tf.cond(tf.image.is_jpeg(image_file),
                        lambda: tf.image.decode_jpeg(image_file, channels= 3 if rgb, else 1),
                        lambda: tf.image.decode_bmp(image_file))
    # image preprocessing code
    ...
    ...
    # your prediction model code
    ...
    ...
</code>```

Body:
I am trying to deploy my tensorflow model in a tensorflow serving using tensorflow saved model. Input for my tf model is a string value and i have defined my signature as below

        prediction_signature = (
            tf.saved_model.signature_def_utils.build_signature_def(
                inputs={'input_path': tensor_info_input},
                outputs={'output_prediction': tensor_info_output},
                method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))

        builder.add_meta_graph_and_variables(
            sess, [tf.saved_model.tag_constants.SERVING],
            signature_def_map={
                'predict_images':
                    prediction_signature,
            })

My objective is to read a image from the path specified in signature definition. How do i get the input_path from input definition and convert the tensor into actual string value to read the path

Body:
I think you need to add some "reading operation" in your model file.

Like this:

def inference(image_path_string):
    # read image from a image path string
    image_file = tf.read_file(image_path_string)
    image_raw = tf.cond(tf.image.is_jpeg(image_file),
                        lambda: tf.image.decode_jpeg(image_file, channels= 3 if rgb, else 1),
                        lambda: tf.image.decode_bmp(image_file))
    # image preprocessing code
    ...
    ...
    # your prediction model code
    ...
    ...


问:
Adding claims to IdentityServer setup by AddIdentityServer
I have a SPA that has an ASP.NET Core web API together with the inbuilt identity server switched on using AddIdentityServer and then AddIdentityServerJwt:

```<code>services.AddIdentityServer()
   .AddApiAuthorization<User, UserDataContext>();
services.AddAuthentication()
   .AddIdentityServerJwt();
</code>```

I also have an authorization policy setup that requires an "Admin" role claim:

```<code>services.AddAuthorization(options =>
{
    options.AddPolicy("IsAdmin", policy => policy.RequireClaim(ClaimTypes.Role, "Admin"));
});
</code>```

I have a controller action that uses this policy

```<code>[Authorize(Policy = "IsAdmin")]
[HttpDelete("{id}")]
public IActionResult Deleten(int id)
{
    ...
}
</code>```

The authenticated user does have the "Admin" role claim:

The access token for this authentication user doesn't appear to contain the admin claim:

I get a 403 back when trying to request this resource with the admin user:

So, if I'm understanding this correctly, IdentityServer isn't including the admin role claim and so the user isn't authorized to access the resource.

Is it possible to configure the claims that IdentityServer uses using AddIdentityServerJwt? or am I misunderstanding why this is not working.

答:
I did this without using roles but with using a special claim added to the users token.  I have created a CustomUserClaimsPrincipalFactory this allows me to add additional claims to the user.

register

```<code>services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, CustomUserClaimsPrincipalFactory>();
</code>```

the code.

```<code>public class CustomUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole<long>>
    {
        public CustomUserClaimsPrincipalFactory(
            UserManager<ApplicationUser> userManager,
            RoleManager<IdentityRole<long>> roleManager,
            IOptions<IdentityOptions> optionsAccessor)
            : base(userManager, roleManager, optionsAccessor)
        {
        }

        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
        {
            var userId = await UserManager.GetUserIdAsync(user);
            var userName = await UserManager.GetUserNameAsync(user);
            var id = new ClaimsIdentity("Identity.Application",
                Options.ClaimsIdentity.UserNameClaimType,
                Options.ClaimsIdentity.RoleClaimType);
            id.AddClaim(new Claim(Options.ClaimsIdentity.UserIdClaimType, userId));
            id.AddClaim(new Claim(Options.ClaimsIdentity.UserNameClaimType, user.Name));
            id.AddClaim(new Claim("preferred_username", userName));
            id.AddClaim(new Claim("culture", user.Culture ?? "da-DK"));
            if (UserManager.SupportsUserSecurityStamp)
            {
                id.AddClaim(new Claim(Options.ClaimsIdentity.SecurityStampClaimType,
                    await UserManager.GetSecurityStampAsync(user)));
            }
            if (UserManager.SupportsUserClaim)
            {
                id.AddClaims(await UserManager.GetClaimsAsync(user));
            }

            if(user.IsXenaSupporter)
               id.AddClaim(new Claim("supporter", user.Id.ToString()));
            return id;
        }
    }
</code>```

policy

```<code>services.AddAuthorization(options =>
            {
                options.AddPolicy("Supporter", policy => policy.RequireClaim("supporter"));
            });
</code>```

usage

```<code>    [Authorize(AuthenticationSchemes = "Bearer", Policy = "Supporter")]
    [HttpPost("supporter")]
    public async Task<ActionResult> ChangeToSpecificUser([FromBody] ChangeUserRequest request)
    {

     // ..................

    }
</code>```

Body:
I have a SPA that has an ASP.NET Core web API together with the inbuilt identity server switched on using AddIdentityServer and then AddIdentityServerJwt:

services.AddIdentityServer()
   .AddApiAuthorization<User, UserDataContext>();
services.AddAuthentication()
   .AddIdentityServerJwt();

I also have an authorization policy setup that requires an "Admin" role claim:

services.AddAuthorization(options =>
{
    options.AddPolicy("IsAdmin", policy => policy.RequireClaim(ClaimTypes.Role, "Admin"));
});

I have a controller action that uses this policy

[Authorize(Policy = "IsAdmin")]
[HttpDelete("{id}")]
public IActionResult Deleten(int id)
{
    ...
}

The authenticated user does have the "Admin" role claim:

The access token for this authentication user doesn't appear to contain the admin claim:

I get a 403 back when trying to request this resource with the admin user:

So, if I'm understanding this correctly, IdentityServer isn't including the admin role claim and so the user isn't authorized to access the resource.

Is it possible to configure the claims that IdentityServer uses using AddIdentityServerJwt? or am I misunderstanding why this is not working.

Body:
I did this without using roles but with using a special claim added to the users token.  I have created a CustomUserClaimsPrincipalFactory this allows me to add additional claims to the user.

register

services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, CustomUserClaimsPrincipalFactory>();

the code.

public class CustomUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole<long>>
    {
        public CustomUserClaimsPrincipalFactory(
            UserManager<ApplicationUser> userManager,
            RoleManager<IdentityRole<long>> roleManager,
            IOptions<IdentityOptions> optionsAccessor)
            : base(userManager, roleManager, optionsAccessor)
        {
        }

        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
        {
            var userId = await UserManager.GetUserIdAsync(user);
            var userName = await UserManager.GetUserNameAsync(user);
            var id = new ClaimsIdentity("Identity.Application",
                Options.ClaimsIdentity.UserNameClaimType,
                Options.ClaimsIdentity.RoleClaimType);
            id.AddClaim(new Claim(Options.ClaimsIdentity.UserIdClaimType, userId));
            id.AddClaim(new Claim(Options.ClaimsIdentity.UserNameClaimType, user.Name));
            id.AddClaim(new Claim("preferred_username", userName));
            id.AddClaim(new Claim("culture", user.Culture ?? "da-DK"));
            if (UserManager.SupportsUserSecurityStamp)
            {
                id.AddClaim(new Claim(Options.ClaimsIdentity.SecurityStampClaimType,
                    await UserManager.GetSecurityStampAsync(user)));
            }
            if (UserManager.SupportsUserClaim)
            {
                id.AddClaims(await UserManager.GetClaimsAsync(user));
            }

            if(user.IsXenaSupporter)
               id.AddClaim(new Claim("supporter", user.Id.ToString()));
            return id;
        }
    }

policy

services.AddAuthorization(options =>
            {
                options.AddPolicy("Supporter", policy => policy.RequireClaim("supporter"));
            });

usage

    [Authorize(AuthenticationSchemes = "Bearer", Policy = "Supporter")]
    [HttpPost("supporter")]
    public async Task<ActionResult> ChangeToSpecificUser([FromBody] ChangeUserRequest request)
    {

     // ..................

    }


问:
How can i know which link I clicked?
I'm deploying a table where you can edit the columns. For that, in each cell there's an  to show a modal to change que value in the database and refresh the page. For now it does well the modal appearing but for the moment the modal appears, the code doesn't know which link was clicked. I need to know it to get the id of the row. The JQuery method that calls the last button of the modal ('Guardar') needs to call a php script by AJAX and send the id of the row (to make the UPDATE statement) and the new value of the column.

I tried to use the methods closest() and find() from JQuery and to set a the id of the row in a data-id attribute.

This is where I deploy the table vía PHP(code is simplified to one column to read and understand it better)

```<code>if($resHitos->num_rows>0){
    while ($columna = mysqli_fetch_assoc($resHitos)) {
        $id=$columna['id'];
        echo "<tr data-id='$id'>";
        echo "<td style='text-align:center'><p><a data-toggle='modal' data-target='#modalEditHito'>".$columna['descripcion']."</a></p></td>";
        echo "</tr>";
    }
}
</code>```

This is the modal

```<code><div class="modal fade" id="modalEditarHito" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Editar objetivo</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="newObjetivo">Objetivo</label>
                        <textarea class="form-control" rows="5" id="editObjetivo"></textarea><br>
                 </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal" onclick="editDescripcionHito()">Guardar</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>
</code>```

The expected result is to see the new value inputed in the exact row that was clicked.

答:
You can use a data attribute to uniquely identify rows. or you can simply add id attribute like this

```<code> echo '<tr data-id=".$columnna['id'].">';
</code>```

You should change this line
echo "
".$columna['descripcion']."
	";

to

echo "
".$columna['descripcion']."
	";

Title: How can i know which link I clicked?

Body:
I'm deploying a table where you can edit the columns. For that, in each cell there's an  to show a modal to change que value in the database and refresh the page. For now it does well the modal appearing but for the moment the modal appears, the code doesn't know which link was clicked. I need to know it to get the id of the row. The JQuery method that calls the last button of the modal ('Guardar') needs to call a php script by AJAX and send the id of the row (to make the UPDATE statement) and the new value of the column.

I tried to use the methods closest() and find() from JQuery and to set a the id of the row in a data-id attribute.

This is where I deploy the table vía PHP(code is simplified to one column to read and understand it better)

if($resHitos->num_rows>0){
    while ($columna = mysqli_fetch_assoc($resHitos)) {
        $id=$columna['id'];
        echo "
";
        echo "
".$columna['descripcion']."
	";
        echo "
";
    }
}

This is the modal

Editar objetivo

                    Objetivo
                        <textarea class="form-control" rows="5" id="editObjetivo"></textarea>

                <button type="button" class="btn btn-default" data-dismiss="modal" onclick="editDescripcionHito()">Guardar</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>

The expected result is to see the new value inputed in the exact row that was clicked.

Body:
You can use a data attribute to uniquely identify rows. or you can simply add id attribute like this

 echo '<tr data-id=".$columnna['id'].">';

You should change this line
echo "<td style='text-align:center'><p><a data-toggle='modal' data-target='#modalEditHito'>".$columna['descripcion']."</a></p></td>";

to

echo "<td style='text-align:center'><p><a data-toggle='modal' data-target='#modalEditHito".$columnna['id']."'>".$columna['descripcion']."</a></p></td>";


问:
Is it possible to put calculation inside plotbands using highcharts?
I build line charts using highcharts library. In the highcharts I am using plotBands. Is it possible to put calculation inside plotBands like shown below?

`

```<code>plotBands: [{
                    from:{
                         formatter: function() {
                                 return Math.round(Math.log10(-10.0));
                        }},
                    to: {
                         formatter: function() {
                                 return Math.round(Math.log10(1.0));
                        }},,
                    color: '#00A19C'
                },
</code>```

`

答:
You can achieve it using IIFE:

```<code>  yAxis: {
    plotBands: [{
      color: '#FCFFC5',
      from: (function() {
        return Math.round(Math.log10(-10.0));
      })(),
      to: (function() {
        return Math.round(Math.log10(1.0));
      })()
    }]
  }
</code>```

Demo:

https://jsfiddle.net/BlackLabel/056u7ob3/

Body:
I build line charts using highcharts library. In the highcharts I am using plotBands. Is it possible to put calculation inside plotBands like shown below?

`

plotBands: [{
                    from:{
                         formatter: function() {
                                 return Math.round(Math.log10(-10.0));
                        }},
                    to: {
                         formatter: function() {
                                 return Math.round(Math.log10(1.0));
                        }},,
                    color: '#00A19C'
                },

`

Body:
You can achieve it using IIFE:

  yAxis: {
    plotBands: [{
      color: '#FCFFC5',
      from: (function() {
        return Math.round(Math.log10(-10.0));
      })(),
      to: (function() {
        return Math.round(Math.log10(1.0));
      })()
    }]
  }

Demo:

https://jsfiddle.net/BlackLabel/056u7ob3/


问:
Force Proximity Search into multiple word wordform?
I use Proximity to good use with Sphinx e.g. Twain NEAR/1 Mark will return

Mark Twain

and

Twain, Mark

But say I had a word form like:

Weekday > Week Day

How could I set any given search to use Proximity NEAR/3 (or NEAR/X) so it would find

Week Day

and

Day of Week

I get in this case there are other ways to skin the cat but in general, looking for a way that the multiple word map doe not get pushed as 'Word1 Word2' i.e. 'Week Day' because otherwise I get docs such as

'I worked for one entire day before realizing it was going to take a

full week'

Body:
There's no easy way out of the box. You can perhaps make a change in your app so it does changes each 'word' to "word"~N in your search query or even better do that only for the same wordforms that Sphinx deals with. Here's an example:

mysql> select *, weight() from idx_min where match('weekday');
+------+-------------------------------------------------------------------------------+------+----------+
| id   | doc                                                                           | a    | weight() |
+------+-------------------------------------------------------------------------------+------+----------+
|    1 | Weekday                                                                       |    1 |     2319 |
|    2 | day of week                                                                   |    2 |     1319 |
|    3 | I worked for one entire day before realizing it was going to take a full week |    3 |     1319 |
+------+-------------------------------------------------------------------------------+------+----------+
3 rows in set (0.00 sec)

mysql> select *, weight() from idx_min where match('"weekday"');
+------+---------+------+----------+
| id   | doc     | a    | weight() |
+------+---------+------+----------+
|    1 | Weekday |    1 |     2319 |
+------+---------+------+----------+
1 row in set (0.00 sec)

mysql> select *, weight() from idx_min where match('"weekday"~2');
+------+-------------+------+----------+
| id   | doc         | a    | weight() |
+------+-------------+------+----------+
|    1 | Weekday     |    1 |     2319 |
|    2 | day of week |    2 |     1319 |
+------+-------------+------+----------+
2 rows in set (0.00 sec)

mysql> select *, weight() from idx_min where match('"entire"~2 "day"~2');
+------+-------------------------------------------------------------------------------+------+----------+
| id   | doc                                                                           | a    | weight() |
+------+-------------------------------------------------------------------------------+------+----------+
|    3 | I worked for one entire day before realizing it was going to take a full week |    3 |     1500 |
+------+-------------------------------------------------------------------------------+------+----------+
1 row in set (0.00 sec)

mysql> select *, weight() from idx_min where match('weekday full week');
+------+-------------------------------------------------------------------------------+------+----------+
| id   | doc                                                                           | a    | weight() |
+------+-------------------------------------------------------------------------------+------+----------+
|    3 | I worked for one entire day before realizing it was going to take a full week |    3 |     2439 |
+------+-------------------------------------------------------------------------------+------+----------+
1 row in set (0.01 sec)

mysql> select *, weight() from idx_min where match('"weekday"~2 full week');
Empty set (0.00 sec)

The last one would be the best way to go, but you would have to:

1) parse your query. E.g. like this:

mysql> call keywords('weekday full week', 'idx_min');
+------+-----------+------------+
| qpos | tokenized | normalized |
+------+-----------+------------+
| 1    | weekday   | week       |
| 2    | weekday   | day        |
| 3    | full      | full       |
| 4    | week      | week       |
+------+-----------+------------+
4 rows in set (0.00 sec)

and if you see that for the same tokenized word you get 2 different normalized words that can be a signal for your app to wrap the tokenized word into "word"~N.

2) run the query. In this case "weekday"~2 full week


问:
Firebase .onCall Cloud Function not being called from within Swift Xcode Project
I have added an iOS app to a firebase project and for some reason the function doesn't get called when I call it from iOS. The connection to Firebase seems to be fine as I can run queries on the Firebase database from within the swift project but when I run the swift cloud function it seems to bypass the code.

Below is the test cloud function I have created just to investigate this:

```<code>  exports.testFunction = functions.https.onCall((data,context) => {
      console.log("hi the test function worked");
      return "hi the test function worked";
  })
</code>```

And this is the swift code I am using to call the function,

```<code>lazy var functions = Functions.functions()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()

    functions.httpsCallable("testFunction").call("Hi", completion: {(result,error) in
        if let error = error{
            print("An error occurred while calling the test function: \(error)" )
        }
        print("Results from test cloud function: \(result)")
    })

    return true
}
</code>```

I've tried updating cocoa pods and creating new projects but nothing has seemed to work. There is nothing being returned to my iOS project or being logged in the firebase console. There are no errors thrown, does anyone have any ideas on what could be causing such a strange occurrence to happen? Thank you.

答:
Running into the same issue, and testing all mentioned scenarios but after a long timeout, the error was always the same.

Switching network connection from "USB-MAC-PHONE shared", to Phone 4G. And the call is successful.

I have not time to test further at the moment, just noticed that issue also replicates on simulators.

Body:
I have added an iOS app to a firebase project and for some reason the function doesn't get called when I call it from iOS. The connection to Firebase seems to be fine as I can run queries on the Firebase database from within the swift project but when I run the swift cloud function it seems to bypass the code.

Below is the test cloud function I have created just to investigate this:

  exports.testFunction = functions.https.onCall((data,context) => {
      console.log("hi the test function worked");
      return "hi the test function worked";
  })

And this is the swift code I am using to call the function,

lazy var functions = Functions.functions()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()

    functions.httpsCallable("testFunction").call("Hi", completion: {(result,error) in
        if let error = error{
            print("An error occurred while calling the test function: \(error)" )
        }
        print("Results from test cloud function: \(result)")
    })

    return true
}

I've tried updating cocoa pods and creating new projects but nothing has seemed to work. There is nothing being returned to my iOS project or being logged in the firebase console. There are no errors thrown, does anyone have any ideas on what could be causing such a strange occurrence to happen? Thank you.


问:
How to change value dynamically in ngx-countdown-timer
I'm using  ngx-countdown-timer but dynamically im not able to pass value please help me to do this.

is there any alternate solution for this.

HTML

```<code><div class="swiper-slide desk" *ngFor="let i of dummy">
  <h1 style="margin-left: 17%; color:#df3b3b">
       <countdown-timer [end]="i.date"  class="dealbox"></countdown-timer>
  </h1>
</div>
</code>```

答:
you can check my code, it is working.
Component class dummy array;

```<code>     public dummy=[
        {
            'id':1,
            'date':'2019-06-01 00:00:00'
        },
        {
            'id':2,
            'date':'2019-07-01 00:00:00'
        }
      ];
</code>```

Component html:

```<code>    <div class="swiper-slide desk" *ngFor="let i of dummy">
        <h1 style="margin-left: 17%; color:#df3b3b">
            <countdown-timer [end]="i.date"  class="dealbox"></countdown-timer>
        </h1>
    </div>
</code>```

Body:
I'm using  ngx-countdown-timer but dynamically im not able to pass value please help me to do this.

is there any alternate solution for this.

HTML

       <countdown-timer [end]="i.date"  class="dealbox"></countdown-timer>

Body:
you can check my code, it is working.
Component class dummy array;

     public dummy=[
        {
            'id':1,
            'date':'2019-06-01 00:00:00'
        },
        {
            'id':2,
            'date':'2019-07-01 00:00:00'
        }
      ];

Component html:

    <div class="swiper-slide desk" *ngFor="let i of dummy">
        <h1 style="margin-left: 17%; color:#df3b3b">
            <countdown-timer [end]="i.date"  class="dealbox"></countdown-timer>
        </h1>
    </div>


问:
how do you broadcast the iphone screen
There are a small number of iOS apps which can broadcast the entire iPhone screen (mirror the whole screen including the homescreen) -> Teamviewer, Microsoft Teams, RescueAssist. To do so the user will start the video recording and choose one of those apps as the broadcast receiver.

How do you write such an app? I have searched through the web and I did not find a detailed technical explanation what is required to do so.

答:
As suggested you have to create a broadcast extension. That extension gives you the method calls which delivers the frames. Then you can stream the frames to the internet (e.g. Haishinkit).

```<code>override func processSampleBuffer(_ sampleBuffer: CMSampleBuffer, with sampleBufferType: RPSampleBufferType) {

    switch sampleBufferType {
        case RPSampleBufferType.video:
            rtmpStream?.appendSampleBuffer(sampleBuffer, withType: AVMediaType.video)

            // Handle video sample buffer
            break
        case RPSampleBufferType.audioApp:
            // Handle audio sample buffer for app audio
            break
        case RPSampleBufferType.audioMic:
            // Handle audio sample buffer for mic audio
            break
    }
}
</code>```

Note, that most likely Apple will decline your app. They only allow it for a few cases.

Title: how do you broadcast the iphone screen

Body:
As suggested you have to create a broadcast extension. That extension gives you the method calls which delivers the frames. Then you can stream the frames to the internet (e.g. Haishinkit).

override func processSampleBuffer(_ sampleBuffer: CMSampleBuffer, with sampleBufferType: RPSampleBufferType) {

    switch sampleBufferType {
        case RPSampleBufferType.video:
            rtmpStream?.appendSampleBuffer(sampleBuffer, withType: AVMediaType.video)

            // Handle video sample buffer
            break
        case RPSampleBufferType.audioApp:
            // Handle audio sample buffer for app audio
            break
        case RPSampleBufferType.audioMic:
            // Handle audio sample buffer for mic audio
            break
    }
}

Note, that most likely Apple will decline your app. They only allow it for a few cases.


问:
Getting letters in a string. Why my code didn't work well?
I am new to java and I barely have the time to study it. Actually, my question is a little bit awkward and meaningless. I am trying to get letters from user input. I know that there are more efficient ways to do it, but I only want to know what is wrong with this method. The problem is when I write a string that doesn't contain any space the program is fine but if I write one with spaces it stops work.

```<code>Scanner qx = new Scanner(System.in);
String a = qx.next();
for(int b = 0; b<a.length();b++){
    char z = a.charAt(b);
    System.out.print(z + " ");
    }
</code>```

For example: When I wrote "Hi there" (without quotes)

I expect the output of "H i t h e r e"

But it only shows "H i "

İf I would have written "Hithere"
it would show "H i t h e r e "

So why is there a difference between the one has spaces and the one doesn't?

Also, I am sorry for my grammar. I tried to do my best but I haven't practised for a long time.

答:
I had these same problems when started to code in java. Like reading inputs which are mixed with integer and string.

For Ex :

if you want to read...

```<code>5 // as an Integer
Hi there // as a string
</code>```

you have to code like this

```<code>Scanner in = new Scanner(System.in);
int number = in.nextInt();
in.next();
String str = in.nextLine();
</code>```

I put that extra  in.next() to move the buffer to the next line (as it would be only at the end of the same line after reading an integer number).

So, now coming to your question, next() will just read the bytes until the whitespace occurs. so if you want to read one full line of input you have to use nextLine(). nextLine() will read the whole line.

Body:
I am new to java and I barely have the time to study it. Actually, my question is a little bit awkward and meaningless. I am trying to get letters from user input. I know that there are more efficient ways to do it, but I only want to know what is wrong with this method. The problem is when I write a string that doesn't contain any space the program is fine but if I write one with spaces it stops work.

Scanner qx = new Scanner(System.in);
String a = qx.next();
for(int b = 0; b<a.length();b++){
    char z = a.charAt(b);
    System.out.print(z + " ");
    }

For example: When I wrote "Hi there" (without quotes)

I expect the output of "H i t h e r e"

But it only shows "H i "

İf I would have written "Hithere"
it would show "H i t h e r e "

So why is there a difference between the one has spaces and the one doesn't?

Also, I am sorry for my grammar. I tried to do my best but I haven't practised for a long time.

Body:
I had these same problems when started to code in java. Like reading inputs which are mixed with integer and string.

For Ex :

if you want to read...

5 // as an Integer
Hi there // as a string

you have to code like this

Scanner in = new Scanner(System.in);
int number = in.nextInt();
in.next();
String str = in.nextLine();

I put that extra  in.next() to move the buffer to the next line (as it would be only at the end of the same line after reading an integer number).

So, now coming to your question, next() will just read the bytes until the whitespace occurs. so if you want to read one full line of input you have to use nextLine(). nextLine() will read the whole line.


问:
Botium isn't working following the tutorial
I'm setting up Botium testing freamework to run some tests against my watson based chatbot, I'm encountering Error: WATSON_USER capability required, I'm follwoing the tutorial available here https://chatbotsmagazine.com/10-minutes-codeless-test-automation-for-ibm-watson-chatbots-d71eac9626d7

As part of the error message, it's also suggesting me to use API key, I'm not sure how to get one.

```<code>botium-cli emulator --config ./botium.json
Error: WATSON_USER capability required (or use WATSON_APIKEY)
    at BotiumConnectorWatson.Validate (/usr/local/lib/node_modules/botium-cli/node_modules/botium-connector-watson/dist/botium-connector-watson-cjs.js:60:55)
    at Validate.Validate.then (/usr/local/lib/node_modules/botium-cli/node_modules/botium-core/src/containers/PluginConnectorContainer.js:72:66)
</code>```

My config looks like:

{
    "botium": {
        "Capabilities": {
            "PROJECTNAME": "****",
            "CONTAINERMODE": "watson",
            "WATSONCONVERSATION_USER": "*****",
            "WATSONCONVERSATION_PASSWORD": "*****",
            "WATSONCONVERSATION_WORKSPACE_ID": "****",
            "WATSONCONVERSATION_USE_INTENT": false
        }
    }
}
```

答:
The error message most likely refers to you requiring a valid username/password (process has changed).

Your IBM cloud username /password is not used for this. When you created the Watson Assistant resource it creates a default credentials for that resource.

At your Watson Assistant skill, select the menu (instead of going into it) and select "View API details".

You will find the IAM apikey. If you have a much earlier instance, it will have username password.

I am not familar with botim, but if it does not have the option to send an API key, then send the username "apikey" and the api key as the password.

Body:
I'm setting up Botium testing freamework to run some tests against my watson based chatbot, I'm encountering Error: WATSON_USER capability required, I'm follwoing the tutorial available here https://chatbotsmagazine.com/10-minutes-codeless-test-automation-for-ibm-watson-chatbots-d71eac9626d7

As part of the error message, it's also suggesting me to use API key, I'm not sure how to get one.

botium-cli emulator --config ./botium.json
Error: WATSON_USER capability required (or use WATSON_APIKEY)
    at BotiumConnectorWatson.Validate (/usr/local/lib/node_modules/botium-cli/node_modules/botium-connector-watson/dist/botium-connector-watson-cjs.js:60:55)
    at Validate.Validate.then (/usr/local/lib/node_modules/botium-cli/node_modules/botium-core/src/containers/PluginConnectorContainer.js:72:66)

My config looks like:

{
    "botium": {
        "Capabilities": {
            "PROJECTNAME": "****",
            "CONTAINERMODE": "watson",
            "WATSONCONVERSATION_USER": "*****",
            "WATSONCONVERSATION_PASSWORD": "*****",
            "WATSONCONVERSATION_WORKSPACE_ID": "****",
            "WATSONCONVERSATION_USE_INTENT": false
        }
    }
}


问:
Problem creating a frequency array of a given array
I am trying to create a frequency array of a given array on Fortran 95. For instance if I have an array (\1 2 4 2 4 2 5), the frequency array should be the number of times each item appears; (\1 3 2 3 2 3 1). So because there are only 1 of 5s in the original array, the last entry in the new array is 1 and because there are 3 of 2s in the original array, the corresponding entries on the new array is a 2.

Below is a sample of the code I have, but I keep getting errors. I was wondering if anyone would be willing to give me some guidance and help on what I could be doing wrong. It would be very much appreciated.

I haven't included the part of the code that generates my original array because I'm pretty sure it is correct so here is just the subroutine for the frequency array. Also the original array was sorted in ascending order outside this subroutine. Perhaps I didn't pass the original array, num(i) correctly??

```<code>INTEGER, DIMENSION(100)::num(100)
    INTEGER, DIMENSION(100)::freq(100)
    INTEGER:: i=0, k=0, numinteger, count=0

CALL FreqArray(num, numinteger,freq)

SUBROUTINE FreqArray(num, numinteger, freq)

INTEGER, INTENT(IN):: num(100), numinteger
INTEGER, INTENT(OUT):: freq(100)

DO i=1,9
    count=0
    DO k=1, numinteger
        IF (num(k)==i)THEN
            count=count+1
        END IF
    END DO
    freq(i)=count
END DO

PRINT*, "Frequency of Digits"
PRINT*, " "
WRITE(*,'(1X,A,T35,A)'),"Digit","Frequency"
WRITE(*,'(1X,I1,T35,I1)'),num(i),freq(i)

END SUBROUTINE
</code>```

Thanks so much for your time.

答:
With regards to your display issue, I suspect that you meant to have a loop around</p>

```<code>WRITE(*,'(1X,I1,T35,I1)'),num(i),freq(i)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a frequency array of a given array on Fortran 95. For instance if I have an array (\1 2 4 2 4 2 5), the frequency array should be the number of times each item appears; (\1 3 2 3 2 3 1). So because there are only 1 of 5s in the original array, the last entry in the new array is 1 and because there are 3 of 2s in the original array, the corresponding entries on the new array is a 2.

Below is a sample of the code I have, but I keep getting errors. I was wondering if anyone would be willing to give me some guidance and help on what I could be doing wrong. It would be very much appreciated.

I haven't included the part of the code that generates my original array because I'm pretty sure it is correct so here is just the subroutine for the frequency array. Also the original array was sorted in ascending order outside this subroutine. Perhaps I didn't pass the original array, num(i) correctly??

INTEGER, DIMENSION(100)::num(100)
    INTEGER, DIMENSION(100)::freq(100)
    INTEGER:: i=0, k=0, numinteger, count=0

CALL FreqArray(num, numinteger,freq)

SUBROUTINE FreqArray(num, numinteger, freq)

INTEGER, INTENT(IN):: num(100), numinteger
INTEGER, INTENT(OUT):: freq(100)

DO i=1,9
    count=0
    DO k=1, numinteger
        IF (num(k)==i)THEN
            count=count+1
        END IF
    END DO
    freq(i)=count
END DO

PRINT*, "Frequency of Digits"
PRINT*, " "
WRITE(*,'(1X,A,T35,A)'),"Digit","Frequency"
WRITE(*,'(1X,I1,T35,I1)'),num(i),freq(i)

END SUBROUTINE

Thanks so much for your time.

Body:
With regards to your display issue, I suspect that you meant to have a loop around

WRITE(*,'(1X,I1,T35,I1)'),num(i),freq(i)


问:
How to return a nested list of frequency from a Python list?
From a list of cards - return a nested list of the cards with the same numbers and then the rest in a separate list.

```<code>EXAMPLE: ['6C', '7C', '7D', '8S', '6D']
</code>```

returning [['7C', '7D'], ['6C','6D'], ['8S']]

I have attempted using a while loop, but cant figure it out.

Thank you!

答:
Another approach without using itertools groupby.</p>

```<code>l = ['6C', '7C', '7D', '8S', '6D']

result, temp = [], []

l = sorted(l, key=lambda x: x[0])

counter = l[0][0]

for i in l:
    if i[0] == counter:
        temp.append(i)

    else:
        result.append(temp)
        temp = [i]
        counter = i[0]

if temp:
    result.append(temp)

print(result)
</code>```

Body:
From a list of cards - return a nested list of the cards with the same numbers and then the rest in a separate list.

EXAMPLE: ['6C', '7C', '7D', '8S', '6D']

returning [['7C', '7D'], ['6C','6D'], ['8S']]

I have attempted using a while loop, but cant figure it out.

Thank you!

Body:
Another approach without using itertools groupby.

l = ['6C', '7C', '7D', '8S', '6D']

result, temp = [], []

l = sorted(l, key=lambda x: x[0])

counter = l[0][0]

for i in l:
    if i[0] == counter:
        temp.append(i)

    else:
        result.append(temp)
        temp = [i]
        counter = i[0]

if temp:
    result.append(temp)

print(result)


问:
How to iterate through complex Json object and do something on each property which equals a certain value
I got the following problem,

I need to iterate through a big Json object ( child nodes consist of array's, strings and objects with at least 4-5 layers of depth in terms of nested properties ).

In some parts across the big Json file there is a specific object structure, it has a property named "erpCode". I need to scan the Json and find all the objects with that property, take the value use that code to ask a different API for details and once I get the details insert them into the object with the current 'erpCode'.

Just to clarify, in my case the parent node property name in the Json always equals the value in 'typeSysname' field which located on the same 'level' as the erpCode property.
A simple example :

```<code>{
   "cars": [
    {
      "name": "X222",
      "carType": {
         "erpCode": "skoda",
         "value": null,
         "typeSysName": "carType"
       }
    }
    ],
    "model": {
       "year": 1999,
       "details": {
           "erpCode": "112"
           "value": null,
           "typeSysName": "details"
        }
     }
}
</code>```

In this example I need to find 2 properties get the values skoda and 112 out of them and get the value and description data from a different API and set it into this Json in the right location.

P.S. Any chance there is a good npm package which can help me with that?

Edit:
I got a solution in C# from a few months ago which runs in a generic way on the Json and handles the complexity of the structure in a generic way.
But I now need to convert this into Javascript and I am a bit lost.

```<code>public static string TranslateDocErpCodes(string jsonString, string topRetailerSysName)
        {

            try
            {
                var doc = JObject.Parse(jsonString);
                var erpCodeList = doc.SelectTokens("$..erpCode").ToList();

                foreach (var erpCodeJToken in erpCodeList)
                {
                    var value = erpCodeJToken?.Value<string>();
                    var erpCodeParent = erpCodeJToken?.Parent.Parent;
                    var erpCodeProperty = erpCodeParent?.Path.Split(".").Last();

                    var result =
                        _dataService.GetLovFromErpCode(topRetailerSysName, erpCodeProperty, value);

                    if (result == null)//reset lov obj
                    {
                        if (erpCodeParent?.Parent is JProperty prop)
                            prop.Value = JObject.FromObject(new LovObject { ErpCode = value });
                    }
                    else//set lov obj
                    {
                        result.ErpCode = value;
                        if (erpCodeParent?.Parent is JProperty prop)
                            prop.Value = JObject.FromObject(result);
                    }

                }
                return JsonConvert.SerializeObject(doc);
            }
            catch (Exception e)
            {
                throw new Exception("ErpConvert.TranslateDocErpCodes() : " + e);
            }
        }
</code>```

答:
mb something like;</p>

```<code>function processObject(jsonData) {
    for (prop in jsonData) {
        if (jsonData.hasOwnProperty(prop)) {
            // We get our prop
            if (prop === 'code') {
                let codeValue = jsonData[prop]
                doSomeAsync(codeValue)
                    .then(response => {
                        jsonData[prop] = response;
                    })
            }
            let curValue = jsonData[prop];
            if (Array.isArray(curValue)) {
                // Loop through the array, if array element is an object, call processObject recursively.
                processArray(curValue);
            } else if (typeof curValue === 'object') {
                processObject(curValue);
            }
        }
    }
}
</code>```

Body:
I got the following problem,

I need to iterate through a big Json object ( child nodes consist of array's, strings and objects with at least 4-5 layers of depth in terms of nested properties ).

In some parts across the big Json file there is a specific object structure, it has a property named "erpCode". I need to scan the Json and find all the objects with that property, take the value use that code to ask a different API for details and once I get the details insert them into the object with the current 'erpCode'.

Just to clarify, in my case the parent node property name in the Json always equals the value in 'typeSysname' field which located on the same 'level' as the erpCode property.
A simple example :

{
   "cars": [
    {
      "name": "X222",
      "carType": {
         "erpCode": "skoda",
         "value": null,
         "typeSysName": "carType"
       }
    }
    ],
    "model": {
       "year": 1999,
       "details": {
           "erpCode": "112"
           "value": null,
           "typeSysName": "details"
        }
     }
}

In this example I need to find 2 properties get the values skoda and 112 out of them and get the value and description data from a different API and set it into this Json in the right location.

P.S. Any chance there is a good npm package which can help me with that?

Edit:
I got a solution in C# from a few months ago which runs in a generic way on the Json and handles the complexity of the structure in a generic way.
But I now need to convert this into Javascript and I am a bit lost.

public static string TranslateDocErpCodes(string jsonString, string topRetailerSysName)
        {

            try
            {
                var doc = JObject.Parse(jsonString);
                var erpCodeList = doc.SelectTokens("$..erpCode").ToList();

                foreach (var erpCodeJToken in erpCodeList)
                {
                    var value = erpCodeJToken?.Value<string>();
                    var erpCodeParent = erpCodeJToken?.Parent.Parent;
                    var erpCodeProperty = erpCodeParent?.Path.Split(".").Last();

                    var result =
                        _dataService.GetLovFromErpCode(topRetailerSysName, erpCodeProperty, value);

                    if (result == null)//reset lov obj
                    {
                        if (erpCodeParent?.Parent is JProperty prop)
                            prop.Value = JObject.FromObject(new LovObject { ErpCode = value });
                    }
                    else//set lov obj
                    {
                        result.ErpCode = value;
                        if (erpCodeParent?.Parent is JProperty prop)
                            prop.Value = JObject.FromObject(result);
                    }

                }
                return JsonConvert.SerializeObject(doc);
            }
            catch (Exception e)
            {
                throw new Exception("ErpConvert.TranslateDocErpCodes() : " + e);
            }
        }

Body:
mb something like;

function processObject(jsonData) {
    for (prop in jsonData) {
        if (jsonData.hasOwnProperty(prop)) {
            // We get our prop
            if (prop === 'code') {
                let codeValue = jsonData[prop]
                doSomeAsync(codeValue)
                    .then(response => {
                        jsonData[prop] = response;
                    })
            }
            let curValue = jsonData[prop];
            if (Array.isArray(curValue)) {
                // Loop through the array, if array element is an object, call processObject recursively.
                processArray(curValue);
            } else if (typeof curValue === 'object') {
                processObject(curValue);
            }
        }
    }
}


问:
Short cut for invoking shell script in unix
I have below two file to start and stop my spring-boot application. Is it possible to have this installed as server etc in unix? so that I can just type start app or  stop app to start or stop my application from any location?

```<code>startApplication.sh
stopApplication.sh
</code>```

答:
You can always define alias in your bash, do as below:

```<code>sudo vim ~/.bashrc
</code>```

go at the end of file and add this line

```<code>alias start-app='bash /<path-to-script>/startApplications.sh'
</code>```

save and exit and resource it with source command

```<code>source ~/.bashrc
</code>```

now if you type in your terminal start-app it will execute your script. create one for stop-app too.

Body:
I have below two file to start and stop my spring-boot application. Is it possible to have this installed as server etc in unix? so that I can just type start app or  stop app to start or stop my application from any location?

startApplication.sh
stopApplication.sh

Body:
You can always define alias in your bash, do as below:

sudo vim ~/.bashrc

go at the end of file and add this line

alias start-app='bash /<path-to-script>/startApplications.sh'

save and exit and resource it with source command

source ~/.bashrc

now if you type in your terminal start-app it will execute your script. create one for stop-app too.


问:
How to send an int from Python to an Arduino in order to use it as an argument for the neopixel function setPixelcolor()?
I am trying to send an int number from Python to an Arduino using PySerial, using .write([data]) to send with Python and Serial.read() or Serial.readString() to recieve on the Arduino, then .setPixelColor() and .show() to light a LED on a matrix which position corresponds to the int sent by the arduino (I am using the Duinofun Neopixel Shield).

But It does not seem to work properly, and I can't use the Serial Monitor as I am sending my data as the port would be busy.

I have tried to input a number myself using Serial.readString() then converting the string to an int and finally putting in into my function that displays the LED.

It does work properly when I do this, but when I send some data over, all the previously lit LEDs suddenly switch off which can only be caused by a reset of the Arduino board as far as I know.

This is the python code, it simply sends an int chosen by the user

import serial

a = int(input('Enter pixel position : '))
ser = serial.Serial("COM16", 9600)

ser.write([a])
```

<p>And this is the part of the Arduino program that reads the incoming data.</p>

<pre class="lang-c prettyprint-override"><code>Adafruit_NeoPixel pixels = Adafruit_NeoPixel(40, 6, NEO_GRB + NEO_KHZ800);

void setup() {
  // put your setup code here, to run once:
  pixels.begin();
  Serial.begin(9600);
}

void loop() {

  String a = Serial.readString();
  int b = a.toInt();
  pixels.setPixelColor(b, 30,30,30);
  pixels.show();
  Serial.println(a);

  delay(1000);

}
</code>```

All the LED switch off when I send some data, except the first LED which position corresponds to a 0 used in the .setPixelColor() function.

Problem is, the LED should light to the corresponding int sent by Python (e.g light the fifth LED for an int of 4).

答:
You don't need to send an int from your Python script. Just send a string and then convert it back to int on your Arduino. Also, you can verify the number simply on your Arduino code if the received value is valid.
Another problem with your Arduino code is you are not checking the Serial port availability which would return an empty string by Serial.readString().

A simple approach is shown below but you can extend it for other pixels.

Python script:

```<code>import serial

ser = serial.Serial("COM16", 9600)
while True:
    input_value = input('Enter pixel position: ')
    ser.write(input_value.encode())
</code>```

Arduino code:

```<code>#define MIN_PIXEL_RANGE 0
#define MAX_PIXEL_RANGE 100

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(40, 6, NEO_GRB + NEO_KHZ800);

void setup()
{
    // put your setup code here, to run once:
    pixels.begin();
    Serial.begin(9600);
}

void loop()
{
    if (Serial.available())
    {
        String a = Serial.readString();
        Serial.print("Received Value: ");
        Serial.println(a);
        int b = a.toInt();
        if ((b >= MIN_PIXEL_RANGE) && (b <= MAX_PIXEL_RANGE))
        {
            pixels.setPixelColor(b, 30, 30, 30);
            pixels.show();
            delay(1000);
        }
    }
}
</code>```

Body:
I am trying to send an int number from Python to an Arduino using PySerial, using .write([data]) to send with Python and Serial.read() or Serial.readString() to recieve on the Arduino, then .setPixelColor() and .show() to light a LED on a matrix which position corresponds to the int sent by the arduino (I am using the Duinofun Neopixel Shield).

But It does not seem to work properly, and I can't use the Serial Monitor as I am sending my data as the port would be busy.

I have tried to input a number myself using Serial.readString() then converting the string to an int and finally putting in into my function that displays the LED.

It does work properly when I do this, but when I send some data over, all the previously lit LEDs suddenly switch off which can only be caused by a reset of the Arduino board as far as I know.

This is the python code, it simply sends an int chosen by the user

import serial

a = int(input('Enter pixel position : '))
ser = serial.Serial("COM16", 9600)

ser.write([a])

And this is the part of the Arduino program that reads the incoming data.

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(40, 6, NEO_GRB + NEO_KHZ800);

void setup() {
  // put your setup code here, to run once:
  pixels.begin();
  Serial.begin(9600);
}

void loop() {

  String a = Serial.readString();
  int b = a.toInt();
  pixels.setPixelColor(b, 30,30,30);
  pixels.show();
  Serial.println(a);

  delay(1000);

}

All the LED switch off when I send some data, except the first LED which position corresponds to a 0 used in the .setPixelColor() function.

Problem is, the LED should light to the corresponding int sent by Python (e.g light the fifth LED for an int of 4).

Body:
You don't need to send an int from your Python script. Just send a string and then convert it back to int on your Arduino. Also, you can verify the number simply on your Arduino code if the received value is valid.
Another problem with your Arduino code is you are not checking the Serial port availability which would return an empty string by Serial.readString().

A simple approach is shown below but you can extend it for other pixels.

Python script:

import serial

ser = serial.Serial("COM16", 9600)
while True:
    input_value = input('Enter pixel position: ')
    ser.write(input_value.encode())

Arduino code:

#define MIN_PIXEL_RANGE 0
#define MAX_PIXEL_RANGE 100

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(40, 6, NEO_GRB + NEO_KHZ800);

void setup()
{
    // put your setup code here, to run once:
    pixels.begin();
    Serial.begin(9600);
}

void loop()
{
    if (Serial.available())
    {
        String a = Serial.readString();
        Serial.print("Received Value: ");
        Serial.println(a);
        int b = a.toInt();
        if ((b >= MIN_PIXEL_RANGE) && (b <= MAX_PIXEL_RANGE))
        {
            pixels.setPixelColor(b, 30, 30, 30);
            pixels.show();
            delay(1000);
        }
    }
}


问:
PHP merge two arrays with same key and output to specific json format
My database has two tables. One is calling out the book info and another is calling image info. I would like to merge these two table data into one JSON. If the img id is matched with the data id, then the image is belongs to this book. I tried to use foreach to loop the book data into array and use another foreach to loop the image data within the book data array, but failed to get the expected result.

Book Table JSON:

```<code>{
 "data": [
    {
        "id": 17,
        "author": "Belcurls",
        "bookname": "You Never Know"
    },
    {
        "id": 18,
        "author": "Carolina",
        "bookname": "A Story Teller"
    },
    {
        "id": 19,
        "author": "Lokas",
        "bookname": "The Love"
    }
 ]
}
</code>```

Image Table JSON:

```<code>{
"img": [
    {
        "id": 18,
        "url": "image18.png"
    },
    {
        "id": 18,
        "url": "image18b.png"
    },
    {
        "id": 19,
        "url": "image19.png"
    },
    {
        "id": 19,
        "url": "image19b.png"
    },
    {
        "id": 19,
        "url": "image19c.png"
    }
]
}
</code>```

Expected Result:

```<code>{
 "data": [
    {
        "id": 17,
        "author": "Belcurls",
        "bookname": "You Never Know"
    },
    {
        "id": 18,
        "author": "Carolina",
        "bookname": "A Story Teller",
        "image":[
           {
             "url":"image18"
           },
           {
             "url":"image18b"
           }
         ]
    },
    {
        "id": 19,
        "author": "Lokas",
        "bookname": "The Love",
        "image":[
           {
             "url":"image19"
           },
           {
             "url":"image19b"
           },
           {
             "url":"image19c"
           }
         ]
    }
 ]
 }
</code>```

答:
Demo Link.

You can do this loop, Please check inline doc for explanation

```<code>foreach ($arr['data'] as $key => &$value) { // & to update changes as its address
    foreach ($imgs['img'] as $key1 => $value1) {
        if($value['id'] == $value1['id']){ // checking if match id of parent with images
            $value['image'][] = ['url' => $value1['url']]; // then simply push
        }
    }
}
</code>```

If you want to convert your json to php array use

```<code> json_decode($yourjson, true); // second parameter is for converting it to array else it will convert into object.
</code>```

Body:
My database has two tables. One is calling out the book info and another is calling image info. I would like to merge these two table data into one JSON. If the img id is matched with the data id, then the image is belongs to this book. I tried to use foreach to loop the book data into array and use another foreach to loop the image data within the book data array, but failed to get the expected result.

Book Table JSON:

{
 "data": [
    {
        "id": 17,
        "author": "Belcurls",
        "bookname": "You Never Know"
    },
    {
        "id": 18,
        "author": "Carolina",
        "bookname": "A Story Teller"
    },
    {
        "id": 19,
        "author": "Lokas",
        "bookname": "The Love"
    }
 ]
}

Image Table JSON:

{
"img": [
    {
        "id": 18,
        "url": "image18.png"
    },
    {
        "id": 18,
        "url": "image18b.png"
    },
    {
        "id": 19,
        "url": "image19.png"
    },
    {
        "id": 19,
        "url": "image19b.png"
    },
    {
        "id": 19,
        "url": "image19c.png"
    }
]
}

Expected Result:

{
 "data": [
    {
        "id": 17,
        "author": "Belcurls",
        "bookname": "You Never Know"
    },
    {
        "id": 18,
        "author": "Carolina",
        "bookname": "A Story Teller",
        "image":[
           {
             "url":"image18"
           },
           {
             "url":"image18b"
           }
         ]
    },
    {
        "id": 19,
        "author": "Lokas",
        "bookname": "The Love",
        "image":[
           {
             "url":"image19"
           },
           {
             "url":"image19b"
           },
           {
             "url":"image19c"
           }
         ]
    }
 ]
 }

Body:
Demo Link.

You can do this loop, Please check inline doc for explanation

foreach ($arr['data'] as $key => &$value) { // & to update changes as its address
    foreach ($imgs['img'] as $key1 => $value1) {
        if($value['id'] == $value1['id']){ // checking if match id of parent with images
            $value['image'][] = ['url' => $value1['url']]; // then simply push
        }
    }
}

If you want to convert your json to php array use

 json_decode($yourjson, true); // second parameter is for converting it to array else it will convert into object.


问:
How to update user data in MongoDB using node.js
I have a simple express app with MongoDB connection where I can register a user. Registering and logging in and out works fine but now I'm trying to add possibility to edit user data. My code doesn't throw any errors but it doesn't update the data in database neither.

I've tried to read the MongoDB documentation and similar problems from stackoverflow. But I just can't seem to get it work.

This is my route for update:

```<code>    User.updateOne({ id: req.session.passport.user}, {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    }, function (err, user){
        if (err) return next(err);
        User.findById(req.user._id, function(err, user) {
            if (err) return next(err);
            return res.render('user', {
            name: user.name,
            email: user.email
        });
    });
});
});
</code>```

I expect it to update my database data but it just renders the user -page and nothing else happens.

EDIT.
Thank you for your answers, I tried those but it still just goes through but nothing happens in database.
I've also tried to make the edit work based on how I handle the registration and I actually got it to save the data but my problem with this solution is that it doesn't hash the password, it is saved as a string in my db. With registration hashing works fine. I also need to do the email validation somehow else because now it requires it to be changed every time I edit my data. Here's the code:

```<code>router.post('/update/:name', ensureAuthenticated, function(req, res, next){
  const { name, email, password, password2 } = req.body;
  let errors = [];

  //check required fields
  if (!name || !email || !password || !password2) {
    errors.push({ msg: 'Please fill in all fields' });
  }

  //check passwords match
  if (password !== password2) {
    errors.push({ msg: 'Passwords do not match' });
  }

  //check pass length
  if (password.length < 6) {
    errors.push({ msg: 'Password should be at least 6 characters' });
  }

  if (errors.length > 0) {
    res.render('update', {
      errors,
      name,
      email,
      password,
      password2
    });
  } else {
    //validation passed
    User.updateOne({ name: name, email: email, password: password })
      .then(user => {
        if (user) {
          //user exists
          errors.push({ msg: 'Email is already registered'});
          res.render('update', {
            errors,
            name,
            email,
            password,
            password2
          });
        } else {
          const updateUser = new User({
            name,
            email,
            password
          });

          //Hash password
          bcrypt.genSalt(10, (err, salt) =>
            bcrypt.hash(updateUser.password, salt, (err, hash) => {
              if (err) throw err;
              //set password to hashed
              updateUser.password = hash;
              //save user
              updateUser
                .save()
                .then(user => {
                  req.flash('success_msg', 'Info updatet, log in');
                  res.redirect('/users/login');
                })
                .catch(err => console.log(err));
          }));
        }
      });
  }
});
</code>```

答:
You need to use SET to update the document:

```<code>User.updateOne({ id: req.session.passport.user }, {
    $set: {
            name: req.body.name,
            email: req.body.email,
            password: req.body.password
          }
     }, function (err, user) {
            if (err) return next(err);
            User.findById(req.user._id, function(err, user) {
                if (err) return next(err);
                return res.render('user', {
                name: user.name,
                email: user.email
            });
        });
});
</code>```

Body:
I have a simple express app with MongoDB connection where I can register a user. Registering and logging in and out works fine but now I'm trying to add possibility to edit user data. My code doesn't throw any errors but it doesn't update the data in database neither.

I've tried to read the MongoDB documentation and similar problems from stackoverflow. But I just can't seem to get it work.

This is my route for update:

    User.updateOne({ id: req.session.passport.user}, {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    }, function (err, user){
        if (err) return next(err);
        User.findById(req.user._id, function(err, user) {
            if (err) return next(err);
            return res.render('user', {
            name: user.name,
            email: user.email
        });
    });
});
});

I expect it to update my database data but it just renders the user -page and nothing else happens.

EDIT.
Thank you for your answers, I tried those but it still just goes through but nothing happens in database.
I've also tried to make the edit work based on how I handle the registration and I actually got it to save the data but my problem with this solution is that it doesn't hash the password, it is saved as a string in my db. With registration hashing works fine. I also need to do the email validation somehow else because now it requires it to be changed every time I edit my data. Here's the code:

router.post('/update/:name', ensureAuthenticated, function(req, res, next){
  const { name, email, password, password2 } = req.body;
  let errors = [];

  //check required fields
  if (!name || !email || !password || !password2) {
    errors.push({ msg: 'Please fill in all fields' });
  }

  //check passwords match
  if (password !== password2) {
    errors.push({ msg: 'Passwords do not match' });
  }

  //check pass length
  if (password.length < 6) {
    errors.push({ msg: 'Password should be at least 6 characters' });
  }

  if (errors.length > 0) {
    res.render('update', {
      errors,
      name,
      email,
      password,
      password2
    });
  } else {
    //validation passed
    User.updateOne({ name: name, email: email, password: password })
      .then(user => {
        if (user) {
          //user exists
          errors.push({ msg: 'Email is already registered'});
          res.render('update', {
            errors,
            name,
            email,
            password,
            password2
          });
        } else {
          const updateUser = new User({
            name,
            email,
            password
          });

          //Hash password
          bcrypt.genSalt(10, (err, salt) =>
            bcrypt.hash(updateUser.password, salt, (err, hash) => {
              if (err) throw err;
              //set password to hashed
              updateUser.password = hash;
              //save user
              updateUser
                .save()
                .then(user => {
                  req.flash('success_msg', 'Info updatet, log in');
                  res.redirect('/users/login');
                })
                .catch(err => console.log(err));
          }));
        }
      });
  }
});

Body:
You need to use SET to update the document:

User.updateOne({ id: req.session.passport.user }, {
    $set: {
            name: req.body.name,
            email: req.body.email,
            password: req.body.password
          }
     }, function (err, user) {
            if (err) return next(err);
            User.findById(req.user._id, function(err, user) {
                if (err) return next(err);
                return res.render('user', {
                name: user.name,
                email: user.email
            });
        });
});


问:
What's the most efficient way to remove all symbols from an object?
Let's say I have an object where I want to keep internal-only key/pairs with symbols.  Given...

```<code>let obj = {
    [Symbol.for('foo')]: 'internal-only member',
    a: 1,
    b: 2,
    c: 3
}
</code>```

When I return these to a client through my API, I want to strip out all Symbols from the Object because the client doesn't have any use for them.

I'd like a generic function that will return:

```<code>{
    a: 1,
    b: 2,
    c: 3
}
</code>```

In other words:

```<code>returnScrubbedObj = (obj) => {
    // filter/map/remove/copy etc the original object to a new object without symbols
    return objWithoutSymbols
}
</code>```

I know there are probably many different ways to do this; just looking for the best/most efficient one.

答:
It is convenient and less memory and space intensive to use for .. in here on the object.

let obj = {
    [Symbol.for('foo')]: 'internal-only member',
    a: 1,
    b: 2,
    c: 3
}

let newObj = {};
for(let prop in obj) {
  if(obj.hasOwnProperty(prop)){
     newObj[prop] = obj[prop];
  }
}

console.log(newObj);```

Body:
Let's say I have an object where I want to keep internal-only key/pairs with symbols.  Given...

let obj = {
    [Symbol.for('foo')]: 'internal-only member',
    a: 1,
    b: 2,
    c: 3
}

When I return these to a client through my API, I want to strip out all Symbols from the Object because the client doesn't have any use for them.

I'd like a generic function that will return:

{
    a: 1,
    b: 2,
    c: 3
}

In other words:

returnScrubbedObj = (obj) => {
    // filter/map/remove/copy etc the original object to a new object without symbols
    return objWithoutSymbols
}

I know there are probably many different ways to do this; just looking for the best/most efficient one.


问:
How to deploy angular 7 project directly to my webserver, so that i shouldn't migrate my dist folder always after deployment?
Currently, I am deploying my Angular 7 Project by using FileZilla to migrate my local files from ./dist folder to server public_HTMl. This is a quite tides job to carry in a daily basis, so I want to deploy my code directly to the server, when I hit ng build --prod then those compiled files have to be migrated directly to the server. Do anybody here who can help me to solve this problem?

To get rid of this problem I have tried lots of steps:

I was using bitbucket pipelines to execute my code, it came to be costly and I cannot run it as well, It took several hours but cannot give output for me.

I also tried by using new Git Repository even it's a good way but cannot give me the solution because when I deploy my code locally it creates a new folder every time while I execute a command.

So, I want to get help and deploy this code directly to the server that is going to host my application. Thank you all and hope all of you provide me good tips regarding this problem.

答:
You can do it in the simple way. Create basic bash/sh script or windows executable and use rsync to do this automatically:

deploy.sh:

#!/bin/bash
ng build --prod
rsync -arvt ./dist remoteuser@remotehost:/var/www/remotedirectory
```

<p>To avoid entering login and password every time add <strong>RSA public key</strong> to your remote machine(trusted host). You can combine this solution with <code>Bitbucket pipelines</code>, when the free plan ends I run this script manually from my developer machine. </p>

<p><strong>bitbucket-pipelines.yml:</strong></p>

```image: mycustomimage:latest
pipelines:
  default:
    - step:
        name: Build and deploy to production
        caches:
          - node
        deployment: production
        script:
          - npm install
          - npm install -g @angular/cli
          - ng config -g cli.warnings.versionMismatch false
          - ./deploy.sh
```

Instead of a simple script you can use some more complex solution like Capistrano, Shipit or some other more advanced tool. All depends on your needs...

The simplest solution is always the best :)

Body:
You can do it in the simple way. Create basic bash/sh script or windows executable and use rsync to do this automatically:

deploy.sh:

#!/bin/bash
ng build --prod
rsync -arvt ./dist remoteuser@remotehost:/var/www/remotedirectory

To avoid entering login and password every time add RSA public key to your remote machine(trusted host). You can combine this solution with Bitbucket pipelines, when the free plan ends I run this script manually from my developer machine.

bitbucket-pipelines.yml:

image: mycustomimage:latest
pipelines:
  default:
    - step:
        name: Build and deploy to production
        caches:
          - node
        deployment: production
        script:
          - npm install
          - npm install -g @angular/cli
          - ng config -g cli.warnings.versionMismatch false
          - ./deploy.sh

Instead of a simple script you can use some more complex solution like Capistrano, Shipit or some other more advanced tool. All depends on your needs...

The simplest solution is always the best :)


问:
How can I show variable width slides without cutting them with slick?
I'm using Slick carousel to make a carousel for my website. The last slide is cut, so I would like to make it disappear if it isn't shown full, as you can see in this image:

How can I do that?

```

<pre class="lang-js prettyprint-override"><code>$(document).ready(function() {
  $('.carousel').slick({
    slidesToScroll: 1,
    autoplaySpeed: 3000,
    variableWidth: true,
    infinite: true,
  });
});
</code>```

答:
The parameter variableWidth it self means that you are using the slides with the auto width, so it's depend upon your images/logos's width. either you should have same width logo's or false the variableWidth option.

Adjusting with the css is not a good option. :)

Body:
I'm using Slick carousel to make a carousel for my website. The last slide is cut, so I would like to make it disappear if it isn't shown full, as you can see in this image:

How can I do that?

$(document).ready(function() {
  $('.carousel').slick({
    slidesToScroll: 1,
    autoplaySpeed: 3000,
    variableWidth: true,
    infinite: true,
  });
});


问:
Read a specific table column with Prototype
I need to read all the values of the first column of an HTML table, and I don't want to use DOM methods. I'd like a simpler solution using Prototype or YUI.

Note: the table is generated by a grid widget provided by an external team. That's why we cannot be sure of which IDs or Classnames are used.

In short I'd like something like:

```<code>For each row in table XXX
   value = row.column[1].value
   do something with value ...
End For
</code>```

Thanks in advance

答: possibly $$('tr') might work.  It returns an array of elements based on a CSS rule.

OwnerDisplayName: Lluís

LastEditorDisplayName: Greg Hewgill

ContentLicense: CC BY-SA 2.5

Body:
I need to read all the values of the first column of an HTML table, and I don't want to use DOM methods. I'd like a simpler solution using Prototype or YUI.

Note: the table is generated by a grid widget provided by an external team. That's why we cannot be sure of which IDs or Classnames are used.

In short I'd like something like:

For each row in table XXX
   value = row.column[1].value
   do something with value ...
End For

Thanks in advance


问:
How to put icon on string in flutter?
I have array string and I want to put icons inside that string like this,

```<code>var arr = ['lorem ipsum dolor select icon '+Icons(Icons.search)+' blablabla...'];
</code>```

But I got error

```<code>The argument type 'Icons' can't be assigned to the parameter type 'String'
</code>```

How I can solve this problem? thanks

答:
You can't use Widgets inside your String variable, what you can do is use the Row widget, like this:

```<code>Row(
  children: [
    Text('lorem ipsum dolor select icon '),
    Icon(Icons.search),
    Text(' blablabla...')
  ],
);
</code>```

More info here: https://api.flutter.dev/flutter/widgets/Row-class.html

Title: How to put icon on string in flutter?

Body:
I have array string and I want to put icons inside that string like this,

var arr = ['lorem ipsum dolor select icon '+Icons(Icons.search)+' blablabla...'];

But I got error

The argument type 'Icons' can't be assigned to the parameter type 'String'

How I can solve this problem? thanks

Body:
You can't use Widgets inside your String variable, what you can do is use the Row widget, like this:

Row(
  children: [
    Text('lorem ipsum dolor select icon '),
    Icon(Icons.search),
    Text(' blablabla...')
  ],
);

More info here: https://api.flutter.dev/flutter/widgets/Row-class.html