问:
send all values from ng repeat in a form
Well I'm generating a ng-repat but I need change data and send all this for edit in back end my problem is when I want to do this, can't obtain values of the form inside ng-repeat

The picture is the form that have, in html looks:

```<code> <form name="FormTablesPackageCreation">
                    <table class="table table-striped ta  ble-bordered">
                        <thead>
                        <tr>
                            <th>Estado</th>
                            <th>Especie</th>
                            <th>Tipo</th>
                            <th>Dimension</th>
                            <th>ubicacion</th>
                            <th>largo</th>
                            <th>Ancho</th>
                            <th>Espesor</th>
                            <th>Cantidad</th>
                        </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="packageList in dataListTables">
                                <input class="form-control" type="hidden" ng-value="packageList.id_table"  name="id_table[{{$index}}]" id="id_table[{{$index}}]">
                                <input class="form-control" type="hidden" ng-value="packageList.id_package" name="id_package[{{$index}}]" id="id_package[{{$index}}]">
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.estado" ng-model="vm.estado" name="estado[{{$index}}]" id="estado[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.especie" name="especie[{{$index}}]" id="especie[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.ubicacion" name="ubicacion[{{$index}}]" id="ubicacion[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.dimension" name="dimension[{{$index}}]" id="dimension[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.tipo" value="{{packageList.tipo}}" name="tipo[{{$index}}]" id="tipo[{{$index}}]" readonly>
                                </td>

                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.humedad" value="{{packageList.humedad}}" name="humedad[{{$index}}]" id="humedad[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.disponible" value="{{packageList.disponible}}" name="disponible[{{$index}}]" id="disponible[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.largo" name="largo[{{$index}}]" id="largo[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.ancho" name="ancho[{{$index}}]" id="ancho[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-value="packageList.espesor" name="espesor[{{$index}}]" id="espesor[{{$index}}]" readonly>
                                </td>
                                <td>
                                    <input class="form-control" type="text" ng-model="packageList.cantidad" ng-value="packageList.cantidad" ng-change=""  name="cantidad[{{$index}}]" id="cantidad[{{$index}}]" required>
                                </td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td>Cantidad de tablas</td>
                                <td>
                                    <input class="form-control" type="text" ng-model="vm.total" ng-value="dataListTables | sumByColumn: 'cantidad'" name="total" id="total" readonly>
                                </td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td>Cantidad de tablas nuevo paquete</td>
                                <td>
                                    <input class="form-control" type="text" ng-model="vm.Referencial" ng-value="sumNewCan(dataListTables | sumByColumn: 'cantidad')" readonly>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <div>
                        <br>
                        <button class="btn btn-primary btn-lg" ng-click="crearPaquete()">Crear nuevo Paquetes</button>
                    </div>
                </form>
</code>```

how I'm trying to obtain of values:

```<code>$scope.crearPaquete = function ()
{
    var vm = this;
    $scope.seleccionadorEspecies = false;
    $scope.creadorPaquetes = false;
    $scope.verificacionPaquetes = true;

    for (var i = 0; i < FormTablesPackageCreation.cantidad.length; i++)
    {
        console.log(FormTablesPackageCreation.id_table[i].value);
        console.log(FormTablesPackageCreation.id_package[i].value);
        console.log(FormTablesPackageCreation.cantidad[i].value);
    }
};
</code>```

I need obtain data of the ng-repeat, Try another way but do not work yet.

答:
You shouldn't be trying to get the Data by way of your Form - it should all be model-bound in your HTML to your dataListTables collection with the ng-model directives (instead of ng-value). Since you haven't posted your controller code it's hard to go much further, but assuming your dataListTables is a $scope variable (which it shouldn't - always assign to a controller variable!!), you could access the data in your controller at any time in the page lifecycle like so:

HTML

<input ... ng-model="packageList.attribute" /> (remove ng-value)

Controller

```<code>angular.forEach($scope.dataListTables, function(obj)
{
    console.log(obj.estado);
    console.log(obj.largo);
    console.log(obj.ancho);
    // and so on
});
</code>```

I'd highly recommend using ng-controller with the as syntax (ng-controller="myController as myCtrl") and then in your controller code assigning your dataListTables to this like so:

```<code>ngApp.controller("myController", function($scope)
{
    this.dataListTables = { ... your data ... };
});
</code>```

Then modify your HTML to access the myCtrl variable instead of the implied $scope:

ng-repeat = "packageList in myCtrl.dataListTables"

For reference, do a quick google on "Angular Dot Rule" to see why using $scope variables is a bad idea.

Body:
Well I'm generating a ng-repat but I need change data and send all this for edit in back end my problem is when I want to do this, can't obtain values of the form inside ng-repeat

The picture is the form that have, in html looks:

 <form name="FormTablesPackageCreation">

                            Estado
                            Especie
                            Tipo
                            Dimension
                            ubicacion
                            largo
                            Ancho
                            Espesor
                            Cantidad

                                <input class="form-control" type="hidden" ng-value="packageList.id_table"  name="id_table[{{$index}}]" id="id_table[{{$index}}]">
                                <input class="form-control" type="hidden" ng-value="packageList.id_package" name="id_package[{{$index}}]" id="id_package[{{$index}}]">

                                    <input class="form-control" type="text" ng-value="packageList.estado" ng-model="vm.estado" name="estado[{{$index}}]" id="estado[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.especie" name="especie[{{$index}}]" id="especie[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.ubicacion" name="ubicacion[{{$index}}]" id="ubicacion[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.dimension" name="dimension[{{$index}}]" id="dimension[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.tipo" value="{{packageList.tipo}}" name="tipo[{{$index}}]" id="tipo[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.humedad" value="{{packageList.humedad}}" name="humedad[{{$index}}]" id="humedad[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.disponible" value="{{packageList.disponible}}" name="disponible[{{$index}}]" id="disponible[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.largo" name="largo[{{$index}}]" id="largo[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.ancho" name="ancho[{{$index}}]" id="ancho[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-value="packageList.espesor" name="espesor[{{$index}}]" id="espesor[{{$index}}]" readonly>

                                    <input class="form-control" type="text" ng-model="packageList.cantidad" ng-value="packageList.cantidad" ng-change=""  name="cantidad[{{$index}}]" id="cantidad[{{$index}}]" required>

                                Cantidad de tablas

                                    <input class="form-control" type="text" ng-model="vm.total" ng-value="dataListTables | sumByColumn: 'cantidad'" name="total" id="total" readonly>

                                Cantidad de tablas nuevo paquete

                                    <input class="form-control" type="text" ng-model="vm.Referencial" ng-value="sumNewCan(dataListTables | sumByColumn: 'cantidad')" readonly>

                        <button class="btn btn-primary btn-lg" ng-click="crearPaquete()">Crear nuevo Paquetes</button>

                </form>

how I'm trying to obtain of values:

$scope.crearPaquete = function ()
{
    var vm = this;
    $scope.seleccionadorEspecies = false;
    $scope.creadorPaquetes = false;
    $scope.verificacionPaquetes = true;

    for (var i = 0; i < FormTablesPackageCreation.cantidad.length; i++)
    {
        console.log(FormTablesPackageCreation.id_table[i].value);
        console.log(FormTablesPackageCreation.id_package[i].value);
        console.log(FormTablesPackageCreation.cantidad[i].value);
    }
};

I need obtain data of the ng-repeat, Try another way but do not work yet.

Body:
You shouldn't be trying to get the Data by way of your Form - it should all be model-bound in your HTML to your dataListTables collection with the ng-model directives (instead of ng-value). Since you haven't posted your controller code it's hard to go much further, but assuming your dataListTables is a $scope variable (which it shouldn't - always assign to a controller variable!!), you could access the data in your controller at any time in the page lifecycle like so:

HTML

<input ... ng-model="packageList.attribute" /> (remove ng-value)

Controller

angular.forEach($scope.dataListTables, function(obj)
{
    console.log(obj.estado);
    console.log(obj.largo);
    console.log(obj.ancho);
    // and so on
});

I'd highly recommend using ng-controller with the as syntax (ng-controller="myController as myCtrl") and then in your controller code assigning your dataListTables to this like so:

ngApp.controller("myController", function($scope)
{
    this.dataListTables = { ... your data ... };
});

Then modify your HTML to access the myCtrl variable instead of the implied $scope:

ng-repeat = "packageList in myCtrl.dataListTables"

For reference, do a quick google on "Angular Dot Rule" to see why using $scope variables is a bad idea.


来源: stackexchange

问:
Spring JDBCTemplate vs Plain JDBC for inserting large numbers of records
We have to insert 2 millions of records across multiple tables and right now we are writing into a CSV file and using db2 import to load into database.

We wanted to change this logic to some kind of JDBC. While looking into multiple options, I am confused with Spring JDBC template and plain JDBC.

Let us say I wanted to insert 1 million records into 10 tables, each of which will have 100 thousand, and all these are simple JDBC statements (not prepared statements because I don't know which table I am dealing with at runtime).

Whatever system we choose will need to handle inserting up to 15 million records for a peak request.

Which framework will be better?

答: As skaffman said, if you are already using Spring then your choice is probably JdbcTemplate. Specifically you may want to look at the batchUpdate() method. Here is a pretty good example of how it works. I've used it to insert a couple hundred thousand rows quickly with great success.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Is there a way to get all elements in a JList?
I was wondering if there is a way to retrieve a list of all the elements that have been added to a JList. For example I would like JList to return an array or list of Strings or JLabels from a custom cell renderer.</p>

答:
Yes of course. You getElementAt() with a loop.

Example:

```<code>import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;

public class Jlist {
    JFrame frame;
    JList<String> list;
    JButton button;

    public Jlist(){
        init();
    }

    public void init(){
        frame = new JFrame("Sample");
        frame.setSize(300, 300);
        frame.setLayout(new  BorderLayout(30, 30));

        DefaultListModel<String> model = new DefaultListModel<>();
        model.addElement("A");
        model.addElement("B");
        model.addElement("C");
        model.addElement("D");
        model.addElement("E");

        list = new JList<>();

        list.setModel(model);
        JScrollPane pane = new JScrollPane(list);
        pane.setViewportView(list);

        button = new JButton("Get");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                buttonActionPerformed();
            }
        });

        frame.add(pane, BorderLayout.NORTH);
        frame.add(button, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
    public void buttonActionPerformed(){
        for(int i = 0; i< list.getModel().getSize();i++){
            System.out.println(list.getModel().getElementAt(i));
        }
    }
    public static void main(String[] args) {
        new Jlist();
    }
}
</code>```

Body:
Yes of course. You getElementAt() with a loop.

Example:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;

public class Jlist {
    JFrame frame;
    JList<String> list;
    JButton button;

    public Jlist(){
        init();
    }

    public void init(){
        frame = new JFrame("Sample");
        frame.setSize(300, 300);
        frame.setLayout(new  BorderLayout(30, 30));

        DefaultListModel<String> model = new DefaultListModel<>();
        model.addElement("A");
        model.addElement("B");
        model.addElement("C");
        model.addElement("D");
        model.addElement("E");

        list = new JList<>();

        list.setModel(model);
        JScrollPane pane = new JScrollPane(list);
        pane.setViewportView(list);

        button = new JButton("Get");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                buttonActionPerformed();
            }
        });

        frame.add(pane, BorderLayout.NORTH);
        frame.add(button, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
    public void buttonActionPerformed(){
        for(int i = 0; i< list.getModel().getSize();i++){
            System.out.println(list.getModel().getElementAt(i));
        }
    }
    public static void main(String[] args) {
        new Jlist();
    }
}


问:
Assistance with reading text file from a batch file
I'm having some issues reading text files from batch files.

Here's the text file:

```<code>ABCD1
ABCD2
ABCD3
ABCD4
ABCD5
ABCD6
ABCD7
ABCD8
ABCD9 ... etc.
</code>```

Here's the batch file:

```<code>@echo off
:start
Echo.
set java_home="C:\Program Files\Java\jre1.8.0_112"
set /p LocName= <LocName.txt
mkdir c:\CSR\%LocName%\

%JAVA_HOME%\bin\keytool.exe -genkey -keyalg RSA -dname "CN=%LocName%.net, O=AAA, C=US, ST=Georgia, L=Atlanta" -alias V5MACHINE -keypass enterpassword -keystore C:\CSR\%LocName%\V5MACHINE.jks -storepass enterpassword -validity 1461 -keysize 2048
%JAVA_HOME%\bin\keytool.exe -certreq -v -alias V5MACHINE -file C:\CSR\%LocName%\V5MACHINE.csr -keypass enterpassword -storepass enterpassword -keystore C:\CSR\%LocName%\V5MACHINE.jks
echo %Date% %Time% Certification request file for %LocName% stored in C:\CSR\%LocName% >>C:\CSR\Log.txt
Pause
Echo Complete!
</code>```

答:
Use a for /f loop to parse the file. %%a represents one line each pass.

```<code>@echo off
:start
Echo.
set java_home="C:\Program Files\Java\jre1.8.0_112"
for /f %%a in (LocName.txt) do (
  mkdir c:\CSR\%%a\
  %JAVA_HOME%\bin\keytool.exe -genkey -keyalg RSA -dname "CN=%%a.net, O=AAA, C=US, ST=Georgia, L=Atlanta" -alias V5MACHINE -keypass enterpassword -keystore C:\CSR\%%a\V5MACHINE.jks -storepass enterpassword -validity 1461 -keysize 2048
  %JAVA_HOME%\bin\keytool.exe -certreq -v -alias V5MACHINE -file C:\CSR\%%a\V5MACHINE.csr -keypass enterpassword -storepass enterpassword -keystore C:\CSR\%%a\V5MACHINE.jks
  echo %Date% %Time% Certification request file for %%a stored in C:\CSR\%%a >>C:\CSR\Log.txt
  Pause
)
Echo Complete!
</code>```

Body:
I'm having some issues reading text files from batch files.

Here's the text file:

ABCD1
ABCD2
ABCD3
ABCD4
ABCD5
ABCD6
ABCD7
ABCD8
ABCD9 ... etc.

Here's the batch file:

@echo off
:start
Echo.
set java_home="C:\Program Files\Java\jre1.8.0_112"
set /p LocName= <LocName.txt
mkdir c:\CSR\%LocName%\

%JAVA_HOME%\bin\keytool.exe -genkey -keyalg RSA -dname "CN=%LocName%.net, O=AAA, C=US, ST=Georgia, L=Atlanta" -alias V5MACHINE -keypass enterpassword -keystore C:\CSR\%LocName%\V5MACHINE.jks -storepass enterpassword -validity 1461 -keysize 2048
%JAVA_HOME%\bin\keytool.exe -certreq -v -alias V5MACHINE -file C:\CSR\%LocName%\V5MACHINE.csr -keypass enterpassword -storepass enterpassword -keystore C:\CSR\%LocName%\V5MACHINE.jks
echo %Date% %Time% Certification request file for %LocName% stored in C:\CSR\%LocName% >>C:\CSR\Log.txt
Pause
Echo Complete!

Body:
Use a for /f loop to parse the file. %%a represents one line each pass.

@echo off
:start
Echo.
set java_home="C:\Program Files\Java\jre1.8.0_112"
for /f %%a in (LocName.txt) do (
  mkdir c:\CSR\%%a\
  %JAVA_HOME%\bin\keytool.exe -genkey -keyalg RSA -dname "CN=%%a.net, O=AAA, C=US, ST=Georgia, L=Atlanta" -alias V5MACHINE -keypass enterpassword -keystore C:\CSR\%%a\V5MACHINE.jks -storepass enterpassword -validity 1461 -keysize 2048
  %JAVA_HOME%\bin\keytool.exe -certreq -v -alias V5MACHINE -file C:\CSR\%%a\V5MACHINE.csr -keypass enterpassword -storepass enterpassword -keystore C:\CSR\%%a\V5MACHINE.jks
  echo %Date% %Time% Certification request file for %%a stored in C:\CSR\%%a >>C:\CSR\Log.txt
  Pause
)
Echo Complete!


问:
Com+ Object change Memory limit with powershell
How would you change the memory limit on a com+ object with powershell?

Here I've increased the Memory Limit to 1GB using the gui.

答:
Microsoft has a document on how to do this with visual basic

https://msdn.microsoft.com/en-us/library/windows/desktop/ms684192(v=vs.85).aspx

The following powershell will increase the memory limit. You will need to change $AppID and $CLSID to the appropriate Identifiers

```<code>$AppID = "{11111111-1111-1111-1111-111111111111}"
$CLSID = "{22222222-2222-2222-2222-222222222222}"
$comAdmin = New-Object -comobject COMAdmin.COMAdminCatalog

function ConfigurePoolLimits ( $comAdmin , $MemoryLimit) {
    Write-Host "Configuring Pool Limits"

    $apps = $comAdmin.GetCollection("Applications")
    $apps.Populate();
    $changesMade = $false
    foreach ($app in $apps ) {
        if ($app.Name -eq $AppName ) {
            Write-Host "Found Application $($app.Name)"
            Write-Host "RecycleMemoryLimit is $($app.Value("RecycleMemoryLimit"))"
            if ($app.Value("RecycleMemoryLimit") -ne $MemoryLimit) {
                $changesMade = $true
                Write-Host "Changing RecycleMemoryLimit to $($MemoryLimit)"
                $app.Value("RecycleMemoryLimit") = $MemoryLimit
            }
        }
    }
    if ($changesMade) {
        $apps.SaveChanges();
    }
}
</code>```

Then call the function with 2 parameters

```<code>ConfigurePoolLimits $comAdmin 1000000
</code>```

Body:
Microsoft has a document on how to do this with visual basic

https://msdn.microsoft.com/en-us/library/windows/desktop/ms684192(v=vs.85).aspx

The following powershell will increase the memory limit. You will need to change $AppID and $CLSID to the appropriate Identifiers

$AppID = "{11111111-1111-1111-1111-111111111111}"
$CLSID = "{22222222-2222-2222-2222-222222222222}"
$comAdmin = New-Object -comobject COMAdmin.COMAdminCatalog

function ConfigurePoolLimits ( $comAdmin , $MemoryLimit) {
    Write-Host "Configuring Pool Limits"

    $apps = $comAdmin.GetCollection("Applications")
    $apps.Populate();
    $changesMade = $false
    foreach ($app in $apps ) {
        if ($app.Name -eq $AppName ) {
            Write-Host "Found Application $($app.Name)"
            Write-Host "RecycleMemoryLimit is $($app.Value("RecycleMemoryLimit"))"
            if ($app.Value("RecycleMemoryLimit") -ne $MemoryLimit) {
                $changesMade = $true
                Write-Host "Changing RecycleMemoryLimit to $($MemoryLimit)"
                $app.Value("RecycleMemoryLimit") = $MemoryLimit
            }
        }
    }
    if ($changesMade) {
        $apps.SaveChanges();
    }
}

Then call the function with 2 parameters

ConfigurePoolLimits $comAdmin 1000000


问:
Keypair asking for passphrase after changing permissions to 600
this has been driving me mad and after hours searching here and everywhere else I am still unable to figure out why this is failing to work.

Syntax
sftp -o IdentityFile=/abc/efg/xxx/Priv_Key2.ppk -P 40007 at0223988_qa@inet-proxy-pg-1.us.adns.me.net

Initially the output was as follows:
Permissions 0755 for '/abc/efg/xxx/Priv_Key2.ppk' are too open.

So I went in, chmod 600 to lock down my private key, but now I get the following:
Enter passphrase for key /abc/efg/xxx/Priv_Key2.ppk:

The problem here is, there is no passphrase. I am logged in as the user that created this keypair and have no issue changing the permissions but sftp ignores the private key and errors out unless it is locked down as 600 but after I apply perms to 600 and rerun the sftp, it prompts me for a pw for this private key.

SCP does the same thing, asks for a passphrase if I change perms to 600.

What am I not seeing here? I am using PuttyCM, keygen was created in Putty KeyGen as SSH-2 RSA

答: Fixed this by reloading my private key back into the PuTTy KeyGen and choosing "Conversions" tab at the top, exporting to OpenSSH, then using that version of the key. Not sure why this worked but must have to do with our version of redhat not wanting to read that .ppk </p>


问:
Undefined property: App\Http\Controllers\PageController::$validate in Laravel
I have controller with the action

```<code>public function postContact(Request $request)
{

    $this->validate($request, [
        'name'    => 'required',
        'email'   => 'required | email',
        'content' => 'required'
    ]);
    if(empty($this->validate->fails())){
        die('wrong');
         return redirect()->route('contact')->withInput();
   }
   return ('right');

}
</code>```

When I don't fill in all input this dies on the wrong statement, but when I fill in all the input this error occurs:

ErrorException in PageController.php line 123:
  Undefined property: App\Http\Controllers\PageController::$validate

How can I fix this?
Thank for reading my answer:
Image

答:
It should be:

```<code>if (empty($this->validate()->fails())) {
</code>```

Because validate() is a method, not property.

https://laravel.com/docs/5.4/validation#quick-writing-the-validation-logic

Body:
I have controller with the action

public function postContact(Request $request)
{

    $this->validate($request, [
        'name'    => 'required',
        'email'   => 'required | email',
        'content' => 'required'
    ]);
    if(empty($this->validate->fails())){
        die('wrong');
         return redirect()->route('contact')->withInput();
   }
   return ('right');

}

When I don't fill in all input this dies on the wrong statement, but when I fill in all the input this error occurs:

ErrorException in PageController.php line 123:
  Undefined property: App\Http\Controllers\PageController::$validate

How can I fix this?
Thank for reading my answer:
Image

Body:
It should be:

if (empty($this->validate()->fails())) {

Because validate() is a method, not property.

https://laravel.com/docs/5.4/validation#quick-writing-the-validation-logic


问:
Regex get image url for Source code

I want to get some URLs of images in Js/HTML:
img class="img-responsive" id="Q72D2600000-MDYI" src="https://s7d5.scene7.com/is/image/Guess/Q72D2600000-MDYI?$2014_G_xxlarge$" alt="Q72D2600000-MDYI" />

Looking for solution that will detect image url. So the output will be:
https://s7d5.scene7.com/is/image/Guess/Q72D2600000-MDYI?$2014_G_xxlarge$

答:
The below code may be helpfull

```<code>$html = '<img class="img-responsive" id="Q72D2600000-MDYI" src="https://s7d5.scene7.com/is/image/Guess/Q72D2600000-MDYI?$2014_G_xxlarge$" alt="Q72D2600000-MDYI" />';
preg_match('/<img\s.*?\bsrc="(.*?)".*?>/si', $html, $matches);

$image_src = $matches[1];

echo $image_src;
</code>```

Output

```<code>https://s7d5.scene7.com/is/image/Guess/Q72D2600000-MDYI?$2014_G_xxlarge$
</code>```

Title: Regex get image url for Source code

Body:
The below code may be helpfull

$html = '<img class="img-responsive" id="Q72D2600000-MDYI" src="https://s7d5.scene7.com/is/image/Guess/Q72D2600000-MDYI?$2014_G_xxlarge$" alt="Q72D2600000-MDYI" />';
preg_match('/<img\s.*?\bsrc="(.*?)".*?>/si', $html, $matches);

$image_src = $matches[1];

echo $image_src;

Output

https://s7d5.scene7.com/is/image/Guess/Q72D2600000-MDYI?$2014_G_xxlarge$


问:
While loop create file from $_GET
I created a script that gets a MP3 file from a GET statement. I need a way to make sure that if the original name "recording.mp3" does not exist then create it from GET contents, if it does exist then append a number to the file name. What am I doing wrong? the part that does not work thus far is appending the number but getting the file and saving works great. Remove the while loop and program works!    </p>

```<code><?php
$actual_name = pathinfo("PHPAPI/recording.mp3",PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo("PHPAPI/recording.mp3",PATHINFO_EXTENSION);

$i = 0;
if ($_GET["RecordingUrl"]){
    while(file_exists("PHPAPI/".$actual_name.".".$extension)){
        $actual_name = $original_name.$i;
        $name = $actual_name.".".$extension;
        $i++;
    }
    file_put_contents($name, file_get_contents($_GET["RecordingUrl"]));
}
elseif ($_GET["RecordingUrl"]){
    file_put_contents($original_name.".".$extension,
    file_get_contents($_GET["RecordingUrl"]));
}
?>
</code>```

答:
To make your code more organized, use a function</p>

```<code><?php
$actual_name = pathinfo("PHPAPI/recording.mp3",PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo("PHPAPI/recording.mp3",PATHINFO_EXTENSION);

if ($_GET["RecordingUrl"]) {
     if (file_exists("PHPAPI/".$actual_name.".".$extension)) {
        $actual_name = find_new_name($original_name, $extension);
     } else {
        $actual_name = $original_name;
     }
     $name = $actual_name.".".$extension;
     file_put_contents($name, file_get_contents($_GET["RecordingUrl"]));
}

function find_new_name ( $file, $extension ) {
    $name = $file.".".$extension;
    $i = 0;
    while(file_exists("PHPAPI/".$name)){
        $new_name = $file.$i;
        $name = $new_name.".".$extension;
        $i++;
    }
    return $new_name;
}
 ?>
</code>```

Title: While loop create file from $_GET

Body:
I created a script that gets a MP3 file from a GET statement. I need a way to make sure that if the original name "recording.mp3" does not exist then create it from GET contents, if it does exist then append a number to the file name. What am I doing wrong? the part that does not work thus far is appending the number but getting the file and saving works great. Remove the while loop and program works!

<?php
$actual_name = pathinfo("PHPAPI/recording.mp3",PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo("PHPAPI/recording.mp3",PATHINFO_EXTENSION);

$i = 0;
if ($_GET["RecordingUrl"]){
    while(file_exists("PHPAPI/".$actual_name.".".$extension)){
        $actual_name = $original_name.$i;
        $name = $actual_name.".".$extension;
        $i++;
    }
    file_put_contents($name, file_get_contents($_GET["RecordingUrl"]));
}
elseif ($_GET["RecordingUrl"]){
    file_put_contents($original_name.".".$extension,
    file_get_contents($_GET["RecordingUrl"]));
}
?>

Body:
To make your code more organized, use a function

<?php
$actual_name = pathinfo("PHPAPI/recording.mp3",PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo("PHPAPI/recording.mp3",PATHINFO_EXTENSION);

if ($_GET["RecordingUrl"]) {
     if (file_exists("PHPAPI/".$actual_name.".".$extension)) {
        $actual_name = find_new_name($original_name, $extension);
     } else {
        $actual_name = $original_name;
     }
     $name = $actual_name.".".$extension;
     file_put_contents($name, file_get_contents($_GET["RecordingUrl"]));
}

function find_new_name ( $file, $extension ) {
    $name = $file.".".$extension;
    $i = 0;
    while(file_exists("PHPAPI/".$name)){
        $new_name = $file.$i;
        $name = $new_name.".".$extension;
        $i++;
    }
    return $new_name;
}
 ?>


问:
Single page responsive dropdown menu - hide dropdown on "a" click
Building a single page layout with a responsive dropdown menu. Issue I'm having is trying to figure out if I can add a call in the .js file to collapse the opened menu once a user clicks on the 'a' jump link.

(function($) {
  $.fn.menumaker = function(options) {
    var cssmenu = $(this),
      settings = $.extend({
        format: "dropdown",
        sticky: false
      }, options);
    return this.each(function() {
      $(this).find(".button-mobile").on('click', function() {
        $(this).toggleClass('menu-opened');
        var mainmenu = $(this).next('ul');
        if (mainmenu.hasClass('open')) {
          mainmenu.slideToggle().removeClass('open');
        } else {
          mainmenu.slideToggle().addClass('open');
          if (settings.format === "dropdown") {
            mainmenu.find('ul').show();
          }
        }
      });
      cssmenu.find('li ul').parent().addClass('has-sub');
      multiTg = function() {
        cssmenu.find(".has-sub").prepend('');
        cssmenu.find('.submenu-button').on('click', function() {
          $(this).toggleClass('submenu-opened');
          if ($(this).siblings('ul').hasClass('open')) {
            $(this).siblings('ul').removeClass('open').slideToggle();
          } else {
            $(this).siblings('ul').addClass('open').slideToggle();
          }
        });
      };
      if (settings.format === 'multitoggle') multiTg();
      else cssmenu.addClass('dropdown');
      if (settings.sticky === true) cssmenu.css('position', 'fixed');
      resizeFix = function() {
        var mediasize = 960;
        if ($(window).width() > mediasize) {
          cssmenu.find('ul').show();
        }
        if ($(window).width() <= mediasize) {
          cssmenu.find('ul').hide().removeClass('open');
        }
      };
      resizeFix();
      return $(window).on('resize', resizeFix);
    });
  };
})(jQuery);

(function($) {
  $(document).ready(function() {
    $("#cssmenu").menumaker({
      format: "multitoggle"
    });
  });
})(jQuery);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>nav {
  float: right;
  margin-top: 15px;
}

#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a,
#cssmenu #head-mobile {
  border: 0;
  list-style: none;
  line-height: 1;
  display: block;
  position: relative;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

#cssmenu:after,
#cssmenu>ul:after {
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}

#cssmenu #head-mobile {
  display: none;
}

#cssmenu>ul>li {
  float: left;
}

#cssmenu>ul>li {
  padding: 10px 0;
}

#cssmenu>ul>li:last-child {
  border: 1px solid #fff;
  border-radius: 3px;
}

#cssmenu>ul>li>a {
  padding: 0 25px 0 25px;
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 1px;
  text-decoration: none;
  color: #FFF;
}

#cssmenu>ul>li:hover>a,
#cssmenu ul li.active a {
  color: rgba(255, 255, 255, .7);
}

li.buttonfill {
  transition: all .3s ease-in;
  -moz-transition: all .3s ease-in;
  -o-transition: all .3s ease-in;
  -webkit-transition: all .3s ease-in;
}

li.buttonfill:hover {
  background-color: rgba(226, 226, 226, .2);
  transition: all .3s ease-out;
  -moz-transition: all .3s ease-out;
  -o-transition: all .3s ease-out;
  -webkit-transition: all .3s ease-out;
}

@media screen and (max-width:960px) {
  nav {
    width: 100%;
    margin-top: 0;
  }
  #cssmenu {
    width: 100%;
    margin-top: -10px;
  }
  #cssmenu ul {
    width: 100%;
    display: none;
  }
  #cssmenu ul li {
    width: 100%;
    border-top: 1px solid rgba(251, 252, 252, 0.5);
    background-color: #A31610;
  }
  #cssmenu>ul>li:last-child {
    border-top: 1px solid rgba(251, 252, 252, 0.5);
    border-left: 0;
    border-right: 0;
    border-bottom: 0;
    border-radius: 0;
  }
  #cssmenu ul li:hover {
    background: #C22D32;
  }
  #cssmenu>ul>li {
    padding: 25px;
  }
  #cssmenu #head-mobile {
    display: block;
    font-size: 16px;
    font-weight: normal;
  }
  .button-mobile {
    width: 55px;
    height: 46px;
    position: absolute;
    right: 40px;
    top: -65px;
    cursor: pointer;
    z-index: 12399994;
  }
  .button-mobile:after {
    position: absolute;
    top: 22px;
    right: 20px;
    display: block;
    height: 8px;
    width: 28px;
    border-top: 2px solid #FFF;
    border-bottom: 2px solid #FFF;
    content: '';
  }
  .button-mobile:before {
    -webkit-transition: all .3s ease;
    -ms-transition: all .3s ease;
    transition: all .3s ease;
    position: absolute;
    top: 16px;
    right: 20px;
    display: block;
    height: 2px;
    width: 28px;
    background: #FFF;
    content: '';
  }
  .button-mobile.menu-opened:after {
    -webkit-transition: all .3s ease;
    -ms-transition: all .3s ease;
    transition: all .3s ease;
    top: 23px;
    border: 0;
    height: 2px;
    width: 27px;
    background: #fff;
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    transform: rotate(45deg);
  }
  .button-mobile.menu-opened:before {
    top: 23px;
    background: #fff;
    width: 27px;
    -webkit-transform: rotate(-45deg);
    -moz-transform: rotate(-45deg);
    -ms-transform: rotate(-45deg);
    -o-transform: rotate(-45deg);
    transform: rotate(-45deg);
  }
  .container.logo-nav,
  .container.logo-nav>.sixteen.columns {
    width: 100%;
    margin: 0;
  }
}</code>```

ABOUT

SERVICES

RESEARCH-MEDIA

CREATIVE

CONTACT

```

答:
After your .menumaker() call add a listener on the "a" tags and fire a function to close all menus.</p>

```<code>$("#cssmenu ul li a").click(function(){
    //fire another click to the menu button to toggle it closed.
});
</code>```

Body:
Building a single page layout with a responsive dropdown menu. Issue I'm having is trying to figure out if I can add a call in the .js file to collapse the opened menu once a user clicks on the 'a' jump link.

(function($) {
  $.fn.menumaker = function(options) {
    var cssmenu = $(this),
      settings = $.extend({
        format: "dropdown",
        sticky: false
      }, options);
    return this.each(function() {
      $(this).find(".button-mobile").on('click', function() {
        $(this).toggleClass('menu-opened');
        var mainmenu = $(this).next('ul');
        if (mainmenu.hasClass('open')) {
          mainmenu.slideToggle().removeClass('open');
        } else {
          mainmenu.slideToggle().addClass('open');
          if (settings.format === "dropdown") {
            mainmenu.find('ul').show();
          }
        }
      });
      cssmenu.find('li ul').parent().addClass('has-sub');
      multiTg = function() {
        cssmenu.find(".has-sub").prepend('');
        cssmenu.find('.submenu-button').on('click', function() {
          $(this).toggleClass('submenu-opened');
          if ($(this).siblings('ul').hasClass('open')) {
            $(this).siblings('ul').removeClass('open').slideToggle();
          } else {
            $(this).siblings('ul').addClass('open').slideToggle();
          }
        });
      };
      if (settings.format === 'multitoggle') multiTg();
      else cssmenu.addClass('dropdown');
      if (settings.sticky === true) cssmenu.css('position', 'fixed');
      resizeFix = function() {
        var mediasize = 960;
        if ($(window).width() > mediasize) {
          cssmenu.find('ul').show();
        }
        if ($(window).width() <= mediasize) {
          cssmenu.find('ul').hide().removeClass('open');
        }
      };
      resizeFix();
      return $(window).on('resize', resizeFix);
    });
  };
})(jQuery);

(function($) {
  $(document).ready(function() {
    $("#cssmenu").menumaker({
      format: "multitoggle"
    });
  });
})(jQuery);

nav {
  float: right;
  margin-top: 15px;
}

#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a,
#cssmenu #head-mobile {
  border: 0;
  list-style: none;
  line-height: 1;
  display: block;
  position: relative;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

#cssmenu:after,
#cssmenu>ul:after {
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}

#cssmenu #head-mobile {
  display: none;
}

#cssmenu>ul>li {
  float: left;
}

#cssmenu>ul>li {
  padding: 10px 0;
}

#cssmenu>ul>li:last-child {
  border: 1px solid #fff;
  border-radius: 3px;
}

#cssmenu>ul>li>a {
  padding: 0 25px 0 25px;
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 1px;
  text-decoration: none;
  color: #FFF;
}

#cssmenu>ul>li:hover>a,
#cssmenu ul li.active a {
  color: rgba(255, 255, 255, .7);
}

li.buttonfill {
  transition: all .3s ease-in;
  -moz-transition: all .3s ease-in;
  -o-transition: all .3s ease-in;
  -webkit-transition: all .3s ease-in;
}

li.buttonfill:hover {
  background-color: rgba(226, 226, 226, .2);
  transition: all .3s ease-out;
  -moz-transition: all .3s ease-out;
  -o-transition: all .3s ease-out;
  -webkit-transition: all .3s ease-out;
}

@media screen and (max-width:960px) {
  nav {
    width: 100%;
    margin-top: 0;
  }
  #cssmenu {
    width: 100%;
    margin-top: -10px;
  }
  #cssmenu ul {
    width: 100%;
    display: none;
  }
  #cssmenu ul li {
    width: 100%;
    border-top: 1px solid rgba(251, 252, 252, 0.5);
    background-color: #A31610;
  }
  #cssmenu>ul>li:last-child {
    border-top: 1px solid rgba(251, 252, 252, 0.5);
    border-left: 0;
    border-right: 0;
    border-bottom: 0;
    border-radius: 0;
  }
  #cssmenu ul li:hover {
    background: #C22D32;
  }
  #cssmenu>ul>li {
    padding: 25px;
  }
  #cssmenu #head-mobile {
    display: block;
    font-size: 16px;
    font-weight: normal;
  }
  .button-mobile {
    width: 55px;
    height: 46px;
    position: absolute;
    right: 40px;
    top: -65px;
    cursor: pointer;
    z-index: 12399994;
  }
  .button-mobile:after {
    position: absolute;
    top: 22px;
    right: 20px;
    display: block;
    height: 8px;
    width: 28px;
    border-top: 2px solid #FFF;
    border-bottom: 2px solid #FFF;
    content: '';
  }
  .button-mobile:before {
    -webkit-transition: all .3s ease;
    -ms-transition: all .3s ease;
    transition: all .3s ease;
    position: absolute;
    top: 16px;
    right: 20px;
    display: block;
    height: 2px;
    width: 28px;
    background: #FFF;
    content: '';
  }
  .button-mobile.menu-opened:after {
    -webkit-transition: all .3s ease;
    -ms-transition: all .3s ease;
    transition: all .3s ease;
    top: 23px;
    border: 0;
    height: 2px;
    width: 27px;
    background: #fff;
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    transform: rotate(45deg);
  }
  .button-mobile.menu-opened:before {
    top: 23px;
    background: #fff;
    width: 27px;
    -webkit-transform: rotate(-45deg);
    -moz-transform: rotate(-45deg);
    -ms-transform: rotate(-45deg);
    -o-transform: rotate(-45deg);
    transform: rotate(-45deg);
  }
  .container.logo-nav,
  .container.logo-nav>.sixteen.columns {
    width: 100%;
    margin: 0;
  }
}

ABOUT

SERVICES

RESEARCH-MEDIA

CREATIVE

CONTACT

Body:
After your .menumaker() call add a listener on the "a" tags and fire a function to close all menus.

$("#cssmenu ul li a").click(function(){
    //fire another click to the menu button to toggle it closed.
});


问:
Is it correct to use single quotes for HTML attributes?
Recently I've been seeing a lot of this:

```<code><a href='http://widget-site-example.com/example.html'>
    <img src='http://widget-site-example.com/ross.jpg' alt='Ross's Widget' />
</a>
</code>```

Is it valid to use single quotes in HTML? As I've highlighted above it's also problematic because you have to escape apostrophes.

答: Single quotes are perfectly legal in (X)HTML. Using a backslash to escape them, on the other hand, isn't.  is an image with the alt text "Ross\", and empty s and Widget/Widget' attributes. The correct way of escaping an apostrophe in HTML is '.

OwnerDisplayName: Ross

Body:
Recently I've been seeing a lot of this:

Is it valid to use single quotes in HTML? As I've highlighted above it's also problematic because you have to escape apostrophes.

LastEditorDisplayName: MrValdez

Body: Single quotes are perfectly legal in (X)HTML. Using a backslash to escape them, on the other hand, isn't. <img src='http://widget-site-example.com/ross.jpg' alt='Ross\'s Widget' /> is an image with the alt text "Ross\", and empty s and Widget/Widget' attributes. The correct way of escaping an apostrophe in HTML is &#39;.


问:
PHP SQLSTATE[42000] syntax error or access violation: 1064 in query
I'm running a query but when i run it, it returns a

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' count(distinct exams.user_id) as count_user_mhs from `users` where `users.type`' at line 1 (SQL: select `universities`.`name`, count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0, count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1, count(exams.subject_id) as count_subject, sum(exams.score) as count_score, TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time from `exams` inner join `universities` on `universities`.`id` = `exams`.`university_id` inner join `users` on `users`.`id` = `exams`.`user_id` where exists (select * from `universities` where `exams`.`university_id` = `universities`.`id`) group by `user_id` order by `count_score` desc, `count_time` asc)

```<code>$exams = Exam::join('universities', 'universities.id', '=', 'exams.university_id')
                ->join('users', 'users.id', '=', 'exams.user_id')
                ->select('universities.name',DB::raw('count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0'),DB::raw('count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1'),DB::raw('count(exams.subject_id) as count_subject'),DB::raw('sum(exams.score) as count_score'),DB::raw('TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time'));
</code>```

Can anyone help? I am guessing, it has something to do with the DB::raw expression. But I don't know exactly what is wrong.

答:
Your generated query looks like this:

```<code>select
    `universities`.`name`,
    count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0,
    count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1,
    count(exams.subject_id) as count_subject,
    sum(exams.score) as count_score,
    TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time
from
    `exams`
        inner join
    `universities` on `universities`.`id` = `exams`.`university_id`
        inner join
    `users` on `users`.`id` = `exams`.`user_id`
where
    exists (select * from `universities` where `exams`.`university_id` = `universities`.`id`)
group by
    `user_id`
order by
    `count_score` desc,
    `count_time` asc
</code>```

The problem is on lines 3 and 4 which are generated by the DB::raw code.

To fix this you need to update your Eloquent query like this:

```<code><?php
$exams = Exam::join('universities', 'universities.id', '=', 'exams.university_id')
    ->join('users', 'users.id', '=', 'exams.user_id')
    ->select(
        'universities.name',
        DB::raw('(select count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0)'),
        DB::raw('(select count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1)'),
        DB::raw('count(exams.subject_id) as count_subject'),DB::raw('sum(exams.score) as count_score'),
        DB::raw('TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time')
    );
</code>```

That said... Executing the SELECT COUNT subqueries in the main SELECT statement is not a good idea as they will be executed for each row selected by the main query.

Body:
I'm running a query but when i run it, it returns a

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' count(distinct exams.user_id) as count_user_mhs from `users` where `users.type`' at line 1 (SQL: select `universities`.`name`, count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0, count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1, count(exams.subject_id) as count_subject, sum(exams.score) as count_score, TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time from `exams` inner join `universities` on `universities`.`id` = `exams`.`university_id` inner join `users` on `users`.`id` = `exams`.`user_id` where exists (select * from `universities` where `exams`.`university_id` = `universities`.`id`) group by `user_id` order by `count_score` desc, `count_time` asc)

$exams = Exam::join('universities', 'universities.id', '=', 'exams.university_id')
                ->join('users', 'users.id', '=', 'exams.user_id')
                ->select('universities.name',DB::raw('count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0'),DB::raw('count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1'),DB::raw('count(exams.subject_id) as count_subject'),DB::raw('sum(exams.score) as count_score'),DB::raw('TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time'));

Can anyone help? I am guessing, it has something to do with the DB::raw expression. But I don't know exactly what is wrong.

Body:
Your generated query looks like this:

select
    `universities`.`name`,
    count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0,
    count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1,
    count(exams.subject_id) as count_subject,
    sum(exams.score) as count_score,
    TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time
from
    `exams`
        inner join
    `universities` on `universities`.`id` = `exams`.`university_id`
        inner join
    `users` on `users`.`id` = `exams`.`user_id`
where
    exists (select * from `universities` where `exams`.`university_id` = `universities`.`id`)
group by
    `user_id`
order by
    `count_score` desc,
    `count_time` asc

The problem is on lines 3 and 4 which are generated by the DB::raw code.

To fix this you need to update your Eloquent query like this:

<?php
$exams = Exam::join('universities', 'universities.id', '=', 'exams.university_id')
    ->join('users', 'users.id', '=', 'exams.user_id')
    ->select(
        'universities.name',
        DB::raw('(select count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0)'),
        DB::raw('(select count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1)'),
        DB::raw('count(exams.subject_id) as count_subject'),DB::raw('sum(exams.score) as count_score'),
        DB::raw('TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time')
    );

That said... Executing the SELECT COUNT subqueries in the main SELECT statement is not a good idea as they will be executed for each row selected by the main query.


问:
I am trying to compare two dictionaries in Python and return the key for which values changed. But Python throws a invalid Syntax
I am new to Python. I am trying to compare two dictionaries based on the value and return if there are any newly added keys and removed keys. I also want to print the modified keys(if the values are changed).

Basically, i have a directory with multiple sub folders and files in it. I calculate the md5sum of all these and have similar directory on other node, check these both and print the added, removed and modified keys based on checksum.

I have written the code to do these, it works as well in Python 2.7. But sadly, i m suppposed make this work in 2.6 and lesser as well. Here is the code and it throws invalid syntax in

```<code>import os
import sys
from hashlib import md5
import ssl
import json

walk_dir = sys.argv[1]
actual_hash = {}
data = {}

def get_md5sum(file_name):
    """
    Calculate the md5sum of file.
    Returns a valid md5sum if successful, None otherwise.
    """
    md5sum = md5()
    block_size = 128 * md5sum.block_size
    try:
        with open(file_name, 'rb') as f:
            while True:
                data = f.read(block_size)
                if not data:
                    break
                md5sum.update(data)
        return md5sum.hexdigest()
    except Exception as e:
        ERROR("Failed to calculate md5sum for %s with %s" %
              (file_name, e))
        return None

def dict_compare(d1, d2):
    d1_keys = set(d1.keys())
    d2_keys = set(d2.keys())
    intersect_keys = d1_keys.intersection(d2_keys)
    added = d1_keys - d2_keys
    removed = d2_keys - d1_keys
    modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
    same = set(o for o in intersect_keys if d1[o] == d2[o])
    return added, removed, modified, same

with open('../tool/file.json', 'r') as f:
     data = json.load(f)

for root, subdirs, files in os.walk(walk_dir):
for filename in files:
    file_path = os.path.join(root, filename)
    tmp_str = get_md5sum(file_path)
    actual_hash[file_path]= tmp_str

added, removed, modified, same = dict_compare(data, actual_hash)

print "\n\n*******************************"
print "Newly Added Files"
print "*******************************"
if len(added) == 0:
    print "No files are newly added"
else:
    print "\n ".join(str(e) for e in added)

print "\n\n*******************************"
print "Missing Files"
print "*******************************"
if len(removed) == 0:
    print "No files are missing or removed"
else:
    print "\n ".join(str(e) for e in removed)

print "\n\n*******************************"
print "Modified Files"
print "*******************************"
if not modified:
    print "No modified files are found"
else:
    print modified
</code>```

It throws

modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
                                     ^
SyntaxError: invalid syntax

How can i make this work on older versions and also, please suggest improvements on this code. Thanks!

答:
One improvement suggestion, immediately check if d1 is equal to d2, return without unnecessary processing, then carry on with finding out why it is not.</p>

```<code>def dict_compare(d1, d2):
    if d1 == d2:
        return 0, 0, False, True
    {the rest of your code here}
</code>```

Body:
I am new to Python. I am trying to compare two dictionaries based on the value and return if there are any newly added keys and removed keys. I also want to print the modified keys(if the values are changed).

Basically, i have a directory with multiple sub folders and files in it. I calculate the md5sum of all these and have similar directory on other node, check these both and print the added, removed and modified keys based on checksum.

I have written the code to do these, it works as well in Python 2.7. But sadly, i m suppposed make this work in 2.6 and lesser as well. Here is the code and it throws invalid syntax in

import os
import sys
from hashlib import md5
import ssl
import json

walk_dir = sys.argv[1]
actual_hash = {}
data = {}

def get_md5sum(file_name):
    """
    Calculate the md5sum of file.
    Returns a valid md5sum if successful, None otherwise.
    """
    md5sum = md5()
    block_size = 128 * md5sum.block_size
    try:
        with open(file_name, 'rb') as f:
            while True:
                data = f.read(block_size)
                if not data:
                    break
                md5sum.update(data)
        return md5sum.hexdigest()
    except Exception as e:
        ERROR("Failed to calculate md5sum for %s with %s" %
              (file_name, e))
        return None

def dict_compare(d1, d2):
    d1_keys = set(d1.keys())
    d2_keys = set(d2.keys())
    intersect_keys = d1_keys.intersection(d2_keys)
    added = d1_keys - d2_keys
    removed = d2_keys - d1_keys
    modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
    same = set(o for o in intersect_keys if d1[o] == d2[o])
    return added, removed, modified, same

with open('../tool/file.json', 'r') as f:
     data = json.load(f)

for root, subdirs, files in os.walk(walk_dir):
for filename in files:
    file_path = os.path.join(root, filename)
    tmp_str = get_md5sum(file_path)
    actual_hash[file_path]= tmp_str

added, removed, modified, same = dict_compare(data, actual_hash)

print "\n\n*******************************"
print "Newly Added Files"
print "*******************************"
if len(added) == 0:
    print "No files are newly added"
else:
    print "\n ".join(str(e) for e in added)

print "\n\n*******************************"
print "Missing Files"
print "*******************************"
if len(removed) == 0:
    print "No files are missing or removed"
else:
    print "\n ".join(str(e) for e in removed)

print "\n\n*******************************"
print "Modified Files"
print "*******************************"
if not modified:
    print "No modified files are found"
else:
    print modified

It throws

modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
                                     ^
SyntaxError: invalid syntax

How can i make this work on older versions and also, please suggest improvements on this code. Thanks!

Body:
One improvement suggestion, immediately check if d1 is equal to d2, return without unnecessary processing, then carry on with finding out why it is not.

def dict_compare(d1, d2):
    if d1 == d2:
        return 0, 0, False, True
    {the rest of your code here}


问:
How to destroy and recreate a Jquery Mobile form element with the same name
I am using Jquery Mobile and have a situation which requires me to programmatically create some form fields (select, input, etc) like so:

```<code>$fieldInput = $('<input type="text" name="' + fieldName + '" />');
</code>```

This works totally fine and Jquery styles the input as expected. The problem comes when the form has to be recreated. I then first "empty" the containing div element using Jquery's .empty() method and then proceed to create the form elements again exactly as above.

The problem is that after the first time, all subsequent attempts to create the form elements result in Jquery Mobile not styling the elements. I am smart enough to work out that this is because I am attempting to create an element which effectively already exists so far as Jquery is concerned and it's getting confused. However, I am not smart enough to know what to do about it... I'm thinking I need to somehow 'unregister' the element before creating it again but I don't know how.

I have tried calling both

```<code>$fieldInput.trigger('refresh');
</code>```

and

```<code>$fieldInput.trigger('create');
</code>```

on the elements to no avail. I could go to the lengthy process of rewriting my code so that the elements are only created once at the start and are simply reset when necessary but for reasons I won't go into this would make things a lot more complicated for me.

How can I recreate the same form element (same name, no ID) and still have Jquery Mobile do it's thing? How do I 'unregister' a a Jquery Mobile element?

答:
You know already how to programmatically compose the HTML, so i haven't nothing to learn to You about that, so straight to the point: after you are adding your form elements, you should tell JQM to create the Widgets and update the layout of the container.

Your question is somehow vague about what widgets you need, and below is an example with an input, a textarea and a select. Using empty() is just fine.

function createFormElements() {
  var input = [
    'Text Input:',
    '<input type="text" name="name" id="basic" value="">'].join("");
  var textarea = [
    'Textarea:',
    '<textarea name="textarea" id="textarea">',
    'I\'m a basic textarea.',
    '</textarea>'].join("");
  var select = [
    'Shipping method:',
    '<select name="select" id="select" data-mini="true">',
    '<option value="standard">Standard: 7 day</option>',
    '<option value="rush">Rush: 3 days</option>',
    '<option value="express">Express: next day</option>',
    '<option value="overnight">Overnight</option>',
    '</select>'].join("");
  $("#myForm").empty();
  $(input).appendTo("#myForm");
  $(textarea).appendTo("#myForm");
  $(select).appendTo("#myForm");
  $("#myForm input").textinput();
  $("#myForm textarea").textinput();
  $("#myForm select").selectmenu();
  $(".ui-content").trigger("updatelayout");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
  <link rel="stylesheet" href="style.css" />
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <div id="page-one" data-role="page">
    <div role="main" class="ui-content">
      Create Elements
      <form id="myForm">
      </form>
    </div>
  </div>
</body>
</html></code>```

Body:
I am using Jquery Mobile and have a situation which requires me to programmatically create some form fields (select, input, etc) like so:

$fieldInput = $('<input type="text" name="' + fieldName + '" />');

This works totally fine and Jquery styles the input as expected. The problem comes when the form has to be recreated. I then first "empty" the containing div element using Jquery's .empty() method and then proceed to create the form elements again exactly as above.

The problem is that after the first time, all subsequent attempts to create the form elements result in Jquery Mobile not styling the elements. I am smart enough to work out that this is because I am attempting to create an element which effectively already exists so far as Jquery is concerned and it's getting confused. However, I am not smart enough to know what to do about it... I'm thinking I need to somehow 'unregister' the element before creating it again but I don't know how.

I have tried calling both

$fieldInput.trigger('refresh');

and

$fieldInput.trigger('create');

on the elements to no avail. I could go to the lengthy process of rewriting my code so that the elements are only created once at the start and are simply reset when necessary but for reasons I won't go into this would make things a lot more complicated for me.

How can I recreate the same form element (same name, no ID) and still have Jquery Mobile do it's thing? How do I 'unregister' a a Jquery Mobile element?

Body:
You know already how to programmatically compose the HTML, so i haven't nothing to learn to You about that, so straight to the point: after you are adding your form elements, you should tell JQM to create the Widgets and update the layout of the container.

Your question is somehow vague about what widgets you need, and below is an example with an input, a textarea and a select. Using empty() is just fine.

function createFormElements() {
  var input = [
    '<label for="basic">Text Input:</label>',
    '<input type="text" name="name" id="basic" value="">'].join("");
  var textarea = [
    '<label for="textarea">Textarea:</label>',
    '<textarea name="textarea" id="textarea">',
    'I\'m a basic textarea.',
    '</textarea>'].join("");
  var select = [
    '<label for="select" class="select">Shipping method:</label>',
    '<select name="select" id="select" data-mini="true">',
    '<option value="standard">Standard: 7 day</option>',
    '<option value="rush">Rush: 3 days</option>',
    '<option value="express">Express: next day</option>',
    '<option value="overnight">Overnight</option>',
    '</select>'].join("");
  $("#myForm").empty();
  $(input).appendTo("#myForm");
  $(textarea).appendTo("#myForm");
  $(select).appendTo("#myForm");
  $("#myForm input").textinput();
  $("#myForm textarea").textinput();
  $("#myForm select").selectmenu();
  $(".ui-content").trigger("updatelayout");
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
  <link rel="stylesheet" href="style.css" />
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <div id="page-one" data-role="page">
    <div role="main" class="ui-content">
      <a class="ui-btn ui-corner-all" href="javascript:void(0);" onclick="createFormElements();">Create Elements</a>
      <form id="myForm">
      </form>
    </div>
  </div>
</body>
</html>


问:
React.js: Set a Default value into a prop
Fellows I have made this Component that creates a simple Button:

```<code>class AppButton extends Component {

  setOnClick() {
    if(!this.props.onClick && typeof this.props.onClick == 'function') {
      this.props.onClick=function(){ alert("Hello"); }
    }
  }

  setMessage() {
    if(!this.props.message){
        this.props.message="Hello"
    }
  }

  render(){
    this.setOnClick()
    this.setMessage()
    return (
      <button onClick={this.props.onClick}>{this.props.message}</button>
    )
  }
}
</code>```

And I have an another Component that renders 2 Buttons:

```<code>class App extends Component {
  render() {
    return (
          <AppButton onClick={function(){ alert('Test Alert') } } message="My Button" />
          <AppButton />
    );
  }
}
</code>```

But I get the following error:

TypeError: can't define property "message": Object is not extensible

On the line that says:

```<code>        this.props.message="Hello"
</code>```

in method setMessage of the AppButton class.

Edit 1

I generated the react application using npm and me package.json has the following content

```<code>{
  "name": "sample",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "react-scripts": "1.0.7"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
</code>```

答: Are you using React v.14 or above? the props object is now frozen and cant be changed. You can use React.cloneElement instead</p>

ContentLicense: CC BY-SA 4.0

Body:
Fellows I have made this Component that creates a simple Button:

class AppButton extends Component {

  setOnClick() {
    if(!this.props.onClick && typeof this.props.onClick == 'function') {
      this.props.onClick=function(){ alert("Hello"); }
    }
  }

  setMessage() {
    if(!this.props.message){
        this.props.message="Hello"
    }
  }

  render(){
    this.setOnClick()
    this.setMessage()
    return (
      <button onClick={this.props.onClick}>{this.props.message}</button>
    )
  }
}

And I have an another Component that renders 2 Buttons:

class App extends Component {
  render() {
    return (
          <AppButton onClick={function(){ alert('Test Alert') } } message="My Button" />
          <AppButton />
    );
  }
}

But I get the following error:

TypeError: can't define property "message": Object is not extensible

On the line that says:

        this.props.message="Hello"

in method setMessage of the AppButton class.

Edit 1

I generated the react application using npm and me package.json has the following content

{
  "name": "sample",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "react-scripts": "1.0.7"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}


问:
Eclipse and JavaFX? is it just me?
I'm looking at learning JavaFX.

I've tried setting Eclipse to develop a small app and I've downloaded the Eclipse plugin.

Eclipse JavaFX plugin

BUT... it just seems, well, flakey.

So I have 3 questions...

1: Is there a better plugin?

2: Or is there some great set of tutorials out there that I'm missing?

3: finally, is it meant to be easy to call Java code from FX? I'm stuggling, it there a good example somewhere?

On questions 1 & 2, Eclipse underlines code in red that just shouln't be. For example..
see this image... alt text http://www.qenet.co.uk/fx.jpg

Why does it underline bit of imports in red?

I know this is little of an open ended question. So I guess my main question is this...

Is my experiance of JavaFX and Eclipse the best I can hope for? Or am I missing something ?
(and I'm not looking for a Yes/No response) :-)

Just looking for a discussion on how best to learn/develop JavaFx.

答: To me this has happened when I wronlgy installed javafx sdk 1.2.3....This plugin works only with 1.2.1... :/</p>

Title: Eclipse and JavaFX? is it just me?


问:
Discrepancy in Facebook Graph API Documentation Regarding Page Likes (Incoming vs Outgoing)?
I'm looking at the Facebook Graph API documentation and noticed something odd, or maybe I'm misunderstanding something.

This page here: https://developers.facebook.com/docs/graph-api/reference/v2.9/page/likes describes /{page-id}/likes as returning "The Pages that this Page Likes"

However, this page: https://developers.facebook.com/docs/graph-api/reference/v2.9/object/likes (which seems to be describing the same endpoint if a {page-id} is passed in for {object-id} is saying that it returns "An array of User or Page objects representing the people or Pages that liked the object".

The first link says /{page-id}/likes will return outgoing likes for a page, whereas the second link suggests the same endpoint will return incoming likes. Testing it out in the Graph Explorer indicates that the 2nd link is true, which makes me wonder how I can access the outgoing likes described by the first link, as that is what I am interested in.

Am I misunderstanding something here? Thanks!

答: This is a bug in the Facebook documentation: https://developers.facebook.com/bugs/638061899718019/</p>


问:
Dijkstra's Algorithm modification
Let G (V, E) be a weighted, directed graph with non negative weight function
W : E -> {0, 1, 2... W } for some non negative integer W . How to modify Dijkstra’s algorithm to compute the shortest paths from a given source vertex s in O(V W + E) time.

答:
Standard Dijkstra's uses a priority queue and can handle floating-point values. This allows all the weights to differ from each other and implies no upper bound.

But now you have integer weights and an upper bound: given these additional constraints you should be able to build a faster algorithm. And, indeed, you can, by using buckets (one for each weight) to store the nodes.

In full:

Create buckets labeled 0, 1, 2, 3, ..., W(V-1) where W is the maximum weight and V is the number of nodes. Bucket k will contain all nodes labeled with distance k. Each bucket can be represented by a vector or list of nodes.

Buckets 0, 1, 2, ..., WV are checked sequentially until the first non-empty bucket is found. The nodes in this bucket are at the frontier.

Each node in this bucket is labeled with its true distance and then deleted from the bucket.

Steps (2-4) are now repeated (though begin scanning in 2 at the bucket you just emptied) until all buckets are empty.

You need WV buckets to account for the degenerate case in which W=1 but the graph is a line. In this case, the farthest apart two nodes can be is W(V-1).

A more complete explanation is available here.

Title: Dijkstra's Algorithm modification


问:
How can I craft a csv from multi level json in powershell?
I am trying to parse a JSON response that looks like

```<code>{
"Objects":  [
                     {
                         "Name":  "FirstName",
                         "Type":  "XXXX",
                     },
                     {
                         "Name":  "SecondName",
                         "Type":  "YYYY",
                     },
                     {
                     "Name":  "ThirdName",
                         "Type":  "ZZZZ",
                     },
            ],
 "TotalCount":  127
 }
</code>```

I want a CSV formatted like

```<code>"Name","Type"
"FirstName","XXXX"
"SecondName","YYYY"
</code>```

and so on.
I tried creating a PSCustomObject and using Select-Object with it to generate the CSV but it does not give me the desired output.
My code:

```<code>$report=$null
foreach($obj in $json){
$item=$obj | ConvertFrom-Json
$report=[pscustomobject]@{
Name=($item.Objects.Name | Out-String).Trim()
Type=($item.Objects.Type | Out-String).Trim()
}
$report | Select-Object Name,Type | Export-Csv "PATH"`
</code>```

Gives me CSV that looks like:

```<code>"Name","Type"
"FirstName
 SecondName
 ThirdName",
"XXXX
 YYYY
 ZZZZ"
</code>```

答:
if you really want the total count in the csv as well, here is one thing you could do:</p>

```<code>$psobjarray = ($json | convertfrom-json)
$psobjarray.objects | Select-Object Name,Type | Export-Csv $Path
"Total Count: $($psobjarray.totalcount)" | out-file $Path -append
</code>```

Body:
I am trying to parse a JSON response that looks like

{
"Objects":  [
                     {
                         "Name":  "FirstName",
                         "Type":  "XXXX",
                     },
                     {
                         "Name":  "SecondName",
                         "Type":  "YYYY",
                     },
                     {
                     "Name":  "ThirdName",
                         "Type":  "ZZZZ",
                     },
            ],
 "TotalCount":  127
 }

I want a CSV formatted like

"Name","Type"
"FirstName","XXXX"
"SecondName","YYYY"

and so on.
I tried creating a PSCustomObject and using Select-Object with it to generate the CSV but it does not give me the desired output.
My code:

$report=$null
foreach($obj in $json){
$item=$obj | ConvertFrom-Json
$report=[pscustomobject]@{
Name=($item.Objects.Name | Out-String).Trim()
Type=($item.Objects.Type | Out-String).Trim()
}
$report | Select-Object Name,Type | Export-Csv "PATH"`

Gives me CSV that looks like:

"Name","Type"
"FirstName
 SecondName
 ThirdName",
"XXXX
 YYYY
 ZZZZ"

Body:
if you really want the total count in the csv as well, here is one thing you could do:

$psobjarray = ($json | convertfrom-json)
$psobjarray.objects | Select-Object Name,Type | Export-Csv $Path
"Total Count: $($psobjarray.totalcount)" | out-file $Path -append


问:
URL openConnection by mobild data throws ConnectException when Device sleep
I create an HttpURLConnection in a Thread or AsyncTask and it works fine.
But when the Device is in sleep mode, (Display is Off...) then I get an
Exception by open the Connection -> java.net.ConnectException: Connection refused.

My idea is to wake up the Device with the PowerManager.PARTIAL_WAKE_LOCK, but that doesn't help.

The other defines from PowerManager for example ACQUIRE_CAUSES_WAKEUP are deprecated.

What can I do to create a successful connection?

The code:

```<code>URL url = new URL("myUrl...");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
int response = urlConnection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
     // to do some work
 }
</code>```

答: I suggest you to use OkHttp. It is better than HttpClient.</p>

Body:
I create an HttpURLConnection in a Thread or AsyncTask and it works fine.
But when the Device is in sleep mode, (Display is Off...) then I get an
Exception by open the Connection -> java.net.ConnectException: Connection refused.

My idea is to wake up the Device with the PowerManager.PARTIAL_WAKE_LOCK, but that doesn't help.

The other defines from PowerManager for example ACQUIRE_CAUSES_WAKEUP are deprecated.

What can I do to create a successful connection?

The code:

URL url = new URL("myUrl...");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
int response = urlConnection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
     // to do some work
 }


问:
Why do we use composer,nodejs and gulp when using laravel?
What is the real purpose of installing composer and node.js, and the npm install?</p>

答:
composer is the dependency manager for php laravel framework. Look at this link for more infomation on this: https://www.tutorialspoint.com/laravel/laravel_installation.htm

Node js : like @ceejayoz said, it is not mandatory for laravel but may be needed to hook up some external tools.

If by non install you meant npm install, npm is the package manager for node js (npm stands for nodejs package manager). This is a tool that lets you install several packages that work with nodejs. According to the npm website, npm lets you discover and re-use over 470,000 free code packages in the npm Registry.


问:
AspectJ: matching GenericServlet.init() call of an annotated subclass instance
I'm deriving from GenericServlet and annotate that derived class with @Tx. I want to use the GenericServlet.init() method call during servlet startup to trigger some initialization outside the servlet via aop. The first two lines don't match at all, the third one matches obviously all servlets, and the fourth matches all servlets despite using the annotation to specify the target.

```<code>@Before("@this(com.github.jjYBdx4IL.aop.tx.Tx)
    && execution(* javax.servlet.GenericServlet+.init()) && this(foo)")
@Before("@target(com.github.jjYBdx4IL.aop.tx.Tx)
    && execution(* javax.servlet.GenericServlet+.init()) && this(foo)")

@Before("execution(* javax.servlet.GenericServlet+.init()) && this(foo)")
@Before("target(@com.github.jjYBdx4IL.aop.tx.Tx Object)
    && execution(* javax.servlet.GenericServlet+.init()) && this(foo)")
</code>```

This first line works if I replace GenericServlet+.init() with GenericServlet.init(..)

```<code>@Before("@this(com.github.jjYBdx4IL.aop.tx.Tx)
    && execution(* javax.servlet.GenericServlet.init(..)) && this(foo)")
</code>```

which is strange because, using a debugger, GenericServlet.init() definitely gets called from GenericServlet.init(ServletConfig)...

Can someone please clarify, what's going on here? I would expect that the first line should do the trick, but it doesn't.

My best guess is that it has to do with the separation of class loaders used by the Jetty instance itself and the webapp's class loaders... I managed to make the following at least weave the init() method (according to maspectj's debug output):

```<code>@After("@this(com.github.jjYBdx4IL.aop.tx.Tx
    && target(javax.servlet.GenericServlet+)
    && execution(* init()) && this(foo)")
</code>```

but it does not trigger.

Update

I traced the problem down to this: URLClassLoader loads Annotation as com.sun.$Proxy$27

Basically, foo.getClass().isAnnotationPresent(Tx.class) always returns false. Now the question is: what is this nonsense? And how can I disable it?

答:
Turns out those com.sun.proxy.$Proxy instances are being used by the classloader when a parent classloader already defined the same class/annotation. Because I want to weave system classes like javax.servlet.GenericServlet, I need to load my annotations/aspects using the parent classloader, ie with Jetty itself. Setting the annotation-containing dependency for my webapp to the maven scope "provided" solved the issue.

"Solved" means: the proxy for the annotation is still there, but calls to "isAnnotationPresent" actually return true and not false now, which was the reason behind AspectJ's failure to identify the annotation pointcuts at runtime.

Body:
I'm deriving from GenericServlet and annotate that derived class with @Tx. I want to use the GenericServlet.init() method call during servlet startup to trigger some initialization outside the servlet via aop. The first two lines don't match at all, the third one matches obviously all servlets, and the fourth matches all servlets despite using the annotation to specify the target.

@Before("@this(com.github.jjYBdx4IL.aop.tx.Tx)
    && execution(* javax.servlet.GenericServlet+.init()) && this(foo)")
@Before("@target(com.github.jjYBdx4IL.aop.tx.Tx)
    && execution(* javax.servlet.GenericServlet+.init()) && this(foo)")

@Before("execution(* javax.servlet.GenericServlet+.init()) && this(foo)")
@Before("target(@com.github.jjYBdx4IL.aop.tx.Tx Object)
    && execution(* javax.servlet.GenericServlet+.init()) && this(foo)")

This first line works if I replace GenericServlet+.init() with GenericServlet.init(..)

@Before("@this(com.github.jjYBdx4IL.aop.tx.Tx)
    && execution(* javax.servlet.GenericServlet.init(..)) && this(foo)")

which is strange because, using a debugger, GenericServlet.init() definitely gets called from GenericServlet.init(ServletConfig)...

Can someone please clarify, what's going on here? I would expect that the first line should do the trick, but it doesn't.

My best guess is that it has to do with the separation of class loaders used by the Jetty instance itself and the webapp's class loaders... I managed to make the following at least weave the init() method (according to maspectj's debug output):

@After("@this(com.github.jjYBdx4IL.aop.tx.Tx
    && target(javax.servlet.GenericServlet+)
    && execution(* init()) && this(foo)")

but it does not trigger.

Update

I traced the problem down to this: URLClassLoader loads Annotation as com.sun.$Proxy$27

Basically, foo.getClass().isAnnotationPresent(Tx.class) always returns false. Now the question is: what is this nonsense? And how can I disable it?


问:
angular2, how to return object who have the max value of an attribute in an array of objects
i'am working on an angular2 app , i have an array of objects and i want to return the object how has max value of an attribute (in my case the object how have more likes) how to do that in typescript

import {Player} from './player';
export const PlayersData : Player[] = [
{id:1,name:"Marc-andré Ter stegen",number:"1",post:"Goalkeeper",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/150720.jpg"},
{id:2,name:"Gerrad Piqué",number:"3",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/27798.jpg"},
{id:3,name:"Ivan Rakitić",number:"4",post:"Midfielder",goals:0,assist:0,likes:7,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/35308.jpg"},
{id:4,name:"Sergie Buskquets",number:"5",post:"Midfielder",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/124973.jpg"},
{id:5,name:"Denis Suarez",number:"6",post:"Midfielder",goals:20,assist:20,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/200516.jpg"},
{id:6,name:"Arda Turan",number:"7",post:"Midfielder",goals:0,assist:10,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/30203.jpg"},
{id:7,name:"Andres Iniesta",number:"8",post:"Midfielder",goals:10,assist:20,likes:0,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/5057.jpg"},
{id:8,name:"Luis Suarez",number:"9",post:"Forward",goals:0,assist:0,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/43635.jpg"},
{id:9,name:"Lionel Messi",number:"10",post:"Forward",goals:0,assist:0,likes:40,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/26622.jpg"},
{id:10,name:"Neymar Jr",number:"11",post:"Forward",goals:30,assist:10,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/142105.jpg"},
{id:11,name:"Javier Mascherano",number:"14",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/22185.jpg"},
{id:12,name:"Jordi Alba",number:"18",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/125417.jpg"},
{id:13,name:"Sergio Roberto",number:"20",post:"Midfielder",goals:0,assist:0,likes:20,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/171905.jpg"},
{id:14,name:"Samuel Umtiti",number:"23",post:"Defender",goals:0,assist:0,likes:9,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/170711.jpg"}

];```
</div>
</div>
</p>

<p>this is what i tried in typescript </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export class DashboardComponent implements OnInit {
  players : Player[] = [];
 bestPlayer:Player;
  constructor(private playerService : PlayerService) { }
 max =0;
 bestPlayer = this.players[0];
  ngOnInit() {
   this.playerService.getPlayers()
   .then(players=> this.players = players);
   for (player of players)
      if (player.likes>max) {
        max => player.likes;
        bestPlayer => player;
      }
  }

}</code>```

答:
As Igor comment, you should read duplicate topic first.
I also give suggest for your other stuck, get object contain max value.
Please read other topic for clear answer Finding the max value of an attribute in an array of objects</p>

```<code>export class DashboardComponent implements OnInit {
  players : Player[] = [];
  bestPlayer:Player;

  constructor(private playerService : PlayerService) { }

  max =0;

  ngOnInit() {
    this.playerService.getPlayers()
    .then(players=> {
         this.players = players;
         let maxValue = Math.max.apply(Math,players.map(function(o){return o.likes;}));
         this.bestPlayer = players.filter(function(o) { return o.likes === maxValue; })[0];
     });
  }
}
</code>```

Body:
i'am working on an angular2 app , i have an array of objects and i want to return the object how has max value of an attribute (in my case the object how have more likes) how to do that in typescript

import {Player} from './player';
export const PlayersData : Player[] = [
{id:1,name:"Marc-andré Ter stegen",number:"1",post:"Goalkeeper",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/150720.jpg"},
{id:2,name:"Gerrad Piqué",number:"3",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/27798.jpg"},
{id:3,name:"Ivan Rakitić",number:"4",post:"Midfielder",goals:0,assist:0,likes:7,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/35308.jpg"},
{id:4,name:"Sergie Buskquets",number:"5",post:"Midfielder",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/124973.jpg"},
{id:5,name:"Denis Suarez",number:"6",post:"Midfielder",goals:20,assist:20,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/200516.jpg"},
{id:6,name:"Arda Turan",number:"7",post:"Midfielder",goals:0,assist:10,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/30203.jpg"},
{id:7,name:"Andres Iniesta",number:"8",post:"Midfielder",goals:10,assist:20,likes:0,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/5057.jpg"},
{id:8,name:"Luis Suarez",number:"9",post:"Forward",goals:0,assist:0,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/43635.jpg"},
{id:9,name:"Lionel Messi",number:"10",post:"Forward",goals:0,assist:0,likes:40,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/26622.jpg"},
{id:10,name:"Neymar Jr",number:"11",post:"Forward",goals:30,assist:10,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/142105.jpg"},
{id:11,name:"Javier Mascherano",number:"14",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/22185.jpg"},
{id:12,name:"Jordi Alba",number:"18",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/125417.jpg"},
{id:13,name:"Sergio Roberto",number:"20",post:"Midfielder",goals:0,assist:0,likes:20,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/171905.jpg"},
{id:14,name:"Samuel Umtiti",number:"23",post:"Defender",goals:0,assist:0,likes:9,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/170711.jpg"}

];

this is what i tried in typescript

export class DashboardComponent implements OnInit {
  players : Player[] = [];
 bestPlayer:Player;
  constructor(private playerService : PlayerService) { }
 max =0;
 bestPlayer = this.players[0];
  ngOnInit() {
   this.playerService.getPlayers()
   .then(players=> this.players = players);
   for (player of players)
      if (player.likes>max) {
        max => player.likes;
        bestPlayer => player;
      }
  }

}

Body:
As Igor comment, you should read duplicate topic first.
I also give suggest for your other stuck, get object contain max value.
Please read other topic for clear answer Finding the max value of an attribute in an array of objects

export class DashboardComponent implements OnInit {
  players : Player[] = [];
  bestPlayer:Player;

  constructor(private playerService : PlayerService) { }

  max =0;

  ngOnInit() {
    this.playerService.getPlayers()
    .then(players=> {
         this.players = players;
         let maxValue = Math.max.apply(Math,players.map(function(o){return o.likes;}));
         this.bestPlayer = players.filter(function(o) { return o.likes === maxValue; })[0];
     });
  }
}


问:
DocuSign API - Creating an envelope with a Document that has an Approve button
I am creating a draft envelope with a TXT document - which needs to display an Approve button to allow the signer to sign without placing a signature/initials on the document itself. Unfortunately I can't get the Approve button to show on the document, where have I gone wrong?

Here is the Request XML:

```<code><ns1:envelopeDefinition xmlns:ns1="http://www.docusign.com/restapi">
    <ns1:emailSubject>Test from iPaaS</ns1:emailSubject>
        <ns1:documents>
            <ns1:document>
                <ns1:name>TestDocument</ns1:name>
                <ns1:documentId>1</ns1:documentId>
                <ns1:documentBase64><Base64BytesHere></ns1:documentBase64>
                <ns1:fileExtension>txt</ns1:fileExtension>
            </ns1:document>
        </ns1:documents>
        <ns1:recipients>
            <ns1:signers>
                <ns1:signer>
                    <ns1:routingOrder>1</ns1:routingOrder>
                    <ns1:recipientId>1</ns1:recipientId>
                    <ns1:name>John Smith</ns1:name>
                    <ns1:email>nobody@nobody.com</ns1:email>
                </ns1:signer>
            </ns1:signers>
        </ns1:recipients>
        <ns1:tabs>
            <ns1:approveTabs>
                <ns1:approve>
                    <anchorCaseSensitive />
                    <anchorHorizontalAlignment />
                    <anchorIgnoreIfNotPresent />
                    <anchorMatchWholeWord />
                    <anchorString />
                    <anchorUnits />
                    <anchorXOffset />
                    <anchorYOffset />
                    <conditionalParentLabel />
                    <conditionalParentValue />
                    <customTabId />
                    <documentId>1</documentId>
                    <mergeField />
                    <pageNumber>1</pageNumber>
                    <recipientId>1</recipientId>
                    <tabId />
                    <tabOrder />
                    <templateLocked />
                    <templateRequired />
                    <xPosition>100</xPosition>
                    <yPosition>100</yPosition>
                    <bold />
                    <font />
                    <fontColor />
                    <fontSize />
                    <italic />
                    <tabLabel />
                    <underline />
                    <buttonText />
                    <height>30</height>
                    <width>50</width>
                </ns1:approve>
            </ns1:approveTabs>
        </ns1:tabs>
</ns1:envelopeDefinition>
</code>```

Essentially I am looking for something that looks like the attached screenshot

答:
The <tabs> node should be inside the <signer> node. The following example should work.

```<code><ns1:envelopeDefinition xmlns:ns1="http://www.docusign.com/restapi">
    <ns1:emailSubject>Test from iPaaS</ns1:emailSubject>
        <ns1:documents>
            <ns1:document>
                <ns1:name>TestDocument</ns1:name>
                <ns1:documentId>1</ns1:documentId>
                <ns1:fileExtension>txt</ns1:fileExtension>
                <ns1:documentBase64>RG9jIFRXTyBUV08gVFdP</ns1:documentBase64>
                <ns1:fileExtension>txt</ns1:fileExtension>
            </ns1:document>
        </ns1:documents>
        <ns1:recipients>
            <ns1:signers>
                <ns1:signer>
                    <ns1:routingOrder>1</ns1:routingOrder>
                    <ns1:recipientId>1</ns1:recipientId>
                    <ns1:name>John Smith</ns1:name>
                    <ns1:email>johnsmith@acme.com</ns1:email>
                    <ns1:tabs>
                        <ns1:approveTabs>
                            <ns1:approve>
                                <documentId>1</documentId>
                                <pageNumber>1</pageNumber>
                                <xPosition>100</xPosition>
                                <yPosition>100</yPosition>
                                <height>30</height>
                                <width>50</width>
                            </ns1:approve>
                        </ns1:approveTabs>
                    </ns1:tabs>
                </ns1:signer>
            </ns1:signers>
        </ns1:recipients>
</ns1:envelopeDefinition>
</code>```

Body:
I am creating a draft envelope with a TXT document - which needs to display an Approve button to allow the signer to sign without placing a signature/initials on the document itself. Unfortunately I can't get the Approve button to show on the document, where have I gone wrong?

Here is the Request XML:

<ns1:envelopeDefinition xmlns:ns1="http://www.docusign.com/restapi">
    <ns1:emailSubject>Test from iPaaS</ns1:emailSubject>
        <ns1:documents>
            <ns1:document>
                <ns1:name>TestDocument</ns1:name>
                <ns1:documentId>1</ns1:documentId>
                <ns1:documentBase64><Base64BytesHere></ns1:documentBase64>
                <ns1:fileExtension>txt</ns1:fileExtension>
            </ns1:document>
        </ns1:documents>
        <ns1:recipients>
            <ns1:signers>
                <ns1:signer>
                    <ns1:routingOrder>1</ns1:routingOrder>
                    <ns1:recipientId>1</ns1:recipientId>
                    <ns1:name>John Smith</ns1:name>
                    <ns1:email>nobody@nobody.com</ns1:email>
                </ns1:signer>
            </ns1:signers>
        </ns1:recipients>
        <ns1:tabs>
            <ns1:approveTabs>
                <ns1:approve>
                    <anchorCaseSensitive />
                    <anchorHorizontalAlignment />
                    <anchorIgnoreIfNotPresent />
                    <anchorMatchWholeWord />
                    <anchorString />
                    <anchorUnits />
                    <anchorXOffset />
                    <anchorYOffset />
                    <conditionalParentLabel />
                    <conditionalParentValue />
                    <customTabId />
                    <documentId>1</documentId>
                    <mergeField />
                    <pageNumber>1</pageNumber>
                    <recipientId>1</recipientId>
                    <tabId />
                    <tabOrder />
                    <templateLocked />
                    <templateRequired />
                    <xPosition>100</xPosition>
                    <yPosition>100</yPosition>
                    <bold />

                    <fontColor />
                    <fontSize />
                    <italic />
                    <tabLabel />
                    <underline />
                    <buttonText />
                    <height>30</height>
                    <width>50</width>
                </ns1:approve>
            </ns1:approveTabs>
        </ns1:tabs>
</ns1:envelopeDefinition>

Essentially I am looking for something that looks like the attached screenshot

Body:
The <tabs> node should be inside the <signer> node. The following example should work.

<ns1:envelopeDefinition xmlns:ns1="http://www.docusign.com/restapi">
    <ns1:emailSubject>Test from iPaaS</ns1:emailSubject>
        <ns1:documents>
            <ns1:document>
                <ns1:name>TestDocument</ns1:name>
                <ns1:documentId>1</ns1:documentId>
                <ns1:fileExtension>txt</ns1:fileExtension>
                <ns1:documentBase64>RG9jIFRXTyBUV08gVFdP</ns1:documentBase64>
                <ns1:fileExtension>txt</ns1:fileExtension>
            </ns1:document>
        </ns1:documents>
        <ns1:recipients>
            <ns1:signers>
                <ns1:signer>
                    <ns1:routingOrder>1</ns1:routingOrder>
                    <ns1:recipientId>1</ns1:recipientId>
                    <ns1:name>John Smith</ns1:name>
                    <ns1:email>johnsmith@acme.com</ns1:email>
                    <ns1:tabs>
                        <ns1:approveTabs>
                            <ns1:approve>
                                <documentId>1</documentId>
                                <pageNumber>1</pageNumber>
                                <xPosition>100</xPosition>
                                <yPosition>100</yPosition>
                                <height>30</height>
                                <width>50</width>
                            </ns1:approve>
                        </ns1:approveTabs>
                    </ns1:tabs>
                </ns1:signer>
            </ns1:signers>
        </ns1:recipients>
</ns1:envelopeDefinition>