问:
Timer is not getting called on scheduled time
I want to track a location every 10 minutes and send it to server through TraceDelivery async task. For this I tried to use a service and timer to get the location every 10 minutes.

But when from another activity I call the service it works only once, i.e. once TraceDelivery api gets called but not again. For testing I have given just a second delay still its not getting called again.

Also if I check if mLatLang is null and then call the TraceDelivery it it did not get called at least once. But if location is null it gets crashed with a null pointer on mLatLang.

Service code :

```<code>public class LocationTrackerService extends IntentService implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{

    private Handler handler;
    private Timer timer;
    private TimerTask timerTask;
    private GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    private LatLng mLatLang;
    LocationManager mLocationManager = null;
    boolean gps_enabled = false;
    boolean network_enabled = false;

    LocationListener[] mLocationListeners = new LocationListener[]{
            new LocationListener(LocationManager.NETWORK_PROVIDER),
            new LocationListener(LocationManager.GPS_PROVIDER)

    };

    /**
     * A constructor is required, and must call the super IntentService(String)
     * constructor with a name for the worker thread.
     */
    public LocationTrackerService() {
        super("HelloIntentService");
    }

    /**
     * The IntentService calls this method from the default worker thread with
     * the intent that started the service. When this method returns, IntentService
     * stops the service, as appropriate.
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        // Normally we would do some work here, like download a file.
        // For our sample, we just sleep for 5 seconds.
        try {
            Thread.sleep(1000);

            buildGoogleApiClient();
            mGoogleApiClient.connect();

            handler = new Handler();

                initializeLocationManager();
                requestLocation();

                startTimer(intent.getStringExtra("dl_id"), intent.getStringExtra("pt_id"), intent.getStringExtra("ur_id"),intent.getStringExtra("address"),
                        intent.getStringExtra("api_key"));

        } catch (InterruptedException e) {
            // Restore interrupt status.
            Thread.currentThread().interrupt();
        }
    }
    public void startTimer(String dlId,String ptId,String urId,String add,String key) {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask(dlId, ptId, urId,key);

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
        timer.schedule(timerTask, 1000, 1000);//
    }

    public void initializeTimerTask(final String dlId, final String ptId, final String urId, final String key) {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {

                            TraceDeliveryAsyncTask traceDeliveryAsyncTask = new TraceDeliveryAsyncTask(LocationTrackerService.this);
                            traceDeliveryAsyncTask.execute(dlId, ptId, urId, String.valueOf(mLatLang.latitude),
                                    String.valueOf(mLatLang.longitude),"", key);

                            Log.e("timer","success");

                    }
                });
            }
        };
    }

    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    protected synchronized void buildGoogleApiClient() {

        mGoogleApiClient = new GoogleApiClient.Builder(LocationTrackerService.this)
                .addConnectionCallbacks(LocationTrackerService.this)
                .addOnConnectionFailedListener(LocationTrackerService.this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onConnected(Bundle bundle) {
        // Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onConnectionSuspended(int i) {
        //  Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //    Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
    }

    private void initializeLocationManager() {
        // Log.e(Application.TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        }

        try {
            gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }

        try {
            network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        if (!gps_enabled && !network_enabled) {
            // notify user
            if(!CommonUtils.isGPSEnabled(getApplicationContext()))
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }

    }

    public class LocationListener implements android.location.LocationListener {

        public LocationListener() {
        }

        public LocationListener(String provider) {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location) {
            Log.e(TAG, "onLocationChanged: " + location);

            //get current location

            if(mLastLocation != null && !mLastLocation.equals("")) {
                mLastLocation.set(location);
                mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            }
            else {

            }

        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled: " + provider);

        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, "onProviderEnabled: " + provider);

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }

    //request for location, first by network, then by gps

    public void requestLocation() {

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 0, 0,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 0, 0,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

}
</code>```

How can I achieve this?
Please help with this.Thank you..

答: The Android AlarmManager class can trigger an intent to be sent to your application at set intervals and execute the defined task.Probably what have you been looking for</p>

Body:
I want to track a location every 10 minutes and send it to server through TraceDelivery async task. For this I tried to use a service and timer to get the location every 10 minutes.

But when from another activity I call the service it works only once, i.e. once TraceDelivery api gets called but not again. For testing I have given just a second delay still its not getting called again.

Also if I check if mLatLang is null and then call the TraceDelivery it it did not get called at least once. But if location is null it gets crashed with a null pointer on mLatLang.

Service code :

public class LocationTrackerService extends IntentService implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{

    private Handler handler;
    private Timer timer;
    private TimerTask timerTask;
    private GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    private LatLng mLatLang;
    LocationManager mLocationManager = null;
    boolean gps_enabled = false;
    boolean network_enabled = false;

    LocationListener[] mLocationListeners = new LocationListener[]{
            new LocationListener(LocationManager.NETWORK_PROVIDER),
            new LocationListener(LocationManager.GPS_PROVIDER)

    };

    /**
     * A constructor is required, and must call the super IntentService(String)
     * constructor with a name for the worker thread.
     */
    public LocationTrackerService() {
        super("HelloIntentService");
    }

    /**
     * The IntentService calls this method from the default worker thread with
     * the intent that started the service. When this method returns, IntentService
     * stops the service, as appropriate.
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        // Normally we would do some work here, like download a file.
        // For our sample, we just sleep for 5 seconds.
        try {
            Thread.sleep(1000);

            buildGoogleApiClient();
            mGoogleApiClient.connect();

            handler = new Handler();

                initializeLocationManager();
                requestLocation();

                startTimer(intent.getStringExtra("dl_id"), intent.getStringExtra("pt_id"), intent.getStringExtra("ur_id"),intent.getStringExtra("address"),
                        intent.getStringExtra("api_key"));

        } catch (InterruptedException e) {
            // Restore interrupt status.
            Thread.currentThread().interrupt();
        }
    }
    public void startTimer(String dlId,String ptId,String urId,String add,String key) {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask(dlId, ptId, urId,key);

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
        timer.schedule(timerTask, 1000, 1000);//
    }

    public void initializeTimerTask(final String dlId, final String ptId, final String urId, final String key) {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {

                            TraceDeliveryAsyncTask traceDeliveryAsyncTask = new TraceDeliveryAsyncTask(LocationTrackerService.this);
                            traceDeliveryAsyncTask.execute(dlId, ptId, urId, String.valueOf(mLatLang.latitude),
                                    String.valueOf(mLatLang.longitude),"", key);

                            Log.e("timer","success");

                    }
                });
            }
        };
    }

    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    protected synchronized void buildGoogleApiClient() {

        mGoogleApiClient = new GoogleApiClient.Builder(LocationTrackerService.this)
                .addConnectionCallbacks(LocationTrackerService.this)
                .addOnConnectionFailedListener(LocationTrackerService.this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onConnected(Bundle bundle) {
        // Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onConnectionSuspended(int i) {
        //  Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //    Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
    }

    private void initializeLocationManager() {
        // Log.e(Application.TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        }

        try {
            gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }

        try {
            network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        if (!gps_enabled && !network_enabled) {
            // notify user
            if(!CommonUtils.isGPSEnabled(getApplicationContext()))
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }

    }

    public class LocationListener implements android.location.LocationListener {

        public LocationListener() {
        }

        public LocationListener(String provider) {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location) {
            Log.e(TAG, "onLocationChanged: " + location);

            //get current location

            if(mLastLocation != null && !mLastLocation.equals("")) {
                mLastLocation.set(location);
                mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            }
            else {

            }

        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled: " + provider);

        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, "onProviderEnabled: " + provider);

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }

    //request for location, first by network, then by gps

    public void requestLocation() {

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 0, 0,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 0, 0,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

}

How can I achieve this?
Please help with this.Thank you..


来源: stackexchange

问:
View Background HTML page in Chrome Extension
I am working on a Chrome extension. The purpose is to display data gathered from several servers on a page. I am utilizing the Chrome extension's ability to run as a background process whenever the PC is on so that data is always being gathered.

Manifest.json

```<code>{
   "manifest_version": 2,

   "name": "Data Hub",
   "description": "This extension gathers and analyzes data from several servers",
   "version": "1.0",

   "browser_action": {
      "default_icon": "icon.png",
      "default_popup": "popup.html"
   },
   "background": {
      "page": "background.html"
   },
   "permissions":[
      "background"
   ],
}
</code>```

Popup.html and Popup.js

Opens a new instance of Background.html when the popup icon is clicked.

Work.js

Infinite loop: makes AJAX requests, processes data, and updates Background.html. Script is located in my extension's folder.

Background.html

Each instance calls its own instance of Work.js.

If I click the popup, a new instance of Background.html opens in a new tab. I can see in the chrome://extensions/ that there are now 2 instances of Background.html. It begins displaying data starting at this instant in time and I can see the page's HTML elements. When the tab is closed, that data is lost.

I would like to be able to see the HTML elements of the original Background.html page. The original instance has been running since start-up and continues running when Chrome is closed, and therefore it contains all the data.

In chrome://extensions/ when I click to view the original instance of Background.html, I can only see the developer tools, not the HTML elements on the page.

答:
Just because a file is named background.html it doesn't become a background page when you open it in a tab. It becomes just another page that has its own context, document, window - and it all exists only until that tab is closed. The extensions have just one real background page that's declared in "background" section of manifest.json.

Make sure to read the extensions architecture overview and rework your code. You can persist data in chrome.storage.local or you can use chrome.extension.getBackgroundPage() in other pages of your extension to access the real and only background page window object that will expose global variables and functions.

ContentLicense: CC BY-SA 3.0

Body:
I am working on a Chrome extension. The purpose is to display data gathered from several servers on a page. I am utilizing the Chrome extension's ability to run as a background process whenever the PC is on so that data is always being gathered.

Manifest.json

{
   "manifest_version": 2,

   "name": "Data Hub",
   "description": "This extension gathers and analyzes data from several servers",
   "version": "1.0",

   "browser_action": {
      "default_icon": "icon.png",
      "default_popup": "popup.html"
   },
   "background": {
      "page": "background.html"
   },
   "permissions":[
      "background"
   ],
}

Popup.html and Popup.js

Opens a new instance of Background.html when the popup icon is clicked.

Work.js

Infinite loop: makes AJAX requests, processes data, and updates Background.html. Script is located in my extension's folder.

Background.html

Each instance calls its own instance of Work.js.

If I click the popup, a new instance of Background.html opens in a new tab. I can see in the chrome://extensions/ that there are now 2 instances of Background.html. It begins displaying data starting at this instant in time and I can see the page's HTML elements. When the tab is closed, that data is lost.

I would like to be able to see the HTML elements of the original Background.html page. The original instance has been running since start-up and continues running when Chrome is closed, and therefore it contains all the data.

In chrome://extensions/ when I click to view the original instance of Background.html, I can only see the developer tools, not the HTML elements on the page.


问:
How to find no of rows with same value in php mysql
I have one table with event_id & image_id. I want to find the no of rows which with the same value -> max in this table.

means in this table output should like:
1508706279  -> image_id
4  -> no of rows

here is my table.

below is the code which i have tried.

```<code>$sql2 = "select image_id, COUNT(*) as count from user_likes where event_id  = '$id' GROUP BY image_id";

                    if($result2 = mysqli_query($conn, $sql2)) {

                        $result1 = mysqli_fetch_array($result2);

                        $win = $result1['image_id'];
                        $count = $result1['count'];

                    }
</code>```

Now, i can't understand what is issue but this code works fine when there are rows between id 52 to 60
it shows output:

1508706279  -> image_id
4  -> no of rows

but when i add two more rows with id 64 & 65
it shows output:

818525590  -> image_id
1  -> no of rows

help me in this what mistake i am doing here.!!

答:
Your query return a  collection of image_id and count.
The collection is not ordered  so you have the first one from select
if you need  the max try ordering by count(*) desc </p>

```<code>  $sql2 = "select image_id, COUNT(*) as count
            from user_likes
            where event_id  = '$id'
            GROUP BY image_id
            ORDER BY count(*) DESC";
</code>```

<p>and you can limit to 1 if you need one row only </p>

```<code>  $sql2 = "select image_id, COUNT(*) as count
            from user_likes
            where event_id  = '$id'
            GROUP BY image_id
            ORDER BY count(*) DESC LIMIT 1";
</code>```

Body:
I have one table with event_id & image_id. I want to find the no of rows which with the same value -> max in this table.

means in this table output should like:
1508706279  -> image_id
4  -> no of rows

here is my table.

below is the code which i have tried.

$sql2 = "select image_id, COUNT(*) as count from user_likes where event_id  = '$id' GROUP BY image_id";

                    if($result2 = mysqli_query($conn, $sql2)) {

                        $result1 = mysqli_fetch_array($result2);

                        $win = $result1['image_id'];
                        $count = $result1['count'];

                    }

Now, i can't understand what is issue but this code works fine when there are rows between id 52 to 60
it shows output:

1508706279  -> image_id
4  -> no of rows

but when i add two more rows with id 64 & 65
it shows output:

818525590  -> image_id
1  -> no of rows

help me in this what mistake i am doing here.!!

Body:
Your query return a  collection of image_id and count.
The collection is not ordered  so you have the first one from select
if you need  the max try ordering by count(*) desc

  $sql2 = "select image_id, COUNT(*) as count
            from user_likes
            where event_id  = '$id'
            GROUP BY image_id
            ORDER BY count(*) DESC";

and you can limit to 1 if you need one row only

  $sql2 = "select image_id, COUNT(*) as count
            from user_likes
            where event_id  = '$id'
            GROUP BY image_id
            ORDER BY count(*) DESC LIMIT 1";


问:
Angularjs collapsable table with php mysql
Using php to write a query to mysql which produces a json rest return that I am manipulating with angularjs.

My data appears as 2 columns: Parent, Child.

PARENT  | CHILD
parent1 | child1
parent1 | child2
parent2 | child1
parent3 | child1
parent3 | child2

I am attempting to make an html table of Parents. After expanding the row, all children will be listed underneath.

I would like only 1 row per parent.

However (using the fake data from above)my current html table is displaying..essentially repeating parents
Parent1
  |-Child 1
  |-Child 2
Parent1
  |-Child 1
  |-Child 2
 ...

Is there something I can do with angular, or perhaps a way of modifying my json object in a way to make the desired result possible?

              <button class="btn btn-warning" ng-if="parent.expanded" ng-click="parent.expanded = false">-</button>
              <button class="btn btn-info" ng-if="!parent.expanded" ng-click="parent.expanded = true">+</button>

            {{parent.name}}

            {{parent.child}}

```

答:
```<code>    Html

   <!DOCTYPE html>

<head>
  <meta charset="utf-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width">
  <link rel="stylesheet" href="style.css">

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-animate.min.js"></script>
  <script src="script.js"></script>

</head>

<body ng-app="expandCollapseApp">

  <div ng-controller="expandCollapseCtrl">
    <div class="container">

      <div class="expandcollapse-item">
        <div ng-click="active = !active" ng-class="{'expandcollapse-heading-collapsed': active, 'expandcollapse-heading-expanded': !active}">
          <p>Parent 1</p></p>
        </div>

        <div class="slideDown" ng-hide="active">
          <div class="expand-collapse-content">
            <table>
              <tr>
                <td>
                  child1
                </td>
                <td>
                  child2
                </td>
              </tr>
            </table>
          </div>
        </div>
      </div>

      <div class="expandcollapse-item">
        <div ng-click="active1 = !active1" ng-class="{'expandcollapse-heading-collapsed': active1, 'expandcollapse-heading-expanded': !active1}">
          <p>Parent 2</p>
        </div>

        <div class="slideDown" ng-hide="active1">
          <div class="expand-collapse-content">
           <table>
              <tr>
                <td>
                  child1
                </td>
                <td>
                  child2
                </td>
              </tr>
            </table>
          </div>
        </div>
      </div>

    </div>
  </div>

</body>

</html>

    Controller

        var expandCollapseApp = angular.module('expandCollapseApp', ['ngAnimate']);

        expandCollapseApp.controller('expandCollapseCtrl', function ($scope) {
                $scope.active = true;
                $scope.active1 = true;

        });

    CSS
        .container {
          margin-top:100px;
          border: 1px solid blue;
          border-right: 1px solid blue;
        }

        .expandcollapse-item {
          overflow: hidden;
          border-top:1px solid blue;
        }

        .expandcollapse-heading-collapsed {
          cursor: pointer;
          padding: 15px 20px;
          position: relative;
          z-index: 100000000;
          color: black;
          background-color: white;

        }

        .expandcollapse-item:first-of-type {
          border-top:0px;
        }

        .expandcollapse-heading-collapsed p{
          font-size: 16px;
          font-weight: normal;
          margin:0px;
        }

        .expandcollapse-heading-expanded {
          cursor: pointer;
          z-index: 100000000;
          padding: 15px 20px;
          position: relative;
          color: white;
          background-color: black;
          border: 1px solid blue;
        }

        .expandcollapse-heading-expanded p{
          font-size: 16px;
          font-weight: bold;
          margin:0px;
        }

        .expandcollapse-heading-collapsed > span,
        .expandcollapse-heading-expanded > span {
          position:absolute;
          top: 25px;
          right: 15px;
          font-size: 20px;
          line-height: 0px;
        }

        .expand-collapse-content {
          padding: 20px;
        }

        /*
        animation:*/

        .slideDown.ng-hide {
          height:0;
          transition:height 0.35s ease;
          overflow:hidden;
          position:relative;
        }

        .slideDown {
          height:141px;
          transition:height 0.35s ease;
          overflow:hidden;
          position:relative;
        }

        .slideDown.ng-hide-remove,
        .slideDown.ng-hide-add {
          /* remember, the .hg-hide class is added to element
          when the active class is added causing it to appear
          as hidden. Therefore set the styling to display=block
          so that the hide animation is visible */
          display:block!important;
        }

        .slideDown.ng-hide-add {
          animation-name: hide;
          -webkit-animation-name: hide;

          animation-duration: .5s;
          -webkit-animation-duration: .5s;

          animation-timing-function: ease-in;
          -webkit-animation-timing-function: ease-in;
        }

        .slideDown.ng-hide-remove {
          animation-name: show;
          -webkit-animation-name: show;

          animation-duration: .5s;
          -webkit-animation-duration: .5s;

          animation-timing-function: ease-out;
          -webkit-animation-timing-function: ease-out;
        }
</code>```

Demo

Body:
    Html

   <!DOCTYPE html>

<head>
  <meta charset="utf-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width">
  <link rel="stylesheet" href="style.css">

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-animate.min.js"></script>
  <script src="script.js"></script>

</head>

<body ng-app="expandCollapseApp">

  <div ng-controller="expandCollapseCtrl">
    <div class="container">

      <div class="expandcollapse-item">
        <div ng-click="active = !active" ng-class="{'expandcollapse-heading-collapsed': active, 'expandcollapse-heading-expanded': !active}">
          <p>Parent 1</p></p>
        </div>

        <div class="slideDown" ng-hide="active">
          <div class="expand-collapse-content">
            <table>
              <tr>
                <td>
                  child1
                </td>
                <td>
                  child2
                </td>
              </tr>
            </table>
          </div>
        </div>
      </div>

      <div class="expandcollapse-item">
        <div ng-click="active1 = !active1" ng-class="{'expandcollapse-heading-collapsed': active1, 'expandcollapse-heading-expanded': !active1}">
          <p>Parent 2</p>
        </div>

        <div class="slideDown" ng-hide="active1">
          <div class="expand-collapse-content">
           <table>
              <tr>
                <td>
                  child1
                </td>
                <td>
                  child2
                </td>
              </tr>
            </table>
          </div>
        </div>
      </div>

    </div>
  </div>

</body>

</html>

    Controller

        var expandCollapseApp = angular.module('expandCollapseApp', ['ngAnimate']);

        expandCollapseApp.controller('expandCollapseCtrl', function ($scope) {
                $scope.active = true;
                $scope.active1 = true;

        });

    CSS
        .container {
          margin-top:100px;
          border: 1px solid blue;
          border-right: 1px solid blue;
        }

        .expandcollapse-item {
          overflow: hidden;
          border-top:1px solid blue;
        }

        .expandcollapse-heading-collapsed {
          cursor: pointer;
          padding: 15px 20px;
          position: relative;
          z-index: 100000000;
          color: black;
          background-color: white;

        }

        .expandcollapse-item:first-of-type {
          border-top:0px;
        }

        .expandcollapse-heading-collapsed p{
          font-size: 16px;
          font-weight: normal;
          margin:0px;
        }

        .expandcollapse-heading-expanded {
          cursor: pointer;
          z-index: 100000000;
          padding: 15px 20px;
          position: relative;
          color: white;
          background-color: black;
          border: 1px solid blue;
        }

        .expandcollapse-heading-expanded p{
          font-size: 16px;
          font-weight: bold;
          margin:0px;
        }

        .expandcollapse-heading-collapsed > span,
        .expandcollapse-heading-expanded > span {
          position:absolute;
          top: 25px;
          right: 15px;
          font-size: 20px;
          line-height: 0px;
        }

        .expand-collapse-content {
          padding: 20px;
        }

        /*
        animation:*/

        .slideDown.ng-hide {
          height:0;
          transition:height 0.35s ease;
          overflow:hidden;
          position:relative;
        }

        .slideDown {
          height:141px;
          transition:height 0.35s ease;
          overflow:hidden;
          position:relative;
        }

        .slideDown.ng-hide-remove,
        .slideDown.ng-hide-add {
          /* remember, the .hg-hide class is added to element
          when the active class is added causing it to appear
          as hidden. Therefore set the styling to display=block
          so that the hide animation is visible */
          display:block!important;
        }

        .slideDown.ng-hide-add {
          animation-name: hide;
          -webkit-animation-name: hide;

          animation-duration: .5s;
          -webkit-animation-duration: .5s;

          animation-timing-function: ease-in;
          -webkit-animation-timing-function: ease-in;
        }

        .slideDown.ng-hide-remove {
          animation-name: show;
          -webkit-animation-name: show;

          animation-duration: .5s;
          -webkit-animation-duration: .5s;

          animation-timing-function: ease-out;
          -webkit-animation-timing-function: ease-out;
        }

Demo


问:
Can't run Insert and Select LAST_INSERT_ID() in the same query?
I am using node to connect to mysql and I need to run an insert and then immediately run a select last_insert_id().

```<code>insert into data_temp values (null, '{"test":{"id":12,"otherdata":"x","otherdata2":"y"}}');
SELECT LAST_INSERT_ID();
</code>```

In mysql workbench this query works but gives me an error saying:

```<code>SELECT LAST_INSERT_ID() )
</code>```

Error Code: 1064. You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near ')' at line 2  0.047 sec

It actually returns the correct id but because it is throwing an error on the last part node is catching the error.

答:
There is an issue in your insert query you just missed to put the name of your columns

Do like this

```<code>insert into data_temp (`col1`, `col2`) values (null, '{"test":
{"id":12,"otherdata":"x","otherdata2":"y"}}'); SELECT LAST_INSERT_ID();
</code>```

In place of col1and  col2 put your columns name then it will work for you.

Body:
I am using node to connect to mysql and I need to run an insert and then immediately run a select last_insert_id().

insert into data_temp values (null, '{"test":{"id":12,"otherdata":"x","otherdata2":"y"}}');
SELECT LAST_INSERT_ID();

In mysql workbench this query works but gives me an error saying:

SELECT LAST_INSERT_ID() )

Error Code: 1064. You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near ')' at line 2  0.047 sec

It actually returns the correct id but because it is throwing an error on the last part node is catching the error.

Body:
There is an issue in your insert query you just missed to put the name of your columns

Do like this

insert into data_temp (`col1`, `col2`) values (null, '{"test":
{"id":12,"otherdata":"x","otherdata2":"y"}}'); SELECT LAST_INSERT_ID();

In place of col1and  col2 put your columns name then it will work for you.


问:
Return the inserted sub-document
Im building an app where i need to add messages as sub documents in a chat room. i need to return the data of the the sub document as soon as i insert it to the existing room. this is my code

```<code>  Room.findOne({ roomname: data.room }, (err, room) => {
    room.messages.push({ username: data.username, message: data.message });
    room.save((err, room) => {
      socket.broadcast.to(data.room).emit("new message", {
          username: room.messages.slice(-1).name,
          message: room.messages.slice(-1).message,
          createdat: room.messages.slice(-1).createdat
      });
    });
  });
</code>```

So this the code i have used to retrieve last sub document. Is there any other way to achieve this?

答:
```<code>room.messages.slice(-1).name
</code>```

This is incorrect, demo below

```<code>[1,2,3].slice(-1)
// returns [3], not 3
</code>```

You still have to use index

```<code>room.messages.slice(-1)[0].name
// or simply
room.messages[room.messages.length - 1].name
</code>```

Title: Return the inserted sub-document

Body:
Im building an app where i need to add messages as sub documents in a chat room. i need to return the data of the the sub document as soon as i insert it to the existing room. this is my code

  Room.findOne({ roomname: data.room }, (err, room) => {
    room.messages.push({ username: data.username, message: data.message });
    room.save((err, room) => {
      socket.broadcast.to(data.room).emit("new message", {
          username: room.messages.slice(-1).name,
          message: room.messages.slice(-1).message,
          createdat: room.messages.slice(-1).createdat
      });
    });
  });

So this the code i have used to retrieve last sub document. Is there any other way to achieve this?

Body:
room.messages.slice(-1).name

This is incorrect, demo below

[1,2,3].slice(-1)
// returns [3], not 3

You still have to use index

room.messages.slice(-1)[0].name
// or simply
room.messages[room.messages.length - 1].name


答:
Use .findOneAndUpdate() with $push instead. That way you only touch the database "once", and it also avoids the problem that something else possibly modifies the document and you end up overwriting that. This avoids the danger of the .find() then .save() pattern:

```<code>Room.findOneAndUpdate(
  { roomname: data.room },
  { "$push": {
    "messages": { username: data.username, message: data.message }
  }},
  { "new": true },
  (err, room) => {
    let message = room.messages.slice(-1)[0];
    socket.broadcast.to(data.room).emit(
      "new message",
      Object.keys(message).filter(k => k !== "_id")
        .reduce((acc,curr) => Object.assign(acc,{ [curr]: message[curr] }),{})
    );
  }
);
</code>```

Also, just .slice(-1)[0] to get the whole object and just return it, or filter out the unwanted keys just as shown above.

Or even simply just return all the fields from the array element and $slice the array to return from the query from the server:

```<code>Room.findOneAndUpdate(
  { roomname: data.room },
  { "$push": {
    "messages": { username: data.username, message: data.message }
  }},
  { "new": true, "fields":  { "messages": { "$slice": -1 } } },
  (err, room) => {
    socket.broadcast.to(data.room).emit(
      "new message", room.messages[0]
    );
  }
);
</code>```

Title: Return the inserted sub-document

Body:
Use .findOneAndUpdate() with $push instead. That way you only touch the database "once", and it also avoids the problem that something else possibly modifies the document and you end up overwriting that. This avoids the danger of the .find() then .save() pattern:

Room.findOneAndUpdate(
  { roomname: data.room },
  { "$push": {
    "messages": { username: data.username, message: data.message }
  }},
  { "new": true },
  (err, room) => {
    let message = room.messages.slice(-1)[0];
    socket.broadcast.to(data.room).emit(
      "new message",
      Object.keys(message).filter(k => k !== "_id")
        .reduce((acc,curr) => Object.assign(acc,{ [curr]: message[curr] }),{})
    );
  }
);

Also, just .slice(-1)[0] to get the whole object and just return it, or filter out the unwanted keys just as shown above.

Or even simply just return all the fields from the array element and $slice the array to return from the query from the server:

Room.findOneAndUpdate(
  { roomname: data.room },
  { "$push": {
    "messages": { username: data.username, message: data.message }
  }},
  { "new": true, "fields":  { "messages": { "$slice": -1 } } },
  (err, room) => {
    socket.broadcast.to(data.room).emit(
      "new message", room.messages[0]
    );
  }
);


问:
Excel SUM across sheets: determine row based on current cell
Consider this formula, which sums the content of cells A6 in the worksheet range from RbStart to RbEnd.

```<code>=SUM(RbStart:RbEnd!A6)
</code>```

Is there a way to make A6 dynamic in the sense that it takes the row number from the current cell's row? The reason is ask is that my first sheet is a sheet that consolidates a dynamic number of other sheets, located between RbStart and RbEnd (RbStart and RbEnd are just helper sheets to be able to include a dynamic number of sheets.)

The rows on the first sheet are dynamic. This is OK because Excel will automatically update the cell reference when you add additional rows. The problem is that for technical reasons during row generation we have blank rows in between, which are removed afterwards. But when you do that, Excel does not update the formula, so it goes out of sync with the dynamic sheets it sums.

You can simulate this as follows:

Put my formula in cell A6.

Drag it down to copy. Note how in subsequent rows, it becomes A7, A8, A9, A10, etc.

Now delete, say, row 9. Note how formula in row 9 no refers A10.

Since the same blank rows are deleted on the dynamic sheets, it now refers the wrong row. If I could somehow change the SUM formula such that instead of A6 it takes the row that the current cell is on, the problem would be solved.

I hope I am making sense. Happy to clarify.

答:
Well the first thing that came in my mind was to use below formula

```<code>=SUM(INDIRECT("'Sheet1:Sheet3'!A"&ROW()))
</code>```

But then I realized INDIRECT does not work here.

So you'll have to list down names of all the sheets somewhere and refer that list in formula. Using named range will be a better option here. See this link for details on named range. You can then add/remove sheet names in this list as and when required. After that you can use the following formula

```<code>=SUMPRODUCT(SUMIF(INDIRECT("'" & NamedRange &"'!A" & ROW()),"<>0"))
</code>```

or you can use below array formula

```<code>=SUM(N(INDIRECT(NamedRange & "!A"&ROW())))
</code>```

Being an array formula, commit it by pressing Ctrl+Shift+Enter.

Instead of named range you can also use cell range directly. Assuming you have list of sheet names in Cell AA1:AA5 then formula becomes

```<code>SUMPRODUCT(SUMIF(INDIRECT("'" & $AA$1:$AA$5 &"'!A" & ROW()),"<>0"))
</code>```

Other option would be to use VBA.

Body:
Consider this formula, which sums the content of cells A6 in the worksheet range from RbStart to RbEnd.

=SUM(RbStart:RbEnd!A6)

Is there a way to make A6 dynamic in the sense that it takes the row number from the current cell's row? The reason is ask is that my first sheet is a sheet that consolidates a dynamic number of other sheets, located between RbStart and RbEnd (RbStart and RbEnd are just helper sheets to be able to include a dynamic number of sheets.)

The rows on the first sheet are dynamic. This is OK because Excel will automatically update the cell reference when you add additional rows. The problem is that for technical reasons during row generation we have blank rows in between, which are removed afterwards. But when you do that, Excel does not update the formula, so it goes out of sync with the dynamic sheets it sums.

You can simulate this as follows:

Put my formula in cell A6.

Drag it down to copy. Note how in subsequent rows, it becomes A7, A8, A9, A10, etc.

Now delete, say, row 9. Note how formula in row 9 no refers A10.

Since the same blank rows are deleted on the dynamic sheets, it now refers the wrong row. If I could somehow change the SUM formula such that instead of A6 it takes the row that the current cell is on, the problem would be solved.

I hope I am making sense. Happy to clarify.

Body:
Well the first thing that came in my mind was to use below formula

=SUM(INDIRECT("'Sheet1:Sheet3'!A"&ROW()))

But then I realized INDIRECT does not work here.

So you'll have to list down names of all the sheets somewhere and refer that list in formula. Using named range will be a better option here. See this link for details on named range. You can then add/remove sheet names in this list as and when required. After that you can use the following formula

=SUMPRODUCT(SUMIF(INDIRECT("'" & NamedRange &"'!A" & ROW()),"<>0"))

or you can use below array formula

=SUM(N(INDIRECT(NamedRange & "!A"&ROW())))

Being an array formula, commit it by pressing Ctrl+Shift+Enter.

Instead of named range you can also use cell range directly. Assuming you have list of sheet names in Cell AA1:AA5 then formula becomes

SUMPRODUCT(SUMIF(INDIRECT("'" & $AA$1:$AA$5 &"'!A" & ROW()),"<>0"))

Other option would be to use VBA.


问:
making a jar file for console
I have a program without a GUI and I use console! So first I read a line from a user from console

BufferedReader userReader = new BufferedReader(new InputStreamReader(System.in));

and then I will write an answer for the user in the console!

System.out.println("Server:"+output);

I want to create a jar file for it ! but how can i show my console in jar file with out using GUI?
please help me thanks.

答:
First, there are no such things as "console JAR" and "GUI JAR". There are different VM launchers for console and GUI modes, though. Or, more precisely, there are different launchers one of which has console, the other one hasn't, but both of them are capable of displaying a GUI if your program has one. These launchers are named "java" (console version) and javaw (no console version).

To start a JAR with a specific launcher, use "javaw -jar JARFILE" or "java -jar JARFILE" command. If you start the console version without opening a console before doing it, then the console closes as soon as your program is finished. This means if you want to see your output you should either not terminate your program too quickly or just start a console first (Win+R, "cmd", Enter) and run "java -jar ..." from the console.

The other way is to go to the Windows Control Panel and change the program associated with the JAR extension from "javaw" to "java". This will make every JAR in the system use console. For JARs with GUI this will only introduce an inconvenience of having another window open. Sometimes it is what you want, sometimes not.

ContentLicense: CC BY-SA 2.5

Title: making a jar file for console


问:
CNN architecture
At first, this question is less about programming itself but about some logic behind the CNN architecture.
I do understand how every layer works but my only question is: Does is make sense to separate the ReLU and Convolution-Layer? I mean, can a ConvLayer exist and work and update its weights by using backpropagation without having a ReLU behind it?

I thought so. This is why I created the following independent layers:

ConvLayer

ReLU

Fully Connected

Pooling

Transformation (transform the 3D output into one dimension) for ConvLayer -> Fully Connected.

I am thinking about merging Layer 1 and 2 into one. What should I go for?

答:
Can it exist?

Yes. It can. There's nothing that stops neural networks from working without non-linearity modules in the model. The thing is, skipping the non-linearity module  between two adjacent layers is equivalent to just a linear combination of inputs at layer 1 to get output at layer 2

M1 : Input =====>  L1 ====> ReLU ====> L2 =====> Output

M2 : Input =====>  L1 ====> ......... ====> L2 =====> Output

M3 : Input =====> L1 =====> Output

M2 & M3 are equivalent since the parameters adjust themselves over the training period to generate the same output. If there is any pooling involved in between, this may not be true but as long as the layers are consecutive, the network structure is just one large linear combination (Think PCA)

There is nothing that prevents the gradient updates & back-propagation throughout the network.

What should you do?

Keep some form of non-linearity between distinct layers. You may create convolution blocks which contain more than 1 convolution layer in it, but you should include a non-linear function at the end of these blocks and definitely after the dense layers. For the dense layer not-using an activation function is completely equivalent to using a single layer.

Have a look here Quora : Role of activation functions

Title: CNN architecture


问:
PHP Search query result ORDER BY not working
I have this code to search database. It now works perfectly but i want to change the order of which it displays. Below is my code.

```<code>if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET["mainSearch"]);

  foreach ($query as $text)
  {
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
  }
  $condition = substr($condition, 0, -4);

  $order = "ORDER BY quiz_id DESC";
  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;
  $result = $db->query($sql_query);
  $resultCount = $db->querySingle($sql_query_count);

  if ($resultCount > 0)
  {
  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '<div class="quesbox_3">
            <div class="questitle">
                <h2>'.$row["question"].'</h2>
            </div>
            <div class="quesanswer">'.$row["answer"].'</div>
        </div>';
      }
  }
  }
  else
  {
      echo "No results found";
  }
}
</code>```

I want the ORDER of which result show to be from bottom to top. Please how can i add this properly as current code isn't working.

答:
Query Space issues. can you try with this query

```<code> $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;
</code>```

Body:
I have this code to search database. It now works perfectly but i want to change the order of which it displays. Below is my code.

if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET["mainSearch"]);

  foreach ($query as $text)
  {
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
  }
  $condition = substr($condition, 0, -4);

  $order = "ORDER BY quiz_id DESC";
  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;
  $result = $db->query($sql_query);
  $resultCount = $db->querySingle($sql_query_count);

  if ($resultCount > 0)
  {
  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '

'.$row["question"].'

'.$row["answer"].'

';
      }
  }
  }
  else
  {
      echo "No results found";
  }
}

I want the ORDER of which result show to be from bottom to top. Please how can i add this properly as current code isn't working.

Body:
Query Space issues. can you try with this query

 $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;


问:
CustomView dependency injection with dagger 2 (within activity scope)
My question is similar to this.

So for instance, I have a LiveData implementation:

```<code>public class CustomLiveData extends LiveData<SomeEvent> {

    @Inject
    public CustomLiveData(@ActivityContext Context context) {
        //....
    }

}
</code>```

that I want to inject into a custom view:

```<code>public class CustomView extends View {
   @Inject
   SomeApplicationProvider anyProvider;

   @Inject
   CustomLiveData dataProvider;
   // Getting @com.di.qualifiers.ActivityContext  android.content.Context cannot be provided without an @Provides-annotated method.
   // @com.di.qualifiers.ActivityContext android.content.Context is injected at com.repositories.CustomLiveData.<init>(context)
   // com.repositories.CustomLiveData is injected at com.ui.CustomView.dataProvider com.ui.CustomView is injected at
   // com.di.ApplicationComponent.inject(view)

   public CustomView(Context context) { this(context, null); }
   public CustomView(Context AttributeSet attrs) {
      super(context, attrs);

      // Works ok for application provider
      Application.getComponent(context).inject(this);
   }
}
</code>```

And here is the rest of DI classes:

```<code>@ApplicationScope
@Component(
        modules = {AndroidInjectionModule.class,
                ActivityBuilder.class
        })

public interface ApplicationComponent extends AndroidInjector<MyApp> {

    void inject(MyApp application);

    void inject(CustomView view);

    @Component.Builder
    abstract class Builder extends AndroidInjector.Builder<MyApp> {

        public abstract ApplicationComponent build();
    }
}

@ActivityScope
@Module (subcomponents = MainActivitySubcomponent.class)
public abstract class ActivityBuilder {

    @Binds
    @IntoMap
    @ActivityKey(MainActivity.class)
    abstract AndroidInjector.Factory<? extends Activity>
    bindActivityInjectorFactory(MainActivitySubcomponent.Builder builder);

    //...

}

@Subcomponent(modules = {MainActivityModule.class})
public interface MainActivitySubcomponent extends AndroidInjector<MainActivity> {

    @Subcomponent.Builder
    abstract class Builder extends AndroidInjector.Builder<MainActivity> {

    }
}

@ActivityScope
@Module
public class MainActivityModule {

    @Provides
    @ActivityContext
    public Context provideActivityContext(MainActivity activity) {
        return activity;
    }

    // Seems to be wrong or not enough!?
    @Provides
    public CustomLiveData provideCustomLiveData(@ActivityContext Context context) {
        return new CustomLiveData(context);
    }
}

@Qualifier
public @interface ActivityContext{
}
</code>```

Note, that I don't get any compiler complaints if CustomLiveData is injected into MainActivity instead into the view.
Thanks!

答:
tl;dr Don't inject model layer dependencies inside custom View objects

Subclasses of View are not good targets for Dagger 2 injection. View objects are meant to be drawn and not must else, hence the name "view". The constructors for View should make this clear; they are designed for inflating View objects from attributes specified in XML. In other words, a View object should be able to be specified in a layout.xml file, inflated at the appropriate point in the lifecycle, and then obtained using findViewById(int id), Butterknife or data binding. In this way, the best custom View objects take no dependencies.

If you want to link a View and some data from the model layer, the standard pattern is to write an Adapter like those for RecyclerView and ListView. If this is not possible, using a setter (e.g., setData()) is preferable to passing dependencies from the model layer in the constructor or requesting injection from within one of the lifecycle methods of the View.

If instead you inject your LiveData object inside an Activity or Fragment using the AndroidInjector class the correct Context will be provided without you having to do anything. This explains your comment "I don't get any compiler complaints if CustomLiveData is injected into MainActivity instead into the view."

Once you have injected the LiveData object into the Activity, use one of the above methods (an adapter or a setter) to associate the data with your custom View. See the Google Android Architecture example here where elements from the model layer are injected using Dagger 2 and then associated with a ListView using findViewById and setAdapter()

Link to the Dagger 2 issue where injection of View objects is discussed:

https://github.com/google/dagger/issues/720

Body:
My question is similar to this.

So for instance, I have a LiveData implementation:

public class CustomLiveData extends LiveData<SomeEvent> {

    @Inject
    public CustomLiveData(@ActivityContext Context context) {
        //....
    }

}

that I want to inject into a custom view:

public class CustomView extends View {
   @Inject
   SomeApplicationProvider anyProvider;

   @Inject
   CustomLiveData dataProvider;
   // Getting @com.di.qualifiers.ActivityContext  android.content.Context cannot be provided without an @Provides-annotated method.
   // @com.di.qualifiers.ActivityContext android.content.Context is injected at com.repositories.CustomLiveData.<init>(context)
   // com.repositories.CustomLiveData is injected at com.ui.CustomView.dataProvider com.ui.CustomView is injected at
   // com.di.ApplicationComponent.inject(view)

   public CustomView(Context context) { this(context, null); }
   public CustomView(Context AttributeSet attrs) {
      super(context, attrs);

      // Works ok for application provider
      Application.getComponent(context).inject(this);
   }
}

And here is the rest of DI classes:

@ApplicationScope
@Component(
        modules = {AndroidInjectionModule.class,
                ActivityBuilder.class
        })

public interface ApplicationComponent extends AndroidInjector<MyApp> {

    void inject(MyApp application);

    void inject(CustomView view);

    @Component.Builder
    abstract class Builder extends AndroidInjector.Builder<MyApp> {

        public abstract ApplicationComponent build();
    }
}

@ActivityScope
@Module (subcomponents = MainActivitySubcomponent.class)
public abstract class ActivityBuilder {

    @Binds
    @IntoMap
    @ActivityKey(MainActivity.class)
    abstract AndroidInjector.Factory<? extends Activity>
    bindActivityInjectorFactory(MainActivitySubcomponent.Builder builder);

    //...

}

@Subcomponent(modules = {MainActivityModule.class})
public interface MainActivitySubcomponent extends AndroidInjector<MainActivity> {

    @Subcomponent.Builder
    abstract class Builder extends AndroidInjector.Builder<MainActivity> {

    }
}

@ActivityScope
@Module
public class MainActivityModule {

    @Provides
    @ActivityContext
    public Context provideActivityContext(MainActivity activity) {
        return activity;
    }

    // Seems to be wrong or not enough!?
    @Provides
    public CustomLiveData provideCustomLiveData(@ActivityContext Context context) {
        return new CustomLiveData(context);
    }
}

@Qualifier
public @interface ActivityContext{
}

Note, that I don't get any compiler complaints if CustomLiveData is injected into MainActivity instead into the view.
Thanks!


问:
ionic 3 with storage
I am using ionic 3 with storage.

First, i import storage in the app.module.ts

```<code>import { IonicStorageModule } from '@ionic/storage';

imports: [
IonicStorageModule.forRoot()
]
</code>```

I developed Ecommerce app.If I add to any product to cart using storage.

Here is my code for Cart page.

```<code>   <ion-row class="apply-coupon" *ngFor="let p of Cartproducts;let i=index">
<ion-col col-4>
<img src="{{p.P_IMAGES[0].URL}}" alt="product2">
</ion-col>
<ion-col col-8>
<h1>{{p.P_TITLE}}</h1>
<p class="subtitle">Subtitle</p>
<p class="code">Code: 123</p>
<div>
<button (click)="cancel(i)">Cancel X</button>
</div>
</ion-col>
</ion-row>

 this.items.push(item);
 this.storage.set('products',this.items);
</code>```

item is a product detail.and I have displayed the cart count.

```<code>this.storage.get('products').then((data) => {
     if(data != null)
     {
       this.Cartproducts=data;
       console.log(this.Cartproducts);

     }
    });
</code>```

here is my consoled value.

```<code>   [
    {
        'Product_title':'Product name',
        'Product desc':'product dec',
        'id':1
    },
    {
        'Product_title':'Product name',
        'Product desc':'product dec'
        'id':2
    }
]
</code>```

If I need to remove the last product.

```<code> this.Cartproducts.splice(i, 1);
 console.log(this.Cartproducts);
 this.storage.remove('products');
 this.storage.set('products',this.Cartproducts);
</code>```

Here is my consoled value.

```<code>[
    {
        'Product_title':'Product name',
        'Product desc':'product dec',
        'id':1
    }
]
</code>```

I remove the storage value in 'products' Again I set the value products

I I need another product.so I am going to the product page and add the product.

But my result is

```<code>[
    {
        'Product_title':'Product name',
        'Product desc':'product dec',
        'id':1
    },
    {
        'Product_title':'Product name',
        'Product desc':'product dec'
        'id':2
    },
    {
        'Product_title':'Product name',
        'Product desc':'product dec'
        'id':3
    }
]
</code>```

But Actually, I remove the second product.Did not set to storage why?

Kindly advice me,

Thanks

答:
try </p>

```<code>    this.storage.get('products').then((data) => {
     if(data == null)
     {
      data=[];
     }
this.items=data;//re-initialize the items array equal to storage value
this.items.push(item);
 this.storage.set('products',this.items);
    });
</code>```

<p>instead of </p>

```<code>this.items.push(item); this.storage.set('products',this.items)
</code>```

Title: ionic 3 with storage

Body:
I am using ionic 3 with storage.

First, i import storage in the app.module.ts

import { IonicStorageModule } from '@ionic/storage';

imports: [
IonicStorageModule.forRoot()
]

I developed Ecommerce app.If I add to any product to cart using storage.

Here is my code for Cart page.

   <ion-row class="apply-coupon" *ngFor="let p of Cartproducts;let i=index">
<ion-col col-4>

</ion-col>
<ion-col col-8>

{{p.P_TITLE}}

Subtitle

Code: 123

<button (click)="cancel(i)">Cancel X</button>

</ion-col>
</ion-row>

 this.items.push(item);
 this.storage.set('products',this.items);

item is a product detail.and I have displayed the cart count.

this.storage.get('products').then((data) => {
     if(data != null)
     {
       this.Cartproducts=data;
       console.log(this.Cartproducts);

     }
    });

here is my consoled value.

   [
    {
        'Product_title':'Product name',
        'Product desc':'product dec',
        'id':1
    },
    {
        'Product_title':'Product name',
        'Product desc':'product dec'
        'id':2
    }
]

If I need to remove the last product.

 this.Cartproducts.splice(i, 1);
 console.log(this.Cartproducts);
 this.storage.remove('products');
 this.storage.set('products',this.Cartproducts);

Here is my consoled value.

[
    {
        'Product_title':'Product name',
        'Product desc':'product dec',
        'id':1
    }
]

I remove the storage value in 'products' Again I set the value products

I I need another product.so I am going to the product page and add the product.

But my result is

[
    {
        'Product_title':'Product name',
        'Product desc':'product dec',
        'id':1
    },
    {
        'Product_title':'Product name',
        'Product desc':'product dec'
        'id':2
    },
    {
        'Product_title':'Product name',
        'Product desc':'product dec'
        'id':3
    }
]

But Actually, I remove the second product.Did not set to storage why?

Kindly advice me,

Thanks

Body:
try

    this.storage.get('products').then((data) => {
     if(data == null)
     {
      data=[];
     }
this.items=data;//re-initialize the items array equal to storage value
this.items.push(item);
 this.storage.set('products',this.items);
    });

instead of

this.items.push(item); this.storage.set('products',this.items)


问:
Protractor-CucumberJS - Tagged scenarios - Browser Launched for Scenarios not Tagged
We have a Protractor-CucumberJS framework using BDD feature files and need to create a suite of sanity tests by tagging the relevant scenarios as '@sanity' in feature files and run only the scenarios with this tag.

With this setup, Protractor launches the browser for each feature file one by one, checks if it contains the '@sanity' tag and closes the browser if tag not found and so on.

This will take up a lot of time as there are close to 200 feature files and hence we want the the browser to launch only if the feature file contains the required tag and not otherwise.

Is there a way to achieve that.

Config file -

```<code>exports.config = {
    seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
    framework: 'custom',
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    specs: [../features/*.feature]
    cucumberOpts: {
        require: [
            '../step-definitions/**/*_Steps.js',
            'generateJsonReport.js'
        ],
        format: 'pretty',
        tags: ['@sanity'],
    },

    multiCapabilities: [{
        browserName: 'chrome',
        shardTestFiles: true,
    }
    ],

    onPrepare: function () {
        browser.driver.manage().window().setSize(1600, 800);
    }
 };
</code>```

答:
This is not possible due to the fact that you are using the option shardTestFiles:true, see the config.

If you disable it, or remove it, it will first search all the files (without parsing all files and opening a browser for it) for your specific tag and only run the featurefiles that have that tag.

Body:
We have a Protractor-CucumberJS framework using BDD feature files and need to create a suite of sanity tests by tagging the relevant scenarios as '@sanity' in feature files and run only the scenarios with this tag.

With this setup, Protractor launches the browser for each feature file one by one, checks if it contains the '@sanity' tag and closes the browser if tag not found and so on.

This will take up a lot of time as there are close to 200 feature files and hence we want the the browser to launch only if the feature file contains the required tag and not otherwise.

Is there a way to achieve that.

Config file -

exports.config = {
    seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
    framework: 'custom',
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    specs: [../features/*.feature]
    cucumberOpts: {
        require: [
            '../step-definitions/**/*_Steps.js',
            'generateJsonReport.js'
        ],
        format: 'pretty',
        tags: ['@sanity'],
    },

    multiCapabilities: [{
        browserName: 'chrome',
        shardTestFiles: true,
    }
    ],

    onPrepare: function () {
        browser.driver.manage().window().setSize(1600, 800);
    }
 };


问:
Java if else with nested loop
I am having some problem with my java assignment and currently am stuck at the nested if else statement.I am actually trying to get an input age from the user and store in as a variable.After executing my code i am getting error when i run the program.Am i doing this correctly or is there some other way to program this?

Error message that i got

```
    Enter your selection:
    1
    You have selected No.1
    Please enter your age**Exception in thread "main"
    java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Assignment.main(Assignment.java:48)**
```

```<code>public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println(
       "1. Add player" + "\n" +
       "2.Display transaction" + "\n" +
       "3.Begin the ride");
    System.out.println("");
    System.out.println("Enter your selection: ");
    char selection = sc.findInLine(".").charAt(0);
    sc.close();
    switch(selection)  {
    case '1' :
        System.out.println("You have selected No.1");
        break;
    case '2' :
        System.out.println("You have selected No.2" );
        break;
    case '3' :
        System.out.println("You have selected No.3" );
        break;
    default:
        System.out.println("Please make a selection");
        break;
   }
   if (selection=='1') {
        int age=0;
        System.out.print("Please enter your age");
        age = sc.nextInt();
        while (age<100) {
            age+=age;
        }
    }
    else if (selection=='2') {
        System.out.println("Display daily transaction");
    }
    else if (selection=='3') {
        System.out.println("Begin the ride");
    }
    else {
        System.out.println("Please enter a valid input");
    }
}
</code>```

答:
switch case is a type of nested if else.we can use switch in place of nested if else.you need not to use both switch case and nested if else simultaneously.
you can write your code like this.</p>

```<code>public static void main(String args[]) {

    Scanner sc = new Scanner(System.in);
    System.out.println("1. Add player" + "\n" +
       "2.Display transaction" + "\n" +
       "3.Begin the ride");
    System.out.println("");
    System.out.println("Enter your selection: ");
    char selection = sc.findInLine(".").charAt(0);

    switch(selection)  {

    case '1' :
        System.out.println("You have selected No.1");
        int age=0;
        System.out.print("Please enter your age");
        age = sc.nextInt();
        while (age<100) {
            age+=age;
        }
        System.out.print(age);
        break;

    case '2' :

        System.out.println("You have selected No.2" );
        System.out.println("Display daily transaction");
        break;

    case '3' :

        System.out.println("You have selected No.3" );
        System.out.println("Begin the ride");
        break;

    default:

        System.out.println("Please make a selection");
        System.out.println("Please enter a valid input");
        break;

   }
    sc.close();
}
</code>```

Title: Java if else with nested loop

Body:
I am having some problem with my java assignment and currently am stuck at the nested if else statement.I am actually trying to get an input age from the user and store in as a variable.After executing my code i am getting error when i run the program.Am i doing this correctly or is there some other way to program this?

Error message that i got

    Enter your selection:
    1
    You have selected No.1
    Please enter your age**Exception in thread "main"
    java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Assignment.main(Assignment.java:48)**

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println(
       "1. Add player" + "\n" +
       "2.Display transaction" + "\n" +
       "3.Begin the ride");
    System.out.println("");
    System.out.println("Enter your selection: ");
    char selection = sc.findInLine(".").charAt(0);
    sc.close();
    switch(selection)  {
    case '1' :
        System.out.println("You have selected No.1");
        break;
    case '2' :
        System.out.println("You have selected No.2" );
        break;
    case '3' :
        System.out.println("You have selected No.3" );
        break;
    default:
        System.out.println("Please make a selection");
        break;
   }
   if (selection=='1') {
        int age=0;
        System.out.print("Please enter your age");
        age = sc.nextInt();
        while (age<100) {
            age+=age;
        }
    }
    else if (selection=='2') {
        System.out.println("Display daily transaction");
    }
    else if (selection=='3') {
        System.out.println("Begin the ride");
    }
    else {
        System.out.println("Please enter a valid input");
    }
}

Body:
switch case is a type of nested if else.we can use switch in place of nested if else.you need not to use both switch case and nested if else simultaneously.
you can write your code like this.

public static void main(String args[]) {

    Scanner sc = new Scanner(System.in);
    System.out.println("1. Add player" + "\n" +
       "2.Display transaction" + "\n" +
       "3.Begin the ride");
    System.out.println("");
    System.out.println("Enter your selection: ");
    char selection = sc.findInLine(".").charAt(0);

    switch(selection)  {

    case '1' :
        System.out.println("You have selected No.1");
        int age=0;
        System.out.print("Please enter your age");
        age = sc.nextInt();
        while (age<100) {
            age+=age;
        }
        System.out.print(age);
        break;

    case '2' :

        System.out.println("You have selected No.2" );
        System.out.println("Display daily transaction");
        break;

    case '3' :

        System.out.println("You have selected No.3" );
        System.out.println("Begin the ride");
        break;

    default:

        System.out.println("Please make a selection");
        System.out.println("Please enter a valid input");
        break;

   }
    sc.close();
}


问:
How to secure passwords in the Software Development?
how do you secure your passwords in propertie Files?
Encryption / Encoding?

Or do you use a different approach to handle Database User / Passwords for connection Strings?

Thanks for you help!

Update: Thanks for your responses! In this special case we talk about two tier architecture. We have many clients with direct connections to the databases. Propertie Files are on a network share.

答:
I do this by encrypting the connection string .

This can be achieved by creating a separate application to encrypt the connection string.
And using the decrypting code that is embedded in the application itself.


问:
GraphQL large integer error: Int cannot represent non 32-bit signed integer value
I´m trying to store a UNIX timestamp in MongoDB using GraphQL, but it seens that GraphQL has a limit to handle integers. See the mutation below:

```<code>const addUser = {
    type: UserType,
    description: 'Add an user',
    args: {
        data: {
            name: 'data',
            type: new GraphQLNonNull(CompanyInputType)
        }
    },
    resolve(root, params) {

        params.data.creationTimestamp = Date.now();

        const model = new UserModel(params.data);
        const saved = model.save();

        if (!saved)
            throw new Error('Error adding user');

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

Result:

```<code>  "errors": [
    {
      "message": "Int cannot represent non 32-bit signed integer value: 1499484833027",
      "locations": [
        {
          "line": 14,
          "column": 5
        }
      ],
      "path": [
        "addUser",
        "creationTimestamp"
      ]
    }
</code>```

I´m currently using GraphQLInteger for this field on type definition:

```<code>creationTimestamp: {
    type: GraphQLInt
}
</code>```

How can I solve that situation if there is no larger GraphQLInt available in GraphQL ?

答:
GraphQL doesn't support integers larger than 32 bits as the error indicates. You're better off using a custom scalar like GraphQL Date. There's also a "Long" type available here. Or you could roll your own custom type; there's a great example from Apollo here.

If you're curious why GraphQL does not support anything bigger, you can check out this issue on Github.

Body:
I´m trying to store a UNIX timestamp in MongoDB using GraphQL, but it seens that GraphQL has a limit to handle integers. See the mutation below:

const addUser = {
    type: UserType,
    description: 'Add an user',
    args: {
        data: {
            name: 'data',
            type: new GraphQLNonNull(CompanyInputType)
        }
    },
    resolve(root, params) {

        params.data.creationTimestamp = Date.now();

        const model = new UserModel(params.data);
        const saved = model.save();

        if (!saved)
            throw new Error('Error adding user');

        return saved;
    }
}

Result:

  "errors": [
    {
      "message": "Int cannot represent non 32-bit signed integer value: 1499484833027",
      "locations": [
        {
          "line": 14,
          "column": 5
        }
      ],
      "path": [
        "addUser",
        "creationTimestamp"
      ]
    }

I´m currently using GraphQLInteger for this field on type definition:

creationTimestamp: {
    type: GraphQLInt
}

How can I solve that situation if there is no larger GraphQLInt available in GraphQL ?

ContentLicense: CC BY-SA 4.0


问:
C: WAV file not being opened in "rb"
I'm having a difficult time trying to open a WAV file for reading. When I compile and run my code, I do not get any errors. I am adding the code that I am messing with (assuming necessary libraries have been called). The program is supposed to display the contents of the WAV file and although I enter a valid filename and extension, the statement "Invalid Filename. Try Again." is still being printed to the screen. The other method I attempted was enter the directory of the file instead of just the name, and when I do that, my program ends and nothing is displayed. Any guidance would be helpful and thank you in advance!</p>

```<code>main(){
FILE *fin;
printf("\nEnter filename of WAV file: \n");
char filename[256];
scanf("%s",&filename);
fin = fopen(filename,"rb"); // opens in rb

if(!fin) // if file doesn't exist
{
printf("Invalid filename. Try again.\n");
}
else // if fin opens succesfully
{
    printf("\nFile opened succesfully\n");

    char *header;
    header = (char *)malloc(44);
    if(header == NULL)
    {
        printf("Error in allocating memory.");
        return 0;
    }

    fread(header,1,44,fin);

    char *chunkid;
    unsigned int *chunksize;
    char *format;
    char *subchunk1id;
    unsigned int *subchunk1size;
    unsigned short int *audioformat;
    unsigned short int *numchannels;
    unsigned int *samplerate;
    unsigned int *byterate;
    unsigned short int *blockalign;
    unsigned short int *bitspersample;
    char *subchunk2id;
    unsigned int *subchunk2size;
    unsigned int *data;

    chunkid = header;
    chunksize = (unsigned int *)(header + 4);
    format = header + 8;
    subchunk1id = header + 12;
    subchunk1size = (unsigned int *)(header + 16);
    audioformat = (unsigned short int *)(header + 18);
    numchannels = (unsigned short int*)(header + 20);
    samplerate = (unsigned int*)(header + 24);
    byterate = (unsigned int*)(header + 28);
    blockalign = (unsigned short int*)(header + 30);
    bitspersample = (unsigned short int*)(header + 32);
    subchunk2id = header + 36;
    subchunk2size = (unsigned int*)(header + 40);
    data = (unsigned int*)(header + 44);

    printf("\n%c%c%c%c",*(header),*(header+1),*(header+2),*(header+3));
    printf("\n%d",*chunksize);
    printf("\n%c%c%c%c",*(header + 8),*(header + 9), *(header + 10), *(header + 11));
    printf("\n%c%c%c%c",*(header + 12),*(header + 13), *(header + 14), *(header + 15));
    printf("\n%d",*subchunk1size);
    printf("\n%d",*audioformat);
    printf("\n%d",*numchannels);
    printf("\n%d",*samplerate);
    printf("\n%d",*byterate);
    printf("\n%d",*blockalign);
    printf("\n%d",*bitspersample);
    printf("\n%c%c%c%c",*(header + 36),*(header + 37),*(header + 38), *(header + 39));
    printf("\n%d",*subchunk2size);
    printf("\n%d",*data);

    fclose(fin);

} // end of else
} // end of main
</code>```

答:
Try using

```<code>if(!fin)
{
  perror("Error:");
}
</code>```

it will print the right error message for you to easily diagnose why your file couldn't be opened. May be your program cannot find the file specified by you or you might not have permissions to open it.  Here's a list of errors you may encounter while opening a file.

The other possible problem that I could see is that you are using scanf to read from stdin into your char array. What if the path specified by you contains white-spaces? Every word followed by a White-space will be considered like a different string. And you'll get only the first longest possible word that doesn't contain white-space into it. So, your program isn't reading the entire path. You can try
scanf("%[^\n]", filename) which will read until a '\n' is encountered. Beware! This exposes you to buffer overflow possibilities, that if you pass a valid string set to the program which is of length greater than 256, you'll be writing beyond the boundaries of your char array and which isn't good. So try scanf("%255[^\n]", filename) or try using fgets() doc SO which provides buffer overflow protection.

Title: C: WAV file not being opened in "rb"

Body:
I'm having a difficult time trying to open a WAV file for reading. When I compile and run my code, I do not get any errors. I am adding the code that I am messing with (assuming necessary libraries have been called). The program is supposed to display the contents of the WAV file and although I enter a valid filename and extension, the statement "Invalid Filename. Try Again." is still being printed to the screen. The other method I attempted was enter the directory of the file instead of just the name, and when I do that, my program ends and nothing is displayed. Any guidance would be helpful and thank you in advance!

main(){
FILE *fin;
printf("\nEnter filename of WAV file: \n");
char filename[256];
scanf("%s",&filename);
fin = fopen(filename,"rb"); // opens in rb

if(!fin) // if file doesn't exist
{
printf("Invalid filename. Try again.\n");
}
else // if fin opens succesfully
{
    printf("\nFile opened succesfully\n");

    char *header;
    header = (char *)malloc(44);
    if(header == NULL)
    {
        printf("Error in allocating memory.");
        return 0;
    }

    fread(header,1,44,fin);

    char *chunkid;
    unsigned int *chunksize;
    char *format;
    char *subchunk1id;
    unsigned int *subchunk1size;
    unsigned short int *audioformat;
    unsigned short int *numchannels;
    unsigned int *samplerate;
    unsigned int *byterate;
    unsigned short int *blockalign;
    unsigned short int *bitspersample;
    char *subchunk2id;
    unsigned int *subchunk2size;
    unsigned int *data;

    chunkid = header;
    chunksize = (unsigned int *)(header + 4);
    format = header + 8;
    subchunk1id = header + 12;
    subchunk1size = (unsigned int *)(header + 16);
    audioformat = (unsigned short int *)(header + 18);
    numchannels = (unsigned short int*)(header + 20);
    samplerate = (unsigned int*)(header + 24);
    byterate = (unsigned int*)(header + 28);
    blockalign = (unsigned short int*)(header + 30);
    bitspersample = (unsigned short int*)(header + 32);
    subchunk2id = header + 36;
    subchunk2size = (unsigned int*)(header + 40);
    data = (unsigned int*)(header + 44);

    printf("\n%c%c%c%c",*(header),*(header+1),*(header+2),*(header+3));
    printf("\n%d",*chunksize);
    printf("\n%c%c%c%c",*(header + 8),*(header + 9), *(header + 10), *(header + 11));
    printf("\n%c%c%c%c",*(header + 12),*(header + 13), *(header + 14), *(header + 15));
    printf("\n%d",*subchunk1size);
    printf("\n%d",*audioformat);
    printf("\n%d",*numchannels);
    printf("\n%d",*samplerate);
    printf("\n%d",*byterate);
    printf("\n%d",*blockalign);
    printf("\n%d",*bitspersample);
    printf("\n%c%c%c%c",*(header + 36),*(header + 37),*(header + 38), *(header + 39));
    printf("\n%d",*subchunk2size);
    printf("\n%d",*data);

    fclose(fin);

} // end of else
} // end of main

Body:
Try using

if(!fin)
{
  perror("Error:");
}

it will print the right error message for you to easily diagnose why your file couldn't be opened. May be your program cannot find the file specified by you or you might not have permissions to open it.  Here's a list of errors you may encounter while opening a file.

The other possible problem that I could see is that you are using scanf to read from stdin into your char array. What if the path specified by you contains white-spaces? Every word followed by a White-space will be considered like a different string. And you'll get only the first longest possible word that doesn't contain white-space into it. So, your program isn't reading the entire path. You can try
scanf("%[^\n]", filename) which will read until a '\n' is encountered. Beware! This exposes you to buffer overflow possibilities, that if you pass a valid string set to the program which is of length greater than 256, you'll be writing beyond the boundaries of your char array and which isn't good. So try scanf("%255[^\n]", filename) or try using fgets() doc SO which provides buffer overflow protection.


问:
How can I do Databinding in c#?
I have the following class

```
public class Car
{
   public Name {get; set;}
}
```

and I want to bind this programmatically to a text box.

How do I do that?

Shooting in the dark:

```
...
Car car = new Car();
TextEdit editBox = new TextEdit();
editBox.DataBinding.Add("Name", car, "Car - Name");
...
```

I get the following error

"Cannot bind to the propery 'Name' on the target control.

What am I doing wrong and how should I be doing this? I am finding the databinding concept a bit difficult to grasp coming from web-development.

答:
Using C# 4.6 syntax:

```<code>editBox.DataBinding.Add(nameof(editBox.Text), car, nameof(car.Name));
</code>```

if car is null, then the above code will fail in a more conspicuous way than using literal string to represent the datamember of car

OwnerDisplayName: Xerx

Title: How can I do Databinding in c#?

Body:
I have the following class

public class Car
{
   public Name {get; set;}
}

and I want to bind this programmatically to a text box.

How do I do that?

Shooting in the dark:

...
Car car = new Car();
TextEdit editBox = new TextEdit();
editBox.DataBinding.Add("Name", car, "Car - Name");
...

I get the following error

"Cannot bind to the propery 'Name' on the target control.

What am I doing wrong and how should I be doing this? I am finding the databinding concept a bit difficult to grasp coming from web-development.

LastEditorDisplayName: Jay Bazuzi

Body:
Using C# 4.6 syntax:

editBox.DataBinding.Add(nameof(editBox.Text), car, nameof(car.Name));

if car is null, then the above code will fail in a more conspicuous way than using literal string to represent the datamember of car


问:
Select Parent and Child if child has records
I have 3 tables: firearms_firearmbook, inventory_inventory and inventory_inventorytransaction.

And i have 2 Cases:

If inventory_inventory Table has no inventory_inventorytransaction with item action of 16, show inventory_inventory record

If inventory_inventory Table has inventory_inventorytransaction with item action of 16, show inventory_inventory and inventory_inventorytransaction.item_action_id

The query bellow works for the first cause, but its not working for the second cause.
It should show smth like this:

```<code>-----------------------------------
| id    |    serial   | action_id |
-----------------------------------
   1         MAGUM
   2         EAGLE
   2         EAGLE         16
</code>```

Query:

```<code>SELECT FB.id, INV.serial_number, INV.id, INVT.item_action_id FROM firearms_firearmbook AS FB
LEFT JOIN inventory_inventory AS INV ON INV.id = FB.item_id
LEFT JOIN inventory_inventorytransaction AS INVT ON INVT.item_id = INV.id AND INVT.item_action_id = 16
WHERE FB.store_id = 1
</code>```

答:
It seems that if there is an action 16 record for a given item, you need two records in the output: one with a blank in the third column, and one with 16 in the third column.

In that case you could do this:

```<code>with base as (
        select      fb.id,
                    inv.serial_number,
                    inv.id,
        from        firearms_firearmbook as fb
        inner join  inventory_inventory as inv
                on  inv.id = fb.item_id
        where       fb.store_id = 1
    )
select      base.*,
            invt.item_action_id
from        base
inner join  inventory_inventorytransaction as invt
        on  invt.item_id = base.id
        and invt.item_action_id = 16
union all
select      base.*,
            null
from        base
order by    1, 2, 3, 4 desc
</code>```

Body:
I have 3 tables: firearms_firearmbook, inventory_inventory and inventory_inventorytransaction.

And i have 2 Cases:

If inventory_inventory Table has no inventory_inventorytransaction with item action of 16, show inventory_inventory record

If inventory_inventory Table has inventory_inventorytransaction with item action of 16, show inventory_inventory and inventory_inventorytransaction.item_action_id

The query bellow works for the first cause, but its not working for the second cause.
It should show smth like this:

-----------------------------------
| id    |    serial   | action_id |
-----------------------------------
   1         MAGUM
   2         EAGLE
   2         EAGLE         16

Query:

SELECT FB.id, INV.serial_number, INV.id, INVT.item_action_id FROM firearms_firearmbook AS FB
LEFT JOIN inventory_inventory AS INV ON INV.id = FB.item_id
LEFT JOIN inventory_inventorytransaction AS INVT ON INVT.item_id = INV.id AND INVT.item_action_id = 16
WHERE FB.store_id = 1

Body:
It seems that if there is an action 16 record for a given item, you need two records in the output: one with a blank in the third column, and one with 16 in the third column.

In that case you could do this:

with base as (
        select      fb.id,
                    inv.serial_number,
                    inv.id,
        from        firearms_firearmbook as fb
        inner join  inventory_inventory as inv
                on  inv.id = fb.item_id
        where       fb.store_id = 1
    )
select      base.*,
            invt.item_action_id
from        base
inner join  inventory_inventorytransaction as invt
        on  invt.item_id = base.id
        and invt.item_action_id = 16
union all
select      base.*,
            null
from        base
order by    1, 2, 3, 4 desc


问:
PHP CURL Enable Linux
I have some php scripts that I've been running on an Apache server on a windows machine.  These scripts use curl which isn't enabled by default in php.  For windows enabling it was as easy and un-commenting the line with the curl .dll file in the php.ini file.  Well since Linux uses .so instead of .dll files that wont work.

Does anyone have any idea how to enable curl on an Apache server running on a Linux machine?  Php is already installed so I'm really hoping for a solution that doesn't involve re-installing php.  Thanks in advance!

Edit:
The machine has the openSUSE v11.3 version of linux installed.  I'm didn't setup the machine and am interacting with it over command line(putty).  Any help would be great.

答:
If it's php 7 on ubuntu, try this</p>

```<code>apt-get install php7.0-curl
/etc/init.d/apache2 restart
</code>```

Title: PHP CURL Enable Linux

Body:
If it's php 7 on ubuntu, try this

apt-get install php7.0-curl
/etc/init.d/apache2 restart


问:
Visual studio keyboard shortcut to go to end of line in Windows
I'm using visual studio community 2017. I want to remap the keyboard shortcut that moves the caret to the end of line (since I'm working on a laptop without the "End" key).

I know how to remap visual studio keys, but I can't find the menu item for it. Do you know what is the menu/action name for it so I can change it?

I can't find the answer on the web though it was asked several times.

答:
The command name is Edit.LineEnd. You can assign a new shortcut to it in Visual Studio keyboard options.

Assign the shortcut in the "Text Editor" scope (rather than the default "Global" scope).

When done correctly, it should look like this:


问:
Ruby on Rails - Getting parameter values as hash onside controller
How can i get the values passed in the URL check/1?Answers[1]=2&Answers[7]=3&Answers[6]=4&Answers[4]=0 in controller

@answers = params[:Answers] ?

How can i convert @answers to the format {1 => 2, 7 => 3, 6 => 4, 4 => 0}

答:
You get that in all String you can convert is in Integer</p>

```<code>answers  = params[:Answer].inject({}) do |answers, line|
  answers[line[0].to_i] = line[1].to_i
  answers
end
</code>```

Body:
You get that in all String you can convert is in Integer

answers  = params[:Answer].inject({}) do |answers, line|
  answers[line[0].to_i] = line[1].to_i
  answers
end


问:
How to change property of all buttons in windows from?
I have some buttons on Form1. I want to set their FlatStyle property to FlatStyle.Popup.
I searched and wrote some code as below:

```<code>// List<Control> ButtonsList = new List<Control>();
 List<Button> ButtonsList = new List<Button>();
 public Form1()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.autorun;  //Project->Properties->Resources->
            ButtonsList = GetAccessToAllButtons(this).OfType<Button>.ToList(); //*** hot line ***

            foreach(Button btn in ButtonList)
            {
                btn.FlatStyle = FlatStyle.Popup;
            }

        }

 public IEnumerable<Control> GetAccessToAllButtons(Control thisClass)
        {
            List<Control> ControlsList = new List<Control>();
            foreach (Control child in thisClass.Controls)
            {
                ControlsList.AddRange(GetAccessToAllButtons(child));
            }
            ControlsList.Add(thisClass);
            return ControlsList;
        }
</code>```

But when I use GetAccessToAllButtons() in hot line of my code, VS generates this error:

'System.Linq.Queryable.OfType(Query.Linq.IQueryable)' is a
  'method', which is not valid in the given context

What is my mistake?

Edit: My reference at here missed the (). It is an accepted answer! Do we have a different situation at my reference? or it is only a typo?

答:
OfType is Generic Method and you must use it as a method.
Just replace that line to the following:

```<code>ButtonsList = GetAccessToAllButtons(this).OfType<Button>().ToList();
</code>```

Also I will recommend you to write method as below:

```<code>public List<Button> GetAllButtons(Form f)
{
    List<Button> resultList = new List<Button>();
    foreach(Control a in f.Controls)
    {
        if(a is Button)
        {
            resultList.Add((Button)a);
        }
    }
    return resultList;
}
</code>```

and use it in this way :

```<code>var myBtns = GetAllButtons(yourForm);
foreach (var btn in myBtns)
{
    btn.FlatStyle = FlatStyle.Popup;
}
</code>```

Body:
I have some buttons on Form1. I want to set their FlatStyle property to FlatStyle.Popup.
I searched and wrote some code as below:

// List<Control> ButtonsList = new List<Control>();
 List<Button> ButtonsList = new List<Button>();
 public Form1()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.autorun;  //Project->Properties->Resources->
            ButtonsList = GetAccessToAllButtons(this).OfType<Button>.ToList(); //*** hot line ***

            foreach(Button btn in ButtonList)
            {
                btn.FlatStyle = FlatStyle.Popup;
            }

        }

 public IEnumerable<Control> GetAccessToAllButtons(Control thisClass)
        {
            List<Control> ControlsList = new List<Control>();
            foreach (Control child in thisClass.Controls)
            {
                ControlsList.AddRange(GetAccessToAllButtons(child));
            }
            ControlsList.Add(thisClass);
            return ControlsList;
        }

But when I use GetAccessToAllButtons() in hot line of my code, VS generates this error:

'System.Linq.Queryable.OfType(Query.Linq.IQueryable)' is a
  'method', which is not valid in the given context

What is my mistake?

Edit: My reference at here missed the (). It is an accepted answer! Do we have a different situation at my reference? or it is only a typo?

Body:
OfType is Generic Method and you must use it as a method.
Just replace that line to the following:

ButtonsList = GetAccessToAllButtons(this).OfType<Button>().ToList();

Also I will recommend you to write method as below:

public List<Button> GetAllButtons(Form f)
{
    List<Button> resultList = new List<Button>();
    foreach(Control a in f.Controls)
    {
        if(a is Button)
        {
            resultList.Add((Button)a);
        }
    }
    return resultList;
}

and use it in this way :

var myBtns = GetAllButtons(yourForm);
foreach (var btn in myBtns)
{
    btn.FlatStyle = FlatStyle.Popup;
}


问:
PHP and SQL -- Select from database
I have a problem with this code. It has syntax error and I don't know what is it.</p>

```<code><?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);

if (!$conn) {
die('Could not connect: ' . mysql_error());

$sql  = 'SELECT id FROM users WHERE email=\"donat12@icloud.com\"';

echo $sql;
?>
</code>```

答:
There are two errors

You are missing } closing bracket after die

Mysql query is wrong.

So the code should be

```<code>if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql  = 'SELECT id FROM users WHERE email="donat12@icloud.com"';

echo $sql;
</code>```

Title: PHP and SQL -- Select from database

Body:
I have a problem with this code. It has syntax error and I don't know what is it.

<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);

if (!$conn) {
die('Could not connect: ' . mysql_error());

$sql  = 'SELECT id FROM users WHERE email=\"donat12@icloud.com\"';

echo $sql;
?>

Body:
There are two errors

You are missing } closing bracket after die

Mysql query is wrong.

So the code should be

if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql  = 'SELECT id FROM users WHERE email="donat12@icloud.com"';

echo $sql;


问:
Add custom 500 error page only for production in Laravel
I want to have a custom 500 error page. This can be done simply by creating a view in errors/500.blade.php.

This is fine for production mode, but I no longer get the default exception/ debug pages when in debug mode (the one that looks grey and says "Whoops something went wrong").

Therefore, my question is: how can I have a custom 500 error page for production, but the original 500 error page when debug mode is true?

答:
Add the code to the app/Exceptions/Handler.php file inside the Handler class:

```<code>protected function convertExceptionToResponse(Exception $e)
{
    if (config('app.debug')) {
        return parent::convertExceptionToResponse($e);
    }

    return response()->view('errors.500', [
        'exception' => $e
    ], 500);
}
</code>```

The convertExceptionToResponse method gets right such errors that cause the 500 status.

Body:
Add the code to the app/Exceptions/Handler.php file inside the Handler class:

protected function convertExceptionToResponse(Exception $e)
{
    if (config('app.debug')) {
        return parent::convertExceptionToResponse($e);
    }

    return response()->view('errors.500', [
        'exception' => $e
    ], 500);
}

The convertExceptionToResponse method gets right such errors that cause the 500 status.