问:
Get submatrix made from random rows and columns of large matix
I would like to extract (square) sub-matrices from a matrix, randomly with a size between some min and max values.

I would also like to retain the row and column indices which were selected.

Are there any built-in functions for this purpose? I would appreciate any general algorithm to achieve the desired results.

Just for an example without considering the square matrix constraint:

Input:

```<code>  | 1 2 3 4 5 6 7 8 <- column indices
--+----------------
1 | 4 3 1 4 0 1 0 1
2 | 2 0 1 5 6 3 2 0
3 | 5 5 0 6 7 8 9 0
4 | 2 3 5 6 7 9 0 1
^
Row indices
</code>```

Output sample:

```<code>  | 1 4 5 7 8 <- column indices
--+----------
1 | 4 4 0 0 1
2 | 2 5 6 2 0
4 | 2 6 7 0 1
^
Row indices
</code>```

Edit: I would like to have a function like this

```<code>matrixsample(numberOfSamples, minSize, maxSize, satisfyingFunction)
</code>```

the samples should vary their size between the minSize and maxSize.

If numberOfSamples = 10, minSize = 2 and maxSize = 6 then output should be randomly selected rows and columns like:

```<code>sampleMatrix1 2x2 sampleMatrix2 3x3 sampleMatrix3 5x5 ... sampleMatrix7 6x6 ... sampleMatrx10 4x4
</code>```

satisfyingFunction could test any attribute of the matrix; like being non-singular, rank > x, etc.

答:
In MATLAB, you will find the randperm function useful for selecting random rows/columns.

To get a randomly sized sub-matrix, use randi([minVal, maxVal]) to get a random integer between minVal and maxVal.

Getting a submatrix from random (ordered) combination of rows and columns:

```<code>M = randi([0,9],4,8); % 4x8 matrix of random 1 digit integers, your matrix here!

nRows = randi([2, 4]); % The number of rows to extract, random between 2 and 4
nCols = randi([5, 7]); % The number of columns to extract, random between 5 and 7

idxRows = sort(randperm(size(M,1), nRows)); % Random indices of rows
idxCols = sort(randperm(size(M,2), nCols)); % Random indices of columns

output = M(idxRows, idxCols); % Select the sub-matrix
</code>```

If you want to make the sub-matrix square then simply use the same value for nRows and nCols.

Showing this method works with your example input/output values:

```<code>M = [4 3 1 4 0 1 0 1; 2 0 1 5 6 3 2 0; 5 5 0 6 7 8 9 0; 2 3 5 6 7 9 0 1];
idxRows = [1 2 4]; idxCols = [1 4 5 7 8];
output = M(idxRows, idxCols)
% >>  4     4     0     0     1
%     2     5     6     2     0
%     2     6     7     0     1
</code>```

Edit in response to extended question scope:

You can package the above up into a short function, which returns the row and column indices, as well as the submatrix.

```<code>function output = getsubmatrix(M, nRows, nCols)
    % Get a submatrix of random rows/columns
    idxRows = sort(randperm(size(M,1), nRows));
    idxCols = sort(randperm(size(M,2), nCols));
    submatrix = M(idxRows, idxCols);
    output = {submatrix, idxRows, idxCols};
end
</code>```

Then you can use this in some sampling function as you described:

```<code>function samples = matrixsample(matrix, numberOfSamples, minSize, maxSize, satisfyingFunction)
    % output SAMPLES which contains all sample matrices, with row & column indices w.r.t MATRIX
    samples = cell(numberOfSamples,1);
    % maximum iterations trying to satisfy SATISFYINGCONDITION
    maxiters = 100;
    for ii = 1:numberOfSamples
        iters = 0; submatrixfound = false; % reset loop exiting conditions
        nRows = randi([minSize, maxSize]); % get random submatrix size
        nCols = nRows;                     % Square matrix
        while iters < maxiters && submatrixfound == false
            % Get random submatrix, and the indices
            submatrix = getsubmatrix(matrix, nRows,nCols);
            % satisfyingFunction MUST RETURN BOOLEAN
            if satisfyingFunction(submatrix{1})
                samples{ii} = submatrix; % If satisfied, assign to output
                submatrixfound = true;   % ... and move on!
            end
            iters = iters + 1;
        end
    end
end
</code>```

Test example:

```<code>s = matrixsample(magic(10), 5, 2, 8, @(M)max(M(:)) < 90)
</code>```

Body:
I would like to extract (square) sub-matrices from a matrix, randomly with a size between some min and max values.

I would also like to retain the row and column indices which were selected.

Are there any built-in functions for this purpose? I would appreciate any general algorithm to achieve the desired results.

Just for an example without considering the square matrix constraint:

Input:

  | 1 2 3 4 5 6 7 8 <- column indices
--+----------------
1 | 4 3 1 4 0 1 0 1
2 | 2 0 1 5 6 3 2 0
3 | 5 5 0 6 7 8 9 0
4 | 2 3 5 6 7 9 0 1
^
Row indices

Output sample:

  | 1 4 5 7 8 <- column indices
--+----------
1 | 4 4 0 0 1
2 | 2 5 6 2 0
4 | 2 6 7 0 1
^
Row indices

Edit: I would like to have a function like this

matrixsample(numberOfSamples, minSize, maxSize, satisfyingFunction)

the samples should vary their size between the minSize and maxSize.

If numberOfSamples = 10, minSize = 2 and maxSize = 6 then output should be randomly selected rows and columns like:

sampleMatrix1 2x2 sampleMatrix2 3x3 sampleMatrix3 5x5 ... sampleMatrix7 6x6 ... sampleMatrx10 4x4

satisfyingFunction could test any attribute of the matrix; like being non-singular, rank > x, etc.

Body:
In MATLAB, you will find the randperm function useful for selecting random rows/columns.

To get a randomly sized sub-matrix, use randi([minVal, maxVal]) to get a random integer between minVal and maxVal.

Getting a submatrix from random (ordered) combination of rows and columns:

M = randi([0,9],4,8); % 4x8 matrix of random 1 digit integers, your matrix here!

nRows = randi([2, 4]); % The number of rows to extract, random between 2 and 4
nCols = randi([5, 7]); % The number of columns to extract, random between 5 and 7

idxRows = sort(randperm(size(M,1), nRows)); % Random indices of rows
idxCols = sort(randperm(size(M,2), nCols)); % Random indices of columns

output = M(idxRows, idxCols); % Select the sub-matrix

If you want to make the sub-matrix square then simply use the same value for nRows and nCols.

Showing this method works with your example input/output values:

M = [4 3 1 4 0 1 0 1; 2 0 1 5 6 3 2 0; 5 5 0 6 7 8 9 0; 2 3 5 6 7 9 0 1];
idxRows = [1 2 4]; idxCols = [1 4 5 7 8];
output = M(idxRows, idxCols)
% >>  4     4     0     0     1
%     2     5     6     2     0
%     2     6     7     0     1

Edit in response to extended question scope:

You can package the above up into a short function, which returns the row and column indices, as well as the submatrix.

function output = getsubmatrix(M, nRows, nCols)
    % Get a submatrix of random rows/columns
    idxRows = sort(randperm(size(M,1), nRows));
    idxCols = sort(randperm(size(M,2), nCols));
    submatrix = M(idxRows, idxCols);
    output = {submatrix, idxRows, idxCols};
end

Then you can use this in some sampling function as you described:

function samples = matrixsample(matrix, numberOfSamples, minSize, maxSize, satisfyingFunction)
    % output SAMPLES which contains all sample matrices, with row & column indices w.r.t MATRIX
    samples = cell(numberOfSamples,1);
    % maximum iterations trying to satisfy SATISFYINGCONDITION
    maxiters = 100;
    for ii = 1:numberOfSamples
        iters = 0; submatrixfound = false; % reset loop exiting conditions
        nRows = randi([minSize, maxSize]); % get random submatrix size
        nCols = nRows;                     % Square matrix
        while iters < maxiters && submatrixfound == false
            % Get random submatrix, and the indices
            submatrix = getsubmatrix(matrix, nRows,nCols);
            % satisfyingFunction MUST RETURN BOOLEAN
            if satisfyingFunction(submatrix{1})
                samples{ii} = submatrix; % If satisfied, assign to output
                submatrixfound = true;   % ... and move on!
            end
            iters = iters + 1;
        end
    end
end

Test example:

s = matrixsample(magic(10), 5, 2, 8, @(M)max(M(:)) < 90)


来源: stackexchange

问:
Php using 2 classes
ive been trying to learn some php and i wanted to make a logger

I get user input, put in into an array and make it into json:

This is the class that gets the info:

```<code><?php
class account_Creation
{

    private $username;
    private $password;
    private $email;

    //user input
    public function user_input()
    {
        $username = 'username';
        $password = "password";
        $email = "email";
        $result_array= compact("username","password", "email");
    }
}

$account_creation= new account_Creation();
$account_creation-> user_input();
$logging= new Logging();
$logging-> json_Translator($result_array);
</code>```

This is the class that translates it into json:

```<code><?php
class Logging
{
    public function json_Translator($data)
    {
        echo json_encode($data);
    }
}
</code>```

I get the error: Uncaught Error: Class 'Logging' not found
How do i show the account creation class where the logging class is? I tried include but that did not work

答:
Let's simplify

Consider the first as page1.php and the next one page2.php

In the page1.php, the changes are:

```<code><?php
include("page2.php");
class account_Creation
.
.
$logging= new Logging; //The brackets should be removed
.
.
</code>```

This should remove the

Uncaught Error: Class 'Logging' not found

ContentLicense: CC BY-SA 3.0

Title: Php using 2 classes

Body:
ive been trying to learn some php and i wanted to make a logger

I get user input, put in into an array and make it into json:

This is the class that gets the info:

<?php
class account_Creation
{

    private $username;
    private $password;
    private $email;

    //user input
    public function user_input()
    {
        $username = 'username';
        $password = "password";
        $email = "email";
        $result_array= compact("username","password", "email");
    }
}

$account_creation= new account_Creation();
$account_creation-> user_input();
$logging= new Logging();
$logging-> json_Translator($result_array);

This is the class that translates it into json:

<?php
class Logging
{
    public function json_Translator($data)
    {
        echo json_encode($data);
    }
}

I get the error: Uncaught Error: Class 'Logging' not found
How do i show the account creation class where the logging class is? I tried include but that did not work

Body:
Let's simplify

Consider the first as page1.php and the next one page2.php

In the page1.php, the changes are:

<?php
include("page2.php");
class account_Creation
.
.
$logging= new Logging; //The brackets should be removed
.
.

This should remove the

Uncaught Error: Class 'Logging' not found


问:
Are infinite lists useful for any real world applications?
I've been using haskell for quite a while now, and I've read most of Real World Haskell and Learn You a Haskell. What I want to know is whether there is a point to a language using lazy evaluation, in particular the "advantage" of having infinite lists, is there a task which infinite lists make very easy, or even a task that is only possible with infinite lists?</p>

答:
I found it's often easier and cleaner to just define all of a sequence in one place, even if it's infinite, and have the code that uses it just grab what it wants.

```<code>take 10 mySequence
takeWhile (<100) mySequence
</code>```

instead of having numerous similar but not quite the same functions that generate a subset

```<code>first10ofMySequence
elementsUnder100ofMySequence
</code>```

The benefits are greater when different subsections of the same sequence are used in different areas.

ContentLicense: CC BY-SA 2.5

Body:
I found it's often easier and cleaner to just define all of a sequence in one place, even if it's infinite, and have the code that uses it just grab what it wants.

take 10 mySequence
takeWhile (<100) mySequence

instead of having numerous similar but not quite the same functions that generate a subset

first10ofMySequence
elementsUnder100ofMySequence

The benefits are greater when different subsections of the same sequence are used in different areas.


问:
PHP Insert / Update a mysql table from HTML form
This is my first mysql table.

I use HTML form in order to insert datas into a mysql table.

When submited, the form calls a php script in order to add datas into the form.

Then, mySQL table could look as follow :

From this mySQL table how could i generate and display a HTML table sorted by "NEXT_EVENT" column ?

If i want go on step ahead, is there a way a let user click on an upward / downward arrow placed next to each column header (links) in order to get the HTML table sorted as the desired column ?

--

Once the table sorted, i need to generate a raw simple TXT file where the ID on very FIRST row and NEXT_EVENT values will be copied to.

ie, sort.txt :
the 2 fields are comma separed.

2,    1499005140

Many thanks for your help,

答:
To have such a link next to the heading you can use jQuery plugin tablesorter. You can refer at

http://tablesorter.com/docs/

And for just executing a query for one column, you can use ORDER BY clause

Hope it helps


问:
Verify program calls with gtest & gmock
I'm using google mock & google test and I have an object such as:

```<code>  class Foo {
    public :
        Foo(){}

        virtual void method(int arg) {
            int var = a(arg) ;
            if (var<5){
                b() ;
            }
        }

        virtual int a(int arg){
            // do stuff
        }

        virtual int b(){
            // do stuff
        }
}
</code>```

I want to check that a() is called one time and b() is not whenever a failed ( = return a value <5)
So I wrote something like:

```<code>MockFoo mock ;

mock.method(badArg);

EXPECT_CALL(
    mock,
    a
)
.Times(1) ;

EXPECT_CALL(
    mock,
    a
)
.Times(0) ;
</code>```

But gtest tell me that none of those methods are called, what should I use?

Thanks for your explainations

答:
To use gmock properly, you need to set up your expectation before you run the real thing. This way, gmock knows what's coming and will be able to analyze if the real stuff really meets requirements. Otherwise, if you call the function before you set up your expectations, it's like asking a catcher to get into his standby position after you throw the ball. The catcher off course will miss.

In your case, you want something like:

```<code>MockFoo mock ;

// Catchers ready!
EXPECT_CALL(mock, a)
    .Times(1) ;
EXPECT_CALL(mock, b)
    .Times(0) ;

// Here's the ball!!
mock.method(watermelon);
</code>```

Title: Verify program calls with gtest & gmock

Body:
I'm using google mock & google test and I have an object such as:

  class Foo {
    public :
        Foo(){}

        virtual void method(int arg) {
            int var = a(arg) ;
            if (var<5){
                b() ;
            }
        }

        virtual int a(int arg){
            // do stuff
        }

        virtual int b(){
            // do stuff
        }
}

I want to check that a() is called one time and b() is not whenever a failed ( = return a value <5)
So I wrote something like:

MockFoo mock ;

mock.method(badArg);

EXPECT_CALL(
    mock,
    a
)
.Times(1) ;

EXPECT_CALL(
    mock,
    a
)
.Times(0) ;

But gtest tell me that none of those methods are called, what should I use?

Thanks for your explainations

Body:
To use gmock properly, you need to set up your expectation before you run the real thing. This way, gmock knows what's coming and will be able to analyze if the real stuff really meets requirements. Otherwise, if you call the function before you set up your expectations, it's like asking a catcher to get into his standby position after you throw the ball. The catcher off course will miss.

In your case, you want something like:

MockFoo mock ;

// Catchers ready!
EXPECT_CALL(mock, a)
    .Times(1) ;
EXPECT_CALL(mock, b)
    .Times(0) ;

// Here's the ball!!
mock.method(watermelon);


问:
Get precision and recall value with Tensorflow CNN classifier
I was wondering if there was a simple solution to get recall and precision value for the classes of my classifier?

To put some context, I implemented a 20 classes CNN classifier using Tensorflow with the help of  Denny Britz code : https://github.com/dennybritz/cnn-text-classification-tf .

As you can see at the end of text_cnn.py he implements a simple function to compute the global accuracy :

```<code># Accuracy
        with tf.name_scope("accuracy"):
            correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
            self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
</code>```

Any ideas on how i could do something similar to get the recall and precision value for the differents categories?

Maybe my question will sound dumb but I'm a bit lost with this to be honest. Thanks for the help.

答:
Using tf.metrics did the trick for me :

```<code>#define the method
x = tf.placeholder(tf.int32, )
y = tf.placeholder(tf.int32, )
acc, acc_op = tf.metrics.accuracy(labels=x, predictions=y)
rec, rec_op = tf.metrics.recall(labels=x, predictions=y)
pre, pre_op = tf.metrics.precision(labels=x, predictions=y)

#predict the class using your classifier
scorednn = list(DNNClassifier.predict_classes(input_fn=lambda: input_fn(testing_set)))
scoreArr = np.array(scorednn).astype(int)

#run the session to compare the label with the prediction
sess=tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
v = sess.run(acc_op, feed_dict={x: testing_set["target"],y: scoreArr}) #accuracy
r = sess.run(rec_op, feed_dict={x: testing_set["target"],y: scoreArr}) #recall
p = sess.run(pre_op, feed_dict={x: testing_set["target"],y: scoreArr}) #precision

print("accuracy %f", v)
print("recall %f", r)
print("precision %f", p)
</code>```

Result :

```<code>accuracy %f 0.686667
recall %f 0.978723
precision %f 0.824373
</code>```

Note : for Accuracy I would use :

```<code>accuracy_score = DNNClassifier.evaluate(input_fn=lambda:input_fn(testing_set),steps=1)["accuracy"]
</code>```

As it is simpler and already compute in the evaluate.

Also call variables_initializer if you don't want cumulative result.

Body:
I was wondering if there was a simple solution to get recall and precision value for the classes of my classifier?

To put some context, I implemented a 20 classes CNN classifier using Tensorflow with the help of  Denny Britz code : https://github.com/dennybritz/cnn-text-classification-tf .

As you can see at the end of text_cnn.py he implements a simple function to compute the global accuracy :

# Accuracy
        with tf.name_scope("accuracy"):
            correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
            self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")

Any ideas on how i could do something similar to get the recall and precision value for the differents categories?

Maybe my question will sound dumb but I'm a bit lost with this to be honest. Thanks for the help.

Body:
Using tf.metrics did the trick for me :

#define the method
x = tf.placeholder(tf.int32, )
y = tf.placeholder(tf.int32, )
acc, acc_op = tf.metrics.accuracy(labels=x, predictions=y)
rec, rec_op = tf.metrics.recall(labels=x, predictions=y)
pre, pre_op = tf.metrics.precision(labels=x, predictions=y)

#predict the class using your classifier
scorednn = list(DNNClassifier.predict_classes(input_fn=lambda: input_fn(testing_set)))
scoreArr = np.array(scorednn).astype(int)

#run the session to compare the label with the prediction
sess=tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
v = sess.run(acc_op, feed_dict={x: testing_set["target"],y: scoreArr}) #accuracy
r = sess.run(rec_op, feed_dict={x: testing_set["target"],y: scoreArr}) #recall
p = sess.run(pre_op, feed_dict={x: testing_set["target"],y: scoreArr}) #precision

print("accuracy %f", v)
print("recall %f", r)
print("precision %f", p)

Result :

accuracy %f 0.686667
recall %f 0.978723
precision %f 0.824373

Note : for Accuracy I would use :

accuracy_score = DNNClassifier.evaluate(input_fn=lambda:input_fn(testing_set),steps=1)["accuracy"]

As it is simpler and already compute in the evaluate.

Also call variables_initializer if you don't want cumulative result.


问:
Appium error : [XCUITest] Error: Could not initialize ios-deploy make sure it is installed (npm install -g ios-deploy) and works on your system
I got an error in Appium : [XCUITest] Error: Could not initialize ios-deploy make sure it is installed (npm install -g ios-deploy) and works on your system.

I try to run my test automation on the real device, not on simulator.

I am using Mac v10.12.5
Appium v1.6.5
Xcode v8.3.3

Can anyone help what could cause it please?

答:
Check this out latest appium desktop iOS setup :

AppiumDesktop1.1.0beta4 iOS setup - Inspector and Record the scripts,

Link : https://www.youtube.com/watch?v=2_xHmofGgUE

If you face any issue please comment it.


问:
The audience is invalid error
I have 3 projects 1- Javascript SPA 2- Web API Project, 3- IdentityServer with EF Core

I started debugging API and Identity Server and successfully get the jwt token but, when I try to get value from API method which has Authorize Attribute I get an error:

```<code>WWW-Authenticate →Bearer error="invalid_token", error_description="The audience is invalid"
</code>```

I could not found any property about audience in auth options. This is my configuration in API project

```<code>app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
        {
            ApiSecret="secret",
            Authority = "http://localhost:5000",
            ApiName="fso.Api",
            RequireHttpsMetadata = false,
        });
</code>```

And my Config.cs file in Identity

```<code> public class Config
{
    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource()
            {
                Name = "fso.Api",
                DisplayName = "feasion API",
                Scopes =
                {
                    new Scope("api1"),
                    new Scope(StandardScopes.OfflineAccess)
                },
                UserClaims =
                {
                    JwtClaimTypes.Subject,
                    JwtClaimTypes.EmailVerified,
                    JwtClaimTypes.Email,
                    JwtClaimTypes.Name,
                    JwtClaimTypes.FamilyName,
                    JwtClaimTypes.PhoneNumber,
                    JwtClaimTypes.PhoneNumberVerified,
                    JwtClaimTypes.PreferredUserName,
                    JwtClaimTypes.Profile,
                    JwtClaimTypes.Picture,
                    JwtClaimTypes.Locale,
                    JwtClaimTypes.IdentityProvider,
                    JwtClaimTypes.BirthDate,
                    JwtClaimTypes.AuthenticationTime
                }
            }
        };
    }
    public static List<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Email(),
            new IdentityResources.Profile(),
        };
    }

    // client want to access resources (aka scopes)
    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "fso.api",
                AllowOfflineAccess=true,
                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                AllowedScopes =
                {
                   StandardScopes.OfflineAccess,
                   "api1"
                }
            }
        };
    }
}
</code>```

答:
See here for what this claim is about:

The aud (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the aud claim when this claim is present, then the JWT MUST be rejected....

So your API's name must exist in the aud claim for the JWT to be valid when it is validated by the middleware in your API. You can use jwt.io to look at your token by the way, that can be useful to help make sense of it.

In order to have IdentityServer to add your API's name to the aud claim your client code (which is attempting to get a resource from the API and therefore needs an access token) should request a scope from your API. For example like this (from an MVC client):

```<code>app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    Authority = Configuration["IdpAuthorityAddress"],
    ClientId = "my_web_ui_id",
    Scope = { "api1" },

    //other properties removed...
});
</code>```

Title: The audience is invalid error

Body:
I have 3 projects 1- Javascript SPA 2- Web API Project, 3- IdentityServer with EF Core

I started debugging API and Identity Server and successfully get the jwt token but, when I try to get value from API method which has Authorize Attribute I get an error:

WWW-Authenticate →Bearer error="invalid_token", error_description="The audience is invalid"

I could not found any property about audience in auth options. This is my configuration in API project

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
        {
            ApiSecret="secret",
            Authority = "http://localhost:5000",
            ApiName="fso.Api",
            RequireHttpsMetadata = false,
        });

And my Config.cs file in Identity

 public class Config
{
    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource()
            {
                Name = "fso.Api",
                DisplayName = "feasion API",
                Scopes =
                {
                    new Scope("api1"),
                    new Scope(StandardScopes.OfflineAccess)
                },
                UserClaims =
                {
                    JwtClaimTypes.Subject,
                    JwtClaimTypes.EmailVerified,
                    JwtClaimTypes.Email,
                    JwtClaimTypes.Name,
                    JwtClaimTypes.FamilyName,
                    JwtClaimTypes.PhoneNumber,
                    JwtClaimTypes.PhoneNumberVerified,
                    JwtClaimTypes.PreferredUserName,
                    JwtClaimTypes.Profile,
                    JwtClaimTypes.Picture,
                    JwtClaimTypes.Locale,
                    JwtClaimTypes.IdentityProvider,
                    JwtClaimTypes.BirthDate,
                    JwtClaimTypes.AuthenticationTime
                }
            }
        };
    }
    public static List<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Email(),
            new IdentityResources.Profile(),
        };
    }

    // client want to access resources (aka scopes)
    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "fso.api",
                AllowOfflineAccess=true,
                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                AllowedScopes =
                {
                   StandardScopes.OfflineAccess,
                   "api1"
                }
            }
        };
    }
}

Body:
See here for what this claim is about:

The aud (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the aud claim when this claim is present, then the JWT MUST be rejected....

So your API's name must exist in the aud claim for the JWT to be valid when it is validated by the middleware in your API. You can use jwt.io to look at your token by the way, that can be useful to help make sense of it.

In order to have IdentityServer to add your API's name to the aud claim your client code (which is attempting to get a resource from the API and therefore needs an access token) should request a scope from your API. For example like this (from an MVC client):

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    Authority = Configuration["IdpAuthorityAddress"],
    ClientId = "my_web_ui_id",
    Scope = { "api1" },

    //other properties removed...
});


问:
How to get the integer part and fractional part of a number in Swift
This is a super basic question, but, I can't seem to find an answer in Swift.

Question:

How do I get the whole integer part and fractional part (to the left and right of the decimal point respectively) of a number in Swift 2 and Swift 3? For example, for the number 1234.56789 —

How do I get the integer part 1234.56789 ?

How do I get the fractional part 1234.56789 ?

答:
You could do this ->

```<code>let x:Double = 1234.5678
let y:Double = Double(Int(x))
let z:Double = x - Double(Int(x))
print("\(x) \(y) \(z)")
</code>```

Where x is your original value. y is the integer part and z is the fractional part.

Edit

Thomas answer is the one you want ...

Body:
You could do this ->

let x:Double = 1234.5678
let y:Double = Double(Int(x))
let z:Double = x - Double(Int(x))
print("\(x) \(y) \(z)")

Where x is your original value. y is the integer part and z is the fractional part.

Edit

Thomas answer is the one you want ...


问:
Can the compiler exploit empty base optimisation if the class contains a member of the base class?
Consider

```<code>struct base {};
struct child : base {};
</code>```

It's well-known that sizeof(child) can be 1 by application of the empty base optimisation.

Now however, consider

```<code>struct base {};
struct child : base {base b;};
</code>```

Can the compiler apply the empty base optimisation now, or must sizeof(child) be at least 2?

Reference: http://en.cppreference.com/w/cpp/language/ebo

答:
I'll plop in another more basic quote

[intro.object]

Two objects a and b with overlapping lifetimes that are not bit-fields may have the same address if one is nested within the other, or if at least one is a base class subobject of zero size and they are of different types; otherwise, they have distinct addresses.

Since b is not an subobject of the inherited base, they must have distinct addresses.

Body:
Consider

struct base {};
struct child : base {};

It's well-known that sizeof(child) can be 1 by application of the empty base optimisation.

Now however, consider

struct base {};
struct child : base {base b;};

Can the compiler apply the empty base optimisation now, or must sizeof(child) be at least 2?

Reference: http://en.cppreference.com/w/cpp/language/ebo


问:
Django Inline Formsets - clean() method not working
So I have a django inline formset created by django.forms.inlineformset_factory, which contains a parent: ParentCount, and child: ChildCount.

Inside the ChildCount form I have rewritten the clean method as such:

```<code>class ChildCountForm(ModelForm):
    class Meta:
        model = ChildCount
        exclude = ["name"]

    def clean(self):
        cleaned_data = super(ChildCountForm, self).clean()

        att1 = cleaned_data.get("att1")
        att2 = cleaned_data.get("att2")

        if att1 == "I3i" and att2 is None:
            msg = "Require att2 information for I3i attribute"
            self._errors['att2'] = self.error_class([msg])

        """Returns the cleaned data"""
        return cleaned_data
</code>```

I thought this would get called for each ChildForm inside the formset, as the inlineformset_factory is defined using a custom form class, which uses the logic:

```<code>class CustomInlineFormset(BaseInlineFormSet):
    """used to pass in the constructor of inlineformset_factory"""
    def clean(self):
        """forces each clean() method on the ChildCounts to be called"""
        super(BaseInlineFormSet, self).clean()
        for form in self.forms:
            form.clean()

ChildFormSet = inlineformset_factory(ParentCount, ChildCount,
                                     form=ParentCountForm,
                                     extra=1,
                                     max_num=30,
                                     formset=CustomInlineFormset)
</code>```

However, at this point in the form, the clean method() of each form is not derived from ChildCountForm, it's derived from BaseModelForm. If I instantiate an empty ChildCountForm at that line in the pdb, it says it derives the clean method from ChildCountForm, but the 'form' object in self.forms doesn't. Why is this?

How can I get my custom clean() method to run for each ChildForm?

答:
You've misunderstood what the inlineformset_factory is doing. It creates the formset for the child forms, so you if you want to specify a custom form you should pass in ChildCountForm.

Note also that calling the clean method of each form is the default behaviour, so there is no need to override the formset to do that.

Body:
So I have a django inline formset created by django.forms.inlineformset_factory, which contains a parent: ParentCount, and child: ChildCount.

Inside the ChildCount form I have rewritten the clean method as such:

class ChildCountForm(ModelForm):
    class Meta:
        model = ChildCount
        exclude = ["name"]

    def clean(self):
        cleaned_data = super(ChildCountForm, self).clean()

        att1 = cleaned_data.get("att1")
        att2 = cleaned_data.get("att2")

        if att1 == "I3i" and att2 is None:
            msg = "Require att2 information for I3i attribute"
            self._errors['att2'] = self.error_class([msg])

        """Returns the cleaned data"""
        return cleaned_data

I thought this would get called for each ChildForm inside the formset, as the inlineformset_factory is defined using a custom form class, which uses the logic:

class CustomInlineFormset(BaseInlineFormSet):
    """used to pass in the constructor of inlineformset_factory"""
    def clean(self):
        """forces each clean() method on the ChildCounts to be called"""
        super(BaseInlineFormSet, self).clean()
        for form in self.forms:
            form.clean()

ChildFormSet = inlineformset_factory(ParentCount, ChildCount,
                                     form=ParentCountForm,
                                     extra=1,
                                     max_num=30,
                                     formset=CustomInlineFormset)

However, at this point in the form, the clean method() of each form is not derived from ChildCountForm, it's derived from BaseModelForm. If I instantiate an empty ChildCountForm at that line in the pdb, it says it derives the clean method from ChildCountForm, but the 'form' object in self.forms doesn't. Why is this?

How can I get my custom clean() method to run for each ChildForm?


问:
Jquery show hide issue on server
I am creating a simple show/hide all toggle button for my images in my instagram feed. It works fine in the fiddle but when I put the same code on my server nothing works with no error. Can anyone help me troubleshoot why this isn't working.

Here is the HTML

```<code><div class="btn btn-success toggleAll">
    Show All/Hide All
</div>
</code>```

Here is the Javascript

```<code>$('.toggleAll').on('click',function(){
    $('.pp, .coat, .heart-wrap, .comment-wrap, .check-wrap, .grip .btn').slideToggle('fast');
});
</code>```

and here is the jsfiddle that works

https://jsfiddle.net/galnova/ua0ojhhe/5/

Here is my site where it doesn't work

http://galnova.com

Any help is welcome guys.

答:
I don't see this code in your website's code:  </p>

```<code>$('.toggleAll').on('click',function(){
    $('.pp, .coat, .heart-wrap, .comment-wrap, .check-wrap, .grip .btn').slideToggle('fast');
});
</code>```

<p>I ran this in the console and the show/hide button started working fine. </p>

Title: Jquery show hide issue on server

Body:
I am creating a simple show/hide all toggle button for my images in my instagram feed. It works fine in the fiddle but when I put the same code on my server nothing works with no error. Can anyone help me troubleshoot why this isn't working.

Here is the HTML

    Show All/Hide All

Here is the Javascript

$('.toggleAll').on('click',function(){
    $('.pp, .coat, .heart-wrap, .comment-wrap, .check-wrap, .grip .btn').slideToggle('fast');
});

and here is the jsfiddle that works

https://jsfiddle.net/galnova/ua0ojhhe/5/

Here is my site where it doesn't work

http://galnova.com

Any help is welcome guys.

Body:
I don't see this code in your website's code:

$('.toggleAll').on('click',function(){
    $('.pp, .coat, .heart-wrap, .comment-wrap, .check-wrap, .grip .btn').slideToggle('fast');
});

I ran this in the console and the show/hide button started working fine.


问:
How to use UUID
I am trying to get unique IDs for my Django objects.  In Django 1.8 they have the UUIDField.  I am unsure how to use this field in order to generate unique IDs for each object in my model.

Here is what I have for the UUIDField

```<code>import uuid
from django.db import models

class MyUUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class Person(models.Model):
    ...
    unique_id = MyUUIDModel()
</code>```

I can reproduce the id for the UUID model, but everytime I do I get the exact same id. For Example:

```<code>person = Person.objects.get(some_field = some_thing)
id = person.unique_id.id
</code>```

id then gives me the same id every time.  What is wrong, how do I fix this?

答:
You need to use the class you created as a subclass when declaring your Person model like this: </p>

```<code>import uuid
from django.db import models

class MyUUIDModel(models.Model):
  id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class Person(MyUUIDModel):
  ...
</code>```

<p>This way Person becomes a subclass of MyUUIDModel and will inherit its id field definition. </p>

ContentLicense: CC BY-SA 4.0

Title: How to use UUID

Body:
I am trying to get unique IDs for my Django objects.  In Django 1.8 they have the UUIDField.  I am unsure how to use this field in order to generate unique IDs for each object in my model.

Here is what I have for the UUIDField

import uuid
from django.db import models

class MyUUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class Person(models.Model):
    ...
    unique_id = MyUUIDModel()

I can reproduce the id for the UUID model, but everytime I do I get the exact same id. For Example:

person = Person.objects.get(some_field = some_thing)
id = person.unique_id.id

id then gives me the same id every time.  What is wrong, how do I fix this?

Body:
You need to use the class you created as a subclass when declaring your Person model like this:

import uuid
from django.db import models

class MyUUIDModel(models.Model):
  id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class Person(MyUUIDModel):
  ...

This way Person becomes a subclass of MyUUIDModel and will inherit its id field definition.


问:
Regex in Vim- inserting blank line before numbered lines
I have following text:

```<code>Title line
1. First list
First line
Second line
2. Second list
Oranges
Mangoes
3. Stationary
Pen
Pencils
Etc
</code>```

I want to add a blank line before every numbered line, so that above text looks like following:

```<code>Title line

1. First list
First line
Second line

2. Second list
Oranges
Mangoes

3. Stationary
Pen
Pencils
Etc
</code>```

I tried following code but it is not working:

```<code>%s/^(\d)/\r\1/g
</code>```

and

```<code>%s/(^\d)/\r\1/g
</code>```

and

%s/^([0-9])/\r\1/gc

Where is the problem and how can this be solved. Thanks for your help.

答:
You should escape parentheses within a VIM syntax in order to mean it a special cluster:

```<code>%s/^\(\d\)/\r\1/g
</code>```

Or use an end of match zero-width assertion (\ze) token:

```<code>%s/^\ze\d/\r
</code>```

Body:
I have following text:

Title line
1. First list
First line
Second line
2. Second list
Oranges
Mangoes
3. Stationary
Pen
Pencils
Etc

I want to add a blank line before every numbered line, so that above text looks like following:

Title line

1. First list
First line
Second line

2. Second list
Oranges
Mangoes

3. Stationary
Pen
Pencils
Etc

I tried following code but it is not working:

%s/^(\d)/\r\1/g

and

%s/(^\d)/\r\1/g

and

%s/^([0-9])/\r\1/gc

Where is the problem and how can this be solved. Thanks for your help.

Body:
You should escape parentheses within a VIM syntax in order to mean it a special cluster:

%s/^\(\d\)/\r\1/g

Or use an end of match zero-width assertion (\ze) token:

%s/^\ze\d/\r


问:
ActionFilterAttribute on Web api call does not correctly redirect to the new location
My action filter attribute does not redirect to the new url i have defined:

```<code>public class RunOnServerAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public ServerType Type;

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
    {
        switch (Type)
        {
            case ServerType.CMS:
                if (!filterContext.Request.RequestUri.AbsoluteUri.StartsWith(Config.CMSUrl))
                {
                    Uri correctedUri = new Uri($"{Config.CMSUrl.TrimEnd('/')}/{filterContext.Request.RequestUri.PathAndQuery.TrimStart('/')}");
                    var response = filterContext.Request.CreateResponse(System.Net.HttpStatusCode.Moved);
                    response.Headers.Location = correctedUri;
                    return;
                    // This does not seem to work
                }

                break;
        }

        base.OnActionExecuting(filterContext);
    }
}
</code>```

It just continues on with the normal request. I am debugging this by inspecting the Request.RequestUri in the executing api method

答:
Sorry for not noticing it's a WebAPI project.
Composing the response should be a quick resolution.

```<code>var res = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);
res.Headers.Location = new Uri("https://www.google.com");
actionContext.Response = res;
</code>```

------------- Updated above. --------------

You should use the filterContext.Result and assign the ActionResult. Just like what you do in normal actions.
For instance,

```<code>var controller = (YourBaseControllerType)filterContext.Controller;
filterContext.Result = controller.RedirectToAction("actionName", "controllerName");
</code>```

or

```<code>filterContext.Result = new RedirectResult(YourUrl);
</code>```

Body:
My action filter attribute does not redirect to the new url i have defined:

public class RunOnServerAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public ServerType Type;

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
    {
        switch (Type)
        {
            case ServerType.CMS:
                if (!filterContext.Request.RequestUri.AbsoluteUri.StartsWith(Config.CMSUrl))
                {
                    Uri correctedUri = new Uri($"{Config.CMSUrl.TrimEnd('/')}/{filterContext.Request.RequestUri.PathAndQuery.TrimStart('/')}");
                    var response = filterContext.Request.CreateResponse(System.Net.HttpStatusCode.Moved);
                    response.Headers.Location = correctedUri;
                    return;
                    // This does not seem to work
                }

                break;
        }

        base.OnActionExecuting(filterContext);
    }
}

It just continues on with the normal request. I am debugging this by inspecting the Request.RequestUri in the executing api method

Body:
Sorry for not noticing it's a WebAPI project.
Composing the response should be a quick resolution.

var res = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);
res.Headers.Location = new Uri("https://www.google.com");
actionContext.Response = res;

------------- Updated above. --------------

You should use the filterContext.Result and assign the ActionResult. Just like what you do in normal actions.
For instance,

var controller = (YourBaseControllerType)filterContext.Controller;
filterContext.Result = controller.RedirectToAction("actionName", "controllerName");

or

filterContext.Result = new RedirectResult(YourUrl);


问:
Nancy support for .NETCoreApp
Trying to add the Nancy package to a new project. In project.json (dependencies segment) red squigly under "Nancy": "1.4.3". Mouseover displays an error relating to support for .NETCoreApp

答: Install-Package Nancy -Version 2.0.0-barneyrubble -Pre</p>

Title: Nancy support for .NETCoreApp


问:
While Loop Won't Exit While Using Read System Call
I'm working on building a basic program that acts as a shell using linux system call. Right now I'm trying to have it read the input in as a string so I can modify the information as needed. When I run the program and give it some input from the terminal it proceeds to hang afterwards. I'm guessing my while loop won't end, but I'm not sure why. Any and all help would be appreciated. </p>

```<code>#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char ** argv) {
    int i;

    char prompt[3] = "sh#";
    char input[256];
    char inputc;

    /*print out prompt */
    write(1, &prompt, sizeof(prompt));

    i = 0;
    while(read(0, &inputc, 1) != 0) {
        input[i] = inputc;
        i++;
    }
    input[i] = '\0';  /* null terminator */
    printf("%s\n", input);

    return 0;
}
</code>```

答:
You should use getline() instead of read().  Because getline() does a lot of the work for you.  Also, if you only wanted to receive 1 line from input, then simply use read() or getline() without the while() loop that you established.  The while loop will be most necessary for multiple inputs, which is what I assumed you wanted since you are calling this a shell type program and your prompt string has sh in it.

If you want to use read() in your code, then you should create your own getline() that uses read().  This could be an example of the code for your own my_getline() function code for your loop using read(), and you should add your conditionals to break as you wish.

```<code>char *inputc, input[256];
int i;
for (i = 0; (read(STDIN_FILENO, inputc, 1) != EOF); i++)
{
    input[i] = inputc[0];
}
</code>```

I have modified your code with this fix and removed the unneccessary variables.  You didn't use argc and **argv so they are removed as well.  The while loop uses getline() instead of read().  The string is print after every input line.  The mini-shell terminates when the input string is: "quit".  If you want to terminate with no input you can add a modification for this as well.

```<code>$ cat main.c
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
    size_t size = 256;
    char prompt[5] = "sh$ ";
    char *inputc = NULL;
    /* print out prompt */
    write(1, &prompt, 4);
    while(getline(&inputc, &size, stdin) != -1)
    {
        /* check if input is "quit" to terminate the mini shell */
        if (strncmp(inputc, "quit", 4) == 0)
            break;
        /* prints the input */
        printf("%s", inputc);
        /* re-print out prompt to continue loop*/
        write(1, &prompt, 4);
    }
    printf("%s\n", inputc);
    return 0;
}
</code>```

Output in your terminal (the third input is just newline '\n' or the [RTN] button, no input, and nothing is printed:

```<code>$ gcc -Wall -Werror -Wextra -pedantic main.c
$ ./a.out
sh$ This is a test
This is a test
sh$ See how well getline works!
See how well getline works!
sh$

sh$ quit
quit

$
</code>```

Body:
I'm working on building a basic program that acts as a shell using linux system call. Right now I'm trying to have it read the input in as a string so I can modify the information as needed. When I run the program and give it some input from the terminal it proceeds to hang afterwards. I'm guessing my while loop won't end, but I'm not sure why. Any and all help would be appreciated.

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char ** argv) {
    int i;

    char prompt[3] = "sh#";
    char input[256];
    char inputc;

    /*print out prompt */
    write(1, &prompt, sizeof(prompt));

    i = 0;
    while(read(0, &inputc, 1) != 0) {
        input[i] = inputc;
        i++;
    }
    input[i] = '\0';  /* null terminator */
    printf("%s\n", input);

    return 0;
}

Body:
You should use getline() instead of read().  Because getline() does a lot of the work for you.  Also, if you only wanted to receive 1 line from input, then simply use read() or getline() without the while() loop that you established.  The while loop will be most necessary for multiple inputs, which is what I assumed you wanted since you are calling this a shell type program and your prompt string has sh in it.

If you want to use read() in your code, then you should create your own getline() that uses read().  This could be an example of the code for your own my_getline() function code for your loop using read(), and you should add your conditionals to break as you wish.

char *inputc, input[256];
int i;
for (i = 0; (read(STDIN_FILENO, inputc, 1) != EOF); i++)
{
    input[i] = inputc[0];
}

I have modified your code with this fix and removed the unneccessary variables.  You didn't use argc and **argv so they are removed as well.  The while loop uses getline() instead of read().  The string is print after every input line.  The mini-shell terminates when the input string is: "quit".  If you want to terminate with no input you can add a modification for this as well.

$ cat main.c
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
    size_t size = 256;
    char prompt[5] = "sh$ ";
    char *inputc = NULL;
    /* print out prompt */
    write(1, &prompt, 4);
    while(getline(&inputc, &size, stdin) != -1)
    {
        /* check if input is "quit" to terminate the mini shell */
        if (strncmp(inputc, "quit", 4) == 0)
            break;
        /* prints the input */
        printf("%s", inputc);
        /* re-print out prompt to continue loop*/
        write(1, &prompt, 4);
    }
    printf("%s\n", inputc);
    return 0;
}

Output in your terminal (the third input is just newline '\n' or the [RTN] button, no input, and nothing is printed:

$ gcc -Wall -Werror -Wextra -pedantic main.c
$ ./a.out
sh$ This is a test
This is a test
sh$ See how well getline works!
See how well getline works!
sh$

sh$ quit
quit

$


问:
Create table with Global secondary index using DynamoMapper and class Annotation
I am currently using Java dynamoMapper to create and query the table. When trying to create a table with a global secondary index, I get the following error

No provisioned throughput specified for the global secondary index
```
<p>My java class representing the table has this attribute for the global secondary index.</p>
```@DynamoDBIndexHashKey(globalSecondaryIndexName="sender")
    public String getSender() {
    return sender;
}
```
<p>Class to create table looks like this <br></p>
```public boolean createTable() {
try {
DynamoDBMapper mapper = new DynamoDBMapper(client);
CreateTableRequest tableRequest =     mapper.generateCreateTableRequest(entityClass); // 1
tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1000L, 1500L)); // 2
client.createTable(tableRequest); // 3

    } catch (Error e) {
        e.printStackTrace();
        return false;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}
```

I have searched the Amazon site for additional annotations and configuration but nothing came up for DynamoMapper. Is there anyway to do this using ORM or will i have to manually create by using a lower level API?

答:
Extension to @Jeremy's answer.

If you have more than one GSI, then you may do it like below. Also you don't need to create ProvisionedThroughput object all the time if they are of same values.

```<code> final ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput(5L, 5L);
 createRequest.setProvisionedThroughput(provisionedThroughput);
 createRequest.getGlobalSecondaryIndexes().forEach(v -> v.setProvisionedThroughput(provisionedThroughput));
</code>```

Body:
I am currently using Java dynamoMapper to create and query the table. When trying to create a table with a global secondary index, I get the following error

No provisioned throughput specified for the global secondary index

My java class representing the table has this attribute for the global secondary index.

@DynamoDBIndexHashKey(globalSecondaryIndexName="sender")
    public String getSender() {
    return sender;
}

Class to create table looks like this

public boolean createTable() {
try {
DynamoDBMapper mapper = new DynamoDBMapper(client);
CreateTableRequest tableRequest =     mapper.generateCreateTableRequest(entityClass); // 1
tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1000L, 1500L)); // 2
client.createTable(tableRequest); // 3

    } catch (Error e) {
        e.printStackTrace();
        return false;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

I have searched the Amazon site for additional annotations and configuration but nothing came up for DynamoMapper. Is there anyway to do this using ORM or will i have to manually create by using a lower level API?

Body:
Extension to @Jeremy's answer.

If you have more than one GSI, then you may do it like below. Also you don't need to create ProvisionedThroughput object all the time if they are of same values.

 final ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput(5L, 5L);
 createRequest.setProvisionedThroughput(provisionedThroughput);
 createRequest.getGlobalSecondaryIndexes().forEach(v -> v.setProvisionedThroughput(provisionedThroughput));


问:
Simplify large-data processing script
I am trying to do the following but it takes to much time.
Can someone please suggest a quicker way of doing this</p>

```<code>f = open('answer.csv','w')
f.write('Datetime,0: Vm,0: Va,1: Vm,1: Va,2: Vm,2: Va,3: Vm,3: Va,4: Vm,4: Va,5: Vm,5: Va,6: Vm,6: Va,7: Vm,7: Va,8: Vm,8: Va,9: Vm,9: Va,10: Vm,10: Va,11: Vm,11: Va,12: Vm,12: Va,13: Vm,13: Va\n')
# 'n' is around 8000000
# 'PQ_data' is a pandas DataFrame with more than n rows
# 'class' is a python class object with some functions in it
for i in range(n):
    p = []
    q = []
    for j in range(1,14):
        if j<=10:
            p.append(PQ_data['{} P'.format(j)][i])
            q.append(PQ_data['{} Q'.format(j)][i])
        else:
            p.append(0)
            q.append(0)

    class.do_something(p,q)
    vm = class.get_Vm().tolist()
    va = class.get_Va().tolist()
    # above methods return 14 length lists.
    # PQ_data.index has datetime values
    f.write('{}'.format(PQ_data.index[i]))
    for j in range(len(vm)):
        f.write(',{},{}'.format(vm[j],va[j]))
    f.write('\n')
f.close()
</code>```

答:
Try this. If not, you might need to throw multiprocessing at it</p>

```<code>import csv
import itertools

with open('answer.csv','w') as fout:
    outfile = csv.writer(fout)
    outfile.writerow(['Datetime', '0: Vm', '0: Va', '1: Vm', '1: Va', '2: Vm', '2: Va', '3: Vm', '3: Va', '4: Vm', '4: Va', '5: Vm', '5: Va', '6: Vm', '6: Va', '7: Vm', '7: Va', '8: Vm', '8: Va', '9: Vm', '9: Va', '10: Vm', '10: Va', '11: Vm', '11: Va', '12: Vm', '12: Va', '13: Vm', '13: Va'])

    for i in range(n):
        p = [PQ_data['{} P'.format(j)][i] for j in range(1,11)] + [0]*3
        q = [PQ_data['{} Q'.format(j)][i] for j in range(1,11)] + [0]*3

        class.do_something(p,q)
        vm = class.get_Vm().tolist()
        va = class.get_Va().tolist()

        row = itertools.chain([PQ_data.index[i]], itertools.chain.from_iterable((vm[j],va[j]) for j in range(len(vm))))
        outfile.writerow(row)
</code>```

Title: Simplify large-data processing script

Body:
I am trying to do the following but it takes to much time.
Can someone please suggest a quicker way of doing this

f = open('answer.csv','w')
f.write('Datetime,0: Vm,0: Va,1: Vm,1: Va,2: Vm,2: Va,3: Vm,3: Va,4: Vm,4: Va,5: Vm,5: Va,6: Vm,6: Va,7: Vm,7: Va,8: Vm,8: Va,9: Vm,9: Va,10: Vm,10: Va,11: Vm,11: Va,12: Vm,12: Va,13: Vm,13: Va\n')
# 'n' is around 8000000
# 'PQ_data' is a pandas DataFrame with more than n rows
# 'class' is a python class object with some functions in it
for i in range(n):
    p = []
    q = []
    for j in range(1,14):
        if j<=10:
            p.append(PQ_data['{} P'.format(j)][i])
            q.append(PQ_data['{} Q'.format(j)][i])
        else:
            p.append(0)
            q.append(0)

    class.do_something(p,q)
    vm = class.get_Vm().tolist()
    va = class.get_Va().tolist()
    # above methods return 14 length lists.
    # PQ_data.index has datetime values
    f.write('{}'.format(PQ_data.index[i]))
    for j in range(len(vm)):
        f.write(',{},{}'.format(vm[j],va[j]))
    f.write('\n')
f.close()

Body:
Try this. If not, you might need to throw multiprocessing at it

import csv
import itertools

with open('answer.csv','w') as fout:
    outfile = csv.writer(fout)
    outfile.writerow(['Datetime', '0: Vm', '0: Va', '1: Vm', '1: Va', '2: Vm', '2: Va', '3: Vm', '3: Va', '4: Vm', '4: Va', '5: Vm', '5: Va', '6: Vm', '6: Va', '7: Vm', '7: Va', '8: Vm', '8: Va', '9: Vm', '9: Va', '10: Vm', '10: Va', '11: Vm', '11: Va', '12: Vm', '12: Va', '13: Vm', '13: Va'])

    for i in range(n):
        p = [PQ_data['{} P'.format(j)][i] for j in range(1,11)] + [0]*3
        q = [PQ_data['{} Q'.format(j)][i] for j in range(1,11)] + [0]*3

        class.do_something(p,q)
        vm = class.get_Vm().tolist()
        va = class.get_Va().tolist()

        row = itertools.chain([PQ_data.index[i]], itertools.chain.from_iterable((vm[j],va[j]) for j in range(len(vm))))
        outfile.writerow(row)


问:
How to get text data from the user in PL/SQL block
I'm trying to get text data from the user when the if conditions are true,

Please tell me how to do this in PL/SQL Developer.

答: Presumably, the conditions in question are known before you call from your user interface to the PL/SQL code.  If this is the case, test the conditions before the call to PL/SQL (in the user interface).  If necessary, get the text from the user, then call into your PL/SQL and pass the text.</p>


问:
Unable to find the fragment by tag when Back Button is pressed
I have two fragments namely FoodFragment and WishlistFragment these two are opened when i press their respective item clicks through the NavigationView

The problem I'm facing is when I press on the navigation items the fragments corresponding to them opens and everything works fine but when i press the back button, the MainActivity's onBackPressed() method is called and it only works for the first condition on the fragment that I've written.

Here's my code:

```<code>public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        int id = item.getItemId();
        mFragmentTransaction = getSupportFragmentManager().beginTransaction();

        if (id == R.id.food) {

            if(newFragment == null) {
                newFragment = FoodFragment.newInstance("food", "fragment");
                mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                mFragmentTransaction.replace(R.id.appBar, newFragment, "FoodFragment").addToBackStack("FoodFragment").commit();
            }

        }else if(id == R.id.wishlist){
            if(wishFragment == null){
                wishFragment = WishlistFragment.newInstance("wish", "fragment");
                mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                mFragmentTransaction.replace(R.id.appBar, wishFragment, "WishFragment").addToBackStack("WishFragment").commit();
            }
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
</code>```

Here's the onBackPressed() method:

```<code>public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        try {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            }  else if(getSupportFragmentManager().findFragmentByTag("WishFragment").isVisible()){
                getSupportFragmentManager().popBackStack();
                wishFragment = null;
            }else if (getSupportFragmentManager().findFragmentByTag("FoodFragment").isVisible()) {
                getSupportFragmentManager().popBackStack();
                newFragment = null;
            }else {
                super.onBackPressed();
            }
        }catch (NullPointerException npe){
            super.onBackPressed();
        }
    }
</code>```

I've added tags to each fragment as you can see in the code and handling them through the onBackPressed() method. Here, when I open the WishFragment and press back button everything is cleared and so i can open the WishFragment again by pressing the Navigation Item corresponding to it. But, this seems to be getting wrong in case of FoodFragment when I open the fragment and press back button, the condition corresponding to it is not executed and So, I'm unable to open the FoodFragment again.

But, if I change the ordering of conditions in onBackPressed() like this:

```<code>public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        try {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            }else if (getSupportFragmentManager().findFragmentByTag("FoodFragment").isVisible()) {
                getSupportFragmentManager().popBackStack();
                newFragment = null;
            }  else if(getSupportFragmentManager().findFragmentByTag("WishFragment").isVisible()){
                getSupportFragmentManager().popBackStack();
                wishFragment = null;
            }else {
                super.onBackPressed();
            }
        }catch (NullPointerException npe){
            super.onBackPressed();
        }
    }
</code>```

It seems to work now with FoodFragment but not with WishFragment, as a result I was able to open the FoodFragment again but not the WishFragment. I've searched for this problem on many websites but, I cannot get the right answer.

I've resolved it by adding view.setOnKeyListener(//calling the MainActivity by KeyEvents) for the fragment but, this doesn't seem to be a good way to do things as it reloads my entire MainActivity again.

I don't know where I'm doing wrong. Please suggest me a better way to do this.

Thank you.

答:
When the WishFragment is open and you press the back button

getSupportFragmentManager().findFragmentByTag("FoodFragment").isVisible()

This throws a NullPointerException.

So it will always do super.onBackPressed()since you are catching all the NullPointerException

To solve this change your if else statement to

```<code>if (drawer.isDrawerOpen(GravityCompat.START)) {
    drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().findFragmentByTag("FoodFragment") != null && getSupportFragmentManager().findFragmentByTag("FoodFragment").isVisible()) {
    getSupportFragmentManager().popBackStack();
    newFragment = null;
} else if(getSupportFragmentManager().findFragmentByTag("WishFragment") != null && getSupportFragmentManager().findFragmentByTag("WishFragment").isVisible()){
    getSupportFragmentManager().popBackStack();
    wishFragment = null;
} else {
    super.onBackPressed();
}
</code>```

Body:
I have two fragments namely FoodFragment and WishlistFragment these two are opened when i press their respective item clicks through the NavigationView

The problem I'm facing is when I press on the navigation items the fragments corresponding to them opens and everything works fine but when i press the back button, the MainActivity's onBackPressed() method is called and it only works for the first condition on the fragment that I've written.

Here's my code:

public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        int id = item.getItemId();
        mFragmentTransaction = getSupportFragmentManager().beginTransaction();

        if (id == R.id.food) {

            if(newFragment == null) {
                newFragment = FoodFragment.newInstance("food", "fragment");
                mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                mFragmentTransaction.replace(R.id.appBar, newFragment, "FoodFragment").addToBackStack("FoodFragment").commit();
            }

        }else if(id == R.id.wishlist){
            if(wishFragment == null){
                wishFragment = WishlistFragment.newInstance("wish", "fragment");
                mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                mFragmentTransaction.replace(R.id.appBar, wishFragment, "WishFragment").addToBackStack("WishFragment").commit();
            }
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

Here's the onBackPressed() method:

public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        try {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            }  else if(getSupportFragmentManager().findFragmentByTag("WishFragment").isVisible()){
                getSupportFragmentManager().popBackStack();
                wishFragment = null;
            }else if (getSupportFragmentManager().findFragmentByTag("FoodFragment").isVisible()) {
                getSupportFragmentManager().popBackStack();
                newFragment = null;
            }else {
                super.onBackPressed();
            }
        }catch (NullPointerException npe){
            super.onBackPressed();
        }
    }

I've added tags to each fragment as you can see in the code and handling them through the onBackPressed() method. Here, when I open the WishFragment and press back button everything is cleared and so i can open the WishFragment again by pressing the Navigation Item corresponding to it. But, this seems to be getting wrong in case of FoodFragment when I open the fragment and press back button, the condition corresponding to it is not executed and So, I'm unable to open the FoodFragment again.

But, if I change the ordering of conditions in onBackPressed() like this:

public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        try {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            }else if (getSupportFragmentManager().findFragmentByTag("FoodFragment").isVisible()) {
                getSupportFragmentManager().popBackStack();
                newFragment = null;
            }  else if(getSupportFragmentManager().findFragmentByTag("WishFragment").isVisible()){
                getSupportFragmentManager().popBackStack();
                wishFragment = null;
            }else {
                super.onBackPressed();
            }
        }catch (NullPointerException npe){
            super.onBackPressed();
        }
    }

It seems to work now with FoodFragment but not with WishFragment, as a result I was able to open the FoodFragment again but not the WishFragment. I've searched for this problem on many websites but, I cannot get the right answer.

I've resolved it by adding view.setOnKeyListener(//calling the MainActivity by KeyEvents) for the fragment but, this doesn't seem to be a good way to do things as it reloads my entire MainActivity again.

I don't know where I'm doing wrong. Please suggest me a better way to do this.

Thank you.

Body:
When the WishFragment is open and you press the back button

getSupportFragmentManager().findFragmentByTag("FoodFragment").isVisible()

This throws a NullPointerException.

So it will always do super.onBackPressed()since you are catching all the NullPointerException

To solve this change your if else statement to

if (drawer.isDrawerOpen(GravityCompat.START)) {
    drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().findFragmentByTag("FoodFragment") != null && getSupportFragmentManager().findFragmentByTag("FoodFragment").isVisible()) {
    getSupportFragmentManager().popBackStack();
    newFragment = null;
} else if(getSupportFragmentManager().findFragmentByTag("WishFragment") != null && getSupportFragmentManager().findFragmentByTag("WishFragment").isVisible()){
    getSupportFragmentManager().popBackStack();
    wishFragment = null;
} else {
    super.onBackPressed();
}


问:
How do I check if raw input is integer in python 2.7?
Is there a method that I can use to check if a raw_input is an integer?

I found this method after researching in the web:

```<code>print isinstance(raw_input("number: ")), int)
</code>```

but when I run it and input 4 for example, I get FALSE.
I'm kind of new to python, any help would be appreciated.

答:
```<code>def checker():
  inputt = raw_input("how many u want to check?")
  try:
      return int(inputt)
  except ValueError:
      print "Error!, pls enter int!"
      return checker()
</code>```

Body:
Is there a method that I can use to check if a raw_input is an integer?

I found this method after researching in the web:

print isinstance(raw_input("number: ")), int)

but when I run it and input 4 for example, I get FALSE.
I'm kind of new to python, any help would be appreciated.


问:
Image Upload using fs.writeFile() shows corrupt Images
I am facing a issue while uploading the image to Meteor's /public folder. The Flow works flawless, only the thing is the images are corrupt.

X.html

```<code><form class="documentForm" enctype="multipart/form-data">
    <label for="signature">Upload image of Signature</label>
    <input type="file" name="signature" id="signature" required>

    <label for="panCard">Upload image of Pan Card Only.</label>
    <input type="file" name="panCard" id="panCard" required>

    <button class="btn btn-primary" type="submit">Upload</button>
    <button class="btn btn-warning" id="reset">Reset</button>
</form>
</code>```

X.js

```<code>'submit .documentForm': function(event, template){
    event.preventDefault();
    console.log(event.target.signature.files[0]);
    var signatureImage = event.target.signature.files[0];
    var panCardImage = event.target.panCard.files[0];
    Meteor.call('upload', signatureImage, panCardImage, function(error, response){
      if(error){
        Bert.alert("<strong>Error !</strong> Some Problem occured while submitting documents.", 'danger', 'fixed-top' );
      } else if(response){
        Bert.alert("<strong>Success !</strong> Documents uploaded.", 'success', 'fixed-top' );
      }
    });
    return false;
}
</code>```

Meteor.method();

```<code>'upload'(signatureImage, panCardImage){
    const fs = Npm.require('fs');
    var signatureFileName = Meteor.userId() + "_signature.jpg";
    var panCardFileName = Meteor.userId() + "_pancard.jpg";
    var path = process.env['METEOR_SHELL_DIR'] + '/../../../public/img/userdocuments/';
    /*var encoding = {encoding: 'binary'};*/
    fs.writeFile(path + signatureFileName, signatureImage, Meteor.bindEnvironment(function (err) {
        if (err) {
            log.error(err);
        } else {
            log.debug("Signature upload - " + Meteor.userId());
        }
    }));
    fs.writeFile(path + panCardFileName, panCardImage, Meteor.bindEnvironment(function (err) {
        if (err) {
            log.error(err);
        } else {
            log.debug("Pan Card upload - " + Meteor.userId());
        }
    }));
    return true;
</code>```

},

why my image is corrupt? what should I do to rectify my mistake?

答:
You can't (or shouldn't - you choose) add files to the /public folder, for a number of reasons...

In development meteor will restart - this may be causing the corruption

The location of /public at run time is not the same as where your source is.

The file system where the meteor code is deployed is likely to be read only on the production system

On mobile platforms you don't have easy access to save files on the device, and the space is limited

While it is technically possible to define a location on the file system where your app can save files, and then either symlink this location in so that it's somewhere under /public, or run another express server just to serve up those files, it's not really best practice.

You should either look to store your uploaded files on a service such as AWS S3, or store them in the Mongo database. There are several packages which can help you achieve this, off the top of my head ostrio:files, vsivsi:file-collection and jalik:ufs

Body:
I am facing a issue while uploading the image to Meteor's /public folder. The Flow works flawless, only the thing is the images are corrupt.

X.html

<form class="documentForm" enctype="multipart/form-data">
    Upload image of Signature
    <input type="file" name="signature" id="signature" required>

    Upload image of Pan Card Only.
    <input type="file" name="panCard" id="panCard" required>

    <button class="btn btn-primary" type="submit">Upload</button>
    <button class="btn btn-warning" id="reset">Reset</button>
</form>

X.js

'submit .documentForm': function(event, template){
    event.preventDefault();
    console.log(event.target.signature.files[0]);
    var signatureImage = event.target.signature.files[0];
    var panCardImage = event.target.panCard.files[0];
    Meteor.call('upload', signatureImage, panCardImage, function(error, response){
      if(error){
        Bert.alert("Error ! Some Problem occured while submitting documents.", 'danger', 'fixed-top' );
      } else if(response){
        Bert.alert("Success ! Documents uploaded.", 'success', 'fixed-top' );
      }
    });
    return false;
}

Meteor.method();

'upload'(signatureImage, panCardImage){
    const fs = Npm.require('fs');
    var signatureFileName = Meteor.userId() + "_signature.jpg";
    var panCardFileName = Meteor.userId() + "_pancard.jpg";
    var path = process.env['METEOR_SHELL_DIR'] + '/../../../public/img/userdocuments/';
    /*var encoding = {encoding: 'binary'};*/
    fs.writeFile(path + signatureFileName, signatureImage, Meteor.bindEnvironment(function (err) {
        if (err) {
            log.error(err);
        } else {
            log.debug("Signature upload - " + Meteor.userId());
        }
    }));
    fs.writeFile(path + panCardFileName, panCardImage, Meteor.bindEnvironment(function (err) {
        if (err) {
            log.error(err);
        } else {
            log.debug("Pan Card upload - " + Meteor.userId());
        }
    }));
    return true;

},

why my image is corrupt? what should I do to rectify my mistake?


问:
Jailbroken iPhone 3G with iOS 4.2.1 can't be debugged with XCode
I'm trying to debug my applications with XCode 3.2.5 and jailbroken iPhone 3G with iOS 4.2.1.

When I start debug with enabled breakpoints, application can't start (it stucks on 'Default.png' screen) and I get Data Formatters temporarily unavailable, will re-try after a 'continue'. (Can't find dlopen function, so it is not possible to load shared libraries.) message in GDB.

When I start debug without enabled breakpoints, application starts without problems.

I tried to do steps decribed there, but without any results.

When I used iOS 4.1 there was a problem with reboots.

On every connect of the iPhone Organiser displays this message:

**Unknown iOS detected** Xcode does not have debugging information for the version of iOS on the device named “iPhone”. Xcode can collect debugging data from the device to enable development with this version of iOS. This process only needs to be done once per iOS version, and will take several minutes.

Thanks for any help!

答:
The latest Xcode+SDK drop doesn't know about iOS 4.2.1, because it was published before the latest patch came out. Xcode's Organizer has a new feature that tries to download debug support files directly from the device, but apparently it has some (possibly jailbreak-related) issues for some people.

iOS 4.2.1 is similar enough to 4.2 that Xcode can be coerced to use 4.2 support files to debug on 4.2.1 devices. To do this, simply go to the /Developer/Platforms/iPhoneOS.platform/DeviceSupport folder and manually copy the Symbols subfolder and/or the DeveloperDiskImage.* files from 4.2 (8C134) to 4.2.1 (8C148) (or whatever release folder Organizer creates for your device).


问:
How to get the profile of current user in Express
I am using MEAN Stack and mongoose. Using passport for authentication. I want to get the currently logged in user and display his details. For example if I am logged in and if I go to the profile page I want to get my details. There were only few resources on the internet.

Login.js (passport and routes are here)

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

var passport = require('passport');

var LocalStrategy = require('passport-local').Strategy;

var User = require('../models/user');

var ConnectRoles = require('connect-roles');

router.get('/', function(req, res, next) {

res.render('Login', { title: 'Login' });
});

passport.serializeUser(function(user, done) {

    done(null, user._id);
});

passport.deserializeUser(function(id, done) {

    User.findById(id, function(err, user) {

    done(err, user);
    });
});

passport.use("/", new LocalStrategy(

     function(username, password, done) {

        User.findOne({ username: username }, function(err, user) {

            if (err) { return done(err); }
            if (!user) {
                return done(null, false,
                 { message: "No user has that username!" });
            }
            user.checkPassword(password, function(err, isMatch) {

            if (err) { return done(err); }
                if (isMatch) {

                    return done(null, user);
                } else {
                    return done(null, false,
                 { message: "Invalid password." });
            }
        });
    });
}));

router.use(function(req, res, next) {

    res.locals.currentUser = req.user;

    res.locals.errors = req.flash("error");

    res.locals.infos = req.flash("info");
    next();
});

router.post("/", passport.authenticate("/", {

    successRedirect: "/SubmitSurvey",
    failureRedirect: "/",
    session: false,
    failureFlash: true
}));

router.get("/AdminDatabase", function(req, res) {

   res.render('AdminDatabase', { title: 'AdminDatabase' });

 });

router.get('/CreateSurvey', function(req, res, next) {

  res.render('CreateSurvey', { title: 'CreateSurvey' });

});

router.get('/SubmitSurvey', function(req, res, next) {

  res.render('SubmitSurvey', { title: 'SubmitSurvey' });

});

router.get('/profile', function(req, res, next) {

  res.render('profile', { title: 'profile' });

});

router.get("/Logout", function(req, res) {

    req.logout();

    res.redirect("/");
});

module.exports = router;
</code>```

How can I do this in nodejs

答:
As Alex said, you may explicitly pass some variable (e.g. your req.user) when calling res.render:

```<code>router.get('/profile', function(req, res, next) {
    res.render('profile', { title: 'profile', user: req.user });
});
</code>```

Instead, maybe you'd like some variables (like that req.user) to be accessible in all calls to res.render without bothering to specify them every time? In that case, you can use res.locals, e.g. by adding this middleware:

```<code>app.use(function(req, res, next){
  res.locals.user = req.user;
  next();
});
</code>```

And finally, for completeness -- in both of the approaches above, the variable user is available for you in the view. For example, if you're using a pug template, you may now do something like:

```<code>if user
  p Hello, #{user.id}, good to see you!
else
  p Please log in...
</code>```

Body:
I am using MEAN Stack and mongoose. Using passport for authentication. I want to get the currently logged in user and display his details. For example if I am logged in and if I go to the profile page I want to get my details. There were only few resources on the internet.

Login.js (passport and routes are here)

var express = require('express');
var router = express.Router();

var passport = require('passport');

var LocalStrategy = require('passport-local').Strategy;

var User = require('../models/user');

var ConnectRoles = require('connect-roles');

router.get('/', function(req, res, next) {

res.render('Login', { title: 'Login' });
});

passport.serializeUser(function(user, done) {

    done(null, user._id);
});

passport.deserializeUser(function(id, done) {

    User.findById(id, function(err, user) {

    done(err, user);
    });
});

passport.use("/", new LocalStrategy(

     function(username, password, done) {

        User.findOne({ username: username }, function(err, user) {

            if (err) { return done(err); }
            if (!user) {
                return done(null, false,
                 { message: "No user has that username!" });
            }
            user.checkPassword(password, function(err, isMatch) {

            if (err) { return done(err); }
                if (isMatch) {

                    return done(null, user);
                } else {
                    return done(null, false,
                 { message: "Invalid password." });
            }
        });
    });
}));

router.use(function(req, res, next) {

    res.locals.currentUser = req.user;

    res.locals.errors = req.flash("error");

    res.locals.infos = req.flash("info");
    next();
});

router.post("/", passport.authenticate("/", {

    successRedirect: "/SubmitSurvey",
    failureRedirect: "/",
    session: false,
    failureFlash: true
}));

router.get("/AdminDatabase", function(req, res) {

   res.render('AdminDatabase', { title: 'AdminDatabase' });

 });

router.get('/CreateSurvey', function(req, res, next) {

  res.render('CreateSurvey', { title: 'CreateSurvey' });

});

router.get('/SubmitSurvey', function(req, res, next) {

  res.render('SubmitSurvey', { title: 'SubmitSurvey' });

});

router.get('/profile', function(req, res, next) {

  res.render('profile', { title: 'profile' });

});

router.get("/Logout", function(req, res) {

    req.logout();

    res.redirect("/");
});

module.exports = router;

How can I do this in nodejs

Body:
As Alex said, you may explicitly pass some variable (e.g. your req.user) when calling res.render:

router.get('/profile', function(req, res, next) {
    res.render('profile', { title: 'profile', user: req.user });
});

Instead, maybe you'd like some variables (like that req.user) to be accessible in all calls to res.render without bothering to specify them every time? In that case, you can use res.locals, e.g. by adding this middleware:

app.use(function(req, res, next){
  res.locals.user = req.user;
  next();
});

And finally, for completeness -- in both of the approaches above, the variable user is available for you in the view. For example, if you're using a pug template, you may now do something like:

if user
  p Hello, #{user.id}, good to see you!
else
  p Please log in...


问:
Repeat same action with function and apply familly
I'm new on R (and I use R-studio) and I have to analyze a big data frame (60 variables for 10 000 observations). My data frame had a column name specie with lot of different animals species in there. The goal of my work it's to have results of 8 differents species, so I have to work on there separately.
I start with building different subset (like I learn in school) and with awesome packages(special thanks to dplyr & tdyr). But now I have to repeat many identical (or nearly identical) actions on each of the 8 species, so I spent much time to copy/paste and when I make a mistake I must verify and change mistakes on thousands of lines.
Then I try to learn about loops et apply family functions. But I can't do something good.

There is an exemple of an action I do on a specie with the traditional way (organize data):

```<code>espece_td_a <- subset(BDD, BDD$espece == "espece A" & BDD$placette =="TOTAL")%>%
  select(code_site,passage,adulte)%>%
  spread(passage, adulte)
  espece_td_a <- full_join(B.irene_td_a, BDD_P3_TOT_site)
  espece_td_a <- replace(espece_td_a, is.na(espece_td_a),0)
  espece_td_a$P1[B.irene_td_a$P1>0]<-1
  espece_td_a$P2[B.irene_td_a$P2>0]<-1
  espece_td_a$P3[B.irene_td_a$P3>0]<-1
  write.csv(espece_td_a, file = "espece_td_a.csv")
</code>```

BDD is my data frame.

BDD_P3_TOT_site is vector (or data frame with 1 columns and many rows ?) built with BDD

This "traditional way" work for me, but I must do something like that so many times! And it takes a lot of time...

Then I tried to "apply" this with function :

```<code>f <- function(x)
{
  select(code_site, passage, adulte)%>%
    spread(x, x$passage, x$adulte)%>%
    full_join(x, BDD_P3_TOT_site) -> x
  x <- replace(x, is.na(x),0)
  x$P1[x$P1>0]<-1
  x$P2[x$P2>0]<-1
  x$P3[x$P3>0]<-1
}
</code>```

I wish apply this function to my dataset with lapply (with my 8 species in list):

```<code>l <- c("espece_a","espece_b","espece_c")

lapply(l,f(x))
</code>```

Problems :

I know that is a wrong formulation for lapply if I want take my species into BDD.

the function doesn't want work:
I already made 8 subsets (for each of my interest species)
In my global environment: espece_a; espece_b...

Then I wanted to put my subset one by one into my function:

```<code>> f(espece_a)
</code>```

Error in select_(.data, .dots = lazyeval::lazy_dots(...)) :          Show Traceback
       object 'code_site' not found                                          Rerun with Debug

I wish that my table appears in my Globlal env with a name that make me able to recognize it (ex: "espece_td_a")

答:
You have 3 issues relating to your use of lapply:

You need to return the object x at the end of the f function:

l should be a list of dataframes not just a vector of dataframe names, i.e. l <- list(espece_a,espece_b,espece_c)

When using lapply with an existing function, you only need to pass the name of the function, i.e. lapply(l,f)

Hopefully this should solve your problem.

Body:
I'm new on R (and I use R-studio) and I have to analyze a big data frame (60 variables for 10 000 observations). My data frame had a column name specie with lot of different animals species in there. The goal of my work it's to have results of 8 differents species, so I have to work on there separately.
I start with building different subset (like I learn in school) and with awesome packages(special thanks to dplyr & tdyr). But now I have to repeat many identical (or nearly identical) actions on each of the 8 species, so I spent much time to copy/paste and when I make a mistake I must verify and change mistakes on thousands of lines.
Then I try to learn about loops et apply family functions. But I can't do something good.

There is an exemple of an action I do on a specie with the traditional way (organize data):

espece_td_a <- subset(BDD, BDD$espece == "espece A" & BDD$placette =="TOTAL")%>%
  select(code_site,passage,adulte)%>%
  spread(passage, adulte)
  espece_td_a <- full_join(B.irene_td_a, BDD_P3_TOT_site)
  espece_td_a <- replace(espece_td_a, is.na(espece_td_a),0)
  espece_td_a$P1[B.irene_td_a$P1>0]<-1
  espece_td_a$P2[B.irene_td_a$P2>0]<-1
  espece_td_a$P3[B.irene_td_a$P3>0]<-1
  write.csv(espece_td_a, file = "espece_td_a.csv")

BDD is my data frame.

BDD_P3_TOT_site is vector (or data frame with 1 columns and many rows ?) built with BDD

This "traditional way" work for me, but I must do something like that so many times! And it takes a lot of time...

Then I tried to "apply" this with function :

f <- function(x)
{
  select(code_site, passage, adulte)%>%
    spread(x, x$passage, x$adulte)%>%
    full_join(x, BDD_P3_TOT_site) -> x
  x <- replace(x, is.na(x),0)
  x$P1[x$P1>0]<-1
  x$P2[x$P2>0]<-1
  x$P3[x$P3>0]<-1
}

I wish apply this function to my dataset with lapply (with my 8 species in list):

l <- c("espece_a","espece_b","espece_c")

lapply(l,f(x))

Problems :

I know that is a wrong formulation for lapply if I want take my species into BDD.

the function doesn't want work:
I already made 8 subsets (for each of my interest species)
In my global environment: espece_a; espece_b...

Then I wanted to put my subset one by one into my function:

> f(espece_a)

Error in select_(.data, .dots = lazyeval::lazy_dots(...)) :          Show Traceback
       object 'code_site' not found                                          Rerun with Debug

I wish that my table appears in my Globlal env with a name that make me able to recognize it (ex: "espece_td_a")


问:
Why destructors does not accept parameters in C++?
Recently, I came across an example that my destructor needs to take a parameter.

I am working on a C package that manages memory internally and keeps track of allocating and freeing with parameters of its own. I do not want to break that.

I wrote a C code, that initializes my own data structures and frees them at the end. When I decided to migrate to C++ I realized that allocating data structures and freeing them should be placed in constructor and destructors. So I changed those functions to constructor and destructor.
My problem now is that I need to use a parameter to pass to destructor to free allocated data; that parameter is not in my own code and is C and I do not want to mess with that.

My question is twofold:

Why C++ decided not to accept parameters in destructors in the first place?
and
What are my options?
(I can save a pointer to that parameter or somehow call that function in my destructor, but it seems not a good practice of C++ programming)

Update: adding some code
Here is my imaginary class:

```<code>class paru_symbolic/* paru_symbolic*/
{
    public:
        paru_symbolic ( cholmod_sparse *A, cholmod_common *cc ); // constructor
        ~paru_symbolic (cholmod_common *cc ); // destructor

        // -------------------------------------------------------------------------
        // row-form of the input matrix and its permutations
        // -----------------------------------------------------------------------
              //--- other stuff
                     ...
};
</code>```

Here is my current C constructor:

```<code>#include "Parallel_LU.hpp"
paru_symbolic *paru_sym_analyse
(
 // inputs, not modified
   cholmod_sparse *A,
 // workspace and parameters
   cholmod_common *cc ){

    DEBUGLEVEL(0);
...
   aParent = (Int*) paru_alloc (m+nf, sizeof(Int),cc);

...
}
</code>```

and destructor:

```<code>void paru_freesym (paru_symbolic **LUsym_handle,
            // workspace and parameters
    cholmod_common *cc
){
    DEBUGLEVEL (0);
    if (LUsym_handle == NULL || *LUsym_handle == NULL){
        // nothing to do; caller probably ran out of memory
        return;
    }

    paru_symbolic *LUsym;
    LUsym = *LUsym_handle;

    Int m, n, anz, nf, rjsize;
...
    cholmod_l_free (m+nf, sizeof (Int), LUsym->aParent, cc);

...
    cholmod_l_free (1, sizeof (paru_symbolic), LUsym, cc);

   *LUsym_handle = NULL;
}
</code>```

The parameter cc is used inside the SuiteSparse package for tracking allocations and freeing data. It has been used all over in SuiteSparse package and is a useful tool for tracking memory.
Some people mentioned that who wants to pass a parameter to the destructor.That is a fair point, but we could have the same parameters that we have in the constructor as a default.

答:
Parameters in destructors do not make sense as destructors are automatically invoked when an object goes out of scope. How could you pass a parameter to that?

```<code>{
   Foo x;
} // `~Foo()` is automatically called here
</code>```

What you probably want is to store the resource in your class. Here's an unrealistic example with a dynamically-allocated pointer:

```<code>struct RAIIPointer
{
    Foo* ptr;

    // Initialize the resource
    RAIIPointer() : ptr{new Foo{/*...*/}}
    {
    }

    RAIIPointer(const RAIIPointer&) = delete;
    RAIIPointer& operator=(const RAIIPointer&) = delete;

    RAIIPointer(RAIIPointer&&) { /* implement appropriately */ }
    RAIIPointer& operator=(RAIIPointer&&) { /* implement appropriately */ }

    // Release the resource
    ~RAIIPointer()
    {
        delete ptr;
    }
};
</code>```

Note that in a real-world scenario you would use std::unique_ptr, and if you were implementing your own RAII resource class you would need to implement proper copy/move operations.

Body:
Recently, I came across an example that my destructor needs to take a parameter.

I am working on a C package that manages memory internally and keeps track of allocating and freeing with parameters of its own. I do not want to break that.

I wrote a C code, that initializes my own data structures and frees them at the end. When I decided to migrate to C++ I realized that allocating data structures and freeing them should be placed in constructor and destructors. So I changed those functions to constructor and destructor.
My problem now is that I need to use a parameter to pass to destructor to free allocated data; that parameter is not in my own code and is C and I do not want to mess with that.

My question is twofold:

Why C++ decided not to accept parameters in destructors in the first place?
and
What are my options?
(I can save a pointer to that parameter or somehow call that function in my destructor, but it seems not a good practice of C++ programming)

Update: adding some code
Here is my imaginary class:

class paru_symbolic/* paru_symbolic*/
{
    public:
        paru_symbolic ( cholmod_sparse *A, cholmod_common *cc ); // constructor
        ~paru_symbolic (cholmod_common *cc ); // destructor

        // -------------------------------------------------------------------------
        // row-form of the input matrix and its permutations
        // -----------------------------------------------------------------------
              //--- other stuff
                     ...
};

Here is my current C constructor:

#include "Parallel_LU.hpp"
paru_symbolic *paru_sym_analyse
(
 // inputs, not modified
   cholmod_sparse *A,
 // workspace and parameters
   cholmod_common *cc ){

    DEBUGLEVEL(0);
...
   aParent = (Int*) paru_alloc (m+nf, sizeof(Int),cc);

...
}

and destructor:

void paru_freesym (paru_symbolic **LUsym_handle,
            // workspace and parameters
    cholmod_common *cc
){
    DEBUGLEVEL (0);
    if (LUsym_handle == NULL || *LUsym_handle == NULL){
        // nothing to do; caller probably ran out of memory
        return;
    }

    paru_symbolic *LUsym;
    LUsym = *LUsym_handle;

    Int m, n, anz, nf, rjsize;
...
    cholmod_l_free (m+nf, sizeof (Int), LUsym->aParent, cc);

...
    cholmod_l_free (1, sizeof (paru_symbolic), LUsym, cc);

   *LUsym_handle = NULL;
}

The parameter cc is used inside the SuiteSparse package for tracking allocations and freeing data. It has been used all over in SuiteSparse package and is a useful tool for tracking memory.
Some people mentioned that who wants to pass a parameter to the destructor.That is a fair point, but we could have the same parameters that we have in the constructor as a default.

Body:
Parameters in destructors do not make sense as destructors are automatically invoked when an object goes out of scope. How could you pass a parameter to that?

{
   Foo x;
} // `~Foo()` is automatically called here

What you probably want is to store the resource in your class. Here's an unrealistic example with a dynamically-allocated pointer:

struct RAIIPointer
{
    Foo* ptr;

    // Initialize the resource
    RAIIPointer() : ptr{new Foo{/*...*/}}
    {
    }

    RAIIPointer(const RAIIPointer&) = delete;
    RAIIPointer& operator=(const RAIIPointer&) = delete;

    RAIIPointer(RAIIPointer&&) { /* implement appropriately */ }
    RAIIPointer& operator=(RAIIPointer&&) { /* implement appropriately */ }

    // Release the resource
    ~RAIIPointer()
    {
        delete ptr;
    }
};

Note that in a real-world scenario you would use std::unique_ptr, and if you were implementing your own RAII resource class you would need to implement proper copy/move operations.


问:
How to search in comma separated value in Laravel 5.1?
I want to search in comma separated value from a column in database. I know how to do this in MySQL query,

In MySQL:

```<code>SELECT ... WHERE FIND_IN_SET('1', field)
</code>```

but unable to find the alternative in Laravel.

here is what I have tried so far,

```<code>whereRaw(FIND_IN_SET(2,userid))
</code>```

But it doesn't help.

答:
Please Try the following code where $c is your search id like 1 or 2 or 3 etc and column_name is the your database table field name where search id store like 1,2,3 etc.

```<code>->whereRaw("find_in_set($c , column_name)");
</code>```

means

```<code>->whereRaw("find_in_set('1' , column_name)");
</code>```

Body:
I want to search in comma separated value from a column in database. I know how to do this in MySQL query,

In MySQL:

SELECT ... WHERE FIND_IN_SET('1', field)

but unable to find the alternative in Laravel.

here is what I have tried so far,

whereRaw(FIND_IN_SET(2,userid))

But it doesn't help.

Body:
Please Try the following code where $c is your search id like 1 or 2 or 3 etc and column_name is the your database table field name where search id store like 1,2,3 etc.

->whereRaw("find_in_set($c , column_name)");

means

->whereRaw("find_in_set('1' , column_name)");