问:
Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
</code>```

This is the error I am getting even though I have never used getPackageManager() method.

Following is my code:

AppUtils.java :

```<code>public static boolean checkPlayServices() {

    int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(mContext);

    if (resultCode != ConnectionResult.SUCCESS) {
        if (GoogleApiAvailability.getInstance().isUserResolvableError(resultCode)) {
            GoogleApiAvailability.getInstance().getErrorDialog((Activity) mContext, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST);
        } else {
            Toast.makeText(mContext, "This Device is not Supported!", Toast.LENGTH_LONG).show();
        }
        return false;
    }
    return true;
}
</code>```

MyUtils.java :

```<code>@Override
protected void onResume() {
    super.onResume();
    utils.checkPlayServices();
}
</code>```

Log cat error:

```<code>11-18 12:32:07.705 21076-21076/com.vtrak E/AndroidRuntime: FATAL EXCEPTION: main
                                                       Process: com.vtrak, PID: 21076
                                                       java.lang.RuntimeException: Unable to resume activity {com.vtrak/com.vtrak.Activities.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
                                                           at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3334)
                                                           at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3365)
                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2690)
                                                           at android.app.ActivityThread.access$900(ActivityThread.java:188)
                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1530)
                                                           at android.os.Handler.dispatchMessage(Handler.java:111)
                                                           at android.os.Looper.loop(Looper.java:210)
                                                           at android.app.ActivityThread.main(ActivityThread.java:5839)
                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                           at java.lang.reflect.Method.invoke(Method.java:372)
                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113)
                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879)
                                                        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
                                                           at com.google.android.gms.common.zze.isGooglePlayServicesAvailable(Unknown Source)
                                                           at com.google.android.gms.common.zzc.isGooglePlayServicesAvailable(Unknown Source)
                                                           at com.google.android.gms.common.GoogleApiAvailability.isGooglePlayServicesAvailable(Unknown Source)
                                                           at com.vtrak.Classes.Utils.checkPlayServices(Utils.java:92)
                                                           at com.vtrak.Activities.HomeActivity.onResume(HomeActivity.java:66)
                                                           at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1267)
                                                           at android.app.Activity.performResume(Activity.java:6263)
                                                           at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3319)
                                                           at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3365)
                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2690)
                                                           at android.app.ActivityThread.access$900(ActivityThread.java:188)
                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1530)
                                                           at android.os.Handler.dispatchMessage(Handler.java:111)
                                                           at android.os.Looper.loop(Looper.java:210)
                                                           at android.app.ActivityThread.main(ActivityThread.java:5839)
                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                           at java.lang.reflect.Method.invoke(Method.java:372)
                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113)
                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879)
</code>```

I get this error when this method is called, I don't understand why my app is crashing this method has nothing to do with checkplayServices() method :

```<code>private void getHistory() {
    /*String assetNo = null;
    Bundle bun = getIntent().getExtras();
    if (bun != null) {

        assetNo = bun.getString(RecyclerAdapter.KEY_VEH_NUM, null);
    }*/
    String startDate = tvDate.getText() + " " + tvStartTime.getText();
    String endDate = tvDate.getText() + " " + tvEndTime.getText();

    Call<ModelHistory> call = Utils.retroInterface.getHistory("SG00iX", "Android", Integer.parseInt(LogInActivity.sharedPreferences.getString(LogInActivity.KEY_RESULT_MSG, null)), "GBE8185Y", startDate, endDate);

    call.enqueue(new Callback<ModelHistory>() {
        @Override
        public void onResponse(Call<ModelHistory> call, Response<ModelHistory> response) {

            for (int i = 0; i < response.body().getData().size(); i++) {

                Log.i("lat long : ", response.body().getData().get(i).getLocLat() + "   " + response.body().getData().get(i).getLocLon());

                listLat.add(Double.valueOf(response.body().getData().get(i).getLocLat()));
                listLat.add(Double.valueOf(response.body().getData().get(i).getLocLon()));

            }

            showInMap(listLat, listLong);

        }

        @Override
        public void onFailure(Call<ModelHistory> call, Throwable t) {
            Log.i("no, ", "its failure" + t.toString());
        }
    });
}
</code>```

Edit:

Got the answer finally, lists were not initialized, initializing them like this, solved problem:

```<code>listLat = new ArrayList<Double>;
listLon = new ArrayList<Double>;
</code>```

答:
As per your Above Comment

Alright I didn't initialize utils at first, I was not not supposed to initialize it, its static method I can use directly.

than pass Context in your checkPlayServices like below code

Try this

```<code>public static boolean checkPlayServices(Context mContext) {

    int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(mContext);

    if (resultCode != ConnectionResult.SUCCESS) {
        if (GoogleApiAvailability.getInstance().isUserResolvableError(resultCode)) {
            GoogleApiAvailability.getInstance().getErrorDialog((Activity) context, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST);
        } else {
            Toast.makeText(mContext, "This Device is not Supported!", Toast.LENGTH_LONG).show();
        }
        return false;
    }
    return true;
}
</code>```

than call this method like this

```<code>@Override
protected void onResume() {
    super.onResume();
    AppUtils.checkPlayServices(YourActivity.this);
}
</code>```

Body:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference

This is the error I am getting even though I have never used getPackageManager() method.

Following is my code:

AppUtils.java :

public static boolean checkPlayServices() {

    int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(mContext);

    if (resultCode != ConnectionResult.SUCCESS) {
        if (GoogleApiAvailability.getInstance().isUserResolvableError(resultCode)) {
            GoogleApiAvailability.getInstance().getErrorDialog((Activity) mContext, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST);
        } else {
            Toast.makeText(mContext, "This Device is not Supported!", Toast.LENGTH_LONG).show();
        }
        return false;
    }
    return true;
}

MyUtils.java :

@Override
protected void onResume() {
    super.onResume();
    utils.checkPlayServices();
}

Log cat error:

11-18 12:32:07.705 21076-21076/com.vtrak E/AndroidRuntime: FATAL EXCEPTION: main
                                                       Process: com.vtrak, PID: 21076
                                                       java.lang.RuntimeException: Unable to resume activity {com.vtrak/com.vtrak.Activities.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
                                                           at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3334)
                                                           at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3365)
                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2690)
                                                           at android.app.ActivityThread.access$900(ActivityThread.java:188)
                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1530)
                                                           at android.os.Handler.dispatchMessage(Handler.java:111)
                                                           at android.os.Looper.loop(Looper.java:210)
                                                           at android.app.ActivityThread.main(ActivityThread.java:5839)
                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                           at java.lang.reflect.Method.invoke(Method.java:372)
                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113)
                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879)
                                                        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
                                                           at com.google.android.gms.common.zze.isGooglePlayServicesAvailable(Unknown Source)
                                                           at com.google.android.gms.common.zzc.isGooglePlayServicesAvailable(Unknown Source)
                                                           at com.google.android.gms.common.GoogleApiAvailability.isGooglePlayServicesAvailable(Unknown Source)
                                                           at com.vtrak.Classes.Utils.checkPlayServices(Utils.java:92)
                                                           at com.vtrak.Activities.HomeActivity.onResume(HomeActivity.java:66)
                                                           at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1267)
                                                           at android.app.Activity.performResume(Activity.java:6263)
                                                           at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3319)
                                                           at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3365)
                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2690)
                                                           at android.app.ActivityThread.access$900(ActivityThread.java:188)
                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1530)
                                                           at android.os.Handler.dispatchMessage(Handler.java:111)
                                                           at android.os.Looper.loop(Looper.java:210)
                                                           at android.app.ActivityThread.main(ActivityThread.java:5839)
                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                           at java.lang.reflect.Method.invoke(Method.java:372)
                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113)
                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879)

I get this error when this method is called, I don't understand why my app is crashing this method has nothing to do with checkplayServices() method :

private void getHistory() {
    /*String assetNo = null;
    Bundle bun = getIntent().getExtras();
    if (bun != null) {

        assetNo = bun.getString(RecyclerAdapter.KEY_VEH_NUM, null);
    }*/
    String startDate = tvDate.getText() + " " + tvStartTime.getText();
    String endDate = tvDate.getText() + " " + tvEndTime.getText();

    Call<ModelHistory> call = Utils.retroInterface.getHistory("SG00iX", "Android", Integer.parseInt(LogInActivity.sharedPreferences.getString(LogInActivity.KEY_RESULT_MSG, null)), "GBE8185Y", startDate, endDate);

    call.enqueue(new Callback<ModelHistory>() {
        @Override
        public void onResponse(Call<ModelHistory> call, Response<ModelHistory> response) {

            for (int i = 0; i < response.body().getData().size(); i++) {

                Log.i("lat long : ", response.body().getData().get(i).getLocLat() + "   " + response.body().getData().get(i).getLocLon());

                listLat.add(Double.valueOf(response.body().getData().get(i).getLocLat()));
                listLat.add(Double.valueOf(response.body().getData().get(i).getLocLon()));

            }

            showInMap(listLat, listLong);

        }

        @Override
        public void onFailure(Call<ModelHistory> call, Throwable t) {
            Log.i("no, ", "its failure" + t.toString());
        }
    });
}

Edit:

Got the answer finally, lists were not initialized, initializing them like this, solved problem:

listLat = new ArrayList<Double>;
listLon = new ArrayList<Double>;

Body:
As per your Above Comment

Alright I didn't initialize utils at first, I was not not supposed to initialize it, its static method I can use directly.

than pass Context in your checkPlayServices like below code

Try this

public static boolean checkPlayServices(Context mContext) {

    int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(mContext);

    if (resultCode != ConnectionResult.SUCCESS) {
        if (GoogleApiAvailability.getInstance().isUserResolvableError(resultCode)) {
            GoogleApiAvailability.getInstance().getErrorDialog((Activity) context, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST);
        } else {
            Toast.makeText(mContext, "This Device is not Supported!", Toast.LENGTH_LONG).show();
        }
        return false;
    }
    return true;
}

than call this method like this

@Override
protected void onResume() {
    super.onResume();
    AppUtils.checkPlayServices(YourActivity.this);
}


来源: stackexchange

问:
javascript loop does not seem to work
I expected the code snippet to print out 100 times with the value of i.

But it prints out only once like below.

What am I missing here ?

let i = 0;
for (; i++; i < 100) {
  console.log('Loop ==>' + i);
}
console.log('Loop Done');
console.log('Value of i ==>' + i);```

答:
You mixed the "condition" and "change" places in your for loop. Condition is in the second place and change in the third place.

let i = 0;

for(; i < 100; i++) {
    console.log('Loop ==>'+i);
}

console.log('Loop Done');
console.log('Value of i ==>'+i);```

ContentLicense: CC BY-SA 3.0

Title: javascript loop does not seem to work


答:
Your for loop's structure is faulty. You should use the correct syntax, like this.

```<code>for (; i < 100; i++)
</code>```

for loops have 3 statements, initialization, condition and updation, in that order. The loop runs as long as the second statement, i.e., the condition is met. The third statement, i.e., updation, is executed after all the code in your block is executed.

What you have done is you have mixed up the third (updation) and the second (condition) statements in your for loop.

Title: javascript loop does not seem to work

Body:
I expected the code snippet to print out 100 times with the value of i.

But it prints out only once like below.

What am I missing here ?

let i = 0;
for (; i++; i < 100) {
  console.log('Loop ==>' + i);
}
console.log('Loop Done');
console.log('Value of i ==>' + i);

Body:
Your for loop's structure is faulty. You should use the correct syntax, like this.

for (; i < 100; i++)

for loops have 3 statements, initialization, condition and updation, in that order. The loop runs as long as the second statement, i.e., the condition is met. The third statement, i.e., updation, is executed after all the code in your block is executed.

What you have done is you have mixed up the third (updation) and the second (condition) statements in your for loop.


答:
Change ; i++; i < 100 to ; i < 100; i++. In the former case  i  value is incremeneted and tested if less than 100, whereas it need the opposite

let i = 0;
for (; i < 100; i++) {
  console.log('Loop ==>' + i);
}
console.log('Loop Done');
console.log('Value of i ==>' + i);```

Title: javascript loop does not seem to work


问:
Crypt a message with matlab
I have one question.
I didn't work with MatLab before.
how I read a message from a file. text? and how I crypt and decrypt  it?
I need this work for my study project.</p>

答:
To read text:

```<code>fid=fopen(filename,'r');
text=fread(fid,'*char')';
fclose(fid);
</code>```

To encrypt you can use whatever encrpytion suite you want. look here for aes implementation.
Very simple enc/dec algorithem is xoring the text with some key:

```<code>filename=('my_cypher.m');
key='Justin Bieber'; %some very secret key

fprintf('\n------------Text-------------\n');
fid=fopen(filename,'r');
text=fread(fid,'*char')';
fclose(fid);

text(text==13)=[]; %remove windows CR for readablity
disp(text);

key=uint8(key);
text=uint8(text);
lenkey=length(key);
text(end+1:end+lenkey-mod(length(text),lenkey))=32; %add extra spaces for reshape.

fprintf('\n------------Cipher-------------\n');
cipher = reshape(bitxor(reshape(text,[],lenkey),key),1,[]);
disp(char(cipher));

fprintf('\n------------Decrpyt-------------\n');
decrpyt = reshape(bitxor(reshape(cipher,[],lenkey),key),1,[]);
disp(char(decrpyt));
</code>```

Title: Crypt a message with matlab

Body:
To read text:

fid=fopen(filename,'r');
text=fread(fid,'*char')';
fclose(fid);

To encrypt you can use whatever encrpytion suite you want. look here for aes implementation.
Very simple enc/dec algorithem is xoring the text with some key:

filename=('my_cypher.m');
key='Justin Bieber'; %some very secret key

fprintf('\n------------Text-------------\n');
fid=fopen(filename,'r');
text=fread(fid,'*char')';
fclose(fid);

text(text==13)=[]; %remove windows CR for readablity
disp(text);

key=uint8(key);
text=uint8(text);
lenkey=length(key);
text(end+1:end+lenkey-mod(length(text),lenkey))=32; %add extra spaces for reshape.

fprintf('\n------------Cipher-------------\n');
cipher = reshape(bitxor(reshape(text,[],lenkey),key),1,[]);
disp(char(cipher));

fprintf('\n------------Decrpyt-------------\n');
decrpyt = reshape(bitxor(reshape(cipher,[],lenkey),key),1,[]);
disp(char(decrpyt));


问:
Visual Studio Mac, Android release signed is older than current build
I'm using Visual Studio mac for developing Xamarin, recently I released my Android app but a rare behave happened! Releasing app popped out 2 files named app.apk and app-Signed.apk and I think the 2nd one should be the one I should upload to Google Play store (am I right?), but after opening it on my device I found out many changes that was appearing in debug app are not exist in Singned one! while app.apk is OK with changes I applied to app.

Is app.apk in debug mode?

What should be app-Signed.apk and why it has this problem and how can I fix it (if answer to #1 is true)?

答: Sometimes Visual Studio Mac for some reason does that. Remove obj and bin folder from a project directory, and then build again. If that happens again (2 files) the odd thing that you need to upload to google play non signed one.  </p>


问:
checking invariants in C++
Are there any established patterns for checking class invariants in C++?

Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function. As far as I know, C with classes provided special before and after member functions, but unfortunately, design by contract wasn't quite popular at the time and nobody except Bjarne used that feature, so he removed it.

Of course, manually inserting check_invariants() calls at the beginning and at the end of each public member function is tedious and error-prone. Since RAII is the weapon of choice to deal with exceptions, I came up with the following scheme of defining an invariance checker as the first local variable, and that invariance checker checks the invariants both at construction and destruction time:

```<code>template <typename T>
class invariants_checker
{
    const T* p;

public:

    invariants_checker(const T* p) : p(p)
    {
        p->check_invariants();
    }

    ~invariants_checker()
    {
        p->check_invariants();
    }
};

void Foo::bar()
{
    // class invariants checked by construction of _
    invariants_checker<Foo> _(this);

    // ... mutate the object

    // class invariants checked by destruction of _
}
</code>```

Question #0: I suppose there is no way to declare an unnamed local variable? :)

We would still have to call check_invariants() manually at the end of the Foo constructor and at the beginning of the Foo destructor. However, many constructor bodies and destructor bodies are empty. In that case, could we use an invariants_checker as the last member?

```<code>#include <string>
#include <stdexcept>

class Foo
{
    std::string str;
    std::string::size_type cached_length;
    invariants_checker<Foo> _;

public:

    Foo(const std::string& str)
    : str(str), cached_length(str.length()), _(this) {}

    void check_invariants() const
    {
        if (str.length() != cached_length)
            throw std::logic_error("wrong cached length");
    }

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

Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?

Question #2: Do you see any other problems with this approach? Can you improve it?

Question #3: Is this approach new or well-known? Are there better solutions available?

答:
Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function

I think this is overkill; I instead check invariants judiciously. The data members of your class are private (right?), so only its member functions can change the data memebers and therefore invalidate invariants. So you can get away with checking an invariant just after a change to a data member that particiaptes in that invariant.

ContentLicense: CC BY-SA 2.5

Title: checking invariants in C++

Body:
Are there any established patterns for checking class invariants in C++?

Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function. As far as I know, C with classes provided special before and after member functions, but unfortunately, design by contract wasn't quite popular at the time and nobody except Bjarne used that feature, so he removed it.

Of course, manually inserting check_invariants() calls at the beginning and at the end of each public member function is tedious and error-prone. Since RAII is the weapon of choice to deal with exceptions, I came up with the following scheme of defining an invariance checker as the first local variable, and that invariance checker checks the invariants both at construction and destruction time:

template <typename T>
class invariants_checker
{
    const T* p;

public:

    invariants_checker(const T* p) : p(p)
    {
        p->check_invariants();
    }

    ~invariants_checker()
    {
        p->check_invariants();
    }
};

void Foo::bar()
{
    // class invariants checked by construction of _
    invariants_checker<Foo> _(this);

    // ... mutate the object

    // class invariants checked by destruction of _
}

Question #0: I suppose there is no way to declare an unnamed local variable? :)

We would still have to call check_invariants() manually at the end of the Foo constructor and at the beginning of the Foo destructor. However, many constructor bodies and destructor bodies are empty. In that case, could we use an invariants_checker as the last member?

#include <string>
#include <stdexcept>

class Foo
{
    std::string str;
    std::string::size_type cached_length;
    invariants_checker<Foo> _;

public:

    Foo(const std::string& str)
    : str(str), cached_length(str.length()), _(this) {}

    void check_invariants() const
    {
        if (str.length() != cached_length)
            throw std::logic_error("wrong cached length");
    }

    // ...
};

Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?

Question #2: Do you see any other problems with this approach? Can you improve it?

Question #3: Is this approach new or well-known? Are there better solutions available?


问:
Sum next array elements from a starting position (javascript)
I need this for dynamically use.
I have 2 associated arrays:

```<code>Var $some = [1, 2, 3];
Var $other = [a, b, c];
</code>```

a, b, c are some html ids and 1, 2, 3 are their values.
I want something like this on trigger:

```<code>$'#a').attr('max', //b+c val(2+3)
$'#b').attr('max', //a+c val(1+3)
$'#c').attr('max', //a+b val(1+2)
</code>```

I ve searched here get prev and next items in array about finding next elements in array, and I think would be usefull a loop that itinerate elements a (then b then c) with its values and for each one execute a code like: sum next elements to them. Substracting element value after sumed won't work pripperly because I want that script on some ranges change...
So...my question would be: how can I sum elements itinerated from a loop? I think that would be the key to solve this because I can loop it 2 times in this example and would stop without started element...

答:
Previous solutions works nice, of course, but, just in case, here is more straightforward solution:

```<code>$( "input" ).each(function( index ) {
sum=0;
for(i=0;i<$(this).siblings().length;i++) {
sum+= parseInt($( this ).siblings().eq(i).val());
}
console.log(sum);
$(this).attr('max',sum)
});
</code>```

$( "input" ).each(function( index ) { // loop through each input
sum=0;
for(i=0;i<$(this).siblings().length;i++) { // get all siblings
sum+= parseInt($( this ).siblings().eq(i).val()); //calculate sum of siblings values
}
console.log(sum);
$(this).attr('max',sum)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inputs">
<input type="number" id="a" value=1>
<input type="number" id="b" value=2>
<input type="number" id="c" value=3>
</div></code>```

Body:
I need this for dynamically use.
I have 2 associated arrays:

Var $some = [1, 2, 3];
Var $other = [a, b, c];

a, b, c are some html ids and 1, 2, 3 are their values.
I want something like this on trigger:

$'#a').attr('max', //b+c val(2+3)
$'#b').attr('max', //a+c val(1+3)
$'#c').attr('max', //a+b val(1+2)

I ve searched here get prev and next items in array about finding next elements in array, and I think would be usefull a loop that itinerate elements a (then b then c) with its values and for each one execute a code like: sum next elements to them. Substracting element value after sumed won't work pripperly because I want that script on some ranges change...
So...my question would be: how can I sum elements itinerated from a loop? I think that would be the key to solve this because I can loop it 2 times in this example and would stop without started element...

Body:
Previous solutions works nice, of course, but, just in case, here is more straightforward solution:

$( "input" ).each(function( index ) {
sum=0;
for(i=0;i<$(this).siblings().length;i++) {
sum+= parseInt($( this ).siblings().eq(i).val());
}
console.log(sum);
$(this).attr('max',sum)
});

$( "input" ).each(function( index ) { // loop through each input
sum=0;
for(i=0;i<$(this).siblings().length;i++) { // get all siblings
sum+= parseInt($( this ).siblings().eq(i).val()); //calculate sum of siblings values
}
console.log(sum);
$(this).attr('max',sum)
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inputs">
<input type="number" id="a" value=1>
<input type="number" id="b" value=2>
<input type="number" id="c" value=3>
</div>


问:
How to add 'drawtext' to overlay in ffmpeg?
The command is ffmpeg -loop 1 -t 5 -i "demo_1.jpg" -filter_complex "nullsrc=size=640x360[background];[background][0:v]overlay=shortest=1:x='min(-(t)*20,0)'" -qscale 1 -y out.mp4

I am animating the image from right to left. In the above command, I need to add text, How to integrate the drawtext feature of ffmpeg to that.

The video animation is https://youtu.be/teXUiPKX83o.

Need to add text to that video.

答:
Use

```<code>ffmpeg -loop 1 -t 5 -i "demo_1.jpg" -filter_complex
   "nullsrc=size=640x360[background];
    [background][0:v]overlay=shortest=1:x='min(-(t)*20,0)',
    drawtext=fontfile='/path/to/font':fontsize=30:fontcolor=yellow:x=50:y=50:text='Text'"
 -qscale 1 -y out.mp4
</code>```

See drawtext docs for more info.

Body:
Use

ffmpeg -loop 1 -t 5 -i "demo_1.jpg" -filter_complex
   "nullsrc=size=640x360[background];
    [background][0:v]overlay=shortest=1:x='min(-(t)*20,0)',
    drawtext=fontfile='/path/to/font':fontsize=30:fontcolor=yellow:x=50:y=50:text='Text'"
 -qscale 1 -y out.mp4

See drawtext docs for more info.


问:
Concatenate in SQL Server 2008 R2 failing when the monthid is 2 digits
I have a table like and server is SQL Server 2008 R2 where we cannot use concat function

```<code>YearID  |   MonthId
--------+----------
2017    |    1
2014    |    5
2014    |   10
2016    |   12
</code>```

I want to have the output as

```<code>201701
201405
201410
201612
</code>```

What I tried so far

```<code>select
    cast(YearId as varchar(50)) + '0' + cast(MonthId as varchar(50))
from
    TEST
</code>```

I am getting the output as

```<code>201701
201405
2014010
2016012
</code>```

When the monthID is 2 digits, it is failing.

How to tackle this situation?

答:
```<code>DECLARE @Tmp TABLE (YearID INT ,MOnthId INT)
INSERT INTO @Tmp
SELECT 2017 ,1   UNION ALL
SELECT 2014 ,5   UNION ALL
SELECT 2014 ,10  UNION ALL
SELECT 2016 ,12

SELECT * FROM @Tmp

SELECT
CASE WHEN LEN(MOnthId)>1 THEN CAST(YearId AS VARCHAR(50)) + CAST(MonthId AS VARCHAR(50))
     ELSE CAST(YearId AS VARCHAR(50)) + '0' + CAST(MonthId AS VARCHAR(50))END
 FROM @Tmp

Results :
201701
201405
201410
201612
</code>```

Body:
I have a table like and server is SQL Server 2008 R2 where we cannot use concat function

YearID  |   MonthId
--------+----------
2017    |    1
2014    |    5
2014    |   10
2016    |   12

I want to have the output as

201701
201405
201410
201612

What I tried so far

select
    cast(YearId as varchar(50)) + '0' + cast(MonthId as varchar(50))
from
    TEST

I am getting the output as

201701
201405
2014010
2016012

When the monthID is 2 digits, it is failing.

How to tackle this situation?


问:
How to insert check box value in MYSQL using Flask
I have three Checkbox in HTML and I got the checkbox value in Python.If I select the Checkbox means the value should be insert as "yes" in MYSQL Database otherwise It should be insert as "No".I had tried but I don't know how to get Answer.Please help me,Thanks in Advance:)

Here is my Code:
HTML:

```<code><form action='/hello' method="POST" enctype="multipart/form-data">
Panchayath <input type="checkbox" name="checks[]" value="yes" id="panchayath"><br>
     Ward  <input type="checkbox" name="check[]" value=" yes" id=" ward"><br>
    Results  <input type="checkbox" name="chec[]" value=" yes" id=" results">
    <input type="submit" value="Submit">
</form>
</code>```

py:

```<code>import os
from flask import Flask, request, render_template
from flaskext.mysql import MySQL

mysql = MySQL()

app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'bucketlist'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

@app.route('/hello', methods=['GET', 'POST'])
def get_data():
    print("hlo")
    if request.method == 'POST':
        print("cat")
        panchayath = request.form.getlist('checks[]')
        print panchayath
        ward = request.form.getlist('check[]')
        print ward
        Results = request.form.getlist('chec[]')
        print Results
        conn = mysql.connect()
        cursor = conn.cursor()
        # cursor.execute()
        print "yes"
        # cursor.execute("insert into try_chk3  values (%s,%s,%s)", (some_var))
        # query = "CREATE TABLE saracheck( panchayath  VARCHAR(40), ward VARCHAR(40),Results VARCHAR (40))"
        # cursor.execute(query)
        query = "INSERT INTO saracheck(panchayath,ward,Results) VALUES(%s,%s,%s)"
        a=cursor.execute(query, (panchayath,ward,Results))
        print a
        print "execuet"
        # cursor.execute(query,(first_name,last_name,email_id,can_pic,logo_pic))
        conn.commit()

    return render_template("form.html")

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

output:
enter image description here

答:
First of all why are you naming the fields like "checks", "check" and "chec", it either seems like all of them would have been name = "checks[]" or it's just poor style of naming.

Also aren't you trying to get the values of all three fields? Then you should be trying to get Results of all three of them right?

Can you please also post what you are getting as output so far?

Body:
I have three Checkbox in HTML and I got the checkbox value in Python.If I select the Checkbox means the value should be insert as "yes" in MYSQL Database otherwise It should be insert as "No".I had tried but I don't know how to get Answer.Please help me,Thanks in Advance:)

Here is my Code:
HTML:

<form action='/hello' method="POST" enctype="multipart/form-data">
Panchayath <input type="checkbox" name="checks[]" value="yes" id="panchayath">

     Ward  <input type="checkbox" name="check[]" value=" yes" id=" ward">

    Results  <input type="checkbox" name="chec[]" value=" yes" id=" results">
    <input type="submit" value="Submit">
</form>

py:

import os
from flask import Flask, request, render_template
from flaskext.mysql import MySQL

mysql = MySQL()

app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'bucketlist'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

@app.route('/hello', methods=['GET', 'POST'])
def get_data():
    print("hlo")
    if request.method == 'POST':
        print("cat")
        panchayath = request.form.getlist('checks[]')
        print panchayath
        ward = request.form.getlist('check[]')
        print ward
        Results = request.form.getlist('chec[]')
        print Results
        conn = mysql.connect()
        cursor = conn.cursor()
        # cursor.execute()
        print "yes"
        # cursor.execute("insert into try_chk3  values (%s,%s,%s)", (some_var))
        # query = "CREATE TABLE saracheck( panchayath  VARCHAR(40), ward VARCHAR(40),Results VARCHAR (40))"
        # cursor.execute(query)
        query = "INSERT INTO saracheck(panchayath,ward,Results) VALUES(%s,%s,%s)"
        a=cursor.execute(query, (panchayath,ward,Results))
        print a
        print "execuet"
        # cursor.execute(query,(first_name,last_name,email_id,can_pic,logo_pic))
        conn.commit()

    return render_template("form.html")

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

output:
enter image description here


问:
SQL Updating column in new table with arithmetic function from column in another table
I have two tables:

part of Table1:

```<code> id  |  per  |  va   | gp | minutes
-----+-------+-------+----+---------
   1 | 11.87 |  14.5 | 69 |    16.1
   2 | 17.07 | 154.9 | 78 |    23.9
   3 |  4.30 |  -8.6 | 21 |     4.4
   4 |  5.68 | -42.2 | 52 |     9.3
   5 | 19.46 | 347.8 | 82 |    32.1
   6 | 18.26 | 125.3 | 47 |    23.3
   7 | 12.76 |  79.0 | 82 |    28.5
   8 |  9.19 |  -3.7 | 13 |    14.8
   9 | 21.15 |  10.7 | 10 |     6.8
  10 | 14.38 |  46.1 | 31 |    25.7
</code>```

Table2:

```<code> player |           prl           | position
--------+-------------------------+----------
 1      |                         |
 2      |                         |
 3      |                         |
 4      |                         |
</code>```

I'm trying to calculate prl by taking those columns in table 1 and doing per - ((67*va)/(gp*minutes)). I can of course calculate this outside of inserting it into the prl column but can't find a way to get it into prl. The closest I've gotten is by doing this:

```<code>update hwk2
set prl = per - ((67*va)/(gp*minutes)) from more_player_stats;
UPDATE 1904
</code>```

which gives me the same result throughout the entire prl column. Can anyone help out this brand new sql user?

答:
Use an update join:

```<code>UPDATE hwk2 AS t1
SET prl = t1.per - ((67*t1.va) / (t1.gp*t1.minutes))
FROM more_player_stats AS t2
WHERE t1.player = t2.id;
</code>```

Here is a link to a reference question on SO covering updates in Postgres.

Body:
I have two tables:

part of Table1:

 id  |  per  |  va   | gp | minutes
-----+-------+-------+----+---------
   1 | 11.87 |  14.5 | 69 |    16.1
   2 | 17.07 | 154.9 | 78 |    23.9
   3 |  4.30 |  -8.6 | 21 |     4.4
   4 |  5.68 | -42.2 | 52 |     9.3
   5 | 19.46 | 347.8 | 82 |    32.1
   6 | 18.26 | 125.3 | 47 |    23.3
   7 | 12.76 |  79.0 | 82 |    28.5
   8 |  9.19 |  -3.7 | 13 |    14.8
   9 | 21.15 |  10.7 | 10 |     6.8
  10 | 14.38 |  46.1 | 31 |    25.7

Table2:

 player |           prl           | position
--------+-------------------------+----------
 1      |                         |
 2      |                         |
 3      |                         |
 4      |                         |

I'm trying to calculate prl by taking those columns in table 1 and doing per - ((67*va)/(gp*minutes)). I can of course calculate this outside of inserting it into the prl column but can't find a way to get it into prl. The closest I've gotten is by doing this:

update hwk2
set prl = per - ((67*va)/(gp*minutes)) from more_player_stats;
UPDATE 1904

which gives me the same result throughout the entire prl column. Can anyone help out this brand new sql user?

Body:
Use an update join:

UPDATE hwk2 AS t1
SET prl = t1.per - ((67*t1.va) / (t1.gp*t1.minutes))
FROM more_player_stats AS t2
WHERE t1.player = t2.id;

Here is a link to a reference question on SO covering updates in Postgres.


问:
How to fix AttributeError: 'module' object has no attribute 'Client' when running python in Google Cloud Interactive Shell
I'm trying to run a python script that simulates traffic sensors sending in data in real time to PubSub on my Google Cloud Shell. I'm getting this error

```<code>Traceback (most recent call last):
  File "./send_sensor_data.py", line 87, in <module>
    psclient = pubsub.Client()
AttributeError: 'module' object has no attribute 'Client'
</code>```

Tried running google.cloud.pubsub.__file__, no duplicates exist.
I've been searching everywhere and the popular consensus was to install the pubsub package into a virtual environment which I've tried to no avail.
What I've tried so far:

Set VM to clean state

Uninstalled and reinstalled all gcloud components

Updated all gcloud components to the latest version

uninsalled and reinstalled python pubsub library

Installed pubsub inside a virtualenv

Tried from a different project

Tried from a different GCP account

This is my script:

```<code>import time
import gzip
import logging
import argparse
import datetime
from google.cloud import pubsub

TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
TOPIC = 'sandiego'
INPUT = 'sensor_obs2008.csv.gz'

def publish(topic, events):
   numobs = len(events)
   if numobs > 0:
      with topic.batch() as batch:
         logging.info('Publishing {} events from {}'.
                    format(numobs, get_timestamp(events[0])))
         for event_data in events:
              batch.publish(event_data)

def get_timestamp(line):
   # look at first field of row
   timestamp = line.split(',')[0]
   return datetime.datetime.strptime(timestamp, TIME_FORMAT)

def simulate(topic, ifp, firstObsTime, programStart, speedFactor):
   # sleep computation
   def compute_sleep_secs(obs_time):
        time_elapsed = (datetime.datetime.utcnow() - programStart).seconds
        sim_time_elapsed = (obs_time - firstObsTime).seconds / speedFactor
        to_sleep_secs = sim_time_elapsed - time_elapsed
        return to_sleep_secs

   topublish = list()

   for line in ifp:
       event_data = line   # entire line of input CSV is the message
       obs_time = get_timestamp(line) # from first column

       # how much time should we sleep?
       if compute_sleep_secs(obs_time) > 1:
          # notify the accumulated topublish
          publish(topic, topublish) # notify accumulated messages
          topublish = list() # empty out list

          # recompute sleep, since notification takes a while
          to_sleep_secs = compute_sleep_secs(obs_time)
          if to_sleep_secs > 0:
             logging.info('Sleeping {} seconds'.format(to_sleep_secs))
             time.sleep(to_sleep_secs)
       topublish.append(event_data)

   # left-over records; notify again
   publish(topic, topublish)

def peek_timestamp(ifp):
   # peek ahead to next line, get timestamp and go back
   pos = ifp.tell()
   line = ifp.readline()
   ifp.seek(pos)
   return get_timestamp(line)

if __name__ == '__main__':
   parser = argparse.ArgumentParser(description='Send sensor data to Cloud Pub/Sub in small groups, simulating real-time behavior')
   parser.add_argument('--speedFactor', help='Example: 60 implies 1 hour of data sent to Cloud Pub/Sub in 1 minute', required=True, type=float)
   args = parser.parse_args()

   # create Pub/Sub notification topic
   logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
   psclient = pubsub.Client()
   topic = psclient.topic(TOPIC)
   if not topic.exists():
      logging.info('Creating pub/sub topic {}'.format(TOPIC))
      topic.create()
   else:
      logging.info('Reusing pub/sub topic {}'.format(TOPIC))

   # notify about each line in the input file
   programStartTime = datetime.datetime.utcnow()
   with gzip.open(INPUT, 'rb') as ifp:
      header = ifp.readline()  # skip header
      firstObsTime = peek_timestamp(ifp)
      logging.info('Sending sensor data from {}'.format(firstObsTime))
      simulate(topic, ifp, firstObsTime, programStartTime, args.speedFactor)
</code>```

答:
There's no pubsub.Client class. You
 need to choose a PublisherClient or SubscriberClient

see https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/pubsub/google/cloud/pubsub.py

Body:
I'm trying to run a python script that simulates traffic sensors sending in data in real time to PubSub on my Google Cloud Shell. I'm getting this error

Traceback (most recent call last):
  File "./send_sensor_data.py", line 87, in <module>
    psclient = pubsub.Client()
AttributeError: 'module' object has no attribute 'Client'

Tried running google.cloud.pubsub.__file__, no duplicates exist.
I've been searching everywhere and the popular consensus was to install the pubsub package into a virtual environment which I've tried to no avail.
What I've tried so far:

Set VM to clean state

Uninstalled and reinstalled all gcloud components

Updated all gcloud components to the latest version

uninsalled and reinstalled python pubsub library

Installed pubsub inside a virtualenv

Tried from a different project

Tried from a different GCP account

This is my script:

import time
import gzip
import logging
import argparse
import datetime
from google.cloud import pubsub

TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
TOPIC = 'sandiego'
INPUT = 'sensor_obs2008.csv.gz'

def publish(topic, events):
   numobs = len(events)
   if numobs > 0:
      with topic.batch() as batch:
         logging.info('Publishing {} events from {}'.
                    format(numobs, get_timestamp(events[0])))
         for event_data in events:
              batch.publish(event_data)

def get_timestamp(line):
   # look at first field of row
   timestamp = line.split(',')[0]
   return datetime.datetime.strptime(timestamp, TIME_FORMAT)

def simulate(topic, ifp, firstObsTime, programStart, speedFactor):
   # sleep computation
   def compute_sleep_secs(obs_time):
        time_elapsed = (datetime.datetime.utcnow() - programStart).seconds
        sim_time_elapsed = (obs_time - firstObsTime).seconds / speedFactor
        to_sleep_secs = sim_time_elapsed - time_elapsed
        return to_sleep_secs

   topublish = list()

   for line in ifp:
       event_data = line   # entire line of input CSV is the message
       obs_time = get_timestamp(line) # from first column

       # how much time should we sleep?
       if compute_sleep_secs(obs_time) > 1:
          # notify the accumulated topublish
          publish(topic, topublish) # notify accumulated messages
          topublish = list() # empty out list

          # recompute sleep, since notification takes a while
          to_sleep_secs = compute_sleep_secs(obs_time)
          if to_sleep_secs > 0:
             logging.info('Sleeping {} seconds'.format(to_sleep_secs))
             time.sleep(to_sleep_secs)
       topublish.append(event_data)

   # left-over records; notify again
   publish(topic, topublish)

def peek_timestamp(ifp):
   # peek ahead to next line, get timestamp and go back
   pos = ifp.tell()
   line = ifp.readline()
   ifp.seek(pos)
   return get_timestamp(line)

if __name__ == '__main__':
   parser = argparse.ArgumentParser(description='Send sensor data to Cloud Pub/Sub in small groups, simulating real-time behavior')
   parser.add_argument('--speedFactor', help='Example: 60 implies 1 hour of data sent to Cloud Pub/Sub in 1 minute', required=True, type=float)
   args = parser.parse_args()

   # create Pub/Sub notification topic
   logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
   psclient = pubsub.Client()
   topic = psclient.topic(TOPIC)
   if not topic.exists():
      logging.info('Creating pub/sub topic {}'.format(TOPIC))
      topic.create()
   else:
      logging.info('Reusing pub/sub topic {}'.format(TOPIC))

   # notify about each line in the input file
   programStartTime = datetime.datetime.utcnow()
   with gzip.open(INPUT, 'rb') as ifp:
      header = ifp.readline()  # skip header
      firstObsTime = peek_timestamp(ifp)
      logging.info('Sending sensor data from {}'.format(firstObsTime))
      simulate(topic, ifp, firstObsTime, programStartTime, args.speedFactor)


问:
VSTS copy files to : filenames with variables
I am configuring VSTS build and release process.

I have a scenario where I have DEV and QA environments. I have different config files for each of the environments, think of the naming convention Test.Dev.Config
Test.QA.Config

In the "Copy files to" step of the build process, in the "contents" field, are you able to use the BuildConfiguration variable in order to tell the build process to copy the configuration files relevant to the BuildConfiguration:

so that the output of the package contains the Test.DEV.config files for the Dev build step and the Test.QA.config file for the QA build step.

I am basically testing out a options for config transforms in VSTS

答:
Using a VSO variable combined with a string literal often doesn't work as expected within a task like File Copy. Also, you don't want to do that in every task that requires build configuration specific config file. What you can do instead, is to have a separate variable in your build definition that derives from BuildConfiguration variable like so:

```<code>Variable              Value
BuildConfigFile    *.$(BuildConfiguration).config
</code>```

And then, within the File Copy task, you can directly use this variable as:

```<code>_PublishedWebsites\App_Config\$(BuildConfigFile)
</code>```

For more details on defining one variable in terms of the other, refer this SO post.

Body:
Using a VSO variable combined with a string literal often doesn't work as expected within a task like File Copy. Also, you don't want to do that in every task that requires build configuration specific config file. What you can do instead, is to have a separate variable in your build definition that derives from BuildConfiguration variable like so:

Variable              Value
BuildConfigFile    *.$(BuildConfiguration).config

And then, within the File Copy task, you can directly use this variable as:

_PublishedWebsites\App_Config\$(BuildConfigFile)

For more details on defining one variable in terms of the other, refer this SO post.


问:
Security Concerns About Building A Website
I am new in coding family ,so i am worry bit about things a coder should keep in mind as security concerns, so i come here hoping someone will help me.
i have learned all things which are necessary for building a website (Html,css,js,jquery,php,mysql).i know some basic tricks thanks to w3schools. but i need someone who can share his/her knowledge and practical experience, because i am really concern about security side.
i don,t want any security codes just things i should keep in mind.
Thanks in advance. </p>

答:
There are thousands of security problems and there respective solutions. I don't think all of those can be answered here.

But as you are a beginner here are few things that you should learn:

Server side vs Client side validation

SQL Injections

Cross-site request forgeries

Cross-site scripting

Protocols i.e HTTP and HTTPS

Authentications and authorizations

As I said earlier there are thousands and thousands of techniques to hack into your code and there solutions. All can't be mentioned here. It takes years to learn everything.

In some cases, the problems will apply to only your own use cases, for which you'll have to be open minded and think the solutions according to the use case while building your website.


问:
Vue Component not rendering vue-notify
I am using this library: https://github.com/cristijora/vue-notifyjs

The documentation on the above page states: component: {  //is rendered instead of notification message thus I am trying to give it dynamic component so I can handle custom events. This is my code:

```<code>Vue.use(vueNotifyjs)
new Vue({
  el: '#app',

  methods: {
    addNotification(verticalAlign = 'top', horizontalAlign = 'right') {
      this.$notify({
        component: function(){
            return {
            template: '<h1>Hello</h1>'
           };
        },
        horizontalAlign: horizontalAlign,
        verticalAlign: verticalAlign,
        type: "success"
      })
    }
  }
})
</code>```

This is my jsfiddle: https://jsfiddle.net/z11fe07p/2706/

But the word Hello is not getting rendered in the notify. Any ideas what am I missing?

答:
I think the component key should be have an instance of Vue Component.
In your scenario, create a vue component as follows

Vue.component('custom-message',{
            template:`<div>Hello World</div>`
         })

I have modified the fiddle with the above in this link.

Hope it helps

Title: Vue Component not rendering vue-notify

Body:
I am using this library: https://github.com/cristijora/vue-notifyjs

The documentation on the above page states: component: {  //is rendered instead of notification message thus I am trying to give it dynamic component so I can handle custom events. This is my code:

Vue.use(vueNotifyjs)
new Vue({
  el: '#app',

  methods: {
    addNotification(verticalAlign = 'top', horizontalAlign = 'right') {
      this.$notify({
        component: function(){
            return {
            template: '
Hello
'
           };
        },
        horizontalAlign: horizontalAlign,
        verticalAlign: verticalAlign,
        type: "success"
      })
    }
  }
})

This is my jsfiddle: https://jsfiddle.net/z11fe07p/2706/

But the word Hello is not getting rendered in the notify. Any ideas what am I missing?


问:
How do I delete the last row of a group in r based on conditions in a different row in r
I have a data frame like this (NT and MCS are text placeholders for a certain species let's say)

```<code>A <- c("NT", "MCS","MCS","NT", "MCS", "MCS", "NT", "MCS", "MCS", "MCS",
       "NT", "MCS", "MCS","NT", "MCS","NT","NT","MCS", "MCS","NT")
B <- c("1", "3", "3","3","3", "3","3","4","4","4","4","3",
       "3","3","2","2","1","3","3","3")
C <- c("G1", "G2", "G2", "G2", "G3", "G3", "G3", "G4", "G4", "G4", "G4",
       "G5", "G5", "G5","G6", "G6", "G7","G8","G8","G8")

df <- data.frame(A,B,C)

A   B   C
NT  1   G1
MCS 3   G2
MCS 3   G2
NT  3   G2
MCS 3   G3
MCS 3   G3
NT  3   G3
MCS 4   G4
MCS 4   G4
MCS 4   G4
NT  4   G4
MCS 3   G5
MCS 3   G5
NT  3   G5
MCS 2   G6
NT  2   G6
NT  1   G7
MCS 3   G8
MCS 3   G8
NT  3   G8
</code>```

The A column represents the species. The B column represents an integer value that equals the the number of rows in each group. C column represents unique groups. The criteria is as follows: Delete the LAST row of every group/species IF B > 1. If B = 1, then NT (or the only row in that group) should remain. Here is what I need it to look like.

```<code>A   B   C
NT  1   G1
MCS 3   G2
MCS 3   G2
MCS 3   G3
MCS 3   G3
MCS 4   G4
MCS 4   G4
MCS 4   G4
MCS 3   G5
MCS 3   G5
MCS 2   G6
NT  1   G7
MCS 3   G8
MCS 3   G8

new<- df %>% group_by(A, B) %>% slice(if(any(numb > 1)) 1:n())
</code>```

The above is the closest code I've run but it doesn't evaluate to an integer or numeric vector (which is what I need it to do). I did it like this:

```<code>new <- df %>% group_by(A, B) %>%
              slice(if(any(B > 1)) 1 else 1:n())
</code>```

but it got rid of the repeated values (so all the ones in column A I did not want to delete - not the last row regardless of repetition). Is there something I'm missing in the code I've run or another method that would accomplish this (ideally in dplyr but I'd be curious about all methods)?

答:
With dplyr, we can also do

```<code>library(dplyr)
df %>%
     group_by(C) %>%
     slice(union(1, head(seq_len(n()), -1)))
</code>```

Or with filter

```<code>df %>%
   group_by(C) %>%
   filter(row_number() != n() | n()==1)
</code>```

Body:
I have a data frame like this (NT and MCS are text placeholders for a certain species let's say)

A <- c("NT", "MCS","MCS","NT", "MCS", "MCS", "NT", "MCS", "MCS", "MCS",
       "NT", "MCS", "MCS","NT", "MCS","NT","NT","MCS", "MCS","NT")
B <- c("1", "3", "3","3","3", "3","3","4","4","4","4","3",
       "3","3","2","2","1","3","3","3")
C <- c("G1", "G2", "G2", "G2", "G3", "G3", "G3", "G4", "G4", "G4", "G4",
       "G5", "G5", "G5","G6", "G6", "G7","G8","G8","G8")

df <- data.frame(A,B,C)

A   B   C
NT  1   G1
MCS 3   G2
MCS 3   G2
NT  3   G2
MCS 3   G3
MCS 3   G3
NT  3   G3
MCS 4   G4
MCS 4   G4
MCS 4   G4
NT  4   G4
MCS 3   G5
MCS 3   G5
NT  3   G5
MCS 2   G6
NT  2   G6
NT  1   G7
MCS 3   G8
MCS 3   G8
NT  3   G8

The A column represents the species. The B column represents an integer value that equals the the number of rows in each group. C column represents unique groups. The criteria is as follows: Delete the LAST row of every group/species IF B > 1. If B = 1, then NT (or the only row in that group) should remain. Here is what I need it to look like.

A   B   C
NT  1   G1
MCS 3   G2
MCS 3   G2
MCS 3   G3
MCS 3   G3
MCS 4   G4
MCS 4   G4
MCS 4   G4
MCS 3   G5
MCS 3   G5
MCS 2   G6
NT  1   G7
MCS 3   G8
MCS 3   G8

new<- df %>% group_by(A, B) %>% slice(if(any(numb > 1)) 1:n())

The above is the closest code I've run but it doesn't evaluate to an integer or numeric vector (which is what I need it to do). I did it like this:

new <- df %>% group_by(A, B) %>%
              slice(if(any(B > 1)) 1 else 1:n())

but it got rid of the repeated values (so all the ones in column A I did not want to delete - not the last row regardless of repetition). Is there something I'm missing in the code I've run or another method that would accomplish this (ideally in dplyr but I'd be curious about all methods)?

Body:
With dplyr, we can also do

library(dplyr)
df %>%
     group_by(C) %>%
     slice(union(1, head(seq_len(n()), -1)))

Or with filter

df %>%
   group_by(C) %>%
   filter(row_number() != n() | n()==1)


问:
Regarding p2p connection and c#
i just want to know how two application interact with each other across the internet. how one send some message to other one because when IP is not fixed. please give me some coding tips by which a p2p apps connect other one across the internet when IP is not known.

please help me in detail.

答:
Before trying to get into implementation details and coding tips, you'd better learn how P2P networks work in general, what are possible architectures, and so on (start on http://en.wikipedia.org/wiki/Peer-to-peer). Your question is too wide to "help you in detail".

Edit:
To get in quicker, this can be handy: .NET P2P: Writing Peer-to-Peer Networked Apps with the Microsoft .NET Framework

Title: Regarding p2p connection and c#


问:
Improperly creating timestamped filenames
I'm using a raspberry pi and a python script to capture images from a camera connected to the pi. I have a task scheduler that calls the script, and the script make a command line call that interfaces with the camera. I'm trying to have it create a new file titled with the timestamp taken from python's datetime module.

The problem I'm experiencing is that it won't print both. I can create a file with just the date timestamp; I can create one with just the time. When I try to combine both, however, the file isn't created, and I'm not sure why. Is it because the filename ends up being too long?

I've tried numerous variations of the code below:

```<code>import os

import time
import datetime

ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d_%H:%M:%S")

sys_call = 'fswebcam -r 1280x720 /home/pi/python/projectx_images/%s' %st

os.system(sys_call)
</code>```

I've also tried using datetime.now() to no avail. Specifically, if I try either st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d') or st = datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S') then it works fine, but not with both.

答:
Perhaps using Python is overkill here. Since your task scheduler is probably already invoking a shell when it invokes Python, let's just have the shell do the work.

Use this command for your command scheduler:

```<code>fswebcam -r 1280x720 /home/pi/python/projectx_images/$(date +%Y-%m-%d_%H:%M:%S)
</code>```

Body:
I'm using a raspberry pi and a python script to capture images from a camera connected to the pi. I have a task scheduler that calls the script, and the script make a command line call that interfaces with the camera. I'm trying to have it create a new file titled with the timestamp taken from python's datetime module.

The problem I'm experiencing is that it won't print both. I can create a file with just the date timestamp; I can create one with just the time. When I try to combine both, however, the file isn't created, and I'm not sure why. Is it because the filename ends up being too long?

I've tried numerous variations of the code below:

import os

import time
import datetime

ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d_%H:%M:%S")

sys_call = 'fswebcam -r 1280x720 /home/pi/python/projectx_images/%s' %st

os.system(sys_call)

I've also tried using datetime.now() to no avail. Specifically, if I try either st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d') or st = datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S') then it works fine, but not with both.

Body:
Perhaps using Python is overkill here. Since your task scheduler is probably already invoking a shell when it invokes Python, let's just have the shell do the work.

Use this command for your command scheduler:

fswebcam -r 1280x720 /home/pi/python/projectx_images/$(date +%Y-%m-%d_%H:%M:%S)


问:
Parsing two messy numbers with .NET regex
I have an interesting dataset of numbers that I need to replace. How can I use .NET flavored regex (probably with a lookaround) to parse the first and second number from each row using the following algorithm:

Strings larger than 15 symbols that contain two numbers separated by the first occurrence of [\s\p{P}] after 7th symbol should be split in two. One regex should extract the first substring (containing numbers, spaces, punctuations). The second regex extracts the second half.

There is not much I can do about numbers that do not have a reasonably well defined separator. In example below the first 10 rows are subjects to be split. Strings that can't be split should be picked up by either of the two regex statements. No worries about \n; these strings are processed individually.

```<code>42977424427-77927299
62 92764949 44922672
96649274796/46262299
62-96247469,74292792
69227679/69267664
47694274/42929726
42977424427/77927299
97247-2666/7224-4767
89 3644-883436749503
78-99733017785-01627
967224267
6672-2222
97694629646797496
962 44776699
942 76699466
24796427466476967
99 98448999068440722
</code>```

So, the first regex would return:

```<code>42977424427
62 92764949
96649274796
62-96247469
69227679
47694274
42977424427
97247-2666
89 3644
78-99733017785
967224267
6672-2222
97694629646797496
962 44776699
942 76699466
24796427466476967
99 98448999068440722
</code>```

and the second regex statement would return

```<code>77927299
44922672
46262299
74292792
69267664
42929726
77927299
7224-4767
883436749503
01627
</code>```

Here is my (failing) attempt to extract the second group of numbers:

```<code>(?=[\d \p{P}]{15,})[\s\p{P}][\d\p{P}]{,8}
</code>```

答:
May be you can try this regex:

```<code>^(.{7}\d*)(?:[^\d\n](.*))?$
</code>```

Click fo Demo

Explanation:

^ - asserts the start of the string

(.{7}\d*) - matches 7 occurrences of any character but a newline character. This is followed by 0+ occurrences of a digit. This whole value is captured in Group 1

(?:[^\d\n](.*))? - matches a character that is niether a digit nor a newline. This is then followed by 0+ occurrences of any character but a newline character which is captured in Group2. ? at the end is to make this match optional

$ - asserts the end of the string

Another regex:

^([\d .,?!'":;_-]{7}\d*)(?:[^\d\n]([\d .,?!'":;_-]*))?$

Body:
I have an interesting dataset of numbers that I need to replace. How can I use .NET flavored regex (probably with a lookaround) to parse the first and second number from each row using the following algorithm:

Strings larger than 15 symbols that contain two numbers separated by the first occurrence of [\s\p{P}] after 7th symbol should be split in two. One regex should extract the first substring (containing numbers, spaces, punctuations). The second regex extracts the second half.

There is not much I can do about numbers that do not have a reasonably well defined separator. In example below the first 10 rows are subjects to be split. Strings that can't be split should be picked up by either of the two regex statements. No worries about \n; these strings are processed individually.

42977424427-77927299
62 92764949 44922672
96649274796/46262299
62-96247469,74292792
69227679/69267664
47694274/42929726
42977424427/77927299
97247-2666/7224-4767
89 3644-883436749503
78-99733017785-01627
967224267
6672-2222
97694629646797496
962 44776699
942 76699466
24796427466476967
99 98448999068440722

So, the first regex would return:

42977424427
62 92764949
96649274796
62-96247469
69227679
47694274
42977424427
97247-2666
89 3644
78-99733017785
967224267
6672-2222
97694629646797496
962 44776699
942 76699466
24796427466476967
99 98448999068440722

and the second regex statement would return

77927299
44922672
46262299
74292792
69267664
42929726
77927299
7224-4767
883436749503
01627

Here is my (failing) attempt to extract the second group of numbers:

(?=[\d \p{P}]{15,})[\s\p{P}][\d\p{P}]{,8}

Body:
May be you can try this regex:

^(.{7}\d*)(?:[^\d\n](.*))?$

Click fo Demo

Explanation:

^ - asserts the start of the string

(.{7}\d*) - matches 7 occurrences of any character but a newline character. This is followed by 0+ occurrences of a digit. This whole value is captured in Group 1

(?:[^\d\n](.*))? - matches a character that is niether a digit nor a newline. This is then followed by 0+ occurrences of any character but a newline character which is captured in Group2. ? at the end is to make this match optional

$ - asserts the end of the string

Another regex:

^([\d .,?!'":;_-]{7}\d*)(?:[^\d\n]([\d .,?!'":;_-]*))?$


问:
I am getting null when trying to select video from Google Photos
I am getting null when trying to select video from Google Photos.

It works if the video is also stored in your external memory but its not working,

if its only available on google photos. I tried many solutions but don't know how to accomplish this. Below is the class that i use to get the URI.

```<code>public class FilePath {
    private static final DecimalFormat format = new DecimalFormat("#.##");
    private static final long MiB = 1024 * 1024;
    private static final long KiB = 1024;

    public static String getPath(final Context context, String string) {
        return getPath(context, Uri.parse(string));
    }

    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static String getFileSize(File file) {

        if (!file.isFile()) {
            throw new IllegalArgumentException("Expected a file");
        }
        final double length = file.length();

        if (length > MiB) {
            return format.format(length / MiB) + " MB";
        }
        if (length > KiB) {
            return format.format(length / KiB) + " KB";
        }
        return format.format(length) + " B";
    }
}
</code>```

Thanks in advance.

答:
You have no permission to read the media from which Google Photo sends you a file I suppose. You have to use getContentResolver().openInputStream(uri) to open as an InputStream and show in your activity a photo which Google Photo sends you. Your code is unacceptable. Try to search SO for this topic. It was discussed a lot of times.

```<code>            Intent intent = getIntent();
            if (Intent.ACTION_SEND.equals(intent.getAction()){
                uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                if (uri != null) {
                    InputStream is = getContentResolver().openInputStream(uri);
                    long fileSize = is.available()
                    //Do some suff to show stream as a picture in the Activity
                }
            }
</code>```

This code works for me with last Google Photos app on Android 7.0 when picture is stored on the internal phone memory. If Google Photos keeps a desired file somewhere on a cloud you have to load data from is in the background thread to avoid Networking on main thread exception.

Body:
I am getting null when trying to select video from Google Photos.

It works if the video is also stored in your external memory but its not working,

if its only available on google photos. I tried many solutions but don't know how to accomplish this. Below is the class that i use to get the URI.

public class FilePath {
    private static final DecimalFormat format = new DecimalFormat("#.##");
    private static final long MiB = 1024 * 1024;
    private static final long KiB = 1024;

    public static String getPath(final Context context, String string) {
        return getPath(context, Uri.parse(string));
    }

    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static String getFileSize(File file) {

        if (!file.isFile()) {
            throw new IllegalArgumentException("Expected a file");
        }
        final double length = file.length();

        if (length > MiB) {
            return format.format(length / MiB) + " MB";
        }
        if (length > KiB) {
            return format.format(length / KiB) + " KB";
        }
        return format.format(length) + " B";
    }
}

Thanks in advance.

Body:
You have no permission to read the media from which Google Photo sends you a file I suppose. You have to use getContentResolver().openInputStream(uri) to open as an InputStream and show in your activity a photo which Google Photo sends you. Your code is unacceptable. Try to search SO for this topic. It was discussed a lot of times.

            Intent intent = getIntent();
            if (Intent.ACTION_SEND.equals(intent.getAction()){
                uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                if (uri != null) {
                    InputStream is = getContentResolver().openInputStream(uri);
                    long fileSize = is.available()
                    //Do some suff to show stream as a picture in the Activity
                }
            }

This code works for me with last Google Photos app on Android 7.0 when picture is stored on the internal phone memory. If Google Photos keeps a desired file somewhere on a cloud you have to load data from is in the background thread to avoid Networking on main thread exception.


答:
You can simply do this:

```<code>SELECT CAST(YearID * 100 + MonthID AS VARCHAR(6))
FROM mytable
</code>```

Note, we are using only one cast operation here and arithmetic operations only. No additional checks and functions are used.

Title: Concatenate in SQL Server 2008 R2 failing when the monthid is 2 digits

Body:
You can simply do this:

SELECT CAST(YearID * 100 + MonthID AS VARCHAR(6))
FROM mytable

Note, we are using only one cast operation here and arithmetic operations only. No additional checks and functions are used.


问:
javascript loop does not seem to work
I expected the code snippet to print out 100 times with the value of i.

But it prints out only once like below.

What am I missing here ?

let i = 0;
for (; i++; i < 100) {
  console.log('Loop ==>' + i);
}
console.log('Loop Done');
console.log('Value of i ==>' + i);```

答:
You have to write loop like below -</p>

```<code> <script>
    let i=0;
                        for(;i<100;i++)
                        {
                              console.log('Loop ==>'+i);
                        }
                        console.log('Loop Done');
                        console.log('Value of i ==>'+i);
    </script>
</code>```

Title: javascript loop does not seem to work

Body:
You have to write loop like below -

 <script>
    let i=0;
                        for(;i<100;i++)
                        {
                              console.log('Loop ==>'+i);
                        }
                        console.log('Loop Done');
                        console.log('Value of i ==>'+i);
    </script>


问:
What is correct syntax for arrays in powershell?
Example1:

Note 2: The comma is also used so
  separate items in an array {0,-30}

Example2:

To create an array, we create a
  variable and assign the array. Arrays
  are noted by the “@” symbol. Let’s
  take the discussion above and use an
  array to connect to multiple remote
  computers: $strComputers =
  @(“Server1″, “Server2″, “Server3″)

So, which one is correct or what is the difference ?

答:
Example 2 uses the array cast syntax which allows a single element, for example, to be treated as an array:

```<code>$myList = @("Hello")
</code>```

Essentially, it allows anything between the parenthesis to be treated as an array including the output from other commands:

```<code>$myArray = @(Get-Process Excel)
</code>```

Alternatively you can just create an array by specifying a comma separated list:

```<code>$myArray = "hello", "world", "again"
</code>```

(The curly brackets are not needed)

Body:
Example 2 uses the array cast syntax which allows a single element, for example, to be treated as an array:

$myList = @("Hello")

Essentially, it allows anything between the parenthesis to be treated as an array including the output from other commands:

$myArray = @(Get-Process Excel)

Alternatively you can just create an array by specifying a comma separated list:

$myArray = "hello", "world", "again"

(The curly brackets are not needed)


问:
Google Home App, cannot get OAUTH working properly
We are building a smart home app using actions on google for the google home. Our app requires signing into our system to be able to access the users devices so they can control them using their voice over google home. Our user backend is built using AWS Cognito. We are using API.AI as part of the Google Home app.

I have configured the Cognito OAUTH2 endpoint and the actions on google app to work with each other using the auth code flow and varying scope's but there is something I am missing. When I attempt to link the user account to the Google Home app i get redirected to our login page. After filling out the user details I'm returned to the Google Home 'Discover' tab but there is a message across the bottom that states: ‘Bad response from IdP in Auth Code Exchange’.

I also have tried it using Google's OAUTH2 playground. It seems that when using that I am able to get the code from our OATUH server, but when trying to exchange the code for a token i get the following error:

```<code>HTTP/1.1 400 Bad Request
Strict-transport-security: max-age=31536000 ; includeSubDomains
X-content-type-options: nosniff
X-application-context: application:prod:8443
Transfer-encoding: chunked
Set-cookie: XSRF-TOKEN=35f58337-76f4-4993-a0c9-93429134ea42; Path=/; Secure; HttpOnly
Expires: 0
Server: Server
Connection: keep-alive
X-amz-request-id: 284d862e-b021-4079-b5f5-3cbce675983c
X-xss-protection: 1; mode=block
Pragma: no-cache
Cache-control: no-cache, no-store, max-age=0, must-revalidate
Date: Wed, 23 Aug 2017 13:51:42 GMT
X-frame-options: DENY
Content-type: application/json;charset=UTF-8
{
  "error": "invalid_client"
}
</code>```

I have checked and rechecked the client ID and client secret etc and cannot find any errors.

Does anyone have any idea how I might fix this problem?

Thanks in advance

答:
ok，may be i know the reason.....If you  use  aws cognito ...
According to  this doc (http://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html)

Authorization
If the client was issued a secret, the client must pass its client_id and client_secret in the authorization header through Basic HTTP authorization. The secret is Basic Base64Encode(client_id:client_secret).

they need put client and client sectet  in header ...

Then I use aws http proxy caught the request of google progress .

```<code>Method request headers: {X-Cloud-Trace-Context=d7b6b9b8239965baf69acab659e80a01/13879251242019662389, CloudFront-Viewer-Country=US, CloudFront-Forwarded-Proto=https, CloudFront-Is-Tablet-Viewer=false, CloudFront-Is-Mobile-Viewer=false, User-Agent=google-oauth-playground AppEngine-Google; (+http://code.google.com/appengine; appid: s~oauth2playground), X-Forwarded-Proto=https, CloudFront-Is-SmartTV-Viewer=false, Host=en75z5h2rb.execute-api.us-east-1.amazonaws.com, Accept-Encoding=gzip, deflate, X-Forwarded-Port=443, X-Amzn-Trace-Id=Root=1-5a0fcef2-09197cd86a625ad47d78f0b7, Via=1.1 d63a8908759a2f4775b3f672ebf823cc.cloudfront.net (CloudFront), X-Amz-Cf-Id=nFdLK97vAS5HvmpNYkPpbUMOB4bCaM6pScHWTAReAnonLg1gXF7hSg==, X-Forwarded-For=107.178.195.199, 54.182.238.53, content-type=application/x-www-form-urlencoded, CloudFront-Is-Desktop-Viewer=true}
</code>```

There are no Authorization in request header. So the Cognito will return back

```<code>"error": "invalid_client"
</code>```

According this OAUTH2.0 spec (https://www.rfc-editor.org/rfc/rfc6749#section-2.3.1)

I have already ask AWS support. They said:

Thanks for contacting AWS Support and providing us with detailed references. I would be happy to assist with your question regarding Cognito supporting client credentials in the request-body.

After reading through the OAUTH2.0 Standards RFC 6749 [0], It looks like including the client credentials in the request-body is not recommended. Here's an excerpt on the spec:

"Including the client credentials in the request-body using the two parameters is not recommended and should be limited to clients unable to directly utilize the HTTP Basic authentication scheme (or other password-based HTTP authentication schemes)."

Body:
We are building a smart home app using actions on google for the google home. Our app requires signing into our system to be able to access the users devices so they can control them using their voice over google home. Our user backend is built using AWS Cognito. We are using API.AI as part of the Google Home app.

I have configured the Cognito OAUTH2 endpoint and the actions on google app to work with each other using the auth code flow and varying scope's but there is something I am missing. When I attempt to link the user account to the Google Home app i get redirected to our login page. After filling out the user details I'm returned to the Google Home 'Discover' tab but there is a message across the bottom that states: ‘Bad response from IdP in Auth Code Exchange’.

I also have tried it using Google's OAUTH2 playground. It seems that when using that I am able to get the code from our OATUH server, but when trying to exchange the code for a token i get the following error:

HTTP/1.1 400 Bad Request
Strict-transport-security: max-age=31536000 ; includeSubDomains
X-content-type-options: nosniff
X-application-context: application:prod:8443
Transfer-encoding: chunked
Set-cookie: XSRF-TOKEN=35f58337-76f4-4993-a0c9-93429134ea42; Path=/; Secure; HttpOnly
Expires: 0
Server: Server
Connection: keep-alive
X-amz-request-id: 284d862e-b021-4079-b5f5-3cbce675983c
X-xss-protection: 1; mode=block
Pragma: no-cache
Cache-control: no-cache, no-store, max-age=0, must-revalidate
Date: Wed, 23 Aug 2017 13:51:42 GMT
X-frame-options: DENY
Content-type: application/json;charset=UTF-8
{
  "error": "invalid_client"
}

I have checked and rechecked the client ID and client secret etc and cannot find any errors.

Does anyone have any idea how I might fix this problem?

Thanks in advance

Body:
ok，may be i know the reason.....If you  use  aws cognito ...
According to  this doc (http://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html)

Authorization
If the client was issued a secret, the client must pass its client_id and client_secret in the authorization header through Basic HTTP authorization. The secret is Basic Base64Encode(client_id:client_secret).

they need put client and client sectet  in header ...

Then I use aws http proxy caught the request of google progress .

Method request headers: {X-Cloud-Trace-Context=d7b6b9b8239965baf69acab659e80a01/13879251242019662389, CloudFront-Viewer-Country=US, CloudFront-Forwarded-Proto=https, CloudFront-Is-Tablet-Viewer=false, CloudFront-Is-Mobile-Viewer=false, User-Agent=google-oauth-playground AppEngine-Google; (+http://code.google.com/appengine; appid: s~oauth2playground), X-Forwarded-Proto=https, CloudFront-Is-SmartTV-Viewer=false, Host=en75z5h2rb.execute-api.us-east-1.amazonaws.com, Accept-Encoding=gzip, deflate, X-Forwarded-Port=443, X-Amzn-Trace-Id=Root=1-5a0fcef2-09197cd86a625ad47d78f0b7, Via=1.1 d63a8908759a2f4775b3f672ebf823cc.cloudfront.net (CloudFront), X-Amz-Cf-Id=nFdLK97vAS5HvmpNYkPpbUMOB4bCaM6pScHWTAReAnonLg1gXF7hSg==, X-Forwarded-For=107.178.195.199, 54.182.238.53, content-type=application/x-www-form-urlencoded, CloudFront-Is-Desktop-Viewer=true}

There are no Authorization in request header. So the Cognito will return back

"error": "invalid_client"

According this OAUTH2.0 spec (https://www.rfc-editor.org/rfc/rfc6749#section-2.3.1)

I have already ask AWS support. They said:

Thanks for contacting AWS Support and providing us with detailed references. I would be happy to assist with your question regarding Cognito supporting client credentials in the request-body.

After reading through the OAUTH2.0 Standards RFC 6749 [0], It looks like including the client credentials in the request-body is not recommended. Here's an excerpt on the spec:

"Including the client credentials in the request-body using the two parameters is not recommended and should be limited to clients unable to directly utilize the HTTP Basic authentication scheme (or other password-based HTTP authentication schemes)."

ContentLicense: CC BY-SA 4.0


问:
Heroku cannot find Go application
I'm having some trouble getting it detect the application binary.

For example, my project is called GoServer which is located in $GOPATH/src/GoServer and its binary (which was created by running go install in the project directory) is located in $GOPATH/bin/

Now if I try to run the instance locally using go run main.go it works just fine. If I run it locally using the Heroku Local toolkit (heroku local) it also works fine. BUT when it push to Heroku's remote repo and open the page from there, it crashes. In the logs it says that it could not find GoServer (bash: GoServer: command not found).

How can I fix this? Most of the similar issues threads I've seen refer to a misconfigured GOPATH but mine seems to be fine since Heroku Local works, but not the actual remote setup.

答:
The package in your glide.yaml is incorrect, change it to the package your code is in, that is GoServer. This is the package that gets installed by glide. Since this did not match the package (folder) of your code, GoServer did not get installed and was not available as an executable on heroku. It worked for you locally as you (or your IDE) compiled and installed GoServer and placed the executable into $GOPATH/bin, and so it could be run locally.

So the first line in glide.yaml should be:

```<code>package: GoServer
</code>```

Title: Heroku cannot find Go application

Body:
The package in your glide.yaml is incorrect, change it to the package your code is in, that is GoServer. This is the package that gets installed by glide. Since this did not match the package (folder) of your code, GoServer did not get installed and was not available as an executable on heroku. It worked for you locally as you (or your IDE) compiled and installed GoServer and placed the executable into $GOPATH/bin, and so it could be run locally.

So the first line in glide.yaml should be:

package: GoServer


问:
Thymeleaf How to add conditional block in javascript
I have a web application and using Thymeleaf with spring boot, I need to include an option in my javascript in-case the user locale was Arabic, so how add a conditional block and should be processed at server side?

```<code><script th:inline="javascript">
        var customerNameTitle = /*[[#{pendingPayments.customerName}]]*/ 'customer Name';
        var amountTitle = /*[[#{pendingPayments.amount}]]*/ 'Amount';
        var paymentDateTitle = /*[[#{pendingPayments.paymentDate}]]*/ 'payment Date';
        var submissionDateTitle = /*[[#{pendingPayments.submissionDate}]]*/ 'submission Date';

        $("document").ready(function(e) {
            /*<![CDATA[*/
               var table = $("#example").DataTable( {
                    "ajax": {
                                "url": /*[[@{/payments/getPendingPayments}]]*/ "",
                                "type": "GET",
                                "dataSrc": ""
                            },
                    "columns": [
                                { "data": "customerFullName", "title": customerNameTitle },
                                { "data": "amount", "title": amountTitle },
                                { "data": "paymentDate", "title": paymentDateTitle },
                                { "data": "submissionDate", "title": submissionDateTitle },
                            ],
                    "language": {
                                "emptyTable": /*[[#{pendingPayments.emptyTable}]]*/ "",
                                "url":/*[[@{'/json/dataTables-ar.json'}]]*/ ""
                              }
                });
            /*]]>*/
           });
    </script>
</code>```

the "url":/*[[@{'/json/dataTables-ar.json'}]]*/ should only be loaded if the locale is Arabic, otherwise the the whole line shouldn't be printed in HTML page..

in JSTL I can do that using <c:if>

```<code><c:if test="${LOCALE.language eq 'ar' }">
    ....
</c:if>
</code>```

is there an equivalent in Thymeleaf?

答:
Although, a old question, the following worked for us.</p>

```<code>    <script th:inline="javascript">
    /*<![CDATA[*/
      var isInlineEdit = [[${param.isInlineEdit} != null ? true:false]];

      if(isInlineEdit){
        //in line edit code
      }else{
        //no in line edit
      }
    /*]]>*/
    </script>
</code>```

Body:
I have a web application and using Thymeleaf with spring boot, I need to include an option in my javascript in-case the user locale was Arabic, so how add a conditional block and should be processed at server side?

the "url":/*[[@{'/json/dataTables-ar.json'}]]*/ should only be loaded if the locale is Arabic, otherwise the the whole line shouldn't be printed in HTML page..

in JSTL I can do that using <c:if>

<c:if test="${LOCALE.language eq 'ar' }">
    ....
</c:if>

is there an equivalent in Thymeleaf?

Body:
Although, a old question, the following worked for us.

    <script th:inline="javascript">
    /*<![CDATA[*/
      var isInlineEdit = [[${param.isInlineEdit} != null ? true:false]];

      if(isInlineEdit){
        //in line edit code
      }else{
        //no in line edit
      }
    /*]]>*/
    </script>