问:
Android - can't start activity of a library project
I am developing a library. I want that an application using my library should be able to start my main activity via implicit intents using my custom action. But custom intent is not working. It says "no activity found to handle intent with action = 'my custom action'". Below is my code :

```<code>Intent intent = new Intent();
intent.setAction("my.custom.action");
intent.addCategory("android.intent.category.DEFAULT");
intent.putExtra("foo","bar");
startActivity(intent);
</code>```

I have also tried using the package name to get intent but it didn't work either (though I don't want to use this method since I don't want to expose my package name and components)

```<code>Intent intent = getPackageManager().getLaunchIntentForPackage("com.happay.android.acslibrary");
</code>```

Finally I tried using explicit intent :

```<code>Intent intent = new Intent(this,LibMainActivity.class);
startActivity(intent);
</code>```

This didn't throw exception but didn't open my library activity. It just opened the same activity from my main project.
Here is my Library project manifest where I register my activity :

```<code><activity android:name=".LibMainActivity">
        <intent-filter>
            <action android:name="my.custom.action" />

            <category android:name="android.intent.category.DEFAULT" />

        </intent-filter>
    </activity>
</code>```

What am I doing wrong?

答:
Remove the category from the Intent you pass to startActivity(). You added category LAUNCHER to the Intent, but your <intent-filter> only contains  category DEFAULT. There is no match. According to the documentation for matching Intents:

Categories match if all of the categories in the Intent match
  categories given in the filter. Extra categories in the filter that
  are not in the Intent will not cause the match to fail. Note that
  unlike the action, an IntentFilter with no categories will only match
  an Intent that does not have any categories.

Body:
I am developing a library. I want that an application using my library should be able to start my main activity via implicit intents using my custom action. But custom intent is not working. It says "no activity found to handle intent with action = 'my custom action'". Below is my code :

Intent intent = new Intent();
intent.setAction("my.custom.action");
intent.addCategory("android.intent.category.DEFAULT");
intent.putExtra("foo","bar");
startActivity(intent);

I have also tried using the package name to get intent but it didn't work either (though I don't want to use this method since I don't want to expose my package name and components)

Intent intent = getPackageManager().getLaunchIntentForPackage("com.happay.android.acslibrary");

Finally I tried using explicit intent :

Intent intent = new Intent(this,LibMainActivity.class);
startActivity(intent);

This didn't throw exception but didn't open my library activity. It just opened the same activity from my main project.
Here is my Library project manifest where I register my activity :

<activity android:name=".LibMainActivity">
        <intent-filter>
            <action android:name="my.custom.action" />

            <category android:name="android.intent.category.DEFAULT" />

        </intent-filter>
    </activity>

What am I doing wrong?


来源: stackexchange

问:
How to prevent NULL spinner?
I am populating a spinner from a DB. It works great. Except that if that part of the DB has not been filled out yet and the spinner is empty. That is a problem when someone tries to append to that part of the DB with a blank spinner, you get a nullpointerexception. I have tried all kinds of variations of

```<code>if (spinner == null) {warn the person and finish()}
</code>```

Or

```<code>if (spinner.equals(""){warn the person blah blah blah}.
</code>```

Any Solution?

答:
If you work with the DB, you probably use a Cursor object. Can you not check the count of object in the Cursor with c.getCount()  ?

```<code>if (c.getCount() == 0) {
    warn the person and finish()
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to prevent NULL spinner?

Body:
I am populating a spinner from a DB. It works great. Except that if that part of the DB has not been filled out yet and the spinner is empty. That is a problem when someone tries to append to that part of the DB with a blank spinner, you get a nullpointerexception. I have tried all kinds of variations of

if (spinner == null) {warn the person and finish()}

Or

if (spinner.equals(""){warn the person blah blah blah}.

Any Solution?

Body:
If you work with the DB, you probably use a Cursor object. Can you not check the count of object in the Cursor with c.getCount()  ?

if (c.getCount() == 0) {
    warn the person and finish()
}

ContentLicense: CC BY-SA 2.5


问:
How to select earliest date according to current sg
I need to come with a SQL (SQL Server) that gets the earliest date according to the current sg. Below is the sample table where current sg is 4-3 (current because the end date is 1900-01-01). I want to get the date where the sg actually started (which is 2015-01-01) per employee. I really need some help on this.</p>

```<code>empno      position             sg           date_from         date_to
4508       ADMIN AIDE IV        4-3          2017-01-01        1900-01-01
4508       ADMIN AIDE IV        4-3          2016-01-01        2016-12-31
4508       ADMIN AIDE IV        4-3          2015-01-01        2015-12-31
4508       ADMIN AIDE IV        4-2          2014-01-01        2014-12-31
4508       ADMIN AIDE IV        4-2          2013-01-01        2013-12-31
1207       AIRCRAFT MECHANIC I  6-1          1988-01-01        1989-06-30
1207       AIRCRAFT MECHANIC II 8-7          2006-05-08        2015-12-31
1207       AIRCRAFT MECHANIC II 8-8          2016-01-01        1900-01-01
0889       DATA ENTRY OPERATOR  1-1          2000-12-12        2001-06-30
0889       ADMIN ASSISTANT VI   12-5         2017-03-10        1900-01-01
0889       ADMIN ASSISTANT VI   12-5         2016-01-01        2016-12-31
</code>```

Body:
I need to come with a SQL (SQL Server) that gets the earliest date according to the current sg. Below is the sample table where current sg is 4-3 (current because the end date is 1900-01-01). I want to get the date where the sg actually started (which is 2015-01-01) per employee. I really need some help on this.

empno      position             sg           date_from         date_to
4508       ADMIN AIDE IV        4-3          2017-01-01        1900-01-01
4508       ADMIN AIDE IV        4-3          2016-01-01        2016-12-31
4508       ADMIN AIDE IV        4-3          2015-01-01        2015-12-31
4508       ADMIN AIDE IV        4-2          2014-01-01        2014-12-31
4508       ADMIN AIDE IV        4-2          2013-01-01        2013-12-31
1207       AIRCRAFT MECHANIC I  6-1          1988-01-01        1989-06-30
1207       AIRCRAFT MECHANIC II 8-7          2006-05-08        2015-12-31
1207       AIRCRAFT MECHANIC II 8-8          2016-01-01        1900-01-01
0889       DATA ENTRY OPERATOR  1-1          2000-12-12        2001-06-30
0889       ADMIN ASSISTANT VI   12-5         2017-03-10        1900-01-01
0889       ADMIN ASSISTANT VI   12-5         2016-01-01        2016-12-31

Body:
Please use the below query :

    DECLARE @t TABLE
    (ID INT IDENTITY (1,1),position VARCHAR(20), sg VARCHAR(10),date_from DATE,date_to DATE)

    INSERT INTO @t
    VALUES
    ('ADMIN AIDE IV','4-3','2017-01-01','1900-01-01'),
    ('ADMIN AIDE IV','4-3','2016-01-01','2016-12-31'),
    ('ADMIN AIDE IV','4-3','2015-01-01','2015-12-31'),
    ('ADMIN AIDE IV','4-2','2014-01-01','2014-12-31'),
    ('ADMIN AIDE IV','4-2','2013-01-01','2013-12-31')

    SELECT
        MIN(t1.date_from) AS [Earliest Date]
    FROM
        @t t1 INNER JOIN @t t2 ON t1.sg = t2.sg
    WHERE
        t2.date_to ='1900-01-01'


问:
xlwt on ubuntu installs but does not import
xlwt installs in the following path:

```<code>/usr/local/lib/python2.7/dist-packages
</code>```

successfully with pip or apt-get or easy_install.

However, when I try to import, it gives an error no module named xlwt.

All the relevant answers on this site say to pip install, but xlwt is already installed. As a workaround, I added the dist packages to my python path. Why is it not searching in dist packages?

I'm using ubuntu 16.04 and python 2.7

答:
For python and django related projects it is always preferred to use virtualenv!

sudo pip install virtualenv

To create virtualenv:

virtualenv my_env

To activate virtual env:

source my_env/bin/activate

pip install xlwt

Ref: http://pythoncentral.io/how-to-install-virtualenv-python/

Body:
xlwt installs in the following path:

/usr/local/lib/python2.7/dist-packages

successfully with pip or apt-get or easy_install.

However, when I try to import, it gives an error no module named xlwt.

All the relevant answers on this site say to pip install, but xlwt is already installed. As a workaround, I added the dist packages to my python path. Why is it not searching in dist packages?

I'm using ubuntu 16.04 and python 2.7


问:
List multi dimentional array
I have done a query for getting all data's under same id from other table.There are more than 2 data's under same id.

I need to display all data 's under same id like an array.

Here is my sql query:

```<code>  "SELECT incident.*,entry.*,fighter.*
  FROM register_incident AS incident JOIN
  register_entry_points AS entry
  ON entry.incident_id = incident.incident_id
  JOIN add_fire_fighters AS fighter
  ON entry.entrypoint_id = fighter.entry_point_id
  WHERE incident.incident_id=:incident_id"
</code>```

I get a response like,

```<code> "data":[
 {

  "incident_id": "5",
  "user_id": null,
  "entrypoint_id": "20",
  "entry_points": "New Entry1111",
  "comments": "Comment1",
  "fighter_id": "67",
  "entry_point_id": "20",
  "cylpressure": null,
  "time_in": null,
  "time_out": null,
  "duration": null,
  "notes": null
},
{
  "incident_id": "5",
  "user_id": "16",
  "entrypoint_id": "20",
  "entry_points": "New Entry1111",
  "comments": "Comment1",
  "fighter_id": "68",
  "entry_point_id": "20",
  "cylpressure": "300",
  "time_in": "10:30:00",
  "time_out": "11:45:00",
  "duration": "01:15",
  "notes": "Test"
},
</code>```

But i need to display it like,

```<code>"data": [
   {
  "incident_id": "5",
  "user_id": null,
  "entrypoint_id": "20",
  "entry_points": "New Entry1111",
  "comments": "Comment1",
  "fighter":{
    {
  "fighter_id": "67",
  "entry_point_id": "20",
  "cylpressure": null,
  "time_in": null,
  "time_out": null,
  "duration": null,
  "notes": null
   },
   {

  "fighter_id": "68",
  "entry_point_id": "20",
  "cylpressure": null,
  "time_in": null,
  "time_out": null,
  "duration": null,
  "notes": null

   }
   }
   }]
</code>```

How it is possible?

答:
If I get a ResultSet out of a Query with one or more 1:n relationships, I take the result like this sample.

```<code>$Result = array();
foreach($Records as $Record) {
  // key 1
  $key1 = $Record['incident_id'];
  if(isset($Result[$key1])) {
    $cuIncident=$Result[$key1];
  }
  else {
    $cuIncident=array(
      'incident_id' => $key1,
      'user_id'     => $Record['user_id'],
      //......
      'fighter'     => array()
    );
    $Result[$key1] = $cuIncident;
  }
  // key 2
  $key2 = $Record['fighter_id'];
  if(isset($cuIncident['fighter'][$key2])) {
    $cuFighter = $cuIncident['fighter'][$key2];
  }
  else {
    $cuFighter = array(
      'fighter_id'      => $key2,
      'entry_point_id'  => $Record['entry_point_id'],
      //......
      'key3array'       => array()
    );
    $cuIncident['fighter'][$key2] = $cuFighter;
  }
  // key 3
  // ....
</code>```

If a key is a multi value key, you have to combine these keys like:

```<code>  $key3 = $Record['key3prop1']."/".$Record['key3prop2'];
  if(isset($key3Array[$key3])) ......
</code>```

Title: List multi dimentional array

Body:
I have done a query for getting all data's under same id from other table.There are more than 2 data's under same id.

I need to display all data 's under same id like an array.

Here is my sql query:

  "SELECT incident.*,entry.*,fighter.*
  FROM register_incident AS incident JOIN
  register_entry_points AS entry
  ON entry.incident_id = incident.incident_id
  JOIN add_fire_fighters AS fighter
  ON entry.entrypoint_id = fighter.entry_point_id
  WHERE incident.incident_id=:incident_id"

I get a response like,

 "data":[
 {

  "incident_id": "5",
  "user_id": null,
  "entrypoint_id": "20",
  "entry_points": "New Entry1111",
  "comments": "Comment1",
  "fighter_id": "67",
  "entry_point_id": "20",
  "cylpressure": null,
  "time_in": null,
  "time_out": null,
  "duration": null,
  "notes": null
},
{
  "incident_id": "5",
  "user_id": "16",
  "entrypoint_id": "20",
  "entry_points": "New Entry1111",
  "comments": "Comment1",
  "fighter_id": "68",
  "entry_point_id": "20",
  "cylpressure": "300",
  "time_in": "10:30:00",
  "time_out": "11:45:00",
  "duration": "01:15",
  "notes": "Test"
},

But i need to display it like,

"data": [
   {
  "incident_id": "5",
  "user_id": null,
  "entrypoint_id": "20",
  "entry_points": "New Entry1111",
  "comments": "Comment1",
  "fighter":{
    {
  "fighter_id": "67",
  "entry_point_id": "20",
  "cylpressure": null,
  "time_in": null,
  "time_out": null,
  "duration": null,
  "notes": null
   },
   {

  "fighter_id": "68",
  "entry_point_id": "20",
  "cylpressure": null,
  "time_in": null,
  "time_out": null,
  "duration": null,
  "notes": null

   }
   }
   }]

How it is possible?

Body:
If I get a ResultSet out of a Query with one or more 1:n relationships, I take the result like this sample.

$Result = array();
foreach($Records as $Record) {
  // key 1
  $key1 = $Record['incident_id'];
  if(isset($Result[$key1])) {
    $cuIncident=$Result[$key1];
  }
  else {
    $cuIncident=array(
      'incident_id' => $key1,
      'user_id'     => $Record['user_id'],
      //......
      'fighter'     => array()
    );
    $Result[$key1] = $cuIncident;
  }
  // key 2
  $key2 = $Record['fighter_id'];
  if(isset($cuIncident['fighter'][$key2])) {
    $cuFighter = $cuIncident['fighter'][$key2];
  }
  else {
    $cuFighter = array(
      'fighter_id'      => $key2,
      'entry_point_id'  => $Record['entry_point_id'],
      //......
      'key3array'       => array()
    );
    $cuIncident['fighter'][$key2] = $cuFighter;
  }
  // key 3
  // ....

If a key is a multi value key, you have to combine these keys like:

  $key3 = $Record['key3prop1']."/".$Record['key3prop2'];
  if(isset($key3Array[$key3])) ......


问:
jQuery dispatch event? How to
how can i dispatch an event on my window ready?
For example in my code i've got:

```<code>$("#info").click(function(){
// do stuff
});
</code>```

I need to call this function the first time without have a click on #info, in the way // do stuff.

答:
You could use the .trigger() method:

```<code>$('#info').trigger('click');
</code>```

or simply:

```<code>$('#info').click();
</code>```

which would be the same.

Title: jQuery dispatch event? How to

Body:
how can i dispatch an event on my window ready?
For example in my code i've got:

$("#info").click(function(){
// do stuff
});

I need to call this function the first time without have a click on #info, in the way // do stuff.

Body:
You could use the .trigger() method:

$('#info').trigger('click');

or simply:

$('#info').click();

which would be the same.


问:
How to get random record from MS Access database
I have a MS access database.
In that, one table consists of questions and answers with primary key questionID.
I need to retrieve random question from that table using questionID.
What keywords or query should I use for this scenario.</p>

答:
```<code>SELECT TOP 5 questionID FROM [tableName] ORDER BY rnd(INT(NOW*questionID)-NOW*questionID)
</code>```

This will give you a new set of answers every time, you don't even need to make up a time when you use "NOW" (which will every time be a new time you click this no matter how fast you click), in my opinion the most simple and neat way to solve this in Access.

Body:
SELECT TOP 5 questionID FROM [tableName] ORDER BY rnd(INT(NOW*questionID)-NOW*questionID)

This will give you a new set of answers every time, you don't even need to make up a time when you use "NOW" (which will every time be a new time you click this no matter how fast you click), in my opinion the most simple and neat way to solve this in Access.


问:
Site working fine in Preview but when accessing the index.html file, the background images are missing
I have encountered an issue and I really don't know what is causing it. I am working in brackets and the site works perfectly in preview.

However, when I click on  the actual index.html file my background images from my scss are missing.

Uploaded images via src are working

Rest of my sass is working

Js is working

Only the images for my backgrounds ( using url ) are not working anymore, so I presume it has something to do with the url.

An example of the scss:

```<code>.jumbfirst {
    background: url('/imagini/images/background6.jpg');
    background-size: cover;
    width: $fullwidth;
    min-height: 600px;
}
</code>```

Any ideas? Thank you!

答:
It depends on your devel setup, meaning you use relative paths but depending on the structure of your files and how you run your index.html the browser reads the paths differently.
I'm guessing that double clicking the index.html file doesn't show it from your local server but as an absolute path like

file:///Applications/XAMPP/xamppfiles/htdocs/devel/test/index.html

This example is from a MAC and it's the path to the index.html in the file system.

You should either have a local devel server (e.g. XAMPP) or if you already have one change the address in your browser to something like

http://localhost/devel/test/index.html

In this case I'm calling index.html from my local server, inside the devel/test/ directory.

Hope this helps.

Body:
I have encountered an issue and I really don't know what is causing it. I am working in brackets and the site works perfectly in preview.

However, when I click on  the actual index.html file my background images from my scss are missing.

Uploaded images via src are working

Rest of my sass is working

Js is working

Only the images for my backgrounds ( using url ) are not working anymore, so I presume it has something to do with the url.

An example of the scss:

.jumbfirst {
    background: url('/imagini/images/background6.jpg');
    background-size: cover;
    width: $fullwidth;
    min-height: 600px;
}

Any ideas? Thank you!


问:
How to redirect to home page(in jsx) after logout in react
```<code><li>
    <a href="homepage.jsx">
      <i className="fa fa-sign-out pull-right"></i>
      Log Out
    </a>
</li>
</code>```

I am having homepage component in homepage.jsx, after clicking on logout i need to go to homepage component.

Help me in this.

答:
You are using react-router, so instead of using a and href use Link, write it like this:

```<code><li>
    <Link to="/">
        <i className="fa fa-sign-out pull-right"></i>
        Log Out
    </Link>
</li>
</code>```

Since Homepage component is your indexroute, so navigation to / will render it.

If you want to navigate dynamically means inside any function, then check this answer:

Programmatically navigating in React-Router v4

Body:
      Log Out

I am having homepage component in homepage.jsx, after clicking on logout i need to go to homepage component.

Help me in this.

Body:
You are using react-router, so instead of using a and href use Link, write it like this:

<li>
    <Link to="/">
        <i className="fa fa-sign-out pull-right"></i>
        Log Out
    </Link>
</li>

Since Homepage component is your indexroute, so navigation to / will render it.

If you want to navigate dynamically means inside any function, then check this answer:

Programmatically navigating in React-Router v4


问:
Angular - how to concat var name
I just started to learn Angular, and I tried to make concat var name so I can control it dynamically.

This is what I tried -

```<code><div ng-app="myApp" ng-controller="myCtrl">

<button ng-click="myFunc(1)">Click Me!</button>

<div ng-show="showMe1">
    <h1>Menu:</h1>
    <div>Pizza</div>
    <div>Pasta</div>
    <div>Pesce</div>
</div>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.showMe1 = false;
    $scope.myFunc = function(x) {
        var nametocng = 'showMe'+x;
        //var nametocng = $parse("showMe"+x);  // - I tried this also
        $scope.nametocng = !$scope.nametocng;
    }
});
</script>
</code>```

答:
Try using this

you have keep condition on click and check against concat string

Js code

```<code>    var app = angular.module('myApp', []);

    app.controller('ctrl', function($scope) {
      $scope.showMe1 = false;
      $scope.nametocng = 'showMe1';
      $scope.myFunc = function(x) {
        var nametocng = 'showMe' + x;
        $scope.showMe1 = $scope.nametocng === nametocng; // result will bool
      }
    });
</code>```

HTML

```<code>    <div ng-app='myApp'>
      <div ng-controller='ctrl'>
        <button ng-click="myFunc(1)">Click Me!</button>
        {{showMe1}} {{nametocng}}
        <div ng-show="showMe1">
          <h1>Menu:</h1>
          <div>Pizza</div>
          <div>Pasta</div>
          <div>Pesce</div>
        </div>
      </div>
    </div>
</code>```

Jsfiddle link

Title: Angular - how to concat var name

Body:
I just started to learn Angular, and I tried to make concat var name so I can control it dynamically.

This is what I tried -

<button ng-click="myFunc(1)">Click Me!</button>

Menu:

Pizza

Pasta

Pesce

Body:
Try using this

you have keep condition on click and check against concat string

Js code

    var app = angular.module('myApp', []);

    app.controller('ctrl', function($scope) {
      $scope.showMe1 = false;
      $scope.nametocng = 'showMe1';
      $scope.myFunc = function(x) {
        var nametocng = 'showMe' + x;
        $scope.showMe1 = $scope.nametocng === nametocng; // result will bool
      }
    });

HTML

    <div ng-app='myApp'>
      <div ng-controller='ctrl'>
        <button ng-click="myFunc(1)">Click Me!</button>
        {{showMe1}} {{nametocng}}
        <div ng-show="showMe1">
          <h1>Menu:</h1>
          <div>Pizza</div>
          <div>Pasta</div>
          <div>Pesce</div>
        </div>
      </div>
    </div>

Jsfiddle link


问:
Is there any library available in Xamarin forms for Token Input view?
I want multiple strings to be added and  deleted in a view. I can achieve this by using native libraries.

Native iOS: CLTokenInputView-Swift-master

Native android: TokenAutoComplete-master

I want to implement this in Xamarin forms for both iOS and android. Is there any way to achieve this? Or any library files available?

答: I think what you are looking for is something like the TagEntryView. It may not do everything you want but it is open-source so maybe you could get the important parts out of there and customize it as you like.


问:
Cannot read property of undefined when using interpolation
I have put an effort before asking this question to search and make sure this question is not duplicated, but I didn't find anything similar to my issue.

I am newbie to Angular 2, and my component class is like below:

import {Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

@Component({
 selector: 'pm-products',
 templateUrl: 'app/products/product-list.component.html'
})

export class ProductListComponent{
pageTitle: string = 'Product List';
products: any[] = [
    {
        "productId": 1,
        "productName": "Leaf Rake",
        "productCode": "GDN-0011",
        "releaseDate": "March 19, 2016",
        "description": "Leaf rake with 48-inch wooden handle.",
        "price": 19.95,
        "starRating": 3.2,
        "imageUrl": "SOME URL"
    },
    {
        "productId": 2,
        "productName": "Garden Cart",
        "productCode": "GDN-0023",
        "releaseDate": "March 18, 2016",
        "description": "15 gallon capacity rolling garden cart",
        "price": 32.99,
        "starRating": 4.2,
        "imageUrl": "SOME URL"
    }

    ];
}
```

<p>And below code is my view:</p>

<pre class="lang-js prettyprint-override"><code><div class='table-responsive'>
    <table class='table'
        *ngIf='products && products.length'>
        <thead>
            <tr>
                <th>
                    <button class='btn btn-primary'>
                        Show Image
                    </button>
                </th>

                <th>Product</th>
                <th>Code</th>
                <th>Available</th>
                <th>Price</th>
                <th>5 Star Rating</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor='let product of products'></tr>
            <td></td>
            <td>{{ product.productName }}</td>
            <td>{{ product.productCode }}</td>
            <td>{{ product.releaseDate }}</td>
            <td>{{ product.price }}</td>
            <td>{{ product.starRating }}</td>

        </tbody>
    </table>

</div>
</code>```

When I run this code I get an error saying "Error in app/products/product-list.component.html:38:16 caused by: Cannot read property 'productName' of undefined", and "Cannot read property 'productName' of undefined"

Using the interpolation in my view, my expectation is to see the products object properties values within the  tags.

答:
The only issue with your code is

```<code><tr *ngFor='let product of products'></tr>
<td></td>
<td>{{ product.productName }}</td>
<td>{{ product.productCode }}</td>
<td>{{ product.releaseDate }}</td>
<td>{{ product.price }}</td>
<td>{{ product.starRating }}</td>
-------------------------------------------
<tr *ngFor='let product of products'></tr>
</code>```

Here you are looping through tr tag , so td tag will never get any value of product , because of that you are getting error of

```<code>"Error in app/products/product-list.component.html:38:16 caused by: Cannot read property 'productName' of undefined", and "Cannot read property 'productName' of undefined"
</code>```

If you will inspect element and check the output you will get ,

And there is no need of using any "Elvis operator" , as you are already providing data via component and before view loaded.

Last code should be like

```<code><tr *ngFor='let product of products'>
    <td></td>
    <td>{{ product.productId }}</td>
    <td>{{ product.productCode }}</td>
    <td>{{ product.releaseDate }}</td>
    <td>{{ product.price }}</td>
    <td>{{ product.starRating }}</td>
</tr>
</code>```

Body:
I have put an effort before asking this question to search and make sure this question is not duplicated, but I didn't find anything similar to my issue.

I am newbie to Angular 2, and my component class is like below:

import {Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

@Component({
 selector: 'pm-products',
 templateUrl: 'app/products/product-list.component.html'
})

export class ProductListComponent{
pageTitle: string = 'Product List';
products: any[] = [
    {
        "productId": 1,
        "productName": "Leaf Rake",
        "productCode": "GDN-0011",
        "releaseDate": "March 19, 2016",
        "description": "Leaf rake with 48-inch wooden handle.",
        "price": 19.95,
        "starRating": 3.2,
        "imageUrl": "SOME URL"
    },
    {
        "productId": 2,
        "productName": "Garden Cart",
        "productCode": "GDN-0023",
        "releaseDate": "March 18, 2016",
        "description": "15 gallon capacity rolling garden cart",
        "price": 32.99,
        "starRating": 4.2,
        "imageUrl": "SOME URL"
    }

    ];
}

And below code is my view:

                    <button class='btn btn-primary'>
                        Show Image
                    </button>

                Product
                Code
                Available
                Price
                5 Star Rating

            {{ product.productName }}
            {{ product.productCode }}
            {{ product.releaseDate }}
            {{ product.price }}
            {{ product.starRating }}

When I run this code I get an error saying "Error in app/products/product-list.component.html:38:16 caused by: Cannot read property 'productName' of undefined", and "Cannot read property 'productName' of undefined"

Using the interpolation in my view, my expectation is to see the products object properties values within the  tags.

Body:
The only issue with your code is

<tr *ngFor='let product of products'></tr>
<td></td>
<td>{{ product.productName }}</td>
<td>{{ product.productCode }}</td>
<td>{{ product.releaseDate }}</td>
<td>{{ product.price }}</td>
<td>{{ product.starRating }}</td>
-------------------------------------------
<tr *ngFor='let product of products'></tr>

Here you are looping through tr tag , so td tag will never get any value of product , because of that you are getting error of

"Error in app/products/product-list.component.html:38:16 caused by: Cannot read property 'productName' of undefined", and "Cannot read property 'productName' of undefined"

If you will inspect element and check the output you will get ,

And there is no need of using any "Elvis operator" , as you are already providing data via component and before view loaded.

Last code should be like

<tr *ngFor='let product of products'>
    <td></td>
    <td>{{ product.productId }}</td>
    <td>{{ product.productCode }}</td>
    <td>{{ product.releaseDate }}</td>
    <td>{{ product.price }}</td>
    <td>{{ product.starRating }}</td>
</tr>


问:
C Pointers about the different data type
Pointer always stores a integer value i.e address so why do we need to declare them with different data type.

Like

```<code>int a=3,*p=&a;
char c=r,*cha=&r;
</code>```

why can't we do like

```<code>int *c;
char r=a;
c=&r;
</code>```

答: To pass to the "user" of the pointer information about what kind of data the pointer points to. Basing on that it will/may depend how the pointed data will be interpreted and handled. Any time you can use a pointer to void, in this case that information is not available. Then, the user of that pointer should know from other sources what is pointed and how to work with it.</p>

Body:
Pointer always stores a integer value i.e address so why do we need to declare them with different data type.

Like

int a=3,*p=&a;
char c=r,*cha=&r;

why can't we do like

int *c;
char r=a;
c=&r;


问:
Update when pulling down the screen | ANDROID
Does anyone know how to code it to update the information from the Internet in my app with pulling down the screen?
Like this

Thanks for answering!

答:
Here is example implemantation :

```<code><android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/container_items"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:background="@color/white"
        >

        <ListView
            android:id="@+id/list_recent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />

    </android.support.v4.widget.SwipeRefreshLayout>
</code>```

Then in your class on create :

```<code>        mItemsContainer = (SwipeRefreshLayout) findViewById(R.id.container_items);
    mItemsContainer.setOnRefreshListener(this);
</code>```

then some where in class :

```<code>   @Override
    public void onRefresh() {

       // after refresh code
    }
</code>```

Body:
Here is example implemantation :

<android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/container_items"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:background="@color/white"
        >

        <ListView
            android:id="@+id/list_recent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />

    </android.support.v4.widget.SwipeRefreshLayout>

Then in your class on create :

        mItemsContainer = (SwipeRefreshLayout) findViewById(R.id.container_items);
    mItemsContainer.setOnRefreshListener(this);

then some where in class :

   @Override
    public void onRefresh() {

       // after refresh code
    }


问:
Spring Rest Error: Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING
I am using rest services with spring data . when i get data from single table its return proper result in json format . but when i use many to many association between entities using hibernate i am getting an un acceptable result with following error in chrome's console .

```<code>Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING
</code>```

My result looks like there just one row repeating itself , and its a particularly that field which is being used in new generated table by association.

```<code>[{"id":7,"name":"Milk pack","description":"haleeb","imageUrl":"milk.jpg","price":350.00,"category":null,"orderDetail":[]},{"id":8,"name":"oil","description":"olive oil ","imageUrl":"/resources/uploads/olive.png","price":670.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design ","imageUrl":"/static/uploads","price":34569.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design ","imageUrl":"/static/uploads","price":34569.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design ","imageUrl":"/static/uploads","price":34569.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design
.
.
.and so on
</code>```

My entities are following

Product table

```<code>@ManyToMany(mappedBy = "productlist")
private List<OrderDetail> orderDetail =new ArrayList<OrderDetail>();
</code>```

OrderDetail table

```<code>@ManyToMany
@JoinTable(
        name="order_detail_productlist",
        joinColumns=@JoinColumn(name="order_detail_id", referencedColumnName="id"),
        inverseJoinColumns=@JoinColumn(name="productlist_id", referencedColumnName="id"))
private Set<Product> productlist = new HashSet<Product>();
</code>```

I am using spring data jpa repository to get them

```<code>List<Product> findAll();
</code>```

Note: which products those are not ordered yet that are working properly

答:
My Problem is solved by using jackson 2.0 documentation

by Adding following annotation or OrderDetail table

```<code>@JsonBackReference
</code>```

it breaks loop and show result properly

Body:
I am using rest services with spring data . when i get data from single table its return proper result in json format . but when i use many to many association between entities using hibernate i am getting an un acceptable result with following error in chrome's console .

Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING

My result looks like there just one row repeating itself , and its a particularly that field which is being used in new generated table by association.

[{"id":7,"name":"Milk pack","description":"haleeb","imageUrl":"milk.jpg","price":350.00,"category":null,"orderDetail":[]},{"id":8,"name":"oil","description":"olive oil ","imageUrl":"/resources/uploads/olive.png","price":670.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design ","imageUrl":"/static/uploads","price":34569.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design ","imageUrl":"/static/uploads","price":34569.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design ","imageUrl":"/static/uploads","price":34569.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design
.
.
.and so on

My entities are following

Product table

@ManyToMany(mappedBy = "productlist")
private List<OrderDetail> orderDetail =new ArrayList<OrderDetail>();

OrderDetail table

@ManyToMany
@JoinTable(
        name="order_detail_productlist",
        joinColumns=@JoinColumn(name="order_detail_id", referencedColumnName="id"),
        inverseJoinColumns=@JoinColumn(name="productlist_id", referencedColumnName="id"))
private Set<Product> productlist = new HashSet<Product>();

I am using spring data jpa repository to get them

List<Product> findAll();

Note: which products those are not ordered yet that are working properly

Body:
My Problem is solved by using jackson 2.0 documentation

by Adding following annotation or OrderDetail table

@JsonBackReference

it breaks loop and show result properly


问:
How to programmatically maximize JDesktopPane
I am using JDesktopPane, and I want it to be maximized when I load it. How can I do it?</p>

答:
Set the encompassing container's layout to BorderLayout and add the JDesktopPane to the CENTER. Then set the window to maximized.</p>

```<code>JFrame f = new JFrame();
f.setLayout(new BorderLayout());
JDesktopPane jDesktopPane = new JDesktopPane();
f.add(jDesktopPane, BorderLayout.CENTER);
...
f.setExtendedState(MAXIMIZED_BOTH);
</code>```

Body:
Set the encompassing container's layout to BorderLayout and add the JDesktopPane to the CENTER. Then set the window to maximized.

JFrame f = new JFrame();
f.setLayout(new BorderLayout());
JDesktopPane jDesktopPane = new JDesktopPane();
f.add(jDesktopPane, BorderLayout.CENTER);
...
f.setExtendedState(MAXIMIZED_BOTH);


问:
Dictionary doesn't throw exception for nonexistent key
I have

```<code>CurrentAppSimulator.LicenseInformation.ProductLicenses["nonexistentEntry"]
</code>```

(MSDN)

and it doesn't throw an exception.

Is that expected? Will it always do that?

答:
As I mentioned in comments:

LicenseInformation.ProductLicenses is not a Dictionary. According to documentataion it is IReadOnlyDictionary.

I didn't find information about its behaviour or implementation, but if check it in runtime you can find out that it is System.__ComObject:System.MarshalByRefObject. It mean that it is definitely not a Dictionary.

It is better to check an existence of a key before accessing it, because there is no certainty that behaviour will not change in future.

Body:
I have

CurrentAppSimulator.LicenseInformation.ProductLicenses["nonexistentEntry"]

(MSDN)

and it doesn't throw an exception.

Is that expected? Will it always do that?


问:
Javascript not working on localhost, but it is working on Live site
I am facing JavaScript problems on XAMPP Localhost. The Collapse Buttons, go to top button and jQuery news feed are not working on every site on my localhost.

But Facebook, Twitter, Plusone buttons load correctly from remote server i.e. from the respective Social Sites.

So, I think it narrows me to the point that the JavaScript files hosted locally are not executed while those from Facebook etc. are getting executed.

I tried reinstalling XAMPP but didn't work.

答:
I know this post is old and the answer is already given, I just wanted to give an answer of a possible reason that I encountered in case someone else finds this and it does not help.

Make sure your entire html code gets executed by viewing your page source. With me, half my code was not being executed due to a PHP error that was working on localhost with the local database but not on live with the live database. This caused the HTML to cut of from that point above my javascript.

So check your page source. If it is being cut of somewhere, find out why :)


问:
Return anonymous type results?
Using the simple example below, what is the best way to return results from multiple tables using Linq to SQL?

Say I have two tables:

```<code>Dogs:   Name, Age, BreedId
Breeds: BreedId, BreedName
</code>```

I want to return all dogs with their BreedName.  I should get all dogs using something like this with no problems:

```<code>public IQueryable<Dog> GetDogs()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select d;
    return result;
}
</code>```

But if I want dogs with breeds and try this I have problems:

```<code>public IQueryable<Dog> GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                        {
                            Name = d.Name,
                            BreedName = b.BreedName
                        };
    return result;
}
</code>```

Now I realize that the compiler won't let me return a set of anonymous types since it's expecting Dogs, but is there a way to return this without having to create a custom type?  Or do I have to create my own class for DogsWithBreedNames and specify that type in the select?  Or is there another easier way?

答:
In C# 7 you can now use tuples!... which eliminates the need to create a class just to return the result.

Here is a sample code:

```<code>public List<(string Name, string BreedName)> GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
             join b in db.Breeds on d.BreedId equals b.BreedId
             select new
             {
                Name = d.Name,
                BreedName = b.BreedName
             }.ToList();

    return result.Select(r => (r.Name, r.BreedName)).ToList();
}
</code>```

You might need to install System.ValueTuple nuget package though.

OwnerDisplayName: Jonathan S.

Title: Return anonymous type results?

Body:
Using the simple example below, what is the best way to return results from multiple tables using Linq to SQL?

Say I have two tables:

Dogs:   Name, Age, BreedId
Breeds: BreedId, BreedName

I want to return all dogs with their BreedName.  I should get all dogs using something like this with no problems:

public IQueryable<Dog> GetDogs()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select d;
    return result;
}

But if I want dogs with breeds and try this I have problems:

public IQueryable<Dog> GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                        {
                            Name = d.Name,
                            BreedName = b.BreedName
                        };
    return result;
}

Now I realize that the compiler won't let me return a set of anonymous types since it's expecting Dogs, but is there a way to return this without having to create a custom type?  Or do I have to create my own class for DogsWithBreedNames and specify that type in the select?  Or is there another easier way?

Body:
In C# 7 you can now use tuples!... which eliminates the need to create a class just to return the result.

Here is a sample code:

public List<(string Name, string BreedName)> GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
             join b in db.Breeds on d.BreedId equals b.BreedId
             select new
             {
                Name = d.Name,
                BreedName = b.BreedName
             }.ToList();

    return result.Select(r => (r.Name, r.BreedName)).ToList();
}

You might need to install System.ValueTuple nuget package though.


问:
I am getting error while working with relation in stimulsoft report
Error is : Additional information: Parent Data Source 'EmpDetails' and
Child Data Source 'SalaryDetails' is not located in one DataSet and
can't be used in relation 'EmpSal'! You can use property CacheAllData of
report to cache this Data Source to one DataSet.

```<code> public class Employeedetails
 {
    public string EmployeeName { get; set; }
    public string JoiningDate { get; set; }
    public string Designation { get; set; }
    public string Department { get; set; }
    public string Nationality { get; set; }
    public string Status { get; set; }
    public string ContractType { get; set; }
    public string LastWorkingDate { get; set; }
    public string LengthofService { get; set; }
    public string ReasonforExit { get; set; }
    public int EmployeeId { get; set; }
}

public class EmployeeSalaryDetails
{
    public int EmployeeId { get; set; }
    public string AllowanceName { get; set; }
    public string Amount { get; set; }
}

report.CacheAllData = true;
report.Load(Server.MapPath("~/Content/Reports/ReportTemplates/FinalSettlementReport - Copy.mrt"));
report.RegData("EmpDetails", EmployeeDetailsList);
report.RegData("SalaryDetails", EmployeeSalaryList);
</code>```

this is report designin in stimulsoft

答:
report.CacheAllData = true;

report.Load(Server.MapPath("~/Content/Reports/ReportTemplates/FinalSettlementReport - Copy.mrt"));

//Use this.

report.Compile();

report.RegData("EmpDetails", EmployeeDetailsList);
report.RegData("SalaryDetails", EmployeeSalaryList);

Body:
Error is : Additional information: Parent Data Source 'EmpDetails' and
Child Data Source 'SalaryDetails' is not located in one DataSet and
can't be used in relation 'EmpSal'! You can use property CacheAllData of
report to cache this Data Source to one DataSet.

 public class Employeedetails
 {
    public string EmployeeName { get; set; }
    public string JoiningDate { get; set; }
    public string Designation { get; set; }
    public string Department { get; set; }
    public string Nationality { get; set; }
    public string Status { get; set; }
    public string ContractType { get; set; }
    public string LastWorkingDate { get; set; }
    public string LengthofService { get; set; }
    public string ReasonforExit { get; set; }
    public int EmployeeId { get; set; }
}

public class EmployeeSalaryDetails
{
    public int EmployeeId { get; set; }
    public string AllowanceName { get; set; }
    public string Amount { get; set; }
}

report.CacheAllData = true;
report.Load(Server.MapPath("~/Content/Reports/ReportTemplates/FinalSettlementReport - Copy.mrt"));
report.RegData("EmpDetails", EmployeeDetailsList);
report.RegData("SalaryDetails", EmployeeSalaryList);

this is report designin in stimulsoft


问:
Why element of Java Hash map overrides the previous elements?
Suppose in Hash map of java collections has already a pair 0,"Ram" and I add a new pair 0,"Sham" with same key. I knew it override the value and at last we get the 0,"Sham" in hash set.
My Questions is Why "Sham" i.e newer element override the "Ram" i.e. previous element? Is there any function to stop this overriding or I should use if-else conditions to make a check on it?</p>

答:
You can write your own put method using delegation technique, if any value already present in map, ignore the calling of put and returns false status.

```<code>boolean putIfNotPresent(Map map, Object key, Object value){
    if(map.get(key)==null){
        map.put(key, value);
        return true;
    }else{
        return false;
    }
}
</code>```

Why value is overridden by default :

Its all about use case of functionality. Java implemented the most common use-case. And there are options for any specific use-case .

Body:
You can write your own put method using delegation technique, if any value already present in map, ignore the calling of put and returns false status.

boolean putIfNotPresent(Map map, Object key, Object value){
    if(map.get(key)==null){
        map.put(key, value);
        return true;
    }else{
        return false;
    }
}

Why value is overridden by default :

Its all about use case of functionality. Java implemented the most common use-case. And there are options for any specific use-case .


问:
javascript focus search form on keydown ? (question mark)
How do I focus search form input field when these two keys are pressed using Javascript?

shift + / will generate the ?

So basically, on keydown for question mark, the search form gets autofocus.

Here is my current bootstrap 3 search form code:

```<code><form class="navbar-form navbar-right" role="form" method="post" action="{$WEB_ROOT}/knowledgebase.php?action=search">
    <div class="form-group">
        <input id="inputMessage" class="form-control" placeholder="Search website.com" type="text" name="search">
    </div>
    <button type="submit" class="btn btn-default"></button>
</form>
</code>```

答:
This work. You have to use the event e.shiftKey with the keycode of the / button (I used 219 because it's the ? position in the italian keyboard layout)

$(document).on('keydown', function(e){
  if(e.shiftKey && e.keyCode == 219)
  {
    $("#search").focus();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search"></code>```

Body:
How do I focus search form input field when these two keys are pressed using Javascript?

shift + / will generate the ?

So basically, on keydown for question mark, the search form gets autofocus.

Here is my current bootstrap 3 search form code:

<form class="navbar-form navbar-right" role="form" method="post" action="{$WEB_ROOT}/knowledgebase.php?action=search">

        <input id="inputMessage" class="form-control" placeholder="Search website.com" type="text" name="search">

    <button type="submit" class="btn btn-default"></button>
</form>

Body:
This work. You have to use the event e.shiftKey with the keycode of the / button (I used 219 because it's the ? position in the italian keyboard layout)

$(document).on('keydown', function(e){
  if(e.shiftKey && e.keyCode == 219)
  {
    $("#search").focus();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search">


问:
jquery autocomplete does not work for rerendered textfields
Im having a problem getting jequery autocomplete to work for rerendered textfields.

I have a a4j:commandlink to show some more inputfields in my form, when this is clicked I reRender an outer a4j:outputpanel to reRender the contents. But to my surprise, the jQuery autocomplete event is never fired for a reRendered textfield I have. It is working as expected before the reRender. The textfield gets autocomplete based on its id, from google maps like this:

```<code>jQuery(document).ready(function(){
    jQuery("#createActivityAddressInputId").autocomplete({
    //This bit uses the geocoder to fetch address values
    ...
});
}

<a4j:outputPanel id="createActivityPanel">
    ...
    <h:inputText id="#{GUIComponentIds.createActivityAddressInputId}" value="#"
        {activityRequestBean.newActivityAddress}" />
    <a4j:commandLink value="#{msg.createActivityShowmapLabel}"
        oncomplete="onShowMapPanel()" action="#{activityRequestBean.showMapClicked}"
        rendered="#{!activityRequestBean.showMap}"
        reRender="createActivityMapPanel,createActivityPanel" />
    ...
</a4j:outputPanel>
</code>```

I was thinking that this maybe had something to do with the autocomplete event is hooked up on document load, or am I way off here?

Thanks!

答:
You need to execute your jQuery after the element has been reRendered. Or you can try to bind jQuery event on every element even if added to the DOM later than jQuery(document).ready().

edit:
changed the live method call
edit:
removed code example because it was just wrong

Body:
Im having a problem getting jequery autocomplete to work for rerendered textfields.

I have a a4j:commandlink to show some more inputfields in my form, when this is clicked I reRender an outer a4j:outputpanel to reRender the contents. But to my surprise, the jQuery autocomplete event is never fired for a reRendered textfield I have. It is working as expected before the reRender. The textfield gets autocomplete based on its id, from google maps like this:

jQuery(document).ready(function(){
    jQuery("#createActivityAddressInputId").autocomplete({
    //This bit uses the geocoder to fetch address values
    ...
});
}

<a4j:outputPanel id="createActivityPanel">
    ...
    <h:inputText id="#{GUIComponentIds.createActivityAddressInputId}" value="#"
        {activityRequestBean.newActivityAddress}" />
    <a4j:commandLink value="#{msg.createActivityShowmapLabel}"
        oncomplete="onShowMapPanel()" action="#{activityRequestBean.showMapClicked}"
        rendered="#{!activityRequestBean.showMap}"
        reRender="createActivityMapPanel,createActivityPanel" />
    ...
</a4j:outputPanel>

I was thinking that this maybe had something to do with the autocomplete event is hooked up on document load, or am I way off here?

Thanks!


问:
OR operator with query builder in mongoose.js
How do I do an 'OR' operator with query builder in Mongoose?

I tried something like this: Find a user by ID or Username
but it didn't work.

```<code>User.findOne({})
      .where( '_id', 'username').equals(param)
</code>```

答:
My solution

```<code>// Needed to user ObjectID comparison
const { ObjectID } = require('mongodb');

// Check if param is a valid ID otherwise is Username
let id_or_username = ObjectID.isValid(id) ? '_id' : 'username';

// Find post by ID or Username
Home
  .findOne({})
  .where(id_or_shortid).equals(id)
  .exec(callback)
</code>```

Body:
How do I do an 'OR' operator with query builder in Mongoose?

I tried something like this: Find a user by ID or Username
but it didn't work.

User.findOne({})
      .where( '_id', 'username').equals(param)

Body:
My solution

// Needed to user ObjectID comparison
const { ObjectID } = require('mongodb');

// Check if param is a valid ID otherwise is Username
let id_or_username = ObjectID.isValid(id) ? '_id' : 'username';

// Find post by ID or Username
Home
  .findOne({})
  .where(id_or_shortid).equals(id)
  .exec(callback)


问:
how to convert this code to use lambda and stream api
how can we use lambda and stream api in this scenario</p>

```<code>Map<String, Integer> map = new LinkedHashMap<>();
BufferedReader br = new BufferedReader(new FileReader(new File(("test.txt"))));
String line = ""; String[] words;
while((line = br.readLine()) != null){
    words = line.split(" ");
    for(String word : words){
        if(map.containsKey(word)){
            map.put(word, map.get(word)+1);
        }else{
             map.put(word, 1);
        }
    }
}
System.out.println(map);
</code>```

答:
You can refer the below code starting with bufferedReader.stream() and follow the inline comments:

```<code>Map<String, Integer> map = new LinkedHashMap<>();
BufferedReader br = new BufferedReader(new FileReader(new File(("test.txt"))));

br.lines()//get stream from BufferedReader
  .map(line -> line.split(" "))//split lines to array
  .flatMap(stream -> Arrays.stream(stream))//convert array to stream
  .collect(Collectors.toMap( s -> s, s -> 1,Integer::sum ));//collect stream to Map
</code>```

Body:
how can we use lambda and stream api in this scenario

Map<String, Integer> map = new LinkedHashMap<>();
BufferedReader br = new BufferedReader(new FileReader(new File(("test.txt"))));
String line = ""; String[] words;
while((line = br.readLine()) != null){
    words = line.split(" ");
    for(String word : words){
        if(map.containsKey(word)){
            map.put(word, map.get(word)+1);
        }else{
             map.put(word, 1);
        }
    }
}
System.out.println(map);

Body:
You can refer the below code starting with bufferedReader.stream() and follow the inline comments:

Map<String, Integer> map = new LinkedHashMap<>();
BufferedReader br = new BufferedReader(new FileReader(new File(("test.txt"))));

br.lines()//get stream from BufferedReader
  .map(line -> line.split(" "))//split lines to array
  .flatMap(stream -> Arrays.stream(stream))//convert array to stream
  .collect(Collectors.toMap( s -> s, s -> 1,Integer::sum ));//collect stream to Map


问:
HtmlUnit, how to check if every asset was loaded?
I am using HtmlUnit for integration-testing.

In HtmlUnit, there is WebResponse::getStatusCode() for accessing HTTP_STATUS_CODE of currently loaded page. Let's say, my Page is "about" google.com, statusCode will be 200, usually.

I am wondering, if it is possible with HtmlUnit to check, if all required assets (*.css, *.js) were loaded successfully (200 <= statusCode < [300|400]).

In my use case, my tested page works fine - but a .css-file is missing, so the layout is broken. I would like to assert in my test-case, that each required assert can be loaded.

答:
You can intercept all communication and store information about all assets.

Something like:

```<code>new WebConnectionWrapper(webClient) {

    public WebResponse getResponse(WebRequest request) throws IOException {
        WebResponse response = super.getResponse(request);

        URL url = request.getUrl();
        int status = response.getStatusCode();
        // store the status

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

Body:
You can intercept all communication and store information about all assets.

Something like:

new WebConnectionWrapper(webClient) {

    public WebResponse getResponse(WebRequest request) throws IOException {
        WebResponse response = super.getResponse(request);

        URL url = request.getUrl();
        int status = response.getStatusCode();
        // store the status

        return response;
    }
};


问:
Create variable with many types in swift3
I have a struct and in this struct I have variable that I want to be of any type UITextField of UIButton. I think I can use generics somehow.
So, my code looks like this

```<code>private struct ValidationObject {
    var textField: RITextFieldLine
        ...
}
</code>```

textField variable with type RITextFieldLine is my custom view. But I don't want it to be of this specific type.

答:
I would suggest that you use a protocol to define Validateable.  You can then apply this protocol to any required class via an extension:

```<code>protocol Validateable {}

extension UITextField: Validateable {}

extension UIButton: Validateable {}

extension AnyOtherTypeYouLike: Validateable {}
</code>```

Then you can use it in your struct

```<code>private struct ValidationObject {
   var validationItem: Validateable
    ...
}
</code>```

You can also use the protocol to define any functions that should be implemented by a Validateable object and the extension to implement them.

Body:
I have a struct and in this struct I have variable that I want to be of any type UITextField of UIButton. I think I can use generics somehow.
So, my code looks like this

private struct ValidationObject {
    var textField: RITextFieldLine
        ...
}

textField variable with type RITextFieldLine is my custom view. But I don't want it to be of this specific type.

Body:
I would suggest that you use a protocol to define Validateable.  You can then apply this protocol to any required class via an extension:

protocol Validateable {}

extension UITextField: Validateable {}

extension UIButton: Validateable {}

extension AnyOtherTypeYouLike: Validateable {}

Then you can use it in your struct

private struct ValidationObject {
   var validationItem: Validateable
    ...
}

You can also use the protocol to define any functions that should be implemented by a Validateable object and the extension to implement them.


问:
RGB average of circles
I'm using OpenCV and PIL in Python. I have 96 circles detected with their center coordinates and radios. I need the average RGB from each circles.

Each circle has 6000 pixels, so I thinks iterate one to one it is not efficient.

How can I extract the average RGB from each circle?
I am ready to use any other library if it suits my use-case.

答:
You can use openCV library

load your image

create masks for the circles (How to Mask an image using Numpy/OpenCV?)

compute mean color for each circle (mean_val = cv2.mean(im,mask = mask))

All of these steps is supported by openCV.

Title: RGB average of circles


问:
How can I refer a column of a Datatable by range and not by header name in C#
I have passed the information of an excel file into a datatable.
I have to select only a part of the columns to take action. But four of the columns have the same header name so I cant refer to them by the header name.

Ex. Data|Name|Service|extra|extra|extra|extra.

I cant change the headers name because the excel file is a report generated automatically from a program. Till now for other functions i was selecting the columns like this:

```<code>DataTable dt = xls.ReadExcel(file);
dt = dt.SelectColumns(false, "Date", "Transaction ID", "Service ID", "Service",);
</code>```

The SelectColumns method is:

```<code>public static DataTable SelectColumns(this DataTable dt, bool distinct, params string[] filters)
        {
            DataView dv = new DataView(dt);
            DataTable newdt = dv.ToTable(distinct, filters);
            return newdt;
        }
</code>```

答:
Modify your extension method to accept integers and filter out the columns that are not specified. You must iterate the collection "right to left", because it changes while iterating. This also means that you should enter the params in the correct order (from left to right, meaning smallest first) to ensure correct filtering. Other way would be to order the params collection within the extension method.

Also remember that the columns use a zero-based index, so the first column is 0, not 1.

This worked with quick tests.

```<code>public static DataTable SelectColumns(this DataTable dt, params int[] filters)
{
    for (int i = dt.Columns.Count - 1; i >= 0; i--)
    {
        DataColumn c = dt.Columns[i];
        if (!filters.Contains(c.Ordinal))
        {
            dt.Columns.Remove(c);
        }
    }
    return dt;
}
</code>```

Body:
I have passed the information of an excel file into a datatable.
I have to select only a part of the columns to take action. But four of the columns have the same header name so I cant refer to them by the header name.

Ex. Data|Name|Service|extra|extra|extra|extra.

I cant change the headers name because the excel file is a report generated automatically from a program. Till now for other functions i was selecting the columns like this:

DataTable dt = xls.ReadExcel(file);
dt = dt.SelectColumns(false, "Date", "Transaction ID", "Service ID", "Service",);

The SelectColumns method is:

public static DataTable SelectColumns(this DataTable dt, bool distinct, params string[] filters)
        {
            DataView dv = new DataView(dt);
            DataTable newdt = dv.ToTable(distinct, filters);
            return newdt;
        }

Body:
Modify your extension method to accept integers and filter out the columns that are not specified. You must iterate the collection "right to left", because it changes while iterating. This also means that you should enter the params in the correct order (from left to right, meaning smallest first) to ensure correct filtering. Other way would be to order the params collection within the extension method.

Also remember that the columns use a zero-based index, so the first column is 0, not 1.

This worked with quick tests.

public static DataTable SelectColumns(this DataTable dt, params int[] filters)
{
    for (int i = dt.Columns.Count - 1; i >= 0; i--)
    {
        DataColumn c = dt.Columns[i];
        if (!filters.Contains(c.Ordinal))
        {
            dt.Columns.Remove(c);
        }
    }
    return dt;
}


问:
Get Max() rows per Revision Number in LinQ
I have this result set:

```<code>Company_ID | State | City | Rev |
Company 1  |  S-A  |  C-1 |  1  |
Company 2  |  S-B  |  C-2 |  1  |
Company 1  |  S-A  |  C-3 |  2  |
</code>```

The result set that I wanted is

```<code>Company_ID | State | City | Rev |
Company 1  |  S-A  |  C-3 |  2  |
Company 2  |  S-B  |  C-2 |  1  |
</code>```

Here's the query that I tried:

```<code>var list = (from coy in TBL_COMPANY
where coy.IsActive == "1"
select coy).ToList()
.Select(coy => new
{
  coy.Company_ID,
  coy.State,
  coy.City,
  coy.Rev
});

var companyList = list.GroupBy (grp => new
{
   grp.Company_ID,
   grp.State,
   grp.City
})
.Select(cpy => new
{
   CompanyID = cpy.Key.Company_ID,
   State = cpy.Key.State,
   City = cpy.Key.City,
   Rev = cpy.Max(c => c.Rev)
}).ToList();
</code>```

However, I am not able to get the result set I wanted. My suspicion there is because of the City because it is included. However, I need these columns (except for the Rev). Is there any way to do this?

答:
The required result doesn't fit you grouping. There are 3 different City items which should lead to 3 result items.

I'd say Jon Skeet's comment about Grouping only by Company_ID is correct.

Code (group by Company_ID and pick the items with the highest Rev):

```<code>var result = TBL_COMPANY.Where(x => x.IsActive == "1")
                        .GroupBy(x => x.Company_ID)
                        .Select(x => x.OrderByDescending(y => y.Rev).First())
                        .Select(x=> new {x.Company_ID,  x.State,  x.City,  x.Rev})
                        .ToList();
</code>```

Body:
I have this result set:

Company_ID | State | City | Rev |
Company 1  |  S-A  |  C-1 |  1  |
Company 2  |  S-B  |  C-2 |  1  |
Company 1  |  S-A  |  C-3 |  2  |

The result set that I wanted is

Company_ID | State | City | Rev |
Company 1  |  S-A  |  C-3 |  2  |
Company 2  |  S-B  |  C-2 |  1  |

Here's the query that I tried:

var list = (from coy in TBL_COMPANY
where coy.IsActive == "1"
select coy).ToList()
.Select(coy => new
{
  coy.Company_ID,
  coy.State,
  coy.City,
  coy.Rev
});

var companyList = list.GroupBy (grp => new
{
   grp.Company_ID,
   grp.State,
   grp.City
})
.Select(cpy => new
{
   CompanyID = cpy.Key.Company_ID,
   State = cpy.Key.State,
   City = cpy.Key.City,
   Rev = cpy.Max(c => c.Rev)
}).ToList();

However, I am not able to get the result set I wanted. My suspicion there is because of the City because it is included. However, I need these columns (except for the Rev). Is there any way to do this?

Body:
The required result doesn't fit you grouping. There are 3 different City items which should lead to 3 result items.

I'd say Jon Skeet's comment about Grouping only by Company_ID is correct.

Code (group by Company_ID and pick the items with the highest Rev):

var result = TBL_COMPANY.Where(x => x.IsActive == "1")
                        .GroupBy(x => x.Company_ID)
                        .Select(x => x.OrderByDescending(y => y.Rev).First())
                        .Select(x=> new {x.Company_ID,  x.State,  x.City,  x.Rev})
                        .ToList();


问:
iOS Loading Custom Annotations
I've built an app that displays facilities and users on the map. Both, facility and users are custom annotations (I've extended MKPointAnnotation). I've also enabled callouts, left and right callout accessory views for both the types of annotations. The geo and other meta data for these objects are loaded from my Parse database in background. I have seen a recommendation in many places that says you should load all the annotations in viewDidLoad(). While that seems reasonable, I am wondering if that's the right approach where I want to quickly load and display what's in user's current region.

My current approach is this: load a set of annotations in viewDidLoad()based on user's current location. In my regionDidChange method for the MapView delegate, I perform search, remove all annotations and add them again. This largely works but occasionally I get facility's accessory views assigned to user's annotation. I've checked everything several times it seems to be related to timing and happens when user pans the map while annotations are being added/displayed. It doesn't happen in the debugger. I suspect that's to do with I'm reloading the annotations when user changes his/her region.

I would like to get some feedback on if I'm fundamentally loading the annotations incorrectly and how should I model it to dynamically load/display annotation as user moves the location, or pans on the map. I've seen Redfin loading properties as user pans the map, though I don't know if they have multiple types of custom annotations.

Thank you for all the help!

Rajesh

答: http://swift3devlopment.blogspot.in/ here have some stuff that you actually need..</p>

Title: iOS Loading Custom Annotations


问:
Check if value is available in a list or not along with available value
In SQL Server 2008, I have table with records like these,

```<code>Name
----
John
Amy
Peter
Jack
Alan
Linda
</code>```

I have another list of user ('John', 'Adam', 'Amy', 'Frank')
How do I check that which user in list is in table and not, without creating temp table

Expected output table

```<code>Name   Available
----   ---------
John   John
Adam   Null
Amy    Amy
Frank  Null
</code>```

答:
Assuming you are on SQL Server 2008 you can use row constructors to avoid having to explicitly create a temp table.

Using EXISTS rather than an OUTER JOIN might be more efficient if there can be duplicates of names in your base table (it can stop the seek as soon as the first matching record is found for a name).

```<code>SELECT name,
       CASE
              WHEN EXISTS
                     (SELECT *
                     FROM    yourtable t
                     WHERE   t.name = names.name
                     )
              THEN names.name
       END AS Available
FROM   (VALUES
       ('John'), ( 'Adam'),( 'Amy'), ('Frank') ) names (name)
</code>```

Body:
In SQL Server 2008, I have table with records like these,

Name
----
John
Amy
Peter
Jack
Alan
Linda

I have another list of user ('John', 'Adam', 'Amy', 'Frank')
How do I check that which user in list is in table and not, without creating temp table

Expected output table

Name   Available
----   ---------
John   John
Adam   Null
Amy    Amy
Frank  Null

Body:
Assuming you are on SQL Server 2008 you can use row constructors to avoid having to explicitly create a temp table.

Using EXISTS rather than an OUTER JOIN might be more efficient if there can be duplicates of names in your base table (it can stop the seek as soon as the first matching record is found for a name).

SELECT name,
       CASE
              WHEN EXISTS
                     (SELECT *
                     FROM    yourtable t
                     WHERE   t.name = names.name
                     )
              THEN names.name
       END AS Available
FROM   (VALUES
       ('John'), ( 'Adam'),( 'Amy'), ('Frank') ) names (name)


问:
How to use Angular 2 server side rendering
I have developed a parser for my angular2 components which renders them in my HTML file.
So far I am able to render them in HTML as

```<code>import {Component} from 'angular2/core';
import {NgSwitch, NgSwitchWhen, NgSwitchDefault,NgFor} from 'angular2/common';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';

@Component({
    selector: 'app',
    template: `
            <div>
                <div>
                    <img src={{record}} class="pull-left image-responsive" style="width:50%;">
                    <img src={{record}} class="pull-right image-responsive" style="width:30%;">
                </div>
                <div>
                    <img src={{record}} class="pull-right image-responsive" style="width:100%;">
                </div>
                <br/><br/>
                <div>
                    <table class="table-responsive" style="width:100%;border-collapse:separate;border:solid #D8D8D8 2px;border-radius:5px;">
                        <tr style="background-color: grey;">
                            <th style="text-align:center;">{{record}}</th>
                            <th style="border-left:2px solid #f5821f;text-align:center;">{{record}}</th>
                        </tr>
                        <tr style="text-align:center;">
                            <td > </td>
                            <td style="border-left:2px solid #f5821f;"> </td>
                        </tr>
                    </table>
                </div>
                <br/>
             </div>
           `
 })
export class App{
    public record;
    constructor() {
        this.record="angular2";
    }
}
</code>```

Then my static HTML gets generated correctly,But If I am using my component like this:

```<code>import {Component} from 'angular2/core';
import {NgSwitch, NgSwitchWhen, NgSwitchDefault,NgFor} from 'angular2/common';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import {Component1} from './component_1/component_1.component';
import {Component2} from './component_2/component_2.component';

@Component({
    selector: 'app',
    directives: [Component1,Component2],
    template: `
        <div class="container">
            <div class="row">
                <component_1>loading...</component_1>
            </div>
            <div class="row">
                <component_2>loading...</component_2>
            </div>
        </div>
    `
 })
export class App{
    public record;
    constructor() {
        this.record="angular2";
    }
}
</code>```

Then my components are loaded in HTML correctly,but my Static HTML is not generated correctly.
See the images below:
Components are loaded in browser

But static HTML is not generated correctly
console window for static HTML

Server.ts

import * as path from 'path';
import * as express from 'express';
import * as universal from 'angular2-universal-preview';
// Angular 2
import {App} from './app/app.component'
let app = express();
let root = path.join(path.resolve(__dirname, '..'));

// Express View
app.engine('.ng2.html', universal.ng2engine);
app.set('views', __dirname);
app.set('view engine', 'ng2.html');

// Serve static files
app.use(express.static(root));
var i = 0;
// Routes

app.use('/', (req, res) => {
  res.render('index_new', {App}, function(err,html){
      console.log("------------------My HTML ---------\n"+(i++));
      console.log(html);
      console.log("------------------My HTML ----------");
      res.send(html);
  });
});

// Server
app.listen(3000, () => {
  console.log('Listen on http://localhost:3000');
});```
</div>
</div>
</p>

<p><strong>index_new.ng2.html</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">

<head>
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <link href="\node_modules\bootstrap\dist\css\bootstrap.min.css" rel="stylesheet" />
    <link href="\node_modules\bootstrap\dist\css\style.css" rel="stylesheet" />
    <script src="/node_modules/es6-shim/es6-shim.js"></script>
    <script src="/node_modules/es6-promise/dist/es6-promise.js"></script>
    <script src="/node_modules/reflect-metadata/Reflect.js"></script>
    <script src="/node_modules/zone.js/dist/zone-microtask.js"></script>
    <script src="/node_modules/zone.js/dist/long-stack-trace-zone.js"></script>
    <script src="/dist/client/bundle.js"></script>
</head>
<body>
    <app>Loading....</app>
</body>
</html></code>```

I tried the updated git Hub repository of @alexpods
Thanks in advance.

答:
Have a look on this example app that I deployed recently (https://github.com/ng-seed/universal)

Pros:

Server side rendering

SCSS compilation

Lazy/async routes

Development/Production (AoT) compilation

SPA/Universal modes

TsLint/Codelyzer

Up-to-date dependencies (Angular 4, platform-server, etc)

Modern stack (webpack, karma, protractor)

Body:
I have developed a parser for my angular2 components which renders them in my HTML file.
So far I am able to render them in HTML as

import {Component} from 'angular2/core';
import {NgSwitch, NgSwitchWhen, NgSwitchDefault,NgFor} from 'angular2/common';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';

@Component({
    selector: 'app',
    template: `

                            {{record}}
                            {{record}}

           `
 })
export class App{
    public record;
    constructor() {
        this.record="angular2";
    }
}

Then my static HTML gets generated correctly,But If I am using my component like this:

import {Component} from 'angular2/core';
import {NgSwitch, NgSwitchWhen, NgSwitchDefault,NgFor} from 'angular2/common';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import {Component1} from './component_1/component_1.component';
import {Component2} from './component_2/component_2.component';

@Component({
    selector: 'app',
    directives: [Component1,Component2],
    template: `

                <component_1>loading...</component_1>

                <component_2>loading...</component_2>

    `
 })
export class App{
    public record;
    constructor() {
        this.record="angular2";
    }
}

Then my components are loaded in HTML correctly,but my Static HTML is not generated correctly.
See the images below:
Components are loaded in browser

But static HTML is not generated correctly
console window for static HTML

Server.ts

import * as path from 'path';
import * as express from 'express';
import * as universal from 'angular2-universal-preview';
// Angular 2
import {App} from './app/app.component'
let app = express();
let root = path.join(path.resolve(__dirname, '..'));

// Express View
app.engine('.ng2.html', universal.ng2engine);
app.set('views', __dirname);
app.set('view engine', 'ng2.html');

// Serve static files
app.use(express.static(root));
var i = 0;
// Routes

app.use('/', (req, res) => {
  res.render('index_new', {App}, function(err,html){
      console.log("------------------My HTML ---------\n"+(i++));
      console.log(html);
      console.log("------------------My HTML ----------");
      res.send(html);
  });
});

// Server
app.listen(3000, () => {
  console.log('Listen on http://localhost:3000');
});

index_new.ng2.html

<!doctype html>

    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <link href="\node_modules\bootstrap\dist\css\bootstrap.min.css" rel="stylesheet" />
    <link href="\node_modules\bootstrap\dist\css\style.css" rel="stylesheet" />

    <app>Loading....</app>

I tried the updated git Hub repository of @alexpods
Thanks in advance.


问:
Calculate marginal probabilities from dataframe in R
I would like to calculate the marginal probability distributions from a dataframe containing raw binary data. I'm sure there is an easy way, however I can not seem to find a function for it. Any ideas?
I'm attaching a simple example of a dataframe of binary variables where an outcome can be considered as one and no outcome as 0.</p>

```<code>set.seed(1234)
respondent <- 1:1000
red <- sample(0:1, 1000, replace=T)
blue <- sample(0:1, 1000, replace=T)
green <- sample(0:1, 1000, replace=T)
black <- sample(0:1, 1000, replace=T)
grey <- sample(0:1, 1000, replace=T)

my.new.df <- data.frame(respondent, red ,blue,green,black,grey)
lapply(my.new.df[,2:6],sum)
$red
[1] 518

$blue
[1] 485

$green
[1] 515

$black
[1] 481

$grey
[1] 508
</code>```

答:
You can use:

```<code>colMeans(my.new.df[,2:6])
</code>```

Or as @moto said and you were trying (but more simple):

```<code>lapply(my.new.df[,2:6], function(x) mean(x))
</code>```

Body:
I would like to calculate the marginal probability distributions from a dataframe containing raw binary data. I'm sure there is an easy way, however I can not seem to find a function for it. Any ideas?
I'm attaching a simple example of a dataframe of binary variables where an outcome can be considered as one and no outcome as 0.

set.seed(1234)
respondent <- 1:1000
red <- sample(0:1, 1000, replace=T)
blue <- sample(0:1, 1000, replace=T)
green <- sample(0:1, 1000, replace=T)
black <- sample(0:1, 1000, replace=T)
grey <- sample(0:1, 1000, replace=T)

my.new.df <- data.frame(respondent, red ,blue,green,black,grey)
lapply(my.new.df[,2:6],sum)
$red
[1] 518

$blue
[1] 485

$green
[1] 515

$black
[1] 481

$grey
[1] 508

Body:
You can use:

colMeans(my.new.df[,2:6])

Or as @moto said and you were trying (but more simple):

lapply(my.new.df[,2:6], function(x) mean(x))


问:
java.lang.LinkageError: loader constraint violation for javax.xml.xpath.XPath.setNamespaceContext
```<code>import javax.xml.namespace.NamespaceContext;
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(some code goes here)
</code>```

I use javax.xml.namespace.NamespaceContext in my web app and when deployed on jboss server, it gives out following error:

```<code>javax.servlet.ServletException: java.lang.LinkageError: loader constraint violation: when resolving interface method "javax.xml.xpath.XPath.setNamespaceContext(Ljavax/xml/namespace/NamespaceContext;)V" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the current class, com/accenture/mdh/sso/util/Util, and the class loader (instance of <bootloader>) for resolved class, javax/xml/xpath/XPath, have different Class objects for the type )V used in the signature
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:852)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
    org.apache.jsp.jsp.LoginConsumer_jsp._jspService(LoginConsumer_jsp.java:187)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:322)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:249)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
</code>```

I searched through the internet and it seems like there is conflicting jars with javax.xml.namespace.NamespaceContext in WEB-INF/lib. However, I am still unable to find the cause. Really appreciate your thoughts.

答:
Excluding below libraries which had the same package name of javax.xml.namespace.NamespaceContext resolved the issue.

stax-api.jar

javax.xml.stream_1.0.1.v201004272200.jar

Body:
import javax.xml.namespace.NamespaceContext;
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(some code goes here)

I use javax.xml.namespace.NamespaceContext in my web app and when deployed on jboss server, it gives out following error:

javax.servlet.ServletException: java.lang.LinkageError: loader constraint violation: when resolving interface method "javax.xml.xpath.XPath.setNamespaceContext(Ljavax/xml/namespace/NamespaceContext;)V" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the current class, com/accenture/mdh/sso/util/Util, and the class loader (instance of <bootloader>) for resolved class, javax/xml/xpath/XPath, have different Class objects for the type )V used in the signature
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:852)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
    org.apache.jsp.jsp.LoginConsumer_jsp._jspService(LoginConsumer_jsp.java:187)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:322)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:249)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)

I searched through the internet and it seems like there is conflicting jars with javax.xml.namespace.NamespaceContext in WEB-INF/lib. However, I am still unable to find the cause. Really appreciate your thoughts.


问:
How to setup the Pre-Chat form for Live Agent in Salesforce?
I am newbie to the salesforce and working on the Live Agent setup and its other useful features. Now I am looking to implement the Pre-Chat form, but I dont see the option to choose form. I see the below, Could you please guide what setting needs to be done ?

I have created a custom VF page and now I want to choose that form. But I dont see that option. I created the Pre-chart form using : https://developer.salesforce.com/docs/atlas.en-us.live_agent_dev.meta/live_agent_dev/live_agent_pre_chat_forms_code_sample.htm

答:
For that we need to register the site for your own force.com site like below and then only you will be able to see the

And Now you will be able to see


问:
Django: Model Form "object has no attribute 'cleaned_data'"
I am trying to make a search form for one of my classes. The model of the form is:

```<code>from django import forms
from django.forms import CharField, ModelMultipleChoiceField, ModelChoiceField
from books.models import Book, Author, Category

class SearchForm(forms.ModelForm):
    authors = ModelMultipleChoiceField(queryset=Author.objects.all(),required=False)
    category = ModelChoiceField (queryset=Category.objects.all(),required=False)
    class Meta:
        model = Book
        fields = ["title"]
</code>```

And the view I'm using is:

```<code>from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from books.models import Book,Author
from books.forms import BookForm, SearchForm
from users.models import User

def search_book(request):
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            form = SearchForm(request.POST)
            stitle = form.cleaned_data['title']
            sauthor = form.cleaned_data['author']
            scategory = form.cleaned_data['category']
    else:
        form = SearchForm()
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))
</code>```

The form shows up fine, but when I submit it I get an error: 'SearchForm' object has no attribute 'cleaned_data'

I'm not sure what's going on, can someone help me out? Thanks!

答:
I would write the code like this:

```<code>def search_book(request):
    form = SearchForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        stitle = form.cleaned_data['title']
        sauthor = form.cleaned_data['author']
        scategory = form.cleaned_data['category']
        return HttpResponseRedirect('/thanks/')
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))
</code>```

Pretty much like the documentation.

Body:
I am trying to make a search form for one of my classes. The model of the form is:

from django import forms
from django.forms import CharField, ModelMultipleChoiceField, ModelChoiceField
from books.models import Book, Author, Category

class SearchForm(forms.ModelForm):
    authors = ModelMultipleChoiceField(queryset=Author.objects.all(),required=False)
    category = ModelChoiceField (queryset=Category.objects.all(),required=False)
    class Meta:
        model = Book
        fields = ["title"]

And the view I'm using is:

from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from books.models import Book,Author
from books.forms import BookForm, SearchForm
from users.models import User

def search_book(request):
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            form = SearchForm(request.POST)
            stitle = form.cleaned_data['title']
            sauthor = form.cleaned_data['author']
            scategory = form.cleaned_data['category']
    else:
        form = SearchForm()
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

The form shows up fine, but when I submit it I get an error: 'SearchForm' object has no attribute 'cleaned_data'

I'm not sure what's going on, can someone help me out? Thanks!

Body:
I would write the code like this:

def search_book(request):
    form = SearchForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        stitle = form.cleaned_data['title']
        sauthor = form.cleaned_data['author']
        scategory = form.cleaned_data['category']
        return HttpResponseRedirect('/thanks/')
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

Pretty much like the documentation.


问:
Display image in PHP (Laravel)
I'm trying to display a png image in PHP (Laravel)

So far I've tried

```<code>$response =  Response::make(readfile(public_path() .
"/img/$image_name.png", 200))->header('Content-Type', 'image/png');
return $response;
</code>```

and this

```<code>$file = public_path() . "/img/$image_name.png";
$im = imagecreatefrompng($file);
header('Content-Type: image/png');
imagePNG($im);
imagedestroy($im);
</code>```

I always get something like this instead of an actual image

```<code>�PNG  IHDR:�c PLTE����>tRNS�* �< pHYs���+uIDAT(�eұ� AJs *́[P૒��@8Ҍ��Y�:����s�A�"D�!B�"D�!B�"D�!C~����}��Q��N�+'��bP�.a&^O)%5Y\�L����.ޜ9��IEND�B`�
</code>```

When I use jpeg header and jpeg image it starts showing the actual image in browser, but for some reason it doesn't work for png images. Have anyone faced a similar problem?

答:
You should find the mime dynamicaly using laravel default file facade File::mimeType($path) because as you mentioned that it is working fine with another image type like jpeg. I think this may happen because sometime we change file extension for testing or may be file have some issue with its header etc. You can use the following code :

Method 1 use Response::stream:

```<code>$path = public_path() . "/img/$image_name.png";
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::stream(function() use($file) {
  echo $file;
}, 200, ["Content-Type"=> $type]);
</code>```

Method 2 use Response::make:

```<code>$path = public_path() . "/img/$image_name.png";
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
</code>```

Hope it will help.

Title: Display image in PHP (Laravel)

Body:
I'm trying to display a png image in PHP (Laravel)

So far I've tried

$response =  Response::make(readfile(public_path() .
"/img/$image_name.png", 200))->header('Content-Type', 'image/png');
return $response;

and this

$file = public_path() . "/img/$image_name.png";
$im = imagecreatefrompng($file);
header('Content-Type: image/png');
imagePNG($im);
imagedestroy($im);

I always get something like this instead of an actual image

�PNG  IHDR:�c PLTE����>tRNS�* �< pHYs���+uIDAT(�eұ� AJs *́[P૒��@8Ҍ��Y�:����s�A�"D�!B�"D�!B�"D�!C~����}��Q��N�+'��bP�.a&^O)%5Y\�L����.ޜ9��IEND�B`�

When I use jpeg header and jpeg image it starts showing the actual image in browser, but for some reason it doesn't work for png images. Have anyone faced a similar problem?

Body:
You should find the mime dynamicaly using laravel default file facade File::mimeType($path) because as you mentioned that it is working fine with another image type like jpeg. I think this may happen because sometime we change file extension for testing or may be file have some issue with its header etc. You can use the following code :

Method 1 use Response::stream:

$path = public_path() . "/img/$image_name.png";
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::stream(function() use($file) {
  echo $file;
}, 200, ["Content-Type"=> $type]);

Method 2 use Response::make:

$path = public_path() . "/img/$image_name.png";
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;

Hope it will help.


问:
How to require specific version of macOS?
For example: My Xcode project deployment target can be iOS 10.3 — Is there an equivalent to require macOS 10.12.4? (Latest SDK)

• iOS 10.3 is the latest update (can be targeted in Xcode).

• macOS 10.12.4 is the latest update

My goal/hope is to target the latest macOS update in the same way I can target the latest iOS update.

Verdict: It’s not (yet?) possible in Xcode. :(

答:
Can't you select such an option when you set your deployment target?

The page linked to also states:

Xcode sets the Minimum System Version key in the app’s information
  property list to the deployment target you choose. When you publish
  your app to the store, it uses this property value to indicate which
  versions your app supports.

So you might change it by adapting the information property list as well I presume..


问:
jquery autocomplete does not work for rerendered textfields
Im having a problem getting jequery autocomplete to work for rerendered textfields.

I have a a4j:commandlink to show some more inputfields in my form, when this is clicked I reRender an outer a4j:outputpanel to reRender the contents. But to my surprise, the jQuery autocomplete event is never fired for a reRendered textfield I have. It is working as expected before the reRender. The textfield gets autocomplete based on its id, from google maps like this:

```<code>jQuery(document).ready(function(){
    jQuery("#createActivityAddressInputId").autocomplete({
    //This bit uses the geocoder to fetch address values
    ...
});
}

<a4j:outputPanel id="createActivityPanel">
    ...
    <h:inputText id="#{GUIComponentIds.createActivityAddressInputId}" value="#"
        {activityRequestBean.newActivityAddress}" />
    <a4j:commandLink value="#{msg.createActivityShowmapLabel}"
        oncomplete="onShowMapPanel()" action="#{activityRequestBean.showMapClicked}"
        rendered="#{!activityRequestBean.showMap}"
        reRender="createActivityMapPanel,createActivityPanel" />
    ...
</a4j:outputPanel>
</code>```

I was thinking that this maybe had something to do with the autocomplete event is hooked up on document load, or am I way off here?

Thanks!

答:
Yes; you will need to re-attach the autocomplete by calling the same method every time you re-render. (Presumably you would cache the options that you pass to autocomplete.)

Something like:

```<code>var autocompleteOptions = null;
$(function ()
{
   autocompleteOptions = getFromGeocoder();
});

function onReRender()
{
   $("#createActivityAddressInputId").autocomplete(autocompleteOptions);
}
</code>```

Then call onReRender whenever you rerender the control.

Body:
Im having a problem getting jequery autocomplete to work for rerendered textfields.

I have a a4j:commandlink to show some more inputfields in my form, when this is clicked I reRender an outer a4j:outputpanel to reRender the contents. But to my surprise, the jQuery autocomplete event is never fired for a reRendered textfield I have. It is working as expected before the reRender. The textfield gets autocomplete based on its id, from google maps like this:

jQuery(document).ready(function(){
    jQuery("#createActivityAddressInputId").autocomplete({
    //This bit uses the geocoder to fetch address values
    ...
});
}

<a4j:outputPanel id="createActivityPanel">
    ...
    <h:inputText id="#{GUIComponentIds.createActivityAddressInputId}" value="#"
        {activityRequestBean.newActivityAddress}" />
    <a4j:commandLink value="#{msg.createActivityShowmapLabel}"
        oncomplete="onShowMapPanel()" action="#{activityRequestBean.showMapClicked}"
        rendered="#{!activityRequestBean.showMap}"
        reRender="createActivityMapPanel,createActivityPanel" />
    ...
</a4j:outputPanel>

I was thinking that this maybe had something to do with the autocomplete event is hooked up on document load, or am I way off here?

Thanks!

Body:
Yes; you will need to re-attach the autocomplete by calling the same method every time you re-render. (Presumably you would cache the options that you pass to autocomplete.)

Something like:

var autocompleteOptions = null;
$(function ()
{
   autocompleteOptions = getFromGeocoder();
});

function onReRender()
{
   $("#createActivityAddressInputId").autocomplete(autocompleteOptions);
}

Then call onReRender whenever you rerender the control.


问:
What is the css property for showing the ... when there is overflow-x?
The property overflow-x shows scrollbar when the content exceeds the parent's width. I do not want to show the scrollbar but instead show the three dots "..." How to achieve that ?

答:
```<code>overflow: hidden;
text-overflow: ellipsis;
</code>```

This should do the trick.

Body:
overflow: hidden;
text-overflow: ellipsis;

This should do the trick.


问:
Opening tsv file via Notepad++ and save it in text format
I'm trying to automate a process that where in a folder there are 50+ tsv files. They have to be opened via notepad++ and save it as .txt file in the same folder.

Using the below code i'm opening the tsv file in notepad++.

```<code>MyTxtFile = Shell("C:\Program Files (x86)\Notepad++\notepad++.exe I:\Test\Sample.tsv", 1)
</code>```

However, i have no idea how to save it as txt file by using VBA. Is it doable? If yes kindly teach me how.

Thank you in advance :)

答:
There is another thread which touched upon the general aspect of calling shell commands. Maybe it can be of help to you:
Execute a command in command prompt using excel VBA</p>

Body:
I'm trying to automate a process that where in a folder there are 50+ tsv files. They have to be opened via notepad++ and save it as .txt file in the same folder.

Using the below code i'm opening the tsv file in notepad++.

MyTxtFile = Shell("C:\Program Files (x86)\Notepad++\notepad++.exe I:\Test\Sample.tsv", 1)

However, i have no idea how to save it as txt file by using VBA. Is it doable? If yes kindly teach me how.

Thank you in advance :)