问:
Application Crashes when using Intent
My application crashes after trying to login.
i created navigationActivity as CHome which i want my user to be directed to. But it keeps crashing :

Unfortnately your app has stopped working.

But when i disabled this lines below it shows the Toast and no crash.

Help please

```<code>Toast.makeText(LoginActivity.this, "CUSTOMER",Toast.LENGTH_SHORT).show();

Intent cHome = new Intent(LoginActivity.this, CHome.class);
Common.currentUser = user;
startActivity(cHome);
finish();
</code>```

and i have my manifest here

my CHome is as follows

```<code>package com.example.oracle.eliteafro;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

//import com.example.oracle.eliteafro.Common.Common;
//import com.google.firebase.database.DatabaseReference;
//import com.google.firebase.database.FirebaseDatabase;

public class CHome extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    //Init Firebase
    //FirebaseDatabase database;
    //    DatabaseReference salons;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Menu");
        setSupportActionBar(toolbar);

        //Init Firebase
       // database = FirebaseDatabase.getInstance();
        //salons = database.getReference("el_af_salon");

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //set name for user
        View headerView = navigationView.getHeaderView(0);
        loginName = (TextView) findViewById(R.id.loginName);
        loginName.setText("Beedy");
        //loginName.setText(Common.currentUser.getFullname());

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.chome, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        //int id = item.getItemId();

//        if (id == R.id.nav_camera) {
//            // Handle the camera action
//        } else if (id == R.id.nav_gallery) {
//
//        } else if (id == R.id.nav_slideshow) {
//
//        } else if (id == R.id.nav_manage) {
//
//        } else if (id == R.id.nav_share) {
//
//        } else if (id == R.id.nav_send) {
//
//        }

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

答:
The problem is inside of your onCreate method for CHome, you are references a null TextView. So either, you forgot to call

```<code>TextView textView = findViewById(R.id.your_text_view_id);
</code>```

Or, maybe you did call that method but you passed in a id to a view that doensn't exist in your layout because findViewById will fail silently and return null instead of throughing an exception. So when you call setText() on the TextView you get a NullPointerexception.

Title: Application Crashes when using Intent

Body:
My application crashes after trying to login.
i created navigationActivity as CHome which i want my user to be directed to. But it keeps crashing :

Unfortnately your app has stopped working.

But when i disabled this lines below it shows the Toast and no crash.

Help please

Toast.makeText(LoginActivity.this, "CUSTOMER",Toast.LENGTH_SHORT).show();

Intent cHome = new Intent(LoginActivity.this, CHome.class);
Common.currentUser = user;
startActivity(cHome);
finish();

and i have my manifest here

my CHome is as follows

package com.example.oracle.eliteafro;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

//import com.example.oracle.eliteafro.Common.Common;
//import com.google.firebase.database.DatabaseReference;
//import com.google.firebase.database.FirebaseDatabase;

public class CHome extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    //Init Firebase
    //FirebaseDatabase database;
    //    DatabaseReference salons;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Menu");
        setSupportActionBar(toolbar);

        //Init Firebase
       // database = FirebaseDatabase.getInstance();
        //salons = database.getReference("el_af_salon");

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //set name for user
        View headerView = navigationView.getHeaderView(0);
        loginName = (TextView) findViewById(R.id.loginName);
        loginName.setText("Beedy");
        //loginName.setText(Common.currentUser.getFullname());

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.chome, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        //int id = item.getItemId();

//        if (id == R.id.nav_camera) {
//            // Handle the camera action
//        } else if (id == R.id.nav_gallery) {
//
//        } else if (id == R.id.nav_slideshow) {
//
//        } else if (id == R.id.nav_manage) {
//
//        } else if (id == R.id.nav_share) {
//
//        } else if (id == R.id.nav_send) {
//
//        }

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

Body:
The problem is inside of your onCreate method for CHome, you are references a null TextView. So either, you forgot to call

TextView textView = findViewById(R.id.your_text_view_id);

Or, maybe you did call that method but you passed in a id to a view that doensn't exist in your layout because findViewById will fail silently and return null instead of throughing an exception. So when you call setText() on the TextView you get a NullPointerexception.


来源: stackexchange

问:
c++ assign to pointer a pointer to constant
I have the following code:

```<code>class B{
    /*
    ...
    */
};
class A{
    B** elements;
    public:
        A operator+=(const B& b){
            // this->elements[0] = &b;

        }
        A(int number){
            this->elements = new B*[number];
        }
    /*
    ...
    */
};

int main(){
    A a(10);
    return 0;
}
</code>```

What I want is that the += operator should add the B object(operator's right side) to the A object's elements member.
So let's say I modify main to :

```<code>int main{
    A a(10);
    B b();
    a += b;
}
</code>```

After this a.elements[0] should be the b object.
I commented a line which is not working,but shows what I want.Uncommenting it gives the following error: invalid conversion from const B* to B*

The real code is much longer of course, it's enough if you show me how to make the += operator always assign the B object to A.elements[0], then I can edit my code as neccessary.

Thanks

答:
You have some serious issues with your design.

```<code>    A operator+=(const B& b){
        // this->elements[0] = &b;
</code>```

The idea here is to insert b into your collection, but your collection is little more than a pointer to some (unknown length) amount of raw memory.  You do not have a way to know if elements[x] exists in order to store &b.  For that matter, you don't know if elements exists at all.  You will need more bookkeeping to store lengths.

But worse, you pass a reference to a const B and take its address, storing that pointer in your collection.  What if the argument is a reference bound to a temporary?  (Rvalues can bind to const lvalue references).  In that case, the moment you've finished inserting the pointer into your collection the object it points to is destroyed.

That is assuming you work around your const-incorrectness, as you take a reference to a const b, take its address, and hope that it points to a non-const B.  It doesn't.  Casting it away can result in undefined behavior if b really points to an actually const object (and the non-const interface of b is used through your pointer.)

Your grow function leaks memory and loses the old elements.  Yes, it's pseudocode but too far from anything real to base ideas on.

There is a lot of really dangerous ideas in just a few lines.  Here are suggestions:

do not store raw pointers

even more strongly, do not store pointers obtained from reference arguments

make lifetime management easy; use smart pointers to show who owns the memory of passed-in objects

maintain const correctness.  If you take (smart) pointers to const objects, store them as (smart) pointers to const objects.

when you resize allocations allocations, worry about what happens to the old objects and memory.  Containers help reduce this effort.

use container classes instead of managing raw memory yourself and many of your problems vanish (but not the lifetime management issue of the arguments.)

ContentLicense: CC BY-SA 3.0

Body:
I have the following code:

class B{
    /*
    ...
    */
};
class A{
    B** elements;
    public:
        A operator+=(const B& b){
            // this->elements[0] = &b;

        }
        A(int number){
            this->elements = new B*[number];
        }
    /*
    ...
    */
};

int main(){
    A a(10);
    return 0;
}

What I want is that the += operator should add the B object(operator's right side) to the A object's elements member.
So let's say I modify main to :

int main{
    A a(10);
    B b();
    a += b;
}

After this a.elements[0] should be the b object.
I commented a line which is not working,but shows what I want.Uncommenting it gives the following error: invalid conversion from const B* to B*

The real code is much longer of course, it's enough if you show me how to make the += operator always assign the B object to A.elements[0], then I can edit my code as neccessary.

Thanks

Body:
You have some serious issues with your design.

    A operator+=(const B& b){
        // this->elements[0] = &b;

The idea here is to insert b into your collection, but your collection is little more than a pointer to some (unknown length) amount of raw memory.  You do not have a way to know if elements[x] exists in order to store &b.  For that matter, you don't know if elements exists at all.  You will need more bookkeeping to store lengths.

But worse, you pass a reference to a const B and take its address, storing that pointer in your collection.  What if the argument is a reference bound to a temporary?  (Rvalues can bind to const lvalue references).  In that case, the moment you've finished inserting the pointer into your collection the object it points to is destroyed.

That is assuming you work around your const-incorrectness, as you take a reference to a const b, take its address, and hope that it points to a non-const B.  It doesn't.  Casting it away can result in undefined behavior if b really points to an actually const object (and the non-const interface of b is used through your pointer.)

Your grow function leaks memory and loses the old elements.  Yes, it's pseudocode but too far from anything real to base ideas on.

There is a lot of really dangerous ideas in just a few lines.  Here are suggestions:

do not store raw pointers

even more strongly, do not store pointers obtained from reference arguments

make lifetime management easy; use smart pointers to show who owns the memory of passed-in objects

maintain const correctness.  If you take (smart) pointers to const objects, store them as (smart) pointers to const objects.

when you resize allocations allocations, worry about what happens to the old objects and memory.  Containers help reduce this effort.

use container classes instead of managing raw memory yourself and many of your problems vanish (but not the lifetime management issue of the arguments.)


问:
Java inheritance, generics and the byte-code
When a class in Java inherits another, does the inherited class become (physically) part of the inheriting class such that its byte-code is added to the .class file for the inheriting class? Or does the .class file for the inheriting class contain only the part specific to it and it's at run time that object details from the two .class files of both classes are built together into one object? If either or both classes was generic, would it have effect on the process? Thx.</p>

答:
When A extends B, then only that information is written into the class file for A.

There is no copying of code of any form from B.class to A.class. Meaning: when you change B, there is normally no need to recompile A.

And generics are mainly a compile time feature - any generic type turns into Object in bytecode (that is called type erasure). The class file contains a bit of meta information about which entities were declared as generic type, but thats all. In other words: Java generics are not the same thing as C++ templates.


问:
Kotlin Ternary Conditional Operator
What is the equivalent of this expression in Kotlin?

```<code>a ? b : c
</code>```

This is not valid code in Kotlin.

答:
With the following infix functions I can cover many common use cases pretty much the same way it can be done in Python : </p>

```<code>class TestKotlinTernaryConditionalOperator {

    @Test
    fun testAndOrInfixFunctions() {
        Assertions.assertThat(true and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat(false and "yes" or "no").isEqualTo("no")

        Assertions.assertThat("A" and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat("" and "yes" or "no").isEqualTo("no")

        Assertions.assertThat(1 and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat(0 and "yes" or "no").isEqualTo("no")

        Assertions.assertThat(Date() and "yes" or "no").isEqualTo("yes")
        @Suppress("CAST_NEVER_SUCCEEDS")
        Assertions.assertThat(null as Date? and "yes" or "no").isEqualTo("no")
    }
}

infix fun <E> Boolean?.and(other: E?): E? = if (this == true) other else null
infix fun <E> CharSequence?.and(other: E?): E? = if (!(this ?: "").isEmpty()) other else null
infix fun <E> Number?.and(other: E?): E? = if (this?.toInt() ?: 0 != 0) other else null
infix fun <E> Any?.and(other: E?): E? = if (this != null) other else null
infix fun <E> E?.or(other: E?): E? = this ?: other
</code>```

ContentLicense: CC BY-SA 4.0

Title: Kotlin Ternary Conditional Operator

Body:
What is the equivalent of this expression in Kotlin?

a ? b : c

This is not valid code in Kotlin.

Body:
With the following infix functions I can cover many common use cases pretty much the same way it can be done in Python :

class TestKotlinTernaryConditionalOperator {

    @Test
    fun testAndOrInfixFunctions() {
        Assertions.assertThat(true and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat(false and "yes" or "no").isEqualTo("no")

        Assertions.assertThat("A" and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat("" and "yes" or "no").isEqualTo("no")

        Assertions.assertThat(1 and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat(0 and "yes" or "no").isEqualTo("no")

        Assertions.assertThat(Date() and "yes" or "no").isEqualTo("yes")
        @Suppress("CAST_NEVER_SUCCEEDS")
        Assertions.assertThat(null as Date? and "yes" or "no").isEqualTo("no")
    }
}

infix fun <E> Boolean?.and(other: E?): E? = if (this == true) other else null
infix fun <E> CharSequence?.and(other: E?): E? = if (!(this ?: "").isEmpty()) other else null
infix fun <E> Number?.and(other: E?): E? = if (this?.toInt() ?: 0 != 0) other else null
infix fun <E> Any?.and(other: E?): E? = if (this != null) other else null
infix fun <E> E?.or(other: E?): E? = this ?: other


问:
SQL - Dateadd on working hours only?
I wonder if anyone could help?

I have a table that has the following columns

```<code>creationdate (datetime)
SLAhours (int)
</code>```

I want to create a column called completebydate which would be a dateadd function adding on the SLA hours to the creation date. However I only want it to count 9am to 5pm on the creation date table.

For example, if an SLAhour value is 9, and the create datetime is '01 sep 2017 12:30' then the completebydate would be '02 sep 2017 13:30" instead of '01 sep 2017 21:30'

Does this make sense? Is this easily doable?

答:
Yes this is doable. You can create a trigger on this new column completebydate and write you logic in the trigger. so the trigger will populate the date automatically if the other columns are inserted.

If you have large volume of records incoming trigger is not recommended option.

Title: SQL - Dateadd on working hours only?

Body:
I wonder if anyone could help?

I have a table that has the following columns

creationdate (datetime)
SLAhours (int)

I want to create a column called completebydate which would be a dateadd function adding on the SLA hours to the creation date. However I only want it to count 9am to 5pm on the creation date table.

For example, if an SLAhour value is 9, and the create datetime is '01 sep 2017 12:30' then the completebydate would be '02 sep 2017 13:30" instead of '01 sep 2017 21:30'

Does this make sense? Is this easily doable?


问:
Validate token using different server?
I'm using IdentityServer4 to secure some webapis.  Because of a quirk in our customer setup, we need to support a setup where we will have multiple applications running IdentityServer4 to issue tokens to different clients.  Those clients, however, will end up calling into some common services.

So those common services need to be able to validate a token from multiple instances of IdentityServer4.  Since you register an instance of IdentityServer with the resource server on startup, I thought as long as all of the IdentityServers sign the token in the same way, it will work.

I assumed that setting up IdentityServer to use a shared X509 cert would allow tokens from one IdentityServer to be verified on a resource server configured to use a different IdentityServer, but that does not seem to be the case.  Requesting a token from Server1, then submitting it to a resource server using Server2 does not work, even though they are all using the same cert.

Is there a way to make this work?

答:
Are you using JWT or Reference tokens?

Reference tokens are verified by the authority-holding Identity-server. It might be difficult to use different identity-servers and verify tokens supplied by another one than the one verifying it. If you are using JWT you can use the Discovery-Endpoint to capture the public key. Then you should be able to use this to verify the signature...

You can do this like:

```<code>            // Define the client to access the IdentityServer Discovery-Endpoint
            var discos = new DiscoveryClient(ConfigurationManager.AppSettings["IdentityserverLocation"]);
            var disco = await discos.GetAsync();

            // get the public key from the discovery-endpoint
            var keys = disco.KeySet.Keys;

            //Build the authorization request
            //param: Disco.AuthorizeEndpoint --> retrieves the authorization url from the identityserver
            var request = new AuthorizeRequest(disco.AuthorizeEndpoint);
            var url = request.CreateAuthorizeUrl(
                clientId: ConfigurationManager.AppSettings["ClientId"],
                responseType: "id_token",
                scope: "openid profile email",
                responseMode: OidcConstants.ResponseModes.FormPost,
                redirectUri: ConfigurationManager.AppSettings["RedirectUrl"],
                state: CryptoRandom.CreateUniqueId(),
                nonce: CryptoRandom.CreateUniqueId());

            //Try to initiate validation
            try
            {

                // Check if the token data exists in the request, parse is to a correct token
                var idToken = Request.Form.Get("id_token");
                JwtSecurityToken j = new JwtSecurityToken(idToken);
                var keylist = new List<SecurityKey>();
                foreach (var webKey in disco.KeySet.Keys)
                {
                    var exp = Base64Url.Decode(webKey.E);
                    var mod = Base64Url.Decode(webKey.N);
                    var key = new RsaSecurityKey(new RSAParameters() { Modulus = mod, Exponent = exp });
                    keylist.Add(key);
                }

                //define the parameters for validation of the token
                var parameters = new TokenValidationParameters
                {
                    ValidIssuer = disco.Issuer,
                    ValidAudience = "viper",
                    IssuerSigningKeys = keylist,
                };

                var handler = new JwtSecurityTokenHandler();
                handler.InboundClaimTypeMap.Clear();

                //validate the token using the defined parameters, return the token when validation is succesful
                var user = handler.ValidateToken(j.RawData, parameters, out var validatedtoken);
</code>```

Title: Validate token using different server?

Body:
Are you using JWT or Reference tokens?

Reference tokens are verified by the authority-holding Identity-server. It might be difficult to use different identity-servers and verify tokens supplied by another one than the one verifying it. If you are using JWT you can use the Discovery-Endpoint to capture the public key. Then you should be able to use this to verify the signature...

You can do this like:

            // Define the client to access the IdentityServer Discovery-Endpoint
            var discos = new DiscoveryClient(ConfigurationManager.AppSettings["IdentityserverLocation"]);
            var disco = await discos.GetAsync();

            // get the public key from the discovery-endpoint
            var keys = disco.KeySet.Keys;

            //Build the authorization request
            //param: Disco.AuthorizeEndpoint --> retrieves the authorization url from the identityserver
            var request = new AuthorizeRequest(disco.AuthorizeEndpoint);
            var url = request.CreateAuthorizeUrl(
                clientId: ConfigurationManager.AppSettings["ClientId"],
                responseType: "id_token",
                scope: "openid profile email",
                responseMode: OidcConstants.ResponseModes.FormPost,
                redirectUri: ConfigurationManager.AppSettings["RedirectUrl"],
                state: CryptoRandom.CreateUniqueId(),
                nonce: CryptoRandom.CreateUniqueId());

            //Try to initiate validation
            try
            {

                // Check if the token data exists in the request, parse is to a correct token
                var idToken = Request.Form.Get("id_token");
                JwtSecurityToken j = new JwtSecurityToken(idToken);
                var keylist = new List<SecurityKey>();
                foreach (var webKey in disco.KeySet.Keys)
                {
                    var exp = Base64Url.Decode(webKey.E);
                    var mod = Base64Url.Decode(webKey.N);
                    var key = new RsaSecurityKey(new RSAParameters() { Modulus = mod, Exponent = exp });
                    keylist.Add(key);
                }

                //define the parameters for validation of the token
                var parameters = new TokenValidationParameters
                {
                    ValidIssuer = disco.Issuer,
                    ValidAudience = "viper",
                    IssuerSigningKeys = keylist,
                };

                var handler = new JwtSecurityTokenHandler();
                handler.InboundClaimTypeMap.Clear();

                //validate the token using the defined parameters, return the token when validation is succesful
                var user = handler.ValidateToken(j.RawData, parameters, out var validatedtoken);


问:
Displaying a toast from a Service
I have a service running with a background thread polling for XMPP messages. I want to issue
a toast from the Thread. Previous stackoverflow questions have dealt with this by using the runOnUiThread Activity method, however this is not available in a Service. My question is what is the suggested method in a Service?
Many thanks in advance </p>

答:
You could try to callbacks similar to the example at http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html. Specifically see the section starting with the comment</p>

```<code>/**
 * Our Handler used to execute operations on the main thread.  This is used
 * to schedule increments of our value.
 */
</code>```

ContentLicense: CC BY-SA 2.5

Title: Displaying a toast from a Service

Body:
You could try to callbacks similar to the example at http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html. Specifically see the section starting with the comment

/**
 * Our Handler used to execute operations on the main thread.  This is used
 * to schedule increments of our value.
 */


问:
Getting specific row from a list fails
This is the API output:

```<code>{
    "resultLength":133710,
    "resultList" : [
            {
            "date" :  1510872659568,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9b6b6"
            ],
            "score" :  1,
            "totalRequestTime" :  1261,
            "userId" :  167895
            },
            {
            "date" :  1510872659679,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9be78"
            ],
            "score" :  1,
            "totalRequestTime" :  1255,
            "userId" :  452669
            }
    ]
}
</code>```

I am trying to extract the requestId for each userId, however for some reason I am not able to. This is what I tried:

```<code>req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']

solr_df = pd.DataFrame()
for record in results:
    requestId = pd.DataFrame(record['requestParameters'][3],columns=['requestId'])
    df = pd.DataFrame(requestId)
    df['userId'] = record['userId']
    solr_df = solr_df.append(df)
</code>```

However it throws a ValueError: DataFrame constructor not properly called!
Can you assist with rectifying the error?

If it too hard to only extract the requestId row for each requestParameter, perhaps you can assist instead removing all rows that aren't requestId related after the for statement runs?

Edit:

When I run it for record['requestParameters'], it runs succesfully but it extracts all rows of requestParameters per userId.

I just tried slicing as such: portfolioId = pd.DataFrame(record['requestParameters'][-1:0]) and it did return results (unlike a single index call), however it was for both outputFormat and requestId rows.
I then tried portfolioId = pd.DataFrame(record['requestParameters'][1:2]) and it returned results for both requestId and datesAsStrings.

It looks like requestParameters rows are not indexed consistently (not sure why it is possible), is there still a way to get a specific row from a list?

Thank you

答:
I was able to answer my own question; because the rows in requestParameters are not properly indexed (an explanation as to why that can happen would be great), I had to extract all rows from requestParamters, filter only for those including requestId, and then extracting everything after "=".</p>

```<code>solr_df = pd.DataFrame()
for record in results:
    df = pd.DataFrame(record['requestParameters'],columns=['requestId'])
    df['userEmail'] = record['userEmail']
    solr_df = solr_df.append(df)

solr_df = solr_df[solr_df.requestId.str.contains('requestId')]
solr_df['requestId'] = solr_df['requestId'].str.split('=').str.get(1)
</code>```

Title: Getting specific row from a list fails

Body:
This is the API output:

{
    "resultLength":133710,
    "resultList" : [
            {
            "date" :  1510872659568,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9b6b6"
            ],
            "score" :  1,
            "totalRequestTime" :  1261,
            "userId" :  167895
            },
            {
            "date" :  1510872659679,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9be78"
            ],
            "score" :  1,
            "totalRequestTime" :  1255,
            "userId" :  452669
            }
    ]
}

I am trying to extract the requestId for each userId, however for some reason I am not able to. This is what I tried:

req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']

solr_df = pd.DataFrame()
for record in results:
    requestId = pd.DataFrame(record['requestParameters'][3],columns=['requestId'])
    df = pd.DataFrame(requestId)
    df['userId'] = record['userId']
    solr_df = solr_df.append(df)

However it throws a ValueError: DataFrame constructor not properly called!
Can you assist with rectifying the error?

If it too hard to only extract the requestId row for each requestParameter, perhaps you can assist instead removing all rows that aren't requestId related after the for statement runs?

Edit:

When I run it for record['requestParameters'], it runs succesfully but it extracts all rows of requestParameters per userId.

I just tried slicing as such: portfolioId = pd.DataFrame(record['requestParameters'][-1:0]) and it did return results (unlike a single index call), however it was for both outputFormat and requestId rows.
I then tried portfolioId = pd.DataFrame(record['requestParameters'][1:2]) and it returned results for both requestId and datesAsStrings.

It looks like requestParameters rows are not indexed consistently (not sure why it is possible), is there still a way to get a specific row from a list?

Thank you

Body:
I was able to answer my own question; because the rows in requestParameters are not properly indexed (an explanation as to why that can happen would be great), I had to extract all rows from requestParamters, filter only for those including requestId, and then extracting everything after "=".

solr_df = pd.DataFrame()
for record in results:
    df = pd.DataFrame(record['requestParameters'],columns=['requestId'])
    df['userEmail'] = record['userEmail']
    solr_df = solr_df.append(df)

solr_df = solr_df[solr_df.requestId.str.contains('requestId')]
solr_df['requestId'] = solr_df['requestId'].str.split('=').str.get(1)


问:
EF6 best practice for loading not mapped fields of an entity tracked by the context
Considering the blogging data model:

```<code>Blog:
int Id
ICollection<Post> Posts

Post:
int Id
int BlogId
DateTime Date
</code>```

Then loading Blogs with the date of their latest post (LatestPostDate) and bind to the UI, while they are tracked by the context.

There are some solutions, such as using DTO, but the result entities are not tracked by the context.
Also I can set the LatestPostDate as NotMapped, define a Table-valued function, and apply SqlQuery on DbSet. Although, the NotMapped fields are not loaded in this way.

What are the best practices?

I try not to add column to the table, also avoid calculating the values after loading.

答:
Best practice would be to handle display concerns in a ViewModel.

But as you do not want to map the Entity to another class, let's first take a look at the [NotMapped] variant, using LINQ to calculate the latest post date instead of plain SQL.

```<code>using System.Linq;

public class Blog {
    public int Id { get; set; }
    public virtual ICollection<Post> Posts { get; set; }

    [NotMapped]
    public DateTime? LatestPostDate {
        get {
            return Posts.OrderBy(p => p.Date).LastOrDefault()?.Date;
        }
    }
}
</code>```

This way, the value is calculated only when you access the property LatestPostDate (probably during UI rendering). You can reduce the number of DB accesses by eager loading the Posts, although this will increase the size of the data set you are working with.

```<code>var blogs = _dbContext.Blogs.Include(b => b.Posts).ToArray();
</code>```

But if you use a ViewModel, you can fill the LatestPostDate in one go:

```<code>public class BlogViewModel {
    public int Id { get; set; }
    public DateTime? LatestPostDate { get; set; }
}

var viewModels = _dbContext.Blogs.Select(b => new BlogViewModel {
    Id = b.Id,
    LatestPostDate = b.Posts.OrderBy(p => p.Date).LastOrDefault()?.Date;
}).ToArray();
</code>```

Regarding your concerns that the ViewModel is not tracked by the context: in the edit usecase, load the Entity again using the Id provided by the ViewModel and map the updated properties. This gives you full control over the properties that should be editable. As a bonus, the ViewModel is a good place to do input validation, formatting etc.

Body:
Considering the blogging data model:

Blog:
int Id
ICollection<Post> Posts

Post:
int Id
int BlogId
DateTime Date

Then loading Blogs with the date of their latest post (LatestPostDate) and bind to the UI, while they are tracked by the context.

There are some solutions, such as using DTO, but the result entities are not tracked by the context.
Also I can set the LatestPostDate as NotMapped, define a Table-valued function, and apply SqlQuery on DbSet. Although, the NotMapped fields are not loaded in this way.

What are the best practices?

I try not to add column to the table, also avoid calculating the values after loading.

Body:
Best practice would be to handle display concerns in a ViewModel.

But as you do not want to map the Entity to another class, let's first take a look at the [NotMapped] variant, using LINQ to calculate the latest post date instead of plain SQL.

using System.Linq;

public class Blog {
    public int Id { get; set; }
    public virtual ICollection<Post> Posts { get; set; }

    [NotMapped]
    public DateTime? LatestPostDate {
        get {
            return Posts.OrderBy(p => p.Date).LastOrDefault()?.Date;
        }
    }
}

This way, the value is calculated only when you access the property LatestPostDate (probably during UI rendering). You can reduce the number of DB accesses by eager loading the Posts, although this will increase the size of the data set you are working with.

var blogs = _dbContext.Blogs.Include(b => b.Posts).ToArray();

But if you use a ViewModel, you can fill the LatestPostDate in one go:

public class BlogViewModel {
    public int Id { get; set; }
    public DateTime? LatestPostDate { get; set; }
}

var viewModels = _dbContext.Blogs.Select(b => new BlogViewModel {
    Id = b.Id,
    LatestPostDate = b.Posts.OrderBy(p => p.Date).LastOrDefault()?.Date;
}).ToArray();

Regarding your concerns that the ViewModel is not tracked by the context: in the edit usecase, load the Entity again using the Id provided by the ViewModel and map the updated properties. This gives you full control over the properties that should be editable. As a bonus, the ViewModel is a good place to do input validation, formatting etc.


问:
jQuery - wait for image to load before changing background
There are lots of example of similar functionality on-line, but none seem to work for me. What I currently have is

```<code><img id="sample_image" src="sample_image.png" alt="">
<script>
$('#sample_image').on('load',function(){
    $("#sample_image").css("background", "#ff0000");
});
</script>
</code>```

I expected the image to load/show before the background color is changed, but what happens is you see the red background before the image is loaded.

I tried setting the src using jQuery...

```<code><img id="sample_image" src="" alt="">
<script>
$('#sample_image').attr("src", "sample_image.png").on('load',function(){
    $("#sample_image").css("background", "<%=strRGB%>");
});
</script>
</code>```

But this did the same.

What am I doing wrong?

Thanks

答:
I'm not sure about the load method you are using for whether it's for the element or the image.

You can create a Image object and check for the onload

```<code>var img = new Image();
img.onload = function(){
    //change the attr here
}
</code>```

Body:
There are lots of example of similar functionality on-line, but none seem to work for me. What I currently have is

I expected the image to load/show before the background color is changed, but what happens is you see the red background before the image is loaded.

I tried setting the src using jQuery...

But this did the same.

What am I doing wrong?

Thanks

Body:
I'm not sure about the load method you are using for whether it's for the element or the image.

You can create a Image object and check for the onload

var img = new Image();
img.onload = function(){
    //change the attr here
}


问:
Javascript Chart Library with zoom and large data support
Would anyone recommend a particular JavaScript charting library with zoom functionality, supporting large size data around 2,50,000/250K plotting points at once.

open source would be recommended.

答:
Check the dyGraphs for this purpose. Have a look at the way it zooms:

http://dygraphs.com/tests/zoom.html


问:
How to test my blocking queue actually blocks
I have a blocking queue (it would be really hard for me to change its implementation), and I want to test that it actually blocks. In particular, the pop methods must block if the queue is empty and unblock as soon as a push is performed. See the following pseudo C++11 code for the test:

```<code>BlockingQueue queue; // empty queue

thread pushThread([]
{
    sleep(large_delay);
    queue.push();
});

queue.pop();
</code>```

Obviously it is not perfect, because it may happen that the whole thread pushThread is executed and terminates before pop is called, even if the delay is large, and the larger the delay the more I have to wait for the test being over.

How can I properly ensure that pop is executed before push is called and that is blocks until push returns?

答:
You can use a std::condition_variable to accomplish this. The help page of cppreference.com actually shows a very nice cosumer-producer example which should be exactly what you are looking for: http://en.cppreference.com/w/cpp/thread/condition_variable

EDIT: Actually the german version of cppreference.com has an even better example :-) http://de.cppreference.com/w/cpp/thread/condition_variable

Body:
I have a blocking queue (it would be really hard for me to change its implementation), and I want to test that it actually blocks. In particular, the pop methods must block if the queue is empty and unblock as soon as a push is performed. See the following pseudo C++11 code for the test:

BlockingQueue queue; // empty queue

thread pushThread([]
{
    sleep(large_delay);
    queue.push();
});

queue.pop();

Obviously it is not perfect, because it may happen that the whole thread pushThread is executed and terminates before pop is called, even if the delay is large, and the larger the delay the more I have to wait for the test being over.

How can I properly ensure that pop is executed before push is called and that is blocks until push returns?


问:
Order of Select2 selection based on array of items
I'm trying to set the order of selected items in Select2 based on an array.

A simple solution has already been proposed to append items in the order with which they are clicked in the dropdown menu (see 2rba's answer on 2017-10-26 in this discussion):

```<code>        $("#selectCriteria").on("select2:select", function (evt) {
          var element = evt.params.data.element;
          var $element = $(element);
          $element.detach();
          $(this).append($element);
          $(this).trigger("change");
    });
</code>```

What I'm trying to do is mimick this behavior, but when passing an array of the selected items instead of manually clicking them in the list. I tried the following command:

```<code>displayed_items = ["b", "c", "a"];
$('#selectCriteria').val(displayed_items).trigger('change');
</code>```

But the order isn't preserved. I tried looping the command with one element at a time, but each new call overwrites the previous element:

```<code> $('#selectCriteria').val("b").trigger('change');
 $('#selectCriteria').val("c").trigger('change');
 $('#selectCriteria').val("a").trigger('change');
</code>```

I see two possible solutions to this, but lack the background to make them work:

How should the iteration above be adapted to not overwrite the previously added
value?

How could I incorporate the approach shown in this
fiddle (from vol7ron's posts on github) which does pretty
much what I'm asking (i.e. toggling on/off the
.data('preserved-order',selected))? As it is using JSX I'm
not sure how I could reuse that script in my plain JS/jQuery script.

答:
here you go

EDIT:

this is not the prettiest solution, but it gets the job done.

you would have to call initSelect function that takes an array of values as a parameter. i left some comments in the code.

displayed_items = $('#selected_items').val().split(',');

function selectItem(target, id) { // refactored this a bit, don't pay attention to this being a function
  var option = $(target).children('[value='+id+']');
  option.detach();
  $(target).append(option).change();
}

function customPreSelect() {
  let items = $('#selected_items').val().split(',');
  $("select").val('').change();
  initSelect(items);
}

function initSelect(items) { // pre-select items
  items.forEach(item => { // iterate through array of items that need to be pre-selected
    let value = $('select option[value='+item+']').text(); // get items inner text
    $('select option[value='+item+']').remove(); // remove current item from DOM
    $('select').append(new Option(value, item, true, true)); // append it, making it selected by default
  });
}

$('select').select2();
$('select').on('select2:select', function(e){
  selectItem(e.target, e.params.data.id);
});

initSelect(displayed_items); // call init```
<pre class="snippet-code-css lang-css prettyprint-override"><code>select {
  width: 50%;
}

.container {
  display: flex;
  flex-direction: column;
}

.control-group {
  padding-bottom: 1em;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />

Provide comma separated items to be pre selected and click the button

    <input id="selected_items" value="b,c,a"/>
    <button onclick="customPreSelect()">Init</button>

  <select multiple="multiple">
    <option value="a">A</option>
    <option value="b" >B</option>
    <option value="c">C</option>
    <option value="d">D</option>
  </select>

```

Body:
I'm trying to set the order of selected items in Select2 based on an array.

A simple solution has already been proposed to append items in the order with which they are clicked in the dropdown menu (see 2rba's answer on 2017-10-26 in this discussion):

        $("#selectCriteria").on("select2:select", function (evt) {
          var element = evt.params.data.element;
          var $element = $(element);
          $element.detach();
          $(this).append($element);
          $(this).trigger("change");
    });

What I'm trying to do is mimick this behavior, but when passing an array of the selected items instead of manually clicking them in the list. I tried the following command:

displayed_items = ["b", "c", "a"];
$('#selectCriteria').val(displayed_items).trigger('change');

But the order isn't preserved. I tried looping the command with one element at a time, but each new call overwrites the previous element:

 $('#selectCriteria').val("b").trigger('change');
 $('#selectCriteria').val("c").trigger('change');
 $('#selectCriteria').val("a").trigger('change');

I see two possible solutions to this, but lack the background to make them work:

How should the iteration above be adapted to not overwrite the previously added
value?

How could I incorporate the approach shown in this
fiddle (from vol7ron's posts on github) which does pretty
much what I'm asking (i.e. toggling on/off the
.data('preserved-order',selected))? As it is using JSX I'm
not sure how I could reuse that script in my plain JS/jQuery script.

Body:
here you go

EDIT:

this is not the prettiest solution, but it gets the job done.

you would have to call initSelect function that takes an array of values as a parameter. i left some comments in the code.

displayed_items = $('#selected_items').val().split(',');

function selectItem(target, id) { // refactored this a bit, don't pay attention to this being a function
  var option = $(target).children('[value='+id+']');
  option.detach();
  $(target).append(option).change();
}

function customPreSelect() {
  let items = $('#selected_items').val().split(',');
  $("select").val('').change();
  initSelect(items);
}

function initSelect(items) { // pre-select items
  items.forEach(item => { // iterate through array of items that need to be pre-selected
    let value = $('select option[value='+item+']').text(); // get items inner text
    $('select option[value='+item+']').remove(); // remove current item from DOM
    $('select').append(new Option(value, item, true, true)); // append it, making it selected by default
  });
}

$('select').select2();
$('select').on('select2:select', function(e){
  selectItem(e.target, e.params.data.id);
});

initSelect(displayed_items); // call init

select {
  width: 50%;
}

.container {
  display: flex;
  flex-direction: column;
}

.control-group {
  padding-bottom: 1em;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>

<div class="container">

  <p>Provide comma separated items to be pre selected and click the button</p>
  <div class="control-group">
    <input id="selected_items" value="b,c,a"/>
    <button onclick="customPreSelect()">Init</button>
  </div>

  <select multiple="multiple">
    <option value="a">A</option>
    <option value="b" >B</option>
    <option value="c">C</option>
    <option value="d">D</option>
  </select>
</div>


问:
XML deserialization on android using Simple API
Can anyone give me a link of a tutorial(specially a simple project which deserialize a XML on android using Simple API. I need this badly.</p>

答:
Simple API works fine on Android, and it does not require any configuration. Just:

Place the Simple jar in the libs directory

Configure your Build Path to include that jar

Enjoy. You can take a look at the samples if you haven't yet: http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php


问:
Get data attribute in javascript like jQuery and split it into two values?
I found this nice script from here to calculate the distance between me and other locations.

Script:

```<code>function distance(lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = (lat2-lat1).toRad();  // Javascript functions in radians
  var dLon = (lon2-lon1).toRad();
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
          Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}

window.navigator.geolocation.getCurrentPosition(function(pos) {
    console.log(pos);
    console.log(
        distance(pos.coords.latitude, pos.coords.longitude, lat2, lon2)
  );
});
</code>```

My HTML looks like this:

```<code><div class="map" data-latLng="86.55,79.66">Distance:<i></i></div>
<div class="map" data-latLng="96.55,89.66">Distance:<i></i></div>
<div class="map" data-latLng="116.55,179.66">Distance:<i></i></div>
</code>```

At "[i]" I want to show the distance. So, my problems are:

so far I only work with jQuery, how can I get the [data-latLng] by "var", something like "var lat2 = $("div").attr("data-latLng");" seemes not to work in javascript?

how can I split the "data-latLng" into "lat2" and "lon2" for the function?

is there any ".each" function for javascript to do this for all my loactions?

答:
This will get you the locations from the elements, split them, put them into an object and then push them to an array for you to use.

var locations = []

$(".map").each(function(index, map) {
  var latLngArray = $(map).data("latlng").split(",")
  var latLng = {
    lat: Number(latLngArray[0]),
    lng: Number(latLngArray[1])
  }
  locations.push(latLng)

})

console.log(locations)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Distance:

Distance:

Distance:
```

Body:
I found this nice script from here to calculate the distance between me and other locations.

Script:

function distance(lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = (lat2-lat1).toRad();  // Javascript functions in radians
  var dLon = (lon2-lon1).toRad();
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
          Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}

window.navigator.geolocation.getCurrentPosition(function(pos) {
    console.log(pos);
    console.log(
        distance(pos.coords.latitude, pos.coords.longitude, lat2, lon2)
  );
});

My HTML looks like this:

Distance:

Distance:

Distance:

At "[i]" I want to show the distance. So, my problems are:

so far I only work with jQuery, how can I get the [data-latLng] by "var", something like "var lat2 = $("div").attr("data-latLng");" seemes not to work in javascript?

how can I split the "data-latLng" into "lat2" and "lon2" for the function?

is there any ".each" function for javascript to do this for all my loactions?

Body:
This will get you the locations from the elements, split them, put them into an object and then push them to an array for you to use.

var locations = []

$(".map").each(function(index, map) {
  var latLngArray = $(map).data("latlng").split(",")
  var latLng = {
    lat: Number(latLngArray[0]),
    lng: Number(latLngArray[1])
  }
  locations.push(latLng)

})

console.log(locations)

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="map" data-latLng="86.55,79.66">Distance:<i></i></div>
<div class="map" data-latLng="96.55,89.66">Distance:<i></i></div>
<div class="map" data-latLng="116.55,179.66">Distance:<i></i></div>


问:
Accents with python
I would like to know how to keep the accents in python, and if we could explain to myself a little about how it works, I spend hours searching. I still do not understand anything x)

Example 1:

```<code>text = "Danay Suarèz hablé"
print(text)
</code>```

output:

```<code>Danay Suar▒z habl▒
</code>```

Example 2:

```<code>print(text.encode('utf-8'))
</code>```

output:

```<code> b'Danay Suar\xc3\xa8z habl\xc3\xa9'
</code>```

I would like just output: Danay Suarèz hablé

答:
Computers work in bits, so sequences of ones and zeros (how they are physically stored is another story). Integers are normally saved as 16 ones and zeros, so a 51 = 00000000 00110011. Because that is pretty long we normally write that in hexadecimal, so 2 dec = 00 33 hex. But not only numbers are saved as bits, characters (and basically everything else) is also. While we can "naturally" encode integers in bits (binary) other datatypes are harder. For characters the "normal" way is ASCII, which just maps "randomly" byte sequences to characters. In ASCII 00 33 = "3".

But ASCII only declares 128 (7 bit) different characters. That is just enough for english plus some extra characters, but for other languages that is not enough. So people created lots of encodings, mostly for what characters they used for their language. So while ASCII says 00 33 = "3", other encodings could say 00 33 = "ü" or whatever. Most encodings that one encounters actually agree with ASCII on the first 128 characters but extend it.

Your sys.stdout.encoding says it is UTF8 so python takes your è and translates it to the bytes C3 A8. Now your command line codepage is 850, better known as latin1. In latin1 C3 A8 should be Ã¨ (which is not what you see, so maybe I did an error in the translations somewhere or maybe your terminal does not have a font which can display that) which is different from UTF8.

But how does one fix that? Either tell your command line to use UTF8 or tell python to use latin1. You should be able to change the command line encoding to UF8 by typing chcp 65001 before you execute your script.

If you use print(text.encode('utf-8')) python tries to show a human readable version of the bytes that this object consists of. It will interpret the bytes as ASCII where possible and just show the raw bits where not. So \xc3\xa8 means the bytes c3 a8. But of course if you actually print that it will transmit these signs in UTF8 to your terminal, but because on the ASCII range UTF8 and latin1 do agree, your terminal interprets these characters correctly.

Title: Accents with python

Body:
I would like to know how to keep the accents in python, and if we could explain to myself a little about how it works, I spend hours searching. I still do not understand anything x)

Example 1:

text = "Danay Suarèz hablé"
print(text)

output:

Danay Suar▒z habl▒

Example 2:

print(text.encode('utf-8'))

output:

 b'Danay Suar\xc3\xa8z habl\xc3\xa9'

I would like just output: Danay Suarèz hablé


问:
How to convert miliseconds to hh mm ss format in Oracle
I have a Database table having a column 'time' which has milliseconds stored. I need to convert that in hours:minutes:seconds format.
Can anyone please help how to do that? I think it requires a function. I tried one , but it only works for hours less than 24 hours. I need it to convert greater than 24 hours as well.
Note: the datatype of the Time column is Varchar2.

Thanks in advance..

Body:
milliseconds to hh:mm:ss

SELECT TO_CHAR(TRUNC(s/3600000),'FM9900') || ':' || TO_CHAR(TRUNC(MOD(s,3600000)/60000),'FM00')
|| ':' ||TO_CHAR(MOD(s,60000),'FM00')
FROM DUAL ;


问:
100,000 page renders using headless browser, max per cpu per second on aws
I'm doing a scraping project and need to use a browser to load javascript on websites that I visit.

If using just http I can get up to 150/second on an m4.large. Which has 2 cpus. On initial tests using headless chrome its so much slower around 4 / second and typically the bottleneck is CPU not RAM. For many web pages basic http is fine but increasingly its not with single page apps etc.

Does anyone have some experience doing something similar? What were you able to achieve? What was the stack you used e.g. python, selenium, headless chrome and multiprocessing. Did you have to alter the configuration of chrome?

答:
This particular page on Stack Overflow takes 1.2 seconds to load on my machine, according to the "Performance" tab in Chrome's devtools:

You can break that down by CPU usage or wall clock time, but the point is that it takes a while.

In this case I would load the page once in a browser to learn what resources are accessed, then execute those using a load testing tool other than a browser.

Naively executing this curl command — first parallelizing it by replacing ; with & — takes 1.8 seconds on my machine. But the point is that you only want to hit the server, not interpret any HTML, CSS, JavaScript, or images.

But if you want to crawl the web and see what really happens upon each page load, so that you can look at the page and decide where to go next, there isn't much to do besides a headless browser. Real production web crawlers have a much larger machine budget, and possibly use clever techniques to avoid wasting CPU on decoding images and laying out CSS.


问:
R rep function to index rows
I'm trying to assign a repeating pattern of numbers (i.e. numbers 1:96) to an existing data frame which has approx. 360 rows (not divisible by 96). I kept getting an error where replacement set contains 96 and data contains 360. This is what I had done;

```<code>stamp$index=rep(1:96)
</code>```

I then changed this to calculate the number of times to repeat 1:96 as follows;

```<code>stamp$index=rep(1:96,ceiling(nrow(stamp)/96))
</code>```

But now get an error where replacement set contains 384 and data contains 360.
Any ideas on how to get this right?

答:
One option would be to specify the length.out in rep as the number of rows of the dataset

```<code>rep(1:96, length.out = nrow(stamp))
</code>```

Title: R rep function to index rows

Body:
I'm trying to assign a repeating pattern of numbers (i.e. numbers 1:96) to an existing data frame which has approx. 360 rows (not divisible by 96). I kept getting an error where replacement set contains 96 and data contains 360. This is what I had done;

stamp$index=rep(1:96)

I then changed this to calculate the number of times to repeat 1:96 as follows;

stamp$index=rep(1:96,ceiling(nrow(stamp)/96))

But now get an error where replacement set contains 384 and data contains 360.
Any ideas on how to get this right?

Body:
One option would be to specify the length.out in rep as the number of rows of the dataset

rep(1:96, length.out = nrow(stamp))


问:
Arduino: Use Timer in c++ class
I am trying to use a timer to repeatedly change the PWM Output over time to have a smooth transition when the brightness changes. I keep getting this error when trying to compile the code:

/Users/jt/Documents/Arduino/libraries/SingleColorLight/SingleColorLight.cpp: In constructor 'CSingleColorLight::CSingleColorLight(int)':
  /Users/jt/Documents/Arduino/libraries/SingleColorLight/SingleColorLight.cpp:13:58: error: cannot convert 'CSingleColorLight::DimmerCallback' from type 'void (CSingleColorLight::)(void*)' to type 'void ()(void)'
         ets_timer_setfn(&Dimmer, this->DimmerCallback, NULL);

Here is my code:

```<code>class CSingleColorLight {

  private:
    int pin;
    int intensitySetPoint;
    int intensityActual;
    int percentageBuffer;
    ETSTimer Dimmer;
    int dimmerCount;

  public:
    CSingleColorLight(int _pin);
    bool setIntensity(int _intensity);
    int getIntensity();
    bool getStatus(void);
    bool setStatus(bool _status);
    void DimmerCallback(void*);

};
</code>```

and in the cpp file:

```<code>void CSingleColorLight::DimmerCallback(void*) {
  if(dimmerCount>0){
    dimmerCount--;
    intensityActual++;
  } else if(dimmerCount<0){
    dimmerCount++;
    intensityActual--;
  } else {
    ets_timer_disarm(&Dimmer);
  }
  analogWrite(pin, percentageToTime[intensityActual]);
  return;
}
</code>```

It asks for a pointer, right? Any idea how to fix this?
Thanks a lot!

答:
If you want DimmerCallback to take a void* argument, then you need to name it, like

```<code>void CSingleColorLight::DimmerCallback(void* x)
</code>```

but you are not using the void* in the code. It looks like you should just get rid of it, so it would be

```<code>void CSingleColorLight::DimmerCallback()
</code>```

int the cpp and

```<code>void DimmerCallback();
</code>```

in the header.

A void* argument is a pointer that can point to any data type, it is not the same as void which is just no argument.

Title: Arduino: Use Timer in c++ class

Body:
I am trying to use a timer to repeatedly change the PWM Output over time to have a smooth transition when the brightness changes. I keep getting this error when trying to compile the code:

/Users/jt/Documents/Arduino/libraries/SingleColorLight/SingleColorLight.cpp: In constructor 'CSingleColorLight::CSingleColorLight(int)':
  /Users/jt/Documents/Arduino/libraries/SingleColorLight/SingleColorLight.cpp:13:58: error: cannot convert 'CSingleColorLight::DimmerCallback' from type 'void (CSingleColorLight::)(void*)' to type 'void ()(void)'
         ets_timer_setfn(&Dimmer, this->DimmerCallback, NULL);

Here is my code:

class CSingleColorLight {

  private:
    int pin;
    int intensitySetPoint;
    int intensityActual;
    int percentageBuffer;
    ETSTimer Dimmer;
    int dimmerCount;

  public:
    CSingleColorLight(int _pin);
    bool setIntensity(int _intensity);
    int getIntensity();
    bool getStatus(void);
    bool setStatus(bool _status);
    void DimmerCallback(void*);

};

and in the cpp file:

void CSingleColorLight::DimmerCallback(void*) {
  if(dimmerCount>0){
    dimmerCount--;
    intensityActual++;
  } else if(dimmerCount<0){
    dimmerCount++;
    intensityActual--;
  } else {
    ets_timer_disarm(&Dimmer);
  }
  analogWrite(pin, percentageToTime[intensityActual]);
  return;
}

It asks for a pointer, right? Any idea how to fix this?
Thanks a lot!

Body:
If you want DimmerCallback to take a void* argument, then you need to name it, like

void CSingleColorLight::DimmerCallback(void* x)

but you are not using the void* in the code. It looks like you should just get rid of it, so it would be

void CSingleColorLight::DimmerCallback()

int the cpp and

void DimmerCallback();

in the header.

A void* argument is a pointer that can point to any data type, it is not the same as void which is just no argument.


问:
JavaScript Error...Not creating elements when the button is clicked
My code look like this, It should have created a table when the "submitButton" was clicked but it doesn't do so. Here is my code:

```<code>submitButton.addEventListener("click", () => {
        var newTable = document.createElement("table");
        for(let i = 0; i < parseInt(numOfStudents); i++){
            var newRow = document.createElement("tr");
            var newInput = document.createElement("td");
            var newInput2 = document.createElement("td");
            document.newRow.appendChild(newInput);
            document.newRow.appendChild(newInput2);
            document.newTable.appendChild(newRow);
            document.body.appendChild(newTable);
        }
    });
</code>```

答:
You can't access elements with body. you need to use DOM functions like getElementById etc.. if its a new created elements as in your loop you can append to them directly as below

var numOfStudents=10
submitButton=document.getElementById("submitButton")
submitButton.addEventListener("click", () => {
        var newTable = document.createElement("table");
        for(let i = 0; i < parseInt(numOfStudents); i++){
            var newRow = document.createElement("tr");

            var newInput = document.createElement("td");
            var newInput2 = document.createElement("td");

            newRow.appendChild(newInput);
            newRow.appendChild(newInput2);
            newTable.appendChild(newRow);
            document.body.appendChild(newTable);
        }
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="submitButton" >button</button></code>```

Body:
My code look like this, It should have created a table when the "submitButton" was clicked but it doesn't do so. Here is my code:

submitButton.addEventListener("click", () => {
        var newTable = document.createElement("table");
        for(let i = 0; i < parseInt(numOfStudents); i++){
            var newRow = document.createElement("tr");
            var newInput = document.createElement("td");
            var newInput2 = document.createElement("td");
            document.newRow.appendChild(newInput);
            document.newRow.appendChild(newInput2);
            document.newTable.appendChild(newRow);
            document.body.appendChild(newTable);
        }
    });

Body:
You can't access elements with body. you need to use DOM functions like getElementById etc.. if its a new created elements as in your loop you can append to them directly as below

var numOfStudents=10
submitButton=document.getElementById("submitButton")
submitButton.addEventListener("click", () => {
        var newTable = document.createElement("table");
        for(let i = 0; i < parseInt(numOfStudents); i++){
            var newRow = document.createElement("tr");

            var newInput = document.createElement("td");
            var newInput2 = document.createElement("td");

            newRow.appendChild(newInput);
            newRow.appendChild(newInput2);
            newTable.appendChild(newRow);
            document.body.appendChild(newTable);
        }
    });

<button id="submitButton" >button</button>


问:
Seaborn Heatmap with logarithmic-scale colorbar
Is there a way to set the color bar scale to log on a seaborn heat map graph?

I am using a pivot table output from pandas as an input to the call

sns.heatmap(df_pivot_mirror, annot=False, xticklabels=256, yticklabels=128, cmap=plt.cm.YlOrRd_r)
```

答:
Responding to cphlewis (I don't have enough reputation), I solved this problem using cbar_kws; as I saw here: seaborn clustermap: set colorbar ticks.

For example cbar_kws={"ticks":[0,1,10,1e2,1e3,1e4,1e5]}.

```<code>from matplotlib.colors import LogNorm
s=np.random.rand(20,20)
sns.heatmap(s, norm=LogNorm(s.min(),s.max()),
            cbar_kws={"ticks":[0,1,10,1e2,1e3,1e4,1e5]},
            vmin = 0.001, vmax=10000)
plt.show()
</code>```

Have a nice day.

Body:
Responding to cphlewis (I don't have enough reputation), I solved this problem using cbar_kws; as I saw here: seaborn clustermap: set colorbar ticks.

For example cbar_kws={"ticks":[0,1,10,1e2,1e3,1e4,1e5]}.

from matplotlib.colors import LogNorm
s=np.random.rand(20,20)
sns.heatmap(s, norm=LogNorm(s.min(),s.max()),
            cbar_kws={"ticks":[0,1,10,1e2,1e3,1e4,1e5]},
            vmin = 0.001, vmax=10000)
plt.show()

Have a nice day.


问:
Visual Studio disable playlist load on startup
Visual Studio loads a playlist when opening solution, and I can't find a way to disable this. The only related post I've seen at all is this one What does "Load Playlist started" mean in Visual Studio? It suggests that closing the test explorer window will stop it, but that doesn't help for me. I don't have any unit tests(shame on me, I know) nor have I created a playlist. I can't seem to find any info on this anywhere else either. Anyone know how to disable this? I'm using VS 2015. </p>

答:
I believe you need to uncheck Test -> Test Settings -> Keep Test Execution Engine Running setting.

Restart Visual Studio for the changes to take effect.


问:
Parallellizable Algorithms to traverse a 2D matrix being aware of both col/row-wise neighborhood
I have a fairly large N*N integer matrix Matrix2D (assume sufficient memory),

1, within each row/column, I need to record the col/row index of an element if it's value is different than it's right/lower neighbour.

2, I want to find an optimal algorithms that is parallellizable, ideally by OMP.

So, finally I will have some data structures like,

```<code>std::vector<std::vector<int>>   RowWiseDiscontinuity(N);// N= #of rows
std::vector<std::vector<int>>   ColWiseDiscontinuity(N);// N= #of cols
</code>```

where inner std::vector<int> records the row/col indices.

I put my serial version here but find it difficult to be OMP parallelized... Someone could provide some idea how to implement the traversing over this 2D matrix with omp?

code snippet,

```<code>std::vector<std::vector<int>>   RowWiseDiscontinuity(N);// N= #of rows
std::vector<std::vector<int>>   ColWiseDiscontinuity(N);// N= #of cols
std::vector<int> TempX1;
std::vector<int> TempX2;
for (int y=0; y<N; ++y)
{
    TempX1.clear();
    for (int x =0; x<N; ++x)
    {
        int value = Matrix2D(x,y);
        TempX1.push_back(value);
    }

    auto iter1 = TempX1.begin();
    auto iter2 = TempX2.begin();

    if (y>0)
    for (int x =0; x<N; ++x)
    {
         if (*iter1 !=*(iter1+1))
         {
             RowWiseDiscontinuity[y].push_back(x); //Critical for OMP
         }
         ++iter1;
         ++iter2;
         if (*iter1 != *iter2)
         {
             ColWiseDiscontinuity[x].push_back(y); //Critical for OMP
         }
     }

     TempX2.swap(TempX1); // proceed to next row, remember previous

}
</code>```

答:
Perform two passes (which can be performed on different threads) on the matrix, one for the row wise discontinuities and the other for the column wise discontinuities.

The row pass looks as follows:

```<code>for (int y = 0; y < N; ++y)    // Can be parallelized
{
    for (int x = 0; x < N - 1; ++x)
    {
        if(Matrix(x, y) != Matrix(x + 1, y))
            RowWiseDiscontinuity[y].push_back(x);
    }
}
</code>```

The column pass is similar:

```<code>for (int x = 0; x < N; ++x)    // Can be parallelized
{
    for (int y = 0; y < N - 1; ++y)
    {
        if(Matrix(x, y) != Matrix(x, y + 1))
            ColWiseDiscontinuity[x].push_back(y);
    }
}
</code>```

The outer loop in both cases can be parallelized. A different element of Row / ColWiseDiscontinuity is mutated in each iteration of the outer loop, thus preventing a data race. The passes themselves can be performed on different threads.

As a side note, you can optimize this algorithm further by reducing cache misses (at the expense of memory) by storing the matrix in both row-major and column-major order, and using each order when appropriate. In a row-major order, element (x + 1, y) is always next to (x, y). The same holds true for element (x, y + 1) in a column-major order.

Body:
I have a fairly large N*N integer matrix Matrix2D (assume sufficient memory),

1, within each row/column, I need to record the col/row index of an element if it's value is different than it's right/lower neighbour.

2, I want to find an optimal algorithms that is parallellizable, ideally by OMP.

So, finally I will have some data structures like,

std::vector<std::vector<int>>   RowWiseDiscontinuity(N);// N= #of rows
std::vector<std::vector<int>>   ColWiseDiscontinuity(N);// N= #of cols

where inner std::vector<int> records the row/col indices.

I put my serial version here but find it difficult to be OMP parallelized... Someone could provide some idea how to implement the traversing over this 2D matrix with omp?

code snippet,

std::vector<std::vector<int>>   RowWiseDiscontinuity(N);// N= #of rows
std::vector<std::vector<int>>   ColWiseDiscontinuity(N);// N= #of cols
std::vector<int> TempX1;
std::vector<int> TempX2;
for (int y=0; y<N; ++y)
{
    TempX1.clear();
    for (int x =0; x<N; ++x)
    {
        int value = Matrix2D(x,y);
        TempX1.push_back(value);
    }

    auto iter1 = TempX1.begin();
    auto iter2 = TempX2.begin();

    if (y>0)
    for (int x =0; x<N; ++x)
    {
         if (*iter1 !=*(iter1+1))
         {
             RowWiseDiscontinuity[y].push_back(x); //Critical for OMP
         }
         ++iter1;
         ++iter2;
         if (*iter1 != *iter2)
         {
             ColWiseDiscontinuity[x].push_back(y); //Critical for OMP
         }
     }

     TempX2.swap(TempX1); // proceed to next row, remember previous

}

Body:
Perform two passes (which can be performed on different threads) on the matrix, one for the row wise discontinuities and the other for the column wise discontinuities.

The row pass looks as follows:

for (int y = 0; y < N; ++y)    // Can be parallelized
{
    for (int x = 0; x < N - 1; ++x)
    {
        if(Matrix(x, y) != Matrix(x + 1, y))
            RowWiseDiscontinuity[y].push_back(x);
    }
}

The column pass is similar:

for (int x = 0; x < N; ++x)    // Can be parallelized
{
    for (int y = 0; y < N - 1; ++y)
    {
        if(Matrix(x, y) != Matrix(x, y + 1))
            ColWiseDiscontinuity[x].push_back(y);
    }
}

The outer loop in both cases can be parallelized. A different element of Row / ColWiseDiscontinuity is mutated in each iteration of the outer loop, thus preventing a data race. The passes themselves can be performed on different threads.

As a side note, you can optimize this algorithm further by reducing cache misses (at the expense of memory) by storing the matrix in both row-major and column-major order, and using each order when appropriate. In a row-major order, element (x + 1, y) is always next to (x, y). The same holds true for element (x, y + 1) in a column-major order.


问:
CakePHP 3 and VueJS - use v-model to set default Form's selectbox
I'm using CakePHP Form helper to create form input fields. When a user edit an item, it will pre-fill the fields with data. I use v-model on each input field to make sure data is correctly populated.

It's all good for the textboxes as data is bound correctly. But for <select> fields, v-model doesn't seem to work. I've tried using default property for the Form->input() but no help. Here's some code:

```<code><div class="fields">
    <?= $this->Form->input('email', [
        'label' => __('Email'),
        'type' => 'email',
        'v-model' => 'emailModel',
        'placeholder' => __('Required'),
        '@keydown.enter.stop.prevent' => 'return false;',
        '@keyup.enter.stop.prevent' => 'onSubmit()'
    ]); ?>
    <?= $this->Form->input('status', [
        'label' => __('Status'),
        'type' => 'select',
        'default' => '{{userStatus}}',
        'options' => [
            1 => 'Active',
            2 => 'Inactive'
        ],
        '@keydown.enter.stop.prevent' => 'return false;',
        '@keyup.enter.stop.prevent' => 'onSubmit()'
    ]); ?>
</div>
</code>```

The email textbox has correct data filled, but not for the status selectbox. But if I replace {{userStatus}} with, for example, 2, it will set the default option to Inactive, even though {{userStatus}} itself has value 2.

How do I go about solving this?

答:
I am new to VueJS but I came across the same question. The VueJS documentation states:

v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth. You should declare the initial value on the JavaScript side, inside the data option of your component.
https://v2.vuejs.org/v2/guide/forms.html#Basic-Usage

Therefore, you need to assign your data.userStatus with your default value.

```<code>var vm = new Vue({
    el: '#app',
    data: {
        statusModel: 2 // The default value goes here
    }
});
</code>```

PHP Side:

```<code><div class="fields">
    <?= $this->Form->input('email', [
        'label' => __('Email'),
        'type' => 'email',
        'v-model' => 'emailModel',
        'placeholder' => __('Required'),
        '@keydown.enter.stop.prevent' => 'return false;',
        '@keyup.enter.stop.prevent' => 'onSubmit()'
    ]); ?>
    <?= $this->Form->input('status', [
        'label' => __('Status'),
        'type' => 'select',
        'v-model' => 'statusModel',
        'options' => [
            1 => 'Active',
            2 => 'Inactive'
        ],
        '@keydown.enter.stop.prevent' => 'return false;',
        '@keyup.enter.stop.prevent' => 'onSubmit()'
    ]); ?>
</div>
</code>```

Hope this helps.

Body:
I'm using CakePHP Form helper to create form input fields. When a user edit an item, it will pre-fill the fields with data. I use v-model on each input field to make sure data is correctly populated.

It's all good for the textboxes as data is bound correctly. But for <select> fields, v-model doesn't seem to work. I've tried using default property for the Form->input() but no help. Here's some code:

    <?= $this->Form->input('email', [
        'label' => __('Email'),
        'type' => 'email',
        'v-model' => 'emailModel',
        'placeholder' => __('Required'),
        '@keydown.enter.stop.prevent' => 'return false;',
        '@keyup.enter.stop.prevent' => 'onSubmit()'
    ]); ?>
    <?= $this->Form->input('status', [
        'label' => __('Status'),
        'type' => 'select',
        'default' => '{{userStatus}}',
        'options' => [
            1 => 'Active',
            2 => 'Inactive'
        ],
        '@keydown.enter.stop.prevent' => 'return false;',
        '@keyup.enter.stop.prevent' => 'onSubmit()'
    ]); ?>

The email textbox has correct data filled, but not for the status selectbox. But if I replace {{userStatus}} with, for example, 2, it will set the default option to Inactive, even though {{userStatus}} itself has value 2.

How do I go about solving this?

Body:
I am new to VueJS but I came across the same question. The VueJS documentation states:

v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth. You should declare the initial value on the JavaScript side, inside the data option of your component.
https://v2.vuejs.org/v2/guide/forms.html#Basic-Usage

Therefore, you need to assign your data.userStatus with your default value.

var vm = new Vue({
    el: '#app',
    data: {
        statusModel: 2 // The default value goes here
    }
});

PHP Side:

<div class="fields">
    <?= $this->Form->input('email', [
        'label' => __('Email'),
        'type' => 'email',
        'v-model' => 'emailModel',
        'placeholder' => __('Required'),
        '@keydown.enter.stop.prevent' => 'return false;',
        '@keyup.enter.stop.prevent' => 'onSubmit()'
    ]); ?>
    <?= $this->Form->input('status', [
        'label' => __('Status'),
        'type' => 'select',
        'v-model' => 'statusModel',
        'options' => [
            1 => 'Active',
            2 => 'Inactive'
        ],
        '@keydown.enter.stop.prevent' => 'return false;',
        '@keyup.enter.stop.prevent' => 'onSubmit()'
    ]); ?>
</div>

Hope this helps.


问:
Bean Validation + JAX-RS not reading custom ValidationMessages.properties
I am trying to use custom messages with Bean Validation but my custom messages are not being returned by the JAX-RS resource. What am I doing wrong?

ValidationMessages.properties

```<code>invoice.value.notnull=Invoice value must be informed.
</code>```

The file is located at src/main/resources

InvoiceResource.java

```<code>@Path("/invoice")
public class InvoiceResource {

    @POST
    public void post(@Valid InvoiceRequest request) {
        /* stuff */
    }

}
</code>```

InvoiceRequest.java

```<code>public class InvoiceRequest {

    @NotNull(message = "invoice.value.notnull")
    private Double value;

}
</code>```

答:
Found out that the problem was my declaration of the message in the bean param. The message ID must be forked between braces "{ ... }":

```<code>@NotNull(message = "{invoice.value.notnull}")
</code>```

How we get the proper JSON response with the correct message:

```<code>{
    "exception": null,
    "fieldViolations": [],
    "propertyViolations": [],
    "classViolations": [],
    "parameterViolations": [
        {
            "constraintType": "PARAMETER",
            "path": "post.arg0.value",
            "message": "Invoice value must be informed",
            "value": ""
        }
    ],
    "returnValueViolations": []
}
</code>```

Body:
I am trying to use custom messages with Bean Validation but my custom messages are not being returned by the JAX-RS resource. What am I doing wrong?

ValidationMessages.properties

invoice.value.notnull=Invoice value must be informed.

The file is located at src/main/resources

InvoiceResource.java

@Path("/invoice")
public class InvoiceResource {

    @POST
    public void post(@Valid InvoiceRequest request) {
        /* stuff */
    }

}

InvoiceRequest.java

public class InvoiceRequest {

    @NotNull(message = "invoice.value.notnull")
    private Double value;

}

Body:
Found out that the problem was my declaration of the message in the bean param. The message ID must be forked between braces "{ ... }":

@NotNull(message = "{invoice.value.notnull}")

How we get the proper JSON response with the correct message:

{
    "exception": null,
    "fieldViolations": [],
    "propertyViolations": [],
    "classViolations": [],
    "parameterViolations": [
        {
            "constraintType": "PARAMETER",
            "path": "post.arg0.value",
            "message": "Invoice value must be informed",
            "value": ""
        }
    ],
    "returnValueViolations": []
}


问:
Java while loop printing squared numbers can't use int?
In Java, create a do-while loop that starts at 2, and displays the number squared on each line while the number is less than 1,000,000. And this is what I have:

```<code>int k = 2;
do {
    System.out.println(k);
    k *= k;
} while(k < 1000000);
</code>```

The problem is the output, somehow it is getting stuck at 0 and infinitely looping through 0 to print those out? I don't believe it is due to the fact that the number is out of int range, since a 32 bit number's range is around +/- 2 billion... But when I switch up the data type of k to be long everything works fine... Why is this?

答:
Your code to print squares should be

```<code>int k = 2;
do {
    System.out.println(k*k);
    k++;
}while(k < 1000000);
</code>```

As you are storing the result in same variable, your output is growing exponentially

Body:
In Java, create a do-while loop that starts at 2, and displays the number squared on each line while the number is less than 1,000,000. And this is what I have:

int k = 2;
do {
    System.out.println(k);
    k *= k;
} while(k < 1000000);

The problem is the output, somehow it is getting stuck at 0 and infinitely looping through 0 to print those out? I don't believe it is due to the fact that the number is out of int range, since a 32 bit number's range is around +/- 2 billion... But when I switch up the data type of k to be long everything works fine... Why is this?

Body:
Your code to print squares should be

int k = 2;
do {
    System.out.println(k*k);
    k++;
}while(k < 1000000);

As you are storing the result in same variable, your output is growing exponentially


问:
Adding Excel Sheet Formula
I wanted some help in excel as i have low expertise in it, How do you add a formula on a excel sheet and
secondly i want to add a formula on a column which do something like this

```<code>Text-> ABCD
</code>```

Formula should add ' at the start of the text

```<code>Text->6/11
</code>```

Formula should make it '6/11

When ever user types something in that column it should add ' at the start of the text

答: To apply the formula and values in 1 single cell can only be possible via VBA. If you do not want to use VBA, you will need 2 columns for sure. 1 to get the data entered and 2nd to write the formula to get the output. Concatenate() will do just fine for you.

Title: Adding Excel Sheet Formula

Body:
I wanted some help in excel as i have low expertise in it, How do you add a formula on a excel sheet and
secondly i want to add a formula on a column which do something like this

Text-> ABCD

Formula should add ' at the start of the text

Text->6/11

Formula should make it '6/11

When ever user types something in that column it should add ' at the start of the text


问:
How to edit an XML File
Howdy,
I was wondering if I was able to alter a distinct element in an XML file saved on a Windows Phone 7 device without actually having to serialize the whole file all over again.</p>

答:
In general, no - and this has little to do with Windows Phone 7 (although I don't know whether IsolatedStorageFileStream on WP7 even supports seeking).

I don't know of any mainstream filesystems with high level abstractions (such as those used by Java and C#) which allow you to delete or insert data in the middle of a file.

I suppose theoretically if you were happy to pad with whitespace, or never change the length of the data you're using, you could just overwrite the relevant bytes - but I don't think it would be a good idea at all. Very brittle and hard to work with.

Just go for overwriting the whole file.

Title: How to edit an XML File


问:
Remove 1 week from date in php
Been a long while since I posted here, I have done a LOT of coding without having to ask but I am stuck :(

I have a variable which is called "$date", it is always the current date. Now I have logs which have a date set to them, now what I want to do is delete any logs that are older than a week from the current date. Here's how I'm doing it (? means I don't know what to put).

```<code>$date = date('Y-m-d H:i:s');

$one_week_old = $date - ?;

$clearlog = mysqli_query($con,"DELETE FROM logs WHERE logs.date < '$one_week_old'");
</code>```

答:
If you prefer Oriented Object paradigm, we have:

```<code>$oneWeekAgo = (new DateTime('-1 week'))->format('d/m/Y');
</code>```

Explanation:

Return a new DateTimeObject

Set the timestamp from -1 week

Format to your need.

Title: Remove 1 week from date in php

Body:
Been a long while since I posted here, I have done a LOT of coding without having to ask but I am stuck :(

I have a variable which is called "$date", it is always the current date. Now I have logs which have a date set to them, now what I want to do is delete any logs that are older than a week from the current date. Here's how I'm doing it (? means I don't know what to put).

$date = date('Y-m-d H:i:s');

$one_week_old = $date - ?;

$clearlog = mysqli_query($con,"DELETE FROM logs WHERE logs.date < '$one_week_old'");

Body:
If you prefer Oriented Object paradigm, we have:

$oneWeekAgo = (new DateTime('-1 week'))->format('d/m/Y');

Explanation:

Return a new DateTimeObject

Set the timestamp from -1 week

Format to your need.


问:
Running a command in SSH from command prompt
I am trying to access unix from command prompt using SSH connection with the below command

C:\Program Files\PuTTY>putty.exe -ssh gemini -l usename -pw password

Now i also want to run command in gemini from command prompt.
Will that be possible ?

I have found few solutions as below

C:\Program Files\PuTTY>putty.exe -ssh gemini -l username -pw password -m "C:\path\cmd.txt"

But running that just opens my putty and closes and not sure what is missing.

can someone help me with this please ?

答: Have you tried to remove doble quotes in file path?</p>


问:
ASP.NET Core Project w/ JavaScriptServices in Docker Unable to Launch Node
I am having issues getting a site to run properly inside of a docker container. The container builds fine and runs, however when navigating to a page it fails on loading JavaScript services.

Here is the Dockerfile

```<code>FROM microsoft/aspnetcore-build:2.0 AS builder
WORKDIR /app

ADD company_cas.pem /usr/local/share/ca-certificates/company_cas.crt
RUN update-ca-certificates

COPY company_cas.pem ./
RUN npm config set cafile company_cas.pem

# Run NPM install for dependencies
COPY package.json ./
RUN npm install

# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# Copy everything else and build
COPY . ./

RUN dotnet publish -c Release -o out

# Build runtime image
FROM microsoft/aspnetcore:2.0
WORKDIR /app
COPY --from=builder /app/out .
ENTRYPOINT ["dotnet", "web.dll"]
</code>```

I am using the microsoft/aspnetcore-build:2.0 base image, and npm does run so Node is installed to the best of my knowledge.

The output of the failed request is -

```<code>fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
web   |       An unhandled exception has occurred: Failed to start Node process. To resolve this:.
web   |
web   |       [1] Ensure that Node.js is installed and can be found in one of the PATH directories.
web   |           Current PATH enviroment variable is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
web   |           Make sure the Node executable is in one of those directories, or update your PATH.
web   |
web   |       [2] See the InnerException for further details of the cause.
web   | System.InvalidOperationException: Failed to start Node process. To resolve this:.
web   |
web   | [1] Ensure that Node.js is installed and can be found in one of the PATH directories.
web   |     Current PATH enviroment variable is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
web   |     Make sure the Node executable is in one of those directories, or update your PATH.
web   |
web   | [2] See the InnerException for further details of the cause. ---> System.ComponentModel.Win32Exception: No such file or directory
</code>```

Full Error Stack @ Pastebin

Is this a matter of setting a new PATH for ASP.NET to find Node? If so, any idea on what that path should be in Docker?

答:
I guess I overlooked the runtime image base container.

Changed to FROM microsoft/aspnetcore-build:2.0 and now I'm good.

Body:
I am having issues getting a site to run properly inside of a docker container. The container builds fine and runs, however when navigating to a page it fails on loading JavaScript services.

Here is the Dockerfile

FROM microsoft/aspnetcore-build:2.0 AS builder
WORKDIR /app

ADD company_cas.pem /usr/local/share/ca-certificates/company_cas.crt
RUN update-ca-certificates

COPY company_cas.pem ./
RUN npm config set cafile company_cas.pem

# Run NPM install for dependencies
COPY package.json ./
RUN npm install

# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# Copy everything else and build
COPY . ./

RUN dotnet publish -c Release -o out

# Build runtime image
FROM microsoft/aspnetcore:2.0
WORKDIR /app
COPY --from=builder /app/out .
ENTRYPOINT ["dotnet", "web.dll"]

I am using the microsoft/aspnetcore-build:2.0 base image, and npm does run so Node is installed to the best of my knowledge.

The output of the failed request is -

fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
web   |       An unhandled exception has occurred: Failed to start Node process. To resolve this:.
web   |
web   |       [1] Ensure that Node.js is installed and can be found in one of the PATH directories.
web   |           Current PATH enviroment variable is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
web   |           Make sure the Node executable is in one of those directories, or update your PATH.
web   |
web   |       [2] See the InnerException for further details of the cause.
web   | System.InvalidOperationException: Failed to start Node process. To resolve this:.
web   |
web   | [1] Ensure that Node.js is installed and can be found in one of the PATH directories.
web   |     Current PATH enviroment variable is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
web   |     Make sure the Node executable is in one of those directories, or update your PATH.
web   |
web   | [2] See the InnerException for further details of the cause. ---> System.ComponentModel.Win32Exception: No such file or directory

Full Error Stack @ Pastebin

Is this a matter of setting a new PATH for ASP.NET to find Node? If so, any idea on what that path should be in Docker?


问:
Share Git Staging Area on local subnet(mostly wifi), now with images to explain
I know it sounds like a commit push, but what I would like to do here is have something done in code then stage but before pushing I would like to see what my local office partner(s) done, and he(they) see what I've done using the stage area (index), to work as a "caveat" for all local team members and to mentor them without the team leader leaving his seat, for example take a look at the following:

I want those connected to peek at each other using their wifi connection, but only Developers and the Team leader, anyone who is NOT A Developer shouldn't be able to see (so I can't use local shared directory)

Can  this be done or should I ask for it as an added feature?

P.S. Currently, we are exchanging files involved (Skype, duh!) but then again one can't simply do this unless those involved communicate verbally, mostly leave desk, and turn it into a real-time tutoring session, can't use diff (feature) as is, and worst of all if someone does some code that works and does a push and tests says yes, but days or weeks later turns out to be a simple-code(i.e. low conformity to design approach and how the architect wants it to be) and the need for it to be rewritten.

答:
You wandered from requirements to implementation details when you said "using the stage area", and it changes the answer considerably.

The stage area is not designed as a collaboration tool.  There is no straightforward way to use it as you describe.  You should not attempt to use it as you describe.  You can make a feature request, and I fully expect it will be disregarded, because git already has tools and patterns for collaboration and this isn't one of them.

If you want to share changes without pushing to origin, you can do any of:

a) Commit the changes locally, perhaps to a temporary branch, and then share that commit with your partner.  To share it, you can configure one another's repos as remotes, or you can pass bundle files containing the commit.

b) Create patch files from your index and/or working tree and share those.

c) Stash the changes, and share the stash.  This is a little trickier (beccuse it's not anticipated that you would share a stash), and doesn't buy you much relative to commit-and-share (in fact a stash is implemented using temporary commits anyway), but it can be done.

There's also probably not that much wrong with creating a temporary branch and pushing it to origin so your partner can fetch it, though depending on how your origin is hosted that might cause clutter to accumulate over time.


问:
Firebase - Fallback to Crash Reporting
When I get into Crash Report on Firebase, I see the message:
Someone on your team has set up Crashlytics as your crash reporter for XXXXX
How can I fall back to Crash Report? I`m not ready to move on to crashlytics yet.</p>

答: Great question Rafael. If you want to switch back, simply remove the Crashlytics integration from your app and reintegrate crash reporting. Let me know how it goes and remember to talk to your team about why this happened in the first place. Thanks again!</p>

Title: Firebase - Fallback to Crash Reporting