问:
Activity not opening after signing in
I'm currently creating an application that allows the user to login using a web api. While checking response of the API , i'm not getting any error.

```<code>{"error":0,"data":[{"id":"2","driver_name":"Test Driver","driver_lat":"","driver_long":"","driver_mobile_no":"9164618545","driver_password":"202cb962ac59075b964b07152d234b70","driver_token":"bef1032495ef4b2c891795fce1fa16c2","driver_image":"","is_active":"1","on_duty":"0","t_drivers":"0","created_at":"2017-07-04 06:38:22","last_activity_at":"2017-07-04 09:19:08"}],"msg":"Login Successfully."}
</code>```

But while using the app, it does not go to the mainActivity.
This is the login class:-

```<code>public class login extends AppCompatActivity {
private Button login1;
Session session;
private ConstraintLayout mRootLayout;
boolean doubleBackToExitPressedOnce = false;
boolean status = false;

EditText mEdtEmail , mEdtPassword ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Answers(), new Crashlytics());
    setContentView(R.layout.activity_login);

    login1 = (Button) findViewById(R.id.button);
    mEdtEmail = (EditText) findViewById(R.id.phone_number);
    mEdtPassword = (EditText) findViewById(R.id.password);

    session = new Session(login.this);

    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(login.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

   // sign_in();

    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String mobile = mEdtEmail.getText().toString().trim();
            String password = mEdtPassword.getText().toString().trim();

            status = checkInternetConnection();

            if (status) {

                if (mobile.length() == 0) {
                    mEdtEmail.setError("Required");
                } else if (mobile.length() < 10) {
                    mEdtEmail.setError("Mobile no must be 10 char. long");
                } else if (password.length() == 0) {
                    mEdtPassword.setError("Required");
                } else {

                    new UserLoginTask(mobile, password, login.this).execute();

                }
            }
            else
            {
                Snackbar.make(mRootLayout, "You don't have Internet connection!", Snackbar.LENGTH_LONG).show();
                //  Toast.makeText(getApplicationContext(), "You don't have Internet connection", Toast.LENGTH_LONG).show();
            }
        }
    });
}

private class UserLoginTask extends AsyncTask<String, Void, String> {

    private String mUserName;
    private String mPassword;
    String msg ;
    ProgressDialog progressDialog;

    Boolean loginStatus = false;
    private Activity activity;
    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedpreferences;

    UserLoginTask(String userName, String password, Activity activity) {
        mUserName = userName;
        mPassword = password;
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        progressDialog= ProgressDialog.show(login.this, "Loading. . .","Please Wait. . .", true);
        Toast.makeText(login.this,"toast 1",Toast.LENGTH_SHORT).show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {

        try {

            String result= WebService.postHttpResponse(mUserName, mPassword, activity);

            JSONObject jsonObject = new JSONObject(result);
          //  Log.d("Json Array", "doInBackground: "+jsonObject);
           String status = jsonObject.optString("error");
         //   msg = jsonObject.optString("msg");
           // Toast.makeText(login.this,"toast 2",Toast.LENGTH_SHORT).show();
            if(status.equals("0")){

                loginStatus = true ;

                session.setLogin(true);

                JSONArray jsonarray = jsonObject.getJSONArray("data");
                JSONObject jsonObject1=jsonarray.getJSONObject(0);

                status = jsonObject1.getString("msg");
                Log.e("DRIVER NAME -----" ,jsonObject1.getString("driver_name"));

                Driver driver = new Driver();

                driver.setId(jsonObject1.getString("id"));
                driver.setDriver_name(jsonObject1.getString("driver_name"));
                driver.setDriver_lat(jsonObject1.getString("driver_lat"));
                driver.setDriver_long(jsonObject1.getString("driver_long"));
                driver.setDriver_mobile_no(jsonObject1.getString("driver_mobile_no"));
                driver.setDriver_token(jsonObject1.getString("driver_token"));
                driver.setCreated_at(jsonObject1.getString("created_at"));
                driver.setLast_activity_at(jsonObject1.getString("last_activity_at"));

                sharedpreferences = activity.getSharedPreferences("MY" , Context.MODE_PRIVATE);
                SharedPreferences.Editor editor =  sharedpreferences.edit();

                editor.putString("driver_name",jsonObject1.getString("driver_name"));
                editor.putString("driver_mobile_no", jsonObject1.getString("driver_mobile_no"));
                editor.putString("id", jsonObject1.getString("id"));
                editor.putString("driver_token", jsonObject1.getString("driver_token"));
                editor.putString("driver_image", jsonObject1.getString("driver_image"));
                editor.putString("current_order_no", "");

                editor.commit();
                startActivity(intent);
                activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));

                overridePendingTransition(R.anim.right_in, R.anim.left_out);
                finish();

            }

            else {
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        } catch (JSONException e) {
            e.printStackTrace();

        }

        return msg ;

    }

    @Override
    protected void onPostExecute(String msg) {
        super.onPostExecute(msg);

        progressDialog.dismiss();
        Toast.makeText(activity , msg , Toast.LENGTH_LONG).show();

    }
}

/*public void sign_in(){
    login1=(Button)findViewById(R.id.button);
    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(login.this,"Welcome!", Toast.LENGTH_SHORT).show();

            startActivity(intent);
        }
    });
}*/
@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce){
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true ;
    Toast.makeText(this , "Please click BACK again to exit" , Toast.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            doubleBackToExitPressedOnce = false ;
        }
    }, 2000);

    /*Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
    System.exit(0);*/

}

public boolean checkInternetConnection()
{

    ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity != null)
    {
        NetworkInfo[] inf = connectivity.getAllNetworkInfo();
        if (inf != null)
            for (int i = 0; i < inf.length; i++)
                if (inf[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }

    }
    return false;
}
}
</code>```

Please Help!
Thanks!!

EDIT 1: Thanks a lot! I've gotten the solution for this. It was a really small error on my part!

答:
From your attached JSONObject, its seems that JSONObject contains two string (error and msg) and one JSONArray named data.

So you have to parse this JSON data as below:

```<code>    .........
    ..............

    String result = WebService.postHttpResponse(mUserName, mPassword, activity);

    JSONObject jsonObject = new JSONObject(result);

    // ERROR & STATUS
    String status = jsonObject.optString("error");
    String msg = jsonObject.optString("msg");

    // DATA
    JSONArray jsonArrayData = jsonObject.getJSONArray("data");

    // First DATA JSONObject
    JSONObject jsonObject1 = jsonArrayData.getJSONObject(0);

    ........
    ..............
</code>```

To start MainActivity, use below code in onPostExecute() :

```<code>@Override
protected void onPostExecute() {
    Intent intent = new Intent(login.this, MainActivity.class);
    intent.putExtra("driver_obj" , driver); // driver should be declared as global in `UserLoginTask` class.
    activity.startActivity(intent);

    overridePendingTransition(R.anim.right_in, R.anim.left_out);
    finish();
}
</code>```

Hope this will help~

Title: Activity not opening after signing in

Body:
I'm currently creating an application that allows the user to login using a web api. While checking response of the API , i'm not getting any error.

{"error":0,"data":[{"id":"2","driver_name":"Test Driver","driver_lat":"","driver_long":"","driver_mobile_no":"9164618545","driver_password":"202cb962ac59075b964b07152d234b70","driver_token":"bef1032495ef4b2c891795fce1fa16c2","driver_image":"","is_active":"1","on_duty":"0","t_drivers":"0","created_at":"2017-07-04 06:38:22","last_activity_at":"2017-07-04 09:19:08"}],"msg":"Login Successfully."}

But while using the app, it does not go to the mainActivity.
This is the login class:-

public class login extends AppCompatActivity {
private Button login1;
Session session;
private ConstraintLayout mRootLayout;
boolean doubleBackToExitPressedOnce = false;
boolean status = false;

EditText mEdtEmail , mEdtPassword ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Answers(), new Crashlytics());
    setContentView(R.layout.activity_login);

    login1 = (Button) findViewById(R.id.button);
    mEdtEmail = (EditText) findViewById(R.id.phone_number);
    mEdtPassword = (EditText) findViewById(R.id.password);

    session = new Session(login.this);

    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(login.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

   // sign_in();

    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String mobile = mEdtEmail.getText().toString().trim();
            String password = mEdtPassword.getText().toString().trim();

            status = checkInternetConnection();

            if (status) {

                if (mobile.length() == 0) {
                    mEdtEmail.setError("Required");
                } else if (mobile.length() < 10) {
                    mEdtEmail.setError("Mobile no must be 10 char. long");
                } else if (password.length() == 0) {
                    mEdtPassword.setError("Required");
                } else {

                    new UserLoginTask(mobile, password, login.this).execute();

                }
            }
            else
            {
                Snackbar.make(mRootLayout, "You don't have Internet connection!", Snackbar.LENGTH_LONG).show();
                //  Toast.makeText(getApplicationContext(), "You don't have Internet connection", Toast.LENGTH_LONG).show();
            }
        }
    });
}

private class UserLoginTask extends AsyncTask<String, Void, String> {

    private String mUserName;
    private String mPassword;
    String msg ;
    ProgressDialog progressDialog;

    Boolean loginStatus = false;
    private Activity activity;
    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedpreferences;

    UserLoginTask(String userName, String password, Activity activity) {
        mUserName = userName;
        mPassword = password;
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        progressDialog= ProgressDialog.show(login.this, "Loading. . .","Please Wait. . .", true);
        Toast.makeText(login.this,"toast 1",Toast.LENGTH_SHORT).show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {

        try {

            String result= WebService.postHttpResponse(mUserName, mPassword, activity);

            JSONObject jsonObject = new JSONObject(result);
          //  Log.d("Json Array", "doInBackground: "+jsonObject);
           String status = jsonObject.optString("error");
         //   msg = jsonObject.optString("msg");
           // Toast.makeText(login.this,"toast 2",Toast.LENGTH_SHORT).show();
            if(status.equals("0")){

                loginStatus = true ;

                session.setLogin(true);

                JSONArray jsonarray = jsonObject.getJSONArray("data");
                JSONObject jsonObject1=jsonarray.getJSONObject(0);

                status = jsonObject1.getString("msg");
                Log.e("DRIVER NAME -----" ,jsonObject1.getString("driver_name"));

                Driver driver = new Driver();

                driver.setId(jsonObject1.getString("id"));
                driver.setDriver_name(jsonObject1.getString("driver_name"));
                driver.setDriver_lat(jsonObject1.getString("driver_lat"));
                driver.setDriver_long(jsonObject1.getString("driver_long"));
                driver.setDriver_mobile_no(jsonObject1.getString("driver_mobile_no"));
                driver.setDriver_token(jsonObject1.getString("driver_token"));
                driver.setCreated_at(jsonObject1.getString("created_at"));
                driver.setLast_activity_at(jsonObject1.getString("last_activity_at"));

                sharedpreferences = activity.getSharedPreferences("MY" , Context.MODE_PRIVATE);
                SharedPreferences.Editor editor =  sharedpreferences.edit();

                editor.putString("driver_name",jsonObject1.getString("driver_name"));
                editor.putString("driver_mobile_no", jsonObject1.getString("driver_mobile_no"));
                editor.putString("id", jsonObject1.getString("id"));
                editor.putString("driver_token", jsonObject1.getString("driver_token"));
                editor.putString("driver_image", jsonObject1.getString("driver_image"));
                editor.putString("current_order_no", "");

                editor.commit();
                startActivity(intent);
                activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));

                overridePendingTransition(R.anim.right_in, R.anim.left_out);
                finish();

            }

            else {
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        } catch (JSONException e) {
            e.printStackTrace();

        }

        return msg ;

    }

    @Override
    protected void onPostExecute(String msg) {
        super.onPostExecute(msg);

        progressDialog.dismiss();
        Toast.makeText(activity , msg , Toast.LENGTH_LONG).show();

    }
}

/*public void sign_in(){
    login1=(Button)findViewById(R.id.button);
    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(login.this,"Welcome!", Toast.LENGTH_SHORT).show();

            startActivity(intent);
        }
    });
}*/
@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce){
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true ;
    Toast.makeText(this , "Please click BACK again to exit" , Toast.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            doubleBackToExitPressedOnce = false ;
        }
    }, 2000);

    /*Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
    System.exit(0);*/

}

public boolean checkInternetConnection()
{

    ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity != null)
    {
        NetworkInfo[] inf = connectivity.getAllNetworkInfo();
        if (inf != null)
            for (int i = 0; i < inf.length; i++)
                if (inf[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }

    }
    return false;
}
}

Please Help!
Thanks!!

EDIT 1: Thanks a lot! I've gotten the solution for this. It was a really small error on my part!

Body:
From your attached JSONObject, its seems that JSONObject contains two string (error and msg) and one JSONArray named data.

So you have to parse this JSON data as below:

    .........
    ..............

    String result = WebService.postHttpResponse(mUserName, mPassword, activity);

    JSONObject jsonObject = new JSONObject(result);

    // ERROR & STATUS
    String status = jsonObject.optString("error");
    String msg = jsonObject.optString("msg");

    // DATA
    JSONArray jsonArrayData = jsonObject.getJSONArray("data");

    // First DATA JSONObject
    JSONObject jsonObject1 = jsonArrayData.getJSONObject(0);

    ........
    ..............

To start MainActivity, use below code in onPostExecute() :

@Override
protected void onPostExecute() {
    Intent intent = new Intent(login.this, MainActivity.class);
    intent.putExtra("driver_obj" , driver); // driver should be declared as global in `UserLoginTask` class.
    activity.startActivity(intent);

    overridePendingTransition(R.anim.right_in, R.anim.left_out);
    finish();
}

Hope this will help~


来源: stackexchange

问:
Clearing input field on firebase function after angular submit
The function works and submits the user input to my firebase "back-end" but I cannot figure out a clear function to empty out the input field after using ng-submit.  The input is tied to the var "emailInput" with ng-model.  Thanks for any suggestions!</p>

```<code>var newEmailref = new Firebase("https://nevermind.com");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
    $scope.email.$add(email);
    $scope.emailInput = '';
};
</code>```

答:
i didn't get you.... If add a item in firebase database the database will create key value,
      if you doing like this

```<code> var ref = firebase.database().ref('players/');

      ref.orderByValue().on("value", function(data) {
            data.forEach(function(takenData) {
             console.log("The " + takenData.key + " rating is " +
      takenData.val().email);
       });
     });
</code>```

The console.log answer will be for takenData.key is some id value like
     (-Ko7cGuymlshrS2JQEEC)
     Then takenData.val().email) is an email address...

ContentLicense: CC BY-SA 3.0

Body:
The function works and submits the user input to my firebase "back-end" but I cannot figure out a clear function to empty out the input field after using ng-submit.  The input is tied to the var "emailInput" with ng-model.  Thanks for any suggestions!

var newEmailref = new Firebase("https://nevermind.com");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
    $scope.email.$add(email);
    $scope.emailInput = '';
};

Body:
i didn't get you.... If add a item in firebase database the database will create key value,
      if you doing like this

 var ref = firebase.database().ref('players/');

      ref.orderByValue().on("value", function(data) {
            data.forEach(function(takenData) {
             console.log("The " + takenData.key + " rating is " +
      takenData.val().email);
       });
     });

The console.log answer will be for takenData.key is some id value like
     (-Ko7cGuymlshrS2JQEEC)
     Then takenData.val().email) is an email address...


问:
python incorrectly calculates number
So, this was in my exam paper and I was really confused

```<code>def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    num1 = int(num2)*2.5
    num2 = int(num1)*1.5
    print("num1:", num1, "num2:", num2)

num_input()
</code>```

say that num1 = 60, and num2 = 18, shouldn't the new numbers be:

```<code>num1: 45
num2: 90
</code>```

but why is the output:

```<code>num1: 45
num2: 67.5
</code>```

?

答:
You can use in-place swapping to resolve this:</p>

```<code>def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    num1,num2 = int(num2)*2.5, int(num1)*1.5
    print("num1:", num1, "num2:", num2)

>>>num_input()
num1: 60
num2: 18
('num1:', 45.0, 'num2:', 90.0)
</code>```

Title: python incorrectly calculates number

Body:
So, this was in my exam paper and I was really confused

def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    num1 = int(num2)*2.5
    num2 = int(num1)*1.5
    print("num1:", num1, "num2:", num2)

num_input()

say that num1 = 60, and num2 = 18, shouldn't the new numbers be:

num1: 45
num2: 90

but why is the output:

num1: 45
num2: 67.5

?

Body:
You can use in-place swapping to resolve this:

def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    num1,num2 = int(num2)*2.5, int(num1)*1.5
    print("num1:", num1, "num2:", num2)

>>>num_input()
num1: 60
num2: 18
('num1:', 45.0, 'num2:', 90.0)


问:
Datatables responsive doesn't work first time
I can't seem to make my datatable responsive work.
I've tried multiple solutions from using cdn's, changing table width, adding table responsive, changing the location of the plus sign to the left and so on.

Weirdly enough, it does work the second time the table is drawn for example if I run $("table.dataTable").resize();
I thought about calling this on the end of the ajax call but this causes a stackoverflow since it's pretty much on a loop.
Here is how I define my datatables.

Html:

```<code><div class="col-md-12 col-sm-12 col-xs-12" id="listView">
  <table id="tabela" class="table table-striped table-bordered table-hover table-responsive">
    <thead>
      <tr>
        <th>FILL</th>
        <th>FILL</th>
        <th>FILL</th>
        <th>FILL</th>
        <th>FILL</th>
        <th>FILL</th>
        <th>FILL</th>
        <th>FILL</th>
        <th>FILL</th>
        <th>FILL</th>
        <th>Ações</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</div>
</code>```

And here is how I initialize it in javascript (with jquery adapter)

JS:

```<code>tabelaGlobal = $("#tabela").DataTable({
   responsive: true,
   processing: true,
   serverSide: true,
   info: true,
   ajax: {
      url: routeListInfo,
      method: "POST",
      data: function (data) {
         data.search = typeof tabelaGlobal !== "undefined" ? tabelaGlobal.search() : "";
         delete data.columns;
      }
   },
   "lengthChange": true,
   "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "Todos"]],
   "language": {
      "lengthMenu": "_MENU_ linhas por página",
      "zeroRecords": "Desculpe nada encontrado...",
      "info": "Pagina _PAGE_ de _PAGES_",
      "infoEmpty": "",
      "processing": "",
      "search": "Procurar:",
      "emptyTable": "",
      "paginate": {
        "first": "Primeiro",
        "last": "Último",
        "next": "Próximo",
        "previous": "Anterior"
      },
      "infoFiltered": ""
   },
    columns: [
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            var spanEditar = document.createElement('span');
            $(spanEditar)
               .addClass("btn btn-primary btn-xs")
               .css('color', 'white')
               .css('cursor', 'pointer')
               .html('<i class="fa fa-pencil" aria-hidden="true"></i>')
               .attr("onClick", 'openEdit(\'' + full.id + '\')');

             var spanApagar = document.createElement('span');
             $(spanApagar)
               .addClass("btn btn-danger btn-xs")
               .css('color', 'white')
               .css("background-color", "#dd4b39")
               .css('cursor', 'pointer')
               .html('<i class="fa fa-times" aria-hidden="true"></i>')
               .attr("onClick", 'openDelete(\'' + full.id + '\')');

                return $(spanEditar).clone().wrap('<div/>').parent().html() + $(spanApagar).clone().wrap('<div/>').parent().html();
         }
      },

     ],
   "autoWidth": true,
   "order": [[0, "desc"]],
   "fnDrawCallback": function (result) {
      //$("table.dataTable").resize();
       global_resultado = result.json.data;
    },
    iDisplayStart: iDisplayStart,
});
</code>```

I tried my best indenting the code but its never like a text editor or ide ^^.

Update: After sometime working around the idea of a fix,I noticed that the problem may be in the time it needs to render and the time it "readjusts" the columns.

```<code>setTimeout(function(){
   tabelaGlobal.columns.adjust().responsive.recalc();
},1000)
</code>```

I got this to work but I don't find it really an answer. Will keep trying to find way a cleaner way of doing it

答:
This isn't by any means the correct answer in my opinion but it is a workaround.
Since I'm using pace, whenever pace finishes I check if a datatable is initialized and if it is, adjust columns.
LIke this

```<code>Pace.on('done', function () {
  if (typeof tabelaGlobal !== "undefined")
    tabelaGlobal.columns.adjust().responsive.recalc();
});
</code>```

Still would thank a better and more trustworthy answer so if anyone still has an idea. Thanks

Body:
I can't seem to make my datatable responsive work.
I've tried multiple solutions from using cdn's, changing table width, adding table responsive, changing the location of the plus sign to the left and so on.

Weirdly enough, it does work the second time the table is drawn for example if I run $("table.dataTable").resize();
I thought about calling this on the end of the ajax call but this causes a stackoverflow since it's pretty much on a loop.
Here is how I define my datatables.

Html:

        FILL
        FILL
        FILL
        FILL
        FILL
        FILL
        FILL
        FILL
        FILL
        FILL
        Ações

And here is how I initialize it in javascript (with jquery adapter)

JS:

tabelaGlobal = $("#tabela").DataTable({
   responsive: true,
   processing: true,
   serverSide: true,
   info: true,
   ajax: {
      url: routeListInfo,
      method: "POST",
      data: function (data) {
         data.search = typeof tabelaGlobal !== "undefined" ? tabelaGlobal.search() : "";
         delete data.columns;
      }
   },
   "lengthChange": true,
   "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "Todos"]],
   "language": {
      "lengthMenu": "_MENU_ linhas por página",
      "zeroRecords": "Desculpe nada encontrado...",
      "info": "Pagina _PAGE_ de _PAGES_",
      "infoEmpty": "",
      "processing": "",
      "search": "Procurar:",
      "emptyTable": "",
      "paginate": {
        "first": "Primeiro",
        "last": "Último",
        "next": "Próximo",
        "previous": "Anterior"
      },
      "infoFiltered": ""
   },
    columns: [
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            return "I am here with the purpose of being waaaaaaaaaaaay to big for this";
         }
       },
       {
         "render": function (data, type, full, meta) {
            var spanEditar = document.createElement('span');
            $(spanEditar)
               .addClass("btn btn-primary btn-xs")
               .css('color', 'white')
               .css('cursor', 'pointer')
               .html('')
               .attr("onClick", 'openEdit(\'' + full.id + '\')');

             var spanApagar = document.createElement('span');
             $(spanApagar)
               .addClass("btn btn-danger btn-xs")
               .css('color', 'white')
               .css("background-color", "#dd4b39")
               .css('cursor', 'pointer')
               .html('')
               .attr("onClick", 'openDelete(\'' + full.id + '\')');

                return $(spanEditar).clone().wrap('
').parent().html() + $(spanApagar).clone().wrap('
').parent().html();
         }
      },

     ],
   "autoWidth": true,
   "order": [[0, "desc"]],
   "fnDrawCallback": function (result) {
      //$("table.dataTable").resize();
       global_resultado = result.json.data;
    },
    iDisplayStart: iDisplayStart,
});

I tried my best indenting the code but its never like a text editor or ide ^^.

Update: After sometime working around the idea of a fix,I noticed that the problem may be in the time it needs to render and the time it "readjusts" the columns.

setTimeout(function(){
   tabelaGlobal.columns.adjust().responsive.recalc();
},1000)

I got this to work but I don't find it really an answer. Will keep trying to find way a cleaner way of doing it

Body:
This isn't by any means the correct answer in my opinion but it is a workaround.
Since I'm using pace, whenever pace finishes I check if a datatable is initialized and if it is, adjust columns.
LIke this

Pace.on('done', function () {
  if (typeof tabelaGlobal !== "undefined")
    tabelaGlobal.columns.adjust().responsive.recalc();
});

Still would thank a better and more trustworthy answer so if anyone still has an idea. Thanks


问:
What does graph argument in tf.Session() do?
I am having trouble understanding the graph argument in the tf.Session(). I tried looking up at the TensorFlow website :link but couldn't understand much.

I am trying to find out the different between tf.Session() and tf.Session(graph=some_graph_inserted_here).

Question Context

Code A (Not Working):

```<code>def predict():
    with tf.name_scope("predict"):
        with tf.Session() as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            loaded_graph = tf.get_default_graph()
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})
</code>```

This code gives the following error: ValueError: cannot add op with name hidden_layer1/kernel/Adam as that name is already used when trying to load the graph at saver = tf.train.import_meta_graph("saved_models/testing.meta")

Code B (Working):

```<code>def predict():
    with tf.name_scope("predict"):
        loaded_graph = tf.Graph()
        with tf.Session(graph=loaded_graph) as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})
</code>```

The codes does not work if I replace loaded_graph = tf.Graph() with loaded_graph = tf.get_default_graph(). Why?

Full Code if it helps:
 (https://gist.github.com/duemaster/f8cf05c0923ebabae476b83e895619ab)

答: The function tf.train.import_meta_graph("saved_models/testing.meta") add all the nodes from the meta file to the current graph. In the first code, the current graph is the default_graph which already has the ops defined, so the error. In the second case, you are loading the nodes to a new graph and so it works fine!.

Body:
I am having trouble understanding the graph argument in the tf.Session(). I tried looking up at the TensorFlow website :link but couldn't understand much.

I am trying to find out the different between tf.Session() and tf.Session(graph=some_graph_inserted_here).

Question Context

Code A (Not Working):

def predict():
    with tf.name_scope("predict"):
        with tf.Session() as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            loaded_graph = tf.get_default_graph()
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})

This code gives the following error: ValueError: cannot add op with name hidden_layer1/kernel/Adam as that name is already used when trying to load the graph at saver = tf.train.import_meta_graph("saved_models/testing.meta")

Code B (Working):

def predict():
    with tf.name_scope("predict"):
        loaded_graph = tf.Graph()
        with tf.Session(graph=loaded_graph) as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})

The codes does not work if I replace loaded_graph = tf.Graph() with loaded_graph = tf.get_default_graph(). Why?

Full Code if it helps:
 (https://gist.github.com/duemaster/f8cf05c0923ebabae476b83e895619ab)


问:
why does calling scrollToPosition creates a row behind the list?
In my recyclerview I have a swipe to delete as well as undo action.
Whenever I undo the delete action I made, a row behind the list appears.

Here is the current setup of my app:

```<code>Activity
 - Fragment
   - Recyclerview
</code>```

Here is my delete action. This is inside the recyclerview adapter:

```<code>cards.remove(pos);
notifyItemRemoved(pos);
</code>```

And here is my undo action:

```<code>#inside my fragment
adapter.undoDiscard(pos, card);
layoutManager.scrollToPosition(pos);

#inside my adapter
public void undoDiscard(int pos, Card card) {
    cards.add(pos, card);
    notifyItemInserted(pos);
}
</code>```

Here's my observations so far:

When the recyclerview is created from an Activity, the bug doesn't appear

When I turn off the animation of the recyclerview, the bug doesn't happen

The bug seems to come from scrollToPosition

The bug doesn't happen when I use notifyDataSetChanged

To illustrate the problem, here is a sample image.

After calling undo:

答:
The bug is caused by the animation of recyclerview. Thus, the solution is to turn off the animation temporarily while calling scrollToPosition. In my case I'm using a snackbar to give the user the option to undo the changes. So I'm bringing back the animation after dismissing the snackbar.

```<code>snackbar.addCallback(new Snackbar.Callback() {
        @Override
        public void onDismissed(Snackbar snackbar, int event) {
            super.onDismissed(snackbar, event);
            recyclerview.setItemAnimator(animator);
    })
</code>```

Body:
In my recyclerview I have a swipe to delete as well as undo action.
Whenever I undo the delete action I made, a row behind the list appears.

Here is the current setup of my app:

Activity
 - Fragment
   - Recyclerview

Here is my delete action. This is inside the recyclerview adapter:

cards.remove(pos);
notifyItemRemoved(pos);

And here is my undo action:

#inside my fragment
adapter.undoDiscard(pos, card);
layoutManager.scrollToPosition(pos);

#inside my adapter
public void undoDiscard(int pos, Card card) {
    cards.add(pos, card);
    notifyItemInserted(pos);
}

Here's my observations so far:

When the recyclerview is created from an Activity, the bug doesn't appear

When I turn off the animation of the recyclerview, the bug doesn't happen

The bug seems to come from scrollToPosition

The bug doesn't happen when I use notifyDataSetChanged

To illustrate the problem, here is a sample image.

After calling undo:

Body:
The bug is caused by the animation of recyclerview. Thus, the solution is to turn off the animation temporarily while calling scrollToPosition. In my case I'm using a snackbar to give the user the option to undo the changes. So I'm bringing back the animation after dismissing the snackbar.

snackbar.addCallback(new Snackbar.Callback() {
        @Override
        public void onDismissed(Snackbar snackbar, int event) {
            super.onDismissed(snackbar, event);
            recyclerview.setItemAnimator(animator);
    })


问:
Retrieving Client Information on the Server-Side via WCF
I'm using WCF to build some REST-based services. These services will be connected to via client-side Silverlight and Java applications. I would like to know some information about the requester. My question is, what class exposes requester information in WCF and how do I access it?

I know in ASP.NET I can use HttpRequest. I can even get more details via the HttpRequest.Browser property.

答:
I just read about this:

WebOperationContext.Current.IncomingRequest

where you should info about the clinet and the http request headers.

Hope it helps.

ContentLicense: CC BY-SA 2.5


问:
Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
When run the spark example:

spark-hive-tables , I get errors on hadoop UI

User class threw exception: java.lang.RuntimeException:
  java.lang.RuntimeException: Unable to instantiate
  org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

and warning

executor.CoarseGrainedExecutorBackend: An unknown (x.x.x.x:x) driver
  disconnected.

but I have start hive metastore on my spark-yarn cluster, what should I do?

答:
It means you haven't started your Metastore service, so start you metastore service where you installed hive or in the remote if you have your metastore in remote.

To start metastore use hive --service metastore

what output you got after starting metastore service


问:
How to sort a Map by value in multi layer
Here is the map with the following structure:

```<code>Map<String, Oddcurve> curves;

class Oddcurve entends Curve {
    private String curvename;
}

class Curve {
    private int curveId;
    protected Set<CurvePoint> points = new TreeSet();
}

class CurvePoint {
    private double time;
    private double value;
}
</code>```

I want to sort the curves by the time ASC, and finally return still the same map :

```<code>proxyCurves.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue));
</code>```

I write in this way, When i debug it, I can see that the sorting works fine, but finally still returns the original curves, I don't know why?

```<code>proxyCurves.values().stream().forEach(curve -> curve.setPoints(curve.getPoints().stream().sorted(new ComparableComparator<>()).collect(Collectors.toSet())));
</code>```

答:
Firstly, I would advise you to override hashCode() and equals()
methods (you may run into issues because of that).

Secondly, I would advise you to implement Comparable
interface in CurvePoint class because you are using TreeSet. Then you will be able to override
compareTo() method, and define your way of sorting.

Body:
Here is the map with the following structure:

Map<String, Oddcurve> curves;

class Oddcurve entends Curve {
    private String curvename;
}

class Curve {
    private int curveId;
    protected Set<CurvePoint> points = new TreeSet();
}

class CurvePoint {
    private double time;
    private double value;
}

I want to sort the curves by the time ASC, and finally return still the same map :

proxyCurves.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue));

I write in this way, When i debug it, I can see that the sorting works fine, but finally still returns the original curves, I don't know why?

proxyCurves.values().stream().forEach(curve -> curve.setPoints(curve.getPoints().stream().sorted(new ComparableComparator<>()).collect(Collectors.toSet())));


问:
How can I delete unwanted elements from this JSON array?
I have the following response from an API containing a JSON array and I am trying to remove all elements except for title, column, and searchSourceJSON:

```<code>"hits": [
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Integration-Enabled",
        "_score": 1,
        "_source": {
            "title": "demo Media Integration - Enabled",
            "description": "",
            "hits": 0,
            "columns": [
                "_source"
            ],
            "sort": [
                "timestamp",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"value\":\"Media Integration\",\"disabled\":false},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Integration\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Action\",\"value\":\"Enable\",\"disabled\":false},\"query\":{\"match\":{\"Action\":{\"query\":\"Enable\",\"type\":\"phrase\"}}}}],\"query\":{\"query_string\":{\"query\":\"*\",\"analyze_wildcard\":true}}}"
            }
        }
    },
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Import-True",
        "_score": 1,
        "_source": {
            "title": "demo Media Import - True",
            "description": "",
            "hits": 0,
            "columns": [
                "FormFactor",
                "_type",
                "Identity"
            ],
            "sort": [
                "_type",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"query\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"*\"}},\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"disabled\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"negate\":false,\"value\":\"Media Import\"},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Import\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Successful\",\"value\":\"True\",\"disabled\":false},\"query\":{\"match\":{\"Successful\":{\"query\":\"True\",\"type\":\"phrase\"}}}}]}"
            }
        }
    }
]
</code>```

Could someone help me figure out how to delete the unwanted elements from this JSON document using JavaScript?

EDIT: Answered, thank you everyone for the great information!

答:
Try this :

var jsonObj = [
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Integration-Enabled",
        "_score": 1,
        "_source": {
            "title": "demo Media Integration - Enabled",
            "description": "",
            "hits": 0,
            "columns": [
                "_source"
            ],
            "sort": [
                "timestamp",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"value\":\"Media Integration\",\"disabled\":false},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Integration\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Action\",\"value\":\"Enable\",\"disabled\":false},\"query\":{\"match\":{\"Action\":{\"query\":\"Enable\",\"type\":\"phrase\"}}}}],\"query\":{\"query_string\":{\"query\":\"*\",\"analyze_wildcard\":true}}}"
            }
        }
    },
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Import-True",
        "_score": 1,
        "_source": {
            "title": "demo Media Import - True",
            "description": "",
            "hits": 0,
            "columns": [
                "FormFactor",
                "_type",
                "Identity"
            ],
            "sort": [
                "_type",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"query\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"*\"}},\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"disabled\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"negate\":false,\"value\":\"Media Import\"},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Import\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Successful\",\"value\":\"True\",\"disabled\":false},\"query\":{\"match\":{\"Successful\":{\"query\":\"True\",\"type\":\"phrase\"}}}}]}"
            }
        }
    }
];

var res = jsonObj.map(function(item) {
  return {
           "title": item._source.title,
           "columns": item._source.columns,
           "searchSourceJSON": item._source.exampleSavedObjectMeta.searchSourceJSON
         };
});

console.log(res);```

Body:
I have the following response from an API containing a JSON array and I am trying to remove all elements except for title, column, and searchSourceJSON:

"hits": [
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Integration-Enabled",
        "_score": 1,
        "_source": {
            "title": "demo Media Integration - Enabled",
            "description": "",
            "hits": 0,
            "columns": [
                "_source"
            ],
            "sort": [
                "timestamp",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"value\":\"Media Integration\",\"disabled\":false},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Integration\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Action\",\"value\":\"Enable\",\"disabled\":false},\"query\":{\"match\":{\"Action\":{\"query\":\"Enable\",\"type\":\"phrase\"}}}}],\"query\":{\"query_string\":{\"query\":\"*\",\"analyze_wildcard\":true}}}"
            }
        }
    },
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Import-True",
        "_score": 1,
        "_source": {
            "title": "demo Media Import - True",
            "description": "",
            "hits": 0,
            "columns": [
                "FormFactor",
                "_type",
                "Identity"
            ],
            "sort": [
                "_type",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"query\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"*\"}},\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"disabled\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"negate\":false,\"value\":\"Media Import\"},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Import\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Successful\",\"value\":\"True\",\"disabled\":false},\"query\":{\"match\":{\"Successful\":{\"query\":\"True\",\"type\":\"phrase\"}}}}]}"
            }
        }
    }
]

Could someone help me figure out how to delete the unwanted elements from this JSON document using JavaScript?

EDIT: Answered, thank you everyone for the great information!


问:
Setup notification for private docker registry
I am trying to setup notification for my private docker registry. But i am getting the following error from the docker compose file

PS C:\mydockerregistry> docker-compose up

ERROR: The Compose file '.\docker-compose.yml' is invalid because:
  Unsupported config option for notifications: 'endpoints'

Here is my docker compose file

registry:
  restart: always
  image: registry:2
  ports:
    - 5000:5000
notifications:
  endpoints:
    - name: alistener
      url: https://requestb.in/13yg1rj1
      timeout: 500ms
      threshold: 5
      backoff: 1s```

答:
The approach I was taking was wrong. Notifications will not go in docker-compose file but docker config file
See sample config file https://github.com/docker/distribution/blob/master/cmd/registry/config-example.yml
Documentation:
https://docs.docker.com/registry/configuration/#example-development-configuration</p>


问:
pass props to selectors to filter based on that props
I need to pass props to selectors so that i can fetch the content of the clicked item from the selectors. However i could not pass the props. I tried this way but no success

```<code>const mapStateToProps = createStructuredSelector({
  features: selectFeatures(),
  getFeatureToEditById: selectFeatureToEditById(),
});

handleFeatureEdit = (event, feature) => {
  event.preventDefault();
  console.log("feature handle", feature);
  const dialog = (
    <FeatureEditDialog
      feature={feature}
      featureToEdit={selectFeatureToEditById(feature)}
      onClose={() => this.props.hideDialog(null)}
    />
  );
  this.props.showDialog(dialog);
};

selectors.js

const selectFeatureState = state => state.get("featureReducer");

const selectFeatureById = (_, props) => {
  console.log("props", _, props); #if i get the id of feature here
  # i could then filter based on that id from below selector and show
  # the result in FeatureEditDialog component
};

const selectFeatureToEditById = () =>
  createSelector(
    selectFeatureState,
    selectFeatureById,
    (features, featureId) => {
      console.log("features", features, featureId);
    }
  );
</code>```

Here is the gist for full code

https://gist.github.com/MilanRgm/80fe18e3f25993a27dfd0bbd0ede3c20

答:
Simply pass both state and props from your mapStateToProps to your selectors.

If you use a selector directly as the mapStateToProps function, it will receive the same arguments mapState does: state and ownProps (props set on the connected component).

A simple example:

```<code>// simple selector
export const getSomethingFromState = (state, { id }) => state.stuff[id]
// reselect selector
export const getStuff = createSelector(
  getSomethingFromState,
  (stuff) => stuff
)

// use it as mapDispatchToProps
const mapDispatchToProps = getSomethingFromState

const MyContainer = connect(mapDispatchToProps)(MyComponent)

// and set id as an own prop in the container when rendering
<MyContainer id='foo' />
</code>```

However you're doing some weird things like mapping a selector to reuse it later. It doesn't work that way, at least it's not intended to be used that way.

You use selectors to retrieve slices of your state and pass it as props to your connected components. Whenever the state changes, your selectors will be re-run (with some caching thanks to reselect). If something the component is actually retrieving from Redux has changed indeed, it will re-render.

So your FeatureEditDialog component should be connected as well, and should be capable of retrieving anything it needs from the Redux state, just by using props (which feature, which id, so on) in its own connect call.

this.props.showDialog(dialog); is a big code smell as well. ;)

Body:
I need to pass props to selectors so that i can fetch the content of the clicked item from the selectors. However i could not pass the props. I tried this way but no success

const mapStateToProps = createStructuredSelector({
  features: selectFeatures(),
  getFeatureToEditById: selectFeatureToEditById(),
});

handleFeatureEdit = (event, feature) => {
  event.preventDefault();
  console.log("feature handle", feature);
  const dialog = (
    <FeatureEditDialog
      feature={feature}
      featureToEdit={selectFeatureToEditById(feature)}
      onClose={() => this.props.hideDialog(null)}
    />
  );
  this.props.showDialog(dialog);
};

selectors.js

const selectFeatureState = state => state.get("featureReducer");

const selectFeatureById = (_, props) => {
  console.log("props", _, props); #if i get the id of feature here
  # i could then filter based on that id from below selector and show
  # the result in FeatureEditDialog component
};

const selectFeatureToEditById = () =>
  createSelector(
    selectFeatureState,
    selectFeatureById,
    (features, featureId) => {
      console.log("features", features, featureId);
    }
  );

Here is the gist for full code

https://gist.github.com/MilanRgm/80fe18e3f25993a27dfd0bbd0ede3c20

Body:
Simply pass both state and props from your mapStateToProps to your selectors.

If you use a selector directly as the mapStateToProps function, it will receive the same arguments mapState does: state and ownProps (props set on the connected component).

A simple example:

// simple selector
export const getSomethingFromState = (state, { id }) => state.stuff[id]
// reselect selector
export const getStuff = createSelector(
  getSomethingFromState,
  (stuff) => stuff
)

// use it as mapDispatchToProps
const mapDispatchToProps = getSomethingFromState

const MyContainer = connect(mapDispatchToProps)(MyComponent)

// and set id as an own prop in the container when rendering
<MyContainer id='foo' />

However you're doing some weird things like mapping a selector to reuse it later. It doesn't work that way, at least it's not intended to be used that way.

You use selectors to retrieve slices of your state and pass it as props to your connected components. Whenever the state changes, your selectors will be re-run (with some caching thanks to reselect). If something the component is actually retrieving from Redux has changed indeed, it will re-render.

So your FeatureEditDialog component should be connected as well, and should be capable of retrieving anything it needs from the Redux state, just by using props (which feature, which id, so on) in its own connect call.

this.props.showDialog(dialog); is a big code smell as well. ;)


问:
Getting Cannot call method "getRange" of null error
```<code>var METADATA_SHEET_NAME = 'MetaData';

function readMetaData() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName(METADATA_SHEET_NAME);
  var range = sheet.getRange(1, 2);
  var fixVersion = range.getValue();
  Logger.log(fixVersion);
  return fixVersion;
}
</code>```

In my current google script, I already have Sheet with Name MetaData. I am storing a sheet name in variable METADATA_SHEET_NAME. if I pass sheet name directly in getSheetByName() method, it works perfectly but when I am passing variable name(in which I have stored sheet name) it is giving

TypeError: Cannot call method "getRange" of null.

答:
Global variables in Google apps script aren't persistent. see top answer here for more info

Check out this blog post for loading global variables if you really need to

Body:
var METADATA_SHEET_NAME = 'MetaData';

function readMetaData() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName(METADATA_SHEET_NAME);
  var range = sheet.getRange(1, 2);
  var fixVersion = range.getValue();
  Logger.log(fixVersion);
  return fixVersion;
}

In my current google script, I already have Sheet with Name MetaData. I am storing a sheet name in variable METADATA_SHEET_NAME. if I pass sheet name directly in getSheetByName() method, it works perfectly but when I am passing variable name(in which I have stored sheet name) it is giving

TypeError: Cannot call method "getRange" of null.


问:
IIS not redirecting to maped domain
I have set up IP on BigRock for domain redirection and done binding at IIS. Now when I am browsing my Url it is showing me default site of IIS instead of my hosted one.

Please help me to suggest possible cases.

答:
You should check the host header file, as that is the only thing needs to be changed.
I believe you have the same IP address mapped for different domain.

And still if it doesn't work please check IIS installed featured list and check the features not installed,  it should work.

Title: IIS not redirecting to maped domain


问:
Fatal Error for Chromium
I am getting an error when i run my app from archive. Unable to understand this :(</p>

```<code>Jun 21 11:13:55 NOIMAC61 MyBrowser[26324]: [0621/111355.058483:ERROR:mach_port_broker.mm(100)] bootstrap_check_in: Permission denied (1100)
Jun 21 11:13:55 NOIMAC61 MyBrowser[26324]: [0621/111355.095394:ERROR:mach_broker_mac.mm(52)] Failed to initialize the MachListenerThreadDelegate
Jun 21 11:13:55 NOIMAC61 MyBrowser[26324]: [0621/111354.159264:FATAL:file_path_watcher_kqueue.cc(255)] Check failed: last_entry != 0 (0 vs. 0)
    0   Chromium Embedded Framework         0x000000011eaecfee _ZN4base5debug10StackTraceC2Ev + 30
    1   Chromium Embedded Framework         0x000000011eaed065 _ZN4base5debug10StackTraceC1Ev + 21
    2   Chromium Embedded Framework         0x000000011eb73520 _ZN7logging10LogMessageD2Ev + 80
    3   Chromium Embedded Framework         0x000000011eb71085 _ZN7logging10LogMessageD1Ev + 21
    4   Chromium Embedded Framework         0x000000011eb29ff1 _ZN4base21FilePathWatcherKQueue5WatchERKNS_8FilePathEbRKNS_8CallbackIFvS3_bELNS_8internal8CopyModeE1ELNS6_10RepeatModeE1EEE + 1441
    5   Chromium Embedded Framework         0x000000011eb2e35e _ZN4base12_GLOBAL__N_119FilePathWatcherImpl5WatchERKNS_8FilePathEbRKNS_8CallbackIFvS4_bELNS_8internal8CopyModeE1ELNS7_10RepeatModeE1EEE + 2238
    6   Chromium Embedded Framework         0x000000011eb20ee3 _ZN4base15FilePathWatcher5WatchERKNS_8FilePathEbRKNS_8CallbackIFvS3_bELNS_8internal8CopyModeE1ELNS6_10RepeatModeE1EEE + 515
    7   Chromium Embedded Framework         0x000000012109e6f2 _ZN3net8internal21DnsConfigServicePosix7Watcher5WatchEv + 722
    8   Chromium Embedded Framework         0x000000012109e3ab _ZN3net8internal21DnsConfigServicePosix13StartWatchingEv + 523
    9   Chromium Embedded Framework         0x00000001210997b3 _ZN3net16DnsConfigService11WatchConfigERKN4base8CallbackIFvRKNS_9DnsConfigEELNS1_8internal8CopyModeE1ELNS7_10RepeatModeE1EEE + 595
    10  Chromium Embedded Framework         0x0000000120e4e1c0 _ZN3net24NetworkChangeNotifierMac22DnsConfigServiceThread4InitEv + 800
    11  Chromium Embedded Framework         0x000000011ed8012e _ZN4base6Thread10ThreadMainEv + 3310
    12  Chromium Embedded Framework         0x000000011ed5f821 _ZN4base12_GLOBAL__N_110ThreadFuncEPv + 705
    13  libsystem_pthread.dylib             0x00007fffaf694aab _pthread_body + 180
    14  libsystem_pthread.dylib             0x00007fffaf6949f7 _pthread_body + 0
    15  libsystem_pthread.dylib             0x00007fffaf694221 thread_start + 13
Jun 21 11:13:55 NOIMAC61 com.apple.xpc.launchd[1] (com.es.test.7764[26324]): Service exited due to signal: Trace/BPT trap: 5 sent by exc handler[0]
</code>```

答:
Finally found an answer

I am using a script that moves the chromium framework from one location to another.
This script fetched the framework from DEBUG Folder instead of the RELEASE FOLDER.

Path is updated and it worked!!!!

Title: Fatal Error for Chromium

Body:
I am getting an error when i run my app from archive. Unable to understand this :(

Jun 21 11:13:55 NOIMAC61 MyBrowser[26324]: [0621/111355.058483:ERROR:mach_port_broker.mm(100)] bootstrap_check_in: Permission denied (1100)
Jun 21 11:13:55 NOIMAC61 MyBrowser[26324]: [0621/111355.095394:ERROR:mach_broker_mac.mm(52)] Failed to initialize the MachListenerThreadDelegate
Jun 21 11:13:55 NOIMAC61 MyBrowser[26324]: [0621/111354.159264:FATAL:file_path_watcher_kqueue.cc(255)] Check failed: last_entry != 0 (0 vs. 0)
    0   Chromium Embedded Framework         0x000000011eaecfee _ZN4base5debug10StackTraceC2Ev + 30
    1   Chromium Embedded Framework         0x000000011eaed065 _ZN4base5debug10StackTraceC1Ev + 21
    2   Chromium Embedded Framework         0x000000011eb73520 _ZN7logging10LogMessageD2Ev + 80
    3   Chromium Embedded Framework         0x000000011eb71085 _ZN7logging10LogMessageD1Ev + 21
    4   Chromium Embedded Framework         0x000000011eb29ff1 _ZN4base21FilePathWatcherKQueue5WatchERKNS_8FilePathEbRKNS_8CallbackIFvS3_bELNS_8internal8CopyModeE1ELNS6_10RepeatModeE1EEE + 1441
    5   Chromium Embedded Framework         0x000000011eb2e35e _ZN4base12_GLOBAL__N_119FilePathWatcherImpl5WatchERKNS_8FilePathEbRKNS_8CallbackIFvS4_bELNS_8internal8CopyModeE1ELNS7_10RepeatModeE1EEE + 2238
    6   Chromium Embedded Framework         0x000000011eb20ee3 _ZN4base15FilePathWatcher5WatchERKNS_8FilePathEbRKNS_8CallbackIFvS3_bELNS_8internal8CopyModeE1ELNS6_10RepeatModeE1EEE + 515
    7   Chromium Embedded Framework         0x000000012109e6f2 _ZN3net8internal21DnsConfigServicePosix7Watcher5WatchEv + 722
    8   Chromium Embedded Framework         0x000000012109e3ab _ZN3net8internal21DnsConfigServicePosix13StartWatchingEv + 523
    9   Chromium Embedded Framework         0x00000001210997b3 _ZN3net16DnsConfigService11WatchConfigERKN4base8CallbackIFvRKNS_9DnsConfigEELNS1_8internal8CopyModeE1ELNS7_10RepeatModeE1EEE + 595
    10  Chromium Embedded Framework         0x0000000120e4e1c0 _ZN3net24NetworkChangeNotifierMac22DnsConfigServiceThread4InitEv + 800
    11  Chromium Embedded Framework         0x000000011ed8012e _ZN4base6Thread10ThreadMainEv + 3310
    12  Chromium Embedded Framework         0x000000011ed5f821 _ZN4base12_GLOBAL__N_110ThreadFuncEPv + 705
    13  libsystem_pthread.dylib             0x00007fffaf694aab _pthread_body + 180
    14  libsystem_pthread.dylib             0x00007fffaf6949f7 _pthread_body + 0
    15  libsystem_pthread.dylib             0x00007fffaf694221 thread_start + 13
Jun 21 11:13:55 NOIMAC61 com.apple.xpc.launchd[1] (com.es.test.7764[26324]): Service exited due to signal: Trace/BPT trap: 5 sent by exc handler[0]


问:
Jquery didn't identify the min max float number
I am Working on Two Select Box In which User Simply select Min & Max Value from Dropdown.

I am Simply Preventing a User to select Max Value which is less than Min Value.

I am Using Jquery to Prevent the user to select the "Max Value Which is Less then Min Value"

Case 1: Example If the user selects 4.6 from Min Select Box and If
  select option less then 4.6 then it gives an error message.  But
  Problem is that if User Select options 10, 11, 12+ then it gives
  an error.

$('body').on('change', '#exp_max', function() {

  var min_exp = $('#exp_min').val();
  var max_exp = $(this).val();
  if (max_exp < min_exp) {
    console.log('Max Experience Cannot be Less then Min Experience');
    // $.Notification.autoHideNotify('error', 'top right', 'Max Experience Cannot be Less then Min Experience.','Experience');
    $(this).prop('selectedIndex', 0);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="col-lg-5">
  <select class="form-control" required data-parsley-minlength="1" id="exp_min" name="exp_min">
    <option value="">Min</option>
    <option value="-1">Last Year Student</option>
    <option value="0">Fresher</option>
    <option value="0.6" >0.6</option>
    <option value="1">1</option>
    <option value="1.6" >1.6</option>
    <option value="2">2</option>
    <option value="2.6">2.6</option>
    <option value="3">3</option>
    <option value="3.6">3.6</option>
    <option value="4">4</option>
    <option value="4.6">4.6</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
    <option value="11">11</option>
    <option value="12">12+</option>
   </select>
</div>
<div class="col-lg-5">
  <select class="form-control" data-parsley-type="number" id="exp_max" name="exp_max">
    <option value="">Max</option>
    <option value="1">1</option>
    <option value="1.6">1.6</option>
    <option value="2">2</option>
    <option value="2.6">2.6</option>
    <option value="3">3</option>
    <option value="3.6">3.6</option>
    <option value="4">4</option>
    <option value="4.6">4.6</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
    <option value="11">11</option>
    <option value="12">12+</option>
   </select>
</div></code>```

答:
You need to hide the options when you select a value for the min select dropdown. This code will be really helpful to you .

$(document).ready(function(){
 $('#exp_min').change(function(){
    var selectedValue = parseFloat($(this).val());
    $('#exp_max option').each(function(){
       if(parseFloat($(this).val()) > selectedValue) {
          $(this).css('display', 'block' );
       }else{
          $(this).css('display', 'none' );
       }
    });
    $('#exp_max').val('');
    $('#exp_max').prop('disabled', false);
 })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" required data-parsley-minlength="1" id="exp_min"  name="exp_min">
   <option value="">Min</option>
   <option value="-1">Last Year Student</option>
   <option value="0">Fresher</option>
   <option value="0.6" >0.6</option>
   <option value="1">1</option>
   <option value="1.6" >1.6</option>
   <option value="2">2</option>
   <option value="2.6">2.6</option>
   <option value="3">3</option>
   <option value="3.6">3.6</option>
   <option value="4">4</option>
   <option value="4.6">4.6</option>
   <option value="5">5</option>
   <option value="6">6</option>
   <option value="7">7</option>
   <option value="8">8</option>
   <option value="9">9</option>
   <option value="10">10</option>
   <option value="11">11</option>
   <option value="12">12+</option>
  </select>

    <select class="form-control" data-parsley-type="number" id="exp_max"  name="exp_max" disabled>
   <option value="">Max</option>
   <option value="1">1</option>
   <option value="1.6">1.6</option>
   <option value="2">2</option>
   <option value="2.6">2.6</option>
   <option value="3">3</option>
   <option value="3.6">3.6</option>
   <option value="4">4</option>
   <option value="4.6">4.6</option>
   <option value="5">5</option>
   <option value="6">6</option>
   <option value="7">7</option>
   <option value="8">8</option>
   <option value="9">9</option>
   <option value="10">10</option>
   <option value="11">11</option>
   <option value="12">12+</option>
  </select></code>```

Body:
I am Working on Two Select Box In which User Simply select Min & Max Value from Dropdown.

I am Simply Preventing a User to select Max Value which is less than Min Value.

I am Using Jquery to Prevent the user to select the "Max Value Which is Less then Min Value"

Case 1: Example If the user selects 4.6 from Min Select Box and If
  select option less then 4.6 then it gives an error message.  But
  Problem is that if User Select options 10, 11, 12+ then it gives
  an error.

$('body').on('change', '#exp_max', function() {

  var min_exp = $('#exp_min').val();
  var max_exp = $(this).val();
  if (max_exp < min_exp) {
    console.log('Max Experience Cannot be Less then Min Experience');
    // $.Notification.autoHideNotify('error', 'top right', 'Max Experience Cannot be Less then Min Experience.','Experience');
    $(this).prop('selectedIndex', 0);
  }
});

  <select class="form-control" required data-parsley-minlength="1" id="exp_min" name="exp_min">
    <option value="">Min</option>
    <option value="-1">Last Year Student</option>
    <option value="0">Fresher</option>
    <option value="0.6" >0.6</option>
    <option value="1">1</option>
    <option value="1.6" >1.6</option>
    <option value="2">2</option>
    <option value="2.6">2.6</option>
    <option value="3">3</option>
    <option value="3.6">3.6</option>
    <option value="4">4</option>
    <option value="4.6">4.6</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
    <option value="11">11</option>
    <option value="12">12+</option>
   </select>

  <select class="form-control" data-parsley-type="number" id="exp_max" name="exp_max">
    <option value="">Max</option>
    <option value="1">1</option>
    <option value="1.6">1.6</option>
    <option value="2">2</option>
    <option value="2.6">2.6</option>
    <option value="3">3</option>
    <option value="3.6">3.6</option>
    <option value="4">4</option>
    <option value="4.6">4.6</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
    <option value="11">11</option>
    <option value="12">12+</option>
   </select>

Body:
You need to hide the options when you select a value for the min select dropdown. This code will be really helpful to you .

$(document).ready(function(){
 $('#exp_min').change(function(){
    var selectedValue = parseFloat($(this).val());
    $('#exp_max option').each(function(){
       if(parseFloat($(this).val()) > selectedValue) {
          $(this).css('display', 'block' );
       }else{
          $(this).css('display', 'none' );
       }
    });
    $('#exp_max').val('');
    $('#exp_max').prop('disabled', false);
 })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" required data-parsley-minlength="1" id="exp_min"  name="exp_min">
   <option value="">Min</option>
   <option value="-1">Last Year Student</option>
   <option value="0">Fresher</option>
   <option value="0.6" >0.6</option>
   <option value="1">1</option>
   <option value="1.6" >1.6</option>
   <option value="2">2</option>
   <option value="2.6">2.6</option>
   <option value="3">3</option>
   <option value="3.6">3.6</option>
   <option value="4">4</option>
   <option value="4.6">4.6</option>
   <option value="5">5</option>
   <option value="6">6</option>
   <option value="7">7</option>
   <option value="8">8</option>
   <option value="9">9</option>
   <option value="10">10</option>
   <option value="11">11</option>
   <option value="12">12+</option>
  </select>

    <select class="form-control" data-parsley-type="number" id="exp_max"  name="exp_max" disabled>
   <option value="">Max</option>
   <option value="1">1</option>
   <option value="1.6">1.6</option>
   <option value="2">2</option>
   <option value="2.6">2.6</option>
   <option value="3">3</option>
   <option value="3.6">3.6</option>
   <option value="4">4</option>
   <option value="4.6">4.6</option>
   <option value="5">5</option>
   <option value="6">6</option>
   <option value="7">7</option>
   <option value="8">8</option>
   <option value="9">9</option>
   <option value="10">10</option>
   <option value="11">11</option>
   <option value="12">12+</option>
  </select>


问:
How to append files in input type file with multiple before uploading
I select 2 images and again I select 3 images second time before upload, the first two gets removed from input type file and last 3 images are still there. I know it's the default behavior of input type file, that it replaces the new files with new selected ones, but I want to keep all the files user selects multiple times before upload. How is it possible? I am using ajax and formdata.</p>

答:
The right way is to use
$("input[name=replyfiles]").clone().appendTo( $("input[name=replyfiles]").parent() ).val('');
 $("input[name=replyfiles]").hide(); except $("input[name=replyfiles]").val(storedFiles);.


问:
Fit gaussians (or other distributions) on my data using python
I have a database of features, a 2D np.array (2000 samples and each sample contains 100 features, 2000 X 100). I want to fit gaussian distributions to my database using python. My code is the following:

```<code>data = load_my_data() # loads a np.array with size 2000x200
clf = mixture.GaussianMixture(n_components= 50, covariance_type='full')
clf.fit(data)
</code>```

I am not sure about the parameters for example the covariance_type and how can I investigate whether the fit was occured succesfully or not.

EDIT: I debug the code to investigate what is happening with the clf.means_ and appartently it produced a matrix n_components X size_of_features 50 X 20). Is there a way that i can check that the fitting was successful, or to plot data? What are the alternatives to Gaussian mixtures (mixtures of exponential for example, I cannot find any available implementation)?

答: You can do dimensionality reduction using PCA to 3D space (let's say) and then plot means and data.</p>

Body:
I have a database of features, a 2D np.array (2000 samples and each sample contains 100 features, 2000 X 100). I want to fit gaussian distributions to my database using python. My code is the following:

data = load_my_data() # loads a np.array with size 2000x200
clf = mixture.GaussianMixture(n_components= 50, covariance_type='full')
clf.fit(data)

I am not sure about the parameters for example the covariance_type and how can I investigate whether the fit was occured succesfully or not.

EDIT: I debug the code to investigate what is happening with the clf.means_ and appartently it produced a matrix n_components X size_of_features 50 X 20). Is there a way that i can check that the fitting was successful, or to plot data? What are the alternatives to Gaussian mixtures (mixtures of exponential for example, I cannot find any available implementation)?


问:
Why does: string st = "" + 12; work in c# without conversion?
This is super dumb, but I've googled and checked references and I just cannot find an answer... Why can an int or float etc be added as part of a string without converstion but not on it's own? that is:

while this work fine:

```<code> string st = "" + 12;
</code>```

this doesn't (of course):

```<code> string st = 12;
</code>```

Where is the magic here? I know it works I just want to know WHY it works and how I control HOW the conversion is done?

答:
In the first statement, the left operand for the + is a string, and as such + becomes the concatenation operator. The compiler finds the overload for that operator which takes a string and an arbitrary value as operands. This converts both operands to strings (using ToString()) then joins them.

The second statement does not work because there's no implicit cast from int to string.

You can control how the conversion is done by using parentheses to change the order of operations (semi-effective) or by writing code to handle the conversions pre-emptively.

Body:
This is super dumb, but I've googled and checked references and I just cannot find an answer... Why can an int or float etc be added as part of a string without converstion but not on it's own? that is:

while this work fine:

 string st = "" + 12;

this doesn't (of course):

 string st = 12;

Where is the magic here? I know it works I just want to know WHY it works and how I control HOW the conversion is done?


问:
WPF - How to centre title text on a control
I'm using the XAML designer and C# within Visual Studio 2017 to create controls for an Outlook Addin. I'm currently working on an about screen for the addin.

I'm attempting to remove the icon and move the text to the centre of the header.

The example below is from Outlook's about screen, this has the header I wish to achieve.

This is my first time using XAML so I wanted to know if there's a property that needs to be changed?

Thanks in advance.

答:
I am afraid there is no property or simple way or doing this. You will probably have to create your own custom window from scratch to be able to center the title of the title bar. There is an example of how you could do this here: https://blog.magnusmontin.net/2013/03/16/how-to-create-a-custom-window-in-wpf/.

You could also take a look at the WindowChrome class: https://msdn.microsoft.com/en-us/library/system.windows.shell.windowchrome(v=vs.110).aspx.

To simply hide the minimize and maximize buttons, you could use some P/Invoke: https://blog.magnusmontin.net/2014/11/30/disabling-or-hiding-the-minimize-maximize-or-close-button-of-a-wpf-window/