问:
Laravel - Delete data record from Database
I want to delete record Photo and Photo_list from Database but give me error

This is my Code in Controller

```<code>public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::select('photo','photo_list')->delete($product->id);

    return redirect(route('stores.index'));

}
</code>```

答:
```<code>public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::Where('id','=',$product->id)->delete();

    return redirect(route('stores.index'));

}
</code>```

Or you can directly do this

```<code>Product::find($id)->delete();
</code>```

Body:
I want to delete record Photo and Photo_list from Database but give me error

This is my Code in Controller

public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::select('photo','photo_list')->delete($product->id);

    return redirect(route('stores.index'));

}

Body:
public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::Where('id','=',$product->id)->delete();

    return redirect(route('stores.index'));

}

Or you can directly do this

Product::find($id)->delete();


来源: stackexchange

问:
jquery - Why do these appended divs ignore their css?
I'm appending some div's with jquery.
And gave them size and color with css.
However they don't seem to pick up on the css?
And how can put some of the divs inside others

Here is my code
http://jsfiddle.net/Eqxzz/

答: you need to assign your CSS at a class level. see my fork</p>

ContentLicense: CC BY-SA 2.5


问:
JVM heap memory
Do we need to mandatory specify JVM heap memory arguments in bat file while calling .jar file?

For example:
start /b "" "jre7\bin\javaw.exe" -Xmx1G -jar XYZ.jar

I have the scenario that in some machine when I explicitly specify the arguments(as above) then Java fatal exception is generated!

enter image description here

Error Message:
"Java virtual machine Launcher:
Error: Could not create Java virtual machine.
Error: A fatal exception has occurred. Program will exit."

But when I remove the arguments then no error is reported.
Please anyone let me know. Thank you.

答: You need to update the windows environment variables _JAVA_OPTIONS and set Xmx1024M there. Once done you can start your JVM just fine.</p>

ContentLicense: CC BY-SA 3.0

Title: JVM heap memory


问:
Are there any side-effects on publishing at play store if I use the third-party security reinforce service on apk files？
My Android Apk sometimes is cracked and decompiled.Then they change my app's package name and add ads or something else bad.I try to use some third-party security reinforce and encryption techniques to prevent being cracked and packaged twice. I want to know if it will have any side-effects on publishing an app in play store.</p>

答:
The play store , very recently  now provides much more robust and tested code security features from play store. It is recommended to use that. Check the link below.

https://support.google.com/googleplay/android-developer/answer/7384423


问:
delete tableView cells
I have a table view controller and I have embedded a left bar edit item button.

```<code> override func viewDidLoad() {
        super.viewDidLoad()
navigationItem.leftBarButtonItem = self.editButtonItem
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if (editingStyle == UITableViewCellEditingStyle.delete) {

            MessageTableView.deleteRows(at: [indexPath], with: .fade)
        }

}
</code>```

When I click the edit button, a circle pops up in order to place a check mark in it

But when I click the edit button I want the red minus sign to appear

But every tutorial I follow, I get the first picture and I don't want that.

答:
```<code>var arrayDays:[Student] = []

    @IBOutlet var tableViewForStudents: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let std1 = Student(name: "First", rollNo: 1, address: "this is \\n address of \\n student 1",image:"demo.png")
        let std2 = Student(name: "Two", rollNo: 2, address: "this is \\n address of \\n student 2",image:"demo.png")
        let std3 = Student(name: "Three", rollNo: 3, address: "this is \\n address of \\n student 3",image:"demo.png")
        let std4 = Student(name: "Four", rollNo: 4, address: "this is \\n address of \\n student 4",image:"demo.png")
        let std5 = Student(name: "Five", rollNo: 5, address: "this is \\n address of \\n student 5",image:"demo.png")
        let std6 = Student(name: "Six", rollNo: 6, address: "this is \\n address of \\n student 6",image:"demo.png")

        arrayDays.append(std1)
        arrayDays.append(std2)
        arrayDays.append(std3)
        arrayDays.append(std4)
        arrayDays.append(std5)
        arrayDays.append(std6)

    }
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == .delete {
            arrayDays.remove(at: indexPath.row)

            tableView.deleteRows(at: [indexPath], with: .left)
        }
</code>```

import UIKit

```<code>class Student: NSObject {

    var strStudentName:String!
    var strStrudentRollNo:Int!
    var strStudentAddress:String!
    var imageName:String!

    init(name:String, rollNo:Int, address:String,image:String) {

        strStudentName = name
        strStrudentRollNo = rollNo
        strStudentAddress = address
        imageName = image
    }
    }
</code>```

Title: delete tableView cells

Body:
I have a table view controller and I have embedded a left bar edit item button.

 override func viewDidLoad() {
        super.viewDidLoad()
navigationItem.leftBarButtonItem = self.editButtonItem
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if (editingStyle == UITableViewCellEditingStyle.delete) {

            MessageTableView.deleteRows(at: [indexPath], with: .fade)
        }

}

When I click the edit button, a circle pops up in order to place a check mark in it

But when I click the edit button I want the red minus sign to appear

But every tutorial I follow, I get the first picture and I don't want that.

Body:
var arrayDays:[Student] = []

    @IBOutlet var tableViewForStudents: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let std1 = Student(name: "First", rollNo: 1, address: "this is \\n address of \\n student 1",image:"demo.png")
        let std2 = Student(name: "Two", rollNo: 2, address: "this is \\n address of \\n student 2",image:"demo.png")
        let std3 = Student(name: "Three", rollNo: 3, address: "this is \\n address of \\n student 3",image:"demo.png")
        let std4 = Student(name: "Four", rollNo: 4, address: "this is \\n address of \\n student 4",image:"demo.png")
        let std5 = Student(name: "Five", rollNo: 5, address: "this is \\n address of \\n student 5",image:"demo.png")
        let std6 = Student(name: "Six", rollNo: 6, address: "this is \\n address of \\n student 6",image:"demo.png")

        arrayDays.append(std1)
        arrayDays.append(std2)
        arrayDays.append(std3)
        arrayDays.append(std4)
        arrayDays.append(std5)
        arrayDays.append(std6)

    }
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == .delete {
            arrayDays.remove(at: indexPath.row)

            tableView.deleteRows(at: [indexPath], with: .left)
        }

import UIKit

class Student: NSObject {

    var strStudentName:String!
    var strStrudentRollNo:Int!
    var strStudentAddress:String!
    var imageName:String!

    init(name:String, rollNo:Int, address:String,image:String) {

        strStudentName = name
        strStrudentRollNo = rollNo
        strStudentAddress = address
        imageName = image
    }
    }


问:
vbscript use regex to rename files recursively
I am trying to write a vbscript to recursively rename any files in a folder.
My final plan will be to copy the folder to a zip file, but it fails if the files have any characters apart from

e.g (a-z) or (0-9) or "_", " ".

For example, if the file has characters other than English in the file name, it will not allow me to copy the file to the zip. I have looked at various websites and could have an answer in batch as well.

I am quite new to regex, having started learning about it yesterday.

The error I am getting is "File already Exists".

My script:

```<code>Const ForReading = 1
Const ForWriting = 2
Const ForAppend  = 8
Const OverwriteExisting = TRUE

scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)

Set objFSO = CreateObject("Scripting.FileSystemObject")

objStartFolder = scriptdir & "\Fragments"

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files

Set objRegEx = CreateObject("VBScript.RegExp")

objRegEx.Global = True

objRegEx.Pattern = "[^A-Za-z_0-9-\n\r]"

For Each objFile in colFiles

If regEx.test(objFile.Name) = true Then

FirstlevelNewFileName = objRegEx.Replace(objFile.Name, "_")

objFSO.MoveFile objFile, FirstlevelNewFileName

End If
Next

ShowSubfolders objFSO.GetFolder(objStartFolder)

Sub ShowSubFolders(Folder)

For Each Subfolder in Folder.SubFolders

Set objFolder = objFSO.GetFolder(Subfolder.Path)

Set colFiles = objFolder.Files

For Each objFile in colFiles

        NewFileName = objRegEx.Replace(objFile.Name, "_")

objFSO.MoveFile objFile.Path, NewFileName

    Next

    ShowSubFolders Subfolder

Next

End Sub
</code>```

Thank you for your time!

答:
I think your code have got issues with the Movefile statements(when you are trying to rename files). You are providing only the file name as the Destination parameter. You should provide full path there. I have made changes as shown below.

NOTE: I did not change any of the Logic.

```<code>Const ForReading = 1
Const ForWriting = 2
Const ForAppend  = 8
Const OverwriteExisting = TRUE

scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)

Set objFSO = CreateObject("Scripting.FileSystemObject")

objStartFolder = scriptdir & "\Fragments"

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files

Set objRegEx = new Regexp

objRegEx.Global = True

objRegEx.Pattern = "[^\w.]"     'looks for non-word characters and also not .(for the extension)

For Each objFile in colFiles

    If objRegEx.test(objFile.Name) = true Then                  'Changed this. You had only used the variable RegEx here instead of objRegEx

        FirstlevelNewFileName = objRegEx.Replace(objFile.Name, "_")

        objFile.Move objStartFolder&"\"&FirstlevelNewFileName    'Provided the full file path here. Used the File Object itself

EndIf
Next

ShowSubfolders objFSO.GetFolder(objStartFolder)

Sub ShowSubFolders(Folder)

For Each Subfolder in Folder.SubFolders

    Set objFolder = objFSO.GetFolder(Subfolder.Path)

    Set colFiles = objFolder.Files

    For Each objFile in colFiles

        NewFileName = objRegEx.Replace(objFile.Name, "_")

        objFile.Move Subfolder.Path&"\"&NewFileName       'passed the full path here again

    Next

    ShowSubFolders Subfolder

Next

End Sub
</code>```

Body:
I am trying to write a vbscript to recursively rename any files in a folder.
My final plan will be to copy the folder to a zip file, but it fails if the files have any characters apart from

e.g (a-z) or (0-9) or "_", " ".

For example, if the file has characters other than English in the file name, it will not allow me to copy the file to the zip. I have looked at various websites and could have an answer in batch as well.

I am quite new to regex, having started learning about it yesterday.

The error I am getting is "File already Exists".

My script:

Const ForReading = 1
Const ForWriting = 2
Const ForAppend  = 8
Const OverwriteExisting = TRUE

scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)

Set objFSO = CreateObject("Scripting.FileSystemObject")

objStartFolder = scriptdir & "\Fragments"

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files

Set objRegEx = CreateObject("VBScript.RegExp")

objRegEx.Global = True

objRegEx.Pattern = "[^A-Za-z_0-9-\n\r]"

For Each objFile in colFiles

If regEx.test(objFile.Name) = true Then

FirstlevelNewFileName = objRegEx.Replace(objFile.Name, "_")

objFSO.MoveFile objFile, FirstlevelNewFileName

End If
Next

ShowSubfolders objFSO.GetFolder(objStartFolder)

Sub ShowSubFolders(Folder)

For Each Subfolder in Folder.SubFolders

Set objFolder = objFSO.GetFolder(Subfolder.Path)

Set colFiles = objFolder.Files

For Each objFile in colFiles

        NewFileName = objRegEx.Replace(objFile.Name, "_")

objFSO.MoveFile objFile.Path, NewFileName

    Next

    ShowSubFolders Subfolder

Next

End Sub

Thank you for your time!

Body:
I think your code have got issues with the Movefile statements(when you are trying to rename files). You are providing only the file name as the Destination parameter. You should provide full path there. I have made changes as shown below.

NOTE: I did not change any of the Logic.

Const ForReading = 1
Const ForWriting = 2
Const ForAppend  = 8
Const OverwriteExisting = TRUE

scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)

Set objFSO = CreateObject("Scripting.FileSystemObject")

objStartFolder = scriptdir & "\Fragments"

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files

Set objRegEx = new Regexp

objRegEx.Global = True

objRegEx.Pattern = "[^\w.]"     'looks for non-word characters and also not .(for the extension)

For Each objFile in colFiles

    If objRegEx.test(objFile.Name) = true Then                  'Changed this. You had only used the variable RegEx here instead of objRegEx

        FirstlevelNewFileName = objRegEx.Replace(objFile.Name, "_")

        objFile.Move objStartFolder&"\"&FirstlevelNewFileName    'Provided the full file path here. Used the File Object itself

EndIf
Next

ShowSubfolders objFSO.GetFolder(objStartFolder)

Sub ShowSubFolders(Folder)

For Each Subfolder in Folder.SubFolders

    Set objFolder = objFSO.GetFolder(Subfolder.Path)

    Set colFiles = objFolder.Files

    For Each objFile in colFiles

        NewFileName = objRegEx.Replace(objFile.Name, "_")

        objFile.Move Subfolder.Path&"\"&NewFileName       'passed the full path here again

    Next

    ShowSubFolders Subfolder

Next

End Sub


问:
Extract Integers, Decimals, and Fractional Numbers from sentence of a string
How to extract the array of string with Integers, Decimals, and Fractions from a sentence?
Please find below input and output in iOS Swift.

Input :  array of String["width 32.3", "Length 61 1/4", "height 23 4/5", "measure 5.23"]

Output : ["32.3", "61 1/4", "23 4/5", "5.23"]

答:
Another approach with Regular Expression

```<code>let array = ["width 32.3", "Length 61 1/4", "height 23 4/5", "measure 5.23"]
let pattern = "\\d+[\\s.][\\d/]+"

let regex = try! NSRegularExpression(pattern: pattern)
var result = [String]()

for item in array {
    if let match = regex.firstMatch(in: item, range: NSRange(location:0, length: item.characters.count)) {
        result.append((item as NSString).substring(with: match.range))
    }
}

print(result)
</code>```

The pattern searches for

one or more digits

followed by a whitespace character or dot

followed by one or more digits or slashes

Body:
Another approach with Regular Expression

let array = ["width 32.3", "Length 61 1/4", "height 23 4/5", "measure 5.23"]
let pattern = "\\d+[\\s.][\\d/]+"

let regex = try! NSRegularExpression(pattern: pattern)
var result = [String]()

for item in array {
    if let match = regex.firstMatch(in: item, range: NSRange(location:0, length: item.characters.count)) {
        result.append((item as NSString).substring(with: match.range))
    }
}

print(result)

The pattern searches for

one or more digits

followed by a whitespace character or dot

followed by one or more digits or slashes


问:
Docker failed to initialize
I am trying to install the Docker community edition for windows, the installation was successful and it asked me to logout and login again and I did same. But when I tried to start the docker it says -

A task was canceled.
  at Docker.Core.Pipe.NamedPipeClient.Send(String action, Object[] parameters)
     at Docker.WPF.BackendClient.Version()
     at Docker.Program.Run(IReadOnlyCollection`1 args)

It is giving me below options -

Any help or pointers will really helpful.

答:
I did finally solve the problem and the solution was to restart the machine, which was not properly documented in the official site. As per the site -

Install

Double-click InstallDocker.msi to run the installer.

When the installation finishes, Docker starts automatically. The whale in the notification area indicates that Docker is running, and accessible from a terminal.
Run

Open a command-line terminal like PowerShell, and try out some Docker commands!

Run docker version to check the version.

Run docker run hello-world to verify that Docker can pull and run images.

However it needs a restart to enable virtualization, simply logging off and login again did not work for me as directed by the wizard. Most of the problems related to docker gets resolved by restarting the docker some of the common problems and the resolutions are as follows

Docker not starting in windows or not working properly

Change it to Linux containers

Make sure that docker is installed on machine

Make sure virtualization is enabled and docker starts successfully

Title: Docker failed to initialize

ContentLicense: CC BY-SA 4.0


问:
Recipe compile error - Chef
I have 2 recipes in my cookbook namely - Get.rb and Post.rb.

Get.rb creates one file app.conf which is ultimately gets open in Post.rb.

So Post.rb depends on Get.rb, hence in my run-list I have placed Get.rb first and then Post.rb.

When I run chef-client, I am getting recipe compile error because the file app.conf is not present.

Looks like chef compiles both recipes simultaneously.
What is the way to solve this?

Edit :
 I have come this far:

```<code>ruby_block 'run' do
     action :nothing
     file = ::File.read('/etc/test.conf')
     data = JSON.parse(file) unless file.nil?
     puts data
     only_if { File.exist?('/etc/test.conf') }
end
</code>```

I am still getting the error. What could be the issue in this block?

答: Check out https://coderanger.net/two-pass/ for a full explanation but basically you want to rework your code using the lazy helper or create a custom resource.</p>

Title: Recipe compile error - Chef

Body:
I have 2 recipes in my cookbook namely - Get.rb and Post.rb.

Get.rb creates one file app.conf which is ultimately gets open in Post.rb.

So Post.rb depends on Get.rb, hence in my run-list I have placed Get.rb first and then Post.rb.

When I run chef-client, I am getting recipe compile error because the file app.conf is not present.

Looks like chef compiles both recipes simultaneously.
What is the way to solve this?

Edit :
 I have come this far:

ruby_block 'run' do
     action :nothing
     file = ::File.read('/etc/test.conf')
     data = JSON.parse(file) unless file.nil?
     puts data
     only_if { File.exist?('/etc/test.conf') }
end

I am still getting the error. What could be the issue in this block?


问:
How to debounce on showing loading overlay template
I'm using ag-grid and ag-grid-angular v9.0.0. I need to show loading overlay template after 2 seconds if the rows are empty otherwise hide it. Currently it shows instantly and goes away after rows are rendered. Any clues or suggestions on how to accomplish is appreciated.</p>

答:
Use the settimeout function pass 2000 as argument </p>

```<code>setTimeout(() => {
    //Execute code here
    }, 2000);
</code>```

Body:
Use the settimeout function pass 2000 as argument

setTimeout(() => {
    //Execute code here
    }, 2000);


问:
bash script and command definition
Got a little bash script like so:

```<code>#!/bin/bash
TIME_CMD='/usr/bin/time -f "%E execution time"'

${TIME_CMD} ls
</code>```

Only problem: doesn't work:

```<code>/usr/bin/time: cannot run execution: No such file or directory
Command exited with non-zero status 127
"0:00.00
</code>```

What am I doing wrong?

答:
Try making it...

```<code>#!/bin/bash
TIME_CMD='/usr/bin/time -f "%E execution time"'

eval "$TIME_CMD ls"
</code>```

This will utilize bash to re-parse the command string after it has been constructed, so that the quoted argument will be recognized properly.

Title: bash script and command definition

Body:
Got a little bash script like so:

#!/bin/bash
TIME_CMD='/usr/bin/time -f "%E execution time"'

${TIME_CMD} ls

Only problem: doesn't work:

/usr/bin/time: cannot run execution: No such file or directory
Command exited with non-zero status 127
"0:00.00

What am I doing wrong?

Body:
Try making it...

#!/bin/bash
TIME_CMD='/usr/bin/time -f "%E execution time"'

eval "$TIME_CMD ls"

This will utilize bash to re-parse the command string after it has been constructed, so that the quoted argument will be recognized properly.


问:
Icons appear too small on Bootstrap navbar
How can I make the icons bigger and centered on the navbar?

There are no CSS rules that are associated to the navbar so why don't the icons show up the same as the other elements? I've tried several things but nothing seem to work.

in the following picture notice the icons on the right, they're not aligned with the other elements

Code:

```<code><header>
  <nav class = "navbar navbar-default navbar-fixed-top">
    <div class = "container">
      <div class = "navbar-header">
        <a class = "navbar-brand" href = "#">
          BRAND
        </a>
      </div>
      <ul class = "nav navbar-nav navbar-right">
        <li class = "text"><a href="#">ABCD</a></li>
        <li class = "text"><a href="#">EFGH</a></li>
        <li class = "text"><a href="#">IJKL</a></li>
        <li class = "text"><a href="#">MNOP</a></li>
        <li><i class = "fa fa-facebook"></i><li/>
        <li><i class = "fa fa-twitter"> </i><li/>
        <li><i class = "fa fa-instagram"> </i><li/>
      </ul>
    </div>
  </nav>
</header>
</code>```

答:
Change the font size of the font awesome icons</p>

```<code>.fa{
  font-size: 2em
}
</code>```

Body:
How can I make the icons bigger and centered on the navbar?

There are no CSS rules that are associated to the navbar so why don't the icons show up the same as the other elements? I've tried several things but nothing seem to work.

in the following picture notice the icons on the right, they're not aligned with the other elements

Code:

          BRAND

ABCD

EFGH

IJKL

MNOP

Body:
Change the font size of the font awesome icons

.fa{
  font-size: 2em
}


问:
How to detect that the HTML element has text by clicking on text content area?
I have text content and a boxed element in a div but still changes happen when I click on boxed element while I need to make changes only when I click on text content.

Here is the code:https://jsfiddle.net/Issact/u0g8LLLo/

```<code><div>
some text
<span class="box"></span>
</div>

<div>
some text
</div>

<div><span class="box"></span></div>
</code>```

JS:

```<code>$(document).on('click','div', function(){
    if (!$(this).text().trim().length > 0) {
        $(this).text("foo");
    } else {
    $(this).append('<span>You clicked on a text</span>');
    }

});
</code>```

答:
This is happening because of event bubbling, so we need to stop that. Jquery having method to stop it event.stopPropagation();. Here I used div * selector to prevent firing event for all the child element inside div. Instead of div you can use any class to differentiate from other div

$(document).on('click','div', function(){

    $(this).append('You clicked on a text');

}).on("click","div *", function(e){e.stopPropagation();});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  background-color:green;
  height:50px;
  width:50px;
  display:block;
}</code>```

some text

```

Body:
I have text content and a boxed element in a div but still changes happen when I click on boxed element while I need to make changes only when I click on text content.

Here is the code:https://jsfiddle.net/Issact/u0g8LLLo/

some text

some text

JS:

$(document).on('click','div', function(){
    if (!$(this).text().trim().length > 0) {
        $(this).text("foo");
    } else {
    $(this).append('You clicked on a text');
    }

});

Body:
This is happening because of event bubbling, so we need to stop that. Jquery having method to stop it event.stopPropagation();. Here I used div * selector to prevent firing event for all the child element inside div. Instead of div you can use any class to differentiate from other div

$(document).on('click','div', function(){

    $(this).append('<span>You clicked on a text</span>');

}).on("click","div *", function(e){e.stopPropagation();});

.box {
  background-color:green;
  height:50px;
  width:50px;
  display:block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
some text
<span class="box"></span>
</div>


问:
What is this binary in tflearn installation?
I am trying to install tflearn on my system. They want me to install binary,

```<code>$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.0.0-cp27-none-linux_x86_64.whl
</code>```

so what is binary?I am not able find any proper documentation in regards to this.

答:
you should just run:</p>

```<code>pip install -U tensorflow==1.0
pip install tflearn
</code>```

Body:
I am trying to install tflearn on my system. They want me to install binary,

$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.0.0-cp27-none-linux_x86_64.whl

so what is binary?I am not able find any proper documentation in regards to this.

Body:
you should just run:

pip install -U tensorflow==1.0
pip install tflearn


问:
MVC with Angular - ValidateAntiForgeryToken fails after Azure Login redirect with Adal
I have an MVC site with an embedded angular client and I've recently implemented an anti forgery XSRF token as a security measure.

I have set it up in Startup.cs as follows:

```<code>services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

app.Use(next => context =>
        {
            if (string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(context.Request.Path.Value, "/index.html", StringComparison.OrdinalIgnoreCase))
            {
                // We can send the request token as a JavaScript-readable cookie, and Angular will use it by default.
                var tokens = antiforgery.GetAndStoreTokens(context);
                context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                    new CookieOptions() { HttpOnly = false });
            }

            return next(context);
        });
</code>```

And I've implemented it within my angular front-end like so:

```<code>{ provide: XSRFStrategy, useFactory: xsrfFactory}

export function xsrfFactory(): CookieXSRFStrategy {
return new CookieXSRFStrategy('XSRF-TOKEN', 'X-XSRF-TOKEN');
}
</code>```

And protecting my controllers like:

```<code>[Authorize] //Validation of AzureAD Bearer Token.
[ValidateAntiForgeryToken]
public class UserController : Controller
</code>```

It is intended that the X-XSRF-TOKEN header be validated with any call to my API, and this works successfully for all calls in the original session. However, my app uses Adal to log the user in, and after the redirect from a successful login, this validation step fails and I receive a 400 from my API for any subsequent calls.

The original X-XSRF-TOKEN header is still sent with all outgoing requests from my angular client after the login so I suspect it must be that my server side no longer has the token to validate against, or my server has generated a new one and my client doesn't retrieve it. But for whatever reason it breaks down and it's very hard to debug without creating some custom filter so I can see what's going on inside it.

Is there a way to reset this token after a client side redirect so that both my server and client share common knowledge of it again? Or should I be generating the token in my Index.html for example?

EDIT

Edited controller decoration above for missing [Authorize] attribute.

So my controller is protected by a step validating the AzureAD Bearer token as well as the Anti-Forgery validation. Removing the AzureAD Validation as a test did not resolve the issue, oddly.

Error on failing API calls displays in output after Adal login as:

The provided anti-forgery token was meant for a different claims-based user than the current user.

答:
Based on my understanding, you were protecting the controller using token. For this issue is expected, you can refer the progress of validate the anti-XSRF tokens from below(refer this link):

To validate the incoming anti-XSRF tokens, the developer includes a ValidateAntiForgeryToken attribute on her MVC action or controller, or she calls @AntiForgery.Validate() from her Razor page. The runtime will perform the following steps:

The incoming session token and field token are read and the anti-XSRF token extracted from each. The anti-XSRF tokens must be identical per step (2) in the generation routine.

If the current user is authenticated, her username is compared with the username stored in the field token. The usernames must match.

If an IAntiForgeryAdditionalDataProvider is configured, the runtime calls its ValidateAdditionalData method. The method must return the Boolean value true.

Since you were developing the SPA application with back-end web API, when the request to the web API, it will always issue the anti-XSRF token with no identity. And when you send the request to the back-end with anti-XSRF and Azure AD token, this time the web API already authenticate the request via the Azure AD token. And it will always return false when checking anti-XSRF token to match the identity information.

In this scenario, if the back-end only using the bear token authentication and store the token with session storage, there is no need to enable XSRF prevention since others is not able to steal the token and forge the request.

If your back-end also support the cookie authentication or basic auth, NTLM etc, you can disable the identity checking by adding the following to your Application_Start method: AntiForgeryConfig.SuppressIdentityHeuristicChecks = true.(refer this link)

More detail about XSRF/CSRF abouth oauth and web API, you can refer the threads below:

How does ValidateAntiForgeryToken fit with Web APIs that can be accessed via web or native app?

AntiForgeryToken does not work well with OAuth via WebAPI

Body:
I have an MVC site with an embedded angular client and I've recently implemented an anti forgery XSRF token as a security measure.

I have set it up in Startup.cs as follows:

services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

app.Use(next => context =>
        {
            if (string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(context.Request.Path.Value, "/index.html", StringComparison.OrdinalIgnoreCase))
            {
                // We can send the request token as a JavaScript-readable cookie, and Angular will use it by default.
                var tokens = antiforgery.GetAndStoreTokens(context);
                context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                    new CookieOptions() { HttpOnly = false });
            }

            return next(context);
        });

And I've implemented it within my angular front-end like so:

{ provide: XSRFStrategy, useFactory: xsrfFactory}

export function xsrfFactory(): CookieXSRFStrategy {
return new CookieXSRFStrategy('XSRF-TOKEN', 'X-XSRF-TOKEN');
}

And protecting my controllers like:

[Authorize] //Validation of AzureAD Bearer Token.
[ValidateAntiForgeryToken]
public class UserController : Controller

It is intended that the X-XSRF-TOKEN header be validated with any call to my API, and this works successfully for all calls in the original session. However, my app uses Adal to log the user in, and after the redirect from a successful login, this validation step fails and I receive a 400 from my API for any subsequent calls.

The original X-XSRF-TOKEN header is still sent with all outgoing requests from my angular client after the login so I suspect it must be that my server side no longer has the token to validate against, or my server has generated a new one and my client doesn't retrieve it. But for whatever reason it breaks down and it's very hard to debug without creating some custom filter so I can see what's going on inside it.

Is there a way to reset this token after a client side redirect so that both my server and client share common knowledge of it again? Or should I be generating the token in my Index.html for example?

EDIT

Edited controller decoration above for missing [Authorize] attribute.

So my controller is protected by a step validating the AzureAD Bearer token as well as the Anti-Forgery validation. Removing the AzureAD Validation as a test did not resolve the issue, oddly.

Error on failing API calls displays in output after Adal login as:

The provided anti-forgery token was meant for a different claims-based user than the current user.


问:
pip error while installing package in Cygwin/Python2.7
I installed Python2.7.3 in Cygwin using this guide, I then installed pip from source.

When I try to use pip:

```<code>$ pip install sqlalchemy
Downloading/unpacking sqlalchemy
Downloading SQLAlchemy-0.7.8.tar.gz (2.6Mb): 2.6Mb downloaded
Running setup.py egg_info for package sqlalchemy
  137 [main] python2.7 1060 child_info_fork::abort: address space needed by 'itertools.dll' (0x2C0000) is already occupied
  Error [Errno 11] Resource temporarily unavailable while executing command python setup.py egg_info
Exception:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/basecommand.py", line 104, in main
  status = self.run(options, args)
File "/usr/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/commands/install.py", line 245, in run
  requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "/usr/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 1009, in prepare_files
  req_to_install.run_egg_info()
File "/usr/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 225, in run_egg_info
  command_desc='python setup.py egg_info')
File "/usr/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/__init__.py", line 221, in call_subprocess
  cwd=cwd, env=env)
File "/usr/local/lib/python2.7/subprocess.py", line 679, in __init__
  errread, errwrite)
File "/usr/local/lib/python2.7/subprocess.py", line 1143, in _execute_child
  self.pid = os.fork()
OSError: [Errno 11] Resource temporarily unavailable

Storing complete log in /home/joshfriend/.pip/pip.log
</code>```

Found a guide noting that this happens, and said that running rebaseall should fix this. I tried, and it didn't. I would assume that this is because I did not install python2.7 with the cygwin installer and therefore was not affected by the rebaseall.

UPDATE:

I gave the wrong link to the instructions I used to install python (sorry). I went back and fixed my explanation of what I did...

答: Try simply running export temp=  from the cygwin console. It solved the issue for me.</p>

Body:
I installed Python2.7.3 in Cygwin using this guide, I then installed pip from source.

When I try to use pip:

$ pip install sqlalchemy
Downloading/unpacking sqlalchemy
Downloading SQLAlchemy-0.7.8.tar.gz (2.6Mb): 2.6Mb downloaded
Running setup.py egg_info for package sqlalchemy
  137 [main] python2.7 1060 child_info_fork::abort: address space needed by 'itertools.dll' (0x2C0000) is already occupied
  Error [Errno 11] Resource temporarily unavailable while executing command python setup.py egg_info
Exception:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/basecommand.py", line 104, in main
  status = self.run(options, args)
File "/usr/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/commands/install.py", line 245, in run
  requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "/usr/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 1009, in prepare_files
  req_to_install.run_egg_info()
File "/usr/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 225, in run_egg_info
  command_desc='python setup.py egg_info')
File "/usr/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/__init__.py", line 221, in call_subprocess
  cwd=cwd, env=env)
File "/usr/local/lib/python2.7/subprocess.py", line 679, in __init__
  errread, errwrite)
File "/usr/local/lib/python2.7/subprocess.py", line 1143, in _execute_child
  self.pid = os.fork()
OSError: [Errno 11] Resource temporarily unavailable

Storing complete log in /home/joshfriend/.pip/pip.log

Found a guide noting that this happens, and said that running rebaseall should fix this. I tried, and it didn't. I would assume that this is because I did not install python2.7 with the cygwin installer and therefore was not affected by the rebaseall.

UPDATE:

I gave the wrong link to the instructions I used to install python (sorry). I went back and fixed my explanation of what I did...


问:
Php Insert Data To MySql From Web Form Securely
I am learning php and have been following the OOP creating a data class tutorial at phpbridge.org

In the tutorial they take form data from a post and insert it into the database.

Here is the code:

Step 1:  The Form

```<code><h2>New Topic</h2>
<form action="add.php" method="POST">
    <label>
        Title: <input type="text" name="title">
    </label>
    <br>
    <label>
        Description:
        <br>
        <textarea name="description" cols="50" rows="20"></textarea>
    </label>
    <br>
    <input type="submit" value="Add Topic">
</form>
</code>```

Step 2 Php file

```<code><?php
 require 'TopicData.php';

if (isset($_POST) && sizeof($_POST) > 0) {
    $data = new TopicData();
    $data->add($_POST);
}
?>
</code>```

Step 3

The Function included in TopicData.php

```<code>public function add($data)
{
    $query = $this->connection->prepare(
        "INSERT INTO topics (
            title,
            description
        ) VALUES (
            :title,
            :description
        )"
    );

    $data = [
        ':title' => $data['title'],
        ':description' => $data['description']
    ];

    $query->execute($data);
}
</code>```

My question is in regards to security.   Before this data is inserted into a database wouldn't it be best practice to run each field of the form through the filter_input() function?  Also should these be run through filter_var() as well?

If this is necessary what exactly would the filter code look like?

Thanks!

答:
The TopicData.php file is using prepared SQL queries. The benefit of using prepared queries is that it removes the possibility of SQL Injection provided that the SQL query is not based on external input. When using prepared queries, the template of the query is sent separately from the data. This has many benefits which are described here: https://www.w3schools.com/php/php_mysql_prepared_statements.asp

It removes the need for sanitizing form data. However the form data may still need to be filtered using the filter_var functions, if validation is required such as maximum string length, maximum and minimum values etc.

Body:
I am learning php and have been following the OOP creating a data class tutorial at phpbridge.org

In the tutorial they take form data from a post and insert it into the database.

Here is the code:

Step 1:  The Form

New Topic

<form action="add.php" method="POST">

        Title: <input type="text" name="title">

        Description:

        <textarea name="description" cols="50" rows="20"></textarea>

    <input type="submit" value="Add Topic">
</form>

Step 2 Php file

<?php
 require 'TopicData.php';

if (isset($_POST) && sizeof($_POST) > 0) {
    $data = new TopicData();
    $data->add($_POST);
}
?>

Step 3

The Function included in TopicData.php

public function add($data)
{
    $query = $this->connection->prepare(
        "INSERT INTO topics (
            title,
            description
        ) VALUES (
            :title,
            :description
        )"
    );

    $data = [
        ':title' => $data['title'],
        ':description' => $data['description']
    ];

    $query->execute($data);
}

My question is in regards to security.   Before this data is inserted into a database wouldn't it be best practice to run each field of the form through the filter_input() function?  Also should these be run through filter_var() as well?

If this is necessary what exactly would the filter code look like?

Thanks!


问:
A function can take another function as one of its arguments
I wrote the following code in playground and try to learn from Apple doc function & classes.

Here is my code..

```<code>func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)
</code>```

How can I directly pass the different condition?
can I write like that..

```<code>hasAnyMatches(numbers, condition: { $0 < 10 })
</code>```

Actually this function return true/false, but when I write like that so in play ground behalf of this line o/p: (4 times)
So what happen when I'm write like that.

And give me solution to direct pass the condition in hasAnyMatches() func.

答:
When you write this:

```<code>hasAnyMatches(numbers, condition: { $0 < 10 })
</code>```

The playground says "(4 times)". This is because the closure { $0 < 10 } is executed four times, one time on each item in numbers.

To get it to show the return value of the hasAnyMatches function, there are a few ways to do this.

You can just make {$0 < 10} be on its own line:

```<code>hasAnyMatches(list: numbers, condition: // shows true on this line
    {$0 < 10} // shows (4 times) on this line
)
</code>```

You can store the result into a variable, then get the value of the variable:

```<code>let val = hasAnyMatches(list: numbers, condition: {$0 < 10})
val // shows true on this line
</code>```

Body:
I wrote the following code in playground and try to learn from Apple doc function & classes.

Here is my code..

func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)

How can I directly pass the different condition?
can I write like that..

hasAnyMatches(numbers, condition: { $0 < 10 })

Actually this function return true/false, but when I write like that so in play ground behalf of this line o/p: (4 times)
So what happen when I'm write like that.

And give me solution to direct pass the condition in hasAnyMatches() func.

Body:
When you write this:

hasAnyMatches(numbers, condition: { $0 < 10 })

The playground says "(4 times)". This is because the closure { $0 < 10 } is executed four times, one time on each item in numbers.

To get it to show the return value of the hasAnyMatches function, there are a few ways to do this.

You can just make {$0 < 10} be on its own line:

hasAnyMatches(list: numbers, condition: // shows true on this line
    {$0 < 10} // shows (4 times) on this line
)

You can store the result into a variable, then get the value of the variable:

let val = hasAnyMatches(list: numbers, condition: {$0 < 10})
val // shows true on this line


问:
Laravel - Delete data record from Database
I want to delete record Photo and Photo_list from Database but give me error

This is my Code in Controller

```<code>public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::select('photo','photo_list')->delete($product->id);

    return redirect(route('stores.index'));

}
</code>```

答:
Try this</p>

```<code>Product::WhereProductId($product->id)->delete();
</code>```

Body:
I want to delete record Photo and Photo_list from Database but give me error

This is my Code in Controller

public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::select('photo','photo_list')->delete($product->id);

    return redirect(route('stores.index'));

}

Body:
Try this

Product::WhereProductId($product->id)->delete();


问:
Django: standard location/conventions for data import scripts?
I'm working on a number of Django projects, and in most of them, I have initial data to import.

This data isn't neat JSON, as shown in the fixture examples in the Django docs - it tends to be messy Excel or CSV files. The scripts tend to look like the following snippet, and I just run them as standalone Python, because I don't know any better:

```<code>import sys
from django.core.management import setup_environ
sys.path.append(LOCATION OF YOUR DJANGO PROJECTS, EX: 'C:\django')
from mysite import settings
setup_environ(settings)

from PROJECT_NAME.APP_NAME.models import MODEL_NAME

import csv
reader = csv.reader(open(COMPLETE PATH TO YOUR DATA, EX: "C:/django/mysite/restaurants.csv"), dialect='excel')

for row in reader:
   COLUMN_ONE_TITLE = row[0]
   COLUMN_TWO_TITLE = row[1]

   MODEL_NAME.objects.get_or_create(MY_FIRST_COLUMN=COLUMN_ONE_TITLE, MY_SECOND_COLUMN=COLUMN_TWO_TITLE)
</code>```

I feel that when I commit these projects to GitHub or send them to the client or whatever, I should include the import scripts. They're an important part of the project.

Is there a standard way, in Django, to store the import scripts  that I've written to import this data?

Where in the project should they sit? Should I be using management commands?

Thanks!

答: Django supports pluggable serialization modules. If you can arrange your CSV formats to work as a deserializer, you can use the regular loaddata command.</p>

Body:
I'm working on a number of Django projects, and in most of them, I have initial data to import.

This data isn't neat JSON, as shown in the fixture examples in the Django docs - it tends to be messy Excel or CSV files. The scripts tend to look like the following snippet, and I just run them as standalone Python, because I don't know any better:

import sys
from django.core.management import setup_environ
sys.path.append(LOCATION OF YOUR DJANGO PROJECTS, EX: 'C:\django')
from mysite import settings
setup_environ(settings)

from PROJECT_NAME.APP_NAME.models import MODEL_NAME

import csv
reader = csv.reader(open(COMPLETE PATH TO YOUR DATA, EX: "C:/django/mysite/restaurants.csv"), dialect='excel')

for row in reader:
   COLUMN_ONE_TITLE = row[0]
   COLUMN_TWO_TITLE = row[1]

   MODEL_NAME.objects.get_or_create(MY_FIRST_COLUMN=COLUMN_ONE_TITLE, MY_SECOND_COLUMN=COLUMN_TWO_TITLE)

I feel that when I commit these projects to GitHub or send them to the client or whatever, I should include the import scripts. They're an important part of the project.

Is there a standard way, in Django, to store the import scripts  that I've written to import this data?

Where in the project should they sit? Should I be using management commands?

Thanks!


问:
Retrieve Starting and Ending values from a table whose values have gaps
How can I retrieve the values from a table where there are TicketType and TicketNo columns. Each TicketType can have mutiple TicketNos and these TicketNos may have gaps between them. TicketNos are not generated by the system. Not my choice. Here is a sample of the data and the desired output:

```<code>    declare @tickets table ( TicketType varchar(20),
                         TicketNo int )
insert into @tickets( tickettype, ticketno )
select 'AIRCON 1', 1
union all
select 'AIRCON 1', 2
union all
select 'AIRCON 1', 3
union all
select 'AIRCON 1', 6
union all
select 'AIRCON 1', 7
union all
select 'AIRCON 1', 8
union all
select 'AIRCON 1', 9
union all
select 'AIRCON 2', 1
union all
select 'AIRCON 2', 2
union all
select 'AIRCON 2', 3
union all
select 'AIRCON 2', 4
union all
select 'AIRCON 2', 5
union all
select 'AIRCON 3', 1
union all
select 'AIRCON 3', 2
union all
select 'AIRCON 3', 9
union all
select 'AIRCON 3', 10

select * from @tickets

SELECT 'AIRCON 1' TicketType, 1 Starting, 3 Ending
union all
select 'AIRCON 1', 6, 9
union all
select 'AIRCON 2', 1, 5
union all
select 'AIRCON 3', 1, 2
union all
select 'AIRCON 3', 9, 10
</code>```

Sample data:

```<code>+------------------------------------+
|   TicketType           TicketNo    |
+------------------------------------+
| AIRCON 1             1             |
| AIRCON 1             2             |
| AIRCON 1             3             |
| AIRCON 1             6             |
| AIRCON 1             7             |
| AIRCON 1             8             |
| AIRCON 1             9             |
| AIRCON 2             1             |
| AIRCON 2             2             |
| AIRCON 2             3             |
| AIRCON 2             4             |
| AIRCON 2             5             |
| AIRCON 3             1             |
| AIRCON 3             2             |
| AIRCON 3             9             |
| AIRCON 3             10            |
</code>```

Desired Result

```<code>| TicketType Starting    Ending      |
| ---------- ----------- ----------- |
| AIRCON 1   1           3           |
| AIRCON 1   6           9           |
| AIRCON 2   1           5           |
| AIRCON 3   1           2           |
| AIRCON 3   9           10          |
+------------------------------------+
</code>```

答:
This is variation of islands problem.</p>

```<code>select TicketType, min(ticketno), max(ticketno)
from (
    select TicketType, ticketno, row_number() over( partition by tickettype order by ticketno) - ticketno grp
    from @tickets
) t
group by TicketType, grp
order by TicketType, min(ticketno)
</code>```

Body:
How can I retrieve the values from a table where there are TicketType and TicketNo columns. Each TicketType can have mutiple TicketNos and these TicketNos may have gaps between them. TicketNos are not generated by the system. Not my choice. Here is a sample of the data and the desired output:

    declare @tickets table ( TicketType varchar(20),
                         TicketNo int )
insert into @tickets( tickettype, ticketno )
select 'AIRCON 1', 1
union all
select 'AIRCON 1', 2
union all
select 'AIRCON 1', 3
union all
select 'AIRCON 1', 6
union all
select 'AIRCON 1', 7
union all
select 'AIRCON 1', 8
union all
select 'AIRCON 1', 9
union all
select 'AIRCON 2', 1
union all
select 'AIRCON 2', 2
union all
select 'AIRCON 2', 3
union all
select 'AIRCON 2', 4
union all
select 'AIRCON 2', 5
union all
select 'AIRCON 3', 1
union all
select 'AIRCON 3', 2
union all
select 'AIRCON 3', 9
union all
select 'AIRCON 3', 10

select * from @tickets

SELECT 'AIRCON 1' TicketType, 1 Starting, 3 Ending
union all
select 'AIRCON 1', 6, 9
union all
select 'AIRCON 2', 1, 5
union all
select 'AIRCON 3', 1, 2
union all
select 'AIRCON 3', 9, 10

Sample data:

+------------------------------------+
|   TicketType           TicketNo    |
+------------------------------------+
| AIRCON 1             1             |
| AIRCON 1             2             |
| AIRCON 1             3             |
| AIRCON 1             6             |
| AIRCON 1             7             |
| AIRCON 1             8             |
| AIRCON 1             9             |
| AIRCON 2             1             |
| AIRCON 2             2             |
| AIRCON 2             3             |
| AIRCON 2             4             |
| AIRCON 2             5             |
| AIRCON 3             1             |
| AIRCON 3             2             |
| AIRCON 3             9             |
| AIRCON 3             10            |

Desired Result

| TicketType Starting    Ending      |
| ---------- ----------- ----------- |
| AIRCON 1   1           3           |
| AIRCON 1   6           9           |
| AIRCON 2   1           5           |
| AIRCON 3   1           2           |
| AIRCON 3   9           10          |
+------------------------------------+

Body:
This is variation of islands problem.

select TicketType, min(ticketno), max(ticketno)
from (
    select TicketType, ticketno, row_number() over( partition by tickettype order by ticketno) - ticketno grp
    from @tickets
) t
group by TicketType, grp
order by TicketType, min(ticketno)


问:
Admin LTE theme + Laravel Mini sidebar issue
I used Admin LTE theme with Laravel and stucked at one known issue,
there is no solution of that in Admin LTE theme,
IF I toggle side bar its showing miniside bar,
but when i navigate to another page the toggled sidebar again opened,
It should not open because i already minimized it,

Please help,

答: If i correctly remember, you must add in the body a class named "collapsed" (or something similar, check it with an inspector) that manage the behavior of the menu. Adding it, menu will be shown, remove it will hide it. You can modify the internal js library adding a cookie, so you can easily know how the menu should be.</p>


问:
Is this a correct way to pass a function into a struct?
I looked but couldn't find a direct reference for this question. I'm new to function pointers (and C), so I don't know all the tricks one can do yet :)

I've effectively got a function:

```<code>void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
    ...
</code>```

...where My_Struct has prototype:

```<code>typedef struct my_struct {
    int (*comp)(int x, int y);
} My_Struct;
</code>```

Modulo some minor details. I just want to know if the following is correct syntax:

```<code>void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
    structure->comp = comp;
}
</code>```

It seems almost too easy, and I'm worried it is.

答:
The code is ok.

Though note that function pointers have plain horrible syntax in C, particularly when passed to/returned from functions. Try writing something like "function returning function-pointer and taking function-pointer as parameter" and you'll soon realize that the syntax is pure madness.

It is therefore a good idea to make function pointers "fall in line" with the rest of the language by using typedefs.

You code could be written like this:

```<code>typedef int comp_t (int x, int y); // typedef a function type

typedef struct {
    comp_t* comp;   // pointer to such a function type
} My_Struct;

void select_comparator(My_Struct *structure, comp_t* comp) {
    structure->comp = comp;
}
</code>```

Now the code turns easier to read and the function pointer behaves pretty much like any other pointer.

Body:
I looked but couldn't find a direct reference for this question. I'm new to function pointers (and C), so I don't know all the tricks one can do yet :)

I've effectively got a function:

void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
    ...

...where My_Struct has prototype:

typedef struct my_struct {
    int (*comp)(int x, int y);
} My_Struct;

Modulo some minor details. I just want to know if the following is correct syntax:

void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
    structure->comp = comp;
}

It seems almost too easy, and I'm worried it is.

Body:
The code is ok.

Though note that function pointers have plain horrible syntax in C, particularly when passed to/returned from functions. Try writing something like "function returning function-pointer and taking function-pointer as parameter" and you'll soon realize that the syntax is pure madness.

It is therefore a good idea to make function pointers "fall in line" with the rest of the language by using typedefs.

You code could be written like this:

typedef int comp_t (int x, int y); // typedef a function type

typedef struct {
    comp_t* comp;   // pointer to such a function type
} My_Struct;

void select_comparator(My_Struct *structure, comp_t* comp) {
    structure->comp = comp;
}

Now the code turns easier to read and the function pointer behaves pretty much like any other pointer.


问:
How does one test item membership in an unordered sequence (C++)?
I've used python for a long time, and I'm just beginning to use C++

In python, if one has a set or a dictionary it is relatively easy to get a boolean value indicating whether or not a particular item is in that sequence using the in keyword.
i.e.

```<code>a = set(2,4,3)
if 4 in a
print "yes, 4 is in a, thank you for asking!"
</code>```

it's much more efficient than doing this:

```<code>a = [2,3,4]
for number in a
>if number == 4
>>return "yes, 4 is in a, thank you for asking!"
</code>```

is there a way to do make a membership test simple and efficient in cpp or do you always have to iterate through some ordered sequence?

答:
You have functionality like this in std::set and tr1::unordered_set (not yet in C++ standard).

```<code>#include <set>
#include <cstdio>

int main() {
     std::set<int> s;
     s.insert(1);
     s.insert(2);
     s.insert(4);
     if (s.find(4) != s.end())
          puts("4 found!");
     return 0;
}
</code>```

In reality, if your data set is small, linear search may still be the faster option.

Body:
I've used python for a long time, and I'm just beginning to use C++

In python, if one has a set or a dictionary it is relatively easy to get a boolean value indicating whether or not a particular item is in that sequence using the in keyword.
i.e.

a = set(2,4,3)
if 4 in a
print "yes, 4 is in a, thank you for asking!"

it's much more efficient than doing this:

a = [2,3,4]
for number in a
>if number == 4
>>return "yes, 4 is in a, thank you for asking!"

is there a way to do make a membership test simple and efficient in cpp or do you always have to iterate through some ordered sequence?

Body:
You have functionality like this in std::set and tr1::unordered_set (not yet in C++ standard).

#include <set>
#include <cstdio>

int main() {
     std::set<int> s;
     s.insert(1);
     s.insert(2);
     s.insert(4);
     if (s.find(4) != s.end())
          puts("4 found!");
     return 0;
}

In reality, if your data set is small, linear search may still be the faster option.


问:
Validation in IOS app
I know that its a simple question but i have tried many times for my code check validation but its not working. When i click register button it takes me to next page instead of validating my form.My code is</p>

```<code>- (IBAction)Register:(id)sender {
    if ([self.name.text isEqualToString:@""]){
        NSString *message = @"Name";

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Name"
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleAlert];

        [self presentViewController:alert animated:YES completion:nil];

        int duration = 1; // duration in seconds

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });

    } else if ([self.email.text isEqualToString:@""]){
        NSString *message = @"Email";

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Email Address"
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleAlert];

        [self presentViewController:alert animated:YES completion:nil];

        int duration = 1; // duration in seconds

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });

    }else{

        NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
        //Valid email address

        if ([emailTest evaluateWithObject:_email.text] == YES)
        {
            // NSLog(@"Correct Email");
        }
        else
        {
            NSString *message = @"Invalid Email";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Email Format Incorrect"
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([_code.titleLabel.text isEqualToString:@"Code"]) {
            NSString *message = @"Select Country Code";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([self.mobileCode.text isEqualToString:@""]) {
            NSString *message = @"Enter Mobile Code";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([self.number1.text isEqualToString:@""]) {
            NSString *message = @"Enter Your Number";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

    }
    [self Account];

}
</code>```

答:
It seems you are calling API even all validation passed or failed. I put small logic when to call API. Kindly check my below and let me know if you have any doubt. </p>

```<code>   - (IBAction)Register:(id)sender {

        BOOL isValidationSuccess = TRUE;
        if ([self.name.text isEqualToString:@""]){

            // You need to change the flage when you get error in your code
            isValidationSuccess = FALSE;
            NSString *message = @"Name";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Name"
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        } else if ([self.email.text isEqualToString:@""]){

            // You need to change the flage when you get error in your code
            isValidationSuccess = FALSE;

            NSString *message = @"Email";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Email Address"
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }else{

            NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
            NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
            //Valid email address

            if ([emailTest evaluateWithObject:_email.text] == YES)
            {
                // NSLog(@"Correct Email");
            }
            else
            {
                // You need to change the flage when you get error in your code
                isValidationSuccess = FALSE;

                NSString *message = @"Invalid Email";

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Email Format Incorrect"
                                                                               message:message
                                                                        preferredStyle:UIAlertControllerStyleAlert];

                [self presentViewController:alert animated:YES completion:nil];

                int duration = 1; // duration in seconds

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                    [alert dismissViewControllerAnimated:YES completion:nil];
                });

            }

            if ([_code.titleLabel.text isEqualToString:@"Code"]) {

                // You need to change the flage when you get error in your code
                isValidationSuccess = FALSE;

                NSString *message = @"Select Country Code";

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:message
                                                                        preferredStyle:UIAlertControllerStyleAlert];

                [self presentViewController:alert animated:YES completion:nil];

                int duration = 1; // duration in seconds

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                    [alert dismissViewControllerAnimated:YES completion:nil];
                });

            }

            if ([self.mobileCode.text isEqualToString:@""]) {

                // You need to change the flage when you get error in your code
                isValidationSuccess = FALSE;

                NSString *message = @"Enter Mobile Code";

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:message
                                                                        preferredStyle:UIAlertControllerStyleAlert];

                [self presentViewController:alert animated:YES completion:nil];

                int duration = 1; // duration in seconds

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                    [alert dismissViewControllerAnimated:YES completion:nil];
                });

            }

            if ([self.number1.text isEqualToString:@""]) {

                // You need to change the flage when you get error in your code
                isValidationSuccess = FALSE;

                NSString *message = @"Enter Your Number";

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:message
                                                                        preferredStyle:UIAlertControllerStyleAlert];

                [self presentViewController:alert animated:YES completion:nil];

                int duration = 1; // duration in seconds

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                    [alert dismissViewControllerAnimated:YES completion:nil];
                });

            }

        }

        // This comes TRUE means you have pass your all validation.
        if(isValidationSuccess)
        {
            /// You can call for register
            [self account];
        }

    }
</code>```

Title: Validation in IOS app

Body:
I know that its a simple question but i have tried many times for my code check validation but its not working. When i click register button it takes me to next page instead of validating my form.My code is

- (IBAction)Register:(id)sender {
    if ([self.name.text isEqualToString:@""]){
        NSString *message = @"Name";

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Name"
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleAlert];

        [self presentViewController:alert animated:YES completion:nil];

        int duration = 1; // duration in seconds

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });

    } else if ([self.email.text isEqualToString:@""]){
        NSString *message = @"Email";

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Email Address"
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleAlert];

        [self presentViewController:alert animated:YES completion:nil];

        int duration = 1; // duration in seconds

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });

    }else{

        NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
        //Valid email address

        if ([emailTest evaluateWithObject:_email.text] == YES)
        {
            // NSLog(@"Correct Email");
        }
        else
        {
            NSString *message = @"Invalid Email";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Email Format Incorrect"
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([_code.titleLabel.text isEqualToString:@"Code"]) {
            NSString *message = @"Select Country Code";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([self.mobileCode.text isEqualToString:@""]) {
            NSString *message = @"Enter Mobile Code";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([self.number1.text isEqualToString:@""]) {
            NSString *message = @"Enter Your Number";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

    }
    [self Account];

}

Body:
It seems you are calling API even all validation passed or failed. I put small logic when to call API. Kindly check my below and let me know if you have any doubt.

   - (IBAction)Register:(id)sender {

        BOOL isValidationSuccess = TRUE;
        if ([self.name.text isEqualToString:@""]){

            // You need to change the flage when you get error in your code
            isValidationSuccess = FALSE;
            NSString *message = @"Name";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Name"
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        } else if ([self.email.text isEqualToString:@""]){

            // You need to change the flage when you get error in your code
            isValidationSuccess = FALSE;

            NSString *message = @"Email";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Email Address"
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }else{

            NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
            NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
            //Valid email address

            if ([emailTest evaluateWithObject:_email.text] == YES)
            {
                // NSLog(@"Correct Email");
            }
            else
            {
                // You need to change the flage when you get error in your code
                isValidationSuccess = FALSE;

                NSString *message = @"Invalid Email";

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Email Format Incorrect"
                                                                               message:message
                                                                        preferredStyle:UIAlertControllerStyleAlert];

                [self presentViewController:alert animated:YES completion:nil];

                int duration = 1; // duration in seconds

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                    [alert dismissViewControllerAnimated:YES completion:nil];
                });

            }

            if ([_code.titleLabel.text isEqualToString:@"Code"]) {

                // You need to change the flage when you get error in your code
                isValidationSuccess = FALSE;

                NSString *message = @"Select Country Code";

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:message
                                                                        preferredStyle:UIAlertControllerStyleAlert];

                [self presentViewController:alert animated:YES completion:nil];

                int duration = 1; // duration in seconds

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                    [alert dismissViewControllerAnimated:YES completion:nil];
                });

            }

            if ([self.mobileCode.text isEqualToString:@""]) {

                // You need to change the flage when you get error in your code
                isValidationSuccess = FALSE;

                NSString *message = @"Enter Mobile Code";

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:message
                                                                        preferredStyle:UIAlertControllerStyleAlert];

                [self presentViewController:alert animated:YES completion:nil];

                int duration = 1; // duration in seconds

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                    [alert dismissViewControllerAnimated:YES completion:nil];
                });

            }

            if ([self.number1.text isEqualToString:@""]) {

                // You need to change the flage when you get error in your code
                isValidationSuccess = FALSE;

                NSString *message = @"Enter Your Number";

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:message
                                                                        preferredStyle:UIAlertControllerStyleAlert];

                [self presentViewController:alert animated:YES completion:nil];

                int duration = 1; // duration in seconds

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                    [alert dismissViewControllerAnimated:YES completion:nil];
                });

            }

        }

        // This comes TRUE means you have pass your all validation.
        if(isValidationSuccess)
        {
            /// You can call for register
            [self account];
        }

    }


问:
Javascript not working after closing/reopening modal
I'm having an issue with using javascript files within a bootstrap modal in a yii2 project I am working on. I have a modal box with the view used for the body of the modal being loaded through ajax. In one of the views I have registered a javascript file to disable certain form inputs depending on a few conditions. The first time I load the modal, the javascript functions without any issues. However, if I close the modal and reopen it, the javascript is no longer working until I refresh the entire page.

I've tried clearing out the content of the modal entirely using

```<code>$("#modal").on('hide.bs.modal', function(e){
    var contentArea = $(this).find('#modalContent');
    contentArea.html('');
});
</code>```

but it the javascript still does not function upon reopening the modal.

This is the code that defines the modal

```<code><?php
  Modal::begin([
    'header'=>'<h4>Event</h4>',
    'id'=>'modal',
    'size'=>'modal-lg',
    'options'=>[
        'tabindex'=>false
    ]
  ]);
?>
  <div id="modalContent"></div>
<?php Modal::end(); ?>
</code>```

And the page being loaded into the modal...

```<code><?php
  $this->registerJsFile('@web/js/registration.js');
?>
<div class="registrant-create">
<?php $form = ActiveForm::begin([
   'id'=>$model->formName(),
   'action'=>['create-payment'],
   'enableAjaxValidation'=>true,
   'validationUrl'=>['/event/registrant/validate-registrant','event_id'=>$model->event_id],
   'options'=>['data-pjax'=>true],
]); ?>
<input type="hidden" name="form_page" value="level" id="form_page" />
<div id="page-level">
    <?=$this->render('_form_level', [
        'form' => $form,
        'model' => $model,
        'model_code'=>$model_code,
        'list_levels' => $list_levels,
        'list_members' => $list_members,
    ])?>
</div>
<div id="page-attendee">
    <?=$this->render('_form_attendee', [
        'form' => $form,
        'model' => $model,
        'model_organization' => $model_organization,
        'models_attendee' => $models_attendee,
        'models_personal' => $models_personal,
        'models_personalEmail' => $models_personalEmail,
        'models_email' => $models_email,
        'models_answer' => $models_answer,
    ]);?>
</div>
</code>```

The sub-views being rendered contain the fields for the individual form pages (theres 4 in total, cut it down to keep it readable). An example of one of the subviews would be...

```<code><div class="alert alert-info">
    Instructions...
</div>
<div class="row">
    <?= $form->field($model, 'level_id',['options'=>['class'=>'col-lg-5']])->dropDownList($list_levels['items'],['options'=>$list_levels['attributes']])->label("Select a level"); ?>
    <?= $form->field($model_code, 'code',['options'=>['class'=>'col-lg-5']])->label("Enter a registration code")?>
</div>
<?= $form->field($model, 'member_id','inputOptions'=>['data-disabled'=>true]])->dropDownList($list_members)->label("Select a member"); ?>

<div class="form-group">
    <?= Html::button('Continue', ['class' => 'btn btn-primary btn-block btn-lg form-continue', 'data-next'=>'attendee'])?>
</div>
</code>```

Is there something I need to do to reload the javascript file? Any help is much appreciated.

答:
try this :</p>

```<code>$(document).on('hide.bs.modal', '#modal' , function(e){
    var contentArea = $(this).find('#modalContent');
    contentArea.html('');
});
</code>```

Body:
I'm having an issue with using javascript files within a bootstrap modal in a yii2 project I am working on. I have a modal box with the view used for the body of the modal being loaded through ajax. In one of the views I have registered a javascript file to disable certain form inputs depending on a few conditions. The first time I load the modal, the javascript functions without any issues. However, if I close the modal and reopen it, the javascript is no longer working until I refresh the entire page.

I've tried clearing out the content of the modal entirely using

$("#modal").on('hide.bs.modal', function(e){
    var contentArea = $(this).find('#modalContent');
    contentArea.html('');
});

but it the javascript still does not function upon reopening the modal.

This is the code that defines the modal

<?php
  Modal::begin([
    'header'=>'
Event
',
    'id'=>'modal',
    'size'=>'modal-lg',
    'options'=>[
        'tabindex'=>false
    ]
  ]);
?>

<?php Modal::end(); ?>

And the page being loaded into the modal...

<?php
  $this->registerJsFile('@web/js/registration.js');
?>

<?php $form = ActiveForm::begin([
   'id'=>$model->formName(),
   'action'=>['create-payment'],
   'enableAjaxValidation'=>true,
   'validationUrl'=>['/event/registrant/validate-registrant','event_id'=>$model->event_id],
   'options'=>['data-pjax'=>true],
]); ?>
<input type="hidden" name="form_page" value="level" id="form_page" />

    <?=$this->render('_form_level', [
        'form' => $form,
        'model' => $model,
        'model_code'=>$model_code,
        'list_levels' => $list_levels,
        'list_members' => $list_members,
    ])?>

    <?=$this->render('_form_attendee', [
        'form' => $form,
        'model' => $model,
        'model_organization' => $model_organization,
        'models_attendee' => $models_attendee,
        'models_personal' => $models_personal,
        'models_personalEmail' => $models_personalEmail,
        'models_email' => $models_email,
        'models_answer' => $models_answer,
    ]);?>

The sub-views being rendered contain the fields for the individual form pages (theres 4 in total, cut it down to keep it readable). An example of one of the subviews would be...

    Instructions...

    <?= $form->field($model, 'level_id',['options'=>['class'=>'col-lg-5']])->dropDownList($list_levels['items'],['options'=>$list_levels['attributes']])->label("Select a level"); ?>
    <?= $form->field($model_code, 'code',['options'=>['class'=>'col-lg-5']])->label("Enter a registration code")?>

<?= $form->field($model, 'member_id','inputOptions'=>['data-disabled'=>true]])->dropDownList($list_members)->label("Select a member"); ?>

    <?= Html::button('Continue', ['class' => 'btn btn-primary btn-block btn-lg form-continue', 'data-next'=>'attendee'])?>

Is there something I need to do to reload the javascript file? Any help is much appreciated.

Body:
try this :

$(document).on('hide.bs.modal', '#modal' , function(e){
    var contentArea = $(this).find('#modalContent');
    contentArea.html('');
});


问:
Get CORS preflight request to follow ODATA routing
I'm using Microsoft.AspNet.WebApi.Cors to enable cross origin request for certain actions on certain controllers (both WebApi & OData) using the [EnableCors(...)] attribute.

This works fine for all the WebApi requests and most OData, but on a particular controller we have two POST actions that are given different routes by the [ODataRoute(...)], and the preflight request for either of those actions is returned a 500 error saying that 'Multiple actions were found that match the request. It looks like CORS doesn't know to look for the OData routing.

Has anyone else experienced this problem and come up with a solution?

Here is the route config:

```<code>// Web API routes
config.MapHttpAttributeRoutes();

config.MapODataServiceRoute(
    routeName: "ODataRoute",
    routePrefix: null,
    model: _GetModel());

// Web API configuration and services
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );
</code>```

And here is the controller with the duplicate actions:

```<code>[EnableCors("*", "*", "*")]
[ODataRoute("Action-1")]
[HttpPost]
public async Task<IHttpActionResult> Action(ODataActionParameters parameters, ODataQueryOptions<Guid> options)
{
    ...
}

[EnableCors("*", "*", "*")]
[ODataRoute("Action-2")]
[HttpPost]
public async Task<IHttpActionResult> Action(ODataActionParameters parameters, ODataQueryOptions<Guid> options)
{
    ...
}
</code>```

答:
In the end I just went with Microsoft.Owin.Cors instead, and hard coded a list of paths that I wanted to enable CORS on for the PolicyResolver.

It's not ideal doing it this way, but I think it's going to take an unreasonable amount of time to work out how to get this working properly.

Body:
I'm using Microsoft.AspNet.WebApi.Cors to enable cross origin request for certain actions on certain controllers (both WebApi & OData) using the [EnableCors(...)] attribute.

This works fine for all the WebApi requests and most OData, but on a particular controller we have two POST actions that are given different routes by the [ODataRoute(...)], and the preflight request for either of those actions is returned a 500 error saying that 'Multiple actions were found that match the request. It looks like CORS doesn't know to look for the OData routing.

Has anyone else experienced this problem and come up with a solution?

Here is the route config:

// Web API routes
config.MapHttpAttributeRoutes();

config.MapODataServiceRoute(
    routeName: "ODataRoute",
    routePrefix: null,
    model: _GetModel());

// Web API configuration and services
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );

And here is the controller with the duplicate actions:

[EnableCors("*", "*", "*")]
[ODataRoute("Action-1")]
[HttpPost]
public async Task<IHttpActionResult> Action(ODataActionParameters parameters, ODataQueryOptions<Guid> options)
{
    ...
}

[EnableCors("*", "*", "*")]
[ODataRoute("Action-2")]
[HttpPost]
public async Task<IHttpActionResult> Action(ODataActionParameters parameters, ODataQueryOptions<Guid> options)
{
    ...
}