问:
How to do sync my events with Google Calendar after Google Sign in
I'm performing a demo for syncing my events with Google calendar from a event adding form. I have completed login with Google but now I'm not able to sync with Google Calendar. Its giving me 401 error. help me out please
Here is my code help would be appreciate thanks :)

scheduler

```<code><script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
    function onSignIn(googleUser) {
        var profile = googleUser.getBasicProfile();
        console.log(profile);
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
        $('#email').val(profile.getEmail());
    }
$('#addScheduler').click(function (e) {
            var error = '';
            var email=$('#email').val();
            var pkShareProfileId=$('#pkShareProfileId').val();
            var profileName=$('#profileName').val();
            var startDate=$('#startDate').val();
            var endDate=$('#endDate').val();
            var description=$('#description').val();
$.ajax({
                    url: 'schedulerAjax.php',
                    type: 'POST',
                    data: {'pkShareProfileId': pkShareProfileId, 'profileName':profileName, 'startDate':startDate, 'endDate': endDate, 'description': description, 'email': email},
                    dataType:'json',
                    success: showResponse
                });
}
 </script>
<form method="POST" id="addSchedulerForm" name="addSchedulerForm" enctype="multipart/form-data">
        <div class="row">
            <p id="errorMsg"></p>
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                <input type="hidden" id="pkShareProfileId" name="pkShareProfileId">
                <input type="hidden" id="email" name="email">
                <div class="form-group">
                    <div class="checkbox g-signin2"data-onsuccess="onSignIn">
                        Sync With Google Calendar
                    </div>
                </div>
                <div class="form-group">
                    <label for="profileName" class="boxShadowEffect label-basic">Profile Name</label>
                    <input type="text" class="form-control" id="profileName" placeholder="Profile Name"  name="profileName">
                </div>
                <div class="form-group">
                    <label for="startDate" class="boxShadowEffect label-basic">Start Date</label>
                    <input type="text" class="form-control" id="startDate" placeholder="Start Date"  name="startDate">
                    <div class="form-group">
                        <label for="endDate" class="boxShadowEffect label-basic">End Date</label>
                        <input type="text" class="form-control" id="endDate" placeholder="End Date"  name="endDate">
                    </div>
                </div>
                <div class="form-group">
                    <label for="description" class="boxShadowEffect label-basic">Description</label>
                    <textarea style="resize:none;" placeholder="Description" id="description" name="description" class="form-control"></textarea>
                </div>
                <div class="col-xs-10 col-md-12 col-sm-10 col-lg-12">
                    <input type="button" class="btn hidden-xs btn-primary btn-block btn-flat save" name="addScheduler" value="Save" id="addScheduler" >
                </div>
            </div>
        </div>
    </form>
</code>```

SchedulerAjax.php

```<code>require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();

$client->setApplicationName("switchit");
$service = new Google_Service_Calendar($client);
$apiCall = new ApiCall();
if(isset($_POST))
{
  $shareProfileId=$_POST['pkShareProfileId'];
  $profileName=$_POST['profileName'];
  $startDate=$_POST['startDate'];
  $startDate=strtotime($startDate);
  $endDate=$_POST['endDate'];
  $endDate=strtotime($endDate);
  $description=$_POST['description'];
  $email=$_POST['email'];
  if ($email) {
    $event = new Google_Service_Calendar_Event(array(
        'summary' => $profileName,
        'description' => $description,
        'start' => array(
            'dateTime' => '2017-03-28T00:00:00-07:00',
            'timeZone' => 'America/Los_Angeles',
        ),
        'end' => array(
            'dateTime' => '2017-03-29T00:00:00-07:00',
            'timeZone' => 'America/Los_Angeles',
        )
    ));
    $calendarId = 'primary';
    $event = $service->events->insert($calendarId, $event);
}
</code>```

答:
You have not properly authenticated the php client library.  So it doesn't have access to do what you are trying to do.

```<code>$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
</code>```

You might want to try checking the Calendar PHP quickstart tutorial.

I have no idea if its even possible to link Google sign-in (Client login) with PHP (server sided) login.  I seriously doubt it.  You may want to consider dropping PHP and just going with JavaScript see : JavaScript quick start

Body:
I'm performing a demo for syncing my events with Google calendar from a event adding form. I have completed login with Google but now I'm not able to sync with Google Calendar. Its giving me 401 error. help me out please
Here is my code help would be appreciate thanks :)

scheduler

<form method="POST" id="addSchedulerForm" name="addSchedulerForm" enctype="multipart/form-data">

                <input type="hidden" id="pkShareProfileId" name="pkShareProfileId">
                <input type="hidden" id="email" name="email">

                        Sync With Google Calendar

                    Profile Name
                    <input type="text" class="form-control" id="profileName" placeholder="Profile Name"  name="profileName">

                    Start Date
                    <input type="text" class="form-control" id="startDate" placeholder="Start Date"  name="startDate">

                        End Date
                        <input type="text" class="form-control" id="endDate" placeholder="End Date"  name="endDate">

                    Description
                    <textarea style="resize:none;" placeholder="Description" id="description" name="description" class="form-control"></textarea>

                    <input type="button" class="btn hidden-xs btn-primary btn-block btn-flat save" name="addScheduler" value="Save" id="addScheduler" >

    </form>

SchedulerAjax.php

require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();

$client->setApplicationName("switchit");
$service = new Google_Service_Calendar($client);
$apiCall = new ApiCall();
if(isset($_POST))
{
  $shareProfileId=$_POST['pkShareProfileId'];
  $profileName=$_POST['profileName'];
  $startDate=$_POST['startDate'];
  $startDate=strtotime($startDate);
  $endDate=$_POST['endDate'];
  $endDate=strtotime($endDate);
  $description=$_POST['description'];
  $email=$_POST['email'];
  if ($email) {
    $event = new Google_Service_Calendar_Event(array(
        'summary' => $profileName,
        'description' => $description,
        'start' => array(
            'dateTime' => '2017-03-28T00:00:00-07:00',
            'timeZone' => 'America/Los_Angeles',
        ),
        'end' => array(
            'dateTime' => '2017-03-29T00:00:00-07:00',
            'timeZone' => 'America/Los_Angeles',
        )
    ));
    $calendarId = 'primary';
    $event = $service->events->insert($calendarId, $event);
}

Body:
You have not properly authenticated the php client library.  So it doesn't have access to do what you are trying to do.

$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');

You might want to try checking the Calendar PHP quickstart tutorial.

I have no idea if its even possible to link Google sign-in (Client login) with PHP (server sided) login.  I seriously doubt it.  You may want to consider dropping PHP and just going with JavaScript see : JavaScript quick start


来源: stackexchange

问:
Using response from one API call to do another API Call
I'm using AngularJS to build a site where one of the functions is to present Billboard(it's a music chart) listings for a specified date.
I want to present the songs in order, together with an image of the song.

First I'm calling this API:

http://billboard.modulo.site/

where I give a date and get a response of the top 10 songs for that date and data about each song.

The response from the Billboard API also includes a spotify id and I want to use that ID and call the Spotify Web API to get an image of that song, to complement the information I present about each song.

This is how it looks like in my controller:

```<code>var spotifyID = [];
$scope.spotifyImg = [];

musicService.getBillboard($scope.date).then(function(data){ //Response is top 10 songs for given date
        $scope.status = "";
        $scope.songlist = data;
        for (var i = 0; i < data.length; i++) {
            spotifyID[i] = data[i].spotify_id; //data[i].spotify_id returns the ID of the track, as given by the billboard API
        }
        $scope.getImages();
    });

$scope.getImages = function() {
    for (var i = 0; i < spotifyID.length; i++) {
        if(spotifyID[i] !== null) {
            musicService.getSpotify(spotifyID[i]).then(function(data){
                $scope.spotifyImg[i] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API
        });
    }
    }
    console.log($scope.spotifyImg);
}
</code>```

And in my view it would look something like this:

```<code><div ng-repeat = "song in songlist">
    <div>{{ song.rank }}</div>
    <div>
        <img ng-src=" {{ spotifyImg[$index] }}"/>
    </div>
</div>
</code>```

However, it does not work.

When I'm checking the $scope.spotifyImg array in the console, it is of length 11 and only has one element in index 10 and that is the image of the last song(that is the 10th song).

I'm a bit confused as to why the $scope.spotifyImg array only contains one element in index 10. Also why is the array of length 11 when the spotifyID is of length 10?

Any ideas of how I could solve this?

答:
Try using this code

Js code

```<code>  var spotifyID = [];
      $scope.spotifyImg = [];
      musicService.getBillboard($scope.date).then(function(data) { //Response is top 10 songs for given date
        $scope.status = "";
        $scope.songlist = data;
        for (var i = 0; i < data.length; i++) {
          spotifyID[i] = data[i].spotify_id; //data[i].spotify_id returns the ID of the track, as given by the billboard API
        }
        $scope.getImages(0);
      });

      $scope.getImages = function(index) {
        if (index == spotifyID.length) {
          return;
        }

        musicService.getSpotify(spotifyID[index]).then(function(data) {
          $scope.spotifyImg[index] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API

          // call recursive here
          $scope.getImages(index++);

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

call your getimages function recursively so that will add you images in array.

ContentLicense: CC BY-SA 3.0

Body:
I'm using AngularJS to build a site where one of the functions is to present Billboard(it's a music chart) listings for a specified date.
I want to present the songs in order, together with an image of the song.

First I'm calling this API:

http://billboard.modulo.site/

where I give a date and get a response of the top 10 songs for that date and data about each song.

The response from the Billboard API also includes a spotify id and I want to use that ID and call the Spotify Web API to get an image of that song, to complement the information I present about each song.

This is how it looks like in my controller:

var spotifyID = [];
$scope.spotifyImg = [];

musicService.getBillboard($scope.date).then(function(data){ //Response is top 10 songs for given date
        $scope.status = "";
        $scope.songlist = data;
        for (var i = 0; i < data.length; i++) {
            spotifyID[i] = data[i].spotify_id; //data[i].spotify_id returns the ID of the track, as given by the billboard API
        }
        $scope.getImages();
    });

$scope.getImages = function() {
    for (var i = 0; i < spotifyID.length; i++) {
        if(spotifyID[i] !== null) {
            musicService.getSpotify(spotifyID[i]).then(function(data){
                $scope.spotifyImg[i] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API
        });
    }
    }
    console.log($scope.spotifyImg);
}

And in my view it would look something like this:

{{ song.rank }}

However, it does not work.

When I'm checking the $scope.spotifyImg array in the console, it is of length 11 and only has one element in index 10 and that is the image of the last song(that is the 10th song).

I'm a bit confused as to why the $scope.spotifyImg array only contains one element in index 10. Also why is the array of length 11 when the spotifyID is of length 10?

Any ideas of how I could solve this?

Body:
Try using this code

Js code

  var spotifyID = [];
      $scope.spotifyImg = [];
      musicService.getBillboard($scope.date).then(function(data) { //Response is top 10 songs for given date
        $scope.status = "";
        $scope.songlist = data;
        for (var i = 0; i < data.length; i++) {
          spotifyID[i] = data[i].spotify_id; //data[i].spotify_id returns the ID of the track, as given by the billboard API
        }
        $scope.getImages(0);
      });

      $scope.getImages = function(index) {
        if (index == spotifyID.length) {
          return;
        }

        musicService.getSpotify(spotifyID[index]).then(function(data) {
          $scope.spotifyImg[index] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API

          // call recursive here
          $scope.getImages(index++);

        });
      }
    }

call your getimages function recursively so that will add you images in array.


问:
Can I run the service on 443 port in docker UCP ??
I want to run a spring-boot microservice on port number 443.
I am creating this service using docker command

```<code>docker service create -p 443:8443 somerepo/someorg/some-service:v0.1
</code>```

When I fire this command service goes fine, but DTR and UCP go down.
I don't have a complete idea on it but just aware of docker UCP controller run on 443.
My Question is

can I run my microservice as a docker service on port 443 ?

can I change the port number of docker UCP controller to some another port.

Thanks in Advance.

答:
You should check whether port 443 is currently occupied by DTR or UCP, apparently both default to 443.

In case of UCP, according to the reference and this discussion, it is possible to change the UCP port by using the --controller-port flag during installation. This can also be configured in the web interface under Admin Settings -> Cluster Configuration -> Controller Port.

As for DTR, there is the flag --replica-https-port to also move it away from 443.

Once you have moved the competing services, there is nothing that should prevent you from having a container listen to port 443.

Body:
I want to run a spring-boot microservice on port number 443.
I am creating this service using docker command

docker service create -p 443:8443 somerepo/someorg/some-service:v0.1

When I fire this command service goes fine, but DTR and UCP go down.
I don't have a complete idea on it but just aware of docker UCP controller run on 443.
My Question is

can I run my microservice as a docker service on port 443 ?

can I change the port number of docker UCP controller to some another port.

Thanks in Advance.


问:
How to change the class of elements that have matching content
I have:

```<code><div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
<div class="foo">qux</div>
</code>```

And I would like all the elements that contain the same content as the one with a class of "bar" to also have a class of "bar" like so:

```<code><div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="bar">baz</div>
<div class="foo">qux</div>
</code>```

But I can't just search for "baz" because that content is subject to change. Instead I have to figure out what's in the lone "bar" div then find the others that match it and change their class to "bar" too.

I've managed to get the content of the first "bar" element into a variable:

```<code>var = body.css(".bar").first.inner_text
</code>```

But nothing I've tried from there as far as finding the matching content and replacing the class has worked.

答:
Be careful using body.css("div:contains('#{text_to_match}')").

```<code>input = '<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="foo">baza</div>
<div class="foo">qux</div>
<div class="foo">bazfdsfsdf</div>
<div class="foo">qux</div>'
</code>```

The output will be:

```<code><div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="bar">baza</div>
<div class="foo">qux</div>
<div class="bar">bazfdsfsdf</div>
<div class="foo">qux</div>
</code>```

If you want to match the exact same text in both elements, you should use:
body.css("div[text() = '#{text_to_match}']")

```<code>input = '<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="foo">baza</div>
<div class="foo">qux</div>
<div class="foo">bazfdsfsdf</div>
<div class="foo">baz</div>'
</code>```

The output would be:

```<code><div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="foo">baza</div>
<div class="foo">qux</div>
<div class="foo">bazfdsfsdf</div>
<div class="bar">baz</div>
</code>```

Body:
I have:

baz

qux

qux

baz

qux

baz

qux

And I would like all the elements that contain the same content as the one with a class of "bar" to also have a class of "bar" like so:

baz

qux

qux

baz

qux

baz

qux

But I can't just search for "baz" because that content is subject to change. Instead I have to figure out what's in the lone "bar" div then find the others that match it and change their class to "bar" too.

I've managed to get the content of the first "bar" element into a variable:

var = body.css(".bar").first.inner_text

But nothing I've tried from there as far as finding the matching content and replacing the class has worked.

Body:
Be careful using body.css("div:contains('#{text_to_match}')").

input = '<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="foo">baza</div>
<div class="foo">qux</div>
<div class="foo">bazfdsfsdf</div>
<div class="foo">qux</div>'

The output will be:

<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="bar">baza</div>
<div class="foo">qux</div>
<div class="bar">bazfdsfsdf</div>
<div class="foo">qux</div>

If you want to match the exact same text in both elements, you should use:
body.css("div[text() = '#{text_to_match}']")

input = '<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="foo">baza</div>
<div class="foo">qux</div>
<div class="foo">bazfdsfsdf</div>
<div class="foo">baz</div>'

The output would be:

<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="foo">baza</div>
<div class="foo">qux</div>
<div class="foo">bazfdsfsdf</div>
<div class="bar">baz</div>


问:
Does style-v21.xml include everything in v19?
Is the repetition needed or do they override each other?

base

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
</style>
</code>```

v19

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
    <item name="android:windowTranslucentStatus">true</item>
</style>
</code>```

v21

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowAllowEnterTransitionOverlap">true</item>
    <item name="android:windowAllowReturnTransitionOverlap">true</item>
    <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
    <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
</style>
</code>```

答: The repetition is needed since the parent is Theme.AppCompat.Light.NoActionBar in every version and it doesn't include the attribute values you set in other versions.

Body:
Is the repetition needed or do they override each other?

base

v19

v21


问:
how to call jdialog from jinternalframe
Can some one tell me how to call JDialog from a JInternalframe?

```<code>public class BSJFrameUpdateOnlineTrdDlg extends JInternalFrame {

public BSJFrameUpdateOnlineTrdDlg(JDesktopPane jdesk) { //constructor
    super("Backoffice Synchronization");
     jdeskTop = jdesk;
     frame = this;
    try {

      jbInit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    setLocation(400, 200);
    setVisible(true);
    setSize(720, 570);

  }
private void jbInit() throws Exception {
//.......
 jButton1.addActionListener(new jButton1_upload_action());
this.getContentPane().add(jButton1, null);

}

 class jButton1_upload_action implements ActionListener{
    public void actionPerformed(ActionEvent e) {
 displayDialog(frame,marketStatus);
}}

 public void displayDialog(JInternalFrame frame,String status){
     JDialog jdg = new JDialog();
     //this is where the JDIalog get initiated

}
}
</code>```

this is what I'm currently having. I have inserted only most important code lines.

答:
It looks like your already calling it? Are you just trying to make it visible? </p>

```
<code>
public void displayDialog(JInternalFrame frame,String status){
     JDialog jdg = new JDialog();
     //...add the guts of the dialog
     jdg.setVisible(true);
}

</code>
```

ContentLicense: CC BY-SA 2.5

Title: how to call jdialog from jinternalframe

Body:
Can some one tell me how to call JDialog from a JInternalframe?

public class BSJFrameUpdateOnlineTrdDlg extends JInternalFrame {

public BSJFrameUpdateOnlineTrdDlg(JDesktopPane jdesk) { //constructor
    super("Backoffice Synchronization");
     jdeskTop = jdesk;
     frame = this;
    try {

      jbInit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    setLocation(400, 200);
    setVisible(true);
    setSize(720, 570);

  }
private void jbInit() throws Exception {
//.......
 jButton1.addActionListener(new jButton1_upload_action());
this.getContentPane().add(jButton1, null);

}

 class jButton1_upload_action implements ActionListener{
    public void actionPerformed(ActionEvent e) {
 displayDialog(frame,marketStatus);
}}

 public void displayDialog(JInternalFrame frame,String status){
     JDialog jdg = new JDialog();
     //this is where the JDIalog get initiated

}
}

this is what I'm currently having. I have inserted only most important code lines.

Body:
It looks like your already calling it? Are you just trying to make it visible?

public void displayDialog(JInternalFrame frame,String status){
     JDialog jdg = new JDialog();
     //...add the guts of the dialog
     jdg.setVisible(true);
}


问:
How to query Windows Eventlog with a large set of EventIds using c#
I am trying to query the event log with a large set of EventIds with following code

```<code>List<string> eventIds = new List<string>() {

            "4741", "4742", "4743", "4739", "4727", "4728", "4729", "4730", "4731", "4732", "4733", "4734", "4735", "4737", "4754", "4755",
            "4756", "4757", "4758", "4720", "4722", "4723", "4724", "4725", "4726", "4738", "4740", "4765", "4766", "4767", "4780", "4781",

            "4934", "5136", "5137", "5138", "5139", "5141"
        };

        var queryString = string.Format(@"*[System[EventRecordID > {0}]] and *[System[({1})]] ",
            maxEventRecordId,
            string.Join(" or ", eventIds.Select(x => string.Format("EventID={0}", x))));

    var elQuery = new EventLogQuery(LogSource, PathType.LogName, queryString );
    var elReader = new System.Diagnostics.Eventing.Reader.EventLogReader(elQuery);

    List<EventRecord> eventList = new List<EventRecord>();
    for (EventRecord eventInstance = elReader.ReadEvent();
        null != eventInstance; eventInstance = elReader.ReadEvent())
    {
        //Access event properties here:
        //eventInstance.LogName;
        //eventInstance.ProviderName;
        eventList.Add(eventInstance);
    }
</code>```

When I limit the number of EventIds from the queryString I am getting the result. But for this large query I am getting a Query error exception. Is there any other method to pass the large event id sets to Event viewer? Please help

答:
I found an alternative for this. Instead of querying large set of events I have excluded unwanted event ids and query all the data and then iterate the result from .NET to collect only needed information.

```<code>    List<string> excludeEventIds = new List<string>() {
                    /*Skip - Audit Logon Events*/
                    "4634", "4647", "4624", "4625", "4648", "4675", "4649", "4778", "4779", "4800", "4801", "4802", "4803", "5378", "5632", "5633",
                    /*Skip few - Audit direcory service access*/
                    "4935","4936","4932","4933"
                };

                var queryString = string.Format(@"*[System[EventRecordID > {0}]] and *[System[({1})]] ",
                   maxEventRecordId,
                   string.Join(" or ", excludeEventIds.Select(x => string.Format("EventID !={0}", x))));

    EventLogQuery query = new EventLogQuery("Security", PathType.LogName, queryString);
</code>```

And while reading the data we will only take the list of event ids and process.

```<code>List<string> eventIds = new List<string>() {
                /*Audit account management*/
                "4741", "4742", "4743", "4739", "4727", "4728", "4729", "4730", "4731", "4732", "4733", "4734", "4735", "4737", "4754", "4755",
                "4756", "4757", "4758", "4720", "4722", "4723", "4724", "4725", "4726", "4738", "4740", "4765", "4766", "4767", "4780", "4781",
                /*Audit directory service access*/
                "4934", "5136", "5137", "5138", "5139", "5141"
            };

for (EventRecord eventInstance = logReader.ReadEvent();
                null != eventInstance; eventInstance = logReader.ReadEvent())
            {

                if (!eventIds.ToArray().Contains(eventInstance.Id.ToString())) continue;
//Process our actual data here

}
</code>```

Hope this will help somebody.

Body:
I am trying to query the event log with a large set of EventIds with following code

List<string> eventIds = new List<string>() {

            "4741", "4742", "4743", "4739", "4727", "4728", "4729", "4730", "4731", "4732", "4733", "4734", "4735", "4737", "4754", "4755",
            "4756", "4757", "4758", "4720", "4722", "4723", "4724", "4725", "4726", "4738", "4740", "4765", "4766", "4767", "4780", "4781",

            "4934", "5136", "5137", "5138", "5139", "5141"
        };

        var queryString = string.Format(@"*[System[EventRecordID > {0}]] and *[System[({1})]] ",
            maxEventRecordId,
            string.Join(" or ", eventIds.Select(x => string.Format("EventID={0}", x))));

    var elQuery = new EventLogQuery(LogSource, PathType.LogName, queryString );
    var elReader = new System.Diagnostics.Eventing.Reader.EventLogReader(elQuery);

    List<EventRecord> eventList = new List<EventRecord>();
    for (EventRecord eventInstance = elReader.ReadEvent();
        null != eventInstance; eventInstance = elReader.ReadEvent())
    {
        //Access event properties here:
        //eventInstance.LogName;
        //eventInstance.ProviderName;
        eventList.Add(eventInstance);
    }

When I limit the number of EventIds from the queryString I am getting the result. But for this large query I am getting a Query error exception. Is there any other method to pass the large event id sets to Event viewer? Please help

Body:
I found an alternative for this. Instead of querying large set of events I have excluded unwanted event ids and query all the data and then iterate the result from .NET to collect only needed information.

    List<string> excludeEventIds = new List<string>() {
                    /*Skip - Audit Logon Events*/
                    "4634", "4647", "4624", "4625", "4648", "4675", "4649", "4778", "4779", "4800", "4801", "4802", "4803", "5378", "5632", "5633",
                    /*Skip few - Audit direcory service access*/
                    "4935","4936","4932","4933"
                };

                var queryString = string.Format(@"*[System[EventRecordID > {0}]] and *[System[({1})]] ",
                   maxEventRecordId,
                   string.Join(" or ", excludeEventIds.Select(x => string.Format("EventID !={0}", x))));

    EventLogQuery query = new EventLogQuery("Security", PathType.LogName, queryString);

And while reading the data we will only take the list of event ids and process.

List<string> eventIds = new List<string>() {
                /*Audit account management*/
                "4741", "4742", "4743", "4739", "4727", "4728", "4729", "4730", "4731", "4732", "4733", "4734", "4735", "4737", "4754", "4755",
                "4756", "4757", "4758", "4720", "4722", "4723", "4724", "4725", "4726", "4738", "4740", "4765", "4766", "4767", "4780", "4781",
                /*Audit directory service access*/
                "4934", "5136", "5137", "5138", "5139", "5141"
            };

for (EventRecord eventInstance = logReader.ReadEvent();
                null != eventInstance; eventInstance = logReader.ReadEvent())
            {

                if (!eventIds.ToArray().Contains(eventInstance.Id.ToString())) continue;
//Process our actual data here

}

Hope this will help somebody.


问:
Protractor data driven - Is displaying 'undefined' when I try to print JSON file
I'm working with protractor and I'm trying to implement data driven.

I'm using this code that I found searching in google.

This is my test.json

```<code>{
"username":"testusername"
}
</code>```

And i'm calling this json from my spec and trying to print in console:

```<code>var fs = require('fs');
var content = fs.readFileSync('test/e2e/tests/test.json');
console.log(content.username);
</code>```

The test is not failing but in the console is print undefined

enter image description here

I'm missing something? or i'm not implementing well the json?
Hope you can help me.

答:
Try this solution.

On Main spec:

```<code>var testData = require('./Data.json');
describe('...', function() {

    testData.forEach( function (data) {

        var strUser = data.strUser;
        var strPass = data.strPass;

        it('...', function() {
            <code here>
        });

    });

});
</code>```

On Data.json (which is located on same folder as Main spec):

```<code>[{
    "strUser": "user1",
    "strPass": "pass1"
},
{
    "strUser": "user2",
    "strPass": "pass2"
},
{
    "strUser": "user3",
    "strPass": "pass3"
}]
</code>```

Hope it helps :)

Body:
I'm working with protractor and I'm trying to implement data driven.

I'm using this code that I found searching in google.

This is my test.json

{
"username":"testusername"
}

And i'm calling this json from my spec and trying to print in console:

var fs = require('fs');
var content = fs.readFileSync('test/e2e/tests/test.json');
console.log(content.username);

The test is not failing but in the console is print undefined

enter image description here

I'm missing something? or i'm not implementing well the json?
Hope you can help me.

Body:
Try this solution.

On Main spec:

var testData = require('./Data.json');
describe('...', function() {

    testData.forEach( function (data) {

        var strUser = data.strUser;
        var strPass = data.strPass;

        it('...', function() {
            <code here>
        });

    });

});

On Data.json (which is located on same folder as Main spec):

[{
    "strUser": "user1",
    "strPass": "pass1"
},
{
    "strUser": "user2",
    "strPass": "pass2"
},
{
    "strUser": "user3",
    "strPass": "pass3"
}]

Hope it helps :)


问:
How to use a PHP switch statement to check if a string contains a word (but can also contain others)?
I'm using a PHP switch to include certain files based on the incoming keywords passed in a parameter of the page's URL.

The URL, for example, could be: ...page.php?kw=citroen%20berlingo%20keywords

Inside the page, I'd like to use something like this:

```<code><?
    switch($_GET['kw']){

        case "berlingo":
            include 'berlingo.php'
            break;
        case "c4":
            include 'c4.php';
            break;

    }
?>
</code>```

What I want to do in the first case is include the berlingo.php file if the keyword parameter contains berlingo, but it doesn't have to be exactly that keyword alone.

For example, I want to include the berlingo.php file if the keyword is berlingo, but also if it's citroen berlingo.

How can I evaluate if a given string contains a value using a PHP case select (switch statement)?

Thanks.

答:
You can also use regular expression in switch -> case:</p>

```<code><?php

    $kw = filter_input(INPUT_GET, "kw");

    switch($kw){

        case (preg_match('/*berlingo*/', $kw) ? true : false):
            include 'berlingo.php';
            break;

        case "c4":
            include 'c4.php';
            break;

    }
?>
</code>```

Body:
I'm using a PHP switch to include certain files based on the incoming keywords passed in a parameter of the page's URL.

The URL, for example, could be: ...page.php?kw=citroen%20berlingo%20keywords

Inside the page, I'd like to use something like this:

<?
    switch($_GET['kw']){

        case "berlingo":
            include 'berlingo.php'
            break;
        case "c4":
            include 'c4.php';
            break;

    }
?>

What I want to do in the first case is include the berlingo.php file if the keyword parameter contains berlingo, but it doesn't have to be exactly that keyword alone.

For example, I want to include the berlingo.php file if the keyword is berlingo, but also if it's citroen berlingo.

How can I evaluate if a given string contains a value using a PHP case select (switch statement)?

Thanks.

Body:
You can also use regular expression in switch -> case:

<?php

    $kw = filter_input(INPUT_GET, "kw");

    switch($kw){

        case (preg_match('/*berlingo*/', $kw) ? true : false):
            include 'berlingo.php';
            break;

        case "c4":
            include 'c4.php';
            break;

    }
?>


问:
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>```

答:
If I understand your code correctly you are just counting the occurrence of individual words in the file. If that's correct:</p>

```<code>Map<String, Long> wordCount = br.lines()
    .flatMap(l -> Arrays.stream(l.split(" "))
    .collect(groupingBy(w -> w, counting());
</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:
If I understand your code correctly you are just counting the occurrence of individual words in the file. If that's correct:

Map<String, Long> wordCount = br.lines()
    .flatMap(l -> Arrays.stream(l.split(" "))
    .collect(groupingBy(w -> w, counting());


问:
jQuery execute function on each carousel slide one at a time
I am trying to run a function on each carousel slide one at a time for visual effect when each slide is visible (active).

The function adds a class to elements but it does not work on page load or the third slide (classes already added).

Working fine on the second carousel item.

```<code>$('#carousel').on('slide.bs.carousel', function () {
    //console.log('slide event!');

    var arr = $('.carousel-item .text .st0').get();
    setTimeout(function delayMainFunction() {

        function random(arr) {
            if (!arr.length) {
                return;
            }
            var el = arr.splice(Math.floor(Math.random() * arr.length), 1);
            $(el).attr('class', 'st0 transition-state');
            setTimeout(function () {
                random(arr);
            }, 10 + Math.floor(Math.random() * 10))
        }
        random(arr);

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

Should do this transition for each individual slide when visible (active).

Codepen here http://codepen.io/Kerrys7777/pen/VpBvZW

答:
I named your function...

This enables you to call it from anywhere.

So now, you can call it on load, like any other function.

And I added a setTimeout to remove the transition-state class for all letters of the SVG.

Your CodePen updated.

```<code>console.clear();

$( document ).ready(function() {

  // Made it a named function
  var myAnimation = function(){
    console.log('slide event!');

    var arr = $('.carousel-item .text .st0').get();
    setTimeout(function delayMainFunction() {

      function random(arr) {
        if (!arr.length) {
          return;
        }
        var el = arr.splice(Math.floor(Math.random() * arr.length), 1);
        $(el).attr('class', 'st0 transition-state');
        setTimeout(function () {
          random(arr);
        }, 10 + Math.floor(Math.random() * 10))
      }
      random(arr);

      // Added setTimeout to remove the transition-state class from all SVG letters
      setTimeout(function() {
        $('.carousel-item .text .st0').removeClass('transition-state');
      },3500);

    }, 600);
  };

  $('.carousel').carousel({
    interval: 6000,
    pause: false
  })

  // To run on load
  myAnimation();

  // To bind the function the carousel event
  $(".carousel").on('slide.bs.carousel', myAnimation);
});
</code>```

Body:
I am trying to run a function on each carousel slide one at a time for visual effect when each slide is visible (active).

The function adds a class to elements but it does not work on page load or the third slide (classes already added).

Working fine on the second carousel item.

$('#carousel').on('slide.bs.carousel', function () {
    //console.log('slide event!');

    var arr = $('.carousel-item .text .st0').get();
    setTimeout(function delayMainFunction() {

        function random(arr) {
            if (!arr.length) {
                return;
            }
            var el = arr.splice(Math.floor(Math.random() * arr.length), 1);
            $(el).attr('class', 'st0 transition-state');
            setTimeout(function () {
                random(arr);
            }, 10 + Math.floor(Math.random() * 10))
        }
        random(arr);

    }, 600)
});

Should do this transition for each individual slide when visible (active).

Codepen here http://codepen.io/Kerrys7777/pen/VpBvZW

Body:
I named your function...

This enables you to call it from anywhere.

So now, you can call it on load, like any other function.

And I added a setTimeout to remove the transition-state class for all letters of the SVG.

Your CodePen updated.

console.clear();

$( document ).ready(function() {

  // Made it a named function
  var myAnimation = function(){
    console.log('slide event!');

    var arr = $('.carousel-item .text .st0').get();
    setTimeout(function delayMainFunction() {

      function random(arr) {
        if (!arr.length) {
          return;
        }
        var el = arr.splice(Math.floor(Math.random() * arr.length), 1);
        $(el).attr('class', 'st0 transition-state');
        setTimeout(function () {
          random(arr);
        }, 10 + Math.floor(Math.random() * 10))
      }
      random(arr);

      // Added setTimeout to remove the transition-state class from all SVG letters
      setTimeout(function() {
        $('.carousel-item .text .st0').removeClass('transition-state');
      },3500);

    }, 600);
  };

  $('.carousel').carousel({
    interval: 6000,
    pause: false
  })

  // To run on load
  myAnimation();

  // To bind the function the carousel event
  $(".carousel").on('slide.bs.carousel', myAnimation);
});


问:
"Splitting" the output of a RLE (groupby) depending on a defined value ( the "character" to split the RLE on )
Consider the "string" ( treat it as an array of digits )

```<code>0 0 1 8 8 8 1 0
</code>```

The RLE ( "groupby" ) is:

```<code>[(0,2), (1, 1), (8,3), (1, 1), (0, 1)]
</code>```

We then enrich the above RLE with the sum of the run lengths of the previous elements.

Hence, the enriched version of the above becomes:

```<code>[(0, (0,2)), (0+2, (1, 1)), (0+2+1, (8,3)), (0+1+2+3, (1, 1)), (0+1+2+3+1, (0, 1))]
</code>```

The "string" split on 1:

```<code>0 0 , 8 8 8 , 0
</code>```

RLE split on 1

```<code>[(0,2)] , [(8,3)] , [(0, 1)]
</code>```

The "string" split on 8:

```<code>0 0 1 , , , 1 0
</code>```

RLE split on 8

```<code>[(0,2), (1, 1)] , , , [(1, 1), (0, 1)]
</code>```

Note : In my examples, I have cited the "RLE split on Z" lists without enriching them. This would not be so. I left them out to reduce clutter. For example, the "RLE split on 1" should really be treated as:

```<code>[(0, (0,2))] , [(0+2+1, (8,3))] , [(0+1+2+3+1, (0, 1)]
</code>```

How can I achieve this "RLE split" on Z ( = 1, 8; in this case )

It's fine to leave out empty arrays ( after split ).

Perhaps a clever list comp.? ( it seems a little easier to solve with a for loop with an append nested within )

答:
```<code>import itertools

def get_rle(list_of_digits, split_on=None):
    count = 0
    rle = []
    active_group = []
    rle_app = rle.append
    for item, group in itertools.groupby(list_of_digits):
        L = len(list(group))
        if item == split_on:
            rle_app(active_group)
            active_group = []
        else:
            active_group.append((count, (item, L)))
        count += L

    rle_app(active_group)
    return rle

list_of_digits = map(int, '0 0 1 8 8 8 1 0'.split())
print get_rle(list_of_digits)
print get_rle(list_of_digits, 8)
print get_rle(list_of_digits, 1)

aaron@aaron-laptop:~/code/tmp$ python rle.py
[[(0, (0, 2)), (2, (1, 1)), (3, (8, 3)), (6, (1, 1)), (7, (0, 1))]]
[[(0, (0, 2)), (2, (1, 1))], [(6, (1, 1)), (7, (0, 1))]]
[[(0, (0, 2))], [(3, (8, 3))], [(7, (0, 1))]]
</code>```

Body:
Consider the "string" ( treat it as an array of digits )

0 0 1 8 8 8 1 0

The RLE ( "groupby" ) is:

[(0,2), (1, 1), (8,3), (1, 1), (0, 1)]

We then enrich the above RLE with the sum of the run lengths of the previous elements.

Hence, the enriched version of the above becomes:

[(0, (0,2)), (0+2, (1, 1)), (0+2+1, (8,3)), (0+1+2+3, (1, 1)), (0+1+2+3+1, (0, 1))]

The "string" split on 1:

0 0 , 8 8 8 , 0

RLE split on 1

[(0,2)] , [(8,3)] , [(0, 1)]

The "string" split on 8:

0 0 1 , , , 1 0

RLE split on 8

[(0,2), (1, 1)] , , , [(1, 1), (0, 1)]

Note : In my examples, I have cited the "RLE split on Z" lists without enriching them. This would not be so. I left them out to reduce clutter. For example, the "RLE split on 1" should really be treated as:

[(0, (0,2))] , [(0+2+1, (8,3))] , [(0+1+2+3+1, (0, 1)]

How can I achieve this "RLE split" on Z ( = 1, 8; in this case )

It's fine to leave out empty arrays ( after split ).

Perhaps a clever list comp.? ( it seems a little easier to solve with a for loop with an append nested within )


问:
PHP merge and rearrange 2 or more arrays
It will be 2 or more arrays come out from foreach loop. Like following

```<code>array1
    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )

    [1] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

array2
   [0] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [1] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )
</code>```

I want to get same index value from these 2 arrays and merge these array like that.

```<code>**FinalArray = array1[0],array2[0],array1[1],array2[1]**
</code>```

E.g

```<code>FinalArray

    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )
    [1] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [2] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

    [3] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )
</code>```

please help how to get same index values and merge that 2 arrays. Thanks

答:
you may achieve this by only one loop using array_column and array_merge as follows,

```<code>$array1 = array(
    0 => [0 => 1207, 1 => 4, 2 => "haha.mp4"],
    1 => [0 => 1208, 1 => 4, 2 => "hehe.mp4"],
);

$array2 = array(
    0 => [0 => 1209, 1 => 16, 2 => "SampleVideo.mp4"],
    1 => [0 => 1210, 1 => 16, 2 => "295.mp4"],
);

// here I assume that the following array is the output of your foreach loop
$array = [$array1, $array2];
$list = [];
foreach ($array as $key => $value) {
    $list = array_merge($list, array_column($array, $key));
}

print_r($list);
</code>```

live demo: https://3v4l.org/2chf5

Body:
It will be 2 or more arrays come out from foreach loop. Like following

array1
    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )

    [1] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

array2
   [0] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [1] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )

I want to get same index value from these 2 arrays and merge these array like that.

**FinalArray = array1[0],array2[0],array1[1],array2[1]**

E.g

FinalArray

    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )
    [1] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [2] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

    [3] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )

please help how to get same index values and merge that 2 arrays. Thanks

Body:
you may achieve this by only one loop using array_column and array_merge as follows,

$array1 = array(
    0 => [0 => 1207, 1 => 4, 2 => "haha.mp4"],
    1 => [0 => 1208, 1 => 4, 2 => "hehe.mp4"],
);

$array2 = array(
    0 => [0 => 1209, 1 => 16, 2 => "SampleVideo.mp4"],
    1 => [0 => 1210, 1 => 16, 2 => "295.mp4"],
);

// here I assume that the following array is the output of your foreach loop
$array = [$array1, $array2];
$list = [];
foreach ($array as $key => $value) {
    $list = array_merge($list, array_column($array, $key));
}

print_r($list);

live demo: https://3v4l.org/2chf5


问:
How a byte array is being stored in sql server table column of type Varbinary?
I have a requirement in which I want to store a byte array in a sql server table column of type Varbinary using C# code. Now when I try to do this, I get a value in sql server table as  "0x4A6974656E6472612053616E6B686C61" for a byte array a[] = { 74, 105, 116, 101, 110, 100, 114, 97, 32, 83, 97, 110, 107, 104, 108, 97}. I am not sure how this is done. The value I get is actually a hexa representation of each decimal number.

Is it like sql server performs some internal conversion while storing a byte array into a varbinary sql table column ?

答:
Try this:

```<code>DECLARE @bin VARBINARY(MAX)=0x4A6974656E6472612053616E6B686C61;
SELECT CAST(@bin AS VARCHAR(MAX))
</code>```

The result Jitendra Sankhla looks pretty - uhm - fitting... :-)

Some background:

VARBINARY is nothing more than a BLOB. In a SELECT it is presented as HEX-string, but this is not the way it is stored actually.

You can store literally everything in a VARBINARYcolumn: pictures, strings, numbers, XML, complex structures... The only - but very important! - point is, that you must know, how to read and interpret this.

Why did I cast this to VARCHAR? Your numbers looked like ASCII-codes for plain letters. VARCHAR is a datatype representing 1-byte-extended-ASCII strings (the bound collation defines - like a codepage - the intpretation and sorting of non-plain characters).

Assuming, that you pass in byte after byte, the conversion to a normal string leads to letters according to the byte's values.

It is obvious, that you won't convert any binary to a string.

Many values between 0 and 255 are not printable. Other sources of pain can be differing collation/codepage settings. Furthermore, if you pass in a string with an encoding like utf-8 you will get some erronous characters, because utf-8 will encode some characters with more than one byte.

But in your simple example it works.

Body:
Try this:

DECLARE @bin VARBINARY(MAX)=0x4A6974656E6472612053616E6B686C61;
SELECT CAST(@bin AS VARCHAR(MAX))

The result Jitendra Sankhla looks pretty - uhm - fitting... :-)

Some background:

VARBINARY is nothing more than a BLOB. In a SELECT it is presented as HEX-string, but this is not the way it is stored actually.

You can store literally everything in a VARBINARYcolumn: pictures, strings, numbers, XML, complex structures... The only - but very important! - point is, that you must know, how to read and interpret this.

Why did I cast this to VARCHAR? Your numbers looked like ASCII-codes for plain letters. VARCHAR is a datatype representing 1-byte-extended-ASCII strings (the bound collation defines - like a codepage - the intpretation and sorting of non-plain characters).

Assuming, that you pass in byte after byte, the conversion to a normal string leads to letters according to the byte's values.

It is obvious, that you won't convert any binary to a string.

Many values between 0 and 255 are not printable. Other sources of pain can be differing collation/codepage settings. Furthermore, if you pass in a string with an encoding like utf-8 you will get some erronous characters, because utf-8 will encode some characters with more than one byte.

But in your simple example it works.


问:
CRM 2013 - Plugin to retrieve username
I have an AutoNumber plug-in that invokes when the user presses save, but I've received a requirement to append the initials of the person creating the record to the end of the ticket.

For example: 0001-0327-RBS

I have been able to get the GUID of the user creating the record, but I have no idea how to get the literal value outside of SQL. I haven't been able to figure out how I can get the user name of the active user creating the record. Is this possible from within a plug-in?

any help is appreciated. thanks.

答:
You should get IOrganizationService from IServiceProvider

```<code>var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(context.UserId);
</code>```

now you can simply retrieve the SystemUser using the service:

```<code>var systemUser = service.Retrieve("systemuser", context.UserId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
</code>```

in ColumnSet you can specify the columns which you want to retrieve (so for example "firstname", "lastname", "fullname" etc.).

Now you can simply do

```<code>systemUser["fullname"]
</code>```

to get the name. Or if you are using early binds:

```<code>systemUser.ToEntity<SystemUser>().FullName
</code>```

Title: CRM 2013 - Plugin to retrieve username

Body:
You should get IOrganizationService from IServiceProvider

var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(context.UserId);

now you can simply retrieve the SystemUser using the service:

var systemUser = service.Retrieve("systemuser", context.UserId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));

in ColumnSet you can specify the columns which you want to retrieve (so for example "firstname", "lastname", "fullname" etc.).

Now you can simply do

systemUser["fullname"]

to get the name. Or if you are using early binds:

systemUser.ToEntity<SystemUser>().FullName


问:
AngularJS display data of index that has matching value
I am working on a dashboard and am trying to display a certain piece of data. In my scope I have a project which consists of a couple fields and an array of users. The users consist of the following fields:

user_id

user_name

user_email

role

I want to display the user_name of the role which matches a certain value.  Is there a way to do this within my html file or is it recommended to do this in my controller?

My table code looks as follows:

```<code><tbody md-body>
        <tr md-row md-select="project" md-select-id="name" md-auto-select
            ng-repeat="project in projects.data | orderBy : myOrder">
            <td md-cell ng-click="getProject()">{{project.title}}</td>
            <td md-cell><i class="material-icons" style="color: green">radio_button_checked</i></td>
            <td md-cell>{{project.phase}}</td>
            <td md-cell>{{project.budget_indication}}</td>
            <td md-cell>{{project.users}}</td> <!-- Display user with specific role -->
            <td md-cell>{{project.start_date | date:dd/MM/yyyy}}</td>
        </tr>
</tbody>
</code>```

Thanks in advance!

答:
```<code><tbody md-body>
        <tr md-row md-select="project" md-select-id="name" md-auto-select
            ng-repeat="project in projects.data | orderBy : myOrder"  ng-if="project.users === 'role'">
            <td md-cell ng-click="getProject()">{{project.title}}</td>
            <td md-cell><i class="material-icons" style="color: green">radio_button_checked</i></td>
            <td md-cell>{{project.phase}}</td>
            <td md-cell>{{project.budget_indication}}</td>
            <td md-cell>  {{project.users}} </td> <!-- Display user with specific role -->
            <td md-cell>{{project.start_date | date:dd/MM/yyyy}}</td>
        </tr>
</tbody>
</code>```

Assuming role is specific role

Body:
I am working on a dashboard and am trying to display a certain piece of data. In my scope I have a project which consists of a couple fields and an array of users. The users consist of the following fields:

user_id

user_name

user_email

role

I want to display the user_name of the role which matches a certain value.  Is there a way to do this within my html file or is it recommended to do this in my controller?

My table code looks as follows:

            {{project.title}}
            radio_button_checked
            {{project.phase}}
            {{project.budget_indication}}
            {{project.users}}
            {{project.start_date | date:dd/MM/yyyy}}

Thanks in advance!

Body:
<tbody md-body>
        <tr md-row md-select="project" md-select-id="name" md-auto-select
            ng-repeat="project in projects.data | orderBy : myOrder"  ng-if="project.users === 'role'">
            <td md-cell ng-click="getProject()">{{project.title}}</td>
            <td md-cell><i class="material-icons" style="color: green">radio_button_checked</i></td>
            <td md-cell>{{project.phase}}</td>
            <td md-cell>{{project.budget_indication}}</td>
            <td md-cell>  {{project.users}} </td> <!-- Display user with specific role -->
            <td md-cell>{{project.start_date | date:dd/MM/yyyy}}</td>
        </tr>
</tbody>

Assuming role is specific role


问:
Is C strongly typed?
To quote Wikipedia:

Two commonly used languages that
  support many kinds of implicit
  conversion are C and C++, and it is
  sometimes claimed that these are
  weakly typed languages. However,
  others argue that these languages
  place enough restrictions on how
  operands of different types can be
  mixed, that the two should be regarded
  as strongly typed languages.

Is there a more definitive answer?

答:
The term strongly typed doesn't have a agreed-upon definition. Therefore, unless you define what you mean by "strongly typed", it is impossible to answer your question.

In my experience, the terms "strongly typed" and "weakly typed" are used exclusively by trolls, because their lack of definitions allows the trolls to redefine them mid-argument to suit their agenda. Other than for starting flamewars, these terms are pretty much useless.

You might also want to take a look at What are the key aspects of a strongly typed language? here on StackOverflow.

OwnerDisplayName: Sydius

Title: Is C strongly typed?

LastEditorDisplayName: Sydius

OwnerDisplayName: Jörg W Mittag


问:
Mail App's emails button iPhone
I need a for a project i'm working on a button similar to the one the Mail app use to display the a contacts.

If you don't see what i'm talking about, please see this image: http://www.aboutptc.net/theButtonIneed.png

Thanks in advance.

答:
Here is the code... you need to grab the images from the MessageUI.framework:

```<code>-(UIButton *) buttonForComposeName:(NSString *) name{
    UIButton *button;
    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    CGSize stringSize=[name sizeWithFont:[UIFont fontWithName:@"Helvetica" size:20]];

    [button setFrame:CGRectMake(0,0, stringSize.width+10, 20)];
    [button setTitle:name forState:UIControlStateNormal];
    [button addTarget:self action:@selector(composeNameButtonTapped:) forControlEvents:UIControlEventAllEvents];

    UIImage *image = [[UIImage imageNamed: @"Compose_atom@2x.png"] stretchableImageWithLeftCapWidth:25 topCapHeight:0];
    image=[MailRect imageWithImage:image scaledToSize:CGSizeMake(button.frame.size.width*2, 40)];

    [button setBackgroundImage:image forState:UIControlStateNormal];
}

-(void) composeNameButtonTapped:(id)sender{
    ((UIButton *)sender).selected=YES;

    UIImage *imageSelected = [[UIImage imageNamed: @"compose_atom_selected@2x.png"] stretchableImageWithLeftCapWidth:25 topCapHeight:0];
    imageSelected=[MailRect imageWithImage:imageSelected scaledToSize:CGSizeMake(((UIButton *)sender).frame.size.width*2, 40)];

    [((UIButton *)sender) setBackgroundImage:imageSelected forState:(UIControlStateSelected)];
}

+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize{
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}
</code>```

Title: Mail App's emails button iPhone

Body:
Here is the code... you need to grab the images from the MessageUI.framework:

-(UIButton *) buttonForComposeName:(NSString *) name{
    UIButton *button;
    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    CGSize stringSize=[name sizeWithFont:[UIFont fontWithName:@"Helvetica" size:20]];

    [button setFrame:CGRectMake(0,0, stringSize.width+10, 20)];
    [button setTitle:name forState:UIControlStateNormal];
    [button addTarget:self action:@selector(composeNameButtonTapped:) forControlEvents:UIControlEventAllEvents];

    UIImage *image = [[UIImage imageNamed: @"Compose_atom@2x.png"] stretchableImageWithLeftCapWidth:25 topCapHeight:0];
    image=[MailRect imageWithImage:image scaledToSize:CGSizeMake(button.frame.size.width*2, 40)];

    [button setBackgroundImage:image forState:UIControlStateNormal];
}

-(void) composeNameButtonTapped:(id)sender{
    ((UIButton *)sender).selected=YES;

    UIImage *imageSelected = [[UIImage imageNamed: @"compose_atom_selected@2x.png"] stretchableImageWithLeftCapWidth:25 topCapHeight:0];
    imageSelected=[MailRect imageWithImage:imageSelected scaledToSize:CGSizeMake(((UIButton *)sender).frame.size.width*2, 40)];

    [((UIButton *)sender) setBackgroundImage:imageSelected forState:(UIControlStateSelected)];
}

+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize{
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}


问:
iOS app localization in Xcode \ Swift
I have an app in which I want to localize the interface. There are just a view strings to translate.

I added localization files to storyboard so I have a similar structure like on this screeshot:

Now I have translated the string values on the right side of equations to the language they represent.

But if I run the app in simulator and set the scheme to use that language or even in the simulator itself set the language - i still don't get the labels translated to that language.

Which steps might I be missing?

答:
It is very simple to perform localisation in ios, please follow the below steps.

Create a xcode project like : LocalizationDemo

Design the storyboard, with labels as screen shot below.

Click on the project, under navigation select project. Under localizations click +(plus) button and select the preferred language. as below.

Create a "Localizable.strings" by right click on project folder, click new file, choose the template IOS, under resources select "String File"  and give the name "Localizable".

Select the Localizable.strings file from project navigator, on the right most corner use can see as below,

Click on the localize, then you will see a pop up , select Base. Later click on Localization.strings file on the right side select the preferred languages as below.

Under Localization.strings, select the preferred .strings file and declare the Keys and values for the labels of storyboard, as below

Get the translated text from goole or from your client.

Create a swift file like: StringExtension.swift , under that file write the code as below.

```<code>import Foundation

let LANGUAGE = "te-IN"

extension String {

  //code for swift 2.3

  func localized() -> String {

     let path = NSBundle.mainBundle().pathForResource(LANGUAGE, ofType:  "lproj")

     let bundle = NSBundle(path: path!)

     return NSLocalizedString(self, tableName: nil, bundle: bundle!,   value: "", comment: "")

 }

 //Code for Swift 3.0

 func localized() -> String{

    let path = Bundle.main.path(forResource: LANGUAGE, ofType: "lproj")
    let bundle = Bundle(path: path!)

    return NSLocalizedString(self, tableName: nil, bundle: bundle!,      value: "", comment: "")
   }
 }
</code>```

When you click the language specific localization.strings file, on right side you can see the "te-IN" as below,

Create the outlets of labels in viewcontroller, and in viewdidload write the code as below,

```<code>welcomeLbl.text = "Welcome".localized()

haiLbl.text = "Hai how are you?".localized()
</code>```

Finally the language and images are just for reference.

Title: iOS app localization in Xcode \ Swift

Body:
It is very simple to perform localisation in ios, please follow the below steps.

Create a xcode project like : LocalizationDemo

Design the storyboard, with labels as screen shot below.

Click on the project, under navigation select project. Under localizations click +(plus) button and select the preferred language. as below.

Create a "Localizable.strings" by right click on project folder, click new file, choose the template IOS, under resources select "String File"  and give the name "Localizable".

Select the Localizable.strings file from project navigator, on the right most corner use can see as below,

Click on the localize, then you will see a pop up , select Base. Later click on Localization.strings file on the right side select the preferred languages as below.

Under Localization.strings, select the preferred .strings file and declare the Keys and values for the labels of storyboard, as below

Get the translated text from goole or from your client.

Create a swift file like: StringExtension.swift , under that file write the code as below.

import Foundation

let LANGUAGE = "te-IN"

extension String {

  //code for swift 2.3

  func localized() -> String {

     let path = NSBundle.mainBundle().pathForResource(LANGUAGE, ofType:  "lproj")

     let bundle = NSBundle(path: path!)

     return NSLocalizedString(self, tableName: nil, bundle: bundle!,   value: "", comment: "")

 }

 //Code for Swift 3.0

 func localized() -> String{

    let path = Bundle.main.path(forResource: LANGUAGE, ofType: "lproj")
    let bundle = Bundle(path: path!)

    return NSLocalizedString(self, tableName: nil, bundle: bundle!,      value: "", comment: "")
   }
 }

When you click the language specific localization.strings file, on right side you can see the "te-IN" as below,

Create the outlets of labels in viewcontroller, and in viewdidload write the code as below,

welcomeLbl.text = "Welcome".localized()

haiLbl.text = "Hai how are you?".localized()

Finally the language and images are just for reference.

ContentLicense: CC BY-SA 4.0


问:
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!

答:
Step 1: paste the code in your layout file

```<code> <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ListView
            android:smoothScrollbar="true"
            android:id="@+id/mListView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone" />
    </android.support.v4.widget.SwipeRefreshLayout>
</code>```

Step 2: Open your java file and add these lines

```<code>    public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener
      private SwipeRefreshLayout swipeRefreshLayout;

         public void onCreate(Bundle savedStateInstances){
        ....
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    swipeRefreshLayout.setOnRefreshListener(this);

        }

   @Override
    public void onRefresh() {

       //implement the logic you want to do when the pull down happen.

//after completion of your logic add this line.
 swipeRefreshLayout.setRefreshing(false);
    }
</code>```

Body:
Step 1: paste the code in your layout file

 <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ListView
            android:smoothScrollbar="true"
            android:id="@+id/mListView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone" />
    </android.support.v4.widget.SwipeRefreshLayout>

Step 2: Open your java file and add these lines

    public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener
      private SwipeRefreshLayout swipeRefreshLayout;

         public void onCreate(Bundle savedStateInstances){
        ....
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    swipeRefreshLayout.setOnRefreshListener(this);

        }

   @Override
    public void onRefresh() {

       //implement the logic you want to do when the pull down happen.

//after completion of your logic add this line.
 swipeRefreshLayout.setRefreshing(false);
    }


问:
Irrelevant Line on nav bar Menu Boostrap
This is my Full screen menu on 1080p display

This is Menu on 720p display

The problem is i am experiencing An extra line on 720P display can anyone tell why it is happening? Here is my code

```<code>  <div class="collapse navbar-collapse" id="myNavbar1">

    <ul id="main" class="nav nav-tabs nav-justified" style="background-color: #F7F7F7;color:white">
      <?php
              $pages = array('home.php');
              if(in_array($pageName,$pages)){
                 $mainActive = 'active';
                 $inactive='';
                 $color='';
              }
              else
              {
                $mainActive = '';
                $inactive='inactive';
                $color='style="color:white"';
              }
            ?>
      <li class="<?php echo $mainActive?>" style="border-right:1px solid;border-radius: 5px;background-color: #31b0d5;"><a class="<?php echo $inactive?>" href="home.php" <?php echo $color; ?>>Home</a></li>
 <?php
              $pages = array('calendar.php');
              if(in_array($pageName,$pages)){
                $mainActive = 'active';
                $inactive='';
                $color='';
              }
              else
              {
                $mainActive = '';
                $inactive='inactive';
                $color='style="color:white"';
              }
      ?>

      <li class="<?php echo $mainActive; ?>" style="border-right:1px solid;border-radius: 5px;background-color: #31b0d5;"><a class="<?php echo $inactive?>" href="calendar.php" <?php echo $color; ?>>My Schedules</a></li>
// and so on all other menu items have similar styling
</ul>
</div>
</code>```

答:
Because the anchor text becomes multi-line, you may set the text vertically middle align the
 block.

I add the below css:

```<code>.nav-tabs.nav-justified>li {
  vertical-align: middle;
}

.nav-tabs.nav-justified>li>a {
  border: 0!important;
}
</code>```

You may need to modify your php as well, I changed the
 to background-color: white when it is active.

Here's the jsfiddle:
https://jsfiddle.net/urmf4ejf/

Body:
This is my Full screen menu on 1080p display

This is Menu on 720p display

The problem is i am experiencing An extra line on 720P display can anyone tell why it is happening? Here is my code

      <?php
              $pages = array('home.php');
              if(in_array($pageName,$pages)){
                 $mainActive = 'active';
                 $inactive='';
                 $color='';
              }
              else
              {
                $mainActive = '';
                $inactive='inactive';
                $color='style="color:white"';
              }
            ?>
      <li class="<?php echo $mainActive?>" style="border-right:1px solid;border-radius: 5px;background-color: #31b0d5;"><a class="<?php echo $inactive?>" href="home.php" <?php echo $color; ?>>Home

 <?php
              $pages = array('calendar.php');
              if(in_array($pageName,$pages)){
                $mainActive = 'active';
                $inactive='';
                $color='';
              }
              else
              {
                $mainActive = '';
                $inactive='inactive';
                $color='style="color:white"';
              }
      ?>

      <li class="<?php echo $mainActive; ?>" style="border-right:1px solid;border-radius: 5px;background-color: #31b0d5;"><a class="<?php echo $inactive?>" href="calendar.php" <?php echo $color; ?>>My Schedules

// and so on all other menu items have similar styling

Body:
Because the anchor text becomes multi-line, you may set the text vertically middle align the <li> block.

I add the below css:

.nav-tabs.nav-justified>li {
  vertical-align: middle;
}

.nav-tabs.nav-justified>li>a {
  border: 0!important;
}

You may need to modify your php as well, I changed the <li> to background-color: white when it is active.

Here's the jsfiddle:
https://jsfiddle.net/urmf4ejf/


问:
Add placeholder to select tag in angular2
I have simple component that contains only form:

```<code>import {Component, FORM_DIRECTIVES, NgFor} from 'angular2/angular2';

@Component({
  selector: 'test-component',
  directives: [FORM_DIRECTIVES, NgFor],
  template: `
    <form class="form-inline" (ng-submit)="onSubmit()" #form="form">
      <div class="form-group">
        <select class="form-control"
          [(ng-model)]="model.server"
          ng-control="server"
          #server="form"
          required>
          <option selected hidden>placeholder</option>
          <option *ng-for="#server of servers"
            [value]="server">{{ server | uppercase }}
          </option>
        </select>
      </div>
      <div class="form-group">
        <input class="btn btn-primary" type="submit" value="Load"
          [disabled]="!form.form.valid">
      </div>
    </form>
  `
})
export class TestComponent {
  public model: Model = new Model();
  public servers: string[] = ['a', 'b', 'c'];

  onSubmit(): void {
    // Complicated logic.

    // Reset form.
    this.model.reset();
  }
}

class Model {
  constructor(
    public server: string = ''
  ) { }

  reset(): void {
    this.server = '';
  }
}
</code>```

I want to create "placeholder" for my select, however ng-model overrides selected property which cause no selected option at all. Any sugestions? I am using angular 2.0.0-alpha.48.

答:
This is how we I do it: </p>

```<code><select class="form-control" name="selectedSignierer" #selectedSignierer="ngModel" [(ngModel)]="suisseIdDetail.selectedSigniererBenutzerId" required>
  <option value="null" disabled selected>Select your option</option>
  <option *ngFor="let item of signiererCatalog.entries;" value="{{ item.id }}" >{{ item.value }}</option>
</select>
<div *ngIf="fb.submitted && showSignDefinition === true && !selectedSignierer.valid" class="validation-error">{{ 'ERROR_FIELD_REQUIRED' | translate:lang }}</div>
</code>```

Body:
I have simple component that contains only form:

import {Component, FORM_DIRECTIVES, NgFor} from 'angular2/angular2';

@Component({
  selector: 'test-component',
  directives: [FORM_DIRECTIVES, NgFor],
  template: `
    <form class="form-inline" (ng-submit)="onSubmit()" #form="form">

        <select class="form-control"
          [(ng-model)]="model.server"
          ng-control="server"
          #server="form"
          required>
          <option selected hidden>placeholder</option>
          <option *ng-for="#server of servers"
            [value]="server">{{ server | uppercase }}
          </option>
        </select>

        <input class="btn btn-primary" type="submit" value="Load"
          [disabled]="!form.form.valid">

    </form>
  `
})
export class TestComponent {
  public model: Model = new Model();
  public servers: string[] = ['a', 'b', 'c'];

  onSubmit(): void {
    // Complicated logic.

    // Reset form.
    this.model.reset();
  }
}

class Model {
  constructor(
    public server: string = ''
  ) { }

  reset(): void {
    this.server = '';
  }
}

I want to create "placeholder" for my select, however ng-model overrides selected property which cause no selected option at all. Any sugestions? I am using angular 2.0.0-alpha.48.

Body:
This is how we I do it:

<select class="form-control" name="selectedSignierer" #selectedSignierer="ngModel" [(ngModel)]="suisseIdDetail.selectedSigniererBenutzerId" required>
  <option value="null" disabled selected>Select your option</option>
  <option *ngFor="let item of signiererCatalog.entries;" value="{{ item.id }}" >{{ item.value }}</option>
</select>
<div *ngIf="fb.submitted && showSignDefinition === true && !selectedSignierer.valid" class="validation-error">{{ 'ERROR_FIELD_REQUIRED' | translate:lang }}</div>


问:
Select odd numbers and does not contain special characters
This is Table WWE :

```<code>    |**Col A**  | **Col B** |
   -+-----------+-----------+-
    | Hello     | 9%15A     |
    | World     | 2*10      |
    | Cat       | 12        |
    | Dog       | 13        |
</code>```

Col B is Varchar (100)

How do I select all rows consist of ODD NUMBERS ONLY and does not contain '%' or '*' or alphabets??

I know how to get ODD NUMBERS : colB % 2 <> 0

But I don't know how to EXCLUDE the special characters and to calculate the number as NUMBER since they're stored in VARCHAR

For example in this table, the output will be

```<code>| Dog | 13 |
</code>```

答:
USE REGEXP if you need only numeric result:

```<code>SELECT * FROM WWE WHERE colB REGEXP '[0-9]' AND colB mod 2 = 1
</code>```

Body:
This is Table WWE :

    |**Col A**  | **Col B** |
   -+-----------+-----------+-
    | Hello     | 9%15A     |
    | World     | 2*10      |
    | Cat       | 12        |
    | Dog       | 13        |

Col B is Varchar (100)

How do I select all rows consist of ODD NUMBERS ONLY and does not contain '%' or '*' or alphabets??

I know how to get ODD NUMBERS : colB % 2 <> 0

But I don't know how to EXCLUDE the special characters and to calculate the number as NUMBER since they're stored in VARCHAR

For example in this table, the output will be

| Dog | 13 |

Body:
USE REGEXP if you need only numeric result:

SELECT * FROM WWE WHERE colB REGEXP '[0-9]' AND colB mod 2 = 1


问:
How to use MSCAPI provider for client SSL authentication
I am writing a program which needs to make HTTPS connections to a web server, where SSL Client authentication needs to be used.

The users of this program will use certificates from the windows environment to authenticate themselves.

I've found plenty of examples showing how to set up client authentication, and it works fine if I first export my certificate to pkcs12 format, but I don't wish to force my users to do that. However when I try to use the MSCAPI it always bombs out with an exception:

```<code>javax.net.ssl.SSLHandshakeException: Error signing certificate verify
        at sun.security.ssl.Alerts.getSSLException(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
        at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
        at sun.security.ssl.ClientHandshaker.serverHelloDone(Unknown Source)
        at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
        at sun.security.ssl.Handshaker.processLoop(Unknown Source)
        at sun.security.ssl.Handshaker.process_record(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
        at sun.security.ssl.AppInputStream.read(Unknown Source)
        at java.io.BufferedInputStream.fill(Unknown Source)
        at java.io.BufferedInputStream.read1(Unknown Source)
        at java.io.BufferedInputStream.read(Unknown Source)
        at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
        at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
        at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
        at com.example.Win2.main(Win2.java:62)
Caused by: java.security.SignatureException: Bad Key.

        at sun.security.mscapi.RSASignature.signHash(Native Method)
        at sun.security.mscapi.RSASignature.engineSign(RSASignature.java:390)
        at java.security.Signature$Delegate.engineSign(Unknown Source)
        at java.security.Signature.sign(Unknown Source)
        at sun.security.ssl.RSASignature.engineSign(Unknown Source)
        at java.security.Signature$Delegate.engineSign(Unknown Source)
        at java.security.Signature.sign(Unknown Source)
        at sun.security.ssl.HandshakeMessage$CertificateVerify.<init>(Unknown Source)
        ... 16 more
</code>```

I can't really tell what might be wrong with the key from that exception.

I have made a tiny test program to reproduce the problem I am having:

```<code>String passwd = .....";
URL url = new URL("https://.........");

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance("Windows-MY");
keyStore.load(null, passwd.toCharArray());
keyManagerFactory.init(keyStore, passwd.toCharArray());

SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, null);
SSLSocketFactory socketFactory = context.getSocketFactory();

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(socketFactory);
</code>```

There is clearly something about the APIs I don't understand here. How does it know which of the keys in the keystore I want to use? I was expecting for Windows to prompt me, as it does for other applications which need to authenticate, but I suspect instead it is just choosing the first one it finds.

Do I need to implement my own key manager so it can choose which key will be used?

If I iterate through the keystore, I can see the keys in it and can extract one by calling getKey. To complicate matters, there are multiple keys in the store with the same alias (but differing validity). Other (non-java) applications, eg. Chrome, seem to be able to determine which keys to use somehow.

EDIT: I forgot to mention, I am using Java 1.7.

答:
The responsible for choosing which key in the keystore would be used is the KeyManager object.
You can get a vector of those objects calling keyManagerFactory.getKeyManagers().

The libraries usually get the first key entry they find in the store (could be compatible with the server certificate presented in this case). The MS-CAPI API does no different.

To select which key in the keystore you want to use, you should do 3 things:

implement the interface X509KeyManager

make the method chooseClientAlias of the above interface return the desired alias of your key

set the object to your SSLContext.

Remind that your keystore must contain all the chain of certificates starting at your personal certificate up to a root authority. You should use the certmgr.msc program to import the certificates and/or check if all of them are present in the folders Personal (your certificate), Intermediate Certification Authorities (any middle CA in your chain) and Trusted Root Certification Authorities.

It's also important to set your trust keystore - it stores the root certificates you trust, this store would be used to verify the server certificate. In case of MS-CAPI you would use the KeyStore.getInstance("Windows-ROOT") command to get it (the certs in the Trusted Root Certification Authorities folder).

Modifying your code to accomplish that:

```<code>URL url = new URL("https://.........");

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance("Windows-MY");
keyStore.load(null, null);
keyManagerFactory.init(keyStore);

/* You must also set your trust store */
KeyStore ts = KeyStore.getInstance("Windows-ROOT");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);

/* Here you can implement a way to set your key alias
** You can run through all key entries and implement a way
** to prompt the user to choose one - for simplicity I just set a
** name*/
String alias = "user1_alias";

/* Get your current KeyManager from the factory */
final X509KeyManager okm = (X509KeyManager)keyManagerFactory.getKeyManagers()[0];

/* Implement the Interface X509KeyManager */
X509KeyManager km = new X509KeyManager() {
    public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
         /* Implement your own logic to choose the alias
            according to the validity if the case,
            or use the entry id or any other way, you can get
            those values outside this class*/
         return alias;
    }

    public X509Certificate[] getCertificateChain(String alias) {
         return okm.getCertificateChain(alias);
    }
   /* Implement the other methods of the interface using the okm object */
};
SSLContext context = SSLContext.getInstance("TLS");
/* set the keymanager in the SSLContext */
context.init(new KeyManager[]{km}, tmf.getTrustManagers(), new SecureRandom());
SSLSocketFactory socketFactory = context.getSocketFactory();

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(socketFactory);
</code>```

Body:
I am writing a program which needs to make HTTPS connections to a web server, where SSL Client authentication needs to be used.

The users of this program will use certificates from the windows environment to authenticate themselves.

I've found plenty of examples showing how to set up client authentication, and it works fine if I first export my certificate to pkcs12 format, but I don't wish to force my users to do that. However when I try to use the MSCAPI it always bombs out with an exception:

javax.net.ssl.SSLHandshakeException: Error signing certificate verify
        at sun.security.ssl.Alerts.getSSLException(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
        at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
        at sun.security.ssl.ClientHandshaker.serverHelloDone(Unknown Source)
        at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
        at sun.security.ssl.Handshaker.processLoop(Unknown Source)
        at sun.security.ssl.Handshaker.process_record(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
        at sun.security.ssl.AppInputStream.read(Unknown Source)
        at java.io.BufferedInputStream.fill(Unknown Source)
        at java.io.BufferedInputStream.read1(Unknown Source)
        at java.io.BufferedInputStream.read(Unknown Source)
        at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
        at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
        at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
        at com.example.Win2.main(Win2.java:62)
Caused by: java.security.SignatureException: Bad Key.

        at sun.security.mscapi.RSASignature.signHash(Native Method)
        at sun.security.mscapi.RSASignature.engineSign(RSASignature.java:390)
        at java.security.Signature$Delegate.engineSign(Unknown Source)
        at java.security.Signature.sign(Unknown Source)
        at sun.security.ssl.RSASignature.engineSign(Unknown Source)
        at java.security.Signature$Delegate.engineSign(Unknown Source)
        at java.security.Signature.sign(Unknown Source)
        at sun.security.ssl.HandshakeMessage$CertificateVerify.<init>(Unknown Source)
        ... 16 more

I can't really tell what might be wrong with the key from that exception.

I have made a tiny test program to reproduce the problem I am having:

String passwd = .....";
URL url = new URL("https://.........");

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance("Windows-MY");
keyStore.load(null, passwd.toCharArray());
keyManagerFactory.init(keyStore, passwd.toCharArray());

SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, null);
SSLSocketFactory socketFactory = context.getSocketFactory();

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(socketFactory);

There is clearly something about the APIs I don't understand here. How does it know which of the keys in the keystore I want to use? I was expecting for Windows to prompt me, as it does for other applications which need to authenticate, but I suspect instead it is just choosing the first one it finds.

Do I need to implement my own key manager so it can choose which key will be used?

If I iterate through the keystore, I can see the keys in it and can extract one by calling getKey. To complicate matters, there are multiple keys in the store with the same alias (but differing validity). Other (non-java) applications, eg. Chrome, seem to be able to determine which keys to use somehow.

EDIT: I forgot to mention, I am using Java 1.7.

Body:
The responsible for choosing which key in the keystore would be used is the KeyManager object.
You can get a vector of those objects calling keyManagerFactory.getKeyManagers().

The libraries usually get the first key entry they find in the store (could be compatible with the server certificate presented in this case). The MS-CAPI API does no different.

To select which key in the keystore you want to use, you should do 3 things:

implement the interface X509KeyManager

make the method chooseClientAlias of the above interface return the desired alias of your key

set the object to your SSLContext.

Remind that your keystore must contain all the chain of certificates starting at your personal certificate up to a root authority. You should use the certmgr.msc program to import the certificates and/or check if all of them are present in the folders Personal (your certificate), Intermediate Certification Authorities (any middle CA in your chain) and Trusted Root Certification Authorities.

It's also important to set your trust keystore - it stores the root certificates you trust, this store would be used to verify the server certificate. In case of MS-CAPI you would use the KeyStore.getInstance("Windows-ROOT") command to get it (the certs in the Trusted Root Certification Authorities folder).

Modifying your code to accomplish that:

URL url = new URL("https://.........");

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance("Windows-MY");
keyStore.load(null, null);
keyManagerFactory.init(keyStore);

/* You must also set your trust store */
KeyStore ts = KeyStore.getInstance("Windows-ROOT");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);

/* Here you can implement a way to set your key alias
** You can run through all key entries and implement a way
** to prompt the user to choose one - for simplicity I just set a
** name*/
String alias = "user1_alias";

/* Get your current KeyManager from the factory */
final X509KeyManager okm = (X509KeyManager)keyManagerFactory.getKeyManagers()[0];

/* Implement the Interface X509KeyManager */
X509KeyManager km = new X509KeyManager() {
    public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
         /* Implement your own logic to choose the alias
            according to the validity if the case,
            or use the entry id or any other way, you can get
            those values outside this class*/
         return alias;
    }

    public X509Certificate[] getCertificateChain(String alias) {
         return okm.getCertificateChain(alias);
    }
   /* Implement the other methods of the interface using the okm object */
};
SSLContext context = SSLContext.getInstance("TLS");
/* set the keymanager in the SSLContext */
context.init(new KeyManager[]{km}, tmf.getTrustManagers(), new SecureRandom());
SSLSocketFactory socketFactory = context.getSocketFactory();

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(socketFactory);


问:
Custom Authorization - Web Api
I have a web api for which i would need to implement custom authentication and authorization. The authorization should be defined by Resource and Action as shown below:

```<code>[Authorize("users","view")]
public async Task<IHttpActionResult> GetAsync()
{
}
</code>```

Is there any way i can use custom authorization filter and implement this?

Also, the web api is protected by client certificate and the caller is identifier by key which is passed in the request header. The Key is authenticated using a custom authentication filter.

Regarads,

John

答:
Yes you can create custom Authorization and put on controller or method that needs to be authorized.

sample example is as below

```<code>public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
    {
        private string Resource { get; set; }
        private string Action { get; set; }
        public CustomAuthorize(string resource, string action)
        {
            Resource = resource;
            Action = action;
        }
        public override void OnAuthorization(
               System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);
            //Check your post authorization logic using Resource and Action
            //Your logic here to return authorize or unauthorized response
        }
    }
</code>```

Here you can do your custom authorization logic and sample controller will look like this

```<code>public class DoThisController : ApiController
{
    [CustomAuthorize("users","view")]// for specific methods
    public string Get()
    {
        return "Sample Authorized";
    }
}
</code>```

Title: Custom Authorization - Web Api

Body:
I have a web api for which i would need to implement custom authentication and authorization. The authorization should be defined by Resource and Action as shown below:

[Authorize("users","view")]
public async Task<IHttpActionResult> GetAsync()
{
}

Is there any way i can use custom authorization filter and implement this?

Also, the web api is protected by client certificate and the caller is identifier by key which is passed in the request header. The Key is authenticated using a custom authentication filter.

Regarads,

John

Body:
Yes you can create custom Authorization and put on controller or method that needs to be authorized.

sample example is as below

public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
    {
        private string Resource { get; set; }
        private string Action { get; set; }
        public CustomAuthorize(string resource, string action)
        {
            Resource = resource;
            Action = action;
        }
        public override void OnAuthorization(
               System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);
            //Check your post authorization logic using Resource and Action
            //Your logic here to return authorize or unauthorized response
        }
    }

Here you can do your custom authorization logic and sample controller will look like this

public class DoThisController : ApiController
{
    [CustomAuthorize("users","view")]// for specific methods
    public string Get()
    {
        return "Sample Authorized";
    }
}


问:
Smarty Undefiend Variable As Array
I have a smarty application that was written about 1 year ago ,  now i migrated to Smarty v3 and i've got some errors in my code that i dont have any clue how to fix them. here i will list them , thanks

1-Cannot use object of type Smarty_Undefined_Variable as array

```<code>$this->_tpl_vars['cart']['domains'] = array();
</code>```

i was able to set variable like this but now i'm getting error with this code , i read the Smarty document and it said : for making variables i should use this code :

```<code>$template->assign('myNewVariable', 'myNewValue');
</code>```

the problem is that i want to add an array in variable and its nested like the code i have shown above and i need something like this  as array :

```<code> $template->assign('cart[domains]', 'myNewValue');
</code>```

or maybe :

```<code>$test= $template->assign('cart', array);
$domain=$test->assign('domains',array);
</code>```

both of them should be assigned as array.

答:
If you want to an array to a variable, you can do like this

```<code>$arr['domain']=YourNewValue;
$template->assign('cart', $arr);
</code>```

Simple as that.

Title: Smarty Undefiend Variable As Array

Body:
I have a smarty application that was written about 1 year ago ,  now i migrated to Smarty v3 and i've got some errors in my code that i dont have any clue how to fix them. here i will list them , thanks

1-Cannot use object of type Smarty_Undefined_Variable as array

$this->_tpl_vars['cart']['domains'] = array();

i was able to set variable like this but now i'm getting error with this code , i read the Smarty document and it said : for making variables i should use this code :

$template->assign('myNewVariable', 'myNewValue');

the problem is that i want to add an array in variable and its nested like the code i have shown above and i need something like this  as array :

 $template->assign('cart[domains]', 'myNewValue');

or maybe :

$test= $template->assign('cart', array);
$domain=$test->assign('domains',array);

both of them should be assigned as array.

Body:
If you want to an array to a variable, you can do like this

$arr['domain']=YourNewValue;
$template->assign('cart', $arr);

Simple as that.