问:
Google Maps API (Directions) throws 403 error in Payara, not in WebLogic
I've been given the task to move our application from WebLogic 12.1.3 to Payara 4.1 and have run into an issue that I feel I'm more or less at the end of the line of troubleshooting.
We have an EJB (a Stateless bean) that has two methods, one that makes a call to the Google Maps Directions API and one that makes a call to the Google Maps Geocoding API, both using the same credentials and Googles client libraries for Java. Both methods work perfectly running on WebLogic, but after switching to Payara the one using the Directions API gives me an error. Here's the relevant part of the stacktrace:

```<code>java.io.IOException: Server Error: 403 Forbidden
    at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:258)
    at com.google.maps.internal.OkHttpPendingResult.await(OkHttpPendingResult.java:167)
    at com.google.maps.PendingResultBase.await(PendingResultBase.java:56)
    at com.somecompany.integration.GoogleDirectionsIntegration.getDirections(GoogleDirectionsIntegration.java:XXX)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
</code>```

So the geocoding-method still works on both platforms, but when attempting the call to the Directions API I get a 403 back from Google indicating that my credentials are messed up, but the very same credentials work for the geocoding call. The code hasn't been changed in any way switching from one platform to the other.

What's even more confusing is that if I grab the actual URL of the call to Google from the logs and try it in my browser, i.e. paste "https://maps.googleapis.com/maps/api/directions/json?client=gme-company&mode=driving&arrival_time=1435825037&o
rigin=Somewhere&destination=Somewhere+else&alternat
ives=false&signature=nfre3XYZ2kmuDX8Qibce87ZFKQQ=" into Chrome, it works. I get a proper answer from Google. (btw, those aren't the actual credentials or origin and destination I'm using, they've been "anonymized" :-)). I've also checked that this URL (which is built by the client library) is the same running on both platforms as well as used the URL Signing Debugger on Google's developer pages, but to no avail. There should be nothing wrong with my credentials.

I'm really at the end of the line here, having spent days troubleshooting and searching online without finding a solution.

Not that it matters that much but I didn't write this code myself, and the person who did of course doesn't work here anymore :-P

Anyway, here's the code (somewhat anonymized):

```<code>@Stateless
public class GoogleDirectionsIntegration {

private static final Logger LOGGER = Logger.getLogger(GoogleDirectionsIntegration.class.getName());

private GeoApiContext context = null;

/**
 * Initializer
 */
@PostConstruct
public void init() {
    LOGGER.log(Level.INFO, "initiating {0}", this.getClass().getSimpleName());
    this.context = new GeoApiContext().setEnterpriseCredentials("gme-company", "companyGoogleCryptographicSecret");
    this.context.setReadTimeout(1, TimeUnit.SECONDS)
            .setRetryTimeout(1, TimeUnit.SECONDS)
            .setConnectTimeout(1, TimeUnit.SECONDS)
            .setWriteTimeout(1, TimeUnit.SECONDS);
    OkHttpRequestHandler okHttpRequestHandler = null;
    OkHttpClient okHttpClient = null;

    try {
        Field requestField = this.context.getClass().getDeclaredField("requestHandler");
        requestField.setAccessible(true);
        okHttpRequestHandler = (OkHttpRequestHandler) requestField.get(this.context);
        Field f = okHttpRequestHandler.getClass().getDeclaredField("client");
        f.setAccessible(true);
        okHttpClient = (OkHttpClient) f.get(okHttpRequestHandler);
    } catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException e) {
        throw new IllegalStateException("Failed to create SSL context", e);
    }

    SSLContext sslCtx = this.getSslContext();

    if (sslCtx != null && okHttpClient != null) {
        SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
    }
}

private SSLContext getSslContext() {
    TrustManager[] tm = new TrustManager[] {
            new CustomTrustManager()
    };

    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, tm, new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException ex) {
        throw new IllegalStateException("Failed to create SSL context", ex);
    }
    return sslContext;
}

public DirectionsRoute getDirections(final String origin, final String destination, final DistanceUnit distanceUnit,
        @Nullable TransportMode mode, @NotNull Instant arrivalTime) throws NotFoundException {
    TransportMode actualMode = mode == null ? TransportMode.CAR : mode;
    DirectionsRoute[] directionsRoutes;

    DirectionsApiRequest directionsApiRequest = DirectionsApi.getDirections(this.context, origin, destination);
    directionsApiRequest.arrivalTime(new Instant(arrivalTime));
    directionsApiRequest.alternatives(false);
    directionsApiRequest.mode(this.toTravelMode(actualMode));

    try {
        DirectionsResult res = directionsApiRequest.await(); // THIS IS WHERE IT BREAKS!
        directionsRoutes = res.routes;
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, e.getMessage(), e);
        throw new NotFoundException(e.getMessage());
    }

    if (directionsRoutes.length != 1) {
        throw new NotFoundException("Failed to fetch valid directions");
    }

    return directionsRoutes[0];
}

public void getAddress(LatLng startLocation, Location location, boolean cacheOverride) throws Exception {
    com.google.maps.model.LatLng gLatLng = new com.google.maps.model.LatLng(startLocation.getLat(), startLocation.getLng());
    GeocodingApiRequest geocodingApiRequest = GeocodingApi.reverseGeocode(this.context, gLatLng);
    GeocodingResult[] geocodingResults;
    geocodingResults = geocodingApiRequest.await();
    if (0 < geocodingResults.length) {
        //.. Code that does stuff with the result..
    } else {
        LOGGER.log(Level.WARNING, "Received empty results from Google reverse geocode for [{0}].", startLocation);
    }
}

}
</code>```

答: So I solved it. The problem wasn't in the code but in the dependencies, or rather in a dependency to one of the dependencies - OkHttp. I simply changed the version and it works now.</p>

Body:
I've been given the task to move our application from WebLogic 12.1.3 to Payara 4.1 and have run into an issue that I feel I'm more or less at the end of the line of troubleshooting.
We have an EJB (a Stateless bean) that has two methods, one that makes a call to the Google Maps Directions API and one that makes a call to the Google Maps Geocoding API, both using the same credentials and Googles client libraries for Java. Both methods work perfectly running on WebLogic, but after switching to Payara the one using the Directions API gives me an error. Here's the relevant part of the stacktrace:

java.io.IOException: Server Error: 403 Forbidden
    at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:258)
    at com.google.maps.internal.OkHttpPendingResult.await(OkHttpPendingResult.java:167)
    at com.google.maps.PendingResultBase.await(PendingResultBase.java:56)
    at com.somecompany.integration.GoogleDirectionsIntegration.getDirections(GoogleDirectionsIntegration.java:XXX)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)

So the geocoding-method still works on both platforms, but when attempting the call to the Directions API I get a 403 back from Google indicating that my credentials are messed up, but the very same credentials work for the geocoding call. The code hasn't been changed in any way switching from one platform to the other.

What's even more confusing is that if I grab the actual URL of the call to Google from the logs and try it in my browser, i.e. paste "https://maps.googleapis.com/maps/api/directions/json?client=gme-company&mode=driving&arrival_time=1435825037&o
rigin=Somewhere&destination=Somewhere+else&alternat
ives=false&signature=nfre3XYZ2kmuDX8Qibce87ZFKQQ=" into Chrome, it works. I get a proper answer from Google. (btw, those aren't the actual credentials or origin and destination I'm using, they've been "anonymized" :-)). I've also checked that this URL (which is built by the client library) is the same running on both platforms as well as used the URL Signing Debugger on Google's developer pages, but to no avail. There should be nothing wrong with my credentials.

I'm really at the end of the line here, having spent days troubleshooting and searching online without finding a solution.

Not that it matters that much but I didn't write this code myself, and the person who did of course doesn't work here anymore :-P

Anyway, here's the code (somewhat anonymized):

@Stateless
public class GoogleDirectionsIntegration {

private static final Logger LOGGER = Logger.getLogger(GoogleDirectionsIntegration.class.getName());

private GeoApiContext context = null;

/**
 * Initializer
 */
@PostConstruct
public void init() {
    LOGGER.log(Level.INFO, "initiating {0}", this.getClass().getSimpleName());
    this.context = new GeoApiContext().setEnterpriseCredentials("gme-company", "companyGoogleCryptographicSecret");
    this.context.setReadTimeout(1, TimeUnit.SECONDS)
            .setRetryTimeout(1, TimeUnit.SECONDS)
            .setConnectTimeout(1, TimeUnit.SECONDS)
            .setWriteTimeout(1, TimeUnit.SECONDS);
    OkHttpRequestHandler okHttpRequestHandler = null;
    OkHttpClient okHttpClient = null;

    try {
        Field requestField = this.context.getClass().getDeclaredField("requestHandler");
        requestField.setAccessible(true);
        okHttpRequestHandler = (OkHttpRequestHandler) requestField.get(this.context);
        Field f = okHttpRequestHandler.getClass().getDeclaredField("client");
        f.setAccessible(true);
        okHttpClient = (OkHttpClient) f.get(okHttpRequestHandler);
    } catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException e) {
        throw new IllegalStateException("Failed to create SSL context", e);
    }

    SSLContext sslCtx = this.getSslContext();

    if (sslCtx != null && okHttpClient != null) {
        SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
    }
}

private SSLContext getSslContext() {
    TrustManager[] tm = new TrustManager[] {
            new CustomTrustManager()
    };

    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, tm, new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException ex) {
        throw new IllegalStateException("Failed to create SSL context", ex);
    }
    return sslContext;
}

public DirectionsRoute getDirections(final String origin, final String destination, final DistanceUnit distanceUnit,
        @Nullable TransportMode mode, @NotNull Instant arrivalTime) throws NotFoundException {
    TransportMode actualMode = mode == null ? TransportMode.CAR : mode;
    DirectionsRoute[] directionsRoutes;

    DirectionsApiRequest directionsApiRequest = DirectionsApi.getDirections(this.context, origin, destination);
    directionsApiRequest.arrivalTime(new Instant(arrivalTime));
    directionsApiRequest.alternatives(false);
    directionsApiRequest.mode(this.toTravelMode(actualMode));

    try {
        DirectionsResult res = directionsApiRequest.await(); // THIS IS WHERE IT BREAKS!
        directionsRoutes = res.routes;
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, e.getMessage(), e);
        throw new NotFoundException(e.getMessage());
    }

    if (directionsRoutes.length != 1) {
        throw new NotFoundException("Failed to fetch valid directions");
    }

    return directionsRoutes[0];
}

public void getAddress(LatLng startLocation, Location location, boolean cacheOverride) throws Exception {
    com.google.maps.model.LatLng gLatLng = new com.google.maps.model.LatLng(startLocation.getLat(), startLocation.getLng());
    GeocodingApiRequest geocodingApiRequest = GeocodingApi.reverseGeocode(this.context, gLatLng);
    GeocodingResult[] geocodingResults;
    geocodingResults = geocodingApiRequest.await();
    if (0 < geocodingResults.length) {
        //.. Code that does stuff with the result..
    } else {
        LOGGER.log(Level.WARNING, "Received empty results from Google reverse geocode for [{0}].", startLocation);
    }
}

}


来源: stackexchange

问:
Postgres sql count number of days active in month
I have a table like so:

```<code>meterId | startDate  | endDate  |location
meter01 | 2017-05-01 |2017-05-16| locA
meter02 | 2017-05-01 |9999-12-31| locB
meter03 | 2017-01-01 |9999-12-31| locA
meter04 | 2017-01-01 |9999-12-31| locB
</code>```

I need to return a count for how many days a location had activity for in a given month.  The query would need to return this:
(Given there is 31 days in May)

```<code>location |  Month  |  days  |
locA     |  May-17 |    47  |
locB     |  May-17 |    62  |
</code>```

what i have tried so far is something like this: (note i am joining to another table which isn't optimum and shown here)

```<code>SELECT count(distinct(read_date)) AS days, location from t where EXTRACT(MONTH FROM read_date) = 5 and EXTRACT(YEAR FROM read_date) = 2017
</code>```

It's somewhat close.  It has duplicates of location however.  I also need the date in the format as above.

New edit for @StanislavL

```<code>    select SUM(sub.intervalEnd - sub.intervalStart +1) as days,
     location
from (select
    location,
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart,
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd
from my_table

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01')
   OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31'))sub
  group by location
</code>```

答:
For anyone interested, this is the final working example

```<code>select location,  subItem1, item2, SUM(sub.intervalEnd - sub.intervalStart +1) as days

from (select
    location, item1,item2,
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart,
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd,
    case when item1 =  'APPLE' then item1 else 'ORANGE' end as subItem1
from myTable

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01')
   OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31')
group by item1, item2, location, effective_start_date, effective_end_date
   )sub
  group by location, subItem1, item2
</code>```

There are some extra fields and a 'case' query in there (item1, item2) for my own needs which may serve to help.

ContentLicense: CC BY-SA 3.0

Body:
I have a table like so:

meterId | startDate  | endDate  |location
meter01 | 2017-05-01 |2017-05-16| locA
meter02 | 2017-05-01 |9999-12-31| locB
meter03 | 2017-01-01 |9999-12-31| locA
meter04 | 2017-01-01 |9999-12-31| locB

I need to return a count for how many days a location had activity for in a given month.  The query would need to return this:
(Given there is 31 days in May)

location |  Month  |  days  |
locA     |  May-17 |    47  |
locB     |  May-17 |    62  |

what i have tried so far is something like this: (note i am joining to another table which isn't optimum and shown here)

SELECT count(distinct(read_date)) AS days, location from t where EXTRACT(MONTH FROM read_date) = 5 and EXTRACT(YEAR FROM read_date) = 2017

It's somewhat close.  It has duplicates of location however.  I also need the date in the format as above.

New edit for @StanislavL

    select SUM(sub.intervalEnd - sub.intervalStart +1) as days,
     location
from (select
    location,
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart,
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd
from my_table

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01')
   OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31'))sub
  group by location

Body:
For anyone interested, this is the final working example

select location,  subItem1, item2, SUM(sub.intervalEnd - sub.intervalStart +1) as days

from (select
    location, item1,item2,
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart,
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd,
    case when item1 =  'APPLE' then item1 else 'ORANGE' end as subItem1
from myTable

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01')
   OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31')
group by item1, item2, location, effective_start_date, effective_end_date
   )sub
  group by location, subItem1, item2

There are some extra fields and a 'case' query in there (item1, item2) for my own needs which may serve to help.


问:
Using ES6 import and export default inside webpack.config
I would like to be able to use es6 imports and export default inside my webpack.config. If I run my webpack like this.

webpack.config.js

```<code>"webpack": "cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js"
</code>```

I get an error SyntaxError: Unexpected token import whick is expected. Then I found on other questions solution that seemed to work for a lot of people. Renaming file to webpack.config.babel.js and including babel-register. I tried that
webpack.config.babel.js

```<code>"webpack": "cross-env NODE_ENV=development node -r babel-register node_modules/.bin/webpack-dev-server --config=webpack.config.babel.js"
</code>```

but now I get this error

```<code>basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^
SyntaxError: missing ) after argument list
</code>```

I tried a lot more combinations with babel-node and babel-register but nothing seems to work. I am on windows 10. How do I do this?

答:
Try running webpack directly, without babel-register:

```<code>"webpack": "cross-env NODE_ENV=development node_modules/.bin/webpack-dev-server --config=webpack.config.babel.js"
</code>```

Also, make sure that in your .babelrc file you have the babel-plugin-transform-es2015-modules-commonjs plugin, or if you're using the es2015 preset, the modules option is set to true. If you don't want Babel to transpile modules in other situations (for example when making a production bundle), you can tell babel-loader not to use .babelrc and specify presets manually:

```<code>{
  test: /\.js$/,
  exclude: /node_modules/,
  loader: 'babel-loader',
  options: {
    babelrc: false,
    presets: [
      ['latest', {
        modules: false,
      }],
    ],
  },
},
</code>```

Body:
I would like to be able to use es6 imports and export default inside my webpack.config. If I run my webpack like this.

webpack.config.js

"webpack": "cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js"

I get an error SyntaxError: Unexpected token import whick is expected. Then I found on other questions solution that seemed to work for a lot of people. Renaming file to webpack.config.babel.js and including babel-register. I tried that
webpack.config.babel.js

"webpack": "cross-env NODE_ENV=development node -r babel-register node_modules/.bin/webpack-dev-server --config=webpack.config.babel.js"

but now I get this error

basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^
SyntaxError: missing ) after argument list

I tried a lot more combinations with babel-node and babel-register but nothing seems to work. I am on windows 10. How do I do this?

Body:
Try running webpack directly, without babel-register:

"webpack": "cross-env NODE_ENV=development node_modules/.bin/webpack-dev-server --config=webpack.config.babel.js"

Also, make sure that in your .babelrc file you have the babel-plugin-transform-es2015-modules-commonjs plugin, or if you're using the es2015 preset, the modules option is set to true. If you don't want Babel to transpile modules in other situations (for example when making a production bundle), you can tell babel-loader not to use .babelrc and specify presets manually:

{
  test: /\.js$/,
  exclude: /node_modules/,
  loader: 'babel-loader',
  options: {
    babelrc: false,
    presets: [
      ['latest', {
        modules: false,
      }],
    ],
  },
},


问:
Verify logged in user against exchange distribution list or AD groups in c#
I am trying to verify whether the logged in user exists in a AD group or distribution list. I tried to use WindowsIdentity but that does not give me proper results. If I add a user to the DL and then check whether the user is in the DL, it gives me incorrect results.

I restarted my IIS and even cleared my browser cookies and cache, but no luck. Where does the IsInRole() function verifies for the user role. In AD or on local machine....? I tried to remove myself from local machine group too, but it still authorizes me for that group. Any help would be appreciated.

答: If you are using .NET 3.5, you can consider to use Principal.IsMemberOf() in  System.DirectoryServices.AccountManagement.  I tried it and it works with AD security group as well as DL.  More details about how to programming with groups can be found here</p>

ContentLicense: CC BY-SA 2.5


问:
REST API to consume form with values as json
Our REST APIs consumes Content-Type : application/x-www-form-urlencoded as input. The request contains form parameters with values as JSON. Eg.

```<code>URI :  /abc/id
    Request Body :
    param1 : {"name":"vineet", "age" : "9"}  --JSON
    param2 : {"city":"delhi","state":"delhi"}  --JSON
</code>```

But when the input is mapped to the request object the values are coming as

```<code>        param1 : {name : vineet, age : 9},
        param2 : {city : delhi,state : delhi}
</code>```

Qoutes are missing. so it comes as invalid JSON.

答:
This answer may help you to understand what you looking for.

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

Body:
Our REST APIs consumes Content-Type : application/x-www-form-urlencoded as input. The request contains form parameters with values as JSON. Eg.

URI :  /abc/id
    Request Body :
    param1 : {"name":"vineet", "age" : "9"}  --JSON
    param2 : {"city":"delhi","state":"delhi"}  --JSON

But when the input is mapped to the request object the values are coming as

        param1 : {name : vineet, age : 9},
        param2 : {city : delhi,state : delhi}

Qoutes are missing. so it comes as invalid JSON.


问:
Removing similar rows using GROUP BY / DISTINCT
I currently have a table of document paths next to an ID and other metadata, however the same file path is referenced multiple times with different IDs.

An example data set:

```<code>ID           FullPath
1            \\some\file\path.txt
2            \\some\file\path.txt
3            \\some\file\path.txt
4            \\another\file\path.txt
5            \\another\file\path.txt
</code>```

I want to return a distinct set of paths and do not need the other IDs. It is probably quite a simple GROUP BY aggregate function but I can't figure it out. Please help!

I think I want something along these lines, but to be selecting the ID from the subquery instead of the path as the path causes it to return all rows. But I cant do that and GROUP BY the FullPath!

```<code>select *
from Documents
where FullPath in (
    select min(FullPath)
    from Documents
    group by FullPath
)
</code>```

Results I am after:

```<code>ID           FullPath
1            \\some\file\path.txt
4            \\another\file\path.txt
</code>```

答:
Please use Like

EXEC('
DELETE Duplicate_Row  from (
SELECT  ROW_NUMBER() OVER (PARTITION BY id ORDER BY id) RN
from Documents

) AS Duplicate_Row  WHERE Duplicate_Row.RN > 1')

Body:
I currently have a table of document paths next to an ID and other metadata, however the same file path is referenced multiple times with different IDs.

An example data set:

ID           FullPath
1            \\some\file\path.txt
2            \\some\file\path.txt
3            \\some\file\path.txt
4            \\another\file\path.txt
5            \\another\file\path.txt

I want to return a distinct set of paths and do not need the other IDs. It is probably quite a simple GROUP BY aggregate function but I can't figure it out. Please help!

I think I want something along these lines, but to be selecting the ID from the subquery instead of the path as the path causes it to return all rows. But I cant do that and GROUP BY the FullPath!

select *
from Documents
where FullPath in (
    select min(FullPath)
    from Documents
    group by FullPath
)

Results I am after:

ID           FullPath
1            \\some\file\path.txt
4            \\another\file\path.txt


问:
Display a xib view into a UITableView Cell
I made a view in a xib file which is loaded in the main ViewController called "ExperienceScreen". Adding this xib view to the ExperienceScreen works perfectly. The problem is that I would like to add this xib view in a UITableViewCel. I am using the following code to do that :

```<code>   let experiences = service.getExperiences()

    // 3. Loop through the array of experiences
    for element in experiences {

        if let customView = Bundle.main.loadNibNamed("ExperienceDetail", owner: self, options: nil)?.first as? ExperienceDetail
        {
            customView.lblTitle.text = element.title
            customView.lblCompany.text = element.company
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
            cell.addSubview(customView)
            cell.bringSubview(toFront: customView)
        }
    }

    tableView.reloadData()
</code>```

When launching, the subview is not shown in the UITableViewCell. The customView View is filled correctly with the xib View. I checked this using a breakpoint.

Someone knows what I'am doing wrong?

Many thanks for helping !!

答:
If you want to display your xib file as UITableViewCell, then following scenario works
1. make sure your xib class is sub class of UITableViewCell.
2. register your xib

```<code>//class of xib file
class TableCell: UITableViewCell {
  static let identifier = "TableCell"
  static let nib = UINib(nibName: "TableCell", bundle: nil)
}

// In view controller
func setupTableView() {
 tableView.dataSource = self
 tableView.delefate = self
 tableView.register(TableCell.nib, forCellReuseIdentifier:
 TableCell.identifier)
}
</code>```

call setupTableView() in viewDidLoad()

Body:
I made a view in a xib file which is loaded in the main ViewController called "ExperienceScreen". Adding this xib view to the ExperienceScreen works perfectly. The problem is that I would like to add this xib view in a UITableViewCel. I am using the following code to do that :

   let experiences = service.getExperiences()

    // 3. Loop through the array of experiences
    for element in experiences {

        if let customView = Bundle.main.loadNibNamed("ExperienceDetail", owner: self, options: nil)?.first as? ExperienceDetail
        {
            customView.lblTitle.text = element.title
            customView.lblCompany.text = element.company
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
            cell.addSubview(customView)
            cell.bringSubview(toFront: customView)
        }
    }

    tableView.reloadData()

When launching, the subview is not shown in the UITableViewCell. The customView View is filled correctly with the xib View. I checked this using a breakpoint.

Someone knows what I'am doing wrong?

Many thanks for helping !!

Body:
If you want to display your xib file as UITableViewCell, then following scenario works
1. make sure your xib class is sub class of UITableViewCell.
2. register your xib

//class of xib file
class TableCell: UITableViewCell {
  static let identifier = "TableCell"
  static let nib = UINib(nibName: "TableCell", bundle: nil)
}

// In view controller
func setupTableView() {
 tableView.dataSource = self
 tableView.delefate = self
 tableView.register(TableCell.nib, forCellReuseIdentifier:
 TableCell.identifier)
}

call setupTableView() in viewDidLoad()


问:
Nodejs cannot find module sparkles
I already installed gulp -g, and when I use "gulp tsc" I receive this message from node. Anyone can help</p>

```<code>Error: Cannot find module 'sparkles'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\mateus.leal\AppData\Roaming\npm\node_modules\gulp-cli\node_modules\glogg\index
.js:5:16)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
</code>```

答:
it says it is missing sparkles package , you should install it by running </p>

```<code>npm install sparkles
</code>```

Title: Nodejs cannot find module sparkles

Body:
I already installed gulp -g, and when I use "gulp tsc" I receive this message from node. Anyone can help

Error: Cannot find module 'sparkles'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\mateus.leal\AppData\Roaming\npm\node_modules\gulp-cli\node_modules\glogg\index
.js:5:16)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)

Body:
it says it is missing sparkles package , you should install it by running

npm install sparkles


问:
How can I check if an object is an array?
I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item so I can loop over it without fear of an error.

So how do I check if the variable is an array?

答:
You can find with push like below:

function isArray(obj){
   return (typeof obj.push === 'function') ? true : false;
}

var array = new Array();

or

var array = ['a', 'b', 'c'];
console.log(isArray(array));```

ContentLicense: CC BY-SA 4.0


问:
Updating datatype property value base on SWRL rules
Hi
i have made an ontology in protege 4.3 for users , suppose 1 of my ontology subclass of class user are:

 1-"Interest" , and class "interest" have subclasses: "onlineGaming","onlineMovie","onlineshoping",... and every subclass has individual: everyday,onceAweek,onceAmonth)

and i have 3 datatype property for every user: (internetspeed,internetTraffic,Price)

data gathered based on a questionnaire

i just need to infer from this ontology how important this 3 datatype property factors is for internet users

i need to make some SWRL rules in protege to Infer user interest weight , for example if a user do onlineMovie everyday add a +3 to internetTraffic dataproperty.

```<code>user(?u) ^ hasOnlineMovieInterest(?u , everyday)-> add +3 to user(?u,InternetTraffic)
user(?u) ^ hasOnlineGamingInterest(?u , OnceAweek) and hasOnlineMovieInterest(?u , everyday)-> add +2 to user(?u,internetSpeed)
</code>```

how should i write this properly in SWRL rules?

and my second question is how can i have the value of this 3 datatype property for every user in sparql and save the result?

Thanks for your help

答:
First of all; it is not clear what you are doing / which technology using, etc., please consider clarifying your question. Moreover, the conceptual made you developed doesn't seem sound. Are you sure this is the best way to represent the information you want? For example, why would a UserInterest be a subClassOf User? I think you mean that UserInterest and UserInterestRate are ranges for an object property that connect User to them, i.e., hasInterest rdfs:domain User and hasInterest rdfs:range UserInterest.

Coming to your questions, do you use Protege? If you use it you can implement these SWRL rules using the SWRL tab in Protege.

After you have implemented this correctly, you can simply use some SPARQL query similar to:

```<code>select ?user ?r1 ?r2 ?r3 Where {
    ?user rdf:type yourNamespacePrefix:User.
    ?user yourNamespacePrefix:rate1 ?r1.
    ?user yourNamespacePrefix:rate2 ?r2.
    ?user yourNamespacePrefix:rate3 ?r3.
}
</code>```

Body:
Hi
i have made an ontology in protege 4.3 for users , suppose 1 of my ontology subclass of class user are:

 1-"Interest" , and class "interest" have subclasses: "onlineGaming","onlineMovie","onlineshoping",... and every subclass has individual: everyday,onceAweek,onceAmonth)

and i have 3 datatype property for every user: (internetspeed,internetTraffic,Price)

data gathered based on a questionnaire

i just need to infer from this ontology how important this 3 datatype property factors is for internet users

i need to make some SWRL rules in protege to Infer user interest weight , for example if a user do onlineMovie everyday add a +3 to internetTraffic dataproperty.

user(?u) ^ hasOnlineMovieInterest(?u , everyday)-> add +3 to user(?u,InternetTraffic)
user(?u) ^ hasOnlineGamingInterest(?u , OnceAweek) and hasOnlineMovieInterest(?u , everyday)-> add +2 to user(?u,internetSpeed)

how should i write this properly in SWRL rules?

and my second question is how can i have the value of this 3 datatype property for every user in sparql and save the result?

Thanks for your help

Body:
First of all; it is not clear what you are doing / which technology using, etc., please consider clarifying your question. Moreover, the conceptual made you developed doesn't seem sound. Are you sure this is the best way to represent the information you want? For example, why would a UserInterest be a subClassOf User? I think you mean that UserInterest and UserInterestRate are ranges for an object property that connect User to them, i.e., hasInterest rdfs:domain User and hasInterest rdfs:range UserInterest.

Coming to your questions, do you use Protege? If you use it you can implement these SWRL rules using the SWRL tab in Protege.

After you have implemented this correctly, you can simply use some SPARQL query similar to:

select ?user ?r1 ?r2 ?r3 Where {
    ?user rdf:type yourNamespacePrefix:User.
    ?user yourNamespacePrefix:rate1 ?r1.
    ?user yourNamespacePrefix:rate2 ?r2.
    ?user yourNamespacePrefix:rate3 ?r3.
}


问:
Show progress dialog while adding views dynamically to scrollview in android

In the start of an activity in OnCreate method, I'm trying to add some text views dynamically to a scrollview of the layout file. But during the time of this operation the screen remains blank. Is it possible to show a progress dialog when adding views dynamically to a scrollview?

答: You should use a AsyncTask for that. Please post some code you're having in your onCreate method at the moment.


问:
How to add click listener in List View, If ListView have already button in xml?
How to add click listener in List View, If ListView have already button in xml? I want to click on button for open New Activity.

Here is my code.
WashDetail.xml

```<code>      <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000"
                android:text="Malaber Hill" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="16dp"
                android:layout_marginEnd="20dp"
                android:text="Get Details"
                android:id="@+id/gardetails"
                android:textColor="#FFFFFF"
                android:textSize="20dp"
                android:textStyle="normal"

                />
 </LinearLayout>
</code>```

activity_wash_detail

```<code>    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
       <ListView
         android:layout_width="fill_parent"
         android:id="@+id/ls"
         android:layout_below="@+id/headerlay"
         android:focusable="true"
         android:clickable="true"
         android:duplicateParentState="true"
         android:focusableInTouchMode="true"
         android:layout_height="fill_parent">
        </ListView>
 </LinearLayout>
</code>```

WashDetailActivity.java

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wash_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView) findViewById(ls);
    GetDetails=(Button)findViewById(R.id.gardetails);
    Models = new ArrayList<>();
    Models.add(new WashDetailing(R.drawable.spl, "PP AUTOMATIVES", R.drawable.mahindra, "Authorized"));
    adapter = new WashDetailingAdapter(Models, getApplicationContext());

    listView.setAdapter(adapter);

    listView.setClickable(false);

     gardetails.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v)
         {
            Intent intent= new         Intent(getApplicationContext(),GarageDetailActivity.class);
            startActivity(intent);

        }
    });
}
</code>```

答:
Use Custom Adapter Like this

```<code>public class Custom_Adapter_Products extends BaseAdapter {
    Context context;
    Cursor mCursor;
    static int[] intArr;
    DatabaseAdapter db;
    public ImageLoader imageLoader;

    public Custom_Adapter_Products(Context context, Cursor mCursor){
        this.context = context;
        this.mCursor = mCursor;
        this.intArr = new int[this.mCursor.getCount()];
        imageLoader=new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return mCursor.getCount();
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        try{
                ViewHolder holder;
                this.mCursor.moveToPosition(position);
                LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                if (convertView == null)
                {
                    convertView = vi.inflate(R.layout.lv_row_for_products, null);
                    holder = createViewHolder(convertView);
                    convertView.setTag(holder);
                    holder.btnMinus.setTag(holder);
                    holder.btnAdd.setTag(holder);
                }
                else
                {
                    holder = (ViewHolder) convertView.getTag();
                }

                holder.btnMinus.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try{
                        ViewHolder holder = (ViewHolder) v.getTag();
                        // Do whatever you want
                    }catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }
            });

                holder.btnAdd.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try{
                        ViewHolder holder = (ViewHolder) v.getTag();

                    }catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }}
            });

            String strProductName = this.mCursor.getString(this.mCursor.getColumnIndex(DatabaseAdapter.PRODUCT_NAME));
            String strPrice = this.mCursor.getString(this.mCursor.getColumnIndex(DatabaseAdapter.PRICE));
            String strMOQ = this.mCursor.getString(this.mCursor.getColumnIndex(DatabaseAdapter.MOQ));
            String strProductId = this.mCursor.getString(this.mCursor.getColumnIndex(DatabaseAdapter.PRODUCT_ID));
            String strMrp = this.mCursor.getString(this.mCursor.getColumnIndex(DatabaseAdapter.MRP));
            holder.tvProductName.setText(strProductName);
            holder.tvPrice.setText(context.getString(R.string.Rupee)+" "+strPrice);

        }catch (Exception e){
            // TODO: handle exception
            e.printStackTrace();
        }
        return convertView;
    }

    private static class ViewHolder
    {
        public TextView tvProductName;
        public TextView tvPrice;
        public TextView tvMRP;
        public TextView tvMOQ;
        public TextView tvPercent;
        public TextView tvQuantity;
        public ImageView imgProduct;
        public ProgressBar pBar;
        public Button btnMinus;
        public Button btnAdd;
    }

    private ViewHolder createViewHolder(View v) {
        ViewHolder holder = new ViewHolder();
        try{
            holder.tvProductName = (TextView) v.findViewById(R.id.tvProductName);
            holder.tvPrice = (TextView) v.findViewById(R.id.tvPrice);
            holder.tvMRP = (TextView) v.findViewById(R.id.tvMRP);
            holder.tvMOQ = (TextView) v.findViewById(R.id.tvMOQ);
            holder.tvQuantity = (TextView) v.findViewById(R.id.tvQuantity);
            holder.imgProduct = (ImageView) v.findViewById(R.id.imgProduct);
            holder.pBar = (ProgressBar) v.findViewById(R.id.img_pb);
            holder.btnMinus = (Button) v.findViewById(R.id.btnMinus);
            holder.btnAdd = (Button) v.findViewById(R.id.btnAdd);
            holder.tvPercent = (TextView) v.findViewById(R.id.tvPercent);
        }catch (Exception e) {
        // TODO: handle exception
            e.printStackTrace();
    }
        return holder;
    }
}
</code>```

Body:
How to add click listener in List View, If ListView have already button in xml? I want to click on button for open New Activity.

Here is my code.
WashDetail.xml

      <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000"
                android:text="Malaber Hill" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="16dp"
                android:layout_marginEnd="20dp"
                android:text="Get Details"
                android:id="@+id/gardetails"
                android:textColor="#FFFFFF"
                android:textSize="20dp"
                android:textStyle="normal"

                />
 </LinearLayout>

activity_wash_detail

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
       <ListView
         android:layout_width="fill_parent"
         android:id="@+id/ls"
         android:layout_below="@+id/headerlay"
         android:focusable="true"
         android:clickable="true"
         android:duplicateParentState="true"
         android:focusableInTouchMode="true"
         android:layout_height="fill_parent">
        </ListView>
 </LinearLayout>

WashDetailActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wash_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView) findViewById(ls);
    GetDetails=(Button)findViewById(R.id.gardetails);
    Models = new ArrayList<>();
    Models.add(new WashDetailing(R.drawable.spl, "PP AUTOMATIVES", R.drawable.mahindra, "Authorized"));
    adapter = new WashDetailingAdapter(Models, getApplicationContext());

    listView.setAdapter(adapter);

    listView.setClickable(false);

     gardetails.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v)
         {
            Intent intent= new         Intent(getApplicationContext(),GarageDetailActivity.class);
            startActivity(intent);

        }
    });
}

Body:
Use Custom Adapter Like this

public class Custom_Adapter_Products extends BaseAdapter {
    Context context;
    Cursor mCursor;
    static int[] intArr;
    DatabaseAdapter db;
    public ImageLoader imageLoader;

    public Custom_Adapter_Products(Context context, Cursor mCursor){
        this.context = context;
        this.mCursor = mCursor;
        this.intArr = new int[this.mCursor.getCount()];
        imageLoader=new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return mCursor.getCount();
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        try{
                ViewHolder holder;
                this.mCursor.moveToPosition(position);
                LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                if (convertView == null)
                {
                    convertView = vi.inflate(R.layout.lv_row_for_products, null);
                    holder = createViewHolder(convertView);
                    convertView.setTag(holder);
                    holder.btnMinus.setTag(holder);
                    holder.btnAdd.setTag(holder);
                }
                else
                {
                    holder = (ViewHolder) convertView.getTag();
                }

                holder.btnMinus.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try{
                        ViewHolder holder = (ViewHolder) v.getTag();
                        // Do whatever you want
                    }catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }
            });

                holder.btnAdd.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try{
                        ViewHolder holder = (ViewHolder) v.getTag();

                    }catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }}
            });

            String strProductName = this.mCursor.getString(this.mCursor.getColumnIndex(DatabaseAdapter.PRODUCT_NAME));
            String strPrice = this.mCursor.getString(this.mCursor.getColumnIndex(DatabaseAdapter.PRICE));
            String strMOQ = this.mCursor.getString(this.mCursor.getColumnIndex(DatabaseAdapter.MOQ));
            String strProductId = this.mCursor.getString(this.mCursor.getColumnIndex(DatabaseAdapter.PRODUCT_ID));
            String strMrp = this.mCursor.getString(this.mCursor.getColumnIndex(DatabaseAdapter.MRP));
            holder.tvProductName.setText(strProductName);
            holder.tvPrice.setText(context.getString(R.string.Rupee)+" "+strPrice);

        }catch (Exception e){
            // TODO: handle exception
            e.printStackTrace();
        }
        return convertView;
    }

    private static class ViewHolder
    {
        public TextView tvProductName;
        public TextView tvPrice;
        public TextView tvMRP;
        public TextView tvMOQ;
        public TextView tvPercent;
        public TextView tvQuantity;
        public ImageView imgProduct;
        public ProgressBar pBar;
        public Button btnMinus;
        public Button btnAdd;
    }

    private ViewHolder createViewHolder(View v) {
        ViewHolder holder = new ViewHolder();
        try{
            holder.tvProductName = (TextView) v.findViewById(R.id.tvProductName);
            holder.tvPrice = (TextView) v.findViewById(R.id.tvPrice);
            holder.tvMRP = (TextView) v.findViewById(R.id.tvMRP);
            holder.tvMOQ = (TextView) v.findViewById(R.id.tvMOQ);
            holder.tvQuantity = (TextView) v.findViewById(R.id.tvQuantity);
            holder.imgProduct = (ImageView) v.findViewById(R.id.imgProduct);
            holder.pBar = (ProgressBar) v.findViewById(R.id.img_pb);
            holder.btnMinus = (Button) v.findViewById(R.id.btnMinus);
            holder.btnAdd = (Button) v.findViewById(R.id.btnAdd);
            holder.tvPercent = (TextView) v.findViewById(R.id.tvPercent);
        }catch (Exception e) {
        // TODO: handle exception
            e.printStackTrace();
    }
        return holder;
    }
}


问:
Can't retrive the good information from JSON on C#
I'm trying to get information from the Google API (YT). I need to take the videoId from the API of Google.

So I download the JSON page and trying to deserialize my result but he doesn't works.

This is the JSON result

```<code>    {
   "kind": "youtube#playlistItemListResponse",
   "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/E6IhaTG5XEbqo_uSYhCcIvQhtwY\"",
   "nextPageToken": "CDIQAA",
   "pageInfo": {
   "totalResults": 180,
   "resultsPerPage": 50
   },
  "items": [
  {
   "kind": "youtube#playlistItem",
   "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/0cAZGJiF62yaNO7GwJlJBsc7DqY\"",
   "id": "UExNQzlLTmtJbmNLdFB6Z1ktNXJtaHZqN2ZheDhmZHhvai41RDlFNzlCQjE5NzcyQTYx",
   "snippet": {
    "publishedAt": "2016-05-19T13:47:40.000Z",
    "channelId": "UCs72iRpTEuwV3y6pdWYLgiw",
    "title": "Katy Perry - Dark Horse (Official) ft. Juicy J",
    "description": "Bla bla bla",
    },
    "channelTitle": "#RedMusic: Just Hits",
    "playlistId": "PLMC9KNkIncKtPzgY-5rmhvj7fax8fdxoj",
    "position": 0,
    "resourceId": {
     "kind": "youtube#video",
     "videoId": "0KSOMA3QBU0"
    }
   }
  },
</code>```

And this is my code for taking the videoId

```<code>JObject jObj = (JObject)JsonConvert.DeserializeObject(x.Result);
foreach (var item in jObj["items"])
{
  string title = item["videoId"].ToString();
}
</code>```

And when I'm start my app I have an error with System.NullReferenceException.

Where is my problem ?

Thanks

答:
Change:

string title = item["videoId"].ToString();

to:

string title = item["resourceId"]["videoId"].ToString();

Body:
I'm trying to get information from the Google API (YT). I need to take the videoId from the API of Google.

So I download the JSON page and trying to deserialize my result but he doesn't works.

This is the JSON result

    {
   "kind": "youtube#playlistItemListResponse",
   "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/E6IhaTG5XEbqo_uSYhCcIvQhtwY\"",
   "nextPageToken": "CDIQAA",
   "pageInfo": {
   "totalResults": 180,
   "resultsPerPage": 50
   },
  "items": [
  {
   "kind": "youtube#playlistItem",
   "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/0cAZGJiF62yaNO7GwJlJBsc7DqY\"",
   "id": "UExNQzlLTmtJbmNLdFB6Z1ktNXJtaHZqN2ZheDhmZHhvai41RDlFNzlCQjE5NzcyQTYx",
   "snippet": {
    "publishedAt": "2016-05-19T13:47:40.000Z",
    "channelId": "UCs72iRpTEuwV3y6pdWYLgiw",
    "title": "Katy Perry - Dark Horse (Official) ft. Juicy J",
    "description": "Bla bla bla",
    },
    "channelTitle": "#RedMusic: Just Hits",
    "playlistId": "PLMC9KNkIncKtPzgY-5rmhvj7fax8fdxoj",
    "position": 0,
    "resourceId": {
     "kind": "youtube#video",
     "videoId": "0KSOMA3QBU0"
    }
   }
  },

And this is my code for taking the videoId

JObject jObj = (JObject)JsonConvert.DeserializeObject(x.Result);
foreach (var item in jObj["items"])
{
  string title = item["videoId"].ToString();
}

And when I'm start my app I have an error with System.NullReferenceException.

Where is my problem ?

Thanks


问:
ng serve erroring after NPM 5.0.1 update: Invalid Version:
I just updated to NPM 5.0.1 and right away I had compilation errors in my Angular 4.1.3 project. After deleting and completely reinstalling my node_modules (all packages up to date) I get a strange and red colored error when running ng serve:

```<code>Invalid Version: https://registry.npmjs.org/@angular/core/-/core-4.1.3.tgz
TypeError: Invalid Version: https://registry.npmjs.org/@angular/core/-/core-4.1.3.tgz
    at new SemVer (/Users/bracicot/dev/recruitler/node_modules/semver/semver.js:293:11)
    at new Version (/Users/bracicot/dev/recruitler/node_modules/@angular/cli/upgrade/version.js:23:36)
    at Function.assertAngularVersionIs2_3_1OrHigher (/Users/bracicot/dev/recruitler/node_modules/@angular/cli/upgrade/version.js:80:23)
    at Class.run (/Users/bracicot/dev/recruitler/node_modules/@angular/cli/commands/serve.js:102:27)
    at Class.Command.validateAndRun (/Users/bracicot/dev/recruitler/node_modules/@angular/cli/ember-cli/lib/models/command.js:128:15)
    at /Users/bracicot/dev/recruitler/node_modules/@angular/cli/ember-cli/lib/cli/cli.js:92:22
    at tryCatch (/Users/bracicot/dev/recruitler/node_modules/rsvp/dist/rsvp.js:539:12)
    at invokeCallback (/Users/bracicot/dev/recruitler/node_modules/rsvp/dist/rsvp.js:554:13)
    at /Users/bracicot/dev/recruitler/node_modules/rsvp/dist/rsvp.js:629:16
    at flush (/Users/bracicot/dev/recruitler/node_modules/rsvp/dist/rsvp.js:2414:5)
    at _combinedTickCallback (internal/process/next_tick.js:95:7)
    at process._tickCallback (internal/process/next_tick.js:161:9)
</code>```

I'm kind of stumped as to what could be causing this short of rolling back NPM. There doesnt seem to be anything online about it either.

UPDATE:
NPM added a package-lock.json file. The Invalid Version is coming from there.

UPDATE 2:
After reinstalling the CLI I get
Cannot find module 'webpack/lib/node/NodeTemplatePlugin' could it be that the package.json and package-lock.json are not in sync?

UPDATE 3:
Special thanks to @Dylanb124
Yes NPM5 is certainly buggy, the first issue was the package-lock file being created with incorrect values... There is a lot to this issue and I have resolved it. My dev partner was able to get NPM 5 working with a fresh NG project. Therefore we matched the working version against our repo until it built properly. The main conflicts were packages that supported node and mongo (hammer.js) and some others that I was able to remove permanently. (some cleanup was due anyways) in the end we were able to get it running. I would recommend waiting as long as possible to upgrade to NPM 5x

答:
What worked for me on npm 5.0.2

delete node_modules

rm -f package-lock.json && npm install

Body:
I just updated to NPM 5.0.1 and right away I had compilation errors in my Angular 4.1.3 project. After deleting and completely reinstalling my node_modules (all packages up to date) I get a strange and red colored error when running ng serve:

Invalid Version: https://registry.npmjs.org/@angular/core/-/core-4.1.3.tgz
TypeError: Invalid Version: https://registry.npmjs.org/@angular/core/-/core-4.1.3.tgz
    at new SemVer (/Users/bracicot/dev/recruitler/node_modules/semver/semver.js:293:11)
    at new Version (/Users/bracicot/dev/recruitler/node_modules/@angular/cli/upgrade/version.js:23:36)
    at Function.assertAngularVersionIs2_3_1OrHigher (/Users/bracicot/dev/recruitler/node_modules/@angular/cli/upgrade/version.js:80:23)
    at Class.run (/Users/bracicot/dev/recruitler/node_modules/@angular/cli/commands/serve.js:102:27)
    at Class.Command.validateAndRun (/Users/bracicot/dev/recruitler/node_modules/@angular/cli/ember-cli/lib/models/command.js:128:15)
    at /Users/bracicot/dev/recruitler/node_modules/@angular/cli/ember-cli/lib/cli/cli.js:92:22
    at tryCatch (/Users/bracicot/dev/recruitler/node_modules/rsvp/dist/rsvp.js:539:12)
    at invokeCallback (/Users/bracicot/dev/recruitler/node_modules/rsvp/dist/rsvp.js:554:13)
    at /Users/bracicot/dev/recruitler/node_modules/rsvp/dist/rsvp.js:629:16
    at flush (/Users/bracicot/dev/recruitler/node_modules/rsvp/dist/rsvp.js:2414:5)
    at _combinedTickCallback (internal/process/next_tick.js:95:7)
    at process._tickCallback (internal/process/next_tick.js:161:9)

I'm kind of stumped as to what could be causing this short of rolling back NPM. There doesnt seem to be anything online about it either.

UPDATE:
NPM added a package-lock.json file. The Invalid Version is coming from there.

UPDATE 2:
After reinstalling the CLI I get
Cannot find module 'webpack/lib/node/NodeTemplatePlugin' could it be that the package.json and package-lock.json are not in sync?

UPDATE 3:
Special thanks to @Dylanb124
Yes NPM5 is certainly buggy, the first issue was the package-lock file being created with incorrect values... There is a lot to this issue and I have resolved it. My dev partner was able to get NPM 5 working with a fresh NG project. Therefore we matched the working version against our repo until it built properly. The main conflicts were packages that supported node and mongo (hammer.js) and some others that I was able to remove permanently. (some cleanup was due anyways) in the end we were able to get it running. I would recommend waiting as long as possible to upgrade to NPM 5x


问:
C programming usin cmd prompt on windows
```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(){
    char command[20];

    system("dir");

    while(1){
    printf("\n\n");
    scanf("%s", &command);
    system(command);
    }

    return 0;
}
</code>```

this is my code, it's a console app written in C and I wanna be able to control the cmd prompt of my computer, whenever I run new command like cd.. the path always goes back to where it was before, how do i make it like a process? sorry I'm new to it.

答:
I have used a little trick which worked just fine. Let's imagine you want to launch an app located in "C:/Program Files".

```<code>const char applicationPath[] = "cd C:/Program Files/App&&";

bool sytemCallsToApp(void) {
    char cmd[200] = "";
    strcpy(cmd, applicationPath); // cmd to access app
    strcat(cmd, "app.exe");
    strcat(cmd, "&&HERE YOUR NEXT COMMAND"); // This command will be concatenated after the && thus executed just after cd
    if (system(cmd) != 0)
        return false; // If failed exit

    // Use strcpy to modify the content of cmd[]
    // Use strcat to add instructions to cmd
    // Add && when you want to execute multiple cmd in one system call
    // Don't forget system() returns values depending of your calls. It'd be wise to check them.
    return true;
}
</code>```

Body:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(){
    char command[20];

    system("dir");

    while(1){
    printf("\n\n");
    scanf("%s", &command);
    system(command);
    }

    return 0;
}

this is my code, it's a console app written in C and I wanna be able to control the cmd prompt of my computer, whenever I run new command like cd.. the path always goes back to where it was before, how do i make it like a process? sorry I'm new to it.

Body:
I have used a little trick which worked just fine. Let's imagine you want to launch an app located in "C:/Program Files".

const char applicationPath[] = "cd C:/Program Files/App&&";

bool sytemCallsToApp(void) {
    char cmd[200] = "";
    strcpy(cmd, applicationPath); // cmd to access app
    strcat(cmd, "app.exe");
    strcat(cmd, "&&HERE YOUR NEXT COMMAND"); // This command will be concatenated after the && thus executed just after cd
    if (system(cmd) != 0)
        return false; // If failed exit

    // Use strcpy to modify the content of cmd[]
    // Use strcat to add instructions to cmd
    // Add && when you want to execute multiple cmd in one system call
    // Don't forget system() returns values depending of your calls. It'd be wise to check them.
    return true;
}


问:
i need to allow the data which is in between the start and end date
Here i given my database table. i need to create a code to allow the data to show after the start date and remove the data after the end date:

答:
To remove date when End occurs you can use the DELETE command and use the internal date (GetDate() in Sql Server) as a reference. Then do a SELECT to get the records for the current offers, again using the internal date. Both commands can be used together, just separate with a semicolon

```<code>DELETE FROM [Table] WHERE GetDate() >= [End];
SELECT * FROM [Table] WHERE GetDate() >= [Start];
</code>```

If you would like this to be a Stored Procedure, it is fairly simple to do. All you need to do is to wrap those commands with a CREATE PROCEDURE block. The hardest thing about it coming up with a name.

```<code>CREATE PROCEDURE dbo.mp_GetCurrentOffers
AS
BEGIN
    DELETE FROM [Table] WHERE GetDate() >= [End];
    SELECT * FROM [Table] WHERE GetDate() >= [Start];
END
GO
</code>```

Body:
To remove date when End occurs you can use the DELETE command and use the internal date (GetDate() in Sql Server) as a reference. Then do a SELECT to get the records for the current offers, again using the internal date. Both commands can be used together, just separate with a semicolon

DELETE FROM [Table] WHERE GetDate() >= [End];
SELECT * FROM [Table] WHERE GetDate() >= [Start];

If you would like this to be a Stored Procedure, it is fairly simple to do. All you need to do is to wrap those commands with a CREATE PROCEDURE block. The hardest thing about it coming up with a name.

CREATE PROCEDURE dbo.mp_GetCurrentOffers
AS
BEGIN
    DELETE FROM [Table] WHERE GetDate() >= [End];
    SELECT * FROM [Table] WHERE GetDate() >= [Start];
END
GO


问:
Get viewport coordinates from mapView? regionDidChanged swift
The following function is called when the user moved the map.

It is possible to get the viewport? Viewport is latitude and longitude of north/east and the lat. and lon. of south/west.

```<code> func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool){
    print("The \(mapView.centerCoordinate)")
    print("the maprect \(mapView.visibleMapRect.origin)")
    print("the maprect \(mapView.visibleMapRect.size)")
    //I find just this attributes for mapView

    }
</code>```

I don't know how get the viewports out of my data. I can't find anything in the www.

The destination is that I log the coordinates with google analytics and another tool evaluate the datas.

Has somebody an idea? Thanks a lot

答:
Based on fel1xw answer

Swift 3 MapKit

```
let northEast = mapView.convert(CGPoint(x: mapView.bounds.width, y: 0), toCoordinateFrom: mapView)
let southWest = mapView.convert(CGPoint(x: 0, y: mapView.bounds.height), toCoordinateFrom: mapView)
```

Body:
The following function is called when the user moved the map.

It is possible to get the viewport? Viewport is latitude and longitude of north/east and the lat. and lon. of south/west.

 func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool){
    print("The \(mapView.centerCoordinate)")
    print("the maprect \(mapView.visibleMapRect.origin)")
    print("the maprect \(mapView.visibleMapRect.size)")
    //I find just this attributes for mapView

    }

I don't know how get the viewports out of my data. I can't find anything in the www.

The destination is that I log the coordinates with google analytics and another tool evaluate the datas.

Has somebody an idea? Thanks a lot

Body:
Based on fel1xw answer

Swift 3 MapKit

let northEast = mapView.convert(CGPoint(x: mapView.bounds.width, y: 0), toCoordinateFrom: mapView)
let southWest = mapView.convert(CGPoint(x: 0, y: mapView.bounds.height), toCoordinateFrom: mapView)


答:
I think you can just use group by:

```<code>SELECT id, FullPath FROM Documents GROUP BY FullPath;
</code>```

Title: Removing similar rows using GROUP BY / DISTINCT

Body:
I think you can just use group by:

SELECT id, FullPath FROM Documents GROUP BY FullPath;


问:
What is this spell-checker like feature which is not linked to an addon?
One of my installs of Visual Studio Code has a feature which I do not know how to remove. When typing a tag, there is an entry with an abc icon which looks like a check speller and which I cannot link to neither setting, nor add-on:

The other entries identify the add-on they come from (and are therefore easy to disable or uninstall):

Since I could not find it in Settings, it is either a better-hidden setting, or a plugin which does not identify itself (another instance of VSCode I have elsewhere does not have it).

Can you please help to identify it?

答:
These abc entries are the typed words in your file.

Since you typed div one line above, when you start typing di, the autocomplete feature will show up the previously typed words that starts with di, snippets that starts with di and other language features (depending on extensions you installed).

You can turn off this suggestions if you set "editor.wordBasedSuggestions" to false:

```<code>"editor.wordBasedSuggestions": false
</code>```

Body:
These abc entries are the typed words in your file.

Since you typed div one line above, when you start typing di, the autocomplete feature will show up the previously typed words that starts with di, snippets that starts with di and other language features (depending on extensions you installed).

You can turn off this suggestions if you set "editor.wordBasedSuggestions" to false:

"editor.wordBasedSuggestions": false


问:
How to enable Cross domain requests on JAX-RS web services?
I developed a set of restful web services. I couldn't call any of these methods from remote clients due to the error
No 'Access-Control-Allow-Origin' header is present on the requested resource.

The services work perfectly on localhost. Is there any changes or configs to do on the server side to resolve the issue. i.e. to enable cross domain requests.

I'm using WildFly 8, JavaEE 7

答:
Just to add something to other responses.
Allowing * is a little bit dangerous.
What can be done is configuring a database of the allowed origin (it can be a file)

Then when the request arrive you can do:

```<code>// this will return you the origin
String[] referers = requestContext.getHeaders().get("referer")

// then search in your DB if the origin is allowed
if (referers != null && referers.lenght == 1 && isAllowedOriging(referers[0])) {
        containerResponseContext.getHeaders().add("Access-Control-Allow-Origin", referers[0]);
        containerResponseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization, <HERE PUT YOUR DEDICATED HEADERS>);
        containerResponseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        containerResponseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        containerResponseContext.getHeaders().add("Access-Control-Max-Age", "1209600");
}
</code>```

In that way you won't allow everyone.

Body:
Just to add something to other responses.
Allowing * is a little bit dangerous.
What can be done is configuring a database of the allowed origin (it can be a file)

Then when the request arrive you can do:

// this will return you the origin
String[] referers = requestContext.getHeaders().get("referer")

// then search in your DB if the origin is allowed
if (referers != null && referers.lenght == 1 && isAllowedOriging(referers[0])) {
        containerResponseContext.getHeaders().add("Access-Control-Allow-Origin", referers[0]);
        containerResponseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization, <HERE PUT YOUR DEDICATED HEADERS>);
        containerResponseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        containerResponseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        containerResponseContext.getHeaders().add("Access-Control-Max-Age", "1209600");
}

In that way you won't allow everyone.


问:
Database Design
I'm trying to model nested relationships and am having a tough time getting to where I want to be.  I want to present an example that will hopefully answer some of my questions; its based on geography.

I'd like to have a single Region entity.  This region entity allows for Planets, Continents and Countries.

I would basically have a single Region called Earth.  This would be the first level of the hierarchy.  Then I would have the 7 Continents which would be nested within Region Earth.  Then I would add all the countries of the world and associate each with their outer continent.  There may be edges cases (I don't know if there are in this example, but I want there to be) where a Country belongs to more than one continent.

What I essentially want to get to is the ability to say:

Select All Countries in a Continent.  I'd like the ability to indefinitely nest too; so the next layer would be states/provinces.  So I could then say I want all provinces in North America.

I can kind of envision how the SQL would look, but I don't know how to do the multi-tier nesting:

```<code>Select *
From Region Outer, Region Inner
Where Outer.Name = "North America"
AND Inner.Type = "State"
</code>```

I've come up with just a simple Region entity and then a self-referential Parent-Child entity:

```<code>Region {RegionID, Name, Type}
SubRegion {ParentID, ChildID}
</code>```

I'm most interested in learning how this should be achieved.  If I'm making incorrect or poor design decisions/assumptions feel free to make your own suggestion.  I'm also not explicitly interested in the geographic stuff, I just thought it was a good example that illustrated what I am trying to accomplish.

I'm trying to do this in SQL 2008 R2 with C# and Linq.

This feels like a hierarchical network graph, so I think there should be a well understood way to do this; I just don't know it..

答:
Region mapping can be a complex problem. The primary issue is that when dealing with mapping, regions do not neatly fit into continents etc. For example, if you regard the US as a region it covers two parts of North America, and includes islands in the Pacific. many other examples come from more esoteric region mappings. One example someone mentioned to me was the Rocky Mountains which span both North America and Canada, so who does it belong to? Other region types can overlap each other rather than nest. For example, a wine region may overlap, but not completely encompass a municipal area. It may even include bits from several.

So if you are going to be dealing with regions in this sense then you will have to basically allow for multiple shapes on a map, of any shape and location, which may have any sort of relationship with other shapes.

If this is for a game then you can basically hack the model to suite yourself. I'd suggest adding some basic limitations along the lines that any given region cannot overlap another, except for it's parent which must completely contain it.

If this is for Real then you have the above complex issues to deal with.

Title: Database Design

Body:
I'm trying to model nested relationships and am having a tough time getting to where I want to be.  I want to present an example that will hopefully answer some of my questions; its based on geography.

I'd like to have a single Region entity.  This region entity allows for Planets, Continents and Countries.

I would basically have a single Region called Earth.  This would be the first level of the hierarchy.  Then I would have the 7 Continents which would be nested within Region Earth.  Then I would add all the countries of the world and associate each with their outer continent.  There may be edges cases (I don't know if there are in this example, but I want there to be) where a Country belongs to more than one continent.

What I essentially want to get to is the ability to say:

Select All Countries in a Continent.  I'd like the ability to indefinitely nest too; so the next layer would be states/provinces.  So I could then say I want all provinces in North America.

I can kind of envision how the SQL would look, but I don't know how to do the multi-tier nesting:

Select *
From Region Outer, Region Inner
Where Outer.Name = "North America"
AND Inner.Type = "State"

I've come up with just a simple Region entity and then a self-referential Parent-Child entity:

Region {RegionID, Name, Type}
SubRegion {ParentID, ChildID}

I'm most interested in learning how this should be achieved.  If I'm making incorrect or poor design decisions/assumptions feel free to make your own suggestion.  I'm also not explicitly interested in the geographic stuff, I just thought it was a good example that illustrated what I am trying to accomplish.

I'm trying to do this in SQL 2008 R2 with C# and Linq.

This feels like a hierarchical network graph, so I think there should be a well understood way to do this; I just don't know it..


问:
Restrict text till the width of div in contenteditable and trigger enter to form new line
I want to restrict the text in contenteditable at the end of div width (800px) or when ellipsis detect and trigger enter using jQuery. If I press enter it form new line perfectly but how to achieve by checking width or overflow or ellipsis for each line
My code is as below:

$('.content p').on('keypress', function(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    alert("det");
    $(this).after('

');
  }
}).on('click', function(e) {
  e.preventDefault();
  var tx = $(this).text();
  if (tx == 'Click here...) {
    $(this).text(' ');
  }
});

function pasteHtmlAtCaret(html) {
  var sel, range;
  if (window.getSelection) {
    // IE9 and non-IE
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();

      // Range.createContextualFragment() would be useful here but is
      // non-standard and not supported in all browsers (IE9, for one)
      var el = document.createElement("div");
      el.innerHTML = html;
      var frag = document.createDocumentFragment(),
        node, lastNode;
      while ((node = el.firstChild)) {
        lastNode = frag.appendChild(node);
      }
      range.insertNode(frag);

      // Preserve the selection
      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  } else if (document.selection && document.selection.type != "Control") {
    // IE < 9

  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  position: relative;
  z-index: 10;
  padding: 30px;
  background: #fff;
  border-top: 2px solid #36F;
  border-bottom: 2px solid #36F border:2px solid #390;
  top: 22px;
  max-width: 800px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  font-size: 76px;
  border-style: solid;
}</code>```

Click here..

```

答:
use this to prevent the editing after a fixed number of characters in contenteditable div. Here i am restricting the user to type upto 500 characters</p>

```<code>$('.content p').keydown(function (e) {
    check_charcount($(this), 500, e);
});

function check_charcount(element, max, e) {
    if (e.which != 8 && element.text().length > max) {
        e.preventDefault();
    }
}
</code>```

Body:
I want to restrict the text in contenteditable at the end of div width (800px) or when ellipsis detect and trigger enter using jQuery. If I press enter it form new line perfectly but how to achieve by checking width or overflow or ellipsis for each line
My code is as below:

$('.content p').on('keypress', function(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    alert("det");
    $(this).after('

');
  }
}).on('click', function(e) {
  e.preventDefault();
  var tx = $(this).text();
  if (tx == 'Click here...) {
    $(this).text(' ');
  }
});

function pasteHtmlAtCaret(html) {
  var sel, range;
  if (window.getSelection) {
    // IE9 and non-IE
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();

      // Range.createContextualFragment() would be useful here but is
      // non-standard and not supported in all browsers (IE9, for one)
      var el = document.createElement("div");
      el.innerHTML = html;
      var frag = document.createDocumentFragment(),
        node, lastNode;
      while ((node = el.firstChild)) {
        lastNode = frag.appendChild(node);
      }
      range.insertNode(frag);

      // Preserve the selection
      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  } else if (document.selection && document.selection.type != "Control") {
    // IE < 9

  }

p {
  position: relative;
  z-index: 10;
  padding: 30px;
  background: #fff;
  border-top: 2px solid #36F;
  border-bottom: 2px solid #36F border:2px solid #390;
  top: 22px;
  max-width: 800px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  font-size: 76px;
  border-style: solid;
}

Click here..

Body:
use this to prevent the editing after a fixed number of characters in contenteditable div. Here i am restricting the user to type upto 500 characters

$('.content p').keydown(function (e) {
    check_charcount($(this), 500, e);
});

function check_charcount(element, max, e) {
    if (e.which != 8 && element.text().length > max) {
        e.preventDefault();
    }
}


问:
Swift Picker Items
I'm trying to make items show up on my pickerView, I can't seem to figure out why its not showing up. Any Suggestions?</p>

```<code>import UIKit

class InspectionViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var picker: UIPickerView!

    var pickerData: [String] = [String]();

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        // Connect data:
        self.picker.delegate = self;
        self.picker.dataSource = self;

        // Input data into the Array:
        pickerData = ["53W4", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"];
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.

    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return pickerData[row]
    }

    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}
</code>```

答:
You should use this:

func pickerView(
    _ pickerView: UIPickerView,
    titleForRow row: Int,
    forComponent component: Int
) -> String? {
  pickerData[row]
}
```

<p>instead of:</p>

<pre class="lang-swift prettyprint-override"><code>func pickerView(
  pickerView: UIPickerView,
  titleForRow row: Int,
  forComponent component: Int
) -> String! {
  pickerData[row]
}
</code>```

The diff is in Omitting Argument Labels.
Here is a doc link

Title: Swift Picker Items

Body:
I'm trying to make items show up on my pickerView, I can't seem to figure out why its not showing up. Any Suggestions?

import UIKit

class InspectionViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var picker: UIPickerView!

    var pickerData: [String] = [String]();

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        // Connect data:
        self.picker.delegate = self;
        self.picker.dataSource = self;

        // Input data into the Array:
        pickerData = ["53W4", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"];
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.

    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return pickerData[row]
    }

    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}

Body:
You should use this:

func pickerView(
    _ pickerView: UIPickerView,
    titleForRow row: Int,
    forComponent component: Int
) -> String? {
  pickerData[row]
}

instead of:

func pickerView(
  pickerView: UIPickerView,
  titleForRow row: Int,
  forComponent component: Int
) -> String! {
  pickerData[row]
}

The diff is in Omitting Argument Labels.
Here is a doc link


问:
Wicket AjaxLink erases onclick listeners
In our project we have an AjaxLink:

```<code><a title="some title.." wicket:id="addMessage">Add</a>
</code>```

Incide Page.class:

```<code>add(new AjaxLink() {
    @Override
    public void onClick(final AjaxRequestTarget target) {
        //...
    }
    @Override
    protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
        attributes.getAjaxCallListeners().add(new AjaxCallListener() {
            @Override
            public CharSequence getPrecondition(Component component) {
                return "return isPropagationAllowed()";
            }
        });
    }
}
</code>```

(Adding AjaxCallListener with method getPrecondition() stops onclick() method from being executed on some conditions (it should return a name of a function from your js which returns boolean))

Then I define a listener for that html element by js (+ JQuery) and put some behaviour to that:

```<code>$('[title]').each((i, elem) => elem.onclick = (event) => {
    /* ..manually open a tooltip.... */
})
</code>```

It works as intended until that AjaxLink executes. Then my onclick listener dissapears for some reason, and then to make it work I should bind it manually.

Do you have any idea why is this (the erasure of other listeners) happening and how to prevent that?

答:
I think the reason is that the link has been re-created in the DOM due to some target.add(ajaxLinkOrParent) call on the server side. The old one with the onclick attribute is removed and a new one is created.

You should use jQuery "live" binding instead, e.g. $(document).on('click', '[title]', function(evt) {showTooltip();})

Body:
In our project we have an AjaxLink:

Add

Incide Page.class:

add(new AjaxLink() {
    @Override
    public void onClick(final AjaxRequestTarget target) {
        //...
    }
    @Override
    protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
        attributes.getAjaxCallListeners().add(new AjaxCallListener() {
            @Override
            public CharSequence getPrecondition(Component component) {
                return "return isPropagationAllowed()";
            }
        });
    }
}

(Adding AjaxCallListener with method getPrecondition() stops onclick() method from being executed on some conditions (it should return a name of a function from your js which returns boolean))

Then I define a listener for that html element by js (+ JQuery) and put some behaviour to that:

$('[title]').each((i, elem) => elem.onclick = (event) => {
    /* ..manually open a tooltip.... */
})

It works as intended until that AjaxLink executes. Then my onclick listener dissapears for some reason, and then to make it work I should bind it manually.

Do you have any idea why is this (the erasure of other listeners) happening and how to prevent that?


问:
SharePoint Edit Tasklist Task
I have SharePoint setup, and for a test I added a Task List, added a few columns, and tested it out.  I wanted to modify the task list task page, not the task list page.  I can edit the task list page, but I cannot edit the task list task page.  I am missing the Edit Page button from site actions on that page.  How can I edit the page of the actual task?</p>

答: Not out of the box.  Other than generating a different view, there isn't much you can do to the listing page.  Perhaps you can expose the list via a Content Query Web Part and format it how you like.</p>

OwnerDisplayName: Oliver S

Title: SharePoint Edit Tasklist Task

OwnerDisplayName: MrChrister


问:
Showing a preview of the image file that user wants to upload on the website
How i can show a preview of the image which the user chooses to upload on website.

I mean, when a user chooses the file from their system, have the web-page already show them the files they want to upload. how I can do this using HTML and jQuery?

答:
You can't, atleast not in all browsers.

This is because some browsers provide the entire path to the <input type='file'> - this way you can try and show the element on the users harddisk (do watch out for certain browsers' security settings)

Other browsers just provide a filename - you've got nothing to show here.

What you can always do, is upload the file using jQuery (.ajax, so the page does not get refreshed) and then show it to the user already. In these modern times, uploading a file is not that disturbing (especially if you provide an animation while it's working).

If you really need this feature, you can always use a Java Applet (think facebook or imageshack) to allow for previews. Not every user has (a recent enough version of) Java installed and enabled though.

If you still want to implement this for browsers that do provide the full path (say, you work in a corporate environment and everyone uses the same browser, or you have it degrade gracefully and just offer the feature to the users for whom it works), you just use the .val() of the <input type='file'> to get the path to the filename. Add a file:// before and display (dump in an img or so)

More info:

Get full path of a file with FileUpload Control

How to get the file path from HTML input form in Firefox 3

https://developer.mozilla.org/en/using_files_from_web_applications

https://bugzilla.mozilla.org/show_bug.cgi?id=143220

OwnerDisplayName: Steven Spielberg


问:
Justifying text inside a TextView in android
So, as most of you know, there is no text justifying inside a TextView in Android. So, I built a custom TextView to get around the problem. However, for some reason, sometimes punctuation marks break the line for some reason in some devices. I tested on an LG G3 and emulator (Nexus 4 running latest version) and a comma "," for instance breaks the justification on the LG G3 but not on the emulator.

If I add a Padding start and end (or left and right) of at least 2, the problem is solved. This looks very arbitrary to me.

Basically, my logic was that in order to justify the text, I would need to know the width of the TextView itself, construct the text into lines that are at maximum that length. Then, by finding the number of spaces in the line and the remaining empty space, stretch the " " (space) characters to be scaled according to remaining pixels (or, space in the view).

It works almost perfectly, and most of the time it supports RTL text as well.

here're some pictures of the text (a simple lorem impsum) with and without the offending marks (first one is on emulator nexus 4 running 7.1.1, second one is on LG G3 running v5.0)

Here's the code:

```<code>public class DTextView extends AppCompatTextView {

    private boolean justify;

    public DTextView(Context context) {
        super(context);
    }

    public DTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public DTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void setJustify(boolean justify) {
        this.justify = justify;
        if (justify) {
            justify();
        }
    }

    private void init(@Nullable AttributeSet attrs) {
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DTextView, 0, 0);
        justify = ta.getBoolean(R.styleable.DTextView_justify, false);

        ta.recycle();
    }

    private SpannableStringBuilder justifyText() {

        String[] words = getText().toString().split(" ");
        setText("");

        int maxLineWidth = getWidth() - getPaddingLeft() - getPaddingRight();

        SpannableStringBuilder justifiedTextSpannable = new SpannableStringBuilder();

        //This will build the new text with the lines rearranged so that they will have a width
        //bigger than the View's own width
        ArrayList<String> lines = new ArrayList<>(0);
        String line = "";
        for (String word : words) {
            if (getWordWidth(line + word) < maxLineWidth) {
                line += word + " ";
            } else {
                line = line.substring(0, line.length() - 1);
                lines.add(line);
                line = word + " ";
            }
        }
        //Add the last line
        lines.add(line);

        for (int i = 0; i < lines.size() - 1; i++) {
            justifiedTextSpannable.append(justifyLine(lines.get(i), maxLineWidth));
            justifiedTextSpannable.append("\n");
        }

        justifiedTextSpannable.append(lines.get(lines.size() - 1));

        return justifiedTextSpannable;
    }

    private SpannableString justifyLine(String line, float maxWidth) {

        SpannableString sLine = new SpannableString(line);
        float spaces = line.split(" ").length - 1;

        float spaceCharSize = getWordWidth(" ");
        float emptySpace = maxWidth - getWordWidth(line);
        float newSpaceSize = (emptySpace / spaces) + spaceCharSize;
        float scaleX = newSpaceSize / spaceCharSize;

        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) == ' ') {
                sLine.setSpan(new ScaleXSpan(scaleX), i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        return sLine;
    }

    private void justify() {
        justify = false;
        setText(justifyText());
        invalidate();
    }

    private float getWordWidth(String word) {
        return getPaint().measureText(word);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (!justify)
            super.onDraw(canvas);
        else
            justify();
    }
}
</code>```

I would very much appreciate anyone that can shed some light on this.

答:
LIBRARY: https://github.com/bluejamesbond/TextJustify-Android

SUPPORTS: Android 2.0 to 5.X

SCREENSHOT

Body:
So, as most of you know, there is no text justifying inside a TextView in Android. So, I built a custom TextView to get around the problem. However, for some reason, sometimes punctuation marks break the line for some reason in some devices. I tested on an LG G3 and emulator (Nexus 4 running latest version) and a comma "," for instance breaks the justification on the LG G3 but not on the emulator.

If I add a Padding start and end (or left and right) of at least 2, the problem is solved. This looks very arbitrary to me.

Basically, my logic was that in order to justify the text, I would need to know the width of the TextView itself, construct the text into lines that are at maximum that length. Then, by finding the number of spaces in the line and the remaining empty space, stretch the " " (space) characters to be scaled according to remaining pixels (or, space in the view).

It works almost perfectly, and most of the time it supports RTL text as well.

here're some pictures of the text (a simple lorem impsum) with and without the offending marks (first one is on emulator nexus 4 running 7.1.1, second one is on LG G3 running v5.0)

Here's the code:

public class DTextView extends AppCompatTextView {

    private boolean justify;

    public DTextView(Context context) {
        super(context);
    }

    public DTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public DTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void setJustify(boolean justify) {
        this.justify = justify;
        if (justify) {
            justify();
        }
    }

    private void init(@Nullable AttributeSet attrs) {
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DTextView, 0, 0);
        justify = ta.getBoolean(R.styleable.DTextView_justify, false);

        ta.recycle();
    }

    private SpannableStringBuilder justifyText() {

        String[] words = getText().toString().split(" ");
        setText("");

        int maxLineWidth = getWidth() - getPaddingLeft() - getPaddingRight();

        SpannableStringBuilder justifiedTextSpannable = new SpannableStringBuilder();

        //This will build the new text with the lines rearranged so that they will have a width
        //bigger than the View's own width
        ArrayList<String> lines = new ArrayList<>(0);
        String line = "";
        for (String word : words) {
            if (getWordWidth(line + word) < maxLineWidth) {
                line += word + " ";
            } else {
                line = line.substring(0, line.length() - 1);
                lines.add(line);
                line = word + " ";
            }
        }
        //Add the last line
        lines.add(line);

        for (int i = 0; i < lines.size() - 1; i++) {
            justifiedTextSpannable.append(justifyLine(lines.get(i), maxLineWidth));
            justifiedTextSpannable.append("\n");
        }

        justifiedTextSpannable.append(lines.get(lines.size() - 1));

        return justifiedTextSpannable;
    }

    private SpannableString justifyLine(String line, float maxWidth) {

        SpannableString sLine = new SpannableString(line);
        float spaces = line.split(" ").length - 1;

        float spaceCharSize = getWordWidth(" ");
        float emptySpace = maxWidth - getWordWidth(line);
        float newSpaceSize = (emptySpace / spaces) + spaceCharSize;
        float scaleX = newSpaceSize / spaceCharSize;

        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) == ' ') {
                sLine.setSpan(new ScaleXSpan(scaleX), i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        return sLine;
    }

    private void justify() {
        justify = false;
        setText(justifyText());
        invalidate();
    }

    private float getWordWidth(String word) {
        return getPaint().measureText(word);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (!justify)
            super.onDraw(canvas);
        else
            justify();
    }
}

I would very much appreciate anyone that can shed some light on this.