问:
How to get Android simple Firebase Authentication to work? Getting null object reference error

Issue Fixed Update: Fixed by downgrading Firebase to 9.6.0 (just a random version I chose). I'm assuming the original issue has something to do with the emulator's good play or something.

Old Issue: So I need help, trying to set up Firebase Auth for logging in a user. I've enable this in  my Firebase console and I've done this before and had it working as a class assignment weeks ago. But this time I'm getting a Null Object Reference when trying to login.

I'm starting to think this is related to my gradle files.
mAuth isn't null, String email and password aren't null. I'm simply following this Firebase guide: https://firebase.google.com/docs/auth/android/password-auth

Exact Logcat error here

Module app Gradle file here

Project Gradle file here

Full class below. Line 43 where the error begins (as from the screenshot) is
 'mAuth.signInWithEmailAndPassword(email, password)'

```<code>package com.example.bri.inclass09;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class LoginActivity extends AppCompatActivity {

private FirebaseAuth mAuth;
private EditText emailET, passwordET;
private Button login, signup;
private static final String TAG = "test";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mAuth = FirebaseAuth.getInstance();
    Log.d(TAG, "mAuth is: " + mAuth.toString());
    login = findViewById(R.id.loginButton);
    signup = findViewById(R.id.signupButton);
    emailET =  findViewById(R.id.loginEmailET);
    passwordET = findViewById(R.id.loginPassET);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String email = emailET.getText().toString();
            String password = passwordET.getText().toString();
            Log.d(TAG, email + " " + password);

            mAuth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                // Sign in success, update UI with the signed-in user's information
                                Log.d(TAG, "createUserWithEmail:success");
                                FirebaseUser user = mAuth.getCurrentUser();
                            } else {
                                // If sign in fails, display a message to the user.
                                Log.w(TAG, "createUserWithEmail:failure", task.getException());
                                Toast.makeText(LoginActivity.this, "Authentication failed.",
                                        Toast.LENGTH_SHORT).show();
                            }

                            // ...
                        }
                    });
        }
    });
}

@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    //FirebaseUser currentUser = mAuth.getCurrentUser();
}
</code>```

}

答: in Android studio verify everything is correct using tools, firebase, Authentication then follow the prompts and verify your current key either debug or release (whichever your using) matches the setup if correct after the prompts you should get green "OK" then make sure your key matches the one in firebase

Body:
Issue Fixed Update: Fixed by downgrading Firebase to 9.6.0 (just a random version I chose). I'm assuming the original issue has something to do with the emulator's good play or something.

Old Issue: So I need help, trying to set up Firebase Auth for logging in a user. I've enable this in  my Firebase console and I've done this before and had it working as a class assignment weeks ago. But this time I'm getting a Null Object Reference when trying to login.

I'm starting to think this is related to my gradle files.
mAuth isn't null, String email and password aren't null. I'm simply following this Firebase guide: https://firebase.google.com/docs/auth/android/password-auth

Exact Logcat error here

Module app Gradle file here

Project Gradle file here

Full class below. Line 43 where the error begins (as from the screenshot) is
 'mAuth.signInWithEmailAndPassword(email, password)'

package com.example.bri.inclass09;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class LoginActivity extends AppCompatActivity {

private FirebaseAuth mAuth;
private EditText emailET, passwordET;
private Button login, signup;
private static final String TAG = "test";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mAuth = FirebaseAuth.getInstance();
    Log.d(TAG, "mAuth is: " + mAuth.toString());
    login = findViewById(R.id.loginButton);
    signup = findViewById(R.id.signupButton);
    emailET =  findViewById(R.id.loginEmailET);
    passwordET = findViewById(R.id.loginPassET);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String email = emailET.getText().toString();
            String password = passwordET.getText().toString();
            Log.d(TAG, email + " " + password);

            mAuth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                // Sign in success, update UI with the signed-in user's information
                                Log.d(TAG, "createUserWithEmail:success");
                                FirebaseUser user = mAuth.getCurrentUser();
                            } else {
                                // If sign in fails, display a message to the user.
                                Log.w(TAG, "createUserWithEmail:failure", task.getException());
                                Toast.makeText(LoginActivity.this, "Authentication failed.",
                                        Toast.LENGTH_SHORT).show();
                            }

                            // ...
                        }
                    });
        }
    });
}

@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    //FirebaseUser currentUser = mAuth.getCurrentUser();
}

}


来源: stackexchange

问:
Saving images with Sequelize
I'm creating a node app using Sequelize as my ORM over Postgres. But the Sequelize docs are missing any mention of how to do datablob, specifically image, saving. Does anyone know:

How to save an image to the database using sequelize, for example from a form. I seems like I need to convert the image to binary data somehow from what I can tell.

How to create seeds with images so that I can test before my app goes live.

Here is my migration file for an example model

```<code>export default {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      firstName: {
        allowNull: false,
        type: Sequelize.STRING,
      },
      lastName: {
        type: Sequelize.STRING,
      },
      photo: { <--------------------------- Image
        type: Sequelize.BLOB,
      },
      email: {
        type: Sequelize.STRING,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  },
};
</code>```

As well as a small seed file

```<code>export default {
  up: (queryInterface, Sequelize) => {
    /*
      Add altering commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.bulkInsert('Persons', [{
        name: 'John Doe',
        isBetaMember: false
      }], {});
    */
    return queryInterface.bulkInsert('Users', [
      {
        firstName: 'Ricky',
        lastName: 'Sparks',
        // photo: <---------- what should I fill in here to seed with a photo file?
        email: 'email@gmail.com',
        createdAt: Sequelize.fn('NOW'),
        updatedAt: Sequelize.fn('NOW'),
      },
    ]);
  },

  down: (queryInterface, Sequelize) => {
    /*
      Add reverting commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.bulkDelete('Persons', null, {});
    */

    return queryInterface.bulkDelete('Users', null, {});
  },
};
</code>```

答:
You can try Sequelize-file , let it handle the file storage,association with models and reading back from blob. Other than that you can use the buffer,stream in the request object of the framework you are using usually the modules expose an buffer or stream or whatever.

the flow usually goes as below.

when submitting

submit form -> http request object -> read buffer -> store to blob

when responding

read from blob -> to buffer -> build the http response.

About testing you can either create some files manually along with an json file of what are the correct values width/height/image type/etc and use those to read and submit or mock files somehow.

I would personally try to avoid storing files into database as you see its even in theory difficult and not easy to test etc. Instead you can store the files in the filesystem with an encoded filename, store information in database, test existence etc. way easier than doing all that unless its necessary.

ContentLicense: CC BY-SA 3.0

Title: Saving images with Sequelize

Body:
I'm creating a node app using Sequelize as my ORM over Postgres. But the Sequelize docs are missing any mention of how to do datablob, specifically image, saving. Does anyone know:

How to save an image to the database using sequelize, for example from a form. I seems like I need to convert the image to binary data somehow from what I can tell.

How to create seeds with images so that I can test before my app goes live.

Here is my migration file for an example model

export default {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      firstName: {
        allowNull: false,
        type: Sequelize.STRING,
      },
      lastName: {
        type: Sequelize.STRING,
      },
      photo: { <--------------------------- Image
        type: Sequelize.BLOB,
      },
      email: {
        type: Sequelize.STRING,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  },
};

As well as a small seed file

export default {
  up: (queryInterface, Sequelize) => {
    /*
      Add altering commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.bulkInsert('Persons', [{
        name: 'John Doe',
        isBetaMember: false
      }], {});
    */
    return queryInterface.bulkInsert('Users', [
      {
        firstName: 'Ricky',
        lastName: 'Sparks',
        // photo: <---------- what should I fill in here to seed with a photo file?
        email: 'email@gmail.com',
        createdAt: Sequelize.fn('NOW'),
        updatedAt: Sequelize.fn('NOW'),
      },
    ]);
  },

  down: (queryInterface, Sequelize) => {
    /*
      Add reverting commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.bulkDelete('Persons', null, {});
    */

    return queryInterface.bulkDelete('Users', null, {});
  },
};


问:
How does V8 handle objects in "large object space"
I've read in V8 wiki that there's large object space in heap which is not moved by GC.

Large-object-space: This space contains objects which are larger than the size limits of other spaces. Each object gets its own mmap'd region of memory. Large objects are never moved by the garbage collector.

Then how does V8 handle that objects? So if I have object like this

```<code>function Point() {
  this.a = new Array(99999999).join("aaaaaaaaaa");
  this.b = new Array(99999999).join("aaaaaaaaaa");
  this.c = new Array(99999999).join("aaaaaaaaaa");
}
var a = new Point();
</code>```

it will be moved to large object space and never cleaned by GC?

答: (V8 developer here.) Bergi's comment is correct. Large objects are not moved to large object space, they are created in large object space. As long as they are alive, they are not moved. But they are garbage collected like any other object: when the GC detects that they are no longer live, the memory will be freed. In general, freeing dead objects does not involve moving them.

Body:
I've read in V8 wiki that there's large object space in heap which is not moved by GC.

Large-object-space: This space contains objects which are larger than the size limits of other spaces. Each object gets its own mmap'd region of memory. Large objects are never moved by the garbage collector.

Then how does V8 handle that objects? So if I have object like this

function Point() {
  this.a = new Array(99999999).join("aaaaaaaaaa");
  this.b = new Array(99999999).join("aaaaaaaaaa");
  this.c = new Array(99999999).join("aaaaaaaaaa");
}
var a = new Point();

it will be moved to large object space and never cleaned by GC?


问:
Erlang pattern matching performance
new to Erlang.  I am about to start writing some code.  The solution I have in mind can go one of two ways.  I can do a bunch of mathematical calculations, or I can code this up largely as pattern matching.  When I say "pattern matching," I DO NOT mean regex or anything like that - I mean pattern matching in clause heads.

Performance is usually not a concern, however in this app it is.  I am not asking you which method would be faster - I'm sure you would say you don't know (depends on many factors).  What I am asking is the general performance of Erlang pattern matching in clause heads.  In other words, in Prolog, the engine is optimized to do this sort of thing, so all other things being equal, you are "encouraged" to design a solution that takes advantage of pattern matching and unification in clause heads.

Is the same true of Erlang, i.e. is Erlang optimized for pattern matching in clause heads, similar to Prolog?  Rather than ask the question here, I actually tried to profile this in Erlang, and wrote a toy program to do pattern matching of clause heads a couple million times vs. summing a list a couple million times.  But the system would crash if set to do for "couple million times."  But set to any less than a couple million, the results would come back too fast for me to know anything about performance.

Thanks for any insights.

答:
In general, pattern matching in functional languages are as fast or faster than in Prolog. I would expect Erlang to perform inside a factor of 2 compared to Prolog, faster or slower. Since a functional program is almost nothing but pattern matching it is one of those areas you optimize a lot.

The internals usually have a pattern match compiler which turns an advanced pattern match into a simpler series of checks with the goal to minimize the number of checks.

Ok, the first gotcha: "Anything introduced in the shell is interpreted". So we compile modules instead:

```<code>-module(z).

-compile(export_all).

%% This pattern is highly uninteresting because it only matches
%% on a single value. Any decent system can do this quickly.
cl(0) -> 0;
cl(1) -> 0;
cl(2) -> 0;
cl(3) -> 0;
cl(4) -> 0;
cl(5) -> 0;
cl(6) -> 0;
cl(7) -> 0;
cl(8) -> 0;
cl(9) -> 0.

mcl(L) ->
    [cl(E) || E <- L].
</code>```

This gives us a runner of your example.

```<code>cl2(a, 0) -> a0;
cl2(a, 1) -> a1;
cl2(a, 2) -> a2;
cl2(b, 0) -> b0;
cl2(b, 1) -> b1;
cl2(b, 2) -> b2;
cl2(c, 0) -> c0;
cl2(c, 1) -> c0;
cl2(c, 2) -> c0.

mcl2(L) ->
    [cl2(A, V) || {A, V} <- L].
</code>```

A runner for a more interesting example. Here, we can exploit skips in the pattern. If (a, 0) fails to match on the a we know we can skip to the case (b, 0) straight away because the negative match information can be propagated as information in the system. The pattern match compiler usually makes this optimization.

```<code>test1() ->
    L1 = [X rem 10 || X <- lists:seq(1, 2000000)],
    %% A Core 2 Duo 2.4Ghz P8600 eats this in 132984 microseconds without HiPE
    %% c(z).
    %% With HiPE it is 91195 or in 0.6857591890753775 of the time the non-HiPE variant use
    %% c(z, [native, {hipe, [o3]}]).
    timer:tc(z, mcl, [L1]).
</code>```

You must run this example yourself and evaluate if you think it is fast enough for your use case. Note that some time is also spent in the mapping code and quite a lot of time must be spent to pull data from the main memory through the CPU caches and onto the CPU.

```<code>test2() ->
    random:seed(erlang:now()),
    L2 = [{case random:uniform(3) of
                   1 -> a;
                   2 -> b;
                   3 -> c
                   end, V rem 3} || V <- lists:seq(1, 2000000)],
    %% With HiPE this is 220937
    %% Without HiPE this is 296980
    timer:tc(z, mcl2, [L2]).
</code>```

Naturally this example is slower, as we need to match more data before we have a hit. But it is a more interesting case because it gives some indication of the real speed of the match compiler.

Parallel versions were tried, but they are about 10 times slower in this case since the overhead of creating 2 million worker processes far dominates the actual processing :)

ContentLicense: CC BY-SA 2.5

Title: Erlang pattern matching performance

Body:
In general, pattern matching in functional languages are as fast or faster than in Prolog. I would expect Erlang to perform inside a factor of 2 compared to Prolog, faster or slower. Since a functional program is almost nothing but pattern matching it is one of those areas you optimize a lot.

The internals usually have a pattern match compiler which turns an advanced pattern match into a simpler series of checks with the goal to minimize the number of checks.

Ok, the first gotcha: "Anything introduced in the shell is interpreted". So we compile modules instead:

-module(z).

-compile(export_all).

%% This pattern is highly uninteresting because it only matches
%% on a single value. Any decent system can do this quickly.
cl(0) -> 0;
cl(1) -> 0;
cl(2) -> 0;
cl(3) -> 0;
cl(4) -> 0;
cl(5) -> 0;
cl(6) -> 0;
cl(7) -> 0;
cl(8) -> 0;
cl(9) -> 0.

mcl(L) ->
    [cl(E) || E <- L].

This gives us a runner of your example.

cl2(a, 0) -> a0;
cl2(a, 1) -> a1;
cl2(a, 2) -> a2;
cl2(b, 0) -> b0;
cl2(b, 1) -> b1;
cl2(b, 2) -> b2;
cl2(c, 0) -> c0;
cl2(c, 1) -> c0;
cl2(c, 2) -> c0.

mcl2(L) ->
    [cl2(A, V) || {A, V} <- L].

A runner for a more interesting example. Here, we can exploit skips in the pattern. If (a, 0) fails to match on the a we know we can skip to the case (b, 0) straight away because the negative match information can be propagated as information in the system. The pattern match compiler usually makes this optimization.

test1() ->
    L1 = [X rem 10 || X <- lists:seq(1, 2000000)],
    %% A Core 2 Duo 2.4Ghz P8600 eats this in 132984 microseconds without HiPE
    %% c(z).
    %% With HiPE it is 91195 or in 0.6857591890753775 of the time the non-HiPE variant use
    %% c(z, [native, {hipe, [o3]}]).
    timer:tc(z, mcl, [L1]).

You must run this example yourself and evaluate if you think it is fast enough for your use case. Note that some time is also spent in the mapping code and quite a lot of time must be spent to pull data from the main memory through the CPU caches and onto the CPU.

test2() ->
    random:seed(erlang:now()),
    L2 = [{case random:uniform(3) of
                   1 -> a;
                   2 -> b;
                   3 -> c
                   end, V rem 3} || V <- lists:seq(1, 2000000)],
    %% With HiPE this is 220937
    %% Without HiPE this is 296980
    timer:tc(z, mcl2, [L2]).

Naturally this example is slower, as we need to match more data before we have a hit. But it is a more interesting case because it gives some indication of the real speed of the match compiler.

Parallel versions were tried, but they are about 10 times slower in this case since the overhead of creating 2 million worker processes far dominates the actual processing :)


问:
Some Output Lost in Command Passed to SSH
I'm trying to use an ssh command to ssh to a server and run theuseradd command I passed to it. It seems like its running ok for the most part (no errors produced) but the hashed password in the /etc/shadow file is missing the salt (I believe that's the portion that's missing.).

I'm not sure if the quoting that is incorrect or not. But running this command manually on the server works fine, so I'm assuming its the expansion that's messed up.?

The command below is running inside a Bash script...

Command:

```<code>ssh user@$host "useradd -d /usr/local/nagios -p $(perl -e 'print crypt("mypassword", "\$6\$salt");') -g nagios nagios && chown -R nagios:nagios /usr/local/nagios"
</code>```

*When I escape the double quotes inside the perl one-liner, I get the error:

Can't find string terminator '"' anywhere before EOF at -e line 1.

Usage: useradd [options] LOGIN

Any idea what I'm doing wrong here?

答:
Instead of enclosing the entire command in double-quotes and making sure to correctly escape everything in it, it will be more robust to use single-quotes, and handle embedded single-quotes as necessary.
In fact there are no embedded single-quotes to handle,
only the embedded literal $ in the $6$salt.

```<code>ssh "user@$host" 'useradd -d /usr/local/nagios -p $(perl -e "print crypt(q{mypassword}, q{\$6\$salt});") -g nagios nagios && chown -R nagios:nagios /usr/local/nagios'
</code>```

Body:
I'm trying to use an ssh command to ssh to a server and run theuseradd command I passed to it. It seems like its running ok for the most part (no errors produced) but the hashed password in the /etc/shadow file is missing the salt (I believe that's the portion that's missing.).

I'm not sure if the quoting that is incorrect or not. But running this command manually on the server works fine, so I'm assuming its the expansion that's messed up.?

The command below is running inside a Bash script...

Command:

ssh user@$host "useradd -d /usr/local/nagios -p $(perl -e 'print crypt("mypassword", "\$6\$salt");') -g nagios nagios && chown -R nagios:nagios /usr/local/nagios"

*When I escape the double quotes inside the perl one-liner, I get the error:

Can't find string terminator '"' anywhere before EOF at -e line 1.

Usage: useradd [options] LOGIN

Any idea what I'm doing wrong here?

Body:
Instead of enclosing the entire command in double-quotes and making sure to correctly escape everything in it, it will be more robust to use single-quotes, and handle embedded single-quotes as necessary.
In fact there are no embedded single-quotes to handle,
only the embedded literal $ in the $6$salt.

ssh "user@$host" 'useradd -d /usr/local/nagios -p $(perl -e "print crypt(q{mypassword}, q{\$6\$salt});") -g nagios nagios && chown -R nagios:nagios /usr/local/nagios'


问:
What made i = i++ + 1; legal in C++17?
Before you start yelling undefined behaviour, this is explicitly listed in N4659 (C++17)

```<code>  i = i++ + 1;        // the value of i is incremented
</code>```

Yet in N3337 (C++11)

```<code>  i = i++ + 1;        // the behavior is undefined
</code>```

What changed?

From what I can gather, from [N4659 basic.exec]

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a memory location is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent, the behavior is undefined.

Where value is defined at [N4659 basic.type]

For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values

From [N3337 basic.exec]

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

Likewise, value is defined at [N3337 basic.type]

For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values.

They are identical except mention of concurrency which doesn't matter, and with the usage of memory location instead of scalar object, where

Arithmetic types, enumeration types, pointer types, pointer to member types, std::nullptr_t, and cv-qualified versions of these types are collectively called scalar types.

Which doesn't affect the example.

From [N4659 expr.ass]

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.

From [N3337 expr.ass]

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

The only difference being the last sentence being absent in N3337.

The last sentence however, shouldn't have any importance as the left operand i is neither "another side effect" nor "using the value of the same scalar object" as the id-expression is a lvalue.

答:
You identified the new sentence

The right operand is sequenced before the left operand.

and you correctly identified that the evaluation of the left operand as an lvalue is irrelevant. However, sequenced before is specified to be a transitive relation. The complete right operand (including the post-increment) is therefore also sequenced before the assignment. In C++11, only the value computation of the right operand was sequenced before the assignment.

Title: What made i = i++ + 1; legal in C++17?

Body:
Before you start yelling undefined behaviour, this is explicitly listed in N4659 (C++17)

  i = i++ + 1;        // the value of i is incremented

Yet in N3337 (C++11)

  i = i++ + 1;        // the behavior is undefined

What changed?

From what I can gather, from [N4659 basic.exec]

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a memory location is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent, the behavior is undefined.

Where value is defined at [N4659 basic.type]

For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values

From [N3337 basic.exec]

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

Likewise, value is defined at [N3337 basic.type]

For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values.

They are identical except mention of concurrency which doesn't matter, and with the usage of memory location instead of scalar object, where

Arithmetic types, enumeration types, pointer types, pointer to member types, std::nullptr_t, and cv-qualified versions of these types are collectively called scalar types.

Which doesn't affect the example.

From [N4659 expr.ass]

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.

From [N3337 expr.ass]

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

The only difference being the last sentence being absent in N3337.

The last sentence however, shouldn't have any importance as the left operand i is neither "another side effect" nor "using the value of the same scalar object" as the id-expression is a lvalue.


问:
Compile with another version of libc
I try to cross-compile my c++ program to an armv5. Just by cross-compiling for armv5, i run into the following error:
GLIBC_2.17 not found (required by libstdc++, libdbus, libsystemd and liblzma)
I found out, that the current version of libc at my target platform is 15.

1)Is there a safe way to update it? I have no Internet connection at the target and can only connect per Telnet. The problem is, if the update fails, I have no access to just flash a new OS at the device and it is broken for 99% i guess ^^.

2)If "no, not really" to (1), is it possible to compile against a libc15 having a newer one running or is there any way to downgrade to 15? (creating a VM for compiling so I do not care if anything fails)
What do i have to specify to compile against another libc version?, didn't find the right flat/parameter there yet...

Thankful for any tips or ideas, having this problem for a while now and I am just too new to C++ cross-compiling to find any solution yet.
Best regards,

答:
Ok, for everyone with the same error, here my solution:
The LD_LIBRARY_PATH/rpath thing is working keeping in mind that the path from ld-linux.so is hard coded. So its either good to have all libs in the folder specified by LD_LIBRARY_PATH or other dependency errors might occur.
The way with downgrading the cross-compiling toolchain is working as well and fixed the whole problem at the end (I ran into an "kernel too old error" with the LD_LIBRARY_PATH solution) but is a lot more tricky, especially for older kernels. Here the specified CXX for the solution:

CXX:= arm-linux-gnueabi-g++

CXXFLAGS:= -march=armv5 -msoft-float -mfloat-abi=soft -O3 \
    -pipe \
        -DPCAP_CREATE \
    -std=c++1y -Wmissing-include-dirs \
        -D_GLIBCXX_USE_NANOSLEEP \
        -g \
        -fno-deduce-init-list

So I could not make it to cross compile with C++11 or later and i doubt that works for an Armv5 with libc15

Best regards

Title: Compile with another version of libc


问:
What is happening when calling an enum/enum class with parentheses in C++?
This is maybe a bit weird question, but I really don't know how to phrase it better than this.

I just discovered that I can do the following:

```<code>#include <iostream>

enum class Colour  // also works with plain old enum
{
    Red = 1,
    Green,
    Blue,
    Yellow,
    Black,
    White
};

int main()
{
    Colour c = Colour(15);  // this is the line I don't quite understand

    std::cout << static_cast<int>(c) << std::endl;  // this returns 15

    return 0;
}
</code>```

So now I have integer value 15 in a variable of the type Colour.

What exactly is happening here? Is that some kind of enum "constructor" at work? As far as I know, integer value 15 is not put into enumeration, it is stored just in variable c. Why would something like that be useful, in the first place - to create a value that doesn't exist in enum?

答: What's happening here is that strongly-typed enums in C++11 are still capable of holding out-of-range values if you explicitly cast or default initialize them.  In your example Colour c = Colour(15); is perfectly valid even though Colour only has meaningful values for 1-6.

Body:
This is maybe a bit weird question, but I really don't know how to phrase it better than this.

I just discovered that I can do the following:

#include <iostream>

enum class Colour  // also works with plain old enum
{
    Red = 1,
    Green,
    Blue,
    Yellow,
    Black,
    White
};

int main()
{
    Colour c = Colour(15);  // this is the line I don't quite understand

    std::cout << static_cast<int>(c) << std::endl;  // this returns 15

    return 0;
}

So now I have integer value 15 in a variable of the type Colour.

What exactly is happening here? Is that some kind of enum "constructor" at work? As far as I know, integer value 15 is not put into enumeration, it is stored just in variable c. Why would something like that be useful, in the first place - to create a value that doesn't exist in enum?


问:
Cannot resolve symbol NameValuePair
In my project I got an error:

Error retrieving parent for item: No resource found that matches the
  given name 'android:TextAppearance.Material.Widget.Button.Inverse'.

Then I tried to fix it use this:

```<code>compileSdkVersion 23
</code>```

But then I got error:

cannot resolve symbol NameValuePair android

How to fix this error?

答:
Nested class would work:</p>

```<code>private class NameValuePair {
        private String mName;
        private String mValue;

        public NameValuePair(String name, String value) {
            mName = name;
            mValue = value;
        }

        public String getName() {
            return mName;
        }

        public String getValue() {
            return mValue;
        }
    };
</code>```

Title: Cannot resolve symbol NameValuePair

Body:
In my project I got an error:

Error retrieving parent for item: No resource found that matches the
  given name 'android:TextAppearance.Material.Widget.Button.Inverse'.

Then I tried to fix it use this:

compileSdkVersion 23

But then I got error:

cannot resolve symbol NameValuePair android

How to fix this error?

Body:
Nested class would work:

private class NameValuePair {
        private String mName;
        private String mValue;

        public NameValuePair(String name, String value) {
            mName = name;
            mValue = value;
        }

        public String getName() {
            return mName;
        }

        public String getValue() {
            return mValue;
        }
    };


问:
javascript auto refresh using setInterval not working
I have some custom javascript code used by sharepoint.  I need to make part of the page refresh automatically after it loads.  I have tried using setInterval.  Here are my functions:</p>

```<code>define([
  'jquery',
  'knockout',
  'text!./home-page-census.html',
  'q',
  'underscore',
  'census',
  'moment',
  'sp_core',
  'bootstrap',
  '!domReady'
], function ($, ko, htmlString, Q, _, census, moment) {
    var baseUrl = _spPageContextInfo.siteAbsoluteUrl;

    function buildRequestUrl() {
        var requestUrl = baseUrl + "/_api/web/lists/GetByTitle('Census')/items?";
        var oDataSelect = "$select=Title,CensusBranch,BedAvailabilityPercentage,Modified,StatusBarColor,DisplayText,Tooltip";

        return requestUrl += oDataSelect;
    }

    function getUpdatedCensus() {
        return Q.Promise(function (resolve, reject, notify) {
            requestUrl = buildRequestUrl();
            census.getCensus(requestUrl).then(onFulfilled, onRejected);
            //setInterval(census.getCensus(requestUrl).then(onFulfilled, onRejected), 3000);

            function onFulfilled(censusResult) {
                resolve(censusResult);
            }

            function onRejected(reason) {
                reject(reason);
            }
        });
    }

    function initViewModel(viewModel) {
        getUpdatedCensus().then(onFulfilled, onRejected);

        function onFulfilled(result) {
            viewModel.censusByBranch(result);
            viewModel.isInitializing(false);
        }

        function onRejected(reason) {
            console.log(reason.message);
            console.log(reason.stack);
            viewModel.isInitializing(false);
        }
    }

    function HomePageCensusViewModel(params) {
        var self = this;
        self.isInitializing = ko.observable(true);
        self.censusByBranch = ko.observable();

        initViewModel(self);
    }

    ko.bindingHandlers.censusLastUpdatedTime = {
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var value = valueAccessor();
            var lastUpdated = ko.unwrap(value);

            $(element).text(lastUpdated.format('M[/]DD [@] h[:]mmA'));
        }
    }

    return {
        viewModel: HomePageCensusViewModel,
        template: htmlString
    };
});
</code>```

答:
The first argument to setTimeout needs to be the function that will be called. As written...

```<code>setInterval(census.getCensus(requestUrl).then(onFulfilled, onRejected), 3000);
</code>```

... census.getCensus(...) is being called immediately, and the promise returned is being passed to setTimeout.

Wrapping it in a function as such should work...

```<code>setInterval(function() { census.getCensus(requestUrl).then(onFulfilled, onRejected) }, 3000);
</code>```

It's worth mentioning also that using the rejection handler in then is considered a bad practice; it is much better to use .then(onSuccess).catch(onRejected).

Body:
I have some custom javascript code used by sharepoint.  I need to make part of the page refresh automatically after it loads.  I have tried using setInterval.  Here are my functions:

define([
  'jquery',
  'knockout',
  'text!./home-page-census.html',
  'q',
  'underscore',
  'census',
  'moment',
  'sp_core',
  'bootstrap',
  '!domReady'
], function ($, ko, htmlString, Q, _, census, moment) {
    var baseUrl = _spPageContextInfo.siteAbsoluteUrl;

    function buildRequestUrl() {
        var requestUrl = baseUrl + "/_api/web/lists/GetByTitle('Census')/items?";
        var oDataSelect = "$select=Title,CensusBranch,BedAvailabilityPercentage,Modified,StatusBarColor,DisplayText,Tooltip";

        return requestUrl += oDataSelect;
    }

    function getUpdatedCensus() {
        return Q.Promise(function (resolve, reject, notify) {
            requestUrl = buildRequestUrl();
            census.getCensus(requestUrl).then(onFulfilled, onRejected);
            //setInterval(census.getCensus(requestUrl).then(onFulfilled, onRejected), 3000);

            function onFulfilled(censusResult) {
                resolve(censusResult);
            }

            function onRejected(reason) {
                reject(reason);
            }
        });
    }

    function initViewModel(viewModel) {
        getUpdatedCensus().then(onFulfilled, onRejected);

        function onFulfilled(result) {
            viewModel.censusByBranch(result);
            viewModel.isInitializing(false);
        }

        function onRejected(reason) {
            console.log(reason.message);
            console.log(reason.stack);
            viewModel.isInitializing(false);
        }
    }

    function HomePageCensusViewModel(params) {
        var self = this;
        self.isInitializing = ko.observable(true);
        self.censusByBranch = ko.observable();

        initViewModel(self);
    }

    ko.bindingHandlers.censusLastUpdatedTime = {
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var value = valueAccessor();
            var lastUpdated = ko.unwrap(value);

            $(element).text(lastUpdated.format('M[/]DD [@] h[:]mmA'));
        }
    }

    return {
        viewModel: HomePageCensusViewModel,
        template: htmlString
    };
});

Body:
The first argument to setTimeout needs to be the function that will be called. As written...

setInterval(census.getCensus(requestUrl).then(onFulfilled, onRejected), 3000);

... census.getCensus(...) is being called immediately, and the promise returned is being passed to setTimeout.

Wrapping it in a function as such should work...

setInterval(function() { census.getCensus(requestUrl).then(onFulfilled, onRejected) }, 3000);

It's worth mentioning also that using the rejection handler in then is considered a bad practice; it is much better to use .then(onSuccess).catch(onRejected).


问:
Polygot include file for nasm/yasm and C
I have a bunch of magic numbers that I would like to include in both a C program and an assembly file to be compiled by nasm or yasm.

In plain C the file would look something a series of defines, like:

```<code>#define BLESS   55378008
#define ANSWER        42
...
</code>```

In nasm or yasm, the same include could be implemented as:

```<code>%define BLESS   55378008
%define ANSWER        42
...
</code>```

The only difference is that leading character before the define: # for C and % for nasm.

Is there any way to write a polygot include that allows me to include it in both C and nasm and only list the constants once?

Yes, I'm aware that I could just use sed or whatever to generate one file from the other.

答:
NASM by itself has no way to include C header files in assembly code. This has been brought up in the NASM forum through the years. You will need an external tool to parse the C header files into something usable with NASM assembly syntax.

One such 3rd party contribution that is suppose to be compatible with NASM is h2incn. I haven't tested it thoroughly enough so can't say it is stable or usable enough for all use cases.

The alternative is to pre-process the files with other tools like m4, cpp, or even translating with sed

Body:
I have a bunch of magic numbers that I would like to include in both a C program and an assembly file to be compiled by nasm or yasm.

In plain C the file would look something a series of defines, like:

#define BLESS   55378008
#define ANSWER        42
...

In nasm or yasm, the same include could be implemented as:

%define BLESS   55378008
%define ANSWER        42
...

The only difference is that leading character before the define: # for C and % for nasm.

Is there any way to write a polygot include that allows me to include it in both C and nasm and only list the constants once?

Yes, I'm aware that I could just use sed or whatever to generate one file from the other.


问:
Is my data safe with encryption?
In storing passwords in php mysql, can i assume the passwords to be safe if i were to run md5 algorithm again and again and with combination of text replacement and rotation? </p>

答:
No, MD5 is not secure to use to create a password verifier.

With PHP use password_hash and password_verify, the pair are secure and easy to use.

When saving a password verifier just using a hash function is not sufficient and just adding a salt does little to improve the security. Instead use a function such as PBKDF2, Rfc2898DeriveBytes, Argon2, password_hash, Bcrypt or similar functions with about a 100ms duration. Make the attacker spend substantial of time finding passwords by brute force.

Title: Is my data safe with encryption?


问:
Accessing state of another component in ReactJS?
I have 2 components, one of them has a state, which I want to access from the other component. </p>

```<code>class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {test:"Hello World"};
  }
  render() {
    return(<Bar {...this.state} />);
  }
}

class Bar extends React.Component {
  render() {
    return(<h1>{this.props.test}</h1>);
  }
}

ReactDOM.Render(
  <Bar />,
  document.getElementById("root")
);
</code>```

<p>I googled around a bit, but since I'm new to JS and React I think I misunderstood something, because this code doesn't work. From my understanding it should display "Hello World", but instead nothing happens. </p>

答:
This will work. Render Foo instead of Bar

```<code>ReactDOM.Render(
  <Foo />,
  document.getElementById("root")
);
</code>```

Also use ReactDOM.render insetad of ReactDom.Render (lower case for render)

Here a working version: https://codepen.io/anon/pen/OOemzW?editors=1010

Body:
I have 2 components, one of them has a state, which I want to access from the other component.

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {test:"Hello World"};
  }
  render() {
    return(<Bar {...this.state} />);
  }
}

class Bar extends React.Component {
  render() {
    return(
{this.props.test}
);
  }
}

ReactDOM.Render(
  <Bar />,
  document.getElementById("root")
);

I googled around a bit, but since I'm new to JS and React I think I misunderstood something, because this code doesn't work. From my understanding it should display "Hello World", but instead nothing happens.

Body:
This will work. Render Foo instead of Bar

ReactDOM.Render(
  <Foo />,
  document.getElementById("root")
);

Also use ReactDOM.render insetad of ReactDom.Render (lower case for render)

Here a working version: https://codepen.io/anon/pen/OOemzW?editors=1010


问:
Infinite scroll duplicates rows
I'm using ngInfiniteScroll dependency for my angularjs project.

Whenever I scroll up and down again, it duplicates the rows.

HTML

```<code><table infinite-scroll="loadMore()" ng-controller="LastBookingsCtrl">
</code>```

JavaScript

```<code>$scope.loadMore = function() {
$http.get("last.php?start=" + $scope.currentLoadIndex)
    .then(function (res) {
        if (res.data.length > 0) {
            var count = 0;
                for (var i = 0; i < res.data.length; i++) {
                    $scope.lastBookings.push(res.data[i]);
                    count++;
                }
            $scope.currentLoadIndex += count;
        }
    });
};
</code>```

PHP

```<code>$start = $_GET['start'];
$query = "SELECT * FROM `performs` ORDER BY id DESC LIMIT ".$start.", 20";
</code>```

答:
I believe you are getting the same result each time because you $scope.currentLoadIndex is not updating correctly from the then(). Try setting the next index to the length of the current list aka:

$http.get("last.php?start=" + $scope.lastBookings.length)

ContentLicense: CC BY-SA 4.0

Title: Infinite scroll duplicates rows

Body:
I'm using ngInfiniteScroll dependency for my angularjs project.

Whenever I scroll up and down again, it duplicates the rows.

HTML

JavaScript

$scope.loadMore = function() {
$http.get("last.php?start=" + $scope.currentLoadIndex)
    .then(function (res) {
        if (res.data.length > 0) {
            var count = 0;
                for (var i = 0; i < res.data.length; i++) {
                    $scope.lastBookings.push(res.data[i]);
                    count++;
                }
            $scope.currentLoadIndex += count;
        }
    });
};

PHP

$start = $_GET['start'];
$query = "SELECT * FROM `performs` ORDER BY id DESC LIMIT ".$start.", 20";


问:
RxJS & Angular HttpClient: How to transform value asynchronously?
I want to apply an asynchronous transformation function on the value emitted by an observable.

```<code>@Injectable
export class ApiService{
    constructor(private http: HttpClient){}

    getSomething(url): Observable<any>{
        return this.http.get(url);
    }
}
</code>```

In the code above, I want to apply a transformation function myFunc, which returns a promise, on the value emitted by this.http.get(url).

Normally I would use the map operator of RxJS, but since the transformation function returns a promise, I could not find a way to handle it.

For example, let my function be:

```<code>function myFunc(value){
    return new Promise((resolve, reject) => {
        // modify the value async

        resolve(modifiedValue);

        // ...
    });
}
</code>```

Is there an appropriate way to handle this task? I think the following is not suitable, am I right?

return this.http.get(url).map(myFunc);

Any help will be much appreciated.

Note: I'm using RxJS 5.5.2

答:
Use the mergeMap operator to take in the response value, perform some modification asynchronously via another Observable operation, and then return the modified value. This operator will merge the values emitted by HttpClient and your modifier Observable and return a single Observable that emits the mutated values.

EDIT: Including the Observable.fromPromise bit from @bygrace's comment for a more complete answer.

i.e.

EDIT: For RxJs v5.5+

```<code>import { pipe } from 'rxjs/util/pipe';
import { mergeMap } from 'rxjs/operators';

    @Injectable
    export class ApiService{
        constructor(private http: HttpClient){}

        getSomething(url): Observable<any>{
            return this.http.get(url).pipe(
                                        mergeMap(myFunc)
                                      );
        }

        private myFunc(x): Observable<any> {
            // do some asynchronous modification that returns an Observable
            return Observable.fromPromise(x);
        }
    }
</code>```

Pre RxJs v5.5

```<code>@Injectable
export class ApiService{
    constructor(private http: HttpClient){}

    getSomething(url): Observable<any>{
        return this.http.get(url)
               .mergeMap(data => {
                   // do some asynchronous modification that returns an Observable
                   return Observable.fromPromise(data);
                });
    }
}
</code>```

See: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-mergeMap

Body:
I want to apply an asynchronous transformation function on the value emitted by an observable.

@Injectable
export class ApiService{
    constructor(private http: HttpClient){}

    getSomething(url): Observable<any>{
        return this.http.get(url);
    }
}

In the code above, I want to apply a transformation function myFunc, which returns a promise, on the value emitted by this.http.get(url).

Normally I would use the map operator of RxJS, but since the transformation function returns a promise, I could not find a way to handle it.

For example, let my function be:

function myFunc(value){
    return new Promise((resolve, reject) => {
        // modify the value async

        resolve(modifiedValue);

        // ...
    });
}

Is there an appropriate way to handle this task? I think the following is not suitable, am I right?

return this.http.get(url).map(myFunc);

Any help will be much appreciated.

Note: I'm using RxJS 5.5.2

Body:
Use the mergeMap operator to take in the response value, perform some modification asynchronously via another Observable operation, and then return the modified value. This operator will merge the values emitted by HttpClient and your modifier Observable and return a single Observable that emits the mutated values.

EDIT: Including the Observable.fromPromise bit from @bygrace's comment for a more complete answer.

i.e.

EDIT: For RxJs v5.5+

import { pipe } from 'rxjs/util/pipe';
import { mergeMap } from 'rxjs/operators';

    @Injectable
    export class ApiService{
        constructor(private http: HttpClient){}

        getSomething(url): Observable<any>{
            return this.http.get(url).pipe(
                                        mergeMap(myFunc)
                                      );
        }

        private myFunc(x): Observable<any> {
            // do some asynchronous modification that returns an Observable
            return Observable.fromPromise(x);
        }
    }

Pre RxJs v5.5

@Injectable
export class ApiService{
    constructor(private http: HttpClient){}

    getSomething(url): Observable<any>{
        return this.http.get(url)
               .mergeMap(data => {
                   // do some asynchronous modification that returns an Observable
                   return Observable.fromPromise(data);
                });
    }
}

See: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-mergeMap


问:
Android access attribute reference
In the Android resources xml to reference the value of an attribute for a theme you use the question-mark (?) instead of at (@). Such as ListViewCustomStyle below:

```<code> <ListView
     android:id="@+id/MainScreenListView"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     style="?ListViewCustomStyle"/>
</code>```

How can I use the value of the ListViewCustomStyle in code? If I try it the normal way i.e.

```<code>com.myapp.R.attr.ListViewCustomStyle
</code>```

Then the code crashes. Is there a special way to access this since it is a reference to an item and not an actual item?

答:
It might just be crashing because you wrote ListRowCustomStyle there, and ListViewCustomStyle in your xml.

The way I do this is to have the tag style="@style/my_button" for example (with no android: preceding it). Then you can define your style in the values/styles.xml file, e.g.

```<code>    <?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="my_button" parent="@android:style/Widget.Button">
        <item name="android:gravity">center_vertical|center_horizontal</item>
        <item name="android:textColor">#FFFFFFFF</item>
    ...
       </style>
</resources>
</code>```

You can access the style in code by using the id R.style.my_button

Title: Android access attribute reference

Body:
In the Android resources xml to reference the value of an attribute for a theme you use the question-mark (?) instead of at (@). Such as ListViewCustomStyle below:

 <ListView
     android:id="@+id/MainScreenListView"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     style="?ListViewCustomStyle"/>

How can I use the value of the ListViewCustomStyle in code? If I try it the normal way i.e.

com.myapp.R.attr.ListViewCustomStyle

Then the code crashes. Is there a special way to access this since it is a reference to an item and not an actual item?

Body:
It might just be crashing because you wrote ListRowCustomStyle there, and ListViewCustomStyle in your xml.

The way I do this is to have the tag style="@style/my_button" for example (with no android: preceding it). Then you can define your style in the values/styles.xml file, e.g.

    <?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="my_button" parent="@android:style/Widget.Button">
        <item name="android:gravity">center_vertical|center_horizontal</item>
        <item name="android:textColor">#FFFFFFFF</item>
    ...
       </style>
</resources>

You can access the style in code by using the id R.style.my_button


问:
I want to create an adaptive card with buttons for email and call functionality. Whats the possible way for that?
I want to create an adaptive card with buttons for email and call functionality. I cannot find a format for call and email in adaptive cards. Is there a way to combine adaptive cards with hero cards, since hero cards have the cardAction object functionality ? </p>

答:
Adaptive Cards have action elements and selectactions that can be set. You would create a card with your input requirements and then use a submit action to process the input. Note on the text input elements, the format has been set to either email or tel

```<code>{"type":"AdaptiveCard","version":"1.0","id":"c2de1dd7-c916-4196-a914-0694957aff77","minVersion":"1.0","fallbackText":"","speak":"","body":[{"type":"TextBlock","id":"23af4d94-cf3b-480e-8c28-5a7988b8a26b","text":"Email Address","maxLines":1},{"type":"Input.Text","id":"4a47c737-dbf0-42d0-aa9f-10f4f38bd20f","placeholder":"enter your email here","value":"","style":"email","maxLength":250,"isRequired":false},{"type":"TextBlock","id":"b4f3bce9-2464-473f-9129-48a3740aec8b","size":"large","text":"OR","horizontalAlignment":"center","maxLines":1},{"type":"TextBlock","id":"fe2d84aa-79e7-4fdf-91a0-79a9eb264dc1","text":"Call me","maxLines":1},{"type":"Input.Text","id":"d03d538f-7ead-4959-8a8e-7703dbaf1899","placeholder":"What's your number?","value":"","style":"tel","maxLength":250,"isRequired":false}],"actions":[{"type":"Action.Submit","id":"8421a872-2c4f-4fa2-8254-b1d88503cc8a","data":"","title":"Email Me"},{"type":"Action.Submit","id":"2ccf2819-ad38-492a-80f9-7cd5152fea09","data":"","title":"Call Me"}]}
</code>```

Body:
Adaptive Cards have action elements and selectactions that can be set. You would create a card with your input requirements and then use a submit action to process the input. Note on the text input elements, the format has been set to either email or tel

{"type":"AdaptiveCard","version":"1.0","id":"c2de1dd7-c916-4196-a914-0694957aff77","minVersion":"1.0","fallbackText":"","speak":"","body":[{"type":"TextBlock","id":"23af4d94-cf3b-480e-8c28-5a7988b8a26b","text":"Email Address","maxLines":1},{"type":"Input.Text","id":"4a47c737-dbf0-42d0-aa9f-10f4f38bd20f","placeholder":"enter your email here","value":"","style":"email","maxLength":250,"isRequired":false},{"type":"TextBlock","id":"b4f3bce9-2464-473f-9129-48a3740aec8b","size":"large","text":"OR","horizontalAlignment":"center","maxLines":1},{"type":"TextBlock","id":"fe2d84aa-79e7-4fdf-91a0-79a9eb264dc1","text":"Call me","maxLines":1},{"type":"Input.Text","id":"d03d538f-7ead-4959-8a8e-7703dbaf1899","placeholder":"What's your number?","value":"","style":"tel","maxLength":250,"isRequired":false}],"actions":[{"type":"Action.Submit","id":"8421a872-2c4f-4fa2-8254-b1d88503cc8a","data":"","title":"Email Me"},{"type":"Action.Submit","id":"2ccf2819-ad38-492a-80f9-7cd5152fea09","data":"","title":"Call Me"}]}


问:
Load existing db file to memory Python sqlite?
I have an existing sqlite db file, on which I need to make some extensive calculations. Doing the calculations from the file is painfully slow, and as the file is not large (~10 MB), so there should be no problem to load it into memory.

Is there a way in Python to load the existing file into memory in order to speed up the calculations?

答: You could read all the tables into DataFrames with Pandas, though I'm surprised it's slow. sqlite has always been really fast for me. </p>


问:
js get class of calling object in function
I have a structure similar to this:

```<code> class Person {
        greet() {
            console.log(this.constructor.name)
        }
    }

    class User extends Person {
    }

    let user = new User()
    user.greet()
</code>```

Unfortunately it prints window for this.constructor.name instead of User.
Is there some other way to get the actual class Name?

Actual code:

```<code>static MeteorMethod(target: MeteorModel, key: string, descriptor: PropertyDescriptor) {
        let constructor = target.constructor
        let className = target.constructor.name
        let methodName = key
        let method = descriptor.value
        let meteorMethodName = MeteorModelDecorators.generateMethodName(constructor, methodName)
        MeteorModelDecorators.MeteorMethodClasses[className] = target

        if(Meteor.isServer) {
            Meteor.methods({
                [meteorMethodName]: (modelClassName: string, modelProps: object, ...args: any[]) => {
                    let model = new MeteorModelDecorators.MeteorMethodClasses[modelClassName](modelProps)
                    method.apply(model, args)
                }
            })
        }
        else {
            descriptor.value = async function(...args: any[]) {
                // here I expect this to be Book, but I get Window
                return new Promise(function(resolve, reject) {
                    Meteor.call(meteorMethodName, this.constructor.name, this, args, (error: any, result: any) => {
                        if(error) reject(error)
                        resolve(result)
                    })
                })
            }
        }
    }

class MeteorModel {
    @MeteorMethod
    save() {
        console.log('save')
    }
}

class Book extends MeteorModel {
}

let book = new Book()
book.save()
</code>```

答:
Your problem is in this part:

```<code>descriptor.value = async function(...args: any[]) {
            // here I expect this to be Book, but I get Window
            return new Promise(function(resolve, reject) {
                Meteor.call(meteorMethodName, this.constructor.name, this, args, (error: any, result: any) => {
                    if(error) reject(error)
                    resolve(result)
                })
            })
        }
</code>```

It needs to be this:

```<code>descriptor.value = async function(...args: any[]) {
            // With the arrow function, should be Book
            return new Promise((resolve, reject) => {
                Meteor.call(meteorMethodName, this.constructor.name, this, args, (error: any, result: any) => {
                    if(error) reject(error)
                    resolve(result)
                })
            })
        }
</code>```

The function you were passing to the Promise constructor was setting up a new context, by using the arrow function you pick up the this context from the surrounding method.

Body:
I have a structure similar to this:

 class Person {
        greet() {
            console.log(this.constructor.name)
        }
    }

    class User extends Person {
    }

    let user = new User()
    user.greet()

Unfortunately it prints window for this.constructor.name instead of User.
Is there some other way to get the actual class Name?

Actual code:

static MeteorMethod(target: MeteorModel, key: string, descriptor: PropertyDescriptor) {
        let constructor = target.constructor
        let className = target.constructor.name
        let methodName = key
        let method = descriptor.value
        let meteorMethodName = MeteorModelDecorators.generateMethodName(constructor, methodName)
        MeteorModelDecorators.MeteorMethodClasses[className] = target

        if(Meteor.isServer) {
            Meteor.methods({
                [meteorMethodName]: (modelClassName: string, modelProps: object, ...args: any[]) => {
                    let model = new MeteorModelDecorators.MeteorMethodClasses[modelClassName](modelProps)
                    method.apply(model, args)
                }
            })
        }
        else {
            descriptor.value = async function(...args: any[]) {
                // here I expect this to be Book, but I get Window
                return new Promise(function(resolve, reject) {
                    Meteor.call(meteorMethodName, this.constructor.name, this, args, (error: any, result: any) => {
                        if(error) reject(error)
                        resolve(result)
                    })
                })
            }
        }
    }

class MeteorModel {
    @MeteorMethod
    save() {
        console.log('save')
    }
}

class Book extends MeteorModel {
}

let book = new Book()
book.save()

Body:
Your problem is in this part:

descriptor.value = async function(...args: any[]) {
            // here I expect this to be Book, but I get Window
            return new Promise(function(resolve, reject) {
                Meteor.call(meteorMethodName, this.constructor.name, this, args, (error: any, result: any) => {
                    if(error) reject(error)
                    resolve(result)
                })
            })
        }

It needs to be this:

descriptor.value = async function(...args: any[]) {
            // With the arrow function, should be Book
            return new Promise((resolve, reject) => {
                Meteor.call(meteorMethodName, this.constructor.name, this, args, (error: any, result: any) => {
                    if(error) reject(error)
                    resolve(result)
                })
            })
        }

The function you were passing to the Promise constructor was setting up a new context, by using the arrow function you pick up the this context from the surrounding method.


问:
Access the HTML page inside service in AngularJS
I want to access particular HTML page inside a service. Currently, I have made the function inside a controller that can be called from its linked HTML page but I want to access that function from multiple pages. So, I'll want service or factory for it to make it available from anywhere.

In that function, I want the content of particular HTML page but that content is available only when I call the function from that page only.

Here is my function.

```<code>$scope.downloadReport = function(type) {

      var pdf = new jsPDF('p', 'pt', 'a4');
      var source;

      var options = {
         pagesplit: true,
         background: '#ffffff',
         letterRendering: true
      };
      pdf.internal.scaleFactor = 2;

      source = document.getElementsByClassName('complete-report')[0];

      pdf.addHTML(source, options, function () {
        pdf.save('report.pdf');
      });
  };
</code>```

document.getElementsByClassName('complete-report')[0]; It will get data from the HTML page linked with controller.

So, I need service which access the particular HTML page such that I use that function there to get the content of particular HTML page.

答:
You have to make sure that the DOM element which you are trying to access must be loaded in the DOM. Till then you cant do anything.

You can try giving id tag (e.g. elementID)for that perticular dom element and try accessing like below.

```<code>var source = angular.element("#elementID");
</code>```

Body:
I want to access particular HTML page inside a service. Currently, I have made the function inside a controller that can be called from its linked HTML page but I want to access that function from multiple pages. So, I'll want service or factory for it to make it available from anywhere.

In that function, I want the content of particular HTML page but that content is available only when I call the function from that page only.

Here is my function.

$scope.downloadReport = function(type) {

      var pdf = new jsPDF('p', 'pt', 'a4');
      var source;

      var options = {
         pagesplit: true,
         background: '#ffffff',
         letterRendering: true
      };
      pdf.internal.scaleFactor = 2;

      source = document.getElementsByClassName('complete-report')[0];

      pdf.addHTML(source, options, function () {
        pdf.save('report.pdf');
      });
  };

document.getElementsByClassName('complete-report')[0]; It will get data from the HTML page linked with controller.

So, I need service which access the particular HTML page such that I use that function there to get the content of particular HTML page.

Body:
You have to make sure that the DOM element which you are trying to access must be loaded in the DOM. Till then you cant do anything.

You can try giving id tag (e.g. elementID)for that perticular dom element and try accessing like below.

var source = angular.element("#elementID");


问:
Downgrade Visual Studio 2017 15.5 to previous version 15.4.4?
TIFU by upgrading to the latest Visual Studio 15.5 which breaks too many things.

Is it possible to downgrade Visual Studio 2017 from 15.5 to the previous version, 15.4.4 ?

I tried un-installing VS2017 and re-install it, but it goes straight to the latest version.

Any way to do this ?

答:
@Hans should probably take credit for this, but here's the link to properly downgrade: https://www.visualstudio.com/en-us/productinfo/installing-an-earlier-release-of-vs2017

v15.5 also screwed things up for me and I had to uninstall.


问:
Replace random value in string with random value
virus is supposed to be a string of nucleotides, and the function should return a string consisting of the same amount of nucleotides, but one is changed.

```<code>def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus.split
    random.randrange(1, stop=len(virus), step=1) = random.choice(mutations)
</code>```

so for example if the virus is ATCG it should return something like ATCC or GTCG, how can I go about this, I tried making virus into a list, and replacing a random variable in it with a random of my possible mutations list.

So it should probably make a list from the string virus, do a mutation, put the list back into a string and return the string.

答:
You can do something like this:</p>

```<code>import random
def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    r = random.randint(0, len(virus)-1)
    virus = list(virus)
    virus[r] = random.choice(mutations)
    return ''.join(virus)
</code>```

Body:
virus is supposed to be a string of nucleotides, and the function should return a string consisting of the same amount of nucleotides, but one is changed.

def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus.split
    random.randrange(1, stop=len(virus), step=1) = random.choice(mutations)

so for example if the virus is ATCG it should return something like ATCC or GTCG, how can I go about this, I tried making virus into a list, and replacing a random variable in it with a random of my possible mutations list.

So it should probably make a list from the string virus, do a mutation, put the list back into a string and return the string.

Body:
You can do something like this:

import random
def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    r = random.randint(0, len(virus)-1)
    virus = list(virus)
    virus[r] = random.choice(mutations)
    return ''.join(virus)


问:
Can I include dll in exe (in Visual Studio)?

Possible Duplicate:

  .NET windows application, can it be compressed into a single .exe?

To run my App I need AxInterop.WMPLib.dll and Interop.WMPLib.dll that are located in Debug and Release folder. Is there any way to include those dlls into exe so my app is available in one file only?

答:
For example, add x.dll to the project and set its Build Action to Embedded Resource.

To extract:

```<code> string AppPath=Assembly.GetExecutingAssembly().Location;
 Assembly ThisAssembly=Assembly.LoadFrom(AppPath);
 System.IO.Stream fs=ThisAssembly.GetManifestResourceStream("yourproectname.x.dll");
 int ssize=(int)fs.Length;
 byte [] buf=new byte[ssize];
 fs.Read(buf,0,ssize);
 fs.Close();
</code>```

OwnerDisplayName: mark

Body:
For example, add x.dll to the project and set its Build Action to Embedded Resource.

To extract:

 string AppPath=Assembly.GetExecutingAssembly().Location;
 Assembly ThisAssembly=Assembly.LoadFrom(AppPath);
 System.IO.Stream fs=ThisAssembly.GetManifestResourceStream("yourproectname.x.dll");
 int ssize=(int)fs.Length;
 byte [] buf=new byte[ssize];
 fs.Read(buf,0,ssize);
 fs.Close();

OwnerDisplayName: cookre

LastEditorDisplayName: Shy


问:
Trouble Understanding Comparable<T> cast
I just wrote a method that takes two arguments: 1. An array list of any type that extends Number, and 2. a number of the same type. This method should return an array list of all numbers less than the second argument.

My class is called Quiz3FinalQuestion<T extends Comparable>>

My method I wrote looks like this,

```<code>public static <T extends Number> ArrayList<T> lessThan(ArrayList<T> lst, T number) {
        ArrayList<T> arLst = new ArrayList<>();
        for (T obj: lst) {
            if (((Comparable<T>) obj).compareTo(number) < 0)
                arLst.add(obj);
        }
        return arLst;
}
</code>```

It works as expected, but if I didn't have the Java pre-compiler telling me to cast obj to type Comparable, this wouldn't have run. I'm assuming that the number parameter gets cast in the Comparable version of compareTo. So when I add an obj to my arLst, the object should get cast back into type T, right?
Also, are there any simpler ways to compare wrapper class objects of unknown type T?

答:
You can enforce that T also extends Comparable<? super T>:1

```<code>public static <T extends Number & Comparable<? super T>>
ArrayList<T> lessThan(ArrayList<T> lst, T number) {
    ...
}
</code>```

Then you can remove the cast.

1. See e.g. Explanation of generic <T extends Comparable<? super T>> in collection.sort/ comparable code? for why we don't just use Comparable<T>.

Body:
I just wrote a method that takes two arguments: 1. An array list of any type that extends Number, and 2. a number of the same type. This method should return an array list of all numbers less than the second argument.

My class is called Quiz3FinalQuestion<T extends Comparable>>

My method I wrote looks like this,

public static <T extends Number> ArrayList<T> lessThan(ArrayList<T> lst, T number) {
        ArrayList<T> arLst = new ArrayList<>();
        for (T obj: lst) {
            if (((Comparable<T>) obj).compareTo(number) < 0)
                arLst.add(obj);
        }
        return arLst;
}

It works as expected, but if I didn't have the Java pre-compiler telling me to cast obj to type Comparable, this wouldn't have run. I'm assuming that the number parameter gets cast in the Comparable version of compareTo. So when I add an obj to my arLst, the object should get cast back into type T, right?
Also, are there any simpler ways to compare wrapper class objects of unknown type T?

Body:
You can enforce that T also extends Comparable<? super T>:1

public static <T extends Number & Comparable<? super T>>
ArrayList<T> lessThan(ArrayList<T> lst, T number) {
    ...
}

Then you can remove the cast.

1. See e.g. Explanation of generic <T extends Comparable<? super T>> in collection.sort/ comparable code? for why we don't just use Comparable<T>.


问:
aiohttp Websocket client and HTTP server
I'm writing an application that needs to take in events from two sources. Some events will come from a Websocket client connection, and some will come from incoming HTTP requests. Is it possible with aiohttp to have both of these listeners in the same application, or do I need two separate executables?

I currently have a function that takes websocket events, and calls a callback on each event

```<code>async def callback(msg):
    print(msg)

async def websocket():
    session = aiohttp.ClientSession()
    async with session.ws_connect('http://example.org/websocket') as ws:

        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.TEXT:
                await callback(msg.data)
            elif msg.type == aiohttp.WSMsgType.CLOSED:
                break
            elif msg.type == aiohttp.WSMsgType.ERROR:
                break
</code>```

The problem is that this blocks forever, so I don't know how I could integrate this with the aiohttp server. If I do:

```<code>await websocket()
aiohttp.web.run_app(app)
</code>```

then web.run_app is never called. Is there some way to accomplish this? It seems like the ideal case for asyncio, multiple things handling multiple events asynchronously. How do I do it?

答:
I was able to accomplish my goals by using the on_startup handler of my aiohttp app.

```<code>async def callback(msg):
    print(msg)

async def websocket(session):
    async with session.ws_connect('http://example.org/websocket') as ws:
        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.TEXT:
                await callback(msg.data)
            elif msg.type == aiohttp.WSMsgType.CLOSED:
                break
            elif msg.type == aiohttp.WSMsgType.ERROR:
                break

async def init(app):
    session = aiohttp.ClientSession()
    app['websocket_task'] = app.loop.create_task(websocket(session))

app = web.Application()
app.on_startup.append(init)
</code>```

Body:
I'm writing an application that needs to take in events from two sources. Some events will come from a Websocket client connection, and some will come from incoming HTTP requests. Is it possible with aiohttp to have both of these listeners in the same application, or do I need two separate executables?

I currently have a function that takes websocket events, and calls a callback on each event

async def callback(msg):
    print(msg)

async def websocket():
    session = aiohttp.ClientSession()
    async with session.ws_connect('http://example.org/websocket') as ws:

        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.TEXT:
                await callback(msg.data)
            elif msg.type == aiohttp.WSMsgType.CLOSED:
                break
            elif msg.type == aiohttp.WSMsgType.ERROR:
                break

The problem is that this blocks forever, so I don't know how I could integrate this with the aiohttp server. If I do:

await websocket()
aiohttp.web.run_app(app)

then web.run_app is never called. Is there some way to accomplish this? It seems like the ideal case for asyncio, multiple things handling multiple events asynchronously. How do I do it?

Body:
I was able to accomplish my goals by using the on_startup handler of my aiohttp app.

async def callback(msg):
    print(msg)

async def websocket(session):
    async with session.ws_connect('http://example.org/websocket') as ws:
        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.TEXT:
                await callback(msg.data)
            elif msg.type == aiohttp.WSMsgType.CLOSED:
                break
            elif msg.type == aiohttp.WSMsgType.ERROR:
                break

async def init(app):
    session = aiohttp.ClientSession()
    app['websocket_task'] = app.loop.create_task(websocket(session))

app = web.Application()
app.on_startup.append(init)


问:
Does sqlite C\C++ library keep DB file as Memory-mapped file? and is it possible to make it do so?
So I wonder how sqlite C/C++ API keeps opened DB: does it use Memory-mapped file? Or how to make it do so?</p>

答: By default, SQLite uses memory mapping for shared memory file which only gets used in WAL journal mode. As per SQLite documentation https://sqlite.org/mmap.html, we can set PRAGMA mmap_size to force SQLite to use memory mapped file i/o in other modes as well. However, SQLite falls back to regular file i/o if it fails to map files in the memory.</p>


问:
wp v2 rest request from Android App overload CPU usage
I have created Android App for news website (wordpress), i used WP v2 API to get posts from database, the problem that even less than 10 users that using the App in same time can overload the server (CPU usage).

When user open the App i send get request (using retrofit2) and get the first page (json array with 10 objects of that represent posts).

```<code>/wp-json/wp/v2/posts?page=1
</code>```

Then for every post i send another request for media to get image.

```<code>/wp-json/wp/v2/media/21342
</code>```

Without the App the server overloads when 600-700 users browse the website, with the App it overloads at 300 users and 10 App users.

Why it happen what is the difference between wp-v2 request and browser website loading?

答: Don't load the detail unless the user taps it to reduce strain on the wordpress server.  The browser is loading as needed is why the increase on CPU.  Your app appears to be loading in advance for items that may never be viewed.</p>

Body:
I have created Android App for news website (wordpress), i used WP v2 API to get posts from database, the problem that even less than 10 users that using the App in same time can overload the server (CPU usage).

When user open the App i send get request (using retrofit2) and get the first page (json array with 10 objects of that represent posts).

/wp-json/wp/v2/posts?page=1

Then for every post i send another request for media to get image.

/wp-json/wp/v2/media/21342

Without the App the server overloads when 600-700 users browse the website, with the App it overloads at 300 users and 10 App users.

Why it happen what is the difference between wp-v2 request and browser website loading?


问:
Problem trying to detour function with assembly
Just for the fun of it, I am trying to make a simple detouring library that will detour member functions by modifying the vtable of the class to create a detour. I am getting some odd behaviour. Here is the entire program (I am using MSVC++ 2010):

```<code>fixed
</code>```

It's jmping to the address of the new function correctly, but it crashes after that. When I watch it in ollydbg to see why it's crashing, something very strange happens. It will walk right over some instructions without doing anything. Where I see a push xxx in the debugger, the stack will not be modified. Where I see a retn 4 the thing will just keep going, into the space between functions, filled with int 3s. Does anyone have any idea why this is happening?

EDIT: Nevermind, I found the answer.

答:
for MSVC Microsoft Research has library called "Detours":
http://research.microsoft.com/en-us/projects/detours/
You may want to use it since it is already available and I think 32 bit version is free.</p>

Body:
Just for the fun of it, I am trying to make a simple detouring library that will detour member functions by modifying the vtable of the class to create a detour. I am getting some odd behaviour. Here is the entire program (I am using MSVC++ 2010):

fixed

It's jmping to the address of the new function correctly, but it crashes after that. When I watch it in ollydbg to see why it's crashing, something very strange happens. It will walk right over some instructions without doing anything. Where I see a push xxx in the debugger, the stack will not be modified. Where I see a retn 4 the thing will just keep going, into the space between functions, filled with int 3s. Does anyone have any idea why this is happening?

EDIT: Nevermind, I found the answer.


问:
Recovering file size of a specific paperclip image style
I need to know the file size of a paperclip attachment image style (not only the :original style which has a dedicated field already) and I am a bit struggling at the moment.

I have found no solution to do that inside the model

I have installed paperclip-meta gem but this gem is actually returning styles dimensions, not file size.

I might be able to retrieve the file size after the files have been uploaded to S3. I have read something about sending an Http header request or such and parsing return. I am not very at ease with this and it seems a bit complicate as the files have been generated locally and should be accessible by the server at some point.

答:
I had the same need. As you mention Paperclip attachments have a database field for the :original style file size, but the size method just returns that value.

I wanted a quick solution that would allow determining of attachment size in either filesystem or S3 (I use both) and without having to actually perform HTTP header checks. Upon looking at the Paperclip::Storage structure, I realized I could override the size method for each storage method by putting the following in my config/initializers/paperclip.rb:

```<code>module Paperclip
  module Storage
    module Filesystem
      def size(style_name = default_style)
        if original_filename
          File.size(path(style_name))
        else
          false
        end
      end
    end

    module S3
      def size(style = default_style)
        if original_filename
          s3_object(style).content_length
        else
          false
        end
      rescue Aws::Errors::ServiceError => e
        false
      end
    end
  end
end
</code>```

The paperclip-meta gem does appear to have a size method, in addition to image dimensions, aspect ratio, etc. I’m not sure if it’s a more recent addition than when you tried it. It has the advantage of caching the values in the DB.

Body:
I had the same need. As you mention Paperclip attachments have a database field for the :original style file size, but the size method just returns that value.

I wanted a quick solution that would allow determining of attachment size in either filesystem or S3 (I use both) and without having to actually perform HTTP header checks. Upon looking at the Paperclip::Storage structure, I realized I could override the size method for each storage method by putting the following in my config/initializers/paperclip.rb:

module Paperclip
  module Storage
    module Filesystem
      def size(style_name = default_style)
        if original_filename
          File.size(path(style_name))
        else
          false
        end
      end
    end

    module S3
      def size(style = default_style)
        if original_filename
          s3_object(style).content_length
        else
          false
        end
      rescue Aws::Errors::ServiceError => e
        false
      end
    end
  end
end

The paperclip-meta gem does appear to have a size method, in addition to image dimensions, aspect ratio, etc. I’m not sure if it’s a more recent addition than when you tried it. It has the advantage of caching the values in the DB.


问:
Bootstrap 4 with wordpress jquery

Bootstrap 4 doesn't work with  wordpress jquery. When I include jquery cdn everything works. How to fix this mistake without connecting own jquery?

<img src="https://i.stack.imgur.com/6hoZY.jpg" alt="enter image description here">
</p>

答:
A workaround: Add the following line into a script file that is being loaded after jQuery and before Bootstrap:</p>

```<code>var $ = window.jQuery
</code>```

Title: Bootstrap 4 with wordpress jquery

Body:
A workaround: Add the following line into a script file that is being loaded after jQuery and before Bootstrap:

var $ = window.jQuery


问:
Running batch file from USB drive when drive letter changes
So, I have made a batch script and it executes multiple portable programs (e.g., prog1.exe, prog2.exe, etc). The problem is whenever I connect the USB drive to another computer, the drive letters change, giving me errors when running my .bat file. Please help me find a solution. Thank you.</p>

答:
This is how I get the last removable drive in a listing.</p>

```<code>    @echo off

    :: Drivetypes
    ::  0=Unknown
    ::  1=No Root Directory
    ::  2=Removable(USB,Firewire)
    ::  3=Local Disk (Internal Hard Drive)
    ::  4=Network Drive(\\Server\share\)
    ::  5=Compact Disk (CD DVD)
    ::  6=Ram Disk
    for /f "tokens=2 delims==" %%d in ('wmic logicaldisk where "drivetype=2"
    get name /format:value') do set driveletter= %%d
    echo %driveletter%
    pause
</code>```

Body:
This is how I get the last removable drive in a listing.

    @echo off

    :: Drivetypes
    ::  0=Unknown
    ::  1=No Root Directory
    ::  2=Removable(USB,Firewire)
    ::  3=Local Disk (Internal Hard Drive)
    ::  4=Network Drive(\\Server\share\)
    ::  5=Compact Disk (CD DVD)
    ::  6=Ram Disk
    for /f "tokens=2 delims==" %%d in ('wmic logicaldisk where "drivetype=2"
    get name /format:value') do set driveletter= %%d
    echo %driveletter%
    pause


问:
Visual Studio: how to control specific configuration parameters on student PCs?
Can anyone tell me how to control default configuration parameters in VS 2017 C++?  The scenario is that we generate one sample PC with the software we want (Win10, VS2017, et cetera), and this image is cloned onto about 100 PCs in student CS labs.

The two specific things I would like to control are (1) use of precompiled headers and (2) message C4706 (= versus == in an if condition).  There are some others, but these are at top of the list.

I know students could fix this themselves, but so many are confused in the first few weeks of an introductory programming class that I don't want to try that.

A search of MSDN has not been productive, but I probably am using the wrong search terms.

Thank you in advance!

答:
There are two ways I can think of:

Change the default settings in property pages for each configuration

Create a custom project template with all the project settings necessary. This will only affect new projects created with this template. Also it will keep the default template intact and will probably allow students to experiment a bit more.


问:
Optional using a generic wild card in map and orElseGet
I prepare a little example to replicate what happens in my project. I know how to workaround it, but I am very curious why it doesn't even compile. The problem is in the last return when I am using a generic wild card in the method public TestElement<?> test(), exactly the line return response.map((element) -> mapAux(50L)).orElseGet(()-> orElseGetAux(20));... I don't know why it doesn't compile. What am I doing wrong? Any clue?

Thanks in advance!

```<code>public class FullTest {
  public static class TestElement<T>{
    public T element;

    public TestElement(T t) {
      element = t;
    }
  }

  public static <U> TestElement<U> createElement(U input) {
    return new TestElement<>(input);
  }

  private TestElement<?> mapAux(Long element){
    return new TestElement<>(element);
  }

  private TestElement<?> orElseGetAux(Integer element){
    return new TestElement<>(element);
  }

  public TestElement<?> test(){
    Optional<Long> response =  Optional.of(5L);
    return response.map((element) -> mapAux(50L)).orElseGet(()-> orElseGetAux(20));
  }
}
</code>```

Update 1 - Include the error

I am using Java 8, over the last version of IntelliJ, and the error is this:

Error:(33, 78) java: incompatible types: bad return type in lambda  expression

```<code>FullTest.TestElement<capture#1 of ?> cannot be converted to FullTest.TestElement<capture#2> of ?>
</code>```

Update 2 - A little further and workaround

The use of wild card is because I need to return TesElement<> of different classes and It is the only way that I find out (in the example Long and Integer). I am open to other options...

Here a possible workaround that I prefer avoid (It is an example, I know isPresent() always return true) :

```<code>public TestElement<?> testWorkAround(){
    Optional<Long> response =  Optional.of(5L);
    TestElement<?> testElement;
    if(response.isPresent()){
      testElement = mapAux(response.get());
    }
    else{
      testElement = orElseGetAux(20);
    }
    return testElement;
  }
</code>```

答:
Why not do this?</p>

```<code>public TestElement<?> test(){
  Optional<Long> response =  Optional.of(5L);
  Optional< TestElement<?> > opResult = response.map( (element) -> mapAux(50L) );

  TestElement<?> result = opResult.orElseGet( () -> orElseGetAux(20L) );

  return result;
}
</code>```

Body:
I prepare a little example to replicate what happens in my project. I know how to workaround it, but I am very curious why it doesn't even compile. The problem is in the last return when I am using a generic wild card in the method public TestElement<?> test(), exactly the line return response.map((element) -> mapAux(50L)).orElseGet(()-> orElseGetAux(20));... I don't know why it doesn't compile. What am I doing wrong? Any clue?

Thanks in advance!

public class FullTest {
  public static class TestElement<T>{
    public T element;

    public TestElement(T t) {
      element = t;
    }
  }

  public static  TestElement createElement(U input) {
    return new TestElement<>(input);
  }

  private TestElement<?> mapAux(Long element){
    return new TestElement<>(element);
  }

  private TestElement<?> orElseGetAux(Integer element){
    return new TestElement<>(element);
  }

  public TestElement<?> test(){
    Optional<Long> response =  Optional.of(5L);
    return response.map((element) -> mapAux(50L)).orElseGet(()-> orElseGetAux(20));
  }
}

Update 1 - Include the error

I am using Java 8, over the last version of IntelliJ, and the error is this:

Error:(33, 78) java: incompatible types: bad return type in lambda  expression

FullTest.TestElement<capture#1 of ?> cannot be converted to FullTest.TestElement<capture#2> of ?>

Update 2 - A little further and workaround

The use of wild card is because I need to return TesElement<> of different classes and It is the only way that I find out (in the example Long and Integer). I am open to other options...

Here a possible workaround that I prefer avoid (It is an example, I know isPresent() always return true) :

public TestElement<?> testWorkAround(){
    Optional<Long> response =  Optional.of(5L);
    TestElement<?> testElement;
    if(response.isPresent()){
      testElement = mapAux(response.get());
    }
    else{
      testElement = orElseGetAux(20);
    }
    return testElement;
  }

Body:
Why not do this?

public TestElement<?> test(){
  Optional<Long> response =  Optional.of(5L);
  Optional< TestElement<?> > opResult = response.map( (element) -> mapAux(50L) );

  TestElement<?> result = opResult.orElseGet( () -> orElseGetAux(20L) );

  return result;
}