问:
Apps Script - Send Email - Make content in email bold - Format result of Array.toString in bold
My code sends email notifications every time a Google Form is submitted.  It works, but I want the collected form data as bold in the email.</p>

```<code>for(var i in headers)
    message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";

function sendFormByEmail(e)
{
  var s = SpreadsheetApp.getActiveSheet();
  var headers = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
  var message = "";
  var data = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
  var subject = "";

  //Get active Spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  //Get Sheet called 'Form responses 1'
  var fr1 = ss.getSheetByName("Form responses 1");

  //Get all emails from 'Emails' tab
  var emails = ss.getSheetByName("Emails");
  var numRows = emails.getLastRow();
  var emailTo = emails.getRange(2, 2, numRows, 1).getValues();

  // The variable e holds all the form values in an array.
  // Loop through the array and append values to the body.

  for(var i in headers)
    message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";

  // Insert variables from the spreadsheet into the subject.
  // In this case, I wanted the part number as part of the
  // email subject. These are the 3rd and 16th columns in my form.
  // This creates an email subject like "Parts Inquiry Submission: 729302"
  subject += e.namedValues[headers[1]].toString();

  // Send the email
  MailApp.sendEmail(emailTo, subject, message);

  // Based off of a script originally posted by Amit Agarwal - www.labnol.org
  // Credit to Henrique Abreu for fixing the sort order
}
</code>```

答:
Thank you all for your help.  I ended up changing it up a bit.  Here is what I ended up using.

function sendFormByEmail(e)
{

  var message = "";
  var subject = "";
  var emailTo = "";

  //Gets the active Spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  //Get Sheet called 'Form responses 1'
  var fr1 = ss.getSheetByName("Form responses 1");
  var headers = fr1.getRange(1,1,1,fr1.getLastColumn()).getValues()[0];

  //Get all emails from 'Emails' tab
  var emails = ss.getSheetByName("Emails");
  var emailTo = emails.getRange(2, 2, emails.getLastRow()-1, 1).getValues().toString();

  // For each column in the spreadsheet, add the column name and it's new entry as a line in the email
  message = "";
  for(var i in headers)
    message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "

";
  message += "";

  // Set the subject as the Item Number
  subject = e.namedValues[headers[1]].toString();

  // Send the email
  MailApp.sendEmail({
    to: emailTo,
    subject: subject,
    htmlBody: message
  });

}```

ContentLicense: CC BY-SA 4.0

Body:
My code sends email notifications every time a Google Form is submitted.  It works, but I want the collected form data as bold in the email.

for(var i in headers)
    message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";

function sendFormByEmail(e)
{
  var s = SpreadsheetApp.getActiveSheet();
  var headers = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
  var message = "";
  var data = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
  var subject = "";

  //Get active Spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  //Get Sheet called 'Form responses 1'
  var fr1 = ss.getSheetByName("Form responses 1");

  //Get all emails from 'Emails' tab
  var emails = ss.getSheetByName("Emails");
  var numRows = emails.getLastRow();
  var emailTo = emails.getRange(2, 2, numRows, 1).getValues();

  // The variable e holds all the form values in an array.
  // Loop through the array and append values to the body.

  for(var i in headers)
    message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";

  // Insert variables from the spreadsheet into the subject.
  // In this case, I wanted the part number as part of the
  // email subject. These are the 3rd and 16th columns in my form.
  // This creates an email subject like "Parts Inquiry Submission: 729302"
  subject += e.namedValues[headers[1]].toString();

  // Send the email
  MailApp.sendEmail(emailTo, subject, message);

  // Based off of a script originally posted by Amit Agarwal - www.labnol.org
  // Credit to Henrique Abreu for fixing the sort order
}

Body:
Thank you all for your help.  I ended up changing it up a bit.  Here is what I ended up using.

function sendFormByEmail(e)
{

  var message = "";
  var subject = "";
  var emailTo = "";

  //Gets the active Spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  //Get Sheet called 'Form responses 1'
  var fr1 = ss.getSheetByName("Form responses 1");
  var headers = fr1.getRange(1,1,1,fr1.getLastColumn()).getValues()[0];

  //Get all emails from 'Emails' tab
  var emails = ss.getSheetByName("Emails");
  var emailTo = emails.getRange(2, 2, emails.getLastRow()-1, 1).getValues().toString();

  // For each column in the spreadsheet, add the column name and it's new entry as a line in the email
  message = "<html>";
  for(var i in headers)
    message += headers[i] + ': <b>'+ e.namedValues[headers[i]].toString() + "</b><br><br>";
  message += "</html>";

  // Set the subject as the Item Number
  subject = e.namedValues[headers[1]].toString();

  // Send the email
  MailApp.sendEmail({
    to: emailTo,
    subject: subject,
    htmlBody: message
  });

}


来源: stackexchange

问:
React-Native map data and save all items
I have this code:

```<code>  this.state.viaturas.map((item, index) =>
    this.setState({preco: item.Preco, codigo: item.CodViatura})
  )
</code>```

"preco" is only saving 1 item, when viaturas.map has more than 1 object, and more than 1 item.Preco.
And I want to save all item.Preco of all objects in an array or something.

Sorry for the bad explanation, but I've been dealing with bugs all day and I'm really tired.

答:
You need concat these values to your state on one Array.

ejem:

```<code>this.state.viaturas.map((item, index) =>
    let newItem = {preco: item.Preco, codigo: item.CodViatura}
    this.setState({ stateArray: this.state.stateArray.concat(newItem) }) // Initial state to "stateArray: []"
  )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this code:

  this.state.viaturas.map((item, index) =>
    this.setState({preco: item.Preco, codigo: item.CodViatura})
  )

"preco" is only saving 1 item, when viaturas.map has more than 1 object, and more than 1 item.Preco.
And I want to save all item.Preco of all objects in an array or something.

Sorry for the bad explanation, but I've been dealing with bugs all day and I'm really tired.

Body:
You need concat these values to your state on one Array.

ejem:

this.state.viaturas.map((item, index) =>
    let newItem = {preco: item.Preco, codigo: item.CodViatura}
    this.setState({ stateArray: this.state.stateArray.concat(newItem) }) // Initial state to "stateArray: []"
  )


问:
missing return statement when I run my app in Android Studio
I'm trying to write an app where the user clicks on the marker and starts the camera activity. I've coded this but it does not work, what can I do?
When I try to run this app in Android Studio, I get 2 errors :

Error: missing return statement

And

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
  Compilation failed; see the compiler error output for details.

I've tried to search on Google, but I couldn't find the solution.
Here is my code :

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener {

    private GoogleMap mMap1, mMap2;

    //Other methods removed

    @Override
    public boolean onMarkerClick(final Marker marker){
        if (marker.equals(mMap1)) {
            Intent intent = new Intent(MapsActivity.this, CameraView.class);
            startActivity(intent);
        }
    }
}
</code>```

答:
If you already see the marker on the map then your onMarkerClick() should get their arguments :

```<code>@Override
public boolean onMarkerClick(Marker marker) {

    if (marker.equals(marker))
    {
        Intent intent = new Intent(MapsActivity.this, CameraView.class) ;

        startActivity(intent);

    }
    return false;

}
</code>```

return statement is false indeed.

Body:
I'm trying to write an app where the user clicks on the marker and starts the camera activity. I've coded this but it does not work, what can I do?
When I try to run this app in Android Studio, I get 2 errors :

Error: missing return statement

And

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
  Compilation failed; see the compiler error output for details.

I've tried to search on Google, but I couldn't find the solution.
Here is my code :

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener {

    private GoogleMap mMap1, mMap2;

    //Other methods removed

    @Override
    public boolean onMarkerClick(final Marker marker){
        if (marker.equals(mMap1)) {
            Intent intent = new Intent(MapsActivity.this, CameraView.class);
            startActivity(intent);
        }
    }
}

Body:
If you already see the marker on the map then your onMarkerClick() should get their arguments :

@Override
public boolean onMarkerClick(Marker marker) {

    if (marker.equals(marker))
    {
        Intent intent = new Intent(MapsActivity.this, CameraView.class) ;

        startActivity(intent);

    }
    return false;

}

return statement is false indeed.


问:
Can a DataFrame be converted to Dataset of a case class if a column name contains a space?
I have a Spark DataFrame where a column name contains a space. Is it possible to convert these rows into case classes?

For example, if I do this:

```<code>val data = Seq(1, 2, 3).toDF("a number")
case class Record(`a number`: Int)
data.as[Record]
</code>```

I get this exception:

```<code>org.apache.spark.sql.AnalysisException: cannot resolve '`a$u0020number`' given input columns: [a number];
  at org.apache.spark.sql.catalyst.analysis.package$AnalysisErrorAt.failAnalysis(package.scala:42)
  at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$2.applyOrElse(CheckAnalysis.scala:77)
  at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$2.applyOrElse(CheckAnalysis.scala:74)
  at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$transformUp$1.apply(TreeNode.scala:310)
...
</code>```

Is there any way to do this?

(Of course I can work around this by renaming the column before converting to a case class. I was hoping to have the case class match the input schema exactly.)

答:
Can you try this solution , this worked for me without changing the column name.</p>

```<code>import sqlContext.implicits._
case class Record(`a number`: Int)
val data = Seq(1, 2, 3)
val recDF = data.map(x => Record(x)).toDF()
recDF.collect().foreach(println)

[1]
[2]
[3]
</code>```

Body:
I have a Spark DataFrame where a column name contains a space. Is it possible to convert these rows into case classes?

For example, if I do this:

val data = Seq(1, 2, 3).toDF("a number")
case class Record(`a number`: Int)
data.as[Record]

I get this exception:

org.apache.spark.sql.AnalysisException: cannot resolve '`a$u0020number`' given input columns: [a number];
  at org.apache.spark.sql.catalyst.analysis.package$AnalysisErrorAt.failAnalysis(package.scala:42)
  at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$2.applyOrElse(CheckAnalysis.scala:77)
  at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$2.applyOrElse(CheckAnalysis.scala:74)
  at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$transformUp$1.apply(TreeNode.scala:310)
...

Is there any way to do this?

(Of course I can work around this by renaming the column before converting to a case class. I was hoping to have the case class match the input schema exactly.)

Body:
Can you try this solution , this worked for me without changing the column name.

import sqlContext.implicits._
case class Record(`a number`: Int)
val data = Seq(1, 2, 3)
val recDF = data.map(x => Record(x)).toDF()
recDF.collect().foreach(println)

[1]
[2]
[3]


问:
CSS opacity not applied to Adobe pdf reader opened in iframe
Applying a background to entire page with some transparency does not apply to a pdf opened in an iframe. Why is the PDF not being hidden by the background?

```<code> <iframe src="http://www.irs.gov/pub/irs-tege/401k_mistakes.pdf" />

  <div style="left: 0px; top: 0px;
     z-index: 100;
     background-color: gray;
     width: 1000px;
     height: 1000px;
     position: absolute;
     opacity: 0.8;">
 </div>
</code>```

Here is an example http://jsfiddle.net/JXT5V/3/  (example doesn't work in Chrome)

答: The browser is not rendering that part of the screen, the PDF plugin is. The plugin will not honor your CSS.  Whether the background/transparency renders in front of the plugin's content depends on the interaction between the particular browser and the particular plugin (Adobe isn't the only PDF plugin) and you have no way to control that.</p>

ContentLicense: CC BY-SA 2.5

Body:
Applying a background to entire page with some transparency does not apply to a pdf opened in an iframe. Why is the PDF not being hidden by the background?

Here is an example http://jsfiddle.net/JXT5V/3/  (example doesn't work in Chrome)


问:
Why am I getting an error when I try to print the contents of a file I am searching for?
Can you help me with searching for and printing a file specified by text in textbox1? I have the following code but textbox1 shows me an error. I don't know if the code is correctly written and functioning right.

First class:

```<code>Public Class tisk
    'print
    Public Shared Function printers()
        Dim printThis
        Dim strDir As String
        Dim strFile As String
        Dim Textbox1 As String

        strDir = "C:\_Montix a.s. - cloud\iMontix\Testy"
        strFile = "C:\_Montix a.s. - cloud\iMontix\Testy\" & Textbox1.text & ".lbe"

        If Not fileexprint.FileExists Then
            MsgBox("Soubor neexistuje")
            printers = False
        Else

            fileprint.PrintThisfile()
            printers = True

        End If
    End Function

End Class
</code>```

Second class:

```<code>Public Class fileprint
    Public Shared Function PrintThisfile()
        Dim formname As Long
        Dim FileName As String

        On Error Resume Next
        Dim X As Long
        X = Shell(formname, "Print", FileName, 0&)
    End Function
End Class
</code>```

Third class:

```<code>Public Class fileexprint
    Public Shared Function FileExists()
        Dim fname As Boolean
        '   Returns TRUE if the file exists
        Dim X As String
        X = Dir(fname)
        If X <> "" Then FileExists = True _
        Else FileExists = False
    End Function
End Class
</code>```

When I fill a textbox with text, how can I search for a file in the computer using this text and print this file?

答:
Not sure this will fix your issue, but there are some poor practices in that code that are addressed below. This will certainly get you closer than what you have right now.

```<code>Public Class tisk
    'print
    Public Shared Function printers(ByVal fileName As String) As Boolean
        Dim basePath As String = "C:\_Montix a.s. - cloud\iMontix\Testy"
        Dim filePath As String = IO.Path.Combine(basePath, fileName & ".lbe")

        If IO.File.Exists(filePath) Then
            fileprint.PrintThisfile(filePath)
            Return True
        End If
        'Don't show a message box here. Do it in the calling code
        Return False
    End Function
End Class

Public Class fileprint
    Public Shared Sub PrintThisfile(ByVal fileName As String)
        'Not sure how well this will work, but it has better chances than the original
        Dim p As New Process()
        p.StartInfo.FileName = fileName
        p.StartInfo.Verb = "Print"
        p.Start()
    End Sub
End Class
</code>```

One additional comment on the File.Exists() check. It's actually poor practice to check if the file exists here at all. The file system is volatile. It's possible for things to change in the short time between when you check and when you try to use the file. In addition, whether the file exists is only one thing you need to look at. There's also access permissions and whether the file is locked or in use. The better practice is to just try to do whatever you need with the file, and then handle the exception if it fails.

Body:
Can you help me with searching for and printing a file specified by text in textbox1? I have the following code but textbox1 shows me an error. I don't know if the code is correctly written and functioning right.

First class:

Public Class tisk
    'print
    Public Shared Function printers()
        Dim printThis
        Dim strDir As String
        Dim strFile As String
        Dim Textbox1 As String

        strDir = "C:\_Montix a.s. - cloud\iMontix\Testy"
        strFile = "C:\_Montix a.s. - cloud\iMontix\Testy\" & Textbox1.text & ".lbe"

        If Not fileexprint.FileExists Then
            MsgBox("Soubor neexistuje")
            printers = False
        Else

            fileprint.PrintThisfile()
            printers = True

        End If
    End Function

End Class

Second class:

Public Class fileprint
    Public Shared Function PrintThisfile()
        Dim formname As Long
        Dim FileName As String

        On Error Resume Next
        Dim X As Long
        X = Shell(formname, "Print", FileName, 0&)
    End Function
End Class

Third class:

Public Class fileexprint
    Public Shared Function FileExists()
        Dim fname As Boolean
        '   Returns TRUE if the file exists
        Dim X As String
        X = Dir(fname)
        If X <> "" Then FileExists = True _
        Else FileExists = False
    End Function
End Class

When I fill a textbox with text, how can I search for a file in the computer using this text and print this file?

Body:
Not sure this will fix your issue, but there are some poor practices in that code that are addressed below. This will certainly get you closer than what you have right now.

Public Class tisk
    'print
    Public Shared Function printers(ByVal fileName As String) As Boolean
        Dim basePath As String = "C:\_Montix a.s. - cloud\iMontix\Testy"
        Dim filePath As String = IO.Path.Combine(basePath, fileName & ".lbe")

        If IO.File.Exists(filePath) Then
            fileprint.PrintThisfile(filePath)
            Return True
        End If
        'Don't show a message box here. Do it in the calling code
        Return False
    End Function
End Class

Public Class fileprint
    Public Shared Sub PrintThisfile(ByVal fileName As String)
        'Not sure how well this will work, but it has better chances than the original
        Dim p As New Process()
        p.StartInfo.FileName = fileName
        p.StartInfo.Verb = "Print"
        p.Start()
    End Sub
End Class

One additional comment on the File.Exists() check. It's actually poor practice to check if the file exists here at all. The file system is volatile. It's possible for things to change in the short time between when you check and when you try to use the file. In addition, whether the file exists is only one thing you need to look at. There's also access permissions and whether the file is locked or in use. The better practice is to just try to do whatever you need with the file, and then handle the exception if it fails.


问:
How do I use Selenium Webdriver on headless Chrome?
I'm learning to use Selenium for basic things like taking a screenshot, scraping, and testing and would like to use it with headless Chrome, which is now stable as of Chrome 59.

I have been able to take a screenshot using the 'selenium-webdriver' gem and chromedriver, but not headless.

Here is the ruby script that I am running which hangs after starting to initialize the driver

```<code>require 'rubygems'
require 'selenium-webdriver'

Selenium::WebDriver.logger.level = :debug
p 'initializing driver'
driver = Selenium::WebDriver.for :chrome, switches: %w[--headless --disable-gpu --screenshot --hide-scrollbars]
p 'navigating to Google'
driver.navigate.to "http://google.com"
driver.save_screenshot("./screen.png")
driver.quit
</code>```

and the output  from the logs:

```<code>:> ruby rubytest.rb
"initializing driver"
2017-06-07 15:55:43 DEBUG Selenium Executing Process

["/Users/name/Documents/scrapings/python/env/bin/chromedriver", "--port=9515"]
2017-06-07 15:55:43 DEBUG Selenium polling for socket on ["127.0.0.1", 9515]
Starting ChromeDriver 2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b) on port 9515
Only local connections are allowed.
2017-06-07 15:55:43 INFO Selenium -> POST session
2017-06-07 15:55:43 INFO Selenium    >>> http://127.0.0.1:9515/session | {"desiredCapabilities":{"browserName":"chrome","version":"","platform":"ANY","javascriptEnabled":true,"cssSelectorsEnabled":true,"takesScreenshot":false,"nativeEvents":false,"rotatable":false,"chromeOptions":{"args":["--headless","--disable-gpu","--screenshot","--hide-scrollbars"]}}}
2017-06-07 15:55:43 DEBUG Selenium      > {"Accept"=>"application/json", "Content-Type"=>"application/json; charset=utf-8", "Content-Length"=>"284"}
[RUBY BACKTRACE TO DRIVER INITIALIZATION]
</code>```

I have tried using the JavaScript and Python drivers with similar code and nothing works. When I try this with Python, the error message is

```<code>WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
  (Driver info: chromedriver=2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b),platform=Mac OS X 10.12.5 x86_64)
</code>```

答:
Managed to work through this in the end via various docs, blog posts and gists.

```<code>caps = Selenium::WebDriver::Remote::Capabilities.chrome("desiredCapabilities" => {"takesScreenshot" => true}, "chromeOptions" => {"binary" => "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"})

driver = Selenium::WebDriver.for :chrome, desired_capabilities: caps, switches: %w[--headless --no-sandbox --disable-gpu --remote-debugin-port=9222 --screen-size=1200x800]
</code>```

You need to use a very recent version of Chrome (I'm using Canary) and tell Selenium the path to the binary. You also need to set the desired capabilities for 'takesScreenshot' to true.

Body:
I'm learning to use Selenium for basic things like taking a screenshot, scraping, and testing and would like to use it with headless Chrome, which is now stable as of Chrome 59.

I have been able to take a screenshot using the 'selenium-webdriver' gem and chromedriver, but not headless.

Here is the ruby script that I am running which hangs after starting to initialize the driver

require 'rubygems'
require 'selenium-webdriver'

Selenium::WebDriver.logger.level = :debug
p 'initializing driver'
driver = Selenium::WebDriver.for :chrome, switches: %w[--headless --disable-gpu --screenshot --hide-scrollbars]
p 'navigating to Google'
driver.navigate.to "http://google.com"
driver.save_screenshot("./screen.png")
driver.quit

and the output  from the logs:

:> ruby rubytest.rb
"initializing driver"
2017-06-07 15:55:43 DEBUG Selenium Executing Process

["/Users/name/Documents/scrapings/python/env/bin/chromedriver", "--port=9515"]
2017-06-07 15:55:43 DEBUG Selenium polling for socket on ["127.0.0.1", 9515]
Starting ChromeDriver 2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b) on port 9515
Only local connections are allowed.
2017-06-07 15:55:43 INFO Selenium -> POST session
2017-06-07 15:55:43 INFO Selenium    >>> http://127.0.0.1:9515/session | {"desiredCapabilities":{"browserName":"chrome","version":"","platform":"ANY","javascriptEnabled":true,"cssSelectorsEnabled":true,"takesScreenshot":false,"nativeEvents":false,"rotatable":false,"chromeOptions":{"args":["--headless","--disable-gpu","--screenshot","--hide-scrollbars"]}}}
2017-06-07 15:55:43 DEBUG Selenium      > {"Accept"=>"application/json", "Content-Type"=>"application/json; charset=utf-8", "Content-Length"=>"284"}
[RUBY BACKTRACE TO DRIVER INITIALIZATION]

I have tried using the JavaScript and Python drivers with similar code and nothing works. When I try this with Python, the error message is

WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
  (Driver info: chromedriver=2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b),platform=Mac OS X 10.12.5 x86_64)

Body:
Managed to work through this in the end via various docs, blog posts and gists.

caps = Selenium::WebDriver::Remote::Capabilities.chrome("desiredCapabilities" => {"takesScreenshot" => true}, "chromeOptions" => {"binary" => "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"})

driver = Selenium::WebDriver.for :chrome, desired_capabilities: caps, switches: %w[--headless --no-sandbox --disable-gpu --remote-debugin-port=9222 --screen-size=1200x800]

You need to use a very recent version of Chrome (I'm using Canary) and tell Selenium the path to the binary. You also need to set the desired capabilities for 'takesScreenshot' to true.


问:
How can I implement Basic Authentication with JWT authentication in Spring Boot?
I have built a Spring-Boot application that works with jwt authentication.

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.diplie</groupId>
    <artifactId>rest-api</artifactId>
    <version>1.0.0</version>
    <packaging>war</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.0.RC1</version>
    </parent>

    <properties>
        <springfox-version>2.2.2</springfox-version>
        <java.version>1.8</java.version>
        <maven.test.skip>true</maven.test.skip>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>LATEST</version>
        </dependency>

        <!-- Swagger 2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-version}</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <version>${project.parent.version}</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>repository.springsource.milestone</id>
            <name>SpringSource Milestone Repository</name>
            <url>http://repo.springsource.org/milestone</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>repository.springsource.milestone</id>
            <name>SpringSource Milestone Repository</name>
            <url>http://repo.springsource.org/milestone</url>
        </pluginRepository>
    </pluginRepositories>

</project>
</code>```

I want have a basic authentication, when I use Swagger I want to have a popup with when I click on the Try Out button

For example:

how can use two security(form base,JWT token) filters of spring security on same endpoint?

WebSecurityConfig

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.exceptionHandling().and().anonymous().and().servletApi().and().authorizeRequests()

                // Allow anonymous resource requests
                .antMatchers("/swagger-ui.html").permitAll().antMatchers("/").permitAll()
                .antMatchers("/webjars/springfox-swagger-ui/**").permitAll().antMatchers("/swagger-resources/**")
                .permitAll().antMatchers("/v2/api-docs").permitAll().antMatchers("/favicon.ico").permitAll()
                .antMatchers("**/*.html").permitAll().antMatchers("**/*.css").permitAll().antMatchers("**/*.js")
                .permitAll()

                // Allow anonymous logins
                .antMatchers("/user/User").permitAll().antMatchers("/locality/**").hasAuthority("Admin")
                .antMatchers("/category/**").hasAuthority("Admin").antMatchers("/item").hasAuthority("Item")
                .antMatchers("/item/userItems").hasAuthority("Item").antMatchers("item/lookFor").permitAll()
                .antMatchers("item/items").hasAuthority("User")

                // All other request need to be authenticated
                .anyRequest().authenticated().and()
                // And filter other requests to check the presence of JWT in
                // header
                .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // Créer un compte par défaut
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
    }
}
</code>```

TokenAuthenticationService

```<code>public class TokenAuthenticationService {

    static ResourceBundle bundle = ResourceBundle.getBundle("application");

    static void addAuthentication(HttpServletResponse res, String username) {

        String JWT = Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + getExpirationTime()))
                .signWith(SignatureAlgorithm.HS512, getSecret()).compact();
        res.addHeader(getHeaderString(), getTokenPrefix() + " " + JWT);
    }

    static Authentication getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(getHeaderString());
        if (token != null) {
            // Analyse du jeton.
            String user = Jwts.parser().setSigningKey(getSecret()).parseClaimsJws(token.replace(getTokenPrefix(), ""))
                    .getBody().getSubject();
            return user != null ? new UsernamePasswordAuthenticationToken(user, null, emptyList()) : null;
        }
        return null;
    }

    /**
     * @return the secret
     */
    public static String getSecret() {
        return bundle.getString("secret");
    }

    /**
     * @return the expirationTime
     */
    public static long getExpirationTime() {
        return Long.valueOf(bundle.getString("expiration.time"));
    }

    /**
     * @return the tokenPrefix
     */
    public static String getTokenPrefix() {
        return bundle.getString("token.prefix");
    }

    /**
     * @return the headerString
     */
    public static String getHeaderString() {
        return bundle.getString("header.string");
    }

}
</code>```

JWTLoginFilter

```<code>public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {

    public JWTLoginFilter(String url, AuthenticationManager authManager) {
        super(new AntPathRequestMatcher(url));
        setAuthenticationManager(authManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException, IOException, ServletException {
        AccountCredentials creds = new ObjectMapper().readValue(req.getInputStream(), AccountCredentials.class);
        return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(),
                creds.getPassword(), Collections.emptyList()));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
            Authentication auth) throws IOException, ServletException {
        TokenAuthenticationService.addAuthentication(res, auth.getName());
    }
}
</code>```

JWTAuthenticationFilter

```<code>public class JWTAuthenticationFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        Authentication authentication = TokenAuthenticationService.getAuthentication((HttpServletRequest) request);

        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}
</code>```

AccountCredentials

```<code>public class AccountCredentials {

    private String username;
    private String password;

    /**
     *
     */
    public AccountCredentials() {
        super();
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username
     *            the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password
     *            the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

}
</code>```

答:
You will have to create two different WebSecurityConfigurerAdapter configurations with different root URLs. If the URLs overlap (ie /admin and /**) then you will need to define priority by using @Order annotation on the configuration.

Here's a working example for HTTP Basic and Form based authentication.

https://github.com/ConsciousObserver/TestMultipleLoginPagesFormAndBasic.git

```<code>package com.test;

import javax.servlet.http.HttpSession;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@SpringBootApplication
public class TestMultipleLoginPagesApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestMultipleLoginPagesApplication.class, args);
    }
}

@Controller
class MvcController {
    @RequestMapping(path="form/formLogin", method=RequestMethod.GET)
    public String formLoginPage() {
        return "formLogin";
    }

    @RequestMapping(path="form/formHome", method=RequestMethod.GET)
    public String formHomePage() {
        return "formHome";
    }

    @RequestMapping(path="basic/basicHome", method=RequestMethod.GET)
    public String userHomePage() {
        return "basicHome";
    }

    @RequestMapping(path="basic/logout", method=RequestMethod.GET)
    public String userLogout(HttpSession session) {
        session.invalidate();
        return "basicLogout";
    }
}

@Configuration
@Order(1)
class FormSecurity extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/form/**")
            .authorizeRequests()
                .anyRequest().hasRole("FORM_USER")
            .and()
            .formLogin()
                .loginPage("/form/formLogin").permitAll()
                .loginProcessingUrl("/form/formLoginPost").permitAll()
                .defaultSuccessUrl("/form/formHome")
            .and()
                .logout().logoutUrl("/form/logout").logoutSuccessUrl("/form/formLogin")
            .and()
            .httpBasic().disable()
            .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user")
            .password("test")
            .roles("FORM_USER");
    }
}

@Configuration
@Order(2)
class BasicAuthSecurity extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/basic/**")
            .authorizeRequests()
            .anyRequest().hasRole("BASIC_USER")
            .antMatchers("/basic/logout").permitAll()
            .and()
                .httpBasic()
            .and()
                .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("basic_user")
            .password("test")
            .roles("BASIC_USER");
    }
}

@Configuration
@Order(3)
class RootUrlSecurity extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*
         * Put any security expectations from the root URL here, currently everything is permitted.
         * Since it's the last in the order /form/** and /basic/** have a priority over it.
         */
        http.antMatcher("/**")
            .authorizeRequests()
                .anyRequest().permitAll();
    }
}
</code>```

Note: Since these login pages are not from different applications, they share the SecurityContextHolder or the security context. So if you login from one login page and then try to go the protected resource of the other, you won't be redirected to the next login page. Instead you'll get the 403 (depending on the roles assigned by the different login pages). At a time only one login session can be maintained.

Body:
I have built a Spring-Boot application that works with jwt authentication.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.diplie</groupId>
    <artifactId>rest-api</artifactId>
    <version>1.0.0</version>
    <packaging>war</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.0.RC1</version>
    </parent>

    <properties>
        <springfox-version>2.2.2</springfox-version>
        <java.version>1.8</java.version>
        <maven.test.skip>true</maven.test.skip>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>LATEST</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-version}</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <version>${project.parent.version}</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>repository.springsource.milestone</id>
            <name>SpringSource Milestone Repository</name>
            <url>http://repo.springsource.org/milestone</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>repository.springsource.milestone</id>
            <name>SpringSource Milestone Repository</name>
            <url>http://repo.springsource.org/milestone</url>
        </pluginRepository>
    </pluginRepositories>

</project>

I want have a basic authentication, when I use Swagger I want to have a popup with when I click on the Try Out button

For example:

how can use two security(form base,JWT token) filters of spring security on same endpoint?

WebSecurityConfig

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.exceptionHandling().and().anonymous().and().servletApi().and().authorizeRequests()

                // Allow anonymous resource requests
                .antMatchers("/swagger-ui.html").permitAll().antMatchers("/").permitAll()
                .antMatchers("/webjars/springfox-swagger-ui/**").permitAll().antMatchers("/swagger-resources/**")
                .permitAll().antMatchers("/v2/api-docs").permitAll().antMatchers("/favicon.ico").permitAll()
                .antMatchers("**/*.html").permitAll().antMatchers("**/*.css").permitAll().antMatchers("**/*.js")
                .permitAll()

                // Allow anonymous logins
                .antMatchers("/user/User").permitAll().antMatchers("/locality/**").hasAuthority("Admin")
                .antMatchers("/category/**").hasAuthority("Admin").antMatchers("/item").hasAuthority("Item")
                .antMatchers("/item/userItems").hasAuthority("Item").antMatchers("item/lookFor").permitAll()
                .antMatchers("item/items").hasAuthority("User")

                // All other request need to be authenticated
                .anyRequest().authenticated().and()
                // And filter other requests to check the presence of JWT in
                // header
                .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // Créer un compte par défaut
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
    }
}

TokenAuthenticationService

public class TokenAuthenticationService {

    static ResourceBundle bundle = ResourceBundle.getBundle("application");

    static void addAuthentication(HttpServletResponse res, String username) {

        String JWT = Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + getExpirationTime()))
                .signWith(SignatureAlgorithm.HS512, getSecret()).compact();
        res.addHeader(getHeaderString(), getTokenPrefix() + " " + JWT);
    }

    static Authentication getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(getHeaderString());
        if (token != null) {
            // Analyse du jeton.
            String user = Jwts.parser().setSigningKey(getSecret()).parseClaimsJws(token.replace(getTokenPrefix(), ""))
                    .getBody().getSubject();
            return user != null ? new UsernamePasswordAuthenticationToken(user, null, emptyList()) : null;
        }
        return null;
    }

    /**
     * @return the secret
     */
    public static String getSecret() {
        return bundle.getString("secret");
    }

    /**
     * @return the expirationTime
     */
    public static long getExpirationTime() {
        return Long.valueOf(bundle.getString("expiration.time"));
    }

    /**
     * @return the tokenPrefix
     */
    public static String getTokenPrefix() {
        return bundle.getString("token.prefix");
    }

    /**
     * @return the headerString
     */
    public static String getHeaderString() {
        return bundle.getString("header.string");
    }

}

JWTLoginFilter

public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {

    public JWTLoginFilter(String url, AuthenticationManager authManager) {
        super(new AntPathRequestMatcher(url));
        setAuthenticationManager(authManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException, IOException, ServletException {
        AccountCredentials creds = new ObjectMapper().readValue(req.getInputStream(), AccountCredentials.class);
        return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(),
                creds.getPassword(), Collections.emptyList()));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
            Authentication auth) throws IOException, ServletException {
        TokenAuthenticationService.addAuthentication(res, auth.getName());
    }
}

JWTAuthenticationFilter

public class JWTAuthenticationFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        Authentication authentication = TokenAuthenticationService.getAuthentication((HttpServletRequest) request);

        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}

AccountCredentials

public class AccountCredentials {

    private String username;
    private String password;

    /**
     *
     */
    public AccountCredentials() {
        super();
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username
     *            the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password
     *            the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

}

Body:
You will have to create two different WebSecurityConfigurerAdapter configurations with different root URLs. If the URLs overlap (ie /admin and /**) then you will need to define priority by using @Order annotation on the configuration.

Here's a working example for HTTP Basic and Form based authentication.

https://github.com/ConsciousObserver/TestMultipleLoginPagesFormAndBasic.git

package com.test;

import javax.servlet.http.HttpSession;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@SpringBootApplication
public class TestMultipleLoginPagesApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestMultipleLoginPagesApplication.class, args);
    }
}

@Controller
class MvcController {
    @RequestMapping(path="form/formLogin", method=RequestMethod.GET)
    public String formLoginPage() {
        return "formLogin";
    }

    @RequestMapping(path="form/formHome", method=RequestMethod.GET)
    public String formHomePage() {
        return "formHome";
    }

    @RequestMapping(path="basic/basicHome", method=RequestMethod.GET)
    public String userHomePage() {
        return "basicHome";
    }

    @RequestMapping(path="basic/logout", method=RequestMethod.GET)
    public String userLogout(HttpSession session) {
        session.invalidate();
        return "basicLogout";
    }
}

@Configuration
@Order(1)
class FormSecurity extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/form/**")
            .authorizeRequests()
                .anyRequest().hasRole("FORM_USER")
            .and()
            .formLogin()
                .loginPage("/form/formLogin").permitAll()
                .loginProcessingUrl("/form/formLoginPost").permitAll()
                .defaultSuccessUrl("/form/formHome")
            .and()
                .logout().logoutUrl("/form/logout").logoutSuccessUrl("/form/formLogin")
            .and()
            .httpBasic().disable()
            .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user")
            .password("test")
            .roles("FORM_USER");
    }
}

@Configuration
@Order(2)
class BasicAuthSecurity extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/basic/**")
            .authorizeRequests()
            .anyRequest().hasRole("BASIC_USER")
            .antMatchers("/basic/logout").permitAll()
            .and()
                .httpBasic()
            .and()
                .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("basic_user")
            .password("test")
            .roles("BASIC_USER");
    }
}

@Configuration
@Order(3)
class RootUrlSecurity extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*
         * Put any security expectations from the root URL here, currently everything is permitted.
         * Since it's the last in the order /form/** and /basic/** have a priority over it.
         */
        http.antMatcher("/**")
            .authorizeRequests()
                .anyRequest().permitAll();
    }
}

Note: Since these login pages are not from different applications, they share the SecurityContextHolder or the security context. So if you login from one login page and then try to go the protected resource of the other, you won't be redirected to the next login page. Instead you'll get the 403 (depending on the roles assigned by the different login pages). At a time only one login session can be maintained.


问:
jQuery delay function call until element is in view (showing)
I'm showing a circular progress bar that when animated spins around a circular axis from 0 - 1000 so if I set the function at 913 then it spins to 91.3% of the full circle. All this works great BUT it's low down on the page so I need it to start when it reaches the div holding it.

I have tried and here is what I have but at the moment the function does not even run.

```<code>$("body").scroll(function() {

 var scrolledpx = parseInt($("body").scrollTop());
 var p = $("#housePoints");
 var offset = p.offset();

 if(scrolledpx == offset.top )

 {

 // function for progress bar
 var bar = new ProgressBar.Circle(oak, {
   color: '#E44024',
   // This has to be the same size as the maximum width to
   // prevent clipping
   strokeWidth: 4,
   trailWidth: 1,
   easing: 'easeInOut',
   duration: 1400,
   text: {
     autoStyleContainer: false
   },
   from: { color: '#e3ebf7', width: 1 },
   to: { color: '#E44024', width: 4 },
   // Set default step function for all animate calls
   step: function(state, circle) {
     circle.path.setAttribute('stroke', state.color);
     circle.path.setAttribute('stroke-width', state.width);

     var value = Math.round(circle.value() * 1000);
     if (value === 0) {
       circle.setText('');
     } else {
       circle.setText(value);
     }

   }
 });

 bar.animate(0.913);  // Number from 0.000 to 1.000

}

})
</code>```

As I say, the ID of the container is #housePoints and I'd like this animation to run when it comes into view. Maybe even as far as it reaches the bottom of the div in view and their is some padding on the div of 100px top and bottom so might still run when just the top is reached and the user still misses it.

Thanks for any help.
gb

答:
You could try binding your progress circle in the .show() (example. jQuery('#housePoints').show() ) method as explained in the answer to this question.

https://stackoverflow.com/a/1225238/2512022

Body:
I'm showing a circular progress bar that when animated spins around a circular axis from 0 - 1000 so if I set the function at 913 then it spins to 91.3% of the full circle. All this works great BUT it's low down on the page so I need it to start when it reaches the div holding it.

I have tried and here is what I have but at the moment the function does not even run.

$("body").scroll(function() {

 var scrolledpx = parseInt($("body").scrollTop());
 var p = $("#housePoints");
 var offset = p.offset();

 if(scrolledpx == offset.top )

 {

 // function for progress bar
 var bar = new ProgressBar.Circle(oak, {
   color: '#E44024',
   // This has to be the same size as the maximum width to
   // prevent clipping
   strokeWidth: 4,
   trailWidth: 1,
   easing: 'easeInOut',
   duration: 1400,
   text: {
     autoStyleContainer: false
   },
   from: { color: '#e3ebf7', width: 1 },
   to: { color: '#E44024', width: 4 },
   // Set default step function for all animate calls
   step: function(state, circle) {
     circle.path.setAttribute('stroke', state.color);
     circle.path.setAttribute('stroke-width', state.width);

     var value = Math.round(circle.value() * 1000);
     if (value === 0) {
       circle.setText('');
     } else {
       circle.setText(value);
     }

   }
 });

 bar.animate(0.913);  // Number from 0.000 to 1.000

}

})

As I say, the ID of the container is #housePoints and I'd like this animation to run when it comes into view. Maybe even as far as it reaches the bottom of the div in view and their is some padding on the div of 100px top and bottom so might still run when just the top is reached and the user still misses it.

Thanks for any help.
gb


问:
Using decimal/money field types in InfoPath 2010
I'm building a form that contains a large number of fields that will hold money values - for some bizarre reason I can't quite comprehend, InfoPath 2010 doesn't provide a "decimal" or "money" field type to use, out of the box. (The decimal type provided has (double) in brackets next to it, which indicates to me it will be stored using floating point arithmetic).

If I create a xsd from scratch and use that to create a form in InfoPath, it accepts <xsd:decimal> without issue, but I am no longer able to add fields from within infopath, which is frustrating.

So my question is, is there any way to use decimal/money types in InfoPath 2010 without resorting to writing my own xsd -or- is there some way to allow myself to add new fields after creating an InfoPath form from a xsd?

Some way to "import a custom field type" from an xsd to reuse over and over again in an infopath form would probably also solve the issue - then i could just import a "customType" that is of basetype xsd:decimal and reuse that all over my forms...

答:
Unfortunately it is a problem (for lack of a better term) in XPath (not InfoPath/XML or MS specific). So even if you figured out a way to create your own type I think the processing engine internally would still convert it back to double anytime you tried to access and create the same floating point problems you have now.

Check out this article that uses rounding to solve (sort of) the problem. Not the most elegant solution but I think it is what you are stuck with as far as InfoPath goes.
http://blogs.msdn.com/b/infopath/archive/2008/04/17/invalid-data-error-when-calculating-the-result-of-2-or-more-fields.aspx


问:
Kotlin Renaming Generated Getters and Setters
Is there a way to rename the default getters and setters in Kotlin? I have a property named in snake_case, but I still want the getters and setters to be named in camelCase.

The closest I've gotten is something like

```<code>private var property_name = Color.BLACK
private set
fun setPropertyName(c: Color) { property_name = c }
fun getPropertyName() = property_name
</code>```

Is there a way to do this without hiding the getters and setters and defining new methods?

答:
If you just want to change the name and not the functionality, you can also scope the annotation like so:</p>

```<code>@get:JvmName("getPropertyName")
@set:JvmName("setPropertyName")
var property_name = Color.BLACK
</code>```

Body:
Is there a way to rename the default getters and setters in Kotlin? I have a property named in snake_case, but I still want the getters and setters to be named in camelCase.

The closest I've gotten is something like

private var property_name = Color.BLACK
private set
fun setPropertyName(c: Color) { property_name = c }
fun getPropertyName() = property_name

Is there a way to do this without hiding the getters and setters and defining new methods?

Body:
If you just want to change the name and not the functionality, you can also scope the annotation like so:

@get:JvmName("getPropertyName")
@set:JvmName("setPropertyName")
var property_name = Color.BLACK


问:
How do you reverse an iterator's flow?
Is it possible to access the previous value of an iterator, for example:

```<code>function* gen () {
   yield* [0,1,2,3]
}

var it = gen();

it.next().value // 0
it.next().value // 1
it.last().value // would be awesome if this was 0
</code>```

This is strictly a curiosity question. I've been playing with generators lately and was wondering if anyone uses generators/iterators in this manner?

If so, I would love to see your solution. (Doesn't need to follow the above syntax) -Thanks

答:
JS iterators only know one direction: forwards. Meaning, if you would want to use your custom iterator with a for-loop or the like, it would ignore your custom properties. You could however create your own custom iterator for your own use only:</p>

```<code>const obj = {
   values: [0,1,2,3],
   [Symbol.iterator]() {
     const values = this.values;
     const min = 0;
     const max = values.length - 1;

     let index = -1;

     return {
       next() {
        index = Math.min(index + 1, max);
        return { value: values[index], done: index >= max };
       },
       prev() {
        index = Math.max(index - 1, min);
        return { value: values[index], done: index <= min };
       }
     }
   }
}

var it = obj[Symbol.iterator]();

console.log(it.next().value); // 0
console.log(it.next().value); // 1
console.log(it.prev().value); // would be awesome if this was 0
console.log(it.prev().value); // would be awesome if this was 0
console.log(it.prev().value); // would be awesome if this was 0
console.log(it.next().value); // would be awesome if this was 1
</code>```

Title: How do you reverse an iterator's flow?

Body:
Is it possible to access the previous value of an iterator, for example:

function* gen () {
   yield* [0,1,2,3]
}

var it = gen();

it.next().value // 0
it.next().value // 1
it.last().value // would be awesome if this was 0

This is strictly a curiosity question. I've been playing with generators lately and was wondering if anyone uses generators/iterators in this manner?

If so, I would love to see your solution. (Doesn't need to follow the above syntax) -Thanks

Body:
JS iterators only know one direction: forwards. Meaning, if you would want to use your custom iterator with a for-loop or the like, it would ignore your custom properties. You could however create your own custom iterator for your own use only:

const obj = {
   values: [0,1,2,3],
   [Symbol.iterator]() {
     const values = this.values;
     const min = 0;
     const max = values.length - 1;

     let index = -1;

     return {
       next() {
        index = Math.min(index + 1, max);
        return { value: values[index], done: index >= max };
       },
       prev() {
        index = Math.max(index - 1, min);
        return { value: values[index], done: index <= min };
       }
     }
   }
}

var it = obj[Symbol.iterator]();

console.log(it.next().value); // 0
console.log(it.next().value); // 1
console.log(it.prev().value); // would be awesome if this was 0
console.log(it.prev().value); // would be awesome if this was 0
console.log(it.prev().value); // would be awesome if this was 0
console.log(it.next().value); // would be awesome if this was 1


问:
Odoo- Add domain filter on field after creating
I am new to odoo, I have two drop downs in my models, which are loaded from res.users . What i want to do is that when someone select 'Administrator' or any other user in first_approver then that select user should be removed from second_approver drop down

```<code>class test(models.Model):
_name = 'test.test'

name = fields.Char()
first_approver = fields.Many2one('res.users')
second_approver = fields.Many2one('res.users')
</code>```

I think it could be done by adding domain filter on second_approver but i don't know how to update field definition in onChange method

答:
If you want domain then apply following

```<code>first_approver= fields.Many2one('res.users')
second_approve= fields.Many2one('res.users', domain="[('id', '!=', first_approver)]")
</code>```

So the first_approver will not display in second_approver field.

Additional field options and other development help can be found in the Odoo Documentation.

Body:
I am new to odoo, I have two drop downs in my models, which are loaded from res.users . What i want to do is that when someone select 'Administrator' or any other user in first_approver then that select user should be removed from second_approver drop down

class test(models.Model):
_name = 'test.test'

name = fields.Char()
first_approver = fields.Many2one('res.users')
second_approver = fields.Many2one('res.users')

I think it could be done by adding domain filter on second_approver but i don't know how to update field definition in onChange method

Body:
If you want domain then apply following

first_approver= fields.Many2one('res.users')
second_approve= fields.Many2one('res.users', domain="[('id', '!=', first_approver)]")

So the first_approver will not display in second_approver field.

Additional field options and other development help can be found in the Odoo Documentation.


问:
C - a NON INT function example?
Unfortunately all of the  " C function examples " I come across are about "int"s (numbers).

I need a STRING example of a function.

This is a INT example:  ( works )

```<code>int cube(int n){
return n*n*n;
}

int o=1;
o = cube(2);
</code>```

I want a STRING example. I attempted to modify the above .. but I FAILED.

```<code>char cube(char n){
return n;
}

char *o;
o = cube("string");
</code>```

答:
snprintf is a useful library function taking both integers and strings as argument.

strdup is a useful POSIX (& Linux) function taking and returning a string.

Here is an example of a function which returns a dynamically allocated string (to be later free-d, see free(3) & malloc(3)....) and get a string as argument.

```<code>char* stammer(char *inp) {
 size_t ln = strlen(inp);
 char* res = malloc(2*ln+1);
 if (!res) { perror ("malloc stammer"); exit(EXIT_FAILURE); };
 strcpy(res, inp);
 strcat(res, inp);
 return res;
}
</code>```

So stammer("foo") returns a dynamically allocated string containing "foofoo". You are then establishing the convention (which you'll better document, at least as some comment) that the returned (pointer) value should be at some later appropriate time passed to free.

NB. Read more about arrays decaying into pointers in C. A string is conceptually a zero-terminated array (or sequence) of char-s, and practically often a valid pointer into it.

Title: C - a NON INT function example?

Body:
Unfortunately all of the  " C function examples " I come across are about "int"s (numbers).

I need a STRING example of a function.

This is a INT example:  ( works )

int cube(int n){
return n*n*n;
}

int o=1;
o = cube(2);

I want a STRING example. I attempted to modify the above .. but I FAILED.

char cube(char n){
return n;
}

char *o;
o = cube("string");

Body:
snprintf is a useful library function taking both integers and strings as argument.

strdup is a useful POSIX (& Linux) function taking and returning a string.

Here is an example of a function which returns a dynamically allocated string (to be later free-d, see free(3) & malloc(3)....) and get a string as argument.

char* stammer(char *inp) {
 size_t ln = strlen(inp);
 char* res = malloc(2*ln+1);
 if (!res) { perror ("malloc stammer"); exit(EXIT_FAILURE); };
 strcpy(res, inp);
 strcat(res, inp);
 return res;
}

So stammer("foo") returns a dynamically allocated string containing "foofoo". You are then establishing the convention (which you'll better document, at least as some comment) that the returned (pointer) value should be at some later appropriate time passed to free.

NB. Read more about arrays decaying into pointers in C. A string is conceptually a zero-terminated array (or sequence) of char-s, and practically often a valid pointer into it.


问:
Does a foreign key reduce redundancy if all the columns are referenced?
I've read that one of the benefits of normalization is to reduce redundancy in the DB. But I'm wondering, if you end up referencing all the columns in the target table?

For example, if I have a Video table that references a Genre table, the Genre table might very likely have a single column with a dozen fairly static values like 'Horror' 'Sci-Fi' 'Romance' etc.

In a case like this, does it save any space to separate the two, or is the only benefit making it so you can update all referencing rows from one place?

答:
Data modification anomalies

What if you add a new genre?

Is Sci-Fi the same as SciFi?

Is Sci-Fi the same as Sci-fi?

It gets worse if you another table, say, "Books" that have the same Genres.


问:
add authorization header in client browser request on click of
I would like to add 'authorization' header in each client request made with browser on click of Some Link. And these requests are not ajax based.

For example,

    When I access 'domain/sample' directly through URL bar, the 'authorization' header should not set. But when I'm click  , the 'authorization' header should set with some value.
And I would like to do it with basic HTML, Javascript, and Jquery.

答:
This cannot be accomplished with HTML, JavaScript or JQuery.

HTTP headers are sent long before HTML is parsed or rendered, let alone running scripts.

You can send authorisation headers from the server configuration (.htaccess, etc.) or from a script running at the server, like PHP.

Title: add authorization header in client browser request on click of <a href="">


问:
How to remove all double spaces from the text
I'm struggeling a bit with my homework. In one task we have to correct a text. We have to remove multiple spaces from the text and turn that into one space. And if there is the space at the beginning or at the end we have to do the same. I have created this function:

```<code>function clean(word) {
  var output = "";
  for (var x = 0; x < word.length; x++)
  {
      if (word.charAt(x) !== " " || word.charAt(x + 1) !== " ") {
        output = output + word.charAt(x);
      }
  }

  return output;
}
console.log("test = " + clean(" test  word  testing   more"));
</code>```

This works for all the spaces in the text but not at the begionning and end. Also it would be better if I do not use the number of the character directly (x) but I can do it if I don't find another way...

答:
A slightly simpler replace:

var str = 'a  test string   with multiple      extra  spaces'
console.log(str.replace(/  +/g, ' '));```

This is leveraging something called regular expressions (Often referred to as regex) - which is basically pattern matching.

This code /  +/g is saying [a space][1 or more spaces], with the g flag meaning "match all". The 2 slashes are the shorthand method for saying "this is a regular expressions".

Body:
I'm struggeling a bit with my homework. In one task we have to correct a text. We have to remove multiple spaces from the text and turn that into one space. And if there is the space at the beginning or at the end we have to do the same. I have created this function:

function clean(word) {
  var output = "";
  for (var x = 0; x < word.length; x++)
  {
      if (word.charAt(x) !== " " || word.charAt(x + 1) !== " ") {
        output = output + word.charAt(x);
      }
  }

  return output;
}
console.log("test = " + clean(" test  word  testing   more"));

This works for all the spaces in the text but not at the begionning and end. Also it would be better if I do not use the number of the character directly (x) but I can do it if I don't find another way...

Body:
A slightly simpler replace:

var str = 'a  test string   with multiple      extra  spaces'
console.log(str.replace(/  +/g, ' '));

This is leveraging something called regular expressions (Often referred to as regex) - which is basically pattern matching.

This code /  +/g is saying [a space][1 or more spaces], with the g flag meaning "match all". The 2 slashes are the shorthand method for saying "this is a regular expressions".


问:
Module not found: Can't resolve react-raphael-map
Im trying to use react-raphael-map over creat-react-app but apear the the problem

./src/App.js
Module not found: Can't resolve 'react-raphael-map' in 'C:\workspace\maptestproject\src'

I ran create-react-app maptestproject;

Then npm install --save raphael

Then npm install --save react-raphael-map

And the App.js was modified to:

```<code>import React, { Component } from 'react';
import Map from 'react-raphael-map';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    var china= {
        aomen: {
            name: "澳门",
            path: "M413.032...",
            yy: 10
        },
        hk:{
            name: "香港",
            path: "M417.745...",
            xx: 20
        },
        taiwan: {
            name: "台湾",
            path: "M505.438..."
        },
        guangdong: {
            name: "广东",
            path: "M391.37...",
            yy: -10
        },
        guangxi: {
            name: "广西",
            path: "M305.646..."
        }
    }

    return (<Map data={china} width={480} height={560} />)
  }
}

export default App;
</code>```

In his example the react-raphael-map has babel and webpack files in his structure, by the way create-react-app doesnt. Is it necessary?

Someone how to solve?

答: The problem was in node_modules\react-raphael-map, on package.json file the line "main": "index.js" line points to index.js but there's no. The index.js is inside node_modules\react-raphael-map\lib.

Body:
Im trying to use react-raphael-map over creat-react-app but apear the the problem

./src/App.js
Module not found: Can't resolve 'react-raphael-map' in 'C:\workspace\maptestproject\src'

I ran create-react-app maptestproject;

Then npm install --save raphael

Then npm install --save react-raphael-map

And the App.js was modified to:

import React, { Component } from 'react';
import Map from 'react-raphael-map';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    var china= {
        aomen: {
            name: "澳门",
            path: "M413.032...",
            yy: 10
        },
        hk:{
            name: "香港",
            path: "M417.745...",
            xx: 20
        },
        taiwan: {
            name: "台湾",
            path: "M505.438..."
        },
        guangdong: {
            name: "广东",
            path: "M391.37...",
            yy: -10
        },
        guangxi: {
            name: "广西",
            path: "M305.646..."
        }
    }

    return (<Map data={china} width={480} height={560} />)
  }
}

export default App;

In his example the react-raphael-map has babel and webpack files in his structure, by the way create-react-app doesnt. Is it necessary?

Someone how to solve?


答:
Try this:</p>

```<code>char *cube(char *n){
return n;
}

char *o;
o = cube("string");
</code>```

Title: C - a NON INT function example?

Body:
Try this:

char *cube(char *n){
return n;
}

char *o;
o = cube("string");


问:
What does #, fuzzy mean at the top of a xgettext-generated .pot file?
When using xgettext to generate a .pot file, at the top of the generated file I get this:

```<code># SOME DESCRIPTIVE TITLE.
...
#, fuzzy
...
</code>```

What does the #, fuzzy mean?

I know what it means if a translation is fuzzy (it is poor quality), but what does it mean at the top of a .pot file?

答:
xgettext adds the #, fuzzy entry at the top when it auto-generates a project header in the message file. The comment has no special meaning, per se: it's just noting that a human needs to come along and fill in the gaps.

Let's dig a little deeper into the source.

When you first create a message file, xgettext adds project information to the top of the generated message file (unless you pass --omit-header):

```<code>$ cat hello.c
int main() {
  printf(gettext("Hello World\n"));
  return 0;
}

$ xgettext -o- hello.c
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-06-08 11:51-0400\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"

#: hello.c:3
#, c-format
msgid "Hello World\n"
msgstr ""
</code>```

The logic backing this is found in xgettext.c:construct_header(). Way down at the bottom of that function, the newly-generated header information is marked fuzzy:

```<code>mp->is_fuzzy = true;
</code>```

Since this text has been marked as fuzzy, the #, fuzzy comment tag is added to the text. The intent here is to raise awareness: a computer program added text to the message file, and a human needs to take action. In particular, a human needs to come along and fill in the blanks: revision date, translator name, language, and so on.

Using the "#, fuzzy" annotation makes sense in this context, as per the docs:

[Fuzzy entries] usually call for revision by the translator.

Body:
When using xgettext to generate a .pot file, at the top of the generated file I get this:

# SOME DESCRIPTIVE TITLE.
...
#, fuzzy
...

What does the #, fuzzy mean?

I know what it means if a translation is fuzzy (it is poor quality), but what does it mean at the top of a .pot file?

Body:
xgettext adds the #, fuzzy entry at the top when it auto-generates a project header in the message file. The comment has no special meaning, per se: it's just noting that a human needs to come along and fill in the gaps.

Let's dig a little deeper into the source.

When you first create a message file, xgettext adds project information to the top of the generated message file (unless you pass --omit-header):

$ cat hello.c
int main() {
  printf(gettext("Hello World\n"));
  return 0;
}

$ xgettext -o- hello.c
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-06-08 11:51-0400\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"

#: hello.c:3
#, c-format
msgid "Hello World\n"
msgstr ""

The logic backing this is found in xgettext.c:construct_header(). Way down at the bottom of that function, the newly-generated header information is marked fuzzy:

mp->is_fuzzy = true;

Since this text has been marked as fuzzy, the #, fuzzy comment tag is added to the text. The intent here is to raise awareness: a computer program added text to the message file, and a human needs to take action. In particular, a human needs to come along and fill in the blanks: revision date, translator name, language, and so on.

Using the "#, fuzzy" annotation makes sense in this context, as per the docs:

[Fuzzy entries] usually call for revision by the translator.


答:
Here is a very simple example

```<code>char *return_a_string()
{
    return "string";
}

char *o;
o = return_a_string();
printf("%s\n", o);
</code>```

Beware, however, that if you want to return a non-constant string -- that is, if you want your function to dynamically construct the string it returns -- this is more complicated because you have to (have to!) worry about memory allocation.

Title: C - a NON INT function example?

Body:
Here is a very simple example

char *return_a_string()
{
    return "string";
}

char *o;
o = return_a_string();
printf("%s\n", o);

Beware, however, that if you want to return a non-constant string -- that is, if you want your function to dynamically construct the string it returns -- this is more complicated because you have to (have to!) worry about memory allocation.


问:
Build Ionic Application From Xcode Project
I'm building an iOS application using Xcode/Swift, and I have a few less-than-technical group members who don't really know how to build Xcode projects, but are interested in seeing/testing the progress of the application.  One group member pointed out that they could test the app using Ionic/Ionic View.  However, to my understanding, Ionic works by building an application in the specific Ionic framework, and then Ionic translates the project into an Xcode/Swift project (.xcodeproj) or an Android project.  Is there a way to do the reverse conversion––is there a way to convert my Xcode project so that it will work on Ionic, or specifically Ionic View?  </p>

答:
'Ionic View' is a very good advice and the one I would suggest in your case as well.

You don't have to do anything in your code really to use it, just create an ionic account and in your terminal, change into your ionic project directory and then type:

```<code>$> ionic upload
</code>```

You will be asked for the usernmame and password of the account you just created, the application will be uploaded and you will get a unique app ID. You can then share that ID with anyone who you want to test your app, as long as they have the Ionic View app installed on the their iOS or Android devices.

Also do make sure you have updated your global ionic and cordova packages to the latest version before you upload:

```<code>$> sudo npm uninstall -g ionic && sudo npm install ionic
</code>```

Now, as 3squad mentioned, many of they Ionic Native plugins are not supported so don't expect everything to work, but it's a good start to show most of your app and design running.

Here's a list of currently supported plugins.

Please do keep in mind that the performance using Ionic View will be far worse than if you actually build, release and give your users and actual production .apk or .ipa file to install. This latter approach would also showcase the full, final performance and functionality resulting from your code, but it may be more cumbersome.

Here's how to release a production version of your app.

Body:
'Ionic View' is a very good advice and the one I would suggest in your case as well.

You don't have to do anything in your code really to use it, just create an ionic account and in your terminal, change into your ionic project directory and then type:

$> ionic upload

You will be asked for the usernmame and password of the account you just created, the application will be uploaded and you will get a unique app ID. You can then share that ID with anyone who you want to test your app, as long as they have the Ionic View app installed on the their iOS or Android devices.

Also do make sure you have updated your global ionic and cordova packages to the latest version before you upload:

$> sudo npm uninstall -g ionic && sudo npm install ionic

Now, as 3squad mentioned, many of they Ionic Native plugins are not supported so don't expect everything to work, but it's a good start to show most of your app and design running.

Here's a list of currently supported plugins.

Please do keep in mind that the performance using Ionic View will be far worse than if you actually build, release and give your users and actual production .apk or .ipa file to install. This latter approach would also showcase the full, final performance and functionality resulting from your code, but it may be more cumbersome.

Here's how to release a production version of your app.


问:
React-Native (Android) : ArrayIndexOutOfBoundsException thrown when requesting for permissions
Recently I have encountered a very strange issue while working with a React-Native app. Here's my environement:

Rect-Native 0.42.3

Samsung Galaxy Note 5

Android 6.0

As you may know, the Android permission model has changed since Marshmallow, but some days ago, I got his exception:

```<code>java.lang.RuntimeException:
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4156)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4250)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:7229)
    at java.lang.reflect.Method.invoke(Native Method:0)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.ArrayIndexOutOfBoundsException:
    at com.facebook.react.modules.permissions.PermissionsModule$1.invoke(PermissionsModule.java:119)
    at com.facebook.react.modules.permissions.PermissionsModule.onRequestPermissionsResult(PermissionsModule.java:207)
    at com.facebook.react.ReactActivityDelegate$1.invoke(ReactActivityDelegate.java:211)
    at com.facebook.react.ReactActivityDelegate.onResume(ReactActivityDelegate.java:131)
    at com.facebook.react.ReactActivity.onResume(ReactActivity.java:66)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1286)
    at android.app.Activity.performResume(Activity.java:6987)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4145)
</code>```

First, I thought I was missing a check in the code, as explained here but this is not the case as otherwise I would have a message like this instead:

```<code>java.lang.SecurityException: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord{fac49ea 4674:com.gospacesmobile/u0a65} (pid=4674, uid=10065) requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS
</code>```

I looked at React-Native's code and found this:

```<code>// com.facebook.react.modules.permissions.PermissionsModule.java
int[] results = (int[]) args[0];
if (results[0] == PackageManager.PERMISSION_GRANTED) { // <- the exception happens when results is empty
    promise.resolve(GRANTED);
} else {
    PermissionAwareActivity activity = (PermissionAwareActivity) args[1];
    if (activity.shouldShowRequestPermissionRationale(permission)) {
        promise.resolve(DENIED);
    } else {
        promise.resolve(NEVER_ASK_AGAIN);
    }
}
</code>```

According the documentation, the grantResults variable may be empty whenever the permission request has been canceled:

```<code>@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}
</code>```

Unfortunately, I do not have the client code (as the crash report in the google console dev does not mention it). In any case, shouldn't React-Native check for empty grantResults? Is this a bug? If yes, how could this be reproduced? I don't see any way this could be done, except by canceling the promise responsible for ensuring if a permission has been enabled or not (which is impossible considering react-native permissions API).

Any thought is very welcome. Thank you in advance.

答:
So I finally found the problem. Whenever the permission request dialog appear, if the user minimizes the app, and then goes back to it by clicking on the app's icon in from the home menu, the results is empty which makes the app crashing.

This seems to be quiet a simple issue, and I've decided to monkey patch React-Native in order to prevent an unstable upgrade (Now I check if the results array is empty or not, and if it is, then deny the request). I still don't know if this is a common issue or something that comes from my app.

Body:
Recently I have encountered a very strange issue while working with a React-Native app. Here's my environement:

Rect-Native 0.42.3

Samsung Galaxy Note 5

Android 6.0

As you may know, the Android permission model has changed since Marshmallow, but some days ago, I got his exception:

java.lang.RuntimeException:
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4156)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4250)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:7229)
    at java.lang.reflect.Method.invoke(Native Method:0)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.ArrayIndexOutOfBoundsException:
    at com.facebook.react.modules.permissions.PermissionsModule$1.invoke(PermissionsModule.java:119)
    at com.facebook.react.modules.permissions.PermissionsModule.onRequestPermissionsResult(PermissionsModule.java:207)
    at com.facebook.react.ReactActivityDelegate$1.invoke(ReactActivityDelegate.java:211)
    at com.facebook.react.ReactActivityDelegate.onResume(ReactActivityDelegate.java:131)
    at com.facebook.react.ReactActivity.onResume(ReactActivity.java:66)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1286)
    at android.app.Activity.performResume(Activity.java:6987)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4145)

First, I thought I was missing a check in the code, as explained here but this is not the case as otherwise I would have a message like this instead:

java.lang.SecurityException: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord{fac49ea 4674:com.gospacesmobile/u0a65} (pid=4674, uid=10065) requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS

I looked at React-Native's code and found this:

// com.facebook.react.modules.permissions.PermissionsModule.java
int[] results = (int[]) args[0];
if (results[0] == PackageManager.PERMISSION_GRANTED) { // <- the exception happens when results is empty
    promise.resolve(GRANTED);
} else {
    PermissionAwareActivity activity = (PermissionAwareActivity) args[1];
    if (activity.shouldShowRequestPermissionRationale(permission)) {
        promise.resolve(DENIED);
    } else {
        promise.resolve(NEVER_ASK_AGAIN);
    }
}

According the documentation, the grantResults variable may be empty whenever the permission request has been canceled:

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

Unfortunately, I do not have the client code (as the crash report in the google console dev does not mention it). In any case, shouldn't React-Native check for empty grantResults? Is this a bug? If yes, how could this be reproduced? I don't see any way this could be done, except by canceling the promise responsible for ensuring if a permission has been enabled or not (which is impossible considering react-native permissions API).

Any thought is very welcome. Thank you in advance.