答:
Let's try this: with simple jquery function

$(document).on('mouseover', '.tab', function(e){
      e.preventDefault();
      var self = $(this),
          ref = self.attr('ref');

      $('.content').hide();
      $('#' + ref).fadeIn();

    })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  position: relative;
  width: 50%;
  margin: 10% auto;
}

.tab {
  width: 20%;
  height: 50px;
  background: gray;
  cursor: pointer;
}

.content {
  background: #ccc;
  padding:15px;
  min-height:400px; width:100%;
  display: none;
}

.clear {
  clear: both;
  height: 10px;
}

#tab1 {
  position: absolute;
  top: 0;
  left: 0;
}

#tab2 {
  position: absolute;
  top: 60px;
  left: 0;
}

#tab3 {
  position: absolute;
  top: 120px;
  left: 0;
}

#content1 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content2 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content3 {
  position: absolute;
  top: 0;
  left: 20%;
}</code>```

      Tab 1

      Tab 1 Content

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.

      Tab 2

      Tab 2 Content

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.

      Tab 3

      Tab 3 Content

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.

```

Body:
Let's try this: with simple jquery function

$(document).on('mouseover', '.tab', function(e){
      e.preventDefault();
      var self = $(this),
          ref = self.attr('ref');

      $('.content').hide();
      $('#' + ref).fadeIn();

    })

body {
  position: relative;
  width: 50%;
  margin: 10% auto;
}

.tab {
  width: 20%;
  height: 50px;
  background: gray;
  cursor: pointer;
}

.content {
  background: #ccc;
  padding:15px;
  min-height:400px; width:100%;
  display: none;
}

.clear {
  clear: both;
  height: 10px;
}

#tab1 {
  position: absolute;
  top: 0;
  left: 0;
}

#tab2 {
  position: absolute;
  top: 60px;
  left: 0;
}

#tab3 {
  position: absolute;
  top: 120px;
  left: 0;
}

#content1 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content2 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content3 {
  position: absolute;
  top: 0;
  left: 20%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tab1" ref="content1" class="tab">
      Tab 1
    </div>
    <div id="content1" class="content">
      <b>Tab 1 Content</b>
      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.</p>
    </div>
    <div id="tab2" ref="content2" class="tab">
      Tab 2
    </div>
    <div id="content2" class="content">
      <b>Tab 2 Content</b>
      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.</p>
    </div>
    <div id="tab3" ref="content3" class="tab">
      Tab 3
    </div>
    <div id="content3" class="content">
      <b>Tab 3 Content</b>
      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.</p>
    </div>


来源: stackexchange

问:
Maximum of COUNT by group and joining on EQUALS and NOT EQUALS condition
I am working on a scenario where I need to get counts grouped by UserID and then obtain the maximum count obtained from the result set of the grouping.

This maximum count will then be used to calculate percentages against each of the rows obtained from the result set of grouping.

Here is an example:

This is the sample data I have:

```<code> Users Table:
  UserID        CountAsApproved
    1                   1
    2                   1
    1                   1
    2                   1
    3                   1
    3                   0
    4                   1
    1                   1
    4                   0

    Grouping Result:

  UserID            Counts
    1                 3
    2                 2
    3                 1
    4                 1
</code>```

I then need to get the maximum of the count (in this case max count is 3)
and then calculate percentages as follows:

```<code> UserID         Counts      MaxCount            Percentage
    1             3           3            (Count/MaxCount)*100
    2             2           3                 2/3 * 100
    3             1           3                 1/3 * 100
    4             1           3                 1/3 * 100
</code>```

I currently have the query like this:

```<code>    ;WITH Groups_CTE AS(
        SELECT UserID, COUNT(CountAsApproved) as Counts
        FROM Users
        GROUP BY UserID),
MaxCount_CTE AS
(
        SELECT MAX(Counts) AS MaxCount
        FROM Groups_CTE
)
SELECT
        gc.UserID,
        gc.Counts,
        mc.MaxCount,
        CASE WHEN CAST(( ( gc.Counts
                                   / mc.MaxCount ) * 100 ) AS INT) = 0
                     THEN 1
                     ELSE CAST(( ( gc.Counts
                                   / mc.MaxCount ) * 100 ) AS INT)
                END AS Percentage
FROM    Groups_CTE gc CROSS JOIN MaxCount_CTE mc
</code>```

The above query is yielding the same result when I do an Inner join on the below condition instead of a CROSS JOIN

```<code>FROM    Groups_CTE gc JOIN MaxCount_CTE mc
ON gc.Counts <> mc.MaxCount OR gc.Counts = mc.MaxCount
</code>```

I just wanted to check if there is a better way of doing this in performance point of view or in reducing the number of lines of code. I get the same results with either of the joins and also when I used CROSS APPLY without a condition.
I am also a bit hesitant about using two CTEs.

Let me know your thoughts and suggestions in improvising this code.

If it may help, the Users table on which we perform these operations may contain rows ranging in thousands.

ContentLicense: CC BY-SA 3.0

Body:
I am working on a scenario where I need to get counts grouped by UserID and then obtain the maximum count obtained from the result set of the grouping.

This maximum count will then be used to calculate percentages against each of the rows obtained from the result set of grouping.

Here is an example:

This is the sample data I have:

 Users Table:
  UserID        CountAsApproved
    1                   1
    2                   1
    1                   1
    2                   1
    3                   1
    3                   0
    4                   1
    1                   1
    4                   0

    Grouping Result:

  UserID            Counts
    1                 3
    2                 2
    3                 1
    4                 1

I then need to get the maximum of the count (in this case max count is 3)
and then calculate percentages as follows:

 UserID         Counts      MaxCount            Percentage
    1             3           3            (Count/MaxCount)*100
    2             2           3                 2/3 * 100
    3             1           3                 1/3 * 100
    4             1           3                 1/3 * 100

I currently have the query like this:

    ;WITH Groups_CTE AS(
        SELECT UserID, COUNT(CountAsApproved) as Counts
        FROM Users
        GROUP BY UserID),
MaxCount_CTE AS
(
        SELECT MAX(Counts) AS MaxCount
        FROM Groups_CTE
)
SELECT
        gc.UserID,
        gc.Counts,
        mc.MaxCount,
        CASE WHEN CAST(( ( gc.Counts
                                   / mc.MaxCount ) * 100 ) AS INT) = 0
                     THEN 1
                     ELSE CAST(( ( gc.Counts
                                   / mc.MaxCount ) * 100 ) AS INT)
                END AS Percentage
FROM    Groups_CTE gc CROSS JOIN MaxCount_CTE mc

The above query is yielding the same result when I do an Inner join on the below condition instead of a CROSS JOIN

FROM    Groups_CTE gc JOIN MaxCount_CTE mc
ON gc.Counts <> mc.MaxCount OR gc.Counts = mc.MaxCount

I just wanted to check if there is a better way of doing this in performance point of view or in reducing the number of lines of code. I get the same results with either of the joins and also when I used CROSS APPLY without a condition.
I am also a bit hesitant about using two CTEs.

Let me know your thoughts and suggestions in improvising this code.

If it may help, the Users table on which we perform these operations may contain rows ranging in thousands.

Body:
using max() over():

select
    userid
  , Counts     = sum(countasapproved)
  , MaxCount   = max(sum(countasapproved)) over()
  , Percentage = sum(countasapproved+.0)/max(sum(countasapproved)) over()
from Users
group by userid

rextester demo: http://rextester.com/TLG73597

returns:

+--------+--------+----------+------------+
| userid | Counts | MaxCount | Percentage |
+--------+--------+----------+------------+
|      1 |      3 |        3 | 1,000000   |
|      2 |      2 |        3 | 0,666666   |
|      3 |      1 |        3 | 0,333333   |
|      4 |      1 |        3 | 0,333333   |
+--------+--------+----------+------------+


答:
Use window functions on your aggregate results:</p>

```<code>select
  userid,
  sum(countasapproved) as counts,
  max(sum(countasapproved)) over () as maxcount,
  sum(countasapproved) * 100.0 / max(sum(countasapproved)) over () as percentage
from users
group by userid;
</code>```

Title: Maximum of COUNT by group and joining on EQUALS and NOT EQUALS condition

Body:
Use window functions on your aggregate results:

select
  userid,
  sum(countasapproved) as counts,
  max(sum(countasapproved)) over () as maxcount,
  sum(countasapproved) * 100.0 / max(sum(countasapproved)) over () as percentage
from users
group by userid;


问:
Phonegap Android Fingerprint Auth Plugin
I am currently creating a mobile app with Adobe Phonegap and I am trying to lock a page of the app so that it can only be accessed by fingerprint.

I am completely new to incorporating plugins and using them.

I have been following tutorials such as the ones present on the github of the plugin:

https://github.com/mjwheatley/cordova-plugin-android-fingerprint-auth#module_fingerprintauth.config

I have successfully installed the plugin with the command:

```<code>phonegap plugin add cordova-plugin-android-fingerprint-auth
</code>```

However I don't how to set up and use the plugin.

I have tried to check if the fingerprint hardware is available.

Sample code is actually given and it looks like so:

```<code>FingerprintAuth.isAvailable(isAvailableSuccess, isAvailableError);

/**
* @return {
*      isAvailable:boolean,
*      isHardwareDetected:boolean,
*      hasEnrolledFingerprints:boolean
*   }
*/

function isAvailableSuccess(result)
{
    console.log("FingerprintAuth available: " + JSON.stringify(result));
    if (result.isAvailable)
    {
       var encryptConfig = {}; // See config object for required parameters
       FingerprintAuth.encrypt(encryptConfig, encryptSuccessCallback, encryptErrorCallback);
    }
}

function isAvailableError(message)
{
    console.log("isAvailableError(): " + message);
}
</code>```

I keep getting errors such as:

```<code>Error: exec proxy not found for :: FingerprintAuth :: availability
</code>```

and

```<code>isAvailableError(): Missing Command Error
</code>```

Am I missing a trick?
Any advice?

答:
Are you running this on the Phonegap App Developer app? If yes it will not work because apparently, even though it runs on the phone, it still uses the browser plugin, which means that the Android fingerprint native API is not available.
Run:

phonegap build android

And you should be able to deploy the APK to your phone and have it working.

Body:
I am currently creating a mobile app with Adobe Phonegap and I am trying to lock a page of the app so that it can only be accessed by fingerprint.

I am completely new to incorporating plugins and using them.

I have been following tutorials such as the ones present on the github of the plugin:

https://github.com/mjwheatley/cordova-plugin-android-fingerprint-auth#module_fingerprintauth.config

I have successfully installed the plugin with the command:

phonegap plugin add cordova-plugin-android-fingerprint-auth

However I don't how to set up and use the plugin.

I have tried to check if the fingerprint hardware is available.

Sample code is actually given and it looks like so:

FingerprintAuth.isAvailable(isAvailableSuccess, isAvailableError);

/**
* @return {
*      isAvailable:boolean,
*      isHardwareDetected:boolean,
*      hasEnrolledFingerprints:boolean
*   }
*/

function isAvailableSuccess(result)
{
    console.log("FingerprintAuth available: " + JSON.stringify(result));
    if (result.isAvailable)
    {
       var encryptConfig = {}; // See config object for required parameters
       FingerprintAuth.encrypt(encryptConfig, encryptSuccessCallback, encryptErrorCallback);
    }
}

function isAvailableError(message)
{
    console.log("isAvailableError(): " + message);
}

I keep getting errors such as:

Error: exec proxy not found for :: FingerprintAuth :: availability

and

isAvailableError(): Missing Command Error

Am I missing a trick?
Any advice?


问:
Call JavaScript function in another file using JavaScript object
I want to call one JavaScript function from another JavaScript file

below is my code:

```<code> var exJS = function () {
     function coolMethod() {
       alert("hello suraj");
     }
  }
</code>```

when I call the function

```<code>var myClass = new exJS();
myClass.coolMethod();
</code>```

Why do I get the error that coolmethod is not defined?

答:
```<code> var exJS = function (){
  function coolMethod() {
    alert("hello suraj");
   }
}
</code>```

this essentially translates to :

```<code> var exJS = function (){
  var coolMethod = function () {
    alert("hello suraj");
   };
}
</code>```

as you can see coolMethod is just a local variable pointing to a function.

use :

```<code>this.coolMethod = function () {
        alert("hello suraj");
       };
</code>```

so coolMethod becomes a member of exJS.

Body:
I want to call one JavaScript function from another JavaScript file

below is my code:

 var exJS = function () {
     function coolMethod() {
       alert("hello suraj");
     }
  }

when I call the function

var myClass = new exJS();
myClass.coolMethod();

Why do I get the error that coolmethod is not defined?

Body:
 var exJS = function (){
  function coolMethod() {
    alert("hello suraj");
   }
}

this essentially translates to :

 var exJS = function (){
  var coolMethod = function () {
    alert("hello suraj");
   };
}

as you can see coolMethod is just a local variable pointing to a function.

use :

this.coolMethod = function () {
        alert("hello suraj");
       };

so coolMethod becomes a member of exJS.


问:
Calculated fields in Laravel using Query Builder
I've been working in a Laravel Project and I want to know how can I show a calculated field in a blade view? I want to retrieve some information from an invoice and a Total calculated field.

I would like to get this result, but using Eloquent ORM. The query is this:

```<code>SELECT
    invoiceheader.id,
    invoiceheader.customerlastname,
    invoiceheader.customerfirstname,
    invoiceheader.customernit,
    invoicedetail.productid,
    invoicedetail.quantity,
    invoicedetail.saleprice,
    (quantity * saleprice) as Total
FROM invoiceheader
INNER JOIN invoicedetail
    ON invoiceheader.id = invoicedetail.invoiceid
</code>```

Thank you so much in advance.

答:
Try this</p>

```<code>InvoiceHeader::join("invoicedetail",function($query){
    $query->on("invoiceheader.id", "=", "invoicedetail.invoiceid")
})
->select("invoiceheader.id",
         "invoiceheader.customerlastname",
         "invoiceheader.customerfirstname",
         "invoiceheader.customernit",
         "invoicedetail.productid",
         "invoicedetail.quantity",
         "invoicedetail.saleprice",
\DB::raw("(invoicedetail.quantity * invoicedetail.saleprice) as Total"))
->get();
</code>```

Body:
I've been working in a Laravel Project and I want to know how can I show a calculated field in a blade view? I want to retrieve some information from an invoice and a Total calculated field.

I would like to get this result, but using Eloquent ORM. The query is this:

SELECT
    invoiceheader.id,
    invoiceheader.customerlastname,
    invoiceheader.customerfirstname,
    invoiceheader.customernit,
    invoicedetail.productid,
    invoicedetail.quantity,
    invoicedetail.saleprice,
    (quantity * saleprice) as Total
FROM invoiceheader
INNER JOIN invoicedetail
    ON invoiceheader.id = invoicedetail.invoiceid

Thank you so much in advance.

Body:
Try this

InvoiceHeader::join("invoicedetail",function($query){
    $query->on("invoiceheader.id", "=", "invoicedetail.invoiceid")
})
->select("invoiceheader.id",
         "invoiceheader.customerlastname",
         "invoiceheader.customerfirstname",
         "invoiceheader.customernit",
         "invoicedetail.productid",
         "invoicedetail.quantity",
         "invoicedetail.saleprice",
\DB::raw("(invoicedetail.quantity * invoicedetail.saleprice) as Total"))
->get();


问:
How to get a user's skills from Microsoft Delve
I am trying to retrieve the skills that are visible on a user's profile in Microsoft Delve, inside of Office 365. It looks like this on the delve web app:

I want to read the skills from a user's profile in our organization. Furthermore I want to update the skills in delve programmatically. Background is that we have an internal solution that is similar to Delve, but has some specific extensions. We want to synchronize content between the two, so we can make use of both platforms.

I looked through the Microsoft Graph API (https://developer.microsoft.com/en-us/graph/docs) but could not find what I need. Is there a way to retrieve the information (and update it) via Graph or another API?

答:
I found the solution. The key is the Microsoft Graph API. Delve itself is only a Graph App.
On the page: https://developer.microsoft.com/en-us/graph/docs/overview/call_api you learn how to read users.

For example you can query your own skills by using:

GET https://graph.microsoft.com/v1.0/me/skills
(Test with Graph Explorer)

Then, on https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_update you learn how to update a user (and e.g. his skills). You do that with:

PATCH https://graph.microsoft.com/v1.0/me and JSON payload:

```<code>{
"skills": [
    "Web API",
    "asp.net",
    "Windows Forms",
    "WPF",
    "Windows",
    "Windows Server",
    "Xamarin.Forms",
    "vb .net",
    "c#",
    "Citrix XenApp",
    ".NET"
    ]
}
</code>```

To update other users you need one of the following scopes:

User.ReadWrite; User.ReadWrite.All; Directory.ReadWrite.All

The URL for other users is: https://graph.microsoft.com/v1.0/Users/>userPrincipalName< or use the user id.

Body:
I found the solution. The key is the Microsoft Graph API. Delve itself is only a Graph App.
On the page: https://developer.microsoft.com/en-us/graph/docs/overview/call_api you learn how to read users.

For example you can query your own skills by using:

GET https://graph.microsoft.com/v1.0/me/skills
(Test with Graph Explorer)

Then, on https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_update you learn how to update a user (and e.g. his skills). You do that with:

PATCH https://graph.microsoft.com/v1.0/me and JSON payload:

{
"skills": [
    "Web API",
    "asp.net",
    "Windows Forms",
    "WPF",
    "Windows",
    "Windows Server",
    "Xamarin.Forms",
    "vb .net",
    "c#",
    "Citrix XenApp",
    ".NET"
    ]
}

To update other users you need one of the following scopes:

User.ReadWrite; User.ReadWrite.All; Directory.ReadWrite.All

The URL for other users is: https://graph.microsoft.com/v1.0/Users/>userPrincipalName< or use the user id.


问:
Identity Server 4 Scopes found on current principal: ""
I attempting to use Identity Server 4 to authenticate users before granting access to a API. I am using a Implicit configuration as the front end is a Ember JS app. I have been able to Login, display the consent screen and then navigate to the redirectUri. However as soon as the Bearer Token is sent to the API I get back a 403.

I was able to find in the logs right before the 403 is returned it states there are not any scopes specified for the current principle. However I have yet to find anyone else reporting the same issue so I am not sure what I am doing wrong.

Any help would be appreciated.

API LOG

```<code>2017-03-27 15:24:35.358 -05:00 [Information] Request starting HTTP/1.1 GET http://localhost:55026/incentives/api/categories application/json
    2017-03-27 15:24:36.035 -05:00 [Information] Successfully validated the token.
    2017-03-27 15:24:36.046 -05:00 [Information] HttpContext.User merged via AutomaticAuthentication from authenticationScheme: "Bearer".
    2017-03-27 15:24:36.048 -05:00 [Information] AuthenticationScheme: "Bearer" was successfully authenticated.
    2017-03-27 15:24:36.051 -05:00 [Information] Scopes found on current principal: ""
    2017-03-27 15:24:36.053 -05:00 [Warning] Scope validation failed. Return 403
    2017-03-27 15:24:36.059 -05:00 [Debug] Connection id ""0HL3L9SNQEILQ"" completed keep alive response.
    2017-03-27 15:24:36.060 -05:00 [Information] Request finished in 702.0523ms 403

new Client
            {
                ClientName = "IncentivesClient",
                ClientId = "IncentivesClient",
                AllowedGrantTypes = GrantTypes.Implicit,
                AllowAccessTokensViaBrowser = true,
                RedirectUris = new List<string>
                {
                    "http://localhost:4200/authorized"
                },
                PostLogoutRedirectUris = new List<string>
                {
                    "http://localhost:4200/unauthorized"
                },
                AllowedCorsOrigins = new List<string>
                {
                    "http://localhost:4200"
                },
                AllowedScopes = new List<string>
                {
                    StandardScopes.OpenId,
                    StandardScopes.Email,
                    StandardScopes.Profile,
                    "incentiveRecords",
                    "incentiverecordsscope",
                }
            }
</code>```

This is the API settings

```<code>IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
        {
            Authority = "https://localhost:44357",
            RequireHttpsMetadata = true,
            AllowedScopes = new List<string> { "incentiveRecords" },
            ApiSecret = "incentiveRecordsSecret",
            ApiName = "incentiveRecords",
            AutomaticAuthenticate = true,
            SupportedTokens = SupportedTokens.Both,
            AuthenticationScheme = "Bearer",
            SaveToken = true,
            ValidateScope = true,
            // TokenRetriever = _tokenRetriever,
            // required if you want to return a 403 and not a 401 for forbidden responses
            AutomaticChallenge = true,
        };
</code>```

答: The example that I had found for implementing your own torii provider for OATH2 had instructed to include 'id_token' and 'token' in the response params  which made sense considering they are the response type being utilized in my Implicit configuration. To add to the confusion both the id_token and token were obtaining values successfully after the promise. It did bother me that they were identical and when I decoded them the audience was set to the client instead of including the resource server. So the super simple answer was to change the 'token' response param to 'access_token'. Now I am able to obtain the correct token from the promise and move on to utilizing it within the Auth header. Hope this helps someone else out there.</p>

Body:
I attempting to use Identity Server 4 to authenticate users before granting access to a API. I am using a Implicit configuration as the front end is a Ember JS app. I have been able to Login, display the consent screen and then navigate to the redirectUri. However as soon as the Bearer Token is sent to the API I get back a 403.

I was able to find in the logs right before the 403 is returned it states there are not any scopes specified for the current principle. However I have yet to find anyone else reporting the same issue so I am not sure what I am doing wrong.

Any help would be appreciated.

API LOG

2017-03-27 15:24:35.358 -05:00 [Information] Request starting HTTP/1.1 GET http://localhost:55026/incentives/api/categories application/json
    2017-03-27 15:24:36.035 -05:00 [Information] Successfully validated the token.
    2017-03-27 15:24:36.046 -05:00 [Information] HttpContext.User merged via AutomaticAuthentication from authenticationScheme: "Bearer".
    2017-03-27 15:24:36.048 -05:00 [Information] AuthenticationScheme: "Bearer" was successfully authenticated.
    2017-03-27 15:24:36.051 -05:00 [Information] Scopes found on current principal: ""
    2017-03-27 15:24:36.053 -05:00 [Warning] Scope validation failed. Return 403
    2017-03-27 15:24:36.059 -05:00 [Debug] Connection id ""0HL3L9SNQEILQ"" completed keep alive response.
    2017-03-27 15:24:36.060 -05:00 [Information] Request finished in 702.0523ms 403

new Client
            {
                ClientName = "IncentivesClient",
                ClientId = "IncentivesClient",
                AllowedGrantTypes = GrantTypes.Implicit,
                AllowAccessTokensViaBrowser = true,
                RedirectUris = new List<string>
                {
                    "http://localhost:4200/authorized"
                },
                PostLogoutRedirectUris = new List<string>
                {
                    "http://localhost:4200/unauthorized"
                },
                AllowedCorsOrigins = new List<string>
                {
                    "http://localhost:4200"
                },
                AllowedScopes = new List<string>
                {
                    StandardScopes.OpenId,
                    StandardScopes.Email,
                    StandardScopes.Profile,
                    "incentiveRecords",
                    "incentiverecordsscope",
                }
            }

This is the API settings

IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
        {
            Authority = "https://localhost:44357",
            RequireHttpsMetadata = true,
            AllowedScopes = new List<string> { "incentiveRecords" },
            ApiSecret = "incentiveRecordsSecret",
            ApiName = "incentiveRecords",
            AutomaticAuthenticate = true,
            SupportedTokens = SupportedTokens.Both,
            AuthenticationScheme = "Bearer",
            SaveToken = true,
            ValidateScope = true,
            // TokenRetriever = _tokenRetriever,
            // required if you want to return a 403 and not a 401 for forbidden responses
            AutomaticChallenge = true,
        };


问:
Select element grows differently than input in display flex
I'm getting an unexpected behavior in my setup. The inputs grow horizontally as expected but on the row with a select control, the growth seems to be distorted.

I suspected some style to be different but a close inspection led me nowhere. Googling gave nothing and I can't find anything about implicit margin nor padding for selects.

What is this about and how do I kill it?

div.full-page {
  margin: 20px;
  padding: 20px;
  background: ghostwhite;
}

div.input-section {
  border: 3px none darkorchid;
  width: 600px;
}

div.input-title {
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  font-size: 18px;
  border-bottom: 2px solid darkorange;
  padding-bottom: 5px;
}

div.input-row {
  border: 3px none darkolivegreen;
  display: flex;
}

div.input-element {
  border: 3px none darkcyan;
  padding: 10px;
  flex-grow: 1;
  // display:flex;
}

div.input-element input,
div.input-element select {
  width: 100%;
  // border: solid 1px mediumvioletred;
  // padding: 0;
  // margin: 0;
}

div.input-caption {
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  color: darkgrey;
  font-size: 14px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="full-page">

  <div>

    <div class="input-section">
      <div class="input-title">Title 1</div>

      <div class="input-row">
        <div class="input-element">
          <div class="input-caption">Uno</div>
          <input type="text" placeholder="Konrad">
        </div>
        <div class="input-element">
          <div class="input-caption">Duo</div>
          <input type="text" placeholder="Viltersten">
        </div>
      </div>

    </div>

    <div #privs class="input-section">
      <div class="input-title">Title 2</div>

      <div class="input-row">
        <div class="input-element">
          <div class="input-caption">Tress</div>
          <input placeholder="Is really">
        </div>

        <div class="input-element">
          <div class="input-caption">Quatro</div>
          <select>
            <option>The one and only</option>
          </select>
        </div>
      </div>

    </div>

</div></code>```

答:
The parent of the select needs to be set at 100% for it to stretch since now it's constrained.

```<code>.input-element {width:100%;}
</code>```

By the way, it has nothing to do with the flex-grow because the issue of width still existed when I removed that style, which led me to see it was the containing element's problem :)

https://jsfiddle.net/hhft4ke6/

div.full-page {
  margin: 20px;
  padding: 20px;
  background: ghostwhite;
}

div.input-section {
  border: 3px none darkorchid;
  width: 600px;
}

div.input-title {
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  font-size: 18px;
  border-bottom: 2px solid darkorange;
  padding-bottom: 5px;
}

div.input-row {
  border: 3px none darkolivegreen;
  display: flex;
}

div.input-element {
  border: 3px none darkcyan;
  padding: 10px;
  flex-grow: 1;
  width:100%;
  // display:flex;
}

div.input-element input,
div.input-element select {
  width: 100%;
  // border: solid 1px mediumvioletred;
  // padding: 0;
  // margin: 0;
}

div.input-caption {
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  color: darkgrey;
  font-size: 14px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="full-page">

  <div>

    <div class="input-section">
      <div class="input-title">Title 1</div>

      <div class="input-row">
        <div class="input-element">
          <div class="input-caption">Uno</div>
          <input type="text" placeholder="Konrad">
        </div>
        <div class="input-element">
          <div class="input-caption">Duo</div>
          <input type="text" placeholder="Viltersten">
        </div>
      </div>

    </div>

    <div #privs class="input-section">
      <div class="input-title">Title 2</div>

      <div class="input-row">
        <div class="input-element">
          <div class="input-caption">Tress</div>
          <input placeholder="Is really">
        </div>

        <div class="input-element">
          <div class="input-caption">Quatro</div>
          <select>
            <option>The one and only</option>
          </select>
        </div>
      </div>

    </div>

</div></code>```

Body:
I'm getting an unexpected behavior in my setup. The inputs grow horizontally as expected but on the row with a select control, the growth seems to be distorted.

I suspected some style to be different but a close inspection led me nowhere. Googling gave nothing and I can't find anything about implicit margin nor padding for selects.

What is this about and how do I kill it?

div.full-page {
  margin: 20px;
  padding: 20px;
  background: ghostwhite;
}

div.input-section {
  border: 3px none darkorchid;
  width: 600px;
}

div.input-title {
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  font-size: 18px;
  border-bottom: 2px solid darkorange;
  padding-bottom: 5px;
}

div.input-row {
  border: 3px none darkolivegreen;
  display: flex;
}

div.input-element {
  border: 3px none darkcyan;
  padding: 10px;
  flex-grow: 1;
  // display:flex;
}

div.input-element input,
div.input-element select {
  width: 100%;
  // border: solid 1px mediumvioletred;
  // padding: 0;
  // margin: 0;
}

div.input-caption {
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  color: darkgrey;
  font-size: 14px;
}

Title 1

Uno

          <input type="text" placeholder="Konrad">

Duo

          <input type="text" placeholder="Viltersten">

Title 2

Tress

          <input placeholder="Is really">

Quatro

          <select>
            <option>The one and only</option>
          </select>

Body:
The parent of the select needs to be set at 100% for it to stretch since now it's constrained.

.input-element {width:100%;}

By the way, it has nothing to do with the flex-grow because the issue of width still existed when I removed that style, which led me to see it was the containing element's problem :)

https://jsfiddle.net/hhft4ke6/

div.full-page {
  margin: 20px;
  padding: 20px;
  background: ghostwhite;
}

div.input-section {
  border: 3px none darkorchid;
  width: 600px;
}

div.input-title {
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  font-size: 18px;
  border-bottom: 2px solid darkorange;
  padding-bottom: 5px;
}

div.input-row {
  border: 3px none darkolivegreen;
  display: flex;
}

div.input-element {
  border: 3px none darkcyan;
  padding: 10px;
  flex-grow: 1;
  width:100%;
  // display:flex;
}

div.input-element input,
div.input-element select {
  width: 100%;
  // border: solid 1px mediumvioletred;
  // padding: 0;
  // margin: 0;
}

div.input-caption {
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  color: darkgrey;
  font-size: 14px;
}

<div class="full-page">

  <div>

    <div class="input-section">
      <div class="input-title">Title 1</div>

      <div class="input-row">
        <div class="input-element">
          <div class="input-caption">Uno</div>
          <input type="text" placeholder="Konrad">
        </div>
        <div class="input-element">
          <div class="input-caption">Duo</div>
          <input type="text" placeholder="Viltersten">
        </div>
      </div>

    </div>

    <div #privs class="input-section">
      <div class="input-title">Title 2</div>

      <div class="input-row">
        <div class="input-element">
          <div class="input-caption">Tress</div>
          <input placeholder="Is really">
        </div>

        <div class="input-element">
          <div class="input-caption">Quatro</div>
          <select>
            <option>The one and only</option>
          </select>
        </div>
      </div>

    </div>

</div>


问:
@NamedNativeQuery + @SqlResultSetMapping + @ConstructorResult + @ColumnResult results in classCastException
I want to select specific columns from the table and store the results to the non-entity POJO.

My Entity class :

```<code>@Entity
@Table(name = "CUSTOMER")
@NamedNativeQuery(name = "findSampleMapping",
    query = "SELECT CUSTOMER_ID, NAME, REG_TIMESTAMP FROM CUSTOMER where CUSTOMER_ID = ?1", resultSetMapping = "SampleMapping")
@SqlResultSetMapping(name="SampleMapping",
classes = {
 @ConstructorResult(targetClass = com.entity.Sample.class,
   columns = {@ColumnResult(name="customerId"), @ColumnResult(name="name"), @ColumnResult(name="regTimeStamp")}
 )}
)
public class CustomerEntity {

    @Id
    @Column(name = "CUSTOMER_ID")
    private String customerId;

    @Column(name = "NAME")
    private String name;

    @Column(name = "FIRST_NAME")
    private String firstName;

   @Column(name = "LAST_NAME")
    private String lastName;

   @Column(name = "REG_TIMESTAMP ")
    private String regTimeStamp;
}
</code>```

Non-entity POJO:

```<code>import java.sql.Timestamp;

    public class Sample {

        private String customerId;
        private String name;
        private TimeStamp regTimeStamp;

        public Sample(String customerId, String name, TimeStamp regTimeStamp){
            this.customerId = customerId;
            this.name = name;
            this.regTimeStamp= regTimeStamp;
        }

        public String getCustomerId() {
            return customerId;
        }
        public void setCustomerId(String customerId) {
            this.customerId = customerId;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getRegTimeStamp() {
            return regTimeStamp;
        }
        public void setRegTimeStamp(String regTimeStamp) {
            this.regTimeStamp= regTimeStamp;
        }

    }
</code>```

Call :

```<code>Query q = em.createNamedQuery("findSampleMapping");
q.setParameter(1, "1");
@SuppressWarnings("unchecked")
List<Sample> list = q.getResultList();

   for (Sample row : list) {
    System.out.println(row.getCustomerId());
   }
</code>```

When I try to loop and get the values, I get classCastException in for loop Ljava.lang.Object; cannot be cast to com.entity.Sample

答:
```<code>List<Sample> list = q.setResultTransformer(Transformers.aliasToBean(Sample.class)).getResultList();
</code>```

Body:
I want to select specific columns from the table and store the results to the non-entity POJO.

My Entity class :

@Entity
@Table(name = "CUSTOMER")
@NamedNativeQuery(name = "findSampleMapping",
    query = "SELECT CUSTOMER_ID, NAME, REG_TIMESTAMP FROM CUSTOMER where CUSTOMER_ID = ?1", resultSetMapping = "SampleMapping")
@SqlResultSetMapping(name="SampleMapping",
classes = {
 @ConstructorResult(targetClass = com.entity.Sample.class,
   columns = {@ColumnResult(name="customerId"), @ColumnResult(name="name"), @ColumnResult(name="regTimeStamp")}
 )}
)
public class CustomerEntity {

    @Id
    @Column(name = "CUSTOMER_ID")
    private String customerId;

    @Column(name = "NAME")
    private String name;

    @Column(name = "FIRST_NAME")
    private String firstName;

   @Column(name = "LAST_NAME")
    private String lastName;

   @Column(name = "REG_TIMESTAMP ")
    private String regTimeStamp;
}

Non-entity POJO:

import java.sql.Timestamp;

    public class Sample {

        private String customerId;
        private String name;
        private TimeStamp regTimeStamp;

        public Sample(String customerId, String name, TimeStamp regTimeStamp){
            this.customerId = customerId;
            this.name = name;
            this.regTimeStamp= regTimeStamp;
        }

        public String getCustomerId() {
            return customerId;
        }
        public void setCustomerId(String customerId) {
            this.customerId = customerId;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getRegTimeStamp() {
            return regTimeStamp;
        }
        public void setRegTimeStamp(String regTimeStamp) {
            this.regTimeStamp= regTimeStamp;
        }

    }

Call :

Query q = em.createNamedQuery("findSampleMapping");
q.setParameter(1, "1");
@SuppressWarnings("unchecked")
List<Sample> list = q.getResultList();

   for (Sample row : list) {
    System.out.println(row.getCustomerId());
   }

When I try to loop and get the values, I get classCastException in for loop Ljava.lang.Object; cannot be cast to com.entity.Sample


问:
Externally loaded sounds echoes in certain browsers
I'm struggeling with a problem where, in Chrome on Mac and in Chrome, Opera and Safari on PC, it appears to be playing sounds twice, generating an unwanted echo-effect with a rather random delay(always under half a second though).

I have 2 swf-files that communictes through a LocalConnection, the main swf simply calls a function on the second swf and passing a url to an mp3-file as parameter. The second swf then loads the file and onComplete plays it.

This works perfectly on IE(that's a first) and Firefox on both mac and PC but echoes as mentioned above.

I even implemented a double-check to make sure a sound wouldn't play if a sound is already playing.

Some sample code:

```<code>var audio:Sound;
var isPlayingSound:Boolean = false;
var soundURL:String;

public function lcRecieve(url:String = ""):void{
    soundURL = url;
    if (soundOn && !isPlayingSound){
        playSound();
    }
}

public function playSound():void {
    if(!isPlayingSound){
        audio = new Sound(new URLRequest(soundURL));
        audio.addEventListener(Event.COMPLETE, onSoundComplete);
    }

}
public function onSoundComplete(e:Event):void{
        audio.play(0, 1).addEventListener(Event.SOUND_COMPLETE, soundFinnishedPlaying);
        isPlayingSound = true;
}

private function soundFinnishedPlaying(e:Event):void {
        e.target.removeEventListener(Event.SOUND_COMPLETE, soundFinnishedPlaying);
        audio = null;
        isPlayingSound = false;
}
</code>```

Anyone stumbeled upon this problem before? I'm very much lost.

答:
```<code>   private var channel:SoundChannel;

   public function onSoundComplete(e:Event):void
   {
      if( channel != null )
           channel.stop();

      channel = audio.play( 0 , 1 );
   }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm struggeling with a problem where, in Chrome on Mac and in Chrome, Opera and Safari on PC, it appears to be playing sounds twice, generating an unwanted echo-effect with a rather random delay(always under half a second though).

I have 2 swf-files that communictes through a LocalConnection, the main swf simply calls a function on the second swf and passing a url to an mp3-file as parameter. The second swf then loads the file and onComplete plays it.

This works perfectly on IE(that's a first) and Firefox on both mac and PC but echoes as mentioned above.

I even implemented a double-check to make sure a sound wouldn't play if a sound is already playing.

Some sample code:

var audio:Sound;
var isPlayingSound:Boolean = false;
var soundURL:String;

public function lcRecieve(url:String = ""):void{
    soundURL = url;
    if (soundOn && !isPlayingSound){
        playSound();
    }
}

public function playSound():void {
    if(!isPlayingSound){
        audio = new Sound(new URLRequest(soundURL));
        audio.addEventListener(Event.COMPLETE, onSoundComplete);
    }

}
public function onSoundComplete(e:Event):void{
        audio.play(0, 1).addEventListener(Event.SOUND_COMPLETE, soundFinnishedPlaying);
        isPlayingSound = true;
}

private function soundFinnishedPlaying(e:Event):void {
        e.target.removeEventListener(Event.SOUND_COMPLETE, soundFinnishedPlaying);
        audio = null;
        isPlayingSound = false;
}

Anyone stumbeled upon this problem before? I'm very much lost.


问:
Ghostscript - PDF to image - Weird bold text
I am not sure, how to describe the problem. I generate a pdf with mpdf. I have a title line with a bold text and in the PDF everything looks fine.

Here is how the text (or part of it looks in the PDF):

Now i try to convert it with ghostscript to jpg:

```<code>gs -dSAFER -dBATCH -sDEVICE=jpeg -dFirstPage=1 -dLastPage=1 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r600 -sOutputFile=image.jpg pdf.pdf
</code>```

And the text looks good, but there is a weird line inside it:

If I change the text to non bold and convert it, everything is ok

Any ideas how th fix this?

答:
Your text isn't really bold. By which I mean its not using a bold font.

Its 'fake bold' and has been created either by drawing the text twice, or by creating a path from the text and both stroking and filling that path, or by drawing the text as text, and stroking the path as well. Without seeing the PDF file I can't, obviously, be sure which approach is being used.

Your problem is that you are using -dTextAlphaBits=4 and -dGraphicsAlphaBits=4, that 'anti-aliases' both text and graphics as it is drawn by blending it with the existing background. So what you are seeing is the boundary between the two objects being dran in such a way that the intersection ends up partially showing the background.

Turn off those two switches and try again.

If you are going to JPEG then there's really no point in using those two switches, the output will be quite blurred enough already.

Body:
I am not sure, how to describe the problem. I generate a pdf with mpdf. I have a title line with a bold text and in the PDF everything looks fine.

Here is how the text (or part of it looks in the PDF):

Now i try to convert it with ghostscript to jpg:

gs -dSAFER -dBATCH -sDEVICE=jpeg -dFirstPage=1 -dLastPage=1 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r600 -sOutputFile=image.jpg pdf.pdf

And the text looks good, but there is a weird line inside it:

If I change the text to non bold and convert it, everything is ok

Any ideas how th fix this?


问:
Subsampling videos to save every Nth frame
I have thousands of 30sec/20fps/.avi videos (so 600 frames total per video). I need to automate subsampling these videos in order to save every 100th frame (every 5 seconds). Any picture format is fine. </p>

<p>Is there an easy way to do this in either Matlab (R2015b) or Python+libraries? </p>

答:
In MATLAB:

you can use VideoWriter object or imwrite, depends on the desired output format:

```<code>vin = VideoReader('vid1.mp4');
vout = VideoWriter('vid-out.mp4');
framenum = 0;
everyNframe = 100;
vout.open();
while vin.hasFrame
    frame = vin.readFrame;
    if rem(framenum,everyNframe) == 0
        vout.writeVideo(frame);
        % OR
        imwrite(frame, [num2str(framenum,'%04i') '.jpg']);
        disp(framenum)
    end
    framenum = framenum + 1;
end
vout.close();
</code>```

another option the ffwd the input video to the next desired frame is by setting vin.CurrentTime, but for some reason it is slower than simply read 100 frames.

Body:
I have thousands of 30sec/20fps/.avi videos (so 600 frames total per video). I need to automate subsampling these videos in order to save every 100th frame (every 5 seconds). Any picture format is fine.

Is there an easy way to do this in either Matlab (R2015b) or Python+libraries?

Body:
In MATLAB:

you can use VideoWriter object or imwrite, depends on the desired output format:

vin = VideoReader('vid1.mp4');
vout = VideoWriter('vid-out.mp4');
framenum = 0;
everyNframe = 100;
vout.open();
while vin.hasFrame
    frame = vin.readFrame;
    if rem(framenum,everyNframe) == 0
        vout.writeVideo(frame);
        % OR
        imwrite(frame, [num2str(framenum,'%04i') '.jpg']);
        disp(framenum)
    end
    framenum = framenum + 1;
end
vout.close();

another option the ffwd the input video to the next desired frame is by setting vin.CurrentTime, but for some reason it is slower than simply read 100 frames.


问:
Reduce space between ticks in horizontal bar-chart chartJS
I am using the horizontal bar chart from chartjs. Right now my Chart seems to be very big, and the space between the ticks on the xAxis is very high. ( I attached picture of that), can anyone tell me how to reduce this space and scale the chart in total better?

My css properties:

```<code>#myChart {
  width: 90% !important;
  height: 100% !important;
  padding-left: 0;
  padding-right: 0;
  margin-left: auto;
  margin-right: auto;
  display: block;
  padding-bottom: 5%;
}
</code>```

My chart options:

```<code>modelChart = new Chart(ctx, {
      type: 'horizontalBar',
      data: data,
      options: {
        scales: {
          yAxes: [{
            ticks: {
              suggestedMin: 0,
              fontSize: 18
            }
          }],
          xAxes: [{
            ticks: {
              autoSkip: false,
              fontSize: 18,
              beginAtZero: true
            }
          }]
        },
        legend: {
          display: false
        },
        tooltips: {
          footerFontSize: 22,
          bodyFontSize: 22,
          titleFontSize: 18
        },
        hover: {
          animationDuration: 0
        }
      }
    });
</code>```

答:
If you post your corresponding HTML then I can confirm this, but is #myChart the id of your canvas element or of a div that contains your canvas element?

Chart.js will render the chart such that it fully fills the parent of the canvas element.  Even if you set a width property on a canvas element it will still not affect the chart size.

Checkout this codepen example that demonstrates the difference.  At the top is a chart contained by a div whose width is set to 40%.  At the bottom is the same chart but the canvas element's width is set to 40%.  Notice that the second chart still fills the entire window.

So long story short, you should wrap your canvas element in a div and set the div's desired size accordingly to actually change the size of your chart.

Now, let me address your question about changing the space between ticks in your X axis.  There is not really a way to truly do this like I think you are wanting to do, because chart.js determines the tick placement by dividing the width of the chart by the number of tick steps (e.g. it always uses the full width of the chart equally).

So one way to decrease the space between ticks is to simply add more ticks (by changing the tick stepSize using the stepSize and fixedStepSize properties).  Obviously, in this case, the chart size has not changed.  You are just showing more ticks, so the space between them has decreased.

If you want to truly change the distance between ticks, then the only way is to decrease the width of the chart.  But by default, the height of the chart will decrease along with the width because the maintainAspectRatio property is defaulted to true.

So if you want a narrower chart (but still want the chart to be large) then I would advise you to set the maintainAspectRatio property to false and manually set the height and width of your chart's parent div.

Checkout this codepen that gives an example of each of the tick spacing concepts that I discussed.

The first chart is the baseline, the second chart adds more ticks (thus decreasing the tick spacing), and the third chart changes the aspect ratio so the chart is still large but narrower (therefore the distance between ticks is reduced).

Body:
I am using the horizontal bar chart from chartjs. Right now my Chart seems to be very big, and the space between the ticks on the xAxis is very high. ( I attached picture of that), can anyone tell me how to reduce this space and scale the chart in total better?

My css properties:

#myChart {
  width: 90% !important;
  height: 100% !important;
  padding-left: 0;
  padding-right: 0;
  margin-left: auto;
  margin-right: auto;
  display: block;
  padding-bottom: 5%;
}

My chart options:

modelChart = new Chart(ctx, {
      type: 'horizontalBar',
      data: data,
      options: {
        scales: {
          yAxes: [{
            ticks: {
              suggestedMin: 0,
              fontSize: 18
            }
          }],
          xAxes: [{
            ticks: {
              autoSkip: false,
              fontSize: 18,
              beginAtZero: true
            }
          }]
        },
        legend: {
          display: false
        },
        tooltips: {
          footerFontSize: 22,
          bodyFontSize: 22,
          titleFontSize: 18
        },
        hover: {
          animationDuration: 0
        }
      }
    });


问:
Socket.IO keeps reconnecting Websocket on Cloudflare
I have a Node/Express app on server dedicated to sockets and on the client it's Angular 1.5. Running the code locally on http using the same architecture e.g. separate socket server it all works perfectly fine.

When I run the code locally it creates one connection and does very little polling via xhr. On cloudflare with https it does a lot of polling, reconnects continually and not all the messages seem to be getting to the web client

messages hit cloudflare which then redirects them to a loadbalancer running haproxy which then routes the requests to an app running in a docker instance on another machine.

答:
After a lot of investigation I found the issue to be down to the config in haproxy. I needed to alter the timeouts around the socket routing.

This was nothing to do with ports not being open on cloudflare.

The following link helped me
http://blog.haproxy.com/2012/11/07/websockets-load-balancing-with-haproxy/


问:
Jasmine function Spy doesn't work with angular
I have an angular-cli project with the following test suite:

```<code>let fakeCellService = {
  getCellOEE: function (value): Observable<Array<IOee>> {
    return Observable.of([{ time: moment(), val: 67 }, { time: moment(), val: 78 }]);
  }
};

describe('Oee24Component', () => {
  let component: any;
  let fixture: ComponentFixture<Oee24Component>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [Oee24Component],
      providers: [{ provide: CellService, useValue: fakeCellService }]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(Oee24Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
    spyOn(fakeCellService, 'getCellOEE');
  });

  it('should get cell oee on init', () => {
    component.ngOnInit();
    expect(fakeCellService.getCellOEE).toHaveBeenCalled();
  });
});
</code>```

However, the Spy in the test fails. I know the function is called, as I tested this in a debugger. I can't see how this differs from the documented examples, but presumably it does! Any ideas why?

Here is my component:

```<code>@Component({
  selector: 'app-oee',
  templateUrl: './oee.component.html',
  styleUrls: ['./oee.component.css']
})
export class Oee24Component implements OnInit {

  constructor(public dataService: CellService) { }

  ngOnInit() {
    this.dataService.getCellOEE(this.cell).subscribe(value => this.updateChart(value));
  }

  updateChart(data: Array<IOee>) {
      //Logic here
  }
}
</code>```

答:
First inject the Injector

```<code> import { Injector } from '@angular/core';
 import { getTestBed } from '@angular/core/testing';
</code>```

Create service variable (below your component variable )

```<code>let service : CellService;
let injector : Injector;
</code>```

Inject it after testbed process ( just below your component instance)

```<code>injector = getTestBed();
service = injector.get(CellService)
</code>```

Now you can spy it

```<code>spyOn(service, 'YourMethod').and.returnValue({ subscribe: () => {} });
</code>```

Let me know if any confusion here is your working describe section code

```<code>describe('Oee24Component', () => {
 let component: any;
 let fixture: ComponentFixture<Oee24Component>;
 let injector: Injector;
 let service: CellService;

 beforeEach(async(() => {
  TestBed.configureTestingModule({
   declarations: [Oee24Component],
   providers: [{ provide: CellService, useValue: fakeCellService }]
  })
  .compileComponents();
 }));

 beforeEach(() => {
  fixture = TestBed.createComponent(Oee24Component);
  component = fixture.componentInstance;
  injector = getTestBed();
  service = injector.get(CellService)
  fixture.detectChanges();
  spyOn(service, 'getCellOEE').and.returnValue({ subscribe : () => {} });
 });

 it('should get cell oee on init', () => {
  component.ngOnInit();
  expect(service.getCellOEE).toHaveBeenCalled();
 });
});
</code>```

Body:
I have an angular-cli project with the following test suite:

let fakeCellService = {
  getCellOEE: function (value): Observable<Array<IOee>> {
    return Observable.of([{ time: moment(), val: 67 }, { time: moment(), val: 78 }]);
  }
};

describe('Oee24Component', () => {
  let component: any;
  let fixture: ComponentFixture<Oee24Component>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [Oee24Component],
      providers: [{ provide: CellService, useValue: fakeCellService }]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(Oee24Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
    spyOn(fakeCellService, 'getCellOEE');
  });

  it('should get cell oee on init', () => {
    component.ngOnInit();
    expect(fakeCellService.getCellOEE).toHaveBeenCalled();
  });
});

However, the Spy in the test fails. I know the function is called, as I tested this in a debugger. I can't see how this differs from the documented examples, but presumably it does! Any ideas why?

Here is my component:

@Component({
  selector: 'app-oee',
  templateUrl: './oee.component.html',
  styleUrls: ['./oee.component.css']
})
export class Oee24Component implements OnInit {

  constructor(public dataService: CellService) { }

  ngOnInit() {
    this.dataService.getCellOEE(this.cell).subscribe(value => this.updateChart(value));
  }

  updateChart(data: Array<IOee>) {
      //Logic here
  }
}

Body:
First inject the Injector

 import { Injector } from '@angular/core';
 import { getTestBed } from '@angular/core/testing';

Create service variable (below your component variable )

let service : CellService;
let injector : Injector;

Inject it after testbed process ( just below your component instance)

injector = getTestBed();
service = injector.get(CellService)

Now you can spy it

spyOn(service, 'YourMethod').and.returnValue({ subscribe: () => {} });

Let me know if any confusion here is your working describe section code

describe('Oee24Component', () => {
 let component: any;
 let fixture: ComponentFixture<Oee24Component>;
 let injector: Injector;
 let service: CellService;

 beforeEach(async(() => {
  TestBed.configureTestingModule({
   declarations: [Oee24Component],
   providers: [{ provide: CellService, useValue: fakeCellService }]
  })
  .compileComponents();
 }));

 beforeEach(() => {
  fixture = TestBed.createComponent(Oee24Component);
  component = fixture.componentInstance;
  injector = getTestBed();
  service = injector.get(CellService)
  fixture.detectChanges();
  spyOn(service, 'getCellOEE').and.returnValue({ subscribe : () => {} });
 });

 it('should get cell oee on init', () => {
  component.ngOnInit();
  expect(service.getCellOEE).toHaveBeenCalled();
 });
});


问:
how will i know the size of user control?
How will I know the size of user control at run time?

I have a form, and I wanted to host my usercontrol on that form, and I wanted
to know  my user control size at run time to fix my webform size according to
my user control size, so that scroll should not appear while opening the form.

How can I do that?

(actually there are multiple Usercontrols, and I am hosting a user control at run time
according to a condition.)

答: You can expose a .Size property that would contain the height/width of user control. While rendering the control, you read the .Size and process accordingly.


问:
TupleWindow Start/End Time in Apache Storm
I have been developing a profilling application works on CDR(Call Detail Record) data in Apache Storm. Application's main purpose is extracting of Caller TotalCallCount and TotalCallDuration during a specified time block(in every window). For profilling I want to use SlidingWindow technique.

To understand you can look at following image
SlidingWindow Image

For profilling I need to know when TupleWindow started and ended. I mean what is the timestamp of TupleWindow or timestamp of SlidingWindow for start and end.

Even if I looked up implementation of Storm, I couldn't find anything about that. Could you help me about how can figure it out?

Thank you very much

答:
If you are using a 1.x release of apache Storm, this information is not directly accessible via the TupleWindow. You will have to manually calculate this. E.g.

```<code>public class MyBolt extends BaseWindowedBolt {
  ...
  long slidingInterval;

  @Override
  public BaseWindowedBolt withWindow(Duration windowLength, Duration slidingInterval) {
      this.slidingInterval = slidingInterval.value;
      return super.withWindow(windowLength, slidingInterval);
  }

  public void execute(TupleWindow inputWindow) {
    long now = System.currentTimeMillis();
    long windowEnd = now;
    long windowStart = now - slidingInterval;
    ...
  }
</code>```

But it may not be pretty straight forward in all cases especially if you are having event time windows.

In the latest master branch of storm, the TupleWindow has a getTimestamp method which returns the window end timestamp and works for both processing and event time based windows. This will be available in the future release of storm (2.0 release). It could be back ported and made available in future Storm 1.x releases as well.

Body:
If you are using a 1.x release of apache Storm, this information is not directly accessible via the TupleWindow. You will have to manually calculate this. E.g.

public class MyBolt extends BaseWindowedBolt {
  ...
  long slidingInterval;

  @Override
  public BaseWindowedBolt withWindow(Duration windowLength, Duration slidingInterval) {
      this.slidingInterval = slidingInterval.value;
      return super.withWindow(windowLength, slidingInterval);
  }

  public void execute(TupleWindow inputWindow) {
    long now = System.currentTimeMillis();
    long windowEnd = now;
    long windowStart = now - slidingInterval;
    ...
  }

But it may not be pretty straight forward in all cases especially if you are having event time windows.

In the latest master branch of storm, the TupleWindow has a getTimestamp method which returns the window end timestamp and works for both processing and event time based windows. This will be available in the future release of storm (2.0 release). It could be back ported and made available in future Storm 1.x releases as well.


问:
How to find the maximum length of data in a particular field in postgresql?
I have a table "Users" and one of the column is "USERNAME". I am trying to find out the maximum length of the username by comparing all the usernames. I need this max value to use for another query. I tried

```<code>SELECT  max(length(users.username)),username
FROM users group by username;
</code>```

returns all the rows.

Example:

 USERNAME
----------
Tara
Amyamyse
Tommy
John
```

<p>I would like to get the result as below:</p>

<pre class="lang-none prettyprint-override"><code>MAX_Length     USERNAME
--------------------
  8             Amyamyse
</code>```

答:
Another option:

```<code>select username, length(username) as username_length
from users
where length(username) = (select max(length(username)) from users)
</code>```

This would return multiple users in case there be a tie for the longest username.  If you have specific rules for breaking a tie then update your question.

ContentLicense: CC BY-SA 4.0

Body:
I have a table "Users" and one of the column is "USERNAME". I am trying to find out the maximum length of the username by comparing all the usernames. I need this max value to use for another query. I tried

SELECT  max(length(users.username)),username
FROM users group by username;

returns all the rows.

Example:

 USERNAME
----------
Tara
Amyamyse
Tommy
John

I would like to get the result as below:

MAX_Length     USERNAME
--------------------
  8             Amyamyse

Body:
Another option:

select username, length(username) as username_length
from users
where length(username) = (select max(length(username)) from users)

This would return multiple users in case there be a tie for the longest username.  If you have specific rules for breaking a tie then update your question.


问:
Split select options into sections
I got a question about the select box in HTML where I can't seem to find the answer on with Google.

I have a select html field with 1000 options:

```<code><option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
....
</code>```

Now I can show the visitor all the options in 1 select box but when he needs the number 877 he needs to scroll all the way down. Is it possible to transform the select box (with javascript, or something else, PHP is also an option) to make the select box step based. So for example first you get 5 choices:

```<code><option value="1-200">1-200</option>
<option value="201-400">201-400</option>
<option value="401-600">401-600</option>
<option value="601-800">601-800</option>
<option value="801-1000">801-1000</option>
</code>```

And when he selects one of those it becomes 1-50, 51-100, 101-150, 151-200

I searched if Chosen could do this but I don't see an option where this is possible. You could search for a number but that is my last option if this isn't possible.

答:
There are several ways of acomplishing what you want....

As suggested by @Rory, Select2 is a very good option since it
has search capability.

However, if you must, you can count your array, then split into
your desired chunk size, then insert each chunk as an optgroup
element into the select, then upon clicking a group, it expands to show the options inside the group.

The other way to do it is look for a plugin that has tree

You can also use two select boxes, one to select the group, and the
other for options

Title: Split select options into sections

Body:
I got a question about the select box in HTML where I can't seem to find the answer on with Google.

I have a select html field with 1000 options:

<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
....

Now I can show the visitor all the options in 1 select box but when he needs the number 877 he needs to scroll all the way down. Is it possible to transform the select box (with javascript, or something else, PHP is also an option) to make the select box step based. So for example first you get 5 choices:

<option value="1-200">1-200</option>
<option value="201-400">201-400</option>
<option value="401-600">401-600</option>
<option value="601-800">601-800</option>
<option value="801-1000">801-1000</option>

And when he selects one of those it becomes 1-50, 51-100, 101-150, 151-200

I searched if Chosen could do this but I don't see an option where this is possible. You could search for a number but that is my last option if this isn't possible.


问:
Symfony Forms: HTML5 datalist
How can be implemented HTML5 datalist with values from the database (Doctrine)?

Purpose: replace selects with many options to inputs with autocompletion.

答:
In your formType :

```<code>->add('commerciaux', TextType::class,
            [
                'label'     => 'Apporteur d\'affaire*',
                'attr'      =>
                    [
                        'placeholder'   => 'Apporteur d\'affaire',
                        'list'          => 'bieres'
                    ]
            ]
        )
</code>```

In your View :

```<code>                    {{ form_row(formulaire.commerciaux) }}
                    <datalist id="bieres">
                        <option value="Meteor">
                        <option value="Pils">
                        <option value="Kronenbourg">
                        <option value="Grimbergen">
                    </datalist>
</code>```

Title: Symfony Forms: HTML5 datalist

Body:
In your formType :

->add('commerciaux', TextType::class,
            [
                'label'     => 'Apporteur d\'affaire*',
                'attr'      =>
                    [
                        'placeholder'   => 'Apporteur d\'affaire',
                        'list'          => 'bieres'
                    ]
            ]
        )

In your View :

                    {{ form_row(formulaire.commerciaux) }}
                    <datalist id="bieres">
                        <option value="Meteor">
                        <option value="Pils">
                        <option value="Kronenbourg">
                        <option value="Grimbergen">
                    </datalist>


答:
You will have use a subquery because the group by will prevent desired results if you were to use a HAVING clause

```<code>SELECT name, LENGTH(name)
FROM your_table
WHERE LENGTH(name)=( SELECT MAX(length(name)) FROM your_table)
GROUP BY name
</code>```

additionally you can test the answer on this sqlfiddler
http://sqlfiddle.com/#!15/c0ff8/5

Title: How to find the maximum length of data in a particular field in postgresql?

Body:
You will have use a subquery because the group by will prevent desired results if you were to use a HAVING clause

SELECT name, LENGTH(name)
FROM your_table
WHERE LENGTH(name)=( SELECT MAX(length(name)) FROM your_table)
GROUP BY name

additionally you can test the answer on this sqlfiddler
http://sqlfiddle.com/#!15/c0ff8/5


问:
DownloadManager getFilesDir()
I need to download the file to the internal memory of the device. I do it this way:

```<code>Uri downloadUri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setDestinationInExternalFilesDir(getContext(),getContext().getFilesDir().getAbsolutePath(), name);
</code>```

The file loads successfully. I need to check the presence of this file so I do not have to download it again:

```<code>File file = new File(getContext().getFilesDir().getAbsolutePath(), name);
if (!file.exists()) {
   ...
}
</code>```

The check does not work, the file always loads again.
I also try to get a file for MediaPlayer()

```<code>String path = "file://" + getContext().getFilesDir().getAbsolutePath() + File.separator + name;
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(getContext(), Uri.parse(path));
</code>```

This also does not work...
What am I doing wrong?

答:
you are saving the file to device internal memory but while trying to get the file you are searching in app's private memory. Which is different from download localtion

setDestinationInExternalPublicDir

DownloadManager.Request setDestinationInExternalPublicDir (String dirType,
                  String subPath)
  Set the local destination for the downloaded file to a path within the public external storage directory (as returned by getExternalStoragePublicDirectory(String)).

The downloaded file is not scanned by MediaScanner. But it can be made scannable by calling allowScanningByMediaScanner().

getFilesDir

File getFilesDir ()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

The returned path may change over time if the calling app is moved to an adopted storage device, so only relative paths should be persisted.

No additional permissions are required for the calling app to read or write files under the returned path.

Title: DownloadManager getFilesDir()

Body:
I need to download the file to the internal memory of the device. I do it this way:

Uri downloadUri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setDestinationInExternalFilesDir(getContext(),getContext().getFilesDir().getAbsolutePath(), name);

The file loads successfully. I need to check the presence of this file so I do not have to download it again:

File file = new File(getContext().getFilesDir().getAbsolutePath(), name);
if (!file.exists()) {
   ...
}

The check does not work, the file always loads again.
I also try to get a file for MediaPlayer()

String path = "file://" + getContext().getFilesDir().getAbsolutePath() + File.separator + name;
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(getContext(), Uri.parse(path));

This also does not work...
What am I doing wrong?


问:
wrap h.264 stream in mp.4 container and stream it with nodejs
I have a stream of h.264 data from a remote webcam. If i save it to a file i'm able to play it in VLC (meaning that the data arrives intact).

The final goal is to turn this stream into a virtual webcam. After looking around I found manyCam as a possible solution - therefor i want to serve the h.264 data on a local IP in MP4 format.

Two questions:

first, I'm trying to wrap the h.264 with the mp4 container using ffmpeg (using fluent-ffmpeg npm library that exposes the ffmpeg API to Nodejs).

Everything works well when i'm handling static files (not streams). e.g.`

```<code>var ffmpeg = rquire('fluent-ffmpeg')
var readH264 = fs.createReadStream('./vid.h264')
var proc = ffmpeg(readH264).clone().toFormat('mp4').output('./vid.mp4').run()
</code>```

`

But when I'm trying to feed a stream - it throws an error "ffmpeg exited with code 1: could not write header for output file.."
`

```<code>var wrtieMp4 = fs.createWriteStream('./vid.mp4')
var proc = ffmpeg(readH264).clone().toFormat('mp4').output(wrtieMp4).run()`
</code>```

How can i add it a header..?

Second, I'm a bit confused about the transport layer (rtp, rtsp, etc.). After creating the mp4 stream - wouldn't it be sufficient to serve the stream with MIME type video/mp4? It seem to work fine with static file.
`

```<code>let read = fs.createReadStream('./vid.mp4')
let server = http.createServer(function (req, res) {
        res.writeHead(200, {'Content-type': "video/mp4"})
        read.pipe(res)
}).listen(9000)
</code>```

`

答: You can not use MP4 for this purpose. MP4 must write the header at the beginning of the file after the stream is closed. You get "can not write header" error, because ffmpeg knows it will not be able to rewind the stream and write the header later. No, you can not use rtsp eaither.  The browser can only do http. Use a format like DASH that was designed for this purpose. </p>

Body:
I have a stream of h.264 data from a remote webcam. If i save it to a file i'm able to play it in VLC (meaning that the data arrives intact).

The final goal is to turn this stream into a virtual webcam. After looking around I found manyCam as a possible solution - therefor i want to serve the h.264 data on a local IP in MP4 format.

Two questions:

first, I'm trying to wrap the h.264 with the mp4 container using ffmpeg (using fluent-ffmpeg npm library that exposes the ffmpeg API to Nodejs).

Everything works well when i'm handling static files (not streams). e.g.`

var ffmpeg = rquire('fluent-ffmpeg')
var readH264 = fs.createReadStream('./vid.h264')
var proc = ffmpeg(readH264).clone().toFormat('mp4').output('./vid.mp4').run()

`

But when I'm trying to feed a stream - it throws an error "ffmpeg exited with code 1: could not write header for output file.."
`

var wrtieMp4 = fs.createWriteStream('./vid.mp4')
var proc = ffmpeg(readH264).clone().toFormat('mp4').output(wrtieMp4).run()`

How can i add it a header..?

Second, I'm a bit confused about the transport layer (rtp, rtsp, etc.). After creating the mp4 stream - wouldn't it be sufficient to serve the stream with MIME type video/mp4? It seem to work fine with static file.
`

let read = fs.createReadStream('./vid.mp4')
let server = http.createServer(function (req, res) {
        res.writeHead(200, {'Content-type': "video/mp4"})
        read.pipe(res)
}).listen(9000)

`


问:
Display XIB erorr nil
I am new to Swift and I am beginning to learn XIB.  I want to pressing the button appears XIB.
I using liberty ARSPopover

my error :

Warning: Attempt to present   on
   which is already
  presenting (null)

How can I solve this problem?

My code for  button :

```<code>- (IBAction)btnShoPopover:(UIBarButtonItem *)sender {
    ARSPopover *popoverController = [ARSPopover new];
    popoverController.sourceView = self.view;
    popoverController.sourceRect = CGRectMake(370,0, 0, 0);
    popoverController.contentSize = CGSizeMake(200,300);
    popoverController.arrowDirection = UIPopoverArrowDirectionUp;

    [self presentViewController:popoverController animated:YES completion:^{
        [popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
            PopovViewController *poper = [[PopovViewController alloc] init];
            [self presentViewController:poper animated:YES completion:nil];

        }];
    }];
}
</code>```

I my xib don't download:

My code for xib controller:

```<code>@interface PopovViewController ()
@end
@implementation PopovViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
</code>```

My controller:

```<code>#import "ResourseTableViewController.h"
#import "ProbaViewController.h"

@interface ResourseTableViewController ()
@end

@implementation ResourseTableViewController

@synthesize arrayOriginal;
@synthesize arForTable;

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDictionary *dTmp=[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];
    self.arrayOriginal=[dTmp valueForKey:@"Objects"];

    self.arForTable=[[NSMutableArray alloc] init] ;
    [self.arForTable addObjectsFromArray:self.arrayOriginal];

    SWRevealViewController *revealViewController = self.revealViewController;
    if ( revealViewController )
    {
        [self.sidebarButton setTarget: self.revealViewController];
        [self.sidebarButton setAction: @selector( revealToggle: )];
        [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [self.arForTable count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    }
    [cell setIndentationLevel:[[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"level"] intValue]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSDictionary *d=[self.arForTable objectAtIndex:indexPath.row];

    NSLog(@"Selected index data %@",d);

    if([d valueForKey:@"Objects"]) {
        NSArray *ar=[d valueForKey:@"Objects"];

        BOOL isAlreadyInserted=NO;

        for(NSDictionary *dInner in ar ){
            NSInteger index=[self.arForTable indexOfObjectIdenticalTo:dInner];
            isAlreadyInserted=(index>0 && index!=NSIntegerMax);
            if(isAlreadyInserted) break;
        }

        if(isAlreadyInserted) {
            [self miniMizeThisRows:ar];
        } else {
            NSUInteger count=indexPath.row+1;
            NSMutableArray *arCells=[NSMutableArray array];
            for(NSDictionary *dInner in ar ) {
                [arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
                [self.arForTable insertObject:dInner atIndex:count++];
            }
            [tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

- (IBAction)btnPopover:(id)sender {

    ARSPopover *popoverController = [ARSPopover new];
    popoverController.sourceView = self.view;
    popoverController.sourceRect = CGRectMake(370,0, 0, 0);
    popoverController.contentSize = CGSizeMake(200,300);
    popoverController.arrowDirection = UIPopoverArrowDirectionUp;

    [self presentViewController:popoverController animated:NO  completion:^{
        [popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
            ProbaViewController *poper = [[ProbaViewController alloc] init];
            CGFloat width = popoverPresentedSize.width;
            CGFloat height = popoverPresentedSize.height - popoverArrowHeight;
            poper.view.frame = CGRectMake(0, 0, width, height);

            popover.view.layer.backgroundColor = [UIColor clearColor].CGColor;

            [popover.view addSubview:poper.view];
        }];
    }];
}

-(void)miniMizeThisRows:(NSArray*)ar{

    for(NSDictionary *dInner in ar ) {
        NSUInteger indexToRemove=[self.arForTable indexOfObjectIdenticalTo:dInner];
        NSArray *arInner=[dInner valueForKey:@"Objects"];
        if(arInner && [arInner count]>0){
            [self miniMizeThisRows:arInner];
        }
        if([self.arForTable indexOfObjectIdenticalTo:dInner]!=NSNotFound) {
            [self.arForTable removeObjectIdenticalTo:dInner];
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:
                                                    [NSIndexPath indexPathForRow:indexToRemove inSection:0]
                                                    ]
                                  withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}
@end
</code>```

答:
Skimming the docs, it looks like the library is very versatile with respect to what's presented in the popover.  Your code provides a clue that you hope to present a custom view controller within it (a PopovViewController).

EDIT Let's find out first where the problem lies.  If everything else is working properly, then this code should present a green box...

```<code>[self presentViewController:popoverController animated:YES completion:^{
    [popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
        CGFloat width = popoverPresentedSize.width;
        CGFloat height = popoverPresentedSize.height - popoverArrowHeight;
        UIView *test = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
        test.backgroundColor = [UIColor greenColor];
        [popover.view addSubview:test];
    }];
}];
</code>```

If that works, we can proceed to discovering why your PopovViewController's view is causing trouble.  (My guess is that it's presentation is triggering  some other presentation animation that conflicts with the 3rd party library.

If you get a working green view with no warnings or errors, post the code for PopovViewController's viewDidLoad, viewWillAppear, ...didAppear, ...didLayout, etc.

Title: Display XIB erorr nil

Body:
I am new to Swift and I am beginning to learn XIB.  I want to pressing the button appears XIB.
I using liberty ARSPopover

my error :

Warning: Attempt to present   on
   which is already
  presenting (null)

How can I solve this problem?

My code for  button :

- (IBAction)btnShoPopover:(UIBarButtonItem *)sender {
    ARSPopover *popoverController = [ARSPopover new];
    popoverController.sourceView = self.view;
    popoverController.sourceRect = CGRectMake(370,0, 0, 0);
    popoverController.contentSize = CGSizeMake(200,300);
    popoverController.arrowDirection = UIPopoverArrowDirectionUp;

    [self presentViewController:popoverController animated:YES completion:^{
        [popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
            PopovViewController *poper = [[PopovViewController alloc] init];
            [self presentViewController:poper animated:YES completion:nil];

        }];
    }];
}

I my xib don't download:

My code for xib controller:

@interface PopovViewController ()
@end
@implementation PopovViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

My controller:

#import "ResourseTableViewController.h"
#import "ProbaViewController.h"

@interface ResourseTableViewController ()
@end

@implementation ResourseTableViewController

@synthesize arrayOriginal;
@synthesize arForTable;

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDictionary *dTmp=[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];
    self.arrayOriginal=[dTmp valueForKey:@"Objects"];

    self.arForTable=[[NSMutableArray alloc] init] ;
    [self.arForTable addObjectsFromArray:self.arrayOriginal];

    SWRevealViewController *revealViewController = self.revealViewController;
    if ( revealViewController )
    {
        [self.sidebarButton setTarget: self.revealViewController];
        [self.sidebarButton setAction: @selector( revealToggle: )];
        [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [self.arForTable count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    }
    [cell setIndentationLevel:[[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"level"] intValue]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSDictionary *d=[self.arForTable objectAtIndex:indexPath.row];

    NSLog(@"Selected index data %@",d);

    if([d valueForKey:@"Objects"]) {
        NSArray *ar=[d valueForKey:@"Objects"];

        BOOL isAlreadyInserted=NO;

        for(NSDictionary *dInner in ar ){
            NSInteger index=[self.arForTable indexOfObjectIdenticalTo:dInner];
            isAlreadyInserted=(index>0 && index!=NSIntegerMax);
            if(isAlreadyInserted) break;
        }

        if(isAlreadyInserted) {
            [self miniMizeThisRows:ar];
        } else {
            NSUInteger count=indexPath.row+1;
            NSMutableArray *arCells=[NSMutableArray array];
            for(NSDictionary *dInner in ar ) {
                [arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
                [self.arForTable insertObject:dInner atIndex:count++];
            }
            [tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

- (IBAction)btnPopover:(id)sender {

    ARSPopover *popoverController = [ARSPopover new];
    popoverController.sourceView = self.view;
    popoverController.sourceRect = CGRectMake(370,0, 0, 0);
    popoverController.contentSize = CGSizeMake(200,300);
    popoverController.arrowDirection = UIPopoverArrowDirectionUp;

    [self presentViewController:popoverController animated:NO  completion:^{
        [popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
            ProbaViewController *poper = [[ProbaViewController alloc] init];
            CGFloat width = popoverPresentedSize.width;
            CGFloat height = popoverPresentedSize.height - popoverArrowHeight;
            poper.view.frame = CGRectMake(0, 0, width, height);

            popover.view.layer.backgroundColor = [UIColor clearColor].CGColor;

            [popover.view addSubview:poper.view];
        }];
    }];
}

-(void)miniMizeThisRows:(NSArray*)ar{

    for(NSDictionary *dInner in ar ) {
        NSUInteger indexToRemove=[self.arForTable indexOfObjectIdenticalTo:dInner];
        NSArray *arInner=[dInner valueForKey:@"Objects"];
        if(arInner && [arInner count]>0){
            [self miniMizeThisRows:arInner];
        }
        if([self.arForTable indexOfObjectIdenticalTo:dInner]!=NSNotFound) {
            [self.arForTable removeObjectIdenticalTo:dInner];
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:
                                                    [NSIndexPath indexPathForRow:indexToRemove inSection:0]
                                                    ]
                                  withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}
@end

Body:
Skimming the docs, it looks like the library is very versatile with respect to what's presented in the popover.  Your code provides a clue that you hope to present a custom view controller within it (a PopovViewController).

EDIT Let's find out first where the problem lies.  If everything else is working properly, then this code should present a green box...

[self presentViewController:popoverController animated:YES completion:^{
    [popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
        CGFloat width = popoverPresentedSize.width;
        CGFloat height = popoverPresentedSize.height - popoverArrowHeight;
        UIView *test = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
        test.backgroundColor = [UIColor greenColor];
        [popover.view addSubview:test];
    }];
}];

If that works, we can proceed to discovering why your PopovViewController's view is causing trouble.  (My guess is that it's presentation is triggering  some other presentation animation that conflicts with the 3rd party library.

If you get a working green view with no warnings or errors, post the code for PopovViewController's viewDidLoad, viewWillAppear, ...didAppear, ...didLayout, etc.


问:
Div overlay two sibling div who will fill parent
I have 4 div, which look something like this

Desired output:

Current code:

```<code><div class="center aligned" style="width: 100%;height: 7em; padding: 2em; position:absolute;">
    <div class="ui small grey label fluid progress_padding_top_bottom" style="z-index:1;height: 7em; border-radius: 0; padding-right: 0; padding-left: 0; background-color: #E8E8E8 !important;">
    <div style="background-color: #21BA45; width: 5%; height: 7em; float:left;"></div>
    <div style="background-color: #ffdd00; width: 20%; height: 7em; float:left;"></div>
    <div style="width: 100%;" class="center aligned">ABC</div>
</div>
</code>```

Update: This is a part of a progress bar, so both red and yellow width will change

答:
Wrap the colored divs in their own container and position it absolutely unde rthe content.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.wrapper {
  width: 50%;
  margin: 1em auto;
  background: lightgrey;
  height: 7em;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  font-weight: bold;
}

.content {
  position: relative;
  z-index: 1;
}

.underlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.red {
  height: 100%;
  background: red;
  width: 25%;
  float: left;
}

.yellow {
  height: 100%;
  background: yellow;
  float: left;
  width: 25%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="content">ABC</div>
  <div class="underlay">
    <div class="red"></div>
    <div class="yellow"></div>
  </div>
</div></code>```

Body:
I have 4 div, which look something like this

Desired output:

Current code:

ABC

Update: This is a part of a progress bar, so both red and yellow width will change

Body:
Wrap the colored divs in their own container and position it absolutely unde rthe content.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.wrapper {
  width: 50%;
  margin: 1em auto;
  background: lightgrey;
  height: 7em;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  font-weight: bold;
}

.content {
  position: relative;
  z-index: 1;
}

.underlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.red {
  height: 100%;
  background: red;
  width: 25%;
  float: left;
}

.yellow {
  height: 100%;
  background: yellow;
  float: left;
  width: 25%;
}

<div class="wrapper">
  <div class="content">ABC</div>
  <div class="underlay">
    <div class="red"></div>
    <div class="yellow"></div>
  </div>
</div>


问:
NSIS SetDateSave error
I'm using the flag "SetDateSave on" ( default value in a .nsis script ) in order to preserve the Last Modified value of future installed files. The flag works correctly on nearly all files, but for some of them the "Last modified" date is 1 second before the real date. Why this happen?

I'm using NULLsoft 2.51.

答: Not all filesystems have the same time granularity, FAT only has two second granularity. NSIS tweaks the time a little bit so date based overwrite comparisons work better.</p>

Title: NSIS SetDateSave error


问:
Spark: cannot resolve input columns
I have

```<code>val colNames = data.schema.fieldNames
.filter(colName => colName.split("-")(0) == "20003" || colName == "eid")
</code>```

which I then use to select a subset of a dataframe:

```<code>var medData = data.select(colNames.map(c => col(c)): _*).rdd
</code>```

but I get

```<code>cannot resolve '`20003-0.0`' given input columns:
[20003-0.0, 20003-0.1, 20003-0.2, 20003-0.3];;
</code>```

What is going on?

答:
I had to include backticks like this:

```<code>var medData = data.select(colNames.map(c => col(s"`$c`")): _*).rdd
</code>```

spark is for some reason adding the backticks

Title: Spark: cannot resolve input columns

Body:
I have

val colNames = data.schema.fieldNames
.filter(colName => colName.split("-")(0) == "20003" || colName == "eid")

which I then use to select a subset of a dataframe:

var medData = data.select(colNames.map(c => col(c)): _*).rdd

but I get

cannot resolve '`20003-0.0`' given input columns:
[20003-0.0, 20003-0.1, 20003-0.2, 20003-0.3];;

What is going on?

Body:
I had to include backticks like this:

var medData = data.select(colNames.map(c => col(s"`$c`")): _*).rdd

spark is for some reason adding the backticks


问:
SQL Basics If Column A is not empty then on Column B use
Hi All just starting out with SQL. would like to ask.
For example if given:

Result:

Explanation:

If column B is not empty the use Column B in Column E

If Column B is empty then use column D in Column E

If Column B and D is empty then leave  Column E as empty

How would you make this work in SQL?

答:
you can try using case statement as below:
select case b is not null then e=b else case d is not null then e=d else e=null end end</p>