问:
mule: how to add value to payload array list
I have a payload as list of maps and another flow variable as map.
I wanted to add flow variable to payload list. I tried using this expression #[payload.addAll(flowVars['entitlement'])]in expression component. But it sets the payload to boolean value true.

答:
Use expression component like

```<code><expression-component doc:name="Expression"><![CDATA[payload.addAll(flowVars['entitlement'])]]></expression-component>
</code>```

Hope this helps.

Body:
Use expression component like

<expression-component doc:name="Expression"><![CDATA[payload.addAll(flowVars['entitlement'])]]></expression-component>

Hope this helps.


来源: stackexchange

问:
UI Testing (casperjs) with good known status of data (mysql database)
I'm using CasperJS for automated UI tests. I've done the basic UI testing and validation with some random data, kind of POC. I've set up this automation using bash script which kicks to start the web server, load MySQL data from SQL file, start CasperJS test cases, stop the web server, check the log files.

Now, I want to start the testing with some good known status of data which are stored in MySQL. So that I can test the list data and form data with detailed field information with some known database status. How should I know the status of data in the database at a moment?

1) Should I use pre-populated JSON dumped file which has status and details about all data?

2) Should I use web service API? (web service APIs are being used to show/save/delete data from the web page)

Let's take an example. I've 5 users in Users table. Now when I open the home page it shows 5 users with some rough details. When I click on any record from the list of users, it shows a form with detailed information about that user. The webpage is requesting to the web application to get the detail about a user with the help of user_id to show the detailed user data in a form. Now I want to check that all the data in that form is populated correctly. So at the next step, what would be the preferred way, should I read content from JSON dumped file or should I use web service API (like webpage does).

Searching this problem online, I also found MYSQL HTTP plugin. Should I consider this as well? and How safe it is to use? (I know from the docs that this plugin is not for the production, it is just for testing purpose only. :) )

答:
For the main question in cases like this I would change the database connection string to your testing database (this is a clone).

In your case use your bash script to change the connection string (file copy?) automatically before you run the tests. And when completed change back.

Your testing database is a direct clone of your dev/live databsae but with ONLY the test data you want.  Downside is you need to keep the schema in sync with DEV/LIVE.

Also another point to take into considertion is if your testing changes state (post). If so your testing data might be out of sync. One way is get around this is to drop foreign keys, truncate the data and load in a dump file.

HTH

ContentLicense: CC BY-SA 3.0


问:
How to sort a list of 1billion elements in python
How to sort a list of 1 billion elements in python
Please elaborate
Assuming we have unlimited space.

Thanks for the answers, but, this question is asked in the perspective of optimizing algorithm to sort, not to work on python. This question is asked in an interview, in the context of, having large number of elements, may be integers or strings, this probably wont be used in real world as we have techniques like pagination.

答:
A dictionary on its own does not store a key order. For this, you will have to use the OrderedDict which stores the order of insertion.

If you just need to iterate through the sorted keys, you can use sorted:

```<code>for key in sorted(my_dict):
    # output is already sorted by dictionary key
    print key, my_dict[key]
</code>```

if you need to specify a special key or method, you could pass this as information to sorted. The following example sorts by value:

```<code>for key, value in sorted(my_dict.items(), key=lambda x: x[1]):
    # output is sorted by value
    print key, value
</code>```

Sort orders can be reversed by using reversed:

```<code>for key in reversed(sorted(my_dict)):
    # output is already sorted descending by dictionary key
    print key, my_dict[key]
</code>```

Finally, this code snippet would fill an OrderedDict with sorted key/value pairs:

```<code>from collections import OrderedDict
my_ordered_dict = OrderedDict(sorted(my_dict.items(), key=lambda t: t[0]))
</code>```

Since you updated your question from dictionary to list

Sorting lists is even easier, just use sorted (again, provide a small method, if you have a different sorting key):

```<code>sorted_list = sorted(unsorted_list)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
A dictionary on its own does not store a key order. For this, you will have to use the OrderedDict which stores the order of insertion.

If you just need to iterate through the sorted keys, you can use sorted:

for key in sorted(my_dict):
    # output is already sorted by dictionary key
    print key, my_dict[key]

if you need to specify a special key or method, you could pass this as information to sorted. The following example sorts by value:

for key, value in sorted(my_dict.items(), key=lambda x: x[1]):
    # output is sorted by value
    print key, value

Sort orders can be reversed by using reversed:

for key in reversed(sorted(my_dict)):
    # output is already sorted descending by dictionary key
    print key, my_dict[key]

Finally, this code snippet would fill an OrderedDict with sorted key/value pairs:

from collections import OrderedDict
my_ordered_dict = OrderedDict(sorted(my_dict.items(), key=lambda t: t[0]))

Since you updated your question from dictionary to list

Sorting lists is even easier, just use sorted (again, provide a small method, if you have a different sorting key):

sorted_list = sorted(unsorted_list)


问:
Android Geofence works after phone restart
I am adding multiple geofence to one app.(Max 100 allowed according to documentation.) I was getting callbacks of geofence then it stopped.
Geofence works smoothly only when I restart phone. After few minutes it stops working again.

```<code>public class GeoFenceHelper implements IGeoFenceListener, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

private Context context;
private GeofencingClient mGeoFencingClient;
private PendingIntent geoFencePendingIntent;
private String TAG = GeoFenceHelper.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
Location tempLocation = new Location("");
/**
 * The list of geoFences used in this sample.
 */
private ArrayList<Geofence> mGeoFenceList;
private List<GeoFenceModel> geoFenceEntries;
private ArrayList<String> removeGeoFenceList = new ArrayList<>();

public GeoFenceHelper(Context context) {
    this.context = context;
    mGeoFenceList = new ArrayList<>();
    mGeoFencingClient = LocationServices.getGeofencingClient(context);
}

public void registerGeoFence(List<GeoFenceModel> geoFenceEntries) {

    mGeoFenceList.clear();
    this.geoFenceEntries = geoFenceEntries;

        if (DatabaseManager.getInstance(context).getGeoFenceLocationCount() <= Constants.MAX_GEOFENCE_ENTRY_COUNT) {
            addGeoFences(geoFenceEntries);
        } else {
            buildGoogleApiClient();
        }
}

private void addGeoFences(List<GeoFenceModel> geoFenceEntries) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    for (GeoFenceModel geoFenceEntry : geoFenceEntries) {

        if(geoFenceEntry.getId()==Constants.DESTINATION_REACHED_ID) {
            removeGeoFenceList.clear();
            removeGeoFenceList.add(""+geoFenceEntry.getId());
            unregisterGeoFence(removeGeoFenceList);
        }
            Geofence geoFence = new Geofence.Builder()
                    .setRequestId(String.valueOf(geoFenceEntry.getId()))
                    .setExpirationDuration(geoFenceEntry.getExpireDuration())
                    .setCircularRegion(
                            geoFenceEntry.getLatitude(),
                            geoFenceEntry.getLongitude(),
                            geoFenceEntry.getRadius()
                    )
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .build();

            CustomLogger.logE("GEOGENCE", "Geo Fence lat = " + geoFenceEntry.getLatitude() + " log = " + geoFenceEntry.getLongitude() + "Radius = " + geoFenceEntry.getRadius()+" Expiry "+geoFenceEntry.getExpireDate());
            mGeoFenceList.add(geoFence);
    }

    mGeoFencingClient.addGeofences(getGeoFencingRequest(mGeoFenceList), getGeoFencePendingIntent());
    Utils.stopLocationUpdate(context);
}

@Override
public void unregisterGeoFence(List<String> genFenceList) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    CustomLogger.logE("GeoFence","Remove GeoFence "+genFenceList.get(0));
    mGeoFencingClient.removeGeofences(genFenceList);
}

/**
 * Builds and returns a GeoFencingRequest. Specifies the list of geoFences to be monitored.
 * Also specifies how the geoFence notifications are initially triggered.
 *
 * @param mGeoFenceList
 */
private GeofencingRequest getGeoFencingRequest(ArrayList<Geofence> mGeoFenceList) {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeoFenceList);
    return builder.build();
}

private PendingIntent getGeoFencePendingIntent() {
    // Reuse the PendingIntent if we already have it.
    if (geoFencePendingIntent != null) {
        return geoFencePendingIntent;
    }
    Intent intent = new Intent(context, GeofenceTransitionsIntentService.class);
    geoFencePendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    return geoFencePendingIntent;
}

//Location related code
private synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this.context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();

    if (mGoogleApiClient != null && !mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();
        CustomLogger.logE("tempLocation", "lat " + latitude + "long " + longitude);

        List<GeoFenceModel> geoFenceLocations = DatabaseManager.getInstance(context).getGeoFenceLocation();
        calculateLocationDistance(mLastLocation, geoFenceLocations);
        try {
            deleteLocations(geoFenceLocations);
            addGeoFences(geoFenceEntries);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    } else {
        CustomLogger.logE("tempLocation", "(Couldn't get the tempLocation. Make sure tempLocation is enabled on the device)");
    }
}

private void deleteLocations(List<GeoFenceModel> geoFenceLocations) throws SQLException {
    int reduceCount = Math.abs(Constants.MAX_GEOFENCE_ENTRY_COUNT - geoFenceLocations.size());

    CustomLogger.logE("GEOGENCE", "Geo Fence App  lat = "+geoFenceLocations.get(0).getLatitude() + " log = "+ geoFenceLocations.get(0).getLongitude() + "App sepcific = "+ geoFenceLocations.get(0).isAppSpecific());
    GeoFenceModel geoFenceModel = null;
    for (int i = 0; i < reduceCount; i++) {

        if(geoFenceLocations.get(0).isAppSpecific())
        {
            geoFenceModel = geoFenceLocations.remove(1); //because app specific item will be available at top of the list
        }
        else
        {
            geoFenceModel = geoFenceLocations.remove(0);
        }
        DatabaseManager.getInstance(context).getHelper().getNotificationGeoFenceModelDao().delete(geoFenceModel);
        try {
            List notificationIds = new ArrayList<String>();
            notificationIds.add(String.valueOf(geoFenceModel.getId()));
            unregisterGeoFence(notificationIds);
        }
        catch (Exception e)
        {
            CustomLogger.logE("GEOFENCE ","EXCEPTION"+e);
        }

        for (GeoFenceModel geoFence: geoFenceEntries) {
            if (geoFence.getId()==geoFenceModel.getId())
            {
                geoFenceEntries.remove(geoFenceModel);
                CustomLogger.logE("GEOGENCE", "Geo Fence Removed  lat = "+geoFence.getLatitude() + " log = "+ geoFence.getLongitude() + "Radius = "+ geoFence.getRadius());
            }
        }
    }
}

private void calculateLocationDistance(Location mLastLocation, List<GeoFenceModel> geoFenceLocations) {

    for (GeoFenceModel geoFenceLocation : geoFenceLocations) {
        tempLocation.setLatitude(geoFenceLocation.getLatitude());
        tempLocation.setLongitude(geoFenceLocation.getLongitude());
        geoFenceLocation.setDistanceInMeters(mLastLocation.distanceTo(tempLocation));
    }
    Collections.sort(geoFenceLocations);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
</code>```

In logs, geofence is getting register properly.
I have implemented IntentService in pending intent. I tried broadcast receiver also but result was same.
Tried same code with multiple devices and OS version.

答:
Location updates on interval is missing in your code.

You have to request for location at HIGH_ACCURACY which enables GPS to give you accurate location at given interval time.

There are lot of changes required as per this tutorial.
go through above tutorial and let me know if it doesn't work.

You must have to create location request.

one more tutorial

Body:
I am adding multiple geofence to one app.(Max 100 allowed according to documentation.) I was getting callbacks of geofence then it stopped.
Geofence works smoothly only when I restart phone. After few minutes it stops working again.

public class GeoFenceHelper implements IGeoFenceListener, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

private Context context;
private GeofencingClient mGeoFencingClient;
private PendingIntent geoFencePendingIntent;
private String TAG = GeoFenceHelper.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
Location tempLocation = new Location("");
/**
 * The list of geoFences used in this sample.
 */
private ArrayList<Geofence> mGeoFenceList;
private List<GeoFenceModel> geoFenceEntries;
private ArrayList<String> removeGeoFenceList = new ArrayList<>();

public GeoFenceHelper(Context context) {
    this.context = context;
    mGeoFenceList = new ArrayList<>();
    mGeoFencingClient = LocationServices.getGeofencingClient(context);
}

public void registerGeoFence(List<GeoFenceModel> geoFenceEntries) {

    mGeoFenceList.clear();
    this.geoFenceEntries = geoFenceEntries;

        if (DatabaseManager.getInstance(context).getGeoFenceLocationCount() <= Constants.MAX_GEOFENCE_ENTRY_COUNT) {
            addGeoFences(geoFenceEntries);
        } else {
            buildGoogleApiClient();
        }
}

private void addGeoFences(List<GeoFenceModel> geoFenceEntries) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    for (GeoFenceModel geoFenceEntry : geoFenceEntries) {

        if(geoFenceEntry.getId()==Constants.DESTINATION_REACHED_ID) {
            removeGeoFenceList.clear();
            removeGeoFenceList.add(""+geoFenceEntry.getId());
            unregisterGeoFence(removeGeoFenceList);
        }
            Geofence geoFence = new Geofence.Builder()
                    .setRequestId(String.valueOf(geoFenceEntry.getId()))
                    .setExpirationDuration(geoFenceEntry.getExpireDuration())
                    .setCircularRegion(
                            geoFenceEntry.getLatitude(),
                            geoFenceEntry.getLongitude(),
                            geoFenceEntry.getRadius()
                    )
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .build();

            CustomLogger.logE("GEOGENCE", "Geo Fence lat = " + geoFenceEntry.getLatitude() + " log = " + geoFenceEntry.getLongitude() + "Radius = " + geoFenceEntry.getRadius()+" Expiry "+geoFenceEntry.getExpireDate());
            mGeoFenceList.add(geoFence);
    }

    mGeoFencingClient.addGeofences(getGeoFencingRequest(mGeoFenceList), getGeoFencePendingIntent());
    Utils.stopLocationUpdate(context);
}

@Override
public void unregisterGeoFence(List<String> genFenceList) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    CustomLogger.logE("GeoFence","Remove GeoFence "+genFenceList.get(0));
    mGeoFencingClient.removeGeofences(genFenceList);
}

/**
 * Builds and returns a GeoFencingRequest. Specifies the list of geoFences to be monitored.
 * Also specifies how the geoFence notifications are initially triggered.
 *
 * @param mGeoFenceList
 */
private GeofencingRequest getGeoFencingRequest(ArrayList<Geofence> mGeoFenceList) {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeoFenceList);
    return builder.build();
}

private PendingIntent getGeoFencePendingIntent() {
    // Reuse the PendingIntent if we already have it.
    if (geoFencePendingIntent != null) {
        return geoFencePendingIntent;
    }
    Intent intent = new Intent(context, GeofenceTransitionsIntentService.class);
    geoFencePendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    return geoFencePendingIntent;
}

//Location related code
private synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this.context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();

    if (mGoogleApiClient != null && !mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();
        CustomLogger.logE("tempLocation", "lat " + latitude + "long " + longitude);

        List<GeoFenceModel> geoFenceLocations = DatabaseManager.getInstance(context).getGeoFenceLocation();
        calculateLocationDistance(mLastLocation, geoFenceLocations);
        try {
            deleteLocations(geoFenceLocations);
            addGeoFences(geoFenceEntries);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    } else {
        CustomLogger.logE("tempLocation", "(Couldn't get the tempLocation. Make sure tempLocation is enabled on the device)");
    }
}

private void deleteLocations(List<GeoFenceModel> geoFenceLocations) throws SQLException {
    int reduceCount = Math.abs(Constants.MAX_GEOFENCE_ENTRY_COUNT - geoFenceLocations.size());

    CustomLogger.logE("GEOGENCE", "Geo Fence App  lat = "+geoFenceLocations.get(0).getLatitude() + " log = "+ geoFenceLocations.get(0).getLongitude() + "App sepcific = "+ geoFenceLocations.get(0).isAppSpecific());
    GeoFenceModel geoFenceModel = null;
    for (int i = 0; i < reduceCount; i++) {

        if(geoFenceLocations.get(0).isAppSpecific())
        {
            geoFenceModel = geoFenceLocations.remove(1); //because app specific item will be available at top of the list
        }
        else
        {
            geoFenceModel = geoFenceLocations.remove(0);
        }
        DatabaseManager.getInstance(context).getHelper().getNotificationGeoFenceModelDao().delete(geoFenceModel);
        try {
            List notificationIds = new ArrayList<String>();
            notificationIds.add(String.valueOf(geoFenceModel.getId()));
            unregisterGeoFence(notificationIds);
        }
        catch (Exception e)
        {
            CustomLogger.logE("GEOFENCE ","EXCEPTION"+e);
        }

        for (GeoFenceModel geoFence: geoFenceEntries) {
            if (geoFence.getId()==geoFenceModel.getId())
            {
                geoFenceEntries.remove(geoFenceModel);
                CustomLogger.logE("GEOGENCE", "Geo Fence Removed  lat = "+geoFence.getLatitude() + " log = "+ geoFence.getLongitude() + "Radius = "+ geoFence.getRadius());
            }
        }
    }
}

private void calculateLocationDistance(Location mLastLocation, List<GeoFenceModel> geoFenceLocations) {

    for (GeoFenceModel geoFenceLocation : geoFenceLocations) {
        tempLocation.setLatitude(geoFenceLocation.getLatitude());
        tempLocation.setLongitude(geoFenceLocation.getLongitude());
        geoFenceLocation.setDistanceInMeters(mLastLocation.distanceTo(tempLocation));
    }
    Collections.sort(geoFenceLocations);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

In logs, geofence is getting register properly.
I have implemented IntentService in pending intent. I tried broadcast receiver also but result was same.
Tried same code with multiple devices and OS version.


问:
MySQL table size
If I had a table with 500 million rows and good indexing would the DB suffer any performance degredation? I am wondering if I need to shard table over multiple DBs even if they might be on the same server. Each row might be 1k in size as it has a couple of text fields. Even if I foreign keyed them they would still be 500 million row table that comprises of say 700 bytes of data.

Also, any tips on engine selection for tables of this size would be great.
Any advise would be greatly appreciated.

Cheers

Rich

答: I've experienced that having over 10 million records in an InnoDB table can be very slow when the table is joined, even with proper indices. Of you're just selecting from this table alone, without joins, grouping or sorting, it might just work.</p>

ContentLicense: CC BY-SA 2.5

Title: MySQL table size


问:
File google-services.json is missing. The Google Services Plugin cannot function without it ionic 3
I am using FCM for push notification I always get this error message

"File google-services.json is missing. The Google Services Plugin
  cannot function without it ionic 3"

on phone I have placed my google-services.json on every folder and nothings working

答:
Place the google-services.json file in your project's root and make sure it will be copied to the www directory by adding this line to the config.xml file (between the <platform name="android">...</platform> tags):

```<code><resource-file src="google-services.json" target="google-services.json" />
</code>```

then run ionic cordova prepare android again.

Body:
Place the google-services.json file in your project's root and make sure it will be copied to the www directory by adding this line to the config.xml file (between the <platform name="android">...</platform> tags):

<resource-file src="google-services.json" target="google-services.json" />

then run ionic cordova prepare android again.


问:
How to enable PHP class suggestion in Visual Studio Code?
I just started using Visual Studio Code editor. But class suggestion is not showing for me. How can I enable this feature? I tried it by installing PHP IntelliSense extension but not working.</p>

答:
You can try this extension for PHP. It's working well for me.

PHP Intelephense


问:
pass an array of object to $stateParams value using angular-ui-router in readable format
I want to make my report parameter part of the url, but since the model is an array of object [{}, {}], when I pass this to the stateParam, the URL gets encoded (replaces [, { etc with digits) and hence are no more readable.

Exa.

I have a form something like this:

```<code>$scope.models = [{}, {}];

<div classs="" ng-repeat="each_model in models">
 <input class="" model="each_model.name"> Name
 <input class="" model="each_model.class"> Class
 <input class="" model="each_model.city"> City
</div>
</code>```

Currently I am passing $scope.models to $stateParams, by passing complete data to parameters:

```<code>$state.go('report', {parameters: models});
</code>```

==my app.js

```<code>.state('report', {
    url: '/report?parameters',
    templateUrl: 'views/class_report.html',
})
</code>```

How can I pass the data to the URL, so that its readable?

答:
Just check what you try to put into "parameters".

```<code>$state.go('class_report', {parameters: models});
</code>```

expect object inside models

and in yours app.js

```<code>.state('report', {
    url: '/report:parameters',
    templateUrl: 'views/class_report.html',
    params: {
              parameters: "some defaulr"
            }
   })
</code>```

Body:
I want to make my report parameter part of the url, but since the model is an array of object [{}, {}], when I pass this to the stateParam, the URL gets encoded (replaces [, { etc with digits) and hence are no more readable.

Exa.

I have a form something like this:

$scope.models = [{}, {}];

 <input class="" model="each_model.name"> Name
 <input class="" model="each_model.class"> Class
 <input class="" model="each_model.city"> City

Currently I am passing $scope.models to $stateParams, by passing complete data to parameters:

$state.go('report', {parameters: models});

==my app.js

.state('report', {
    url: '/report?parameters',
    templateUrl: 'views/class_report.html',
})

How can I pass the data to the URL, so that its readable?

Body:
Just check what you try to put into "parameters".

$state.go('class_report', {parameters: models});

expect object inside models

and in yours app.js

.state('report', {
    url: '/report:parameters',
    templateUrl: 'views/class_report.html',
    params: {
              parameters: "some defaulr"
            }
   })


问:
How to store native timestamp type data while using Eve REST API for MongoDB?
In the Mongo Rest API "Eve(0.7.4v)" , how can I insert a native Mongodb field type like timestamp with a POST request

Here is the Eve schema used:

```<code>DOMAIN = {'middlewaredata': {'timestamp':{'type':'datetime'}}}

MONGO_DBNAME  = 'helloworld'

# Enable reads (GET), inserts (POST) and DELETE for resources/collections
# (if you omit this line, the API will default to ['GET'] and provide
# read-only access to the endpoint).
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']

# Enable reads (GET), edits (PATCH), replacements (PUT) and deletes of
# individual items  (defaults to read-only item access).
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']

ALLOW_UNKNOWN=True
</code>```

Here is the sample code

```<code>import requests,datetime,json

header={'ContentType':'application/json'}
payload=json.dumps({"name":"helloworld","timestamp":datetime.datetime.utcnow().isoformat()}
requests.post("http://locahost:5000/data",headers=header,data=payload)
</code>```

This creates the following document in the Mongodb collection named "data"

```<code>{
"_id": ObjectID("5a26d12a921409307490cd4f"),
"timestamp": "2017-12-04T16:51:25.632389",
"_etag": "a3bc176e34818bd9e4af57a77c11919dbc394c7a",
"_created": ISODate("2017-12-05T17:02:34.000Z")
}
</code>```

Instead I want this to be inserted as shown below -

```<code>{
"_id": ObjectID("5a26d12a921409307490cd4f"),
"timestamp": ISODate("2017-12-04T16:51:25.632389"),
"_etag": "a3bc176e34818bd9e4af57a77c11919dbc394c7a",
"_created": ISODate("2017-12-05T17:02:34.000Z")
}
</code>```

答:
The DATE_FORMAT setting allows you to set the format of datetime values. From the documentation:

A Python date format used to parse and render datetime values. When serving requests, matching JSON strings will be parsed and stored as datetime values. In responses, datetime values will be rendered as JSON strings using this format. Defaults to the RFC1123 (ex RFC 822) standard a, %d %b %Y %H:%M:%S GMT (“Tue, 02 Apr 2013 10:29:13 GMT”).

So, unless you change the default setting, you want to provide RFC-1123 formatted strings, such as "Tue, 02 Apr 2013 10:29:13 GMT".

Body:
In the Mongo Rest API "Eve(0.7.4v)" , how can I insert a native Mongodb field type like timestamp with a POST request

Here is the Eve schema used:

DOMAIN = {'middlewaredata': {'timestamp':{'type':'datetime'}}}

MONGO_DBNAME  = 'helloworld'

# Enable reads (GET), inserts (POST) and DELETE for resources/collections
# (if you omit this line, the API will default to ['GET'] and provide
# read-only access to the endpoint).
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']

# Enable reads (GET), edits (PATCH), replacements (PUT) and deletes of
# individual items  (defaults to read-only item access).
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']

ALLOW_UNKNOWN=True

Here is the sample code

import requests,datetime,json

header={'ContentType':'application/json'}
payload=json.dumps({"name":"helloworld","timestamp":datetime.datetime.utcnow().isoformat()}
requests.post("http://locahost:5000/data",headers=header,data=payload)

This creates the following document in the Mongodb collection named "data"

{
"_id": ObjectID("5a26d12a921409307490cd4f"),
"timestamp": "2017-12-04T16:51:25.632389",
"_etag": "a3bc176e34818bd9e4af57a77c11919dbc394c7a",
"_created": ISODate("2017-12-05T17:02:34.000Z")
}

Instead I want this to be inserted as shown below -

{
"_id": ObjectID("5a26d12a921409307490cd4f"),
"timestamp": ISODate("2017-12-04T16:51:25.632389"),
"_etag": "a3bc176e34818bd9e4af57a77c11919dbc394c7a",
"_created": ISODate("2017-12-05T17:02:34.000Z")
}


问:
Need help in XSLT Code for the forming child nodes as per expected result
I am facing difficult while forming child 3 and child 4 elements like the below expected output, but no luck.

Input Message coming from external source:

```<code>    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <PurchaseOrder id="aoi00037607">
        <attr attr-name="A">
            <new-value>adi00010210</new-value>
        </attr>
        <attr attr-name="B">
            <new-value>99</new-value>
        </attr>
        <attr attr-name="C">
            <new-value>active</new-value>
        </attr>
        <attr attr-name="D">
            <new-value>
                <child1>iop00010538</child1>
                <child2>2</child2>
            </new-value>
            <new-value>
                <child1>cid2313213</child1>
                <child2>2</child2>
            </new-value>
            <new-value>
                <child1>hri00075562</child1>
                <child2>1</child2>
            </new-value>
        </attr>
        <attr attr-name="E">
            <new-value>
                <materials type="required">
                    <material system="XXX">
                        <attr attr-name="child3">primary</attr>
                        <attr attr-name="child4">2</attr>
                    </material >
                </materials>
            </new-value>
        </attr>
</PurchaseOrder>
</code>```

XSLT Code written to transform

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns0="urn:demo:PurchaseOrder">
    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*" />
    <xsl:key name="keyAttrName" match="attr" use="@attr-name" />
    <xsl:template match="PurchaseOrder">
        <ns0:PurchaseOrderMSG>>
            <Orders>
                <Order id="{@id}">
                    <xsl:for-each select="attr[generate-id() = generate-id(key('keyAttrName', @attr-name)[1])]">
                        <xsl:variable name="nodeName" select="@attr-name" />
                        <xsl:choose>
                            <xsl:when test="key('keyAttrName', @attr-name)/new-value/*/node()">
                                <xsl:for-each select="new-value">
                                    <xsl:element name="{$nodeName}">
                                        <xsl:copy-of select="*" />
                                    </xsl:element>
                                </xsl:for-each>
                            </xsl:when>
                            <xsl:when test="key('keyAttrName', @attr-name)/new-value/materials/material">
                                <xsl:for-each select="key('keyAttrName', @attr-name)">
                                    <xsl:element name="{$nodeName}">
                                        <xsl:copy-of select="attr" />
                                    </xsl:element>
                                </xsl:for-each>
                            </xsl:when>
                            <xsl:otherwise>
                                <xsl:for-each select="key('keyAttrName', @attr-name)">
                                    <xsl:element name="{$nodeName}">
                                        <xsl:value-of select="new-value" />
                                    </xsl:element>
                                </xsl:for-each>
                            </xsl:otherwise>
                        </xsl:choose>
                    </xsl:for-each>
                </Order>
            </Orders>
        </ns0:PurchaseOrderMSG>
    </xsl:template>
</xsl:stylesheet>
</code>```

The below code in the above xslt is not giving any result

```<code>                    <xsl:when test="key('keyAttrName', @attr-name)/new-value/materials/material">
                        <xsl:for-each select="key('keyAttrName', @attr-name)">
                            <xsl:element name="{$nodeName}">
                                <xsl:copy-of select="attr" />
                            </xsl:element>
                        </xsl:for-each>
                    </xsl:when>
</code>```

Expected Result:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ns0:PurchaseOrderMSG xmlns:ns0="urn:demo:PurchaseOrder">
    <Orders>
        <Order>
            <A>adi00010210</A>
            <B>99</B>
            <C>active </C>
            <D>
                <Child1>iop00010538</Child1>
                <Child2>2</Child2>
            </D>
            <D>
                <child1>cid2313213</child1>
                <child2>2</child2>
            </D>
            <D>
                <child1>hri00075562</child1>
                <child2>1</child2>
            </D>
            <E>
                <Materials type="required">
                    <Material system="XXXX">
                        <child3>primary</child3>
                        <child4>2</child4>
                    </Material>
                </Materials>
            </E>
        </Order>
    </Orders>
</ns0:PurchaseOrderMSG>
</code>```

What needs to be corrected to get the expected result?

Link for reference: Need help in forming target xml using XSLT

答:
Change

```<code><xsl:when test="key('keyAttrName', @attr-name)/new-value/*/node()">
</code>```

to

```<code><xsl:when test="key('keyAttrName', @attr-name)/new-value/*/node()[not(name() = 'material')]">
</code>```

because of this terminate conditions and your specified script not process.

Body:
I am facing difficult while forming child 3 and child 4 elements like the below expected output, but no luck.

Input Message coming from external source:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <PurchaseOrder id="aoi00037607">
        <attr attr-name="A">
            <new-value>adi00010210</new-value>
        </attr>
        <attr attr-name="B">
            <new-value>99</new-value>
        </attr>
        <attr attr-name="C">
            <new-value>active</new-value>
        </attr>
        <attr attr-name="D">
            <new-value>
                <child1>iop00010538</child1>
                <child2>2</child2>
            </new-value>
            <new-value>
                <child1>cid2313213</child1>
                <child2>2</child2>
            </new-value>
            <new-value>
                <child1>hri00075562</child1>
                <child2>1</child2>
            </new-value>
        </attr>
        <attr attr-name="E">
            <new-value>
                <materials type="required">
                    <material system="XXX">
                        <attr attr-name="child3">primary</attr>
                        <attr attr-name="child4">2</attr>
                    </material >
                </materials>
            </new-value>
        </attr>
</PurchaseOrder>

XSLT Code written to transform

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns0="urn:demo:PurchaseOrder">
    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*" />
    <xsl:key name="keyAttrName" match="attr" use="@attr-name" />
    <xsl:template match="PurchaseOrder">
        <ns0:PurchaseOrderMSG>>
            <Orders>
                <Order id="{@id}">
                    <xsl:for-each select="attr[generate-id() = generate-id(key('keyAttrName', @attr-name)[1])]">
                        <xsl:variable name="nodeName" select="@attr-name" />
                        <xsl:choose>
                            <xsl:when test="key('keyAttrName', @attr-name)/new-value/*/node()">
                                <xsl:for-each select="new-value">
                                    <xsl:element name="{$nodeName}">
                                        <xsl:copy-of select="*" />
                                    </xsl:element>
                                </xsl:for-each>
                            </xsl:when>
                            <xsl:when test="key('keyAttrName', @attr-name)/new-value/materials/material">
                                <xsl:for-each select="key('keyAttrName', @attr-name)">
                                    <xsl:element name="{$nodeName}">
                                        <xsl:copy-of select="attr" />
                                    </xsl:element>
                                </xsl:for-each>
                            </xsl:when>
                            <xsl:otherwise>
                                <xsl:for-each select="key('keyAttrName', @attr-name)">
                                    <xsl:element name="{$nodeName}">
                                        <xsl:value-of select="new-value" />
                                    </xsl:element>
                                </xsl:for-each>
                            </xsl:otherwise>
                        </xsl:choose>
                    </xsl:for-each>
                </Order>
            </Orders>
        </ns0:PurchaseOrderMSG>
    </xsl:template>
</xsl:stylesheet>

The below code in the above xslt is not giving any result

                    <xsl:when test="key('keyAttrName', @attr-name)/new-value/materials/material">
                        <xsl:for-each select="key('keyAttrName', @attr-name)">
                            <xsl:element name="{$nodeName}">
                                <xsl:copy-of select="attr" />
                            </xsl:element>
                        </xsl:for-each>
                    </xsl:when>

Expected Result:

<?xml version="1.0" encoding="UTF-8"?>
<ns0:PurchaseOrderMSG xmlns:ns0="urn:demo:PurchaseOrder">
    <Orders>
        <Order>
            adi00010210
            99
            <C>active </C>
            <D>
                <Child1>iop00010538</Child1>
                <Child2>2</Child2>
            </D>
            <D>
                <child1>cid2313213</child1>
                <child2>2</child2>
            </D>
            <D>
                <child1>hri00075562</child1>
                <child2>1</child2>
            </D>
            <E>
                <Materials type="required">
                    <Material system="XXXX">
                        <child3>primary</child3>
                        <child4>2</child4>
                    </Material>
                </Materials>
            </E>
        </Order>
    </Orders>
</ns0:PurchaseOrderMSG>

What needs to be corrected to get the expected result?

Link for reference: Need help in forming target xml using XSLT

Body:
Change

<xsl:when test="key('keyAttrName', @attr-name)/new-value/*/node()">

to

<xsl:when test="key('keyAttrName', @attr-name)/new-value/*/node()[not(name() = 'material')]">

because of this terminate conditions and your specified script not process.


问:
Disable magnification gesture in WKWebView
I'm looking for a way to disable the "pinch to zoom" magnification gesture on the iOS implementation of WKWebView. There is a magnification BOOL property available for OS X but it doesn't seem to be available on iOS.

WKWebView.h

```<code>#if !TARGET_OS_IPHONE
/* @abstract A Boolean value indicating whether magnify gestures will
 change the web view's magnification.
 @discussion It is possible to set the magnification property even if
 allowsMagnification is set to NO.
 The default value is NO.
 */
@property (nonatomic) BOOL allowsMagnification;
</code>```

I've, also, tried look at the WKWebView's gesture recognizers but that seems to be turning up an empty array. I'm assuming the actual recognizers are bured deeper in the component's structure (fairly complex, by the looks of it) and would rather not go digging for them if at all possible.

I know of possible hacks that could potentially disable the gesture from firing (selectively passing gestures to the WebView, add child view to capture pinch gesture, etc) but I've always found those introduce lag into the event and want to keep the implementation as clean/hack free as possible.

答:
If the webview is user for read-only purposes, i.e, just for displaying the web content use

webView.isUserInteractionEnabled = false

By this the zoom gesture won't work on it.

Body:
I'm looking for a way to disable the "pinch to zoom" magnification gesture on the iOS implementation of WKWebView. There is a magnification BOOL property available for OS X but it doesn't seem to be available on iOS.

WKWebView.h

#if !TARGET_OS_IPHONE
/* @abstract A Boolean value indicating whether magnify gestures will
 change the web view's magnification.
 @discussion It is possible to set the magnification property even if
 allowsMagnification is set to NO.
 The default value is NO.
 */
@property (nonatomic) BOOL allowsMagnification;

I've, also, tried look at the WKWebView's gesture recognizers but that seems to be turning up an empty array. I'm assuming the actual recognizers are bured deeper in the component's structure (fairly complex, by the looks of it) and would rather not go digging for them if at all possible.

I know of possible hacks that could potentially disable the gesture from firing (selectively passing gestures to the WebView, add child view to capture pinch gesture, etc) but I've always found those introduce lag into the event and want to keep the implementation as clean/hack free as possible.


问:
Dialogflow/ API.AI for Google Home Mini App
This is my very first question and seems to be easy but coding it is somehow difficult...

So, basically I've got an Agent that should just call a URL and get the content of the website. This should then be spoken out by the smart speaker.
I already have a webhook working but now I'm stuck at getting the web-content..

Would be awesome if someone could please help me out here.
Best regards

答:
Getting the web content is not easy . you have to parse the content in a web page using program , a simple logic is to detect '<' and '>' and remove all strings in between using string functions

Best of luck with that


问:
Can I change the location of the view scripts in Zend Framework?
Right now the view scripts for my Zend Framework application are located in the application/views/scripts directory. Is it possible to change this location to something that is configurable?

I am assuming this goes somewhere in the index.php file or my application.ini file.

答:
For convenience ZF automatically sets the view script path to be module/views/scripts/controller/action.phtml

You can add a script path via $view->addScriptPath('/path/to/view/scripts') which adds this new path to the stack of available view script paths. It checks the last one set first, then checks on the one before until it finds a file.

Or you can reset the script path via $view->setScriptPath('/path/to/view/scripts')

If you need to do this for a controller place this in your _init() method. If you need it for your entire application I'd recommend sticking it in your Bootstrap.

I believe it's also possible to place this in application.ini via: resources.view.basePath = "/path/to/views/"

See http://framework.zend.com/manual/en/zend.view.controllers.html


问:
Split string Text separator between hyphen in SQL Server
```<code>Select Code From myTable
</code>```

In a jod, I have a problem:

I have result string:

```<code> Code
-----------
 ABCD_12
 EBC_11
 DEEDC_1
</code>```

When I query data, I want to take the chain on the left "_"

And result should be:

```<code>     Code
   -------------
     ABCD
     EBC
     DEEDC
</code>```

Thank you

答:
We can extract the part before _ by using LEFT and CHARINDEX.

LEFT function returns the left part of a string with the specified number of characters. And CHARINDEX function returns the position of the character searched.

Query

```<code>select left([code], charindex('_', [code], 1) - 1) as [code]
from [myTable];
</code>```

Update :

If any string doesn't have _, then use a CASE expression to check whether the string has a _.

Query

```<code>select left([code],
            case when  charindex('_', [code] ) = 0 then len([code])
            else charindex('_', [code], 1) -1 end)
from [myTable];
</code>```

Find a demo here

Body:
Select Code From myTable

In a jod, I have a problem:

I have result string:

 Code
-----------
 ABCD_12
 EBC_11
 DEEDC_1

When I query data, I want to take the chain on the left "_"

And result should be:

     Code
   -------------
     ABCD
     EBC
     DEEDC

Thank you

Body:
We can extract the part before _ by using LEFT and CHARINDEX.

LEFT function returns the left part of a string with the specified number of characters. And CHARINDEX function returns the position of the character searched.

Query

select left([code], charindex('_', [code], 1) - 1) as [code]
from [myTable];

Update :

If any string doesn't have _, then use a CASE expression to check whether the string has a _.

Query

select left([code],
            case when  charindex('_', [code] ) = 0 then len([code])
            else charindex('_', [code], 1) -1 end)
from [myTable];

Find a demo here


问:
Caused by: java.io.IOException: Unable to lock usage tracking spool file
Having problems while building an android application with gradle, here is the error i get when building it;

```<code>Caused by: java.io.IOException: Unable to lock usage tracking spool file
            at com.android.tools.analytics.JournalingUsageTracker.newTrackFile(JournalingUsageTracker.java:98)
            at com.android.tools.analytics.JournalingUsageTracker.<init>(JournalingUsageTracker.java:78)
            ... 121 more
    Caused by: java.nio.channels.OverlappingFileLockException
            at com.android.tools.analytics.JournalingUsageTracker.newTrackFile(JournalingUsageTracker.java:95)
            ... 122 more
</code>```

Here is my gradle details: https://pastebin.com/6v0dk5in

```<code> ./gradlew --version

------------------------------------------------------------
Gradle 4.3.1
------------------------------------------------------------

Build time:   2017-11-08 08:59:45 UTC
Revision:     e4f4804807ef7c2829da51877861ff06e07e006d

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_66 (Oracle Corporation 25.66-b17)
OS:           Mac OS X 10.11 x86_64
</code>```

答:
I found these two other Stackoverflow threads that were helpful:

How do I fix an OverlappingFileLockException when building with Gradle on Windows?

Android studio, configure gradle project takes forever

The issue in this case was that the Gradle Daemon was holding onto a file lock and subsequent builds were failing. This Gradle issue provided a more sustainable workaround:

Gradle daemon locks files by leaving file handles open

Disable the daemon by adding org.gradle.daemon=false to gradle.properties

There are quite a few other variations on how to disable the Gradle build in the documentation

The Gradle Daemon is useful for making builds faster by avoiding restarting the JVM and reloading the Gradle jar, and also by caching information.

Body:
Having problems while building an android application with gradle, here is the error i get when building it;

Caused by: java.io.IOException: Unable to lock usage tracking spool file
            at com.android.tools.analytics.JournalingUsageTracker.newTrackFile(JournalingUsageTracker.java:98)
            at com.android.tools.analytics.JournalingUsageTracker.<init>(JournalingUsageTracker.java:78)
            ... 121 more
    Caused by: java.nio.channels.OverlappingFileLockException
            at com.android.tools.analytics.JournalingUsageTracker.newTrackFile(JournalingUsageTracker.java:95)
            ... 122 more

Here is my gradle details: https://pastebin.com/6v0dk5in

 ./gradlew --version

------------------------------------------------------------
Gradle 4.3.1
------------------------------------------------------------

Build time:   2017-11-08 08:59:45 UTC
Revision:     e4f4804807ef7c2829da51877861ff06e07e006d

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_66 (Oracle Corporation 25.66-b17)
OS:           Mac OS X 10.11 x86_64


问:
How can I update npm on Windows?
I tried this:

```<code>sudo npm cache clean -f
sudo npm install -g n
sudo n stable
</code>```

...but it didn't work.

How do I do this on Windows?

答:
1.    Installing latest npm version

```<code>npm install –g npm@latest
</code>```

(You can type "npm –version" to check that)

2. Installing Node

a.  Install node new version via following URL: https://nodejs.org/en/download/current/
Follow the default choices

b.  Remove C:\Users\\AppData\Roaming\NPM

c.  Remove C:\Users\\AppData\Roaming\npm-cache

Optionally:

d.  (Delete node_modules folder in your current project folder)

e.     npm cache verify

f.     npm install

Title: How can I update npm on Windows?

Body:
I tried this:

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

...but it didn't work.

How do I do this on Windows?

Body:
1.    Installing latest npm version

npm install –g npm@latest

(You can type "npm –version" to check that)

2. Installing Node

a.  Install node new version via following URL: https://nodejs.org/en/download/current/
Follow the default choices

b.  Remove C:\Users\\AppData\Roaming\NPM

c.  Remove C:\Users\\AppData\Roaming\npm-cache

Optionally:

d.  (Delete node_modules folder in your current project folder)

e.     npm cache verify

f.     npm install


问:
how to read files in postgresql data directory
How to read a file in pgsql/data/base/16384 directory in postgresql.
these files similar to binary file or dat file.
I try to import it in a specific table using pgAdmin, but I got error like this:
see the below picture

Also I try to Restore whole database using tar file but i got "no header for toc.dat" when restoring with pgadmin.

Is there any way to read files in data/base/16384 in postgresql?

Thank to All my friend.

答:
try this with pgAdmin:</p>

```<code>select datname from pg_database where oid = 16384;
--connect to the database from return of above
select relname from pg_class where relfilenode = 11779;
--select * from <return of above>
</code>```

Body:
try this with pgAdmin:

select datname from pg_database where oid = 16384;
--connect to the database from return of above
select relname from pg_class where relfilenode = 11779;
--select * from <return of above>


问:
Updating Apache Felix SCR to OSGi Declarative Services R6 - @Property
I'm updating from Apache Felix SCR Annotations to OSGi DS R6 ones and the one is causing me more problem is the @Property inside the class.

Before I had:

```<code>@Component (immediate = true)
@Service (A.class)
public class AImpl implements A
{
    @Property (intValue = 604800)
    public static final String A = "a";
    ...
}
</code>```

Now I have:

```<code>@Component (service = A.class, immediate = true)
@Designate (ocd = Configuration.class)
public class AImpl implements A
{
    ...
}
</code>```

and

```<code>@ObjectClassDefinition (name = "Bla")
public @interface Configuration
{
    @AttributeDefinition (name = "A", type = AttributeType.INTEGER)
    int A() default 604800;
}
</code>```

The most bizarre thing on all of this is:

Before, I could see my AImpl class as a component.

Now, I couldn't see my AImpl class as a component and everyone who uses it cannot start because of unsatisfied references.

How come changing just configurations like this can cause this behaviour ? Maybe I'm missing something ?

The stranger part on all of this is my xml is inside the .jar and seems ok.
The scr:info is getting me nullpointer exception and I cannot see my component, meaning the scr:list will no help in anything.

XML BELLOW:

```<code><?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.3.0" name="AImpl" immediate="true" activate="init" deactivate="stop">
  <implementation class="AImpl"/>
  <service>
    <provide interface="A"/>
  </service>
  <reference name="Bla1" interface="Bla1Service" bind="bindBla1Service" unbind="unbindBla1Service"/>
  <property name="PROP.EVENT.INTERVAL" type="Long" value="900000"/>
</scr:component>
</code>```

Ps.: The classes are with strange names and so on because it's from a private company.

STACKTRACE:

2017-12-11T16:40:27.689+0100 [Framework Event Dispatcher] ERROR o.o.p.l.l.internal.FrameworkHandler:144 frameworkEvent FrameworkEvent ERROR - org.apache.felix.scr
org.osgi.framework.BundleException: The activator org.apache.felix.scr.impl.Activator for bundle org.apache.felix.scr is invalid
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:172)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:679)
        at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.updateWorker(AbstractBundle.java:645)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.update(AbstractBundle.java:592)
        at org.apache.felix.webconsole.internal.core.UpdateHelper.doRun(UpdateHelper.java:60)
        at org.apache.felix.webconsole.internal.core.BaseUpdateInstallHelper.doRun(BaseUpdateInstallHelper.java:93)
        at org.apache.felix.webconsole.internal.core.UpdateHelper.doRun(UpdateHelper.java:70)
        at org.apache.felix.webconsole.internal.core.BaseUpdateInstallHelper.run(BaseUpdateInstallHelper.java:123)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassCastException: org.apache.felix.scr.impl.Activator cannot be cast to org.osgi.framework.BundleActivator
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:167)
        ... 9 common frames omitted

Part of POM.XML who install on karaf my bundles:

```<code><artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-kar-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <inherited>false</inherited>
                        <configuration>
                            <includeScope>runtime</includeScope>
                            <prependGroupId>true</prependGroupId>
                            <excludeTransitive>true</excludeTransitive>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>org.osgi</groupId>
                                    <artifactId>org.osgi.framework</artifactId>
                                    <version>${org.osgi.framework.version}</version>
                                </artifactItem>
                                <artifactItem>
                                    <groupId>org.osgi</groupId>
                                    <artifactId>org.osgi.core</artifactId>
                                    <version>${org.osgi.core.version}</version>
                                </artifactItem>
                                <artifactItem>
                                    <groupId>org.apache.felix</groupId>
                                    <artifactId>org.apache.felix.scr</artifactId>
                                    <version>${org.apache.felix.scr.version}</version>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
</execution>
</executions>
</code>```

答:
This part looks like the error: service=AImpl.class. Your component should be published as a service using its interface A, not the implementation class.

This normally happens implicitly because the component directly implements interface A, but you have overridden that.

The solution should be to simply delete the service=AImpl.class attribute from the @Component annotation.

Body:
I'm updating from Apache Felix SCR Annotations to OSGi DS R6 ones and the one is causing me more problem is the @Property inside the class.

Before I had:

@Component (immediate = true)
@Service (A.class)
public class AImpl implements A
{
    @Property (intValue = 604800)
    public static final String A = "a";
    ...
}

Now I have:

@Component (service = A.class, immediate = true)
@Designate (ocd = Configuration.class)
public class AImpl implements A
{
    ...
}

and

@ObjectClassDefinition (name = "Bla")
public @interface Configuration
{
    @AttributeDefinition (name = "A", type = AttributeType.INTEGER)
    int A() default 604800;
}

The most bizarre thing on all of this is:

Before, I could see my AImpl class as a component.

Now, I couldn't see my AImpl class as a component and everyone who uses it cannot start because of unsatisfied references.

How come changing just configurations like this can cause this behaviour ? Maybe I'm missing something ?

The stranger part on all of this is my xml is inside the .jar and seems ok.
The scr:info is getting me nullpointer exception and I cannot see my component, meaning the scr:list will no help in anything.

XML BELLOW:

<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.3.0" name="AImpl" immediate="true" activate="init" deactivate="stop">
  <implementation class="AImpl"/>
  <service>
    <provide interface="A"/>
  </service>
  <reference name="Bla1" interface="Bla1Service" bind="bindBla1Service" unbind="unbindBla1Service"/>
  <property name="PROP.EVENT.INTERVAL" type="Long" value="900000"/>
</scr:component>

Ps.: The classes are with strange names and so on because it's from a private company.

STACKTRACE:

2017-12-11T16:40:27.689+0100 [Framework Event Dispatcher] ERROR o.o.p.l.l.internal.FrameworkHandler:144 frameworkEvent FrameworkEvent ERROR - org.apache.felix.scr
org.osgi.framework.BundleException: The activator org.apache.felix.scr.impl.Activator for bundle org.apache.felix.scr is invalid
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:172)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:679)
        at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.updateWorker(AbstractBundle.java:645)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.update(AbstractBundle.java:592)
        at org.apache.felix.webconsole.internal.core.UpdateHelper.doRun(UpdateHelper.java:60)
        at org.apache.felix.webconsole.internal.core.BaseUpdateInstallHelper.doRun(BaseUpdateInstallHelper.java:93)
        at org.apache.felix.webconsole.internal.core.UpdateHelper.doRun(UpdateHelper.java:70)
        at org.apache.felix.webconsole.internal.core.BaseUpdateInstallHelper.run(BaseUpdateInstallHelper.java:123)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassCastException: org.apache.felix.scr.impl.Activator cannot be cast to org.osgi.framework.BundleActivator
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:167)
        ... 9 common frames omitted

Part of POM.XML who install on karaf my bundles:

<artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-kar-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <inherited>false</inherited>
                        <configuration>
                            <includeScope>runtime</includeScope>
                            <prependGroupId>true</prependGroupId>
                            <excludeTransitive>true</excludeTransitive>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>org.osgi</groupId>
                                    <artifactId>org.osgi.framework</artifactId>
                                    <version>${org.osgi.framework.version}</version>
                                </artifactItem>
                                <artifactItem>
                                    <groupId>org.osgi</groupId>
                                    <artifactId>org.osgi.core</artifactId>
                                    <version>${org.osgi.core.version}</version>
                                </artifactItem>
                                <artifactItem>
                                    <groupId>org.apache.felix</groupId>
                                    <artifactId>org.apache.felix.scr</artifactId>
                                    <version>${org.apache.felix.scr.version}</version>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
</execution>
</executions>


问:
How i loop through my class object add in hashtable object
```<code>// this is my class object
Friend f1 = new Friend("Nazir",24);
Friend f2 = new Friend("Hamza", 24);
Friend f3 = new Friend("Abdullah", 23);

Hashtable myhash = new Hashtable();

// add this object in hashtable object
myhash.Add("13b-049-bs",f1);
myhash.Add("13b-034-bs", f1);
myhash.Add("13b-038-bs", f1);

foreach (Friend item in myhash)
{
    Console.WriteLine("Key {0}\tName {1}\tAge {2}",item.Name,item.Age,myhash.Keys);
}
</code>```

I got this error:

An unhandled exception of type 'System.InvalidCastException' occurred in HashTableDemo.exe

答:
The iterator (enumerator) of Hashtable returns objects of type DictionaryEntry. Therefore, in your foreach loop, each item will have two properties: Key and Value, both of type object. You can individually cast the Key and Value properties on each item to your desired type. For example:

```<code>foreach (DictionaryEntry item in myhash)
{
    // Cast item.Key to string
    string key = (string)item.Key;

    // And cast item.Value to Friend
    Friend friend = (Friend)item.Value;

    Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, friend.Name, friend.Age);
}
</code>```

Body:
// this is my class object
Friend f1 = new Friend("Nazir",24);
Friend f2 = new Friend("Hamza", 24);
Friend f3 = new Friend("Abdullah", 23);

Hashtable myhash = new Hashtable();

// add this object in hashtable object
myhash.Add("13b-049-bs",f1);
myhash.Add("13b-034-bs", f1);
myhash.Add("13b-038-bs", f1);

foreach (Friend item in myhash)
{
    Console.WriteLine("Key {0}\tName {1}\tAge {2}",item.Name,item.Age,myhash.Keys);
}

I got this error:

An unhandled exception of type 'System.InvalidCastException' occurred in HashTableDemo.exe

Body:
The iterator (enumerator) of Hashtable returns objects of type DictionaryEntry. Therefore, in your foreach loop, each item will have two properties: Key and Value, both of type object. You can individually cast the Key and Value properties on each item to your desired type. For example:

foreach (DictionaryEntry item in myhash)
{
    // Cast item.Key to string
    string key = (string)item.Key;

    // And cast item.Value to Friend
    Friend friend = (Friend)item.Value;

    Console.WriteLine("Key {0}\tName {1}\tAge {2}", key, friend.Name, friend.Age);
}


问:
Django URLS, how to map root to app?
I am pretty new to django but experienced in Python and java web programming with different frameworks.
I have made myself a nice little django app, but I cant seem to make it match www.mysite.com as opposed to www.mysite.com/myapp.

I have defined urls and views in my urls.conf which is currently not decoupled from the app (don't mind that).

```<code>urlpatterns = patterns('myapp.views',
  (r'^myapp/$', 'index'),
  (r'^myapp/(?P<some_id>\d+)/global_stats/$', 'global_stats'),
  (r'^myapp/(?P<some_id>\d+)/player/(?P<player_id>\d+)/$', 'player_stats'),
)
</code>```

All this works like a charm. If someone goes to www.mysite.com/myapp they will hit my index view which causes a http redirect to my "correct" default url.

So, how can I add a pattern that will do the same as (r'^myapp/$', 'index') but without the /myapp--that is, www.mysite.com should suffice?

I would think this would be very basic stuff... I tried adding a line like:

```<code>(r'^$', 'index'),
</code>```

however this throws me in a loop...

Hope you django gurus out there can clarify this for me!

答:
I know the answer is late, but i had my fair share of hunting recently. This is what i tried with CBV..
in Project urls.py

```<code>urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', include('app_name.urls', namespace='app_name')),
]
</code>```

PS: It is always recommended to use namespace. Gives a good advantage later on.

In App urls.py

```<code>urlpatterns = [
    url(r'^$', views.IndexPageView.as_view(), name='index'),
]
</code>```

Title: Django URLS, how to map root to app?

Body:
I am pretty new to django but experienced in Python and java web programming with different frameworks.
I have made myself a nice little django app, but I cant seem to make it match www.mysite.com as opposed to www.mysite.com/myapp.

I have defined urls and views in my urls.conf which is currently not decoupled from the app (don't mind that).

urlpatterns = patterns('myapp.views',
  (r'^myapp/$', 'index'),
  (r'^myapp/(?P<some_id>\d+)/global_stats/$', 'global_stats'),
  (r'^myapp/(?P<some_id>\d+)/player/(?P<player_id>\d+)/$', 'player_stats'),
)

All this works like a charm. If someone goes to www.mysite.com/myapp they will hit my index view which causes a http redirect to my "correct" default url.

So, how can I add a pattern that will do the same as (r'^myapp/$', 'index') but without the /myapp--that is, www.mysite.com should suffice?

I would think this would be very basic stuff... I tried adding a line like:

(r'^$', 'index'),

however this throws me in a loop...

Hope you django gurus out there can clarify this for me!

Body:
I know the answer is late, but i had my fair share of hunting recently. This is what i tried with CBV..
in Project urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', include('app_name.urls', namespace='app_name')),
]

PS: It is always recommended to use namespace. Gives a good advantage later on.

In App urls.py

urlpatterns = [
    url(r'^$', views.IndexPageView.as_view(), name='index'),
]


问:
Faster way to calculate driving distance to many points
I am trying to calculate the driving distance from one origin point and then to many different destinations points (I need to find the closest driver).
I use PHP and I basically run this function many times:

```<code>file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins=' . $latitude . ',' . $longitude . '&destinations=' . $latitude1 . ',' . $longitude1 . '&mode=car&language=da-DK&key=My_API&alternatives=false&sensor=false');
</code>```

I need the distance from latitude, longitude and in some cases 40+ different potential destinations.
My problem is, that it takes forever to calculate the many points one call at the time. It takes 51-56 sec to find the distance from the one origin point to 37 different potential destination points.

Is there a faster way? or service ?

I wish you all a great day.

best regards

答:
Well, IMO you have 3 possibilities:

1) Stick with php and use pthreads, you may be able to process one request per thread and reduce the time your script is working. Have a look at this

2) go "async" and use one http request per driver, so get a list of drivers first and then send a request for each driver. This would involve there is a frontend capeable of executing javascript (browser)

3) use another technology for this purpose, that is non-blocking, like nodejs. Using promises you could do this easily:

```<code>let urls = ["url1", "url2", "url3"];

asnyc doRequest(url) {
    // return promise...
}

Promise.all(urls.map(doRequest)).then(data => {
    console.log(data);
});
</code>```

Have a look here!

Body:
I am trying to calculate the driving distance from one origin point and then to many different destinations points (I need to find the closest driver).
I use PHP and I basically run this function many times:

file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins=' . $latitude . ',' . $longitude . '&destinations=' . $latitude1 . ',' . $longitude1 . '&mode=car&language=da-DK&key=My_API&alternatives=false&sensor=false');

I need the distance from latitude, longitude and in some cases 40+ different potential destinations.
My problem is, that it takes forever to calculate the many points one call at the time. It takes 51-56 sec to find the distance from the one origin point to 37 different potential destination points.

Is there a faster way? or service ?

I wish you all a great day.

best regards

Body:
Well, IMO you have 3 possibilities:

1) Stick with php and use pthreads, you may be able to process one request per thread and reduce the time your script is working. Have a look at this

2) go "async" and use one http request per driver, so get a list of drivers first and then send a request for each driver. This would involve there is a frontend capeable of executing javascript (browser)

3) use another technology for this purpose, that is non-blocking, like nodejs. Using promises you could do this easily:

let urls = ["url1", "url2", "url3"];

asnyc doRequest(url) {
    // return promise...
}

Promise.all(urls.map(doRequest)).then(data => {
    console.log(data);
});

Have a look here!


问:
C++ displaying the wrong object

I am a beginner in C++ and I am trying to create 2 classes that stores Movie for each Day.
For example, there are 2 movies on saturday. One of the movie is Batman and the other is Spiderman. So the object Day saturday should store 2 different movies. However, the problem is when I tried to display the object stored in saturday with the function showAllMovies() within the class Day, it showed the last movie only. Any idea what I have done wrong?

EDIT: I can only use these libraries since my assignment won't allow me to use other libraries.

```<code><iostream>, <iomanip>, <fstream>, <cmath>
</code>```

```<code>#include <iostream>
using namespace std;

class Movie {
private:
    char* name;
public:
    void setName(char* n) {
        name = n;
    }
    char* getName() {
        return name;
    }
};

class Day {
private:
    int movieCount = 0;
    Movie movie[20];
public:
    void addMovie(Movie p) {
        movie[movieCount] = p;
        movieCount++;
    }
    void showAllMovies() {
        for (int i = 0;i < movieCount;i++) {
            cout << "Index: " << i << ", Name: " << movie[i].getName() << endl;
        }
    }
};

int main()
{
    Day saturday;
    int numOfMovies = 0;

    cout << "Input the number of Movies: " << endl;
    cin >> numOfMovies;

    cout << "Input the name of Movie: " << endl;
    for (int i = 0;i < numOfMovies;i++) {
        char movieName[10];
        //Get input
        cin >> movieName;
        Movie m;
        m.setName(movieName);
        saturday.addMovie(m);

    }

    //Show all the name of movies
    cout << "All movies on saturday: " << endl;
    saturday.showAllMovies();

    return 0;
}
</code>```

Input:
2
Batman
Spiderman

Output:

I am expecting to get something like

```<code>All movies on saturday:
Index: 0, Name: Batman
Index: 1, Name: Spiderman
</code>```

Thanks to everyone helping me out. The Solution is to change

```<code>char movieName[10];
</code>```

to

```<code>char *movieName = new char[10];
</code>```

答:
```<code>for (int i = 0;i < numOfMovies;i++) {
        char movieName[10];
        //Get input
        cin >> movieName;
        Movie m;
        m.setName(movieName);
        saturday.addMovie(m);

    }
</code>```

when you call setName internally you make name (which is field of Movie object) point to movieName - however, movieName dies on the next iteration of the for loop due to scope.

The last instance of movieName should also not be accessed after the loop ends.

Title: C++ displaying the wrong object

Body:
I am a beginner in C++ and I am trying to create 2 classes that stores Movie for each Day.
For example, there are 2 movies on saturday. One of the movie is Batman and the other is Spiderman. So the object Day saturday should store 2 different movies. However, the problem is when I tried to display the object stored in saturday with the function showAllMovies() within the class Day, it showed the last movie only. Any idea what I have done wrong?

EDIT: I can only use these libraries since my assignment won't allow me to use other libraries.

<iostream>, <iomanip>, <fstream>, <cmath>

#include <iostream>
using namespace std;

class Movie {
private:
    char* name;
public:
    void setName(char* n) {
        name = n;
    }
    char* getName() {
        return name;
    }
};

class Day {
private:
    int movieCount = 0;
    Movie movie[20];
public:
    void addMovie(Movie p) {
        movie[movieCount] = p;
        movieCount++;
    }
    void showAllMovies() {
        for (int i = 0;i < movieCount;i++) {
            cout << "Index: " << i << ", Name: " << movie[i].getName() << endl;
        }
    }
};

int main()
{
    Day saturday;
    int numOfMovies = 0;

    cout << "Input the number of Movies: " << endl;
    cin >> numOfMovies;

    cout << "Input the name of Movie: " << endl;
    for (int i = 0;i < numOfMovies;i++) {
        char movieName[10];
        //Get input
        cin >> movieName;
        Movie m;
        m.setName(movieName);
        saturday.addMovie(m);

    }

    //Show all the name of movies
    cout << "All movies on saturday: " << endl;
    saturday.showAllMovies();

    return 0;
}

Input:
2
Batman
Spiderman

Output:

I am expecting to get something like

All movies on saturday:
Index: 0, Name: Batman
Index: 1, Name: Spiderman

Thanks to everyone helping me out. The Solution is to change

char movieName[10];

to

char *movieName = new char[10];

Body:
for (int i = 0;i < numOfMovies;i++) {
        char movieName[10];
        //Get input
        cin >> movieName;
        Movie m;
        m.setName(movieName);
        saturday.addMovie(m);

    }

when you call setName internally you make name (which is field of Movie object) point to movieName - however, movieName dies on the next iteration of the for loop due to scope.

The last instance of movieName should also not be accessed after the loop ends.


问:
Calling a method every x minutes
I want to call some method on every 5 minutes. How can I do this?</p>

```<code>public class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("*** calling MyMethod *** ");
        Console.ReadLine();
    }

    private MyMethod()
    {
        Console.WriteLine("*** Method is executed at {0} ***", DateTime.Now);
        Console.ReadLine();
    }
}
</code>```

答:
I've uploaded a Nuget Package that can make it so simple, you can have it from here ActionScheduler

It supports .NET Standard 2.0

And here how to start using it

```<code>using ActionScheduler;

var jobScheduler = new JobScheduler(TimeSpan.FromMinutes(8), new Action(() => {
  //What you want to execute
}));

jobScheduler.Start(); // To Start up the Scheduler

jobScheduler.Stop(); // To Stop Scheduler from Running.
</code>```

Title: Calling a method every x minutes

Body:
I want to call some method on every 5 minutes. How can I do this?

public class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("*** calling MyMethod *** ");
        Console.ReadLine();
    }

    private MyMethod()
    {
        Console.WriteLine("*** Method is executed at {0} ***", DateTime.Now);
        Console.ReadLine();
    }
}

Body:
I've uploaded a Nuget Package that can make it so simple, you can have it from here ActionScheduler

It supports .NET Standard 2.0

And here how to start using it

using ActionScheduler;

var jobScheduler = new JobScheduler(TimeSpan.FromMinutes(8), new Action(() => {
  //What you want to execute
}));

jobScheduler.Start(); // To Start up the Scheduler

jobScheduler.Stop(); // To Stop Scheduler from Running.


问:
how to display 3 random pictures out of 8 using bash
I have 8 images in a directory.

the path is /blabla.com/img.

I need to access this path and choose 3 out of 8 randomly and display those.

If 3 pics are the same, it should echo "yeeey".

Otherwise, "neeey" and record these responses in a text file.

答:
I am not going to do your homework for you!
However I can give you some insight:

store your 8 file names in an array

call $RANDOM % 8 3 times and store the value in 3 index variables

use the 3 index variables to extract your 3 files

use sha256sum, sha512sum or md5sum to compute the signature of your images and store the result in 3 variables

compare the values of the 3 variables if they are the same echo "yeeey" else echo "neeey"

if on top of that you want to display the picture as written in your post you could call eog or other similar tool with the finename as parameter and of course in background, with a & at the end of the command call.

Good luck with your assignment and let me know if you need help!


问:
Is it possible to get an rss feed using javascript client side scripting only?
If I can't do this would the process for getting the data be:
1) Have my server get the rss data from the desired rss feed.
2) Have the server parse the data.  I don't know what rss looks like but I assume some parsing     is needed to display it for a user to read.
3) Send the data to the javascript client.</p>

答:
You can use Yahoo's YQL system just for this. A decent link via Google:

http://www.wait-till-i.com/2008/12/12/yql-is-so-the-bomb-to-get-web-data-as-xml-or-json/


问:
Unable to build Cordova Android on Mac
```<code>Krishnas-MacBook-Air:trialapp krishnalahoti$ cordova build android
ANDROID_HOME=/Users/krishnalahoti/Library/Android/sdk
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
Error: spawn EACCES
</code>```

While running the command for "cordova build android" i am getting the following error and unable to figure out the solution to make a successful cordova android build on ios

答:
You need to add execute permissions to the Gradle demon as it only has rw-r--r by default.

Assuming you have Android Studio installed, you can do this by running the below command

```<code>$ chmod +x /Applications/Android\ Studio.app/Contents/gradle/bin/gradle-<VERSION HERE>/bin/gradle
</code>```

Title: Unable to build Cordova Android on Mac

Body:
Krishnas-MacBook-Air:trialapp krishnalahoti$ cordova build android
ANDROID_HOME=/Users/krishnalahoti/Library/Android/sdk
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
Error: spawn EACCES

While running the command for "cordova build android" i am getting the following error and unable to figure out the solution to make a successful cordova android build on ios

Body:
You need to add execute permissions to the Gradle demon as it only has rw-r--r by default.

Assuming you have Android Studio installed, you can do this by running the below command

$ chmod +x /Applications/Android\ Studio.app/Contents/gradle/bin/gradle-<VERSION HERE>/bin/gradle


问:
How can I access database mysql on the server staging?
Mysql gui tools that I use to connect to my database is sql yog

I connect use data from env laravel

If I connect with data from env localhost, it works

If I connect with data from staging server, it does not works

My env localhost like this :

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myshop
DB_USERNAME=root
DB_PASSWORD=secret
</code>```

I try in sql yog like this :

I use db host, db port, username and password from env to connect in sql yog like that

It works

My env server staging like this :

```<code>DB_CONNECTION=mysql
DB_HOST=xx.xxx.xx.xx
DB_PORT=3306
DB_DATABASE=myshop
DB_USERNAME=forge
DB_PASSWORD=xxxxxxxxxxxxxxx
</code>```

I use the data to connect with sql yog

There exist error like this :

How can I solve this error?

答:
You must use the SSH tunneling for that.

http://sqlyogkb.webyog.com/article/154-connecting-using-ssh-tunneling

Body:
Mysql gui tools that I use to connect to my database is sql yog

I connect use data from env laravel

If I connect with data from env localhost, it works

If I connect with data from staging server, it does not works

My env localhost like this :

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myshop
DB_USERNAME=root
DB_PASSWORD=secret

I try in sql yog like this :

I use db host, db port, username and password from env to connect in sql yog like that

It works

My env server staging like this :

DB_CONNECTION=mysql
DB_HOST=xx.xxx.xx.xx
DB_PORT=3306
DB_DATABASE=myshop
DB_USERNAME=forge
DB_PASSWORD=xxxxxxxxxxxxxxx

I use the data to connect with sql yog

There exist error like this :

How can I solve this error?


答:
Try this:</p>

```<code>select SUBSTRING(Code, CHARINDEX('_', Code) + 1, LEN(Code))
</code>```

Title: Split string Text separator between hyphen in SQL Server

Body:
Select Code From myTable

In a jod, I have a problem:

I have result string:

 Code
-----------
 ABCD_12
 EBC_11
 DEEDC_1

When I query data, I want to take the chain on the left "_"

And result should be:

     Code
   -------------
     ABCD
     EBC
     DEEDC

Thank you

Body:
Try this:

select SUBSTRING(Code, CHARINDEX('_', Code) + 1, LEN(Code))


问:
How to deal with entity relations when fetching data via REST API?
Suppose you have an entity User within a typical Java web application. E.g. Spring framework, Hibernate ORM, and etc. User has some relations e.g.:

```<code>public class User {
    // primitive fields
    private Team team;
    private Set<Group>;
    // ...
}
</code>```

You can easily browse user's graph, e.g. user.getTeam().getName()

What are the best practices of exposing such entities via REST API, and accessing them from Java client?

E.g. when I need to load a user by id. Should I get a response that also contains team, and groups? What if I don't need those relations each time user is fetched.

The question is more about designing a Java client.

答:
In my opinion, it depends on the, in your case, the Team object's size and usage. If it is very small or it's always needed when you need a user, you may attach it directly to the User when calling Get /users/{id}. Otherwise it would get the Team with Get /users/{id}/team.

Best practice would be HATEOAS. A call to Get /users/{id} would return you a user json object, which also indicates the team property by including the path (Get /users/{id}/team) to it. But as this is a lot of work, one might to not go that extra step.

Body:
Suppose you have an entity User within a typical Java web application. E.g. Spring framework, Hibernate ORM, and etc. User has some relations e.g.:

public class User {
    // primitive fields
    private Team team;
    private Set<Group>;
    // ...
}

You can easily browse user's graph, e.g. user.getTeam().getName()

What are the best practices of exposing such entities via REST API, and accessing them from Java client?

E.g. when I need to load a user by id. Should I get a response that also contains team, and groups? What if I don't need those relations each time user is fetched.

The question is more about designing a Java client.


问:
Python Regular Expression to add links to urls
I'm trying to make a regular expression that will correctly capture URLs, including ones that are wrapped in parenthesis as in (http://example.com) and spoken about on coding horror at https://blog.codinghorror.com/the-problem-with-urls/

I'm currently using the following to create HTML A tags in python for links that start with http and www.

```<code>r1 = r"(\b(http|https)://([-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]))"
r2 = r"((^|\b)www\.([-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]))"
return re.sub(r2,r'<a rel="nofollow" target="_blank" href="http://\1">\1</a>',re.sub(r1,r'<a rel="nofollow" target="_blank" href="\1">\1</a>',text))
</code>```

this works well except for the case where someone wraps the url in parens.  Does anyone have a better way?

答:
Problem is, URLs could have parenthesis as part of them... (http://en.wikipedia.org/wiki/Tropical_Storm_Alberto_(2006)) . You can't treat that with regexp alone, since it doesn't have state. You need a parser. So your best chance would be to use a parser, and try to guess the correct close parenthesis. That is error-prone (the url could open parenthesis and never close it) so I guess you're out of luck anyway.

See also http://en.wikipedia.org/wiki/, or (http://en.wikipedia.org/wiki/)) and other similar valid URLs.

OwnerDisplayName: Lokelo

Body:
I'm trying to make a regular expression that will correctly capture URLs, including ones that are wrapped in parenthesis as in (http://example.com) and spoken about on coding horror at https://blog.codinghorror.com/the-problem-with-urls/

I'm currently using the following to create HTML A tags in python for links that start with http and www.

r1 = r"(\b(http|https)://([-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]))"
r2 = r"((^|\b)www\.([-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]))"
return re.sub(r2,r'\1',re.sub(r1,r'\1',text))

this works well except for the case where someone wraps the url in parens.  Does anyone have a better way?

OwnerDisplayName: nosklo

LastEditorDisplayName: nosklo


问:
Running Apache Hadoop 2.1.0 on Windows
I am new to Hadoop and have run into problems trying to run it on my Windows 7 machine. Particularly I am interested in running Hadoop 2.1.0 as its release notes mention that running on Windows is supported. I know that I can try to run 1.x versions on Windows with Cygwin or even use prepared VM by for example Cloudera, but these options are in some reasons less convenient for me.

Having examined a tarball from http://apache-mirror.rbc.ru/pub/apache/hadoop/common/hadoop-2.1.0-beta/ I found that there really are some *.cmd scripts that can be run without Cygwin. Everything worked fine when I formated HDFS partition but when I tried to run hdfs namenode daemon I faced two errors: first, non fatal, was that winutils.exe could not be found (it really wasn't present in the tarball downloaded). I found the sources of this component in the Apache Hadoop sources tree and compiled it with Microsoft SDK and MSbuild. Thanks to detailed error message it was clear where to put the executable to satisfy Hadoop. But the second error which is fatal doesn't contain enough information for me to solve:

```<code>13/09/05 10:20:09 FATAL namenode.NameNode: Exception in namenode join
java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:423)
    at org.apache.hadoop.fs.FileUtil.canWrite(FileUtil.java:952)
    at org.apache.hadoop.hdfs.server.common.Storage$StorageDirectory.analyzeStorage(Storage.java:451)
    at org.apache.hadoop.hdfs.server.namenode.FSImage.recoverStorageDirs(FSImage.java:282)
    at org.apache.hadoop.hdfs.server.namenode.FSImage.recoverTransitionRead(FSImage.java:200)
...
13/09/05 10:20:09 INFO util.ExitUtil: Exiting with status 1
</code>```

Looks like something else should be compiled. I'm going to try to build Hadoop from the source with Maven but isn't there a simpler way? Isn't there some option-I-know-not-of that can disable native code and make that tarball usable on Windows?

Thank you.

UPDATED. Yes, indeed. "Homebrew" package contained some extra files, most importantly winutils.exe and hadoop.dll. With this files namenode and datanode started successfully. I think the question can be closed. I didn't delete it in case someone face the same difficulty.

UPDATED 2. To build the "homebrew" package I did the following:

Got sources, and unpacked them.

Read carefully BUILDING.txt.

Installed dependencies:

3a) Windows SDK 7.1

3b) Maven (I used 3.0.5)
3c) JDK (I used 1.7.25)

3d) ProtocolBuffer (I used 2.5.0 - http://protobuf.googlecode.com/files/protoc-2.5.0-win32.zip). It is enough just to put compiler (protoc.exe) into some of the PATH folders.

3e) A set of UNIX command line tools (I installed Cygwin)

Started command line of Windows SDK. Start | All programs | Microsoft Windows SDK v7.1 | ... Command Prompt (I modified this shortcut, adding option /release in the command line to build release versions of native code). All the next steps are made from inside SDK command line window)

Set up the environment:

set JAVA_HOME={path_to_JDK_root}

It seems that JAVA_HOME MUST NOT contain space!

```<code>set PATH={path_to_maven_bin};%PATH%
set Platform=x64
set PATH={path_to_cygwin_bin};%PATH%
set PATH={path_to_protoc.exe};%PATH%
</code>```

Changed dir to sources root folder (BUILDING.txt warns that there are some limitations on the path length so sources root should have short name - I used D:\hds)

Ran building process:

mvn package -Pdist -DskipTests

You can try without 'skipTests' but on my machine some tests failed and building was terminated. It may be connected to sybolic link issues mentioned in BUILDING .txt.
8. Picked the result in hadoop-dist\target\hadoop-2.1.0-beta (windows executables and dlls are in 'bin' folder)

答:
Download & Install Java in c:/java/

make sure the path is this way, if java is installed in 'program
  files', then hadoop-env.cmd will not recognize java path

Download Hadoop binary distribution.

I am using binary distribution Hadoop-2.8.1. Also I would recommend to keep extraction path as short as possible

Set Environment Variables:

```<code>JAVA_HOME = "c:/Java"
HADOOP_HOME="<your hadoop home>"
Path= "JAVA_HOME/bin"
Path = "HADOOP_HOME/bin"
</code>```

Hadoop will work on windows if Hadoop-src is built using maven in
  your windows machine. Building the Hadoop-src(distribution) will
  create a Hadoop binary distribution, which will work as windows native
  version.

But if you don't want to do that, then download pre-builted winutils of Hadoop distribution.
Here is a GitHub link, which has winutils of some versions of Hadoop.

if the version you are using is not in the list, the follow the
  conventional method for setting up Hadoop on windows - link

If you found your version, then copy paste all content of folder into path: /bin/

Set all the .xml configuration files - Link & set JAVA_HOME path in hadoop-env.cmd file

From cmd go to:

```<code><HADOOP_HOME>/bin/> hdfs namenode -format
<HADOOP_HOME>/sbin> start-all.cmd
</code>```

Hope this helps.

Title: Running Apache Hadoop 2.1.0 on Windows

Body:
I am new to Hadoop and have run into problems trying to run it on my Windows 7 machine. Particularly I am interested in running Hadoop 2.1.0 as its release notes mention that running on Windows is supported. I know that I can try to run 1.x versions on Windows with Cygwin or even use prepared VM by for example Cloudera, but these options are in some reasons less convenient for me.

Having examined a tarball from http://apache-mirror.rbc.ru/pub/apache/hadoop/common/hadoop-2.1.0-beta/ I found that there really are some *.cmd scripts that can be run without Cygwin. Everything worked fine when I formated HDFS partition but when I tried to run hdfs namenode daemon I faced two errors: first, non fatal, was that winutils.exe could not be found (it really wasn't present in the tarball downloaded). I found the sources of this component in the Apache Hadoop sources tree and compiled it with Microsoft SDK and MSbuild. Thanks to detailed error message it was clear where to put the executable to satisfy Hadoop. But the second error which is fatal doesn't contain enough information for me to solve:

13/09/05 10:20:09 FATAL namenode.NameNode: Exception in namenode join
java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:423)
    at org.apache.hadoop.fs.FileUtil.canWrite(FileUtil.java:952)
    at org.apache.hadoop.hdfs.server.common.Storage$StorageDirectory.analyzeStorage(Storage.java:451)
    at org.apache.hadoop.hdfs.server.namenode.FSImage.recoverStorageDirs(FSImage.java:282)
    at org.apache.hadoop.hdfs.server.namenode.FSImage.recoverTransitionRead(FSImage.java:200)
...
13/09/05 10:20:09 INFO util.ExitUtil: Exiting with status 1

Looks like something else should be compiled. I'm going to try to build Hadoop from the source with Maven but isn't there a simpler way? Isn't there some option-I-know-not-of that can disable native code and make that tarball usable on Windows?

Thank you.

UPDATED. Yes, indeed. "Homebrew" package contained some extra files, most importantly winutils.exe and hadoop.dll. With this files namenode and datanode started successfully. I think the question can be closed. I didn't delete it in case someone face the same difficulty.

UPDATED 2. To build the "homebrew" package I did the following:

Got sources, and unpacked them.

Read carefully BUILDING.txt.

Installed dependencies:

3a) Windows SDK 7.1

3b) Maven (I used 3.0.5)
3c) JDK (I used 1.7.25)

3d) ProtocolBuffer (I used 2.5.0 - http://protobuf.googlecode.com/files/protoc-2.5.0-win32.zip). It is enough just to put compiler (protoc.exe) into some of the PATH folders.

3e) A set of UNIX command line tools (I installed Cygwin)

Started command line of Windows SDK. Start | All programs | Microsoft Windows SDK v7.1 | ... Command Prompt (I modified this shortcut, adding option /release in the command line to build release versions of native code). All the next steps are made from inside SDK command line window)

Set up the environment:

set JAVA_HOME={path_to_JDK_root}

It seems that JAVA_HOME MUST NOT contain space!

set PATH={path_to_maven_bin};%PATH%
set Platform=x64
set PATH={path_to_cygwin_bin};%PATH%
set PATH={path_to_protoc.exe};%PATH%

Changed dir to sources root folder (BUILDING.txt warns that there are some limitations on the path length so sources root should have short name - I used D:\hds)

Ran building process:

mvn package -Pdist -DskipTests

You can try without 'skipTests' but on my machine some tests failed and building was terminated. It may be connected to sybolic link issues mentioned in BUILDING .txt.
8. Picked the result in hadoop-dist\target\hadoop-2.1.0-beta (windows executables and dlls are in 'bin' folder)

Body:
Download & Install Java in c:/java/

make sure the path is this way, if java is installed in 'program
  files', then hadoop-env.cmd will not recognize java path

Download Hadoop binary distribution.

I am using binary distribution Hadoop-2.8.1. Also I would recommend to keep extraction path as short as possible

Set Environment Variables:

JAVA_HOME = "c:/Java"
HADOOP_HOME="<your hadoop home>"
Path= "JAVA_HOME/bin"
Path = "HADOOP_HOME/bin"

Hadoop will work on windows if Hadoop-src is built using maven in
  your windows machine. Building the Hadoop-src(distribution) will
  create a Hadoop binary distribution, which will work as windows native
  version.

But if you don't want to do that, then download pre-builted winutils of Hadoop distribution.
Here is a GitHub link, which has winutils of some versions of Hadoop.

if the version you are using is not in the list, the follow the
  conventional method for setting up Hadoop on windows - link

If you found your version, then copy paste all content of folder into path: /bin/

Set all the .xml configuration files - Link & set JAVA_HOME path in hadoop-env.cmd file

From cmd go to:

<HADOOP_HOME>/bin/> hdfs namenode -format
<HADOOP_HOME>/sbin> start-all.cmd

Hope this helps.