问:
Google Api PHP Client - How to login
I'm trying to connect using the api of google using php to loggearme with the user of gmail and retrieve the calendars I have, for this I use this code.
What I get is loggearme and that oauth2 I return the TOKEN but once I have this token I do not know how to use it to get the details of my google calendar.

Thank you

Settings.php

```<code>/* Google App Client Id */
define('CLIENT_ID', 'XXXXXXXX.apps.googleusercontent.com');

/* Google App Client Secret */
 define('CLIENT_SECRET', 'XXXXXXX');

 /* Google App Redirect Url */
 define('CLIENT_REDIRECT_URL',
 'http://localhost:8081/googleTesting/oauth2callback.php');

    <html>
<head>....</head>

<body>

 <a href="<?= 'https://accounts.google.com/o/oauth2/auth?scope=' . urlencode('https://www.googleapis.com/auth/userinfo.profile') . '&redirect_uri=' . urlencode(CLIENT_REDIRECT_URL) . '&response_type=code&client_id=' . CLIENT_ID . '&access_type=online' ?>">Login with Google</a>
<br>

   </body>
 </html>
</code>```

Calendar.php

```<code>//  We have access we can now create our service
if (isset($_SESSION['datosGoogle']['access_token'])) {

$client = new Google_Client();
$client->setAccessToken($_SESSION['datosGoogle']['access_token']);
print "LogOut";

$service = new Google_Service_Calendar($client);

$calendarList  = $service->calendarList->listCalendarList();;

while(true) {
    foreach ($calendarList->getItems() as $calendarListEntry) {

        echo $calendarListEntry->getSummary()."\n";

        // get events
        $events = $service->events->listEvents($calendarListEntry->id);

        foreach ($events->getItems() as $event) {
            echo "-----".$event->getSummary()."";
        }
    }
    $pageToken = $calendarList->getNextPageToken();
    if ($pageToken) {
        $optParams = array('pageToken' => $pageToken);
        $calendarList = $service->calendarList->listCalendarList($optParams);
    } else {
        break;
    }
}
</code>```

}

答:
When you request a login to google you add scope in that request.

Google has better answer. Google tutorial,Google php implementation

This part is important to highlight.

```<code>//import libraries php composer.phar require google/apiclient:^2.0
require_once __DIR__ . '/vendor/autoload.php';

define('SCOPES', implode(' ', array(
  Google_Service_Calendar::CALENDAR_READONLY)
));
$client->setScopes(SCOPES);
</code>```

Title: Google Api PHP Client - How to login

Body:
I'm trying to connect using the api of google using php to loggearme with the user of gmail and retrieve the calendars I have, for this I use this code.
What I get is loggearme and that oauth2 I return the TOKEN but once I have this token I do not know how to use it to get the details of my google calendar.

Thank you

Settings.php

/* Google App Client Id */
define('CLIENT_ID', 'XXXXXXXX.apps.googleusercontent.com');

/* Google App Client Secret */
 define('CLIENT_SECRET', 'XXXXXXX');

 /* Google App Redirect Url */
 define('CLIENT_REDIRECT_URL',
 'http://localhost:8081/googleTesting/oauth2callback.php');

....

 <a href="<?= 'https://accounts.google.com/o/oauth2/auth?scope=' . urlencode('https://www.googleapis.com/auth/userinfo.profile') . '&redirect_uri=' . urlencode(CLIENT_REDIRECT_URL) . '&response_type=code&client_id=' . CLIENT_ID . '&access_type=online' ?>">Login with Google

Calendar.php

//  We have access we can now create our service
if (isset($_SESSION['datosGoogle']['access_token'])) {

$client = new Google_Client();
$client->setAccessToken($_SESSION['datosGoogle']['access_token']);
print "LogOut";

$service = new Google_Service_Calendar($client);

$calendarList  = $service->calendarList->listCalendarList();;

while(true) {
    foreach ($calendarList->getItems() as $calendarListEntry) {

        echo $calendarListEntry->getSummary()."\n";

        // get events
        $events = $service->events->listEvents($calendarListEntry->id);

        foreach ($events->getItems() as $event) {
            echo "-----".$event->getSummary()."";
        }
    }
    $pageToken = $calendarList->getNextPageToken();
    if ($pageToken) {
        $optParams = array('pageToken' => $pageToken);
        $calendarList = $service->calendarList->listCalendarList($optParams);
    } else {
        break;
    }
}

}

Body:
When you request a login to google you add scope in that request.

Google has better answer. Google tutorial,Google php implementation

This part is important to highlight.

//import libraries php composer.phar require google/apiclient:^2.0
require_once __DIR__ . '/vendor/autoload.php';

define('SCOPES', implode(' ', array(
  Google_Service_Calendar::CALENDAR_READONLY)
));
$client->setScopes(SCOPES);


来源: stackexchange

问:
Jquery radio button starts endless loop?
I want to get an answer from the php file if I click on one of the radio buttons, but if I use the radio button, the alert appers in an endless loop. Why? And how do I get the alert only once?

I try it with only a „normal“ button, then it works:
If I click on the button, the ajax responds the values in the alert once.

Thank you

<!doctype html>

    <title>test</title>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

      <button type="button" class="btn btn-dark" id="go">Go</button>

            <input type="radio"  name="aktionswahl" value="alles" checked autocomplete="off"> Alles

            <input type="radio"  name="aktionswahl" value="blue" autocomplete="off"> blue

            <input type="radio"  name="aktionswahl" value="red" autocomplete="off"> red

```

答:
As the alert appears, the radio button will lose focus. As you close the alert, the focus will return which triggers the alert which causes the radio button to lose focus but when you close that alert ...

Use console.log instead

ContentLicense: CC BY-SA 3.0


问:
Does using promises in node.js make node synchronous?
How does promises still retain async while giving sync effect?

I.e Promises can make sequential code execution, doesn’t that remove async?

Then, whats the point of node.js?

答:
No, promises do not make Node.js code run synchronous - promises allow you to write flows that appear synchronous.

When you do this:

```<code>console.log(1);
setTimeout(() => console.log(2));
console.log(3);
</code>```

Node.js runs the code sequantially, first it logs 1, then it registers a function to happen after a timeout, then it logs 3. After a big when the timer fires - it executes its function and logs 2. No threads are involved.

With promises and async await, when you await you're explicitly telling Node.js "pause executing this function and continue when the promise I'm waiting for resolved". pause executing isn't the same as a thread blocking - no context switch happens at an operating system level - it just keeps track of the function and when the promise resolves it calls it.

Node is run with "our code - platform code" cycles, your code runs (until it ends, for example by hitting an await), then the platform code runs (for example, checking timers and I/O) and then that code can call your code (for example your suspended async function) again and run it.

Body:
No, promises do not make Node.js code run synchronous - promises allow you to write flows that appear synchronous.

When you do this:

console.log(1);
setTimeout(() => console.log(2));
console.log(3);

Node.js runs the code sequantially, first it logs 1, then it registers a function to happen after a timeout, then it logs 3. After a big when the timer fires - it executes its function and logs 2. No threads are involved.

With promises and async await, when you await you're explicitly telling Node.js "pause executing this function and continue when the promise I'm waiting for resolved". pause executing isn't the same as a thread blocking - no context switch happens at an operating system level - it just keeps track of the function and when the promise resolves it calls it.

Node is run with "our code - platform code" cycles, your code runs (until it ends, for example by hitting an await), then the platform code runs (for example, checking timers and I/O) and then that code can call your code (for example your suspended async function) again and run it.


问:
Send param in URL using OFBiz
I want to end a param in URL in OFBiz, but I get this error
from security

```<code>org.apache.ofbiz.webapp.event.EventHandlerException: Found URL parameter [twCompagneDeRecrutementId]
passed to secure (https) request-map with uri [showCompagne] with an event that calls service [showCompagne];
this is not allowed for security reasons! The data should be encrypted by making it part of the request body (a form field) instead of the request URL.
Moreover it would be kind if you could create a Jira sub-task of https://issues.apache.org/jira/browse/OFBIZ-2330 (check before if a sub-task for this error does not exist). If you are not sure how to create a Jira issue please have a look before at http://cwiki.apache.org/confluence/x/JIB2
</code>```

This is my ftl

```<code><#if listCompagne??>

            <#list listCompagne as newCompagne>

            <div style="display:flex; width:100%;">
                         <div style="padding:6px; width:24%;"><label>${newCompagne.nom}</label></div>
                         <div style="padding:6px; width:24%;"><label>${newCompagne.dateDebut ?date}</label></div>
                         <div style="padding:6px; width:24%;"><label>${newCompagne.dateFin ?date}</label></div>
                         <input type="hidden" value="${newCompagne.twCompagneDeRecrutementId}"/>
     <div style="padding:6px; width:20%;"> <a class="btn btn-outline-danger btn-block " href="<@ofbizUrl>showCompagne?twCompagneDeRecrutementId=${newCompagne.twCompagneDeRecrutementId}</@ofbizUrl>">afficher</a>
</div>

           </div>
           </#list>
</code>```

答:
I don't use ofbiz , but you should send parameter in body instead of in query.

In your case I would add a form and submit it using hidden form input, form should be unique per iteration using index

```<code> <form action="<@ofbizUrl>showCompagne?</@ofbizUrl>" id="afficher${newCompagne?index}" method="post" style="display: none;">
 <input type="hidden" name="twCompagneDeRecrutementId" value="${newCompagne.twCompagneDeRecrutementId}" />
  </form>
 <a class="btn btn-outline-danger btn-block "
 href="javascript:;" onclick="javascript:
document.getElementById('afficher${newCompagne?index}').submit()">afficher</a>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Send param in URL using OFBiz

Body:
I want to end a param in URL in OFBiz, but I get this error
from security

org.apache.ofbiz.webapp.event.EventHandlerException: Found URL parameter [twCompagneDeRecrutementId]
passed to secure (https) request-map with uri [showCompagne] with an event that calls service [showCompagne];
this is not allowed for security reasons! The data should be encrypted by making it part of the request body (a form field) instead of the request URL.
Moreover it would be kind if you could create a Jira sub-task of https://issues.apache.org/jira/browse/OFBIZ-2330 (check before if a sub-task for this error does not exist). If you are not sure how to create a Jira issue please have a look before at http://cwiki.apache.org/confluence/x/JIB2

This is my ftl

<#if listCompagne??>

            <#list listCompagne as newCompagne>

${newCompagne.nom}

${newCompagne.dateDebut ?date}

${newCompagne.dateFin ?date}

                         <input type="hidden" value="${newCompagne.twCompagneDeRecrutementId}"/>

 <a class="btn btn-outline-danger btn-block " href="<@ofbizUrl>showCompagne?twCompagneDeRecrutementId=${newCompagne.twCompagneDeRecrutementId}</@ofbizUrl>">afficher

           </#list>

Body:
I don't use ofbiz , but you should send parameter in body instead of in query.

In your case I would add a form and submit it using hidden form input, form should be unique per iteration using index

 <form action="<@ofbizUrl>showCompagne?</@ofbizUrl>" id="afficher${newCompagne?index}" method="post" style="display: none;">
 <input type="hidden" name="twCompagneDeRecrutementId" value="${newCompagne.twCompagneDeRecrutementId}" />
  </form>
 <a class="btn btn-outline-danger btn-block "
 href="javascript:;" onclick="javascript:
document.getElementById('afficher${newCompagne?index}').submit()">afficher</a>


问:
How to get the count of number of active client requests for a GET method
Is there a way to find the number of active client requests currently accessing a GET method(getProducts()) in REST?

What I have is:

```<code>@GET
@Path("/products")
@Produces({ "application/xml" })
public Response getProducts(){
//My business logic to retrieve products go here
</code>```

}

Now, I issue a GET request from the browser:
http://localhost:8080/v1/products

How to find the number of active client requests currently accessing getProducts() method at any point in time on the server side?

答:
Pick one:

Write a Servlet Listener (implementing ServletRequestListener) that increments and decrements when the request is initialized and destroyed

Put the logic of counting directly into getProducts() method

Create an AOP advice that wraps getProducts() around and increments/decrements when the method is entered and exited

There are tools already written that can measure the performance (and the request counts). One of them: JETM.

Body:
Is there a way to find the number of active client requests currently accessing a GET method(getProducts()) in REST?

What I have is:

@GET
@Path("/products")
@Produces({ "application/xml" })
public Response getProducts(){
//My business logic to retrieve products go here

}

Now, I issue a GET request from the browser:
http://localhost:8080/v1/products

How to find the number of active client requests currently accessing getProducts() method at any point in time on the server side?


问:
How to redirect to default server index page using php ternary operator?

I had tried to check the server name protocol using php ternary operator ?

Here is example and code:

Example:https://9.218.145.189

example code:

```<code><a href="<?php echo $SERVER['SERVER_NAME']=($_SERVER['SERVER_NAME'])?($_SERVER['SERVER_NAME']=='ON'):($_SERVER['SERVER_NAME']=='OFF');?>">Click here</a>
</code>```

QUery:

If my HTTP/HTTPS is ON/OFF it should redirect me to the https://9.218.145.189 home page when i click href link(i.e 9.218.145.189) instead it is redirecting me to the https://9.212.145.189/outpt.php.

Error:

THe above code for  a href link is not taking me to the https link.

答:
FYI:

= is assignment operator

== is comparision operator

Hence try the following code(modified):

```<code><a href="<?php echo $SERVER['SERVER_NAME']=($_SERVER['SERVER_NAME'])?($_SERVER['SERVER_NAME']='ON'):($_SERVER['SERVER_NAME']='OFF'); ?>">Click here</a>
</code>```

Body:
I had tried to check the server name protocol using php ternary operator ?

Here is example and code:

Example:https://9.218.145.189

example code:

<a href="<?php echo $SERVER['SERVER_NAME']=($_SERVER['SERVER_NAME'])?($_SERVER['SERVER_NAME']=='ON'):($_SERVER['SERVER_NAME']=='OFF');?>">Click here

QUery:

If my HTTP/HTTPS is ON/OFF it should redirect me to the https://9.218.145.189 home page when i click href link(i.e 9.218.145.189) instead it is redirecting me to the https://9.212.145.189/outpt.php.

Error:

THe above code for  a href link is not taking me to the https link.

Body:
FYI:

= is assignment operator

== is comparision operator

Hence try the following code(modified):

<a href="<?php echo $SERVER['SERVER_NAME']=($_SERVER['SERVER_NAME'])?($_SERVER['SERVER_NAME']='ON'):($_SERVER['SERVER_NAME']='OFF'); ?>">Click here</a>


问:
Powershell select HTML text
I have the following powershell script to open multiple HTML files on multiple computers to extract licensing information.  Looking for some help extracting the innertext elements of  where id=2.

Looking to extract for:

Product, Serial number,Product Key, Request code

```<code>ForEach ($system in (Get-Content C:\temp\computers.txt)) {
  $folder = "\\$system\c`$\ProgramData\Autodesk\AdLM\"
  Get-ChildItem $folder *.html  |
  ForEach-Object {
    # Get current filename without .html
    $c = $_.BaseName
    # Create new Internet Explorer Object
    $ie=New-Object -ComObject InternetExplorer.Application
    # $_ (dollar underscore) 'THIS' token. Typically refers to the item inside a foreach loop. Open current HTML file.
    $ie.Navigate("$_")
    while ($ie.busy -eq $true) {
      Start-Sleep -Milliseconds 500
    }

    $doc=$ie.Document
    $tables=$doc.getElementsByTagName('table')
     foreach ($table in $tables) {
        if ($div.innertext -match "Product: ")
        if ($div.innertext -match "Serial number: ")
        if ($div.innertext -match "Product Key: ")
        if ($div.innertext -match "Request code: ")
    }
    $elements.innerText | ForEach-Object { Add-Content -path c:\temp\results.csv "$c,$system,$para1" }
  }
}
</code>```

Example of the HTML file

```<code><table width="100%" cellspacing=0 cellpadding=0>
    <tr><td align=left id=1 width=15%>Product:</td><td align=left id=2 width=35%><!--PREVINFO_START-->Autodesk Building Design Suite Premium 2016<!--PREVINFO_END--></td><td align=left id=1> </td><td align=left id=2> </td></tr>
    <tr><td align=left id=1 width=15%>Serial number:</td><td align=left id=2><!--PREVINFO_START-->999-9999999<!--PREVINFO_END--></td></tr>
</table>
<table width="100%" cellspacing=0 cellpadding=0>
    <tr><td align=left id=1 width=15%>Product key:</td><td align=left id=2>424242</td><td align=left id=1> </td><td align=left id=2> </td></tr>
</table>
<table width="100%" cellspacing=0 cellpadding=0>
    <tr><td align=left id=1 width=15%>Request code:</td><td align=left id=3 style='word-break:break-all'>7777 7777 7777 7777</td></tr>
    <tr><td align=left id=1> </td><td align=left id=3 style='word-break:break-all'>7777 7777 7777 7777</td></tr>
</table>
</code>```

答:
My solution,</p>

```<code># Script to extract Autocad Licensing informatoin from HTML files
# 1. Add the computers you want to access into computers.txt
# 2. Download the Script and execute.
# 3. Results will be saved to the $file variable (default is c:\tools\results.csv)

#File Paths
$file="C:\tools\results.csv";
$computerfile="C:\tools\computers.txt";
$computerfoldername="\c`$\ProgramData\Autodesk\AdLM\";

# Create empty computers array
$computers = @()

ForEach ($system in (Get-Content $computerfile)) {
# Append computers with \\computer\foldername
$computers += "\\" + $system + $computerfoldername
}
 write-host "=========================================================" -foreground "red"
 write-host "MULTI-HTML FILE PARSING AND APPENDING TO CSV SCRIPT "
 write-host "Script Executing at "  (Get-Date).ToString()
 #folders in which html files are kept

write-host "Folders To Parse"
for ($i = 0; $i -lt $computers.Count ; $i++) {
  write-host $computers[$i]

}

write-host "Initializing Script";

# Create new Internet Explorer Object
$ie = new-object -com "InternetExplorer.Application"

# Iterate through each \\computer\folder in the list
for ($i = 0; $i -lt $computers.Count ; $i++) {

write-host ""
write-host "=========================================="
write-host ""
write-host "COMPUTER/FOLDER" + $computers[$i] -foreground "yellow"
write-host ""

# Get HTML files within current \\computer\folder
Get-ChildItem $computers[$i] *.html  |
ForEach-Object {
# For each HTML file within current \\computer\folder
 $innerfile = $computers[$i] + $_.BaseName + $_.Extension
 write-host "=========================================="

write-host "Fetching" + $innerfile
# The easiest way to accomodate for slowness of IE
Start-Sleep -Seconds 1
# open current HTML file
$ie.Navigate($innerfile)
# The easiest way to accomodate for slowness of IE
Start-Sleep -Seconds 1
$doc = $ie.Document

write-host "IE Initiated for file " + $innerfile ;
# Get all <tr> elements in teh HTML file.
$trs=$doc.getElementsByTagName('tr')
$requestcodeflag=0;

foreach ($table in $trs) {

        $machine=$innerfile;
        # Product Key
        Try {
            if ($table.innertext.Substring(0,8) -eq "Product:") {
                write-host "Parsed Product ID " + $table.innertext.Substring(8)
                $product=$table.innertext.Substring(8);
            }
        }
        Catch{}

        # Serial number
        Try {
             if ($table.innertext.Substring(0,14) -eq "Serial number:") {
                write-host "Parsed Serial Number  " + $table.innertext.Substring(14)
                $serialno=$table.innertext.Substring(14);
            }
        }
        Catch{}

        # Product Key
        Try {
            if ($table.innertext.Substring(0,12) -eq "Product key:") {
                write-host "Parsed Product Key  " + $table.innertext.Substring(12)
                $productkey=$table.innertext.Substring(12);
            }
        }
        Catch{}

        # Request code 2
        if($requestcodeflag -eq "1") {
        Try {
            $requestcodeflag=2;
            $requestcode= $requestcode + " | " + $table.innertext;
            write-host "Parsed 2nd Request Code  " +  $table.innertext
            }
        Catch{}
        }

        # Request code 1st
        Try{
            if ($table.innertext.Substring(0,13) -eq "Request code:") {
                write-host "Parsed Request Code  " +  $table.innertext.Substring(13)
                $requestcode=$table.innertext.Substring(13);
                $requestcodeflag=1;
            }
        }
        Catch{}

}

write-host "Writing to CSV file " + $file
$NewLine = "{0},{1},{2},{3},{4}" -f $machine,$product,$serialno,$productkey,$requestcode
$NewLine | add-content -path $file
}
}
$ie.Quit()
write-host "=========================================="
write-host "Data is  appended to csv file" + $file
write-host "Executed Thank You "
write-host "=========================================="
write-host ""
</code>```

Title: Powershell select HTML text

Body:
I have the following powershell script to open multiple HTML files on multiple computers to extract licensing information.  Looking for some help extracting the innertext elements of  where id=2.

Looking to extract for:

Product, Serial number,Product Key, Request code

ForEach ($system in (Get-Content C:\temp\computers.txt)) {
  $folder = "\\$system\c`$\ProgramData\Autodesk\AdLM\"
  Get-ChildItem $folder *.html  |
  ForEach-Object {
    # Get current filename without .html
    $c = $_.BaseName
    # Create new Internet Explorer Object
    $ie=New-Object -ComObject InternetExplorer.Application
    # $_ (dollar underscore) 'THIS' token. Typically refers to the item inside a foreach loop. Open current HTML file.
    $ie.Navigate("$_")
    while ($ie.busy -eq $true) {
      Start-Sleep -Milliseconds 500
    }

    $doc=$ie.Document
    $tables=$doc.getElementsByTagName('table')
     foreach ($table in $tables) {
        if ($div.innertext -match "Product: ")
        if ($div.innertext -match "Serial number: ")
        if ($div.innertext -match "Product Key: ")
        if ($div.innertext -match "Request code: ")
    }
    $elements.innerText | ForEach-Object { Add-Content -path c:\temp\results.csv "$c,$system,$para1" }
  }
}

Example of the HTML file

Product:	Autodesk Building Design Suite Premium 2016

Serial number:	999-9999999

Product key:	424242

Request code:	7777 7777 7777 7777

 	7777 7777 7777 7777

Body:
My solution,

# Script to extract Autocad Licensing informatoin from HTML files
# 1. Add the computers you want to access into computers.txt
# 2. Download the Script and execute.
# 3. Results will be saved to the $file variable (default is c:\tools\results.csv)

#File Paths
$file="C:\tools\results.csv";
$computerfile="C:\tools\computers.txt";
$computerfoldername="\c`$\ProgramData\Autodesk\AdLM\";

# Create empty computers array
$computers = @()

ForEach ($system in (Get-Content $computerfile)) {
# Append computers with \\computer\foldername
$computers += "\\" + $system + $computerfoldername
}
 write-host "=========================================================" -foreground "red"
 write-host "MULTI-HTML FILE PARSING AND APPENDING TO CSV SCRIPT "
 write-host "Script Executing at "  (Get-Date).ToString()
 #folders in which html files are kept

write-host "Folders To Parse"
for ($i = 0; $i -lt $computers.Count ; $i++) {
  write-host $computers[$i]

}

write-host "Initializing Script";

# Create new Internet Explorer Object
$ie = new-object -com "InternetExplorer.Application"

# Iterate through each \\computer\folder in the list
for ($i = 0; $i -lt $computers.Count ; $i++) {

write-host ""
write-host "=========================================="
write-host ""
write-host "COMPUTER/FOLDER" + $computers[$i] -foreground "yellow"
write-host ""

# Get HTML files within current \\computer\folder
Get-ChildItem $computers[$i] *.html  |
ForEach-Object {
# For each HTML file within current \\computer\folder
 $innerfile = $computers[$i] + $_.BaseName + $_.Extension
 write-host "=========================================="

write-host "Fetching" + $innerfile
# The easiest way to accomodate for slowness of IE
Start-Sleep -Seconds 1
# open current HTML file
$ie.Navigate($innerfile)
# The easiest way to accomodate for slowness of IE
Start-Sleep -Seconds 1
$doc = $ie.Document

write-host "IE Initiated for file " + $innerfile ;
# Get all <tr> elements in teh HTML file.
$trs=$doc.getElementsByTagName('tr')
$requestcodeflag=0;

foreach ($table in $trs) {

        $machine=$innerfile;
        # Product Key
        Try {
            if ($table.innertext.Substring(0,8) -eq "Product:") {
                write-host "Parsed Product ID " + $table.innertext.Substring(8)
                $product=$table.innertext.Substring(8);
            }
        }
        Catch{}

        # Serial number
        Try {
             if ($table.innertext.Substring(0,14) -eq "Serial number:") {
                write-host "Parsed Serial Number  " + $table.innertext.Substring(14)
                $serialno=$table.innertext.Substring(14);
            }
        }
        Catch{}

        # Product Key
        Try {
            if ($table.innertext.Substring(0,12) -eq "Product key:") {
                write-host "Parsed Product Key  " + $table.innertext.Substring(12)
                $productkey=$table.innertext.Substring(12);
            }
        }
        Catch{}

        # Request code 2
        if($requestcodeflag -eq "1") {
        Try {
            $requestcodeflag=2;
            $requestcode= $requestcode + " | " + $table.innertext;
            write-host "Parsed 2nd Request Code  " +  $table.innertext
            }
        Catch{}
        }

        # Request code 1st
        Try{
            if ($table.innertext.Substring(0,13) -eq "Request code:") {
                write-host "Parsed Request Code  " +  $table.innertext.Substring(13)
                $requestcode=$table.innertext.Substring(13);
                $requestcodeflag=1;
            }
        }
        Catch{}

}

write-host "Writing to CSV file " + $file
$NewLine = "{0},{1},{2},{3},{4}" -f $machine,$product,$serialno,$productkey,$requestcode
$NewLine | add-content -path $file
}
}
$ie.Quit()
write-host "=========================================="
write-host "Data is  appended to csv file" + $file
write-host "Executed Thank You "
write-host "=========================================="
write-host ""


问:
change of all immediate elements of the corrosponding class using jquery
my html content

```<code> <li class="info"> info<li>
 <li class="other"> info<li>
 <li class="other"> info<li>

 <li class="Error"> error<li>
 <li class="other"> error<li>
 <li class="warning"> warning<li>
 <li class="other"> warning<li>
 <li class="other"> warning<li>
 <li class="info"> info<li>
 <li class="other"> info<li>
 <li class="other"> info<li>
</code>```

based on the li element class, I want to filter only the immediate li.other class item css to be changed using jquery;

I followed the below approach: when I select info elements:

```<code>  $('.info').prevAll('li.other').css({});
</code>```

It worked but it will all the previous li.other elements changed. Instead I want only specific to that particular html(info) element li.other element. rest all to be ignored.
 Please any one provide the possible approach

答:
Try this:</p>

```<code>    $("info + other").css({});
</code>```

Body:
my html content

 info

 info

 info

 error

 error

 warning

 warning

 warning

 info

 info

 info

based on the li element class, I want to filter only the immediate li.other class item css to be changed using jquery;

I followed the below approach: when I select info elements:

  $('.info').prevAll('li.other').css({});

It worked but it will all the previous li.other elements changed. Instead I want only specific to that particular html(info) element li.other element. rest all to be ignored.
 Please any one provide the possible approach

Body:
Try this:

    $("info + other").css({});


问:
How to fix Number of rows in detail section and insert blank rows if number of record less than rows fixed in detail section
I want to print three pay slips in an A4 size page. Page header and footer are fixed number of rows.

I want Detail section to print 8 records. If records are less than 8, remaining line should be blank printed and 3 pay slip print on one page.

Input parameters are Month and Year. I grouped each pay slip with personnel_id and placed the personel_id, name and bank account no.  on group header section.

In detail section

```<code>Earnings:               Total
Basic pay               20000
Arrear                   1000
Qualification Pay         500
Deduction:
Medical  Fee             2000
Club Fee                 1000
</code>```

In Group footer

```<code>Total Earning           21500
Total Deduction          3000
Net Pay                 18500
</code>```

Sometimes Earning has only one record and sometimes deduction has only one record.
I want to fix detail section with 8 or 10 rows and also 2 or 3 pay slips in one A4 size page.
Thanks.

Sample Data

```<code>E=Earnings
D=Deductions
Personnel  ID   EDname          Cur_amount  EDCode  EDtype  P_Month  P_Year
17777-7      Basic Pension         20000     401       E       4       2014
17777-7         Arrear             1000      402       E       4       2014
17777-7     Qualification Alw.     5000      403       E       4        2014
17777-7      Medical Fee           2000      501       D       4       2014
17777-7       Club Fee             1000      502       D       4       2014
18888-8      Medical Fee           1500      501       D       4       2014
18888-8        Club Fee            700        502      D       4       2014
</code>```

Report format on one page id just like below

```<code>Personnel_id:18888-8                              Pay Slip
 Name:            xyz                             Month  April, 2014   //`Group Header`
Account_No. 123444
Deduction:
Medical Fee                      1500.00
Club Fee                         700.00                       // `Detail Section`
Total Earning:                    0.00                       //    `Group Footer`
Total Deduction:                 -2200.00
Net pay                         -2200.00
</code>```

```<code>Personnel_id:17777-7                              Pay Slip
 Name:            ABC                             Month  April, 2014
Account_No. 123456
 Earnings:
Basic Pension                 20000.00
Arrear                        1000.00
Qualification Alw.            5000.00
Deduction:
Medical Fee                   2000.00
Club Fee                      1000.00
Total Earning:                21500.00
Total Deduction:              3000.00
Net pay                       18500.00
</code>```

according to your formula result of first pay slip is

```<code>Personnel_id:18888-8                              Pay Slip
 Name:            xyz                             Month  April, 2014
Account_No. 123444

 Earnings:
Basic Pension
Arrear
Qualification Alw.
Deduction:
Medical Fee                      1500.00
Club Fee                         700.00
Total Earning:                   0.00

Total Deduction:                -2200.00
Net pay                          -2200.00
</code>```

needed remaining 6 blank  lines in detail section after Club fee

答:
1)First of all fix height of detail section
by right click on detail section ->section expert->New Page Before checked->beside button of (x+2) write formula of ->
IF Remainder (RecordNumber, 8) = 0 THEN
    TRUE
ELSE
    FALSE

2)under detail section (suppose section3) is your detail section
  then leave report section blank with needed space and else for footer put it in
page footer .. i think this will solve your problem.. mine is solved..

Body:
I want to print three pay slips in an A4 size page. Page header and footer are fixed number of rows.

I want Detail section to print 8 records. If records are less than 8, remaining line should be blank printed and 3 pay slip print on one page.

Input parameters are Month and Year. I grouped each pay slip with personnel_id and placed the personel_id, name and bank account no.  on group header section.

In detail section

Earnings:               Total
Basic pay               20000
Arrear                   1000
Qualification Pay         500
Deduction:
Medical  Fee             2000
Club Fee                 1000

In Group footer

Total Earning           21500
Total Deduction          3000
Net Pay                 18500

Sometimes Earning has only one record and sometimes deduction has only one record.
I want to fix detail section with 8 or 10 rows and also 2 or 3 pay slips in one A4 size page.
Thanks.

Sample Data

E=Earnings
D=Deductions
Personnel  ID   EDname          Cur_amount  EDCode  EDtype  P_Month  P_Year
17777-7      Basic Pension         20000     401       E       4       2014
17777-7         Arrear             1000      402       E       4       2014
17777-7     Qualification Alw.     5000      403       E       4        2014
17777-7      Medical Fee           2000      501       D       4       2014
17777-7       Club Fee             1000      502       D       4       2014
18888-8      Medical Fee           1500      501       D       4       2014
18888-8        Club Fee            700        502      D       4       2014

Report format on one page id just like below

Personnel_id:18888-8                              Pay Slip
 Name:            xyz                             Month  April, 2014   //`Group Header`
Account_No. 123444
Deduction:
Medical Fee                      1500.00
Club Fee                         700.00                       // `Detail Section`
Total Earning:                    0.00                       //    `Group Footer`
Total Deduction:                 -2200.00
Net pay                         -2200.00

Personnel_id:17777-7                              Pay Slip
 Name:            ABC                             Month  April, 2014
Account_No. 123456
 Earnings:
Basic Pension                 20000.00
Arrear                        1000.00
Qualification Alw.            5000.00
Deduction:
Medical Fee                   2000.00
Club Fee                      1000.00
Total Earning:                21500.00
Total Deduction:              3000.00
Net pay                       18500.00

according to your formula result of first pay slip is

Personnel_id:18888-8                              Pay Slip
 Name:            xyz                             Month  April, 2014
Account_No. 123444

 Earnings:
Basic Pension
Arrear
Qualification Alw.
Deduction:
Medical Fee                      1500.00
Club Fee                         700.00
Total Earning:                   0.00

Total Deduction:                -2200.00
Net pay                          -2200.00

needed remaining 6 blank  lines in detail section after Club fee


问:
Leaflet Choropleth Map - switch to Leaflet 1.2
I have a problem with my map. I switched to Leaflet 1.2 and one of the functions is not working correctly.
The code is here:

http://mapaszlakow.eu/mapa1.2.html

When activating an overlay which is geojson via js and clicking a bicycle route it zooms in to a route but it is not highlighted and the info window does not show up.
Here is exactly the same example that is working but on the older version of Leaflet (I think it is 0.7).

http://mapaszlakow.eu/

I can't locate the problem, the only thing I did is switching to Leaflet 1.2, I will be greatful for help.

EDIT: I believe, the problem is somewhere here:

```<code>    function select(layer) {
    info.update(layer.feature.properties);
    if (selected !== null) {
        var previous = selected;
    }
    map.fitBounds(layer.getBounds());
    selected = layer;
    if (previous) {
        dehighlight(previous);
    }
    }

    var selected = null;
</code>```

答:
I've tested your code from http://mapaszlakow.eu/mapa1.2.html and it works almost fine - on hover it highlights route correctly, on click it zooms to route extent - except from showing the popup info. To fix this please check out the fiddle I made from your code:

http://jsfiddle.net/5z17y5oL/18/  (this fiddle must be accessed through http because your server doesn't serve data with https)

The main difference is that I passed parameter to info.update(e.feature.properties); occurrences.

EDIT

My edited fiddle is here: http://jsfiddle.net/5z17y5oL/25/

So I moved the info.update(e.feature.properties); to be called from layer click listener. On map clicked layer style is reset and info is clearing as it's receiving null.

```<code>.....
onEachFeature: function(feature, layer) {
    layer.on({
      .....
      'click': function(e) {
        select(e.target);
        info.update(e.feature.properties);
      }
    });
    map.on({
      'click': function(e) {
        bicyclegeojson.resetStyle(layer);
        info.update(null);
        selected = null;
      }
    });
....
</code>```

//end of EDIT

One more thing - you have small error, you should change this line:

```<code>map.addControl(layerControl).addTo(map);
</code>```

to

```<code>map.addControl(layerControl);
</code>```

Body:
I have a problem with my map. I switched to Leaflet 1.2 and one of the functions is not working correctly.
The code is here:

http://mapaszlakow.eu/mapa1.2.html

When activating an overlay which is geojson via js and clicking a bicycle route it zooms in to a route but it is not highlighted and the info window does not show up.
Here is exactly the same example that is working but on the older version of Leaflet (I think it is 0.7).

http://mapaszlakow.eu/

I can't locate the problem, the only thing I did is switching to Leaflet 1.2, I will be greatful for help.

EDIT: I believe, the problem is somewhere here:

    function select(layer) {
    info.update(layer.feature.properties);
    if (selected !== null) {
        var previous = selected;
    }
    map.fitBounds(layer.getBounds());
    selected = layer;
    if (previous) {
        dehighlight(previous);
    }
    }

    var selected = null;

Body:
I've tested your code from http://mapaszlakow.eu/mapa1.2.html and it works almost fine - on hover it highlights route correctly, on click it zooms to route extent - except from showing the popup info. To fix this please check out the fiddle I made from your code:

http://jsfiddle.net/5z17y5oL/18/  (this fiddle must be accessed through http because your server doesn't serve data with https)

The main difference is that I passed parameter to info.update(e.feature.properties); occurrences.

EDIT

My edited fiddle is here: http://jsfiddle.net/5z17y5oL/25/

So I moved the info.update(e.feature.properties); to be called from layer click listener. On map clicked layer style is reset and info is clearing as it's receiving null.

.....
onEachFeature: function(feature, layer) {
    layer.on({
      .....
      'click': function(e) {
        select(e.target);
        info.update(e.feature.properties);
      }
    });
    map.on({
      'click': function(e) {
        bicyclegeojson.resetStyle(layer);
        info.update(null);
        selected = null;
      }
    });
....

//end of EDIT

One more thing - you have small error, you should change this line:

map.addControl(layerControl).addTo(map);

to

map.addControl(layerControl);


问:
How to force vbs script to run in cscript host
How do I force the vbs script to run in the cscript host as opposed to the WScript host?

How do I go about reliably determining if vbs is running from the Command Prompt in XP/Vista/7?

Also, if its not running from the command prompt, how would I get the script to launch itself into command prompt?

I'm looking for a short snippet.

答:
There is no property or anything like that you can set, so you are left with ugly hacks like this:</p>

```<code>Function ForceCScript()
On Error Resume Next
WScript.StdErr.Write(Chr(7))
If Err.Number <> 0 Then
    Err.Clear
    On Error GoTo 0
    set WshSh=WScript.CreateObject("WScript.Shell")
    sh=WshSh.ExpandEnvironmentStrings("%COMSPEC%")
    If InStr(sh,"%") = 1 Then sh="cmd.exe"
    WshSh.Run(sh&" /K cscript /nologo """&WScript.ScriptFullName&"""")
    WScript.Quit()
End If
End Function

call ForceCScript()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
There is no property or anything like that you can set, so you are left with ugly hacks like this:

Function ForceCScript()
On Error Resume Next
WScript.StdErr.Write(Chr(7))
If Err.Number <> 0 Then
    Err.Clear
    On Error GoTo 0
    set WshSh=WScript.CreateObject("WScript.Shell")
    sh=WshSh.ExpandEnvironmentStrings("%COMSPEC%")
    If InStr(sh,"%") = 1 Then sh="cmd.exe"
    WshSh.Run(sh&" /K cscript /nologo """&WScript.ScriptFullName&"""")
    WScript.Quit()
End If
End Function

call ForceCScript()


问:
SQL add a table to SQL query without Primary Key
I am a newbie to SQL so I'm sure this is an easy one...

I am using a query builder to build a query.

I have 2 tables linked by 2 primary keys which exist in each table. This Query 1 is working fine and the results are as expected, but I am trying to add a Table 3 to the query but this table has no primary key that can be linked with any key in either of Table 1 or Table 2.

Is there any way to link Table 3 to output data without affecting the number of rows displayed from Query 1?

Thanks all in advance

答:
Assuming your query is a SELECT you could just add Table3 to your query and use it in your SELECT, like</p>

```<code>SELECT t1.col1, t2.col2, t3.col3 FROM Table1 t1, Table2 t2, Table 3 t3
</code>```

Body:
Assuming your query is a SELECT you could just add Table3 to your query and use it in your SELECT, like

SELECT t1.col1, t2.col2, t3.col3 FROM Table1 t1, Table2 t2, Table 3 t3


问:
Angular Material 2: Multiple mat-table sorting is working on first table only
I have used Angular Material in my application and I have two mat-table with sorting on single component but my sorting is working only on first table

here is ts code

@ViewChild(MatSort) inventoryDataSort: MatSort;
@ViewChild(MatPaginator) inventoryDataPaginator: MatPaginator;

@ViewChild(MatSort) additionalDataSort: MatSort;
@ViewChild(MatPaginator) additionalDataPaginator: MatPaginator;
ngAfterViewInit() {
    this.inventoryDataSource.sort = this.inventoryDataSort;
    this.inventoryDataSource.paginator = this.inventoryDataPaginator;
    this.additionalDataSource.sort = this.additionalDataSort;
    this.additionalDataSource.paginator = this.additionalDataPaginator;
}
```

<p>mat-table</p>

<pre class="lang-html prettyprint-override"><code><mat-table #table1 [dataSource]="inventoryDataSource" matSort>
<mat-table #table2 [dataSource]="additionalDataSource" matSort>
</code>```

答:
Selector in ViewChild queries DOM and it finds first math. Could you try change this part from

@ViewChild(MatSort) inventoryDataSort: MatSort;
@ViewChild(MatPaginator) inventoryDataPaginator: MatPaginator;

@ViewChild(MatSort) additionalDataSort: MatSort;
@ViewChild(MatPaginator) additionalDataPaginator: MatPaginator;
```

<p>to </p>

<pre class="lang-js prettyprint-override"><code>@ViewChild(MatSort) inventoryDataSort: MatSort;
@ViewChild(MatPaginator) inventoryDataPaginator: MatPaginator;

@ViewChild('table2', {read: MatSort}) additionalDataSort: MatSort;
@ViewChild('table2', {read: MatPaginator}) additionalDataPaginator: MatPaginator;
</code>```

Body:
I have used Angular Material in my application and I have two mat-table with sorting on single component but my sorting is working only on first table

here is ts code

@ViewChild(MatSort) inventoryDataSort: MatSort;
@ViewChild(MatPaginator) inventoryDataPaginator: MatPaginator;

@ViewChild(MatSort) additionalDataSort: MatSort;
@ViewChild(MatPaginator) additionalDataPaginator: MatPaginator;
ngAfterViewInit() {
    this.inventoryDataSource.sort = this.inventoryDataSort;
    this.inventoryDataSource.paginator = this.inventoryDataPaginator;
    this.additionalDataSource.sort = this.additionalDataSort;
    this.additionalDataSource.paginator = this.additionalDataPaginator;
}

mat-table

<mat-table #table1 [dataSource]="inventoryDataSource" matSort>
<mat-table #table2 [dataSource]="additionalDataSource" matSort>

Body:
Selector in ViewChild queries DOM and it finds first math. Could you try change this part from

@ViewChild(MatSort) inventoryDataSort: MatSort;
@ViewChild(MatPaginator) inventoryDataPaginator: MatPaginator;

@ViewChild(MatSort) additionalDataSort: MatSort;
@ViewChild(MatPaginator) additionalDataPaginator: MatPaginator;

to

@ViewChild(MatSort) inventoryDataSort: MatSort;
@ViewChild(MatPaginator) inventoryDataPaginator: MatPaginator;

@ViewChild('table2', {read: MatSort}) additionalDataSort: MatSort;
@ViewChild('table2', {read: MatPaginator}) additionalDataPaginator: MatPaginator;


问:
Case using at Join
I'm trying to use case function at Join and I failed to execute the Query.
What I'm doing wrong?

```<code>left join vortex_dbo.vw_public_material_history on
CASE
WHEN vw_public_request_material_location_mir.material_request_id = (substring(vw_public_material_history.comments,12,6))

then vw_public_request_material_location_mir.material_request_id
else null
end
</code>```

What I wish to get is join rows only if I have "true" from the "When"

I feel I miss something here.

答:
Your CASE expression makes no sense. A CASE expression results in a value, in your case for example in material_request_id. So you'd get

```<code>left join vortex_dbo.vw_public_material_history on material_request_id
</code>```

in case of a string match. You do notice that this ON clause is incomplete?

You are probably looking for

```<code>left join vortex_dbo.vw_public_material_history on
  vw_public_request_material_location_mir.material_request_id =
  (substring(vw_public_material_history.comments,12,6))
</code>```

That would read better with table aliases:

```<code>from vw_public_request_material_location_mir mir
left join vortex_dbo.vw_public_material_history hist on
  mir.material_request_id = (substring(hist.comments,12,6))
</code>```

As to your data model: It seems strange that you have an ID hidden in a string. You may want to re-consider your table design.

Title: Case using at Join

Body:
I'm trying to use case function at Join and I failed to execute the Query.
What I'm doing wrong?

left join vortex_dbo.vw_public_material_history on
CASE
WHEN vw_public_request_material_location_mir.material_request_id = (substring(vw_public_material_history.comments,12,6))

then vw_public_request_material_location_mir.material_request_id
else null
end

What I wish to get is join rows only if I have "true" from the "When"

I feel I miss something here.

Body:
Your CASE expression makes no sense. A CASE expression results in a value, in your case for example in material_request_id. So you'd get

left join vortex_dbo.vw_public_material_history on material_request_id

in case of a string match. You do notice that this ON clause is incomplete?

You are probably looking for

left join vortex_dbo.vw_public_material_history on
  vw_public_request_material_location_mir.material_request_id =
  (substring(vw_public_material_history.comments,12,6))

That would read better with table aliases:

from vw_public_request_material_location_mir mir
left join vortex_dbo.vw_public_material_history hist on
  mir.material_request_id = (substring(hist.comments,12,6))

As to your data model: It seems strange that you have an ID hidden in a string. You may want to re-consider your table design.


问:
Laravel 5.5 Validation change format of response when validation fails
In Laravel 5.4, we created a class that all our requests for validation inherited because we needed to customize our response.

```<code>class APIRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Response on failure
     *
     * @param array $errors
     * @return Response
     */
    public function response(array $errors) {
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }
        return Response::json($response);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}
</code>```

A sample request that would extend this is shown below

```<code>class ResultsGetTermsRequest extends APIRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'school_id' => 'required|integer',
            'student_id' => 'required|integer',
        ];
    }
}
</code>```

And then our sample response on failure would be

```<code>{
    "status": "FAILED",
    "code": "400",
    "messages": [
        [
            "The school id field is required."
        ],
        [
            "The student id field is required."
        ]
    ],
    "result": []
}
</code>```

However, this doesn't work anymore with Laravel 5.5. I noticed they replaced with response method with failedValidation. This however isn't returning any response when the request isn't validated. If I un-comment the print_r, it is something is returned. It seems the only line that is never executed is the return statement. What am I missing?

```<code> public function failedValidation(Validator $validator) {

        $errors = (new ValidationException($validator))->errors();
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }
        //print_r($response);
        return Response::json($response);
    }
</code>```

答:
If you want to do this from the FormRequest classes, potentially something like this:

```<code>protected function buildResponse($validator)
{
    return response->json([
        'code' => ResponseObject::BAD_REQUEST,
        'status' => ResponseObject::FAILED,
        'messages' => $validator->errors()->all(),
    ]);
 }

protected function failedValidation(Validator $validator)
{
    throw (new ValidationException($validator, $this->buildResponse($validator));
}
</code>```

That would add that response you are building to the validation exception. When the exception handler tries to render this it will check if response was set and if so it will use that response you passed instead of trying to convert the ValidationException to a response itself.

If you want 'ALL' validation exceptions to end up being rendered in this format I might just do this at the exception handler level, as the exception handler already has the ability to convert these exceptions to Json, so you could alter the format in the handler itself and basically not have to make any adjustments to the default FormRequest at all.

Body:
In Laravel 5.4, we created a class that all our requests for validation inherited because we needed to customize our response.

class APIRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Response on failure
     *
     * @param array $errors
     * @return Response
     */
    public function response(array $errors) {
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }
        return Response::json($response);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

A sample request that would extend this is shown below

class ResultsGetTermsRequest extends APIRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'school_id' => 'required|integer',
            'student_id' => 'required|integer',
        ];
    }
}

And then our sample response on failure would be

{
    "status": "FAILED",
    "code": "400",
    "messages": [
        [
            "The school id field is required."
        ],
        [
            "The student id field is required."
        ]
    ],
    "result": []
}

However, this doesn't work anymore with Laravel 5.5. I noticed they replaced with response method with failedValidation. This however isn't returning any response when the request isn't validated. If I un-comment the print_r, it is something is returned. It seems the only line that is never executed is the return statement. What am I missing?

 public function failedValidation(Validator $validator) {

        $errors = (new ValidationException($validator))->errors();
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }
        //print_r($response);
        return Response::json($response);
    }

Body:
If you want to do this from the FormRequest classes, potentially something like this:

protected function buildResponse($validator)
{
    return response->json([
        'code' => ResponseObject::BAD_REQUEST,
        'status' => ResponseObject::FAILED,
        'messages' => $validator->errors()->all(),
    ]);
 }

protected function failedValidation(Validator $validator)
{
    throw (new ValidationException($validator, $this->buildResponse($validator));
}

That would add that response you are building to the validation exception. When the exception handler tries to render this it will check if response was set and if so it will use that response you passed instead of trying to convert the ValidationException to a response itself.

If you want 'ALL' validation exceptions to end up being rendered in this format I might just do this at the exception handler level, as the exception handler already has the ability to convert these exceptions to Json, so you could alter the format in the handler itself and basically not have to make any adjustments to the default FormRequest at all.


问:
Will hashing two eual strings give same hash value
I need to anonymyze personal data in our MySql database. The problem is that I still need to be able to link two persons together after they have been anonymized.

I thought this could be done by hashing their social security number or e-mail address, which lead to my question:

When hashing two equal strings (s1 and s1) I get two hash values (h1 and h2), how sure can I be that:

1) the hashed value is equal (h1 = h2)

2) no not equal (s3 = s1) will produce the same hash value

答:
1) (h1 = h2) is always true for equal strings (s1 and s2) per definition, when using a correct hash function.

2) Two different strings can have the same hash value. This is called a "collsison". The probability depends on the hash function used and the length of the resulting hash. For MD5 for example there are websites and tables for finding collisions, which is quite interesting.

I'm not sure what you mean by linking persons together or what your requirements are, so I cannot help you with that. But you could link two persons together with their ids.


问:
Can't set headers after they are sent error happens with socket.io
I am writing a very simple nodejs socket.io app. Somehow this returns "can't set headers after they are sent" error. but I can't see the point where the header is set again. I've only called server.listen once and I believe socket.listen works independently so it shouldn't conflict.

I am aware that can't set headers error had been posted a multiple times. I've read them briefly and I also understand how does response.writeHead works under normal circumstances(I've experimented with some node.js apps with response.writeHead, they worked fine most cases) it seems I am missing something from here. is it due to socket.io?

```<code>const fs = require("fs");

const server = require("http").createServer();
const io = require("socket.io").listen(server);

server.listen(52273,function(){
  console.log("server up");
});

server.on("request",function(request,response){
  fs.readFile("mainpage.html",function(error,data){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.end(data);
  });
});

io.sockets.on("connection",function(socket){

  var roomName = null;
  socket.on("join", function(data){
    roomName = data;
    socket.join(data);
    console.log("client joined" + data);
  });

  socket.on("message",function(data){
    io.sockets.in(roomName).emit("message","test");
  });
});
</code>```

答:
Thanks everyone. I've solved problem by installing express to my experiment app. I've read the manual again and discovered the socket.io v2 is now requiring express app as a dependency. It seems I have been using socket.io v2 but somehow sticked to socket.io v1 style app writing. It also worked when I downgraded it to socket.io v1.

TL;DR - socket.io v2 is not compatible with apps written for socket.io v1. When a socket.io app returns "can't set headers after they are sent" errors, try use proper version of the socket.io or install correct dependencies.

Body:
I am writing a very simple nodejs socket.io app. Somehow this returns "can't set headers after they are sent" error. but I can't see the point where the header is set again. I've only called server.listen once and I believe socket.listen works independently so it shouldn't conflict.

I am aware that can't set headers error had been posted a multiple times. I've read them briefly and I also understand how does response.writeHead works under normal circumstances(I've experimented with some node.js apps with response.writeHead, they worked fine most cases) it seems I am missing something from here. is it due to socket.io?

const fs = require("fs");

const server = require("http").createServer();
const io = require("socket.io").listen(server);

server.listen(52273,function(){
  console.log("server up");
});

server.on("request",function(request,response){
  fs.readFile("mainpage.html",function(error,data){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.end(data);
  });
});

io.sockets.on("connection",function(socket){

  var roomName = null;
  socket.on("join", function(data){
    roomName = data;
    socket.join(data);
    console.log("client joined" + data);
  });

  socket.on("message",function(data){
    io.sockets.in(roomName).emit("message","test");
  });
});


问:
CSS elements being separated / breaking / wrapping
Edit: fixed. Thanks everyone for the help ;)

Hello everyone,

I'm having a few problems with the blue bar elements being separated instead of being together.

Both elements "Notícias" and the blue bar are inside a div called "content". The blue bar is inside a span, and is created with 3 divs. One for the left image, the middle one is a repeating background and finally the third one with the last image.

Here's an image to ilustrate the problem: http://i52.tinypic.com/b3vhic.png

The code is the following:

.barra .barra-azul {

 background: url(outros/barra_sidebar_e.png) no-repeat top left;

 display: inline-block;

 height: 14px;

 width: 7px;

}

.barra .barra-azul-meio {

 background: #56a3eb repeat-x;

 display: inline-block;

 height: 14px;

 width: 50%;

}

.barra .barra-azul-fim {

 background: url(outros/barra_sidebar_d.png) no-repeat top right;

 display: inline-block;

 height: 14px;

 width: 7px;

}

And the html is:

```<code><span class="barra">
<div class="barra-azul"></div>
<div class="barra-azul-meio"></div>
<div class="barra-azul-fim"></div>
</span>
</code>```

What is the best way to accomplish this?

Thanks in advance ;)

答:
It's hard to answer without being able to experiment with the actual code and graphics. But you can start with adding the following.

```<code>.barra div {
  padding: 0;
  margin: 0;
}
</code>```

If it doesn't work it would be great if you could post a link to a demo of bar.

Body:
Edit: fixed. Thanks everyone for the help ;)

Hello everyone,

I'm having a few problems with the blue bar elements being separated instead of being together.

Both elements "Notícias" and the blue bar are inside a div called "content". The blue bar is inside a span, and is created with 3 divs. One for the left image, the middle one is a repeating background and finally the third one with the last image.

Here's an image to ilustrate the problem: http://i52.tinypic.com/b3vhic.png

The code is the following:

.barra .barra-azul {

 background: url(outros/barra_sidebar_e.png) no-repeat top left;

 display: inline-block;

 height: 14px;

 width: 7px;

}

.barra .barra-azul-meio {

 background: #56a3eb repeat-x;

 display: inline-block;

 height: 14px;

 width: 50%;

}

.barra .barra-azul-fim {

 background: url(outros/barra_sidebar_d.png) no-repeat top right;

 display: inline-block;

 height: 14px;

 width: 7px;

}

And the html is:

What is the best way to accomplish this?

Thanks in advance ;)

Body:
It's hard to answer without being able to experiment with the actual code and graphics. But you can start with adding the following.

.barra div {
  padding: 0;
  margin: 0;
}

If it doesn't work it would be great if you could post a link to a demo of bar.


问:
how to rotate a "triangle down" to a "triangle up" using css and jquery
i have the following triangle

created by the following css:

```<code>.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}
</code>```

html:

```<code><div class=triangle></div>
</code>```

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

```<code>.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}
</code>```

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

答:
Simple solution would be to toggle between the two Classes (if no animation is required):

$('.triangle,.triangle-up').click(function(){
   $(this).toggleClass("triangle triangle-up");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}
.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}</code>```

```

Body:
i have the following triangle

created by the following css:

.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}

html:

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

Body:
Simple solution would be to toggle between the two Classes (if no animation is required):

$('.triangle,.triangle-up').click(function(){
   $(this).toggleClass("triangle triangle-up");
});

.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}
.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class=triangle></div>


问:
Cannot close curly brackets on Android Studio with a AZERTY keyboard
Since yesterday, I cannot close curly brackets on Android Studio with my keyboard... I have an AZERTY french keyboard, and the closing curly bracket is optained by doing "alt gr" + "=".

All the other char involving "alt gr" key are working on Android Studio (including opening curly brackets)

I can insert closing curly brackets by "copy/pasting" this char in Android Studio

This problem occures ONLY in Android Studio (here for instance, it is working: }})

I already restart both Android Studio and my computer, but that does not solve the problem

Do you guys had some problem similar? Is it a temporary bug of Android Studio?

Thanks in advance!

答:
The problem is probably with the software maybe there's is a setting which you might have accidentally messed up while snooping around. Was it working earlier?\

edit:

Add this line:

```<code>actionSystem.force.alt.gr=true
</code>```

to this file:

```<code>...\Android\android-studio\bin\idea.properties
</code>```

As written here: http://youtrack.jetbrains.com/issue/IDEA-91975

Body:
The problem is probably with the software maybe there's is a setting which you might have accidentally messed up while snooping around. Was it working earlier?\

edit:

Add this line:

actionSystem.force.alt.gr=true

to this file:

...\Android\android-studio\bin\idea.properties

As written here: http://youtrack.jetbrains.com/issue/IDEA-91975


问:
how can I look up objective-c's property @synthesize getter setter code
in interview has a question "Could NSMutableArray property use copy why and why not " I have searched the answer but I want to see the auto generate's getter setter code how can I do?</p>

答: You can‘t really see the source code. You could step into it in Xcode‘s debugger though, and see an assembler version of it, which is reasonably readable if you know any platform‘s assembler or are good at guessing abbreviations for english words.</p>


问:
PHP not return correct number of nodes in XML-file

I'm trying to delete certain nodes from an XML-file using PHP, for some reason it was not working properly and I came to the conclusion that that's probably the case, because PHP is not returning the correct number of nodes, that are in said XML-file.

This is the XML-File:

```<code><?xml version="1.0"?>
<Filenames>
    <newFile>
        <link>somelink</link>
        <ViewLink>someotherlink</ViewLink>
        <FileName>test</FileName>
    </newFile>
    <newFile>
        <link>somelink</link>
        <ViewLink>someotherlink</ViewLink>
        <FileName>test</FileName>
    </newFile>
</Filenames>
</code>```

...and so on (the file is way longer, but I'm always using the same name for nodes etc., you get the point)

Since deleting certain nodes did not work out, I tried just getting the information from the xml-file first and I tried to check how many <newFile> (those are the nodes I want to delete) nodes PHP could find.
In order to do that, I did the following:

```<code><?php
    $doc = new DOMDocument();
    $doc->load("FilenameList.xml");

    $root = $doc->documentElement;

    $newFiles = $root->getElementsByTagName("newFile");
    echo count($newFiles);
?>
</code>```

However, that returned "1", even though, obviously, there are way more nodes.
I also tried counting the amount of <newFile>nodes using simpleXML, but again, it did not work. I'm very confused by this, as I used the same syntax in the past and it worked out perfectly.
Another thing I tried was to do this:

```<code>$newFiles = $doc->getElementsByTagName("newFile");
</code>```

Instead of $root = ...

In addition, I also tried using sizeof() instead of count().
Am I missing something or does anyone have an idea about what's going wrong?

答:
```<code>$doc = new DOMDocument;
$doc->loadXML("FilenameList.xml");
$newFiles = $doc->getElementsByTagName('newFile');
foreach ($newFiles as $newFile) {
   $newFile++;
}
echo $newFile;
</code>```

you forgot the foreach loop. Check this http://php.net/manual/en/domdocument.getelementsbytagname.php

Body:
I'm trying to delete certain nodes from an XML-file using PHP, for some reason it was not working properly and I came to the conclusion that that's probably the case, because PHP is not returning the correct number of nodes, that are in said XML-file.

This is the XML-File:

<?xml version="1.0"?>
<Filenames>
    <newFile>
        <link>somelink</link>
        <ViewLink>someotherlink</ViewLink>
        <FileName>test</FileName>
    </newFile>
    <newFile>
        <link>somelink</link>
        <ViewLink>someotherlink</ViewLink>
        <FileName>test</FileName>
    </newFile>
</Filenames>

...and so on (the file is way longer, but I'm always using the same name for nodes etc., you get the point)

Since deleting certain nodes did not work out, I tried just getting the information from the xml-file first and I tried to check how many <newFile> (those are the nodes I want to delete) nodes PHP could find.
In order to do that, I did the following:

<?php
    $doc = new DOMDocument();
    $doc->load("FilenameList.xml");

    $root = $doc->documentElement;

    $newFiles = $root->getElementsByTagName("newFile");
    echo count($newFiles);
?>

However, that returned "1", even though, obviously, there are way more nodes.
I also tried counting the amount of <newFile>nodes using simpleXML, but again, it did not work. I'm very confused by this, as I used the same syntax in the past and it worked out perfectly.
Another thing I tried was to do this:

$newFiles = $doc->getElementsByTagName("newFile");

Instead of $root = ...

In addition, I also tried using sizeof() instead of count().
Am I missing something or does anyone have an idea about what's going wrong?

Body:
$doc = new DOMDocument;
$doc->loadXML("FilenameList.xml");
$newFiles = $doc->getElementsByTagName('newFile');
foreach ($newFiles as $newFile) {
   $newFile++;
}
echo $newFile;

you forgot the foreach loop. Check this http://php.net/manual/en/domdocument.getelementsbytagname.php


问:
UPDATING a table based on a FROM clause, how do I limit with WHERE?
I have a SQL UPDATE clause which looks like:

```<code>UPDATE table
SET column =value
FROM
(SELECT bla bla FROM bla bla WHERE col = val)
JOIN
(SELECT bla bla FROM bla bla WHERE col = val)
</code>```

I want to limit the UPDATE to WHERE a particular column is equal to a particular value.

It doesnt appear to be legal to insert the WHERE after the JOIN or after the SET? I thought I had already limited the update using the JOIN but it doesn't appear so.

Where can I insert my WHERE clause?

答:
Use query something like this :

Important thing that worked for me was join before update after.

```<code>update table1 t1 join table2 t2 on t1.id1 = t2.id2 set t1.value = t2.otherValue;
</code>```

Body:
I have a SQL UPDATE clause which looks like:

UPDATE table
SET column =value
FROM
(SELECT bla bla FROM bla bla WHERE col = val)
JOIN
(SELECT bla bla FROM bla bla WHERE col = val)

I want to limit the UPDATE to WHERE a particular column is equal to a particular value.

It doesnt appear to be legal to insert the WHERE after the JOIN or after the SET? I thought I had already limited the update using the JOIN but it doesn't appear so.

Where can I insert my WHERE clause?

Body:
Use query something like this :

Important thing that worked for me was join before update after.

update table1 t1 join table2 t2 on t1.id1 = t2.id2 set t1.value = t2.otherValue;


问:
Web page does not wait for my codes run completely
I need to run these commands:

Get cookie from browser by JS Cookie plugin in mypage.php

Check its value by Ajax and my PHP codes in myapi.php

Assign some SESSIONs in myapi.php

And now use those SESSION values in many php vars
in bottom of page in mypage.php

but those many php vars defined by default values and need to ONE MORE TIME REFRESH. Can I use cookie by PHP directly? And how?

This is my code in mypage.php:

```<code>$(window).on('load', function() {
            if (typeof Cookies.get( 'isuser' ) != 'undefined') {
                $.ajax({
                    url: apiaddress,
                    data: {action: 'verify_user', verifycode: Cookies.get( 'isuser' )},
                    type: 'POST',
                    dataType: 'JSON',
                    async: false,
                    success: function (result) {
                        if (result['status'] == 'OK') {
                            //some code like welcome
                        }
                    }
                });
            }
        });
</code>```

This is my code in myapi.php:

```<code>if (isset($_POST['action']) && $_POST['action'] == 'verify_user') {
        $usercookie = !empty($_POST['verifycode']) ? mysqli_real_escape_string($db,$_POST['verifycode']) : '';
        $usercookie_a = explode('*', $usercookie);
        $username = $usercookie_a[0];
        $uservcode = $usercookie_a[1];
        $query = "SELECT * FROM users WHERE username = '$username' AND vcode = '$uservcode'";
        if ($result = mysqli_query($db,$query)) {
            $row = mysqli_fetch_array($result);
            $counts = mysqli_num_rows($result);
            if ($counts == 1) {
                $output = [];
                $output['status'] = 'OK';
                $output['username'] = $row['username'];
                $_SESSION['isuseru'] = $row['username'];
                $_SESSION['isuserp'] = $row['password'];
                echo json_encode($output);
                unset($_POST);
            }
        } else {
            echo 'MySQL Connection Error: ' . mysqli_error($db);
        }
    }
</code>```

And now I want use $_SESSION['isuseru'] and others in mypage.php but those are not in hand in first time and need to refresh.

答:
Probably you may go with setTimeout by enclosing the ajax call in mypage.php so that you can get hold of the those session values.

or use timeout in the jquery ajax as specified in the
documentation

Body:
I need to run these commands:

Get cookie from browser by JS Cookie plugin in mypage.php

Check its value by Ajax and my PHP codes in myapi.php

Assign some SESSIONs in myapi.php

And now use those SESSION values in many php vars
in bottom of page in mypage.php

but those many php vars defined by default values and need to ONE MORE TIME REFRESH. Can I use cookie by PHP directly? And how?

This is my code in mypage.php:

$(window).on('load', function() {
            if (typeof Cookies.get( 'isuser' ) != 'undefined') {
                $.ajax({
                    url: apiaddress,
                    data: {action: 'verify_user', verifycode: Cookies.get( 'isuser' )},
                    type: 'POST',
                    dataType: 'JSON',
                    async: false,
                    success: function (result) {
                        if (result['status'] == 'OK') {
                            //some code like welcome
                        }
                    }
                });
            }
        });

This is my code in myapi.php:

if (isset($_POST['action']) && $_POST['action'] == 'verify_user') {
        $usercookie = !empty($_POST['verifycode']) ? mysqli_real_escape_string($db,$_POST['verifycode']) : '';
        $usercookie_a = explode('*', $usercookie);
        $username = $usercookie_a[0];
        $uservcode = $usercookie_a[1];
        $query = "SELECT * FROM users WHERE username = '$username' AND vcode = '$uservcode'";
        if ($result = mysqli_query($db,$query)) {
            $row = mysqli_fetch_array($result);
            $counts = mysqli_num_rows($result);
            if ($counts == 1) {
                $output = [];
                $output['status'] = 'OK';
                $output['username'] = $row['username'];
                $_SESSION['isuseru'] = $row['username'];
                $_SESSION['isuserp'] = $row['password'];
                echo json_encode($output);
                unset($_POST);
            }
        } else {
            echo 'MySQL Connection Error: ' . mysqli_error($db);
        }
    }

And now I want use $_SESSION['isuseru'] and others in mypage.php but those are not in hand in first time and need to refresh.


答:
The problem is that they're inline-block elements per your CSS rules and you have whitespace between them in your markup. You should either float them, or position them absolutely.

HTML:

```<code><div class="barra">
  <div class="barra-azul"></div>
  <div class="barra-azul-meio"></div>
  <div class="barra-azul-fim"></div>
</div>
</code>```

CSS:

```<code>.barra > div {
  float: left;
  height: 14px;
  width: 7px;
}

.barra .barra-azul {
  background: url(outros/barra_sidebar_e.png) no-repeat top left;
}

.barra .barra-azul-meio {
  background: #56a3eb repeat-x;
  width: 50%;
}

.barra .barra-azul-fim {
  background: url(outros/barra_sidebar_d.png) no-repeat top right;
}
</code>```

That also cuts out a bunch of duplication you had going on.

Title: CSS elements being separated / breaking / wrapping

Body:
The problem is that they're inline-block elements per your CSS rules and you have whitespace between them in your markup. You should either float them, or position them absolutely.

HTML:

<div class="barra">
  <div class="barra-azul"></div>
  <div class="barra-azul-meio"></div>
  <div class="barra-azul-fim"></div>
</div>

CSS:

.barra > div {
  float: left;
  height: 14px;
  width: 7px;
}

.barra .barra-azul {
  background: url(outros/barra_sidebar_e.png) no-repeat top left;
}

.barra .barra-azul-meio {
  background: #56a3eb repeat-x;
  width: 50%;
}

.barra .barra-azul-fim {
  background: url(outros/barra_sidebar_d.png) no-repeat top right;
}

That also cuts out a bunch of duplication you had going on.


问:
Bypassing member names cannot be the same as their enclosing type
Similar to: member names cannot be the same as their enclosing type except I can't change the metadata, I want to just ignore the class entirely.

I am trying to add a Service Reference in Visual Studio 2010 but I get the following error.

The custom tool ‘DataServiceClientGenerator’ failed. Data service
  client code-generation failed: Schema specified is not valid. Errors:
  (0,0) : error 0042: Name foo cannot be used in type
  Microsoft.Crm.Sdk.Data.Services.foo. Member names cannot be the
  same as their enclosing type..

I understand that this error is because someone named a field foo in the object foo but I can't change that..

so without being able to make any changes within CRM, how can I generate my service reference?

I have thought of downloading the $metadata and then removing the offending type and then saving it (as the type is not one that I will be using anyway). But I do not know how to get this to work because it's not overly straight forward.

I have tried making the service reference with both C# and VB.NET and neither worked, ideally it would be a solution that works for both, but at this point I would be open to a solution that only works for one of these.

答:
Thanks to Seph, i came up with somewhat improved way to add actual reference, not simple .cs file:

Save your http://localhost/myWcfDataService.svc/$metadata as file, eg. myService.csdl

Edit it to solve names cannot be the same as their enclosing type manually. It is caused when a class has a field with the same name. I decided to rename classes, eg. from foo to foo_. You can rename fields instead. Run c:\Windows\Microsoft.NET\Framework\v4.0.30319\DataSvcUtil.exe /language:CSharp /in:myService.csdl /out:serviceReference1.cs periodically to see when you eliminated all errors.

Rename myService.csdl to $metadata

Temporarily run some web-server in the same folder as $metadata file. For example, i had python 3 installed and simply ran python -m http.server from the folder where $metadata is.

Add Service Reference in Visual Studio as usual, but use your temporary webserver address. In my case it was http://localhost:8000. Visual Studio will request /$metadata and generate everything.


问:
Replace SNMP4J Vector<VariableBinding> with ArrayList<String>
Can somebody show the correct syntax to replace a vector with an ArrayList?

Original code -

```<code>StringBuilder msg = new StringBuilder();
        msg.append(event.toString());
                Vector<? extends VariableBinding> varBinds = event.getPDU()
                .getVariableBindings();
</code>```

Have tried -

```<code>List<String> variables = new ArrayList<>();
for (VariableBinding binding : event.getPDU().getVariableBindings()) {
    variables.add(String.valueOf(binding.getVariable()));
}
</code>```

But multiple issues (diamond operator not supported, can convert ArrayList to String).  Netbeans / JDK1.6

And tried -

```<code>ArrayList<String> list = new ArrayList<String>(varBinds) = event.getPDU().getVariableBindings();
</code>```

But unexpected type, required variable found value, cannot find symbol variable varBinds.

Thoughts appreciated

Regards
Active

答:
The diamond operator was not available in JDK 1.6. You need to define the ArrayList using the old style generics form:

```<code>import java.util.List;
import java.util.ArrayList;

List<String> variables = new ArrayList<String>();
</code>```

Following the docs of SNMP4J at

http://www.snmp4j.org/doc/index.html

The event.getPDU().getVariableBindings() will return an Vector of VariableBindings

If you want to store that in an ArrayList of VariableBindings you could do

```<code>List<VariableBinding> variables = new ArrayList<String>(event.getPDU().getVariableBindings());
</code>```

However if you are looking to store a string representation of the VariableBinding you can retrieve the string representation of the underlying Variable

e.g.

```<code>List<String> variables = new ArrayList<String>();
for (VariableBinding binding : event.getPDU().getVariableBindings()) {
    variables.add(binding.getVariable().toString());
}
</code>```

It all depends on what you're wanting to achieve.

Body:
Can somebody show the correct syntax to replace a vector with an ArrayList?

Original code -

StringBuilder msg = new StringBuilder();
        msg.append(event.toString());
                Vector<? extends VariableBinding> varBinds = event.getPDU()
                .getVariableBindings();

Have tried -

List<String> variables = new ArrayList<>();
for (VariableBinding binding : event.getPDU().getVariableBindings()) {
    variables.add(String.valueOf(binding.getVariable()));
}

But multiple issues (diamond operator not supported, can convert ArrayList to String).  Netbeans / JDK1.6

And tried -

ArrayList<String> list = new ArrayList<String>(varBinds) = event.getPDU().getVariableBindings();

But unexpected type, required variable found value, cannot find symbol variable varBinds.

Thoughts appreciated

Regards
Active

Body:
The diamond operator was not available in JDK 1.6. You need to define the ArrayList using the old style generics form:

import java.util.List;
import java.util.ArrayList;

List<String> variables = new ArrayList<String>();

Following the docs of SNMP4J at

http://www.snmp4j.org/doc/index.html

The event.getPDU().getVariableBindings() will return an Vector of VariableBindings

If you want to store that in an ArrayList of VariableBindings you could do

List<VariableBinding> variables = new ArrayList<String>(event.getPDU().getVariableBindings());

However if you are looking to store a string representation of the VariableBinding you can retrieve the string representation of the underlying Variable

e.g.

List<String> variables = new ArrayList<String>();
for (VariableBinding binding : event.getPDU().getVariableBindings()) {
    variables.add(binding.getVariable().toString());
}

It all depends on what you're wanting to achieve.


问:
Why haven't modern compilers removed the need for expression templates?
The standard pitch for expression templates in C++ is that they increase efficiency by removing unnecessary temporary objects. Why can't C++ compilers already remove these unnecessary temporary objects?

This is a question that I think I already know the answer to but I want to confirm since I couldn't find a low-level answer online.

Expression templates essentially allow/force an extreme degree of inlining. However, even with inlining, compilers cannot optimize out calls to operator new and operator delete because they treat those calls as opaque since those calls can be overridden in other translation units. Expression templates completely remove those calls for intermediate objects.

These superfluous calls to operator new and operator delete can be seen in a simple example where we only copy:

```<code>#include <array>
#include <vector>

std::vector<int> foo(std::vector<int> x)
{
    std::vector<int> y{x};
    std::vector<int> z{y};
    return z;
}

std::array<int, 3> bar(std::array<int, 3> x)
{
    std::array<int, 3> y{x};
    std::array<int, 3> z{y};
    return z;
}
</code>```

In the generated code, we see that foo() compiles to a relatively lengthy function with two calls to operator new and one call to operator delete while bar() compiles to only a transfer of registers and doesn't do any unnecessary copying.

Is this analysis correct?

Could any C++ compiler legally elide the copies in foo()?

答:
There are two kinds of expression templates.

One kind is about domain specific languages embedded directly in C++. Boost.Spirit turns expressions into recursive descent parsers. Boost.Xpressive turns them into regular expressions. Good old Boost.Lambda turns them into function objects with argument placeholders.

Obviously there is nothing a compiler can do to get rid of that need. It would take special-purpose language extensions to add the capabilities that the eDSL adds, like lambdas were added to C++11. But it's not productive to do that for every eDSL written; it would make the language gigantic and impossible to comprehend, among other problems.

The second kind is the expression templates that keep high-level semantics the same but optimize execution. They apply domain-specific knowledge to transform expressions into more efficient execution paths, while keeping the semantics the same. A linear algebra library might do that as Massimiliano explained in his answer, or a SIMD library like Boost.Simd might translate multiple operations into a single fused operation like multiply-add.

These libraries provide services that a compiler could, in theory, perform without modifying the language specification. However, in order to do so, the compiler would have to recognize the domain in question and have all the built-in domain knowledge to do the transformations. This approach is way too complex and would make compilers huge and even slower than they are.

An alternative approach to expression templates for these kinds of libraries would be compiler plugins, i.e. instead of writing a special matrix class that has all the expression template magic, you write a plugin for the compiler that knows about the matrix type and transforms the AST that the compiler uses. The problem with this approach is that either compilers would have to agree on a plugin API (not going to happen, they work too differently internally) or the library author has to write a separate plugin for every compiler they want their library to be usable (or at least performant) with.

Body:
The standard pitch for expression templates in C++ is that they increase efficiency by removing unnecessary temporary objects. Why can't C++ compilers already remove these unnecessary temporary objects?

This is a question that I think I already know the answer to but I want to confirm since I couldn't find a low-level answer online.

Expression templates essentially allow/force an extreme degree of inlining. However, even with inlining, compilers cannot optimize out calls to operator new and operator delete because they treat those calls as opaque since those calls can be overridden in other translation units. Expression templates completely remove those calls for intermediate objects.

These superfluous calls to operator new and operator delete can be seen in a simple example where we only copy:

#include <array>
#include <vector>

std::vector<int> foo(std::vector<int> x)
{
    std::vector<int> y{x};
    std::vector<int> z{y};
    return z;
}

std::array<int, 3> bar(std::array<int, 3> x)
{
    std::array<int, 3> y{x};
    std::array<int, 3> z{y};
    return z;
}

In the generated code, we see that foo() compiles to a relatively lengthy function with two calls to operator new and one call to operator delete while bar() compiles to only a transfer of registers and doesn't do any unnecessary copying.

Is this analysis correct?

Could any C++ compiler legally elide the copies in foo()?


问:
iOS 11 uiBarButtonitems shrunk in size
I have an app and it works fine on iOS 10 but on iOS 11 the UIBarButtonItems icons shrunk in size. (they are bar button custom item with an image).
I have tried to put them constraints but it didn't work. Any idea?

Thanks in advance]1

答:
I found it!

XCode 9 has some bugs! In XCode 8 it works fine!. It wasn't iOS 11 bug, it's a XCode 9 bug...

regards!

Title: iOS 11 uiBarButtonitems shrunk in size


问:
Nginx doesn't work in https with certbot letsencrypt
I have executed the steps shown in the certbot web and have already generated the certificates. They are in /etc/letsencrypt/live/example.com/ and this is my /etc/nginx/sites-available/default:

```<code># Default server configuration
#
server {
listen 80 default_server;
#listen [::]:80 default_server;

root /var/www/html;

# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;

# server_name _;
server_name example.com;

location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ =404;
}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
#   deny all;
#}

listen 443 ssl; # managed by Certbot

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;      # managed by Certbot
ssl_session_cache shared:le_nginx_SSL:1m; # managed by Certbot
ssl_session_timeout 1440m; # managed by Certbot

ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # managed by Certbot
ssl_prefer_server_ciphers on; # managed by Certbot

ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256 ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-AES128-SHA ECDHE-ECDSA-AES256-SHA ECDHE-ECDSA-AES128-SHA256 ECDHE-ECDSA-AES256-SHA384 ECDHE-RSA-AES128-GCM-SHA256 ECDHE-RSA-AES256-GCM-SHA384 ECDHE-RSA-AES128-SHA ECDHE-RSA-AES128-SHA256 ECDHE-RSA-AES256-SHA384 DHE-RSA-AES128-GCM-SHA256 DHE-RSA-AES256-GCM-SHA384 DHE-RSA-AES128-SHA DHE-RSA-AES256-SHA DHE-RSA-AES128-SHA256 DHE-RSA-AES256-SHA256 EDH-RSA-DES-CBC3-SHA"; # managed by Certbot

if ($scheme != "https") {
  return 301 https://$host$request_uri;
} # managed by Certbot

}
</code>```

If I enter in example.com it redirects well to https://example.com

The problem is that it always shows an error indicating that there has been an error showing the page.

The DNS is well redirected with an A entry for example.com.

PD.: assume that example.com is my domain

答: I forgot to redirect the port 443 in my router!</p>

Body:
I have executed the steps shown in the certbot web and have already generated the certificates. They are in /etc/letsencrypt/live/example.com/ and this is my /etc/nginx/sites-available/default:

# Default server configuration
#
server {
listen 80 default_server;
#listen [::]:80 default_server;

root /var/www/html;

# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;

# server_name _;
server_name example.com;

location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ =404;
}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
#   deny all;
#}

listen 443 ssl; # managed by Certbot

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;      # managed by Certbot
ssl_session_cache shared:le_nginx_SSL:1m; # managed by Certbot
ssl_session_timeout 1440m; # managed by Certbot

ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # managed by Certbot
ssl_prefer_server_ciphers on; # managed by Certbot

ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256 ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-AES128-SHA ECDHE-ECDSA-AES256-SHA ECDHE-ECDSA-AES128-SHA256 ECDHE-ECDSA-AES256-SHA384 ECDHE-RSA-AES128-GCM-SHA256 ECDHE-RSA-AES256-GCM-SHA384 ECDHE-RSA-AES128-SHA ECDHE-RSA-AES128-SHA256 ECDHE-RSA-AES256-SHA384 DHE-RSA-AES128-GCM-SHA256 DHE-RSA-AES256-GCM-SHA384 DHE-RSA-AES128-SHA DHE-RSA-AES256-SHA DHE-RSA-AES128-SHA256 DHE-RSA-AES256-SHA256 EDH-RSA-DES-CBC3-SHA"; # managed by Certbot

if ($scheme != "https") {
  return 301 https://$host$request_uri;
} # managed by Certbot

}

If I enter in example.com it redirects well to https://example.com

The problem is that it always shows an error indicating that there has been an error showing the page.

The DNS is well redirected with an A entry for example.com.

PD.: assume that example.com is my domain