问:
How to stop UITableViewCell flashing to white when deselecting?
I have the common pattern of a UITableView with a secondary view controller which gets pushed over the top when a row is selected. To give the user some context when they dismiss the second view controller and return to the tableview, that first view controller has this:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if let index = tableView.indexPathForSelectedRow {
        tableView.deselectRow(at: index, animated: animated)
    }
}
</code>```

That results in this unintended and jarring transition in which the cell being deselected fades it's background away, before snapping back to normal :

My expectation was that it would transition from the partially subdued state selection left it in directly back to the normal, dark state.

(The cell is very much a work-in-progress - it's far from finished)

Following the suggestions here isn't really an option as I do want to preserve the context hint and the cell as a whole should continue to have a white background.

In response to Rico's question, the cell is created as a .swift and .xib pair, the hierarchy of views being:

The Swift does very little - sets .textInsets on the two labels, draws the disclosure indicator in the button.

答:
I believe this is because the default implementation of setSelected removes the background color of all subviews of the cell. What you can do is override setSelected and/or setHighlighted and update the cell yourself.

This also allows you to create a custom look for selected cells.

Example that uses a red background when selected, and white when not selected:

```<code>override func setSelected(_ selected: Bool, animated: Bool) {
    let animationDuration = animated ? 0.3 : 0
    UIView.animate(withDuration: animationDuration) {
      self.backgroundColor = highlighted ? UIColor.red : UIColor.white
    }
  }
</code>```

Body:
I have the common pattern of a UITableView with a secondary view controller which gets pushed over the top when a row is selected. To give the user some context when they dismiss the second view controller and return to the tableview, that first view controller has this:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if let index = tableView.indexPathForSelectedRow {
        tableView.deselectRow(at: index, animated: animated)
    }
}

That results in this unintended and jarring transition in which the cell being deselected fades it's background away, before snapping back to normal :

My expectation was that it would transition from the partially subdued state selection left it in directly back to the normal, dark state.

(The cell is very much a work-in-progress - it's far from finished)

Following the suggestions here isn't really an option as I do want to preserve the context hint and the cell as a whole should continue to have a white background.

In response to Rico's question, the cell is created as a .swift and .xib pair, the hierarchy of views being:

The Swift does very little - sets .textInsets on the two labels, draws the disclosure indicator in the button.

Body:
I believe this is because the default implementation of setSelected removes the background color of all subviews of the cell. What you can do is override setSelected and/or setHighlighted and update the cell yourself.

This also allows you to create a custom look for selected cells.

Example that uses a red background when selected, and white when not selected:

override func setSelected(_ selected: Bool, animated: Bool) {
    let animationDuration = animated ? 0.3 : 0
    UIView.animate(withDuration: animationDuration) {
      self.backgroundColor = highlighted ? UIColor.red : UIColor.white
    }
  }


来源: stackexchange

问:
Wordpress Ajax Form CSV Price Request
I am creating a card calculator form where you can select a card type and select a quantity and a price is returned.

I am using a csv file for the pricing and I have it all working great. as a simple HTML Form displayed through a shortcode in WordPress.

```<code><?php
// Get CSV
$ch = fopen($standard_csv, "r");
$header_row = fgetcsv($ch);

// Get array of rows
$rows = array_map('str_getcsv', file($standard_csv));

// Remove first row (header row) as we already have this separately
unset( $rows[0] );
?>

<!-- The Form -->
<form action="" method="post" name="calc" id="calc">

    Type:
    <select name="card" id="card">
    <option value="">Please Select</option>
    <?php
        // Remove first blank cell from $header
        unset( $header_row[0] );
        foreach ( $header_row as $key => $card ){
            echo '<option value="' . $key . '">' . $card . '</option>';
        }
    ?>
    </select>

    Quantity:
    <select name="quantity" id="quantity">
    <option value="">Please Select</option>
    <?php
        foreach ( $rows as $key => $row ){
            echo '<option value="' . $key . '">' . $row[0] . '</option>';
        }
    ?>

    </select>

    <input type="submit" name="get-price" value="Get Price!">

</form>

<?php

if ( isset( $_POST['get-price'] ) ){
    $card = $_POST['card'];
    $quantity = $_POST['quantity'];
    echo 'Price: £' . $rows[$quantity][$card];
}
?>
</code>```

This is great but I want to display the returned price using AJAX so I do not have to refresh the page when a user requests a price for their chosen card and quantity.

I have my scripts enqueued like so:

```<code>wp_enqueue_script( 'custom_script', plugin_dir_url( __FILE__ ) . 'js/custom.js', array('jquery'), '1.0' );
wp_localize_script( 'custom_script-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),

add_action('wp_ajax_get_price', 'get_price');
add_action('wp_ajax_nopriv_get_price', 'get_price');

function get_price(){

        $card = $_POST['card'];
        $quantity = $_POST['quantity'];
        return 'Price: £' . $rows[$quantity][$card];

}
</code>```

I have this in my Javascript File

```<code>$('#calc').submit(function (event) {
            event.preventDefault();
            var card = jQuery('#card').val();
            var quantity = jQuery('#quantity').val();

            jQuery.ajax({
                type: 'POST',
                url: ajax_object.ajax_url,
                data: {
                    action: 'get_price',
                    card: card,
                    quantity: quantity
                },
                success: function (data) {
                    console.log(data);
                },
                error: function (errorThrown) {
                    console.log(data);
                    alert(errorThrown);
                }
            });
    });
</code>```

I have totally confused myself and I have tried to follow many tutorials, but I just cant work out the correct logic to be able to output a price from the CSV file using AJAX without reloading the page.

I know this code is totally not right, but please any help to set me in the right direction would be extremely appreciated.

I just need help understanding the logic on how to handle passing the variables and prices between the ajax and the php function in order to return a price from the CSV File.

Thank you.

答:
Don't return from ajax - exit.

Replace return 'Price: £' . $rows[$quantity][$card];

with

wp_die('Price: £' . $rows[$quantity][$card]);

Best wishes,
Mitchell

ContentLicense: CC BY-SA 4.0

Title: Wordpress Ajax Form CSV Price Request

Body:
I am creating a card calculator form where you can select a card type and select a quantity and a price is returned.

I am using a csv file for the pricing and I have it all working great. as a simple HTML Form displayed through a shortcode in WordPress.

<?php
// Get CSV
$ch = fopen($standard_csv, "r");
$header_row = fgetcsv($ch);

// Get array of rows
$rows = array_map('str_getcsv', file($standard_csv));

// Remove first row (header row) as we already have this separately
unset( $rows[0] );
?>

<form action="" method="post" name="calc" id="calc">

    Type:
    <select name="card" id="card">
    <option value="">Please Select</option>
    <?php
        // Remove first blank cell from $header
        unset( $header_row[0] );
        foreach ( $header_row as $key => $card ){
            echo '<option value="' . $key . '">' . $card . '</option>';
        }
    ?>
    </select>

    Quantity:
    <select name="quantity" id="quantity">
    <option value="">Please Select</option>
    <?php
        foreach ( $rows as $key => $row ){
            echo '<option value="' . $key . '">' . $row[0] . '</option>';
        }
    ?>

    </select>

    <input type="submit" name="get-price" value="Get Price!">

</form>

<?php

if ( isset( $_POST['get-price'] ) ){
    $card = $_POST['card'];
    $quantity = $_POST['quantity'];
    echo 'Price: £' . $rows[$quantity][$card];
}
?>

This is great but I want to display the returned price using AJAX so I do not have to refresh the page when a user requests a price for their chosen card and quantity.

I have my scripts enqueued like so:

wp_enqueue_script( 'custom_script', plugin_dir_url( __FILE__ ) . 'js/custom.js', array('jquery'), '1.0' );
wp_localize_script( 'custom_script-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),

add_action('wp_ajax_get_price', 'get_price');
add_action('wp_ajax_nopriv_get_price', 'get_price');

function get_price(){

        $card = $_POST['card'];
        $quantity = $_POST['quantity'];
        return 'Price: £' . $rows[$quantity][$card];

}

I have this in my Javascript File

$('#calc').submit(function (event) {
            event.preventDefault();
            var card = jQuery('#card').val();
            var quantity = jQuery('#quantity').val();

            jQuery.ajax({
                type: 'POST',
                url: ajax_object.ajax_url,
                data: {
                    action: 'get_price',
                    card: card,
                    quantity: quantity
                },
                success: function (data) {
                    console.log(data);
                },
                error: function (errorThrown) {
                    console.log(data);
                    alert(errorThrown);
                }
            });
    });

I have totally confused myself and I have tried to follow many tutorials, but I just cant work out the correct logic to be able to output a price from the CSV file using AJAX without reloading the page.

I know this code is totally not right, but please any help to set me in the right direction would be extremely appreciated.

I just need help understanding the logic on how to handle passing the variables and prices between the ajax and the php function in order to return a price from the CSV File.

Thank you.


问:
Java regex to replace in between text using a pattern
I am a newbie to Java regex. I have a long string which contains text like this(Below is only the part of my string which I would like to replace):

```<code>href="javascript:openWin('Images/DCRMBex_01B_ex01.jpg',480,640)"
href="javascript:openWin('Images/DCRMBex_01A_ex01.jpg',480,640)"
href="javascript:openWin('Images/DCRMBex_06A_ex06.jpg',480,640)"
</code>```

I would like to replace

```<code>Images
</code>```

with

```<code>http://google.com/Images
</code>```

For eg. my output should look like this:

```<code>href="javascript:openWin('http://google.com/Images/DCRMBex_01B_ex01.jpg',480,640)"
</code>```

Below is my Java program:

```<code>import java.io.FileReader;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main2 {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner in = new Scanner(new FileReader("C:\\Projects\\input.txt"));

        StringBuilder sb = new StringBuilder();
        while (in.hasNext()) {
            sb.append(in.next());
        }
        String patternString = "href=\"javascript:openWin(.+?)\"";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(sb);
        while (matcher.find()) {
            //System.out.println(matcher.group(1));
            //System.out.println(matcher.group(1).replaceAll("Images", "http://google.com/Images"));
            matcher.group(1).replaceAll("Images", "http://google.com/Images");

        }
        System.out.println(sb);
    }
}
</code>```

Below is my input file(input.txt). This is only a part of my file. The file is too long to paste here:

```<code> <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_01_ex01.pdf"><b>Example 1: Bible (Rusch)</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_01A_ex01.jpg',480,640)">Figure 1A. First page of text</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_01B_ex01.jpg',480,640)">Figure 1B. Source of supplied title</a></td>
                            <td valign="top">  </td>
                            <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_06_ex06.pdf"><b>Example 6: Angelo Carletti</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_06A_ex06.jpg',480,640)">Figure 6A. Title page</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_06B_ex06.jpg',480,640)">Figure 6B. Colophon showing use of i/j and u/v</a></td>
                          </tr>
                          <tr>
                            <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_02_ex02.pdf"><b>Example 2: Greek anthology</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_02A_ex02.jpg',480,640)">Figure 2A. First page of text</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_02B_ex02.jpg',480,640)">Figure 2B. Colophon</a></td>
                            <td valign="top">  </td>
                            <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_07_ex07.pdf"><b>Example 7: Erasmus</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_07A_ex07.jpg',480,640)">Figure 7A. Title page</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_07B_ex07.jpg',480,640)">Figure 7B. Colophon</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_07C_ex07.jpg',640,480)">Figure 7C. Running title</a></td>
                          </tr>
                          <tr>
                            <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_03_ex03.pdf"><b>Example 3: Heytesbury</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_03A_ex03.jpg',480,640)">Figure 3A. Title page</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_03B_ex03.jpg',480,640)">Figure 3B. Colophon showing use of i/j and u/v</a></td>
                            <td valign="top">  </td>
                            <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_08_ex08.pdf"><b>Example 8: Pliny</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_08A_ex08.jpg',480,640)">Figure 8A. Title page</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_08B_ex08.jpg',480,640)">Figure 8B. Colophon</a></td>
</code>```

Output:

1) System.out.println(matcher.group(1))

```<code>('Images/DCRMBex_05_ex05.jpg',480,640)
</code>```

2)System.out.println(matcher.group(1).replaceAll("Images","http://google.com/Images"));

```<code> ('http://google.com/Images/DCRMBex_05_ex05.jpg',480,640)
</code>```

But when I print my struingbuilder, it doesn't show any replacement. What I am doing wrong here? Any help is appreciated. Thanks

答:
replaceAll returns the modified string; it does not modify in place. In this case, I would not use java.util.regex and instead use replaceAll's support for capture groups:

Scanner in = new Scanner(new FileReader("C:\\Projects\\input.txt"));
StringBuilder sb = new StringBuilder();
while (in.hasNext()) {
    sb.append(in.next());
}
// Modified regex
String patternString = "(href=\"javascript:openWin\\(&#39;)(.+?)(&#39;)";

String result = sb.toString().replaceAll(patternString, "$1http://google.com/$2$3");
```

Try it online

Hope this helps!

Body:
I am a newbie to Java regex. I have a long string which contains text like this(Below is only the part of my string which I would like to replace):

href="javascript:openWin(&#39;Images/DCRMBex_01B_ex01.jpg&#39;,480,640)"
href="javascript:openWin(&#39;Images/DCRMBex_01A_ex01.jpg&#39;,480,640)"
href="javascript:openWin(&#39;Images/DCRMBex_06A_ex06.jpg&#39;,480,640)"

I would like to replace

Images

with

http://google.com/Images

For eg. my output should look like this:

href="javascript:openWin(&#39;http://google.com/Images/DCRMBex_01B_ex01.jpg&#39;,480,640)"

Below is my Java program:

import java.io.FileReader;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main2 {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner in = new Scanner(new FileReader("C:\\Projects\\input.txt"));

        StringBuilder sb = new StringBuilder();
        while (in.hasNext()) {
            sb.append(in.next());
        }
        String patternString = "href=\"javascript:openWin(.+?)\"";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(sb);
        while (matcher.find()) {
            //System.out.println(matcher.group(1));
            //System.out.println(matcher.group(1).replaceAll("Images", "http://google.com/Images"));
            matcher.group(1).replaceAll("Images", "http://google.com/Images");

        }
        System.out.println(sb);
    }
}

Below is my input file(input.txt). This is only a part of my file. The file is too long to paste here:

 Example 1: Bible (Rusch) ï¿½ Figure 1A. First page of text ï¿½ Figure 1B. Source of supplied title
                            &nbsp;&nbsp;
                            Example 6: Angelo Carletti ï¿½ Figure 6A. Title page ï¿½ Figure 6B. Colophon showing use of i/j and u/v

                            Example 2: Greek anthology ï¿½ Figure 2A. First page of text ï¿½ Figure 2B. Colophon
                            &nbsp;&nbsp;
                            Example 7: Erasmus ï¿½ Figure 7A. Title page ï¿½ Figure 7B. Colophon ï¿½ Figure 7C. Running title

                            Example 3: Heytesbury ï¿½ Figure 3A. Title page ï¿½ Figure 3B. Colophon showing use of i/j and u/v
                            &nbsp;&nbsp;
                            Example 8: Pliny ï¿½ Figure 8A. Title page ï¿½ Figure 8B. Colophon

Output:

1) System.out.println(matcher.group(1))

(&#39;Images/DCRMBex_05_ex05.jpg&#39;,480,640)

2)System.out.println(matcher.group(1).replaceAll("Images","http://google.com/Images"));

 (&#39;http://google.com/Images/DCRMBex_05_ex05.jpg&#39;,480,640)

But when I print my struingbuilder, it doesn't show any replacement. What I am doing wrong here? Any help is appreciated. Thanks

Body:
replaceAll returns the modified string; it does not modify in place. In this case, I would not use java.util.regex and instead use replaceAll's support for capture groups:

Scanner in = new Scanner(new FileReader("C:\\Projects\\input.txt"));
StringBuilder sb = new StringBuilder();
while (in.hasNext()) {
    sb.append(in.next());
}
// Modified regex
String patternString = "(href=\"javascript:openWin\\(&amp;#39;)(.+?)(&amp;#39;)";

String result = sb.toString().replaceAll(patternString, "$1http://google.com/$2$3");

Try it online

Hope this helps!


问:
Is there any way by which i can know if the recipient have replied to my email or not?
I have set up an email tracking system in my application, that shows how many emails I have sent, how many emails have been read., and the emails I am sending is via AWS SES. I want to know is there a way via which I can know if the client has replied back?</p>

答:
To know how many emails were read/opened, you can use SES feature called "Open".
https://aws.amazon.com/blogs/messaging-and-targeting/open-and-click-tracking-have-arrived/
You need to make use of configuration set to do that and this can enable either Cloudwatch metric or you can have SNS trigger when there is any open event, SES will add a link at the bottom of your HTML body which is a 1 pixel image but the should contain HTML body(html part).

To know how many people have replied back to the email can be tricky. First of all, you're sending emails via SES but when they reply back, does the sender/reply-to address domain points to SES incoming mails ? example: does your domain has mx pointed to SES incoming email endpoint, if so you can use SNS trigger what IceMetalPunk mentioned, but if you don't use SES to receive email, there is no way.
The best option would be to use a subdomain as a sending domain and receive emails to S3 if Main domain is acquired to receive emails to mailboxes.


问:
Unable to start embedded container; nested exception is java.lang.NoSuchMethodError: javax.servlet.ServletContext.addServlet
This is the test I am running:

```<code>@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages="com.tsinghua.controller,com.tsinghua.manager,com.tsinghua.facade")
public class App extends SpringBootServletInitializer implements      EmbeddedServletContainerCustomizer {

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

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    return builder.sources(App.class);
}
public void customize(ConfigurableEmbeddedServletContainer container) {
    container.setPort(28090);
}

@Bean
public Docket mathApi() {
}

@Bean
public Docket serverApi() {
}

private Predicate<String> categoryPaths() {
    return regex("/math.*");
}

private ApiInfo apiInfo() {
}

private ApiInfo serverApiInfo() {
}
}
</code>```

This is the pom.xml:

```<code><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.*.mathservice</groupId>
<artifactId>math</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>mathservice</name>
<description>math service</description>
<url>http://maven.apache.org</url>

<repositories>
    <repository>
        <id>mvn-repo</id>
        <url>http://maven.nlpcn.org/</url>
    </repository>
</repositories>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.2.RELEASE</version>
</parent>
<dependencies>
    <!--add 2-->
    <dependency>
        <groupId>org.springframework.ws</groupId>
        <artifactId>spring-ws-core</artifactId>
    </dependency>
     <!--https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.ansj</groupId>
        <artifactId>ansj_seg</artifactId>
        <version>3.7.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.4.4</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.4.4</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.4.4</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
    </dependency>

    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-staticdocs</artifactId>
        <version>2.2.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.jena</groupId>
        <artifactId>apache-jena-libs</artifactId>
        <type>pom</type>
        <version>3.0.1</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </exclusion>
            <exclusion>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j</artifactId>
    </dependency>
    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
    </dependency>

</dependencies>

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

    </plugins>
</build>
</project>
</code>```

And this is the errors and warnings:

```<code>[2016-10-20 12:48:48.168] boot - 66451 ERROR [com.tsinghua.common.App.main()] --- SpringApplication: Application startup failed
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is java.lang.NoSuchMethodError: javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)Ljavax/servlet/ServletRegistration$Dynamic;
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at com.tsinghua.common.App.main(App.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodError: javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)Ljavax/servlet/ServletRegistration$Dynamic;
    at org.springframework.boot.context.embedded.ServletRegistrationBean.onStartup(ServletRegistrationBean.java:171)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.selfInitialize(EmbeddedWebApplicationContext.java:222)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.access$000(EmbeddedWebApplicationContext.java:84)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext$1.onStartup(EmbeddedWebApplicationContext.java:206)
    at org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer.callInitializers(ServletContextInitializerConfiguration.java:96)
    at org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer.doStart(ServletContextInitializerConfiguration.java:85)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:106)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.handler.ScopedHandler.doStart(ScopedHandler.java:120)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:784)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:294)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1349)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1342)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:505)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.server.Server.start(Server.java:387)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.Server.doStart(Server.java:354)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.initialize(JettyEmbeddedServletContainer.java:83)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.<init>(JettyEmbeddedServletContainer.java:72)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory.getJettyEmbeddedServletContainer(JettyEmbeddedServletContainerFactory.java:389)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory.getEmbeddedServletContainer(JettyEmbeddedServletContainerFactory.java:135)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:157)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
    ... 13 more
[WARNING]
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is java.lang.NoSuchMethodError: javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)Ljavax/servlet/ServletRegistration$Dynamic;
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at com.tsinghua.common.App.main(App.java:37)
    ... 6 more
Caused by: java.lang.NoSuchMethodError: javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)Ljavax/servlet/ServletRegistration$Dynamic;
    at org.springframework.boot.context.embedded.ServletRegistrationBean.onStartup(ServletRegistrationBean.java:171)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.selfInitialize(EmbeddedWebApplicationContext.java:222)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.access$000(EmbeddedWebApplicationContext.java:84)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext$1.onStartup(EmbeddedWebApplicationContext.java:206)
    at org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer.callInitializers(ServletContextInitializerConfiguration.java:96)
    at org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer.doStart(ServletContextInitializerConfiguration.java:85)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:106)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.handler.ScopedHandler.doStart(ScopedHandler.java:120)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:784)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:294)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1349)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1342)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:505)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.server.Server.start(Server.java:387)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.Server.doStart(Server.java:354)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.initialize(JettyEmbeddedServletContainer.java:83)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.<init>(JettyEmbeddedServletContainer.java:72)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory.getJettyEmbeddedServletContainer(JettyEmbeddedServletContainerFactory.java:389)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory.getEmbeddedServletContainer(JettyEmbeddedServletContainerFactory.java:135)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:157)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
    ... 13 more
</code>```

I am using IDEA 15. And the code can run in another guy's machine, I changed maven 3.0.5 to his maven version 3.3.9, but it didn't work.

答:
We had the same problem, but only sometimes, it was random:

Unable to start embedded container; nested exception is java.lang.NoSuchMethodError: javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)Ljavax/servlet/ServletRegistration$Dynamic;

We also used 'spring-boot-starter-jetty' dependency, which includes the 'javax.servlet-api' 3.1.0 dependency. We excluded 'spring-boot-starter-tomcat' dependency from 'spring-boot-starter-web' dependency, just to be safe.

But we investigated and found, in our project dependencies, that we somehow also had the servlet-api 2.5 dependency (this dependency was inherited from other dependencies).

In 3.1.0, the javax.servlet.ServletContext has the method 'addServlet'.

In 2.5, it does not have this method.

We then learnt that maven randomly used version 3.1.0 or version 2.5 in our application. When it randomly used 3.1.0, the application started normally. When it randomly used 2.5, which doesn't have the method 'addServlet', it threw the 'NoSuchMethodError' Exception.

To fix it, in the pom.xml we just excluded the hidden 2.5 'javax.servlet' dependency:

```<code>    <dependency>
        <groupId>our.cool.group</groupId>
        <artifactId>the-artifact-which-includes-2.5-servlet-api-and-we-didnt-know</artifactId>
        <version>${the.artifact.version}</version>
        <exclusions>
            <exclusion>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is the test I am running:

@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages="com.tsinghua.controller,com.tsinghua.manager,com.tsinghua.facade")
public class App extends SpringBootServletInitializer implements      EmbeddedServletContainerCustomizer {

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

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    return builder.sources(App.class);
}
public void customize(ConfigurableEmbeddedServletContainer container) {
    container.setPort(28090);
}

@Bean
public Docket mathApi() {
}

@Bean
public Docket serverApi() {
}

private Predicate<String> categoryPaths() {
    return regex("/math.*");
}

private ApiInfo apiInfo() {
}

private ApiInfo serverApiInfo() {
}
}

This is the pom.xml:

<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.*.mathservice</groupId>
<artifactId>math</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>mathservice</name>
<description>math service</description>
<url>http://maven.apache.org</url>

<repositories>
    <repository>
        <id>mvn-repo</id>
        <url>http://maven.nlpcn.org/</url>
    </repository>
</repositories>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.2.RELEASE</version>
</parent>
<dependencies>

    <dependency>
        <groupId>org.springframework.ws</groupId>
        <artifactId>spring-ws-core</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.ansj</groupId>
        <artifactId>ansj_seg</artifactId>
        <version>3.7.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.4.4</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.4.4</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.4.4</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
    </dependency>

    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-staticdocs</artifactId>
        <version>2.2.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.jena</groupId>
        <artifactId>apache-jena-libs</artifactId>
        <type>pom</type>
        <version>3.0.1</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </exclusion>
            <exclusion>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j</artifactId>
    </dependency>
    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
    </dependency>

</dependencies>

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

    </plugins>
</build>
</project>

And this is the errors and warnings:

[2016-10-20 12:48:48.168] boot - 66451 ERROR [com.tsinghua.common.App.main()] --- SpringApplication: Application startup failed
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is java.lang.NoSuchMethodError: javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)Ljavax/servlet/ServletRegistration$Dynamic;
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at com.tsinghua.common.App.main(App.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodError: javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)Ljavax/servlet/ServletRegistration$Dynamic;
    at org.springframework.boot.context.embedded.ServletRegistrationBean.onStartup(ServletRegistrationBean.java:171)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.selfInitialize(EmbeddedWebApplicationContext.java:222)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.access$000(EmbeddedWebApplicationContext.java:84)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext$1.onStartup(EmbeddedWebApplicationContext.java:206)
    at org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer.callInitializers(ServletContextInitializerConfiguration.java:96)
    at org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer.doStart(ServletContextInitializerConfiguration.java:85)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:106)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.handler.ScopedHandler.doStart(ScopedHandler.java:120)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:784)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:294)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1349)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1342)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:505)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.server.Server.start(Server.java:387)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.Server.doStart(Server.java:354)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.initialize(JettyEmbeddedServletContainer.java:83)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.<init>(JettyEmbeddedServletContainer.java:72)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory.getJettyEmbeddedServletContainer(JettyEmbeddedServletContainerFactory.java:389)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory.getEmbeddedServletContainer(JettyEmbeddedServletContainerFactory.java:135)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:157)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
    ... 13 more
[WARNING]
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is java.lang.NoSuchMethodError: javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)Ljavax/servlet/ServletRegistration$Dynamic;
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at com.tsinghua.common.App.main(App.java:37)
    ... 6 more
Caused by: java.lang.NoSuchMethodError: javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)Ljavax/servlet/ServletRegistration$Dynamic;
    at org.springframework.boot.context.embedded.ServletRegistrationBean.onStartup(ServletRegistrationBean.java:171)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.selfInitialize(EmbeddedWebApplicationContext.java:222)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.access$000(EmbeddedWebApplicationContext.java:84)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext$1.onStartup(EmbeddedWebApplicationContext.java:206)
    at org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer.callInitializers(ServletContextInitializerConfiguration.java:96)
    at org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer.doStart(ServletContextInitializerConfiguration.java:85)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:106)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.handler.ScopedHandler.doStart(ScopedHandler.java:120)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:784)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:294)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1349)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1342)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:505)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.server.Server.start(Server.java:387)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.Server.doStart(Server.java:354)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.initialize(JettyEmbeddedServletContainer.java:83)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.<init>(JettyEmbeddedServletContainer.java:72)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory.getJettyEmbeddedServletContainer(JettyEmbeddedServletContainerFactory.java:389)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory.getEmbeddedServletContainer(JettyEmbeddedServletContainerFactory.java:135)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:157)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
    ... 13 more

I am using IDEA 15. And the code can run in another guy's machine, I changed maven 3.0.5 to his maven version 3.3.9, but it didn't work.

Body:
We had the same problem, but only sometimes, it was random:

Unable to start embedded container; nested exception is java.lang.NoSuchMethodError: javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)Ljavax/servlet/ServletRegistration$Dynamic;

We also used 'spring-boot-starter-jetty' dependency, which includes the 'javax.servlet-api' 3.1.0 dependency. We excluded 'spring-boot-starter-tomcat' dependency from 'spring-boot-starter-web' dependency, just to be safe.

But we investigated and found, in our project dependencies, that we somehow also had the servlet-api 2.5 dependency (this dependency was inherited from other dependencies).

In 3.1.0, the javax.servlet.ServletContext has the method 'addServlet'.

In 2.5, it does not have this method.

We then learnt that maven randomly used version 3.1.0 or version 2.5 in our application. When it randomly used 3.1.0, the application started normally. When it randomly used 2.5, which doesn't have the method 'addServlet', it threw the 'NoSuchMethodError' Exception.

To fix it, in the pom.xml we just excluded the hidden 2.5 'javax.servlet' dependency:

    <dependency>
        <groupId>our.cool.group</groupId>
        <artifactId>the-artifact-which-includes-2.5-servlet-api-and-we-didnt-know</artifactId>
        <version>${the.artifact.version}</version>
        <exclusions>
            <exclusion>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>


问:
Custom PHP Errors for AJAX calls
I'm building a web application, and am wondering how to handle errors with my AJAX calls.  For instance, if the user enters some sort of data that is invalid (bad email address, user already exists) I want to be able to throw an error from PHP.

I've seen here http://php4every1.com/tutorials/jquery-ajax-tutorial/ that you could just use a JSON object and handle the error report from JQuery's Success function, but that doesn't seem like the right way to do it. It would make sense to me that jQuery's error function should be utilized when there is an error. I guess I'm a stickler for that kind of thing.

Here's how I'm doing it right now.

```<code>//In my PHP file called from JQuery
function error($msg) {
    header("HTTP/1.0 555 ".$msg);
    die();
}
//Then that error is handled accordingly from JQuery
</code>```

So I'm creating an error code of 555—which is not defined as anything—and tacking on my own custom error message. Is that the right way to do this? Should I just use JSON? There's gotta be a standard way to send out error messages like this, right?

If you need to see more of my code to get a better idea, the whole project is up on github: https://github.com/josephwegner/fileDrop. The file in question is config/phpFuncts.php.

答: The 400 family of HTTP status codes indicate that there was a problem with the request.  I would set the response code to 400 and include the list of error messages in the response body as JSON.

Title: Custom PHP Errors for AJAX calls

Body:
I'm building a web application, and am wondering how to handle errors with my AJAX calls.  For instance, if the user enters some sort of data that is invalid (bad email address, user already exists) I want to be able to throw an error from PHP.

I've seen here http://php4every1.com/tutorials/jquery-ajax-tutorial/ that you could just use a JSON object and handle the error report from JQuery's Success function, but that doesn't seem like the right way to do it. It would make sense to me that jQuery's error function should be utilized when there is an error. I guess I'm a stickler for that kind of thing.

Here's how I'm doing it right now.

//In my PHP file called from JQuery
function error($msg) {
    header("HTTP/1.0 555 ".$msg);
    die();
}
//Then that error is handled accordingly from JQuery

So I'm creating an error code of 555—which is not defined as anything—and tacking on my own custom error message. Is that the right way to do this? Should I just use JSON? There's gotta be a standard way to send out error messages like this, right?

If you need to see more of my code to get a better idea, the whole project is up on github: https://github.com/josephwegner/fileDrop. The file in question is config/phpFuncts.php.


问:
Combine two objects in an array into a single object if the object properties are the same and convert the unique properties into an array
Input -

```<code>[
  {color:'red', shape:'circle', size:'medium'},
  {color:'red', shape:'circle', size:'small'}
]
</code>```

Output -

```<code>[
  {color:'red', shape:'circle', size:['medium','small']}
]
</code>```

How can this be achieved in Javascript?

答:
You can create a general function which takes an array of objects and array of keys to match as its parameters.

You can do that in following steps:

First use reduce() on the array of objects and set accumulator to empty array []

Get the other props(unique props) by using filter() on Object.keys()

Then in each iteration find the element of the accumulator array whose all the given props matches with the current object.

If the element is found then use forEach() other keys and push the values to to corresponding array.

If element is not found then set each key to an empty array.

At last return the result of reduce()

const arr = [
  {color:'red', shape:'circle', size:'medium'},
  {color:'red', shape:'circle', size:'small'}
]

function groupByProps(arr,props){
  const res = arr.reduce((ac,a) => {
    let ind = ac.findIndex(b => props.every(k => a[k] === b[k]));
    let others = Object.keys(a).filter(x => !props.includes(x));
    if(ind === -1){
      ac.push({...a});
      others.forEach(x => ac[ac.length - 1][x] = []);
      ind = ac.length - 1
    }
    others.forEach(x => ac[ind][x].push(a[x]));
    return ac;
  },[])
  return res;
}

const res = groupByProps(arr,['color','shape'])
console.log(res)```

Body:
Input -

[
  {color:'red', shape:'circle', size:'medium'},
  {color:'red', shape:'circle', size:'small'}
]

Output -

[
  {color:'red', shape:'circle', size:['medium','small']}
]

How can this be achieved in Javascript?


问:
AWS S3 check if file exists based on a conditional path
I would like to check if a file exists in a separate directory of the bucket if a given file exists. I have the following directory structure-

```<code>import boto3
s3 = boto3.resource('s3')
def file_exists(fileN):
    try:
        s3.Object('my-bucket', 'folder1/folder2/'+fileN).load()
    except:
        return False
    else:
        fileN = fileN.split(".")[0]
        try:

            s3.Object('my-bucket', 'folder1/<randomid folderxxxx>/'+fileN+'_condition.jpg').load()
        except:
            return False
        else:
            return True

file_exists("test.jpg")
</code>```

This works but as long as I can send the randomfolderIDas an argument. Is there a better and elegant way to do it?

Basically I have to check if,

my-bucket/folder1/folder2/test.jpg if this exists then check
my-bucket/folder1/<randomID>/test_condition.jpg if this also exists then return True

答:
I ended up using this which gave a little cleaner code</p>

```<code>import boto3
s3client = boto3.client('s3')

def all_file_exist(bucket, prefix, fileN):
    fileFound = False
    fileConditionFound = False
    theObjs = s3client.list_objects_v2(Bucket=bucket, Prefix=prefix)
    for object in theObjs['Contents']:
        if object['Key'].endswith(fileN+'_condition.jpg') :
            fileConditionFound = True
        if object['Key'].endswith(fileN+".jpg") :
            fileFound = True
    if (fileFound and fileConditionFound) :
        return True
    return False

all_file_exist("bucket","folder1", "test")

</code>```

Body:
I would like to check if a file exists in a separate directory of the bucket if a given file exists. I have the following directory structure-

import boto3
s3 = boto3.resource('s3')
def file_exists(fileN):
    try:
        s3.Object('my-bucket', 'folder1/folder2/'+fileN).load()
    except:
        return False
    else:
        fileN = fileN.split(".")[0]
        try:

            s3.Object('my-bucket', 'folder1/<randomid folderxxxx>/'+fileN+'_condition.jpg').load()
        except:
            return False
        else:
            return True

file_exists("test.jpg")

This works but as long as I can send the randomfolderIDas an argument. Is there a better and elegant way to do it?

Basically I have to check if,

my-bucket/folder1/folder2/test.jpg if this exists then check
my-bucket/folder1/<randomID>/test_condition.jpg if this also exists then return True

Body:
I ended up using this which gave a little cleaner code

import boto3
s3client = boto3.client('s3')

def all_file_exist(bucket, prefix, fileN):
    fileFound = False
    fileConditionFound = False
    theObjs = s3client.list_objects_v2(Bucket=bucket, Prefix=prefix)
    for object in theObjs['Contents']:
        if object['Key'].endswith(fileN+'_condition.jpg') :
            fileConditionFound = True
        if object['Key'].endswith(fileN+".jpg") :
            fileFound = True
    if (fileFound and fileConditionFound) :
        return True
    return False

all_file_exist("bucket","folder1", "test")


问:
PyCharm asks for python interpreter every time project is loaded
Rather frustratingly, every time I load up an existing project or create a new one - it complains there is no interpreter selected and I have to provide the path to it.

There is nothing unusual about my python installation, it's sat in C:/Python27/ as you would expect. It always used to work, but the last few weeks something has changed.

I'm running Win7. PATH system variable points to C:/Python27/ as it ought to.

If I crack open commandline, the python command opens as it ought to.

Any ideas?

答: You can easily do it by going to File > Setting for New Projects > Project Interpreter:


问:
Reusing types across multiple webservices
I have a collection of related webservices that share some of the types between them, notably the "token" generated by the TokenService.

When using "add reference" in Visual Studio, proxy classes are generated and many classes, such as the Token class, are duplicated for each webservice.

To resolve this I have written the following powershell script to generate .cs files for the webservices which reuse the types.

```<code>$svcutil = get-item ((get-item 'Env:\ProgramFiles(x86)').Value + "\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64\svcutil.exe")
$csc = "C:\Program Files (x86)\MSBuild\14.0\Bin\csc.exe"

& $svcutil "http://Path/to/WebService/WSTokenService?wsdl" /o:WSTokenService.cs
& $csc /target:library /out:temp.dll WSTokenService.cs

& $svcutil "http://Path/to/WebService/WSAssetService?wsdl" /r:temp.dll /o:WSAssetService.cs
& $csc /target:library /out:temp.dll WSTokenService.cs WSAssetService.cs

& $svcutil "http://Path/to/WebService/WSContactService?wsdl" /r:temp.dll /o:WSContactService.cs
& $csc /target:library /out:temp.dll WSTokenService.cs WSAssetService.cs WSContactService.cs
..
repeat for 8 webservices
</code>```

This "chains" the webservices together, resusing the shared classes, and seems to work.

Are there any problems with this approach and/or is there a better way to achieve sharing classes between the related webservices?

Edit: please note that these are not webservices developed by us and we do not have access to the code or classes that are used server-side.

答:
I am making an assumption in my response that you are asking if the web services can share access to a single path where the DLL (library) is stored.

This is something that you can do in windows using the GAC (requires strong named assemblies) in order for multiple applications to have easy access to it. But to date I don't believe there is a comparable service available for micro-service architecture to do something similar.

So each web services requires it's own instance of the DLL in order to use the requisite internal code.

Body:
I have a collection of related webservices that share some of the types between them, notably the "token" generated by the TokenService.

When using "add reference" in Visual Studio, proxy classes are generated and many classes, such as the Token class, are duplicated for each webservice.

To resolve this I have written the following powershell script to generate .cs files for the webservices which reuse the types.

$svcutil = get-item ((get-item 'Env:\ProgramFiles(x86)').Value + "\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64\svcutil.exe")
$csc = "C:\Program Files (x86)\MSBuild\14.0\Bin\csc.exe"

& $svcutil "http://Path/to/WebService/WSTokenService?wsdl" /o:WSTokenService.cs
& $csc /target:library /out:temp.dll WSTokenService.cs

& $svcutil "http://Path/to/WebService/WSAssetService?wsdl" /r:temp.dll /o:WSAssetService.cs
& $csc /target:library /out:temp.dll WSTokenService.cs WSAssetService.cs

& $svcutil "http://Path/to/WebService/WSContactService?wsdl" /r:temp.dll /o:WSContactService.cs
& $csc /target:library /out:temp.dll WSTokenService.cs WSAssetService.cs WSContactService.cs
..
repeat for 8 webservices

This "chains" the webservices together, resusing the shared classes, and seems to work.

Are there any problems with this approach and/or is there a better way to achieve sharing classes between the related webservices?

Edit: please note that these are not webservices developed by us and we do not have access to the code or classes that are used server-side.


问:
How to change my <select> out with <input> to use with barcode scanner
I'm about to change a script, and right know the script are using an <select> with one options and echo to be used to show the products.

Now I'll like to change the <select> to a <input> so I can scan a barcode, and the information from the product should be added to the DB as it is right now, but I'm lost, I have used several hours to figuere out how to change it, I thought the solution was to use a hidded  but then I can't add the first knowen product to my list.

Could someone please help me? :)

I've tried to use more  boxes to get the products, but that was a big mess.

```<code> <div class="col-md-6">
  <div class="form-group">
    <label for="date">Product Name</label>
    <select class="form-control select2" name="prod_name" tabindex="1" autofocus required>
      <?php
        $branch=$_SESSION['branch'];
        $cid=$_REQUEST['cid'];

        include('../dist/includes/dbcon.php');

        $query2=mysqli_query($con,"select * from product where branch_id='$branch' order by prod_name")or die(mysqli_error());

          while($row=mysqli_fetch_array($query2)){
            ?>
            <option value="<?php echo $row['prod_id'];?>"><?php echo $row['prod_name']." Available(".$row['prod_qty'].")";?></option>
          <?php }?>
    </select>

      <input type="hidden" class="form-control" name="cid" value="<?php echo $cid;?>" required>
    </div><!-- /.form group -->
  </div>
  <div class=" col-md-2">
    <div class="form-group">
      <label for="date">Quantity</label>
      <div class="input-group">
        <input type="number" class="form-control pull-right" id="date" name="qty" placeholder="Quantity" tabindex="2" value="1"  required>
      </div><!-- /.input group -->
    </div><!-- /.form group -->
  </div>
  <div class="col-md-2">
    <div class="form-group">
      <label for="date"></label>
      <div class="input-group">
        <button class="btn btn-lg btn-primary" type="submit" tabindex="3" name="addtocart">+</button>
      </div>
    </div>
</code>```

The code should be changed to use a <input> or something simular, so I can use a barcode scanner to add my items to a list.

答:
What I did to get my result was:

I changed the prod_id to be the barcode, and on scan the form is submitted to a temp_db, to show every items, and then added a "finish db" called inStock, and everything was as it should be! :)

/Kenneth

Body:
I'm about to change a script, and right know the script are using an <select> with one options and echo to be used to show the products.

Now I'll like to change the <select> to a <input> so I can scan a barcode, and the information from the product should be added to the DB as it is right now, but I'm lost, I have used several hours to figuere out how to change it, I thought the solution was to use a hidded  but then I can't add the first knowen product to my list.

Could someone please help me? :)

I've tried to use more  boxes to get the products, but that was a big mess.

    Product Name
    <select class="form-control select2" name="prod_name" tabindex="1" autofocus required>
      <?php
        $branch=$_SESSION['branch'];
        $cid=$_REQUEST['cid'];

        include('../dist/includes/dbcon.php');

        $query2=mysqli_query($con,"select * from product where branch_id='$branch' order by prod_name")or die(mysqli_error());

          while($row=mysqli_fetch_array($query2)){
            ?>
            <option value="<?php echo $row['prod_id'];?>"><?php echo $row['prod_name']." Available(".$row['prod_qty'].")";?></option>
          <?php }?>
    </select>

      <input type="hidden" class="form-control" name="cid" value="<?php echo $cid;?>" required>

      Quantity

        <input type="number" class="form-control pull-right" id="date" name="qty" placeholder="Quantity" tabindex="2" value="1"  required>

        <button class="btn btn-lg btn-primary" type="submit" tabindex="3" name="addtocart">+</button>

The code should be changed to use a <input> or something simular, so I can use a barcode scanner to add my items to a list.


问:
Nuxt: Unexpected token <
<img src="https://i.stack.imgur.com/MbM9f.png" alt="Nuxt: Unexpected token < ">

I am working on a nuxt project, and I'm trying to build a map component using google maps and the plugin https://www.npmjs.com/package/vue2-google-maps. I have installed the plugin using npm

In my index.html page I have a normally working page that looks like:

```<code><template>
   <div>

<br>
<br>
       <Card/>
<br>
<br>
<br>
<br>
       <!-- <Googlemap/> -->
       <Panel/>
       <Four/>
       </div>
</template>

<script>

import Panel from '~/components/panel.vue'
import Card from '~/components/detailCard.vue'
// import GoogleMap from '~/components/googleMap.vue'

export default {

  components: {

    Panel,
    Card,
//     GoogleMap
  }

}
</script>
</code>```

When I Uncomment the 3 lines with Googlemap in them I get the error in the screenshot .

The Googlemap component is:

```<code><template>
  <GmapMap
  :center="{lat:10, lng:10}"
  :zoom="7"
  map-type-id="terrain"
  style="width: 500px; height: 300px"
>
  <GmapMarker
    :key="index"
    v-for="(m, index) in markers"
    :position="m.position"
    :clickable="true"
    :draggable="true"
    @click="center=m.position"
  />
</GmapMap>

</template>

<script>
import Vue from "vue";
import * as VueGoogleMaps from "vue2-google-maps";

Vue.use(VueGoogleMaps, {
  load: {
    key: "MYTOKEN",
    libraries: "places"
  }
});

export default {

}

</script>

<style>

</style>
</code>```

What am I doing wrong?

edit:

答:
Often it refers to the response from a request, where it was expecting a JSON object, but instead is returned HTML. The < refers to the first character in <!DOCTYPE... or similar.

Check the responses coming back from the APIs or other services you’re using.

Title: Nuxt: Unexpected token <

Body:
<img src="https://i.stack.imgur.com/MbM9f.png" alt="Nuxt: Unexpected token < ">

I am working on a nuxt project, and I'm trying to build a map component using google maps and the plugin https://www.npmjs.com/package/vue2-google-maps. I have installed the plugin using npm

In my index.html page I have a normally working page that looks like:

<template>

       <Card/>

       <Panel/>
       <Four/>

</template>

When I Uncomment the 3 lines with Googlemap in them I get the error in the screenshot .

The Googlemap component is:

<template>
  <GmapMap
  :center="{lat:10, lng:10}"
  :zoom="7"
  map-type-id="terrain"
  style="width: 500px; height: 300px"
>
  <GmapMarker
    :key="index"
    v-for="(m, index) in markers"
    :position="m.position"
    :clickable="true"
    :draggable="true"
    @click="center=m.position"
  />
</GmapMap>

</template>

What am I doing wrong?

edit:


问:
How to build a multiple IF conditional in Mule 4 and DW 2.0?
I need to create a function with conditions like this pseudo-code:

```<code>var consent = []

function buildConsent() {
   if (condition1) {
       consent += values1
   }

   if (condition2) {
       consent += values2
   }

   if (condition3) {
       consent += values3
   }
}
</code>```

This is how I am doing it on Mule4 and DW 2.0:

```<code>%dw 2.0
var consent = []
var factIntake = vars.facts

fun buildConsent() =
    if (factIntake.miscFactItems[?($.value1 == true)] != null) {
        consent + {
            "Consent_Type": "some1",
            "Consent_Given_By": "some2"
        }
    }

    if (factIntake.miscFactItems[?($.value2 == true)] != null) {
        consent + {
            "Consent_Type": "some3",
            "Consent_Given_By": "some4"
        }
    }

output application/json
--
{
    "Consent_Data": buildConsent()
}
</code>```

But I am getting the following error from the IDE (AnypointStudio 7):

Invalid input '+', expected Namespace or
  Attribute<'@('(Name:Value)+')'> (line 11, column 11):

Where line 11, column 11 is the first appearance of consent +. If I try to debug the project all I got in the console is:

Message               : Error while parsing script: %dw 2.0

Here is an example of input/output for you to better understand what I am trying to achieve:

```<code>// Input
{
    "miscFactItems": [{
            "factId": "designeeFirstName",
            "factValue": "test test",
            "factValueType": "System.String"
        }, {
            "factId": "designeeLastName",
            "factValue": "test test",
            "factValueType": "System.String"
        },{
            "factId": "value1",
            "factValue": true,
            "factValueType": "System.Boolean"
        }, {
            "factId": "value2",
            "factValue": true,
            "factValueType": "System.Boolean"
        }, {
            "factId": "value3",
            "factValue": true,
            "factValueType": "System.Boolean"
        }
    ]
}

// Output
consent = [{
             "Consent_Type": "type1",
             "Consent_Given_By": miscFactItems.designeeFirstName
         }, {
             "Consent_Type": "type2",
             "Consent_Given_By": miscFactItems.designeeFirstName
         }, {
             "Consent_Type": "type3",
             "Consent_Given_By": miscFactItems.designeeFirstName
         }
]
</code>```

What I am missing here? How do I add the three conditions to my function and append the values to the consent var?

答:
Your requirement looks like a good use of reduce function. Based on the pseudo code you provided, you can do something like below

```<code>output application/json
var payload = [
    {"name":"Ram", "email":"Ram@gmail.com", "state": "CA","age":21},
    {"name":"Bob", "email":"bob32@gmail.com","state": "CA","age":30},
    {"name":"john", "email":"bob32@gmail.com","state": "NY","age":43}

]
---
payload reduce ((item, consent = []) -> consent +
{
    (state: item.state) if(item.state=='CA'),
    (age: item.age) if(item.age >25)
}
)
</code>```

Body:
I need to create a function with conditions like this pseudo-code:

var consent = []

function buildConsent() {
   if (condition1) {
       consent += values1
   }

   if (condition2) {
       consent += values2
   }

   if (condition3) {
       consent += values3
   }
}

This is how I am doing it on Mule4 and DW 2.0:

%dw 2.0
var consent = []
var factIntake = vars.facts

fun buildConsent() =
    if (factIntake.miscFactItems[?($.value1 == true)] != null) {
        consent + {
            "Consent_Type": "some1",
            "Consent_Given_By": "some2"
        }
    }

    if (factIntake.miscFactItems[?($.value2 == true)] != null) {
        consent + {
            "Consent_Type": "some3",
            "Consent_Given_By": "some4"
        }
    }

output application/json
--
{
    "Consent_Data": buildConsent()
}

But I am getting the following error from the IDE (AnypointStudio 7):

Invalid input '+', expected Namespace or
  Attribute<'@('(Name:Value)+')'> (line 11, column 11):

Where line 11, column 11 is the first appearance of consent +. If I try to debug the project all I got in the console is:

Message               : Error while parsing script: %dw 2.0

Here is an example of input/output for you to better understand what I am trying to achieve:

// Input
{
    "miscFactItems": [{
            "factId": "designeeFirstName",
            "factValue": "test test",
            "factValueType": "System.String"
        }, {
            "factId": "designeeLastName",
            "factValue": "test test",
            "factValueType": "System.String"
        },{
            "factId": "value1",
            "factValue": true,
            "factValueType": "System.Boolean"
        }, {
            "factId": "value2",
            "factValue": true,
            "factValueType": "System.Boolean"
        }, {
            "factId": "value3",
            "factValue": true,
            "factValueType": "System.Boolean"
        }
    ]
}

// Output
consent = [{
             "Consent_Type": "type1",
             "Consent_Given_By": miscFactItems.designeeFirstName
         }, {
             "Consent_Type": "type2",
             "Consent_Given_By": miscFactItems.designeeFirstName
         }, {
             "Consent_Type": "type3",
             "Consent_Given_By": miscFactItems.designeeFirstName
         }
]

What I am missing here? How do I add the three conditions to my function and append the values to the consent var?

Body:
Your requirement looks like a good use of reduce function. Based on the pseudo code you provided, you can do something like below

output application/json
var payload = [
    {"name":"Ram", "email":"Ram@gmail.com", "state": "CA","age":21},
    {"name":"Bob", "email":"bob32@gmail.com","state": "CA","age":30},
    {"name":"john", "email":"bob32@gmail.com","state": "NY","age":43}

]
---
payload reduce ((item, consent = []) -> consent +
{
    (state: item.state) if(item.state=='CA'),
    (age: item.age) if(item.age >25)
}
)


问:
Assume Role for IAM user to do s3 upload from Jenkins CI
I am trying to use s3upload from Jenkins CI, I have added IAM user S3_User credentials in Jenkins console and using withAWS(region: s3Region ,credentials: s3User). But my IAM user S3_User doesnt have S3 RW policy, IAM user has to assume role S3_UserRoleWithRWpolicy .How do I do that?

Provided S3_User access and secret key in Jenkins IAM credentials and added S3_UserRoleWithRWpolicy in IAM Role to use under IAM Role Support. But still not able to do S3 upload from Jenkins. How could I configure in Jenkins file to use role?

答:
```<code>Finally figured out the solution:

I was using this in Jenkins CI file :
withAWS(region: 's3Region', credentials: 'iamUser')
{
s3Upload( file:'jar', bucket:s3Bucket, path: s3Path)
}

It worked fine when iamUser has direct access to S3
but failed when iamUser has to assume role to access S3 (after adding IAM Role to Assume in credentials)
But the below worked:

 withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: 'iamUser']]) {
withAWS(region: 's3Region')
{
s3Upload( file:'jar', bucket:s3Bucket, path: s3Path)
}
}
</code>```


问:
“MSVCP100.dll is either not designed to run on Windows or it contains an error”
I built an application in C++ using Visual Studio 2010 Express. When I tried to run it on a certain computer today I got this error:

MyApplication.exe - Bad Image

C:\Path to My Application\MSVCP100.dll is either not designed to run on Windows or it contains an error. Try installing the program again using the original installation media or contact your system administrator or the software vendor for support.

The DLL mentioned is one of the Visual C++ Redistributable DLLs. My application’s installer used to launch Microsoft’s installer for those DLLs but I recently tweaked it just to install msvcp100.dll and msvcr100.dll alongside my application. The new way worked fine on a handful of other computers, though I can’t rule out the possibility that that was only because the DLLs had already been installed at system level on those other computers.

What is causing this sudden DLL mismatch?

答:
Follow da steps

1.Download the dll from here

https://www.sts-tutorial.com/sites/downloadCenter.php?MSVCR100

2.open with winrar

3.Extract MSVCR100.dll to C:\Windows\System32

hope it will work c:


问:
Issues publishing and installing a npm package on a private registry
I finished my package(1 js file) and I want to publish it on artifactory.

package.json:

```<code>{
  "name": "@company/package_name",
  "main": "dist/index.js",
  "publishConfig": {
    "registry": "http://artifactory_url"
  },
  "files": ["dist/index.js"],
  "devDependencies": {
    "tslint": "^5.15.0",
    "webpack": "^4.29.6",
  },
  "dependencies": {
    "axios": "^0.18.0"
  }
}
</code>```

I publish it:

```<code>npm login --registry=https://artifacory_url --scope=@company
npm publish
</code>```

my npm package is available now on artifactory (1 js file and package.json)

Now if I want to install it:

```<code>npm install @company/package_name --registry=https://artifacory_url
</code>```

it complains that a dependency is not in the npm registry:

```<code>Not Found - GET https:artifactory_url/axios - not_found
npm ERR! 404
npm ERR! 404  'axios@^0.18.0' is not in the npm registry
</code>```

which of course it's true, I don't have axios published in my registry, but I expected it to get it from the npm registry.

I'm not sure about the strategy to follow.
I use webpack, so axios is already bundled in my dist/index.js file.  Should I treat it like a devDependencies like tslint? It seems that it is not a dev dependency to me...

答:
The npm devs are not going to facilitate/allow releasing to multiple registries at once because it could lead to issues like:

A given version can be on one registry but not on the other

The same version can be release on each registry with different code

To solve the problematic around private/public registries, most private registries use a proxy feature (if the package requested is in the private repo serve it, otherwise delegate the request to the public registry).

Many registry solution also offer a replication feature.

With those feature you should be able to publish only on one registry and serve it from multiple ones.

You are using artifactory, and they allow to configure it rewriting external dependencies.

Select the Enable Dependency Rewrite checkbox in the npm virtual
repository advanced configuration.

Body:
I finished my package(1 js file) and I want to publish it on artifactory.

package.json:

{
  "name": "@company/package_name",
  "main": "dist/index.js",
  "publishConfig": {
    "registry": "http://artifactory_url"
  },
  "files": ["dist/index.js"],
  "devDependencies": {
    "tslint": "^5.15.0",
    "webpack": "^4.29.6",
  },
  "dependencies": {
    "axios": "^0.18.0"
  }
}

I publish it:

npm login --registry=https://artifacory_url --scope=@company
npm publish

my npm package is available now on artifactory (1 js file and package.json)

Now if I want to install it:

npm install @company/package_name --registry=https://artifacory_url

it complains that a dependency is not in the npm registry:

Not Found - GET https:artifactory_url/axios - not_found
npm ERR! 404
npm ERR! 404  'axios@^0.18.0' is not in the npm registry

which of course it's true, I don't have axios published in my registry, but I expected it to get it from the npm registry.

I'm not sure about the strategy to follow.
I use webpack, so axios is already bundled in my dist/index.js file.  Should I treat it like a devDependencies like tslint? It seems that it is not a dev dependency to me...


问:
Method sp_OAGetProperty does not return value when executed
I have a certain address for a client and I need to get the latitude and longitude coordinates from Google using API Key, however either sp_OAGetProperty is returning blank instead of an XML data, what could be the reason for blank results it is returning?

This is for a geo analytics purposes, I have reconfigured the server to accept the execution of Ole Automation Procedures but still the same.

I'm using code.

```<code>use Development_Weekly
go

DECLARE @Response varchar(8000)
DECLARE @XML xml
DECLARE @Obj int
DECLARE @Result int
DECLARE @HTTPStatus int
DECLARE @Erreur varchar(MAX)
declare @MessageErreur varchar(max)
declare @MessageErreurAvecNumero varchar(max)

declare  @URL varchar(600) =(select top 1 [BranchAddressURL] from [Development_Weekly].[dbo].[vwBranchLocation])
EXEC @Result = sp_OACreate 'MSXML2.ServerXMLHttp', @Obj OUT
if @Erreur <> 0 begin set @MessageErreur = 'sp_OACreate MSXML2.ServerXMLHttp.3.0 failed'   end
--BEGIN TRY
EXEC @Result = sp_OAMethod @Obj, 'open', NULL, 'GET', @URL, false
if @Erreur <> 0 begin set @MessageErreur = 'sp_OAMethod MSXML2.ServerXMLHttp.3.0 failed'   end

EXEC @Result = sp_OAMethod @Obj, 'setRequestHeader', NULL, 'Content-Type', 'application/x-www-form-urlencoded'
if @Erreur <> 0 begin set @MessageErreur = 'sp_OAMethod MSXML2.ServerXMLHttp.3.0 failed'   end

EXEC @Result = sp_OAMethod @Obj, send, NULL, ''
if @Erreur <> 0 begin set @MessageErreur = 'sp_OAMethod MSXML2.ServerXMLHttp.3.0 failed'  end

EXEC @Result = sp_OAGetProperty @Obj, 'responseXML.xml', @Response OUT
if @Erreur <> 0 begin set @MessageErreur = 'sp_OAGetProperty MSXML2.ServerXMLHttp.3.0 failed'   end

EXEC @Result = sp_OADestroy @Obj
if @Erreur <> 0 begin set @MessageErreur = 'sp_OADestroy MSXML2.ServerXMLHttp.3.0 failed'   end

select @Result,@Response,@URL
</code>```

答:
I am not sure what exactly the reason is without a real url. But I always insert the response to a table variable instead of using @Response OUT to avoid truncated result. Here is what I usually do:

```<code>DECLARE @TABLEVAR TABLE (responseXml VARCHAR(MAX))

--skip some codes here

INSERT INTO @TABLEVAR
EXEC @Result = sp_OAGetProperty @Obj, 'responseXML.xml' --, @Response OUT
EXEC sp_OADestroy @Obj

SELECT @Response = responseXml FROM @TABLEVAR
</code>```

Body:
I have a certain address for a client and I need to get the latitude and longitude coordinates from Google using API Key, however either sp_OAGetProperty is returning blank instead of an XML data, what could be the reason for blank results it is returning?

This is for a geo analytics purposes, I have reconfigured the server to accept the execution of Ole Automation Procedures but still the same.

I'm using code.

use Development_Weekly
go

DECLARE @Response varchar(8000)
DECLARE @XML xml
DECLARE @Obj int
DECLARE @Result int
DECLARE @HTTPStatus int
DECLARE @Erreur varchar(MAX)
declare @MessageErreur varchar(max)
declare @MessageErreurAvecNumero varchar(max)

declare  @URL varchar(600) =(select top 1 [BranchAddressURL] from [Development_Weekly].[dbo].[vwBranchLocation])
EXEC @Result = sp_OACreate 'MSXML2.ServerXMLHttp', @Obj OUT
if @Erreur <> 0 begin set @MessageErreur = 'sp_OACreate MSXML2.ServerXMLHttp.3.0 failed'   end
--BEGIN TRY
EXEC @Result = sp_OAMethod @Obj, 'open', NULL, 'GET', @URL, false
if @Erreur <> 0 begin set @MessageErreur = 'sp_OAMethod MSXML2.ServerXMLHttp.3.0 failed'   end

EXEC @Result = sp_OAMethod @Obj, 'setRequestHeader', NULL, 'Content-Type', 'application/x-www-form-urlencoded'
if @Erreur <> 0 begin set @MessageErreur = 'sp_OAMethod MSXML2.ServerXMLHttp.3.0 failed'   end

EXEC @Result = sp_OAMethod @Obj, send, NULL, ''
if @Erreur <> 0 begin set @MessageErreur = 'sp_OAMethod MSXML2.ServerXMLHttp.3.0 failed'  end

EXEC @Result = sp_OAGetProperty @Obj, 'responseXML.xml', @Response OUT
if @Erreur <> 0 begin set @MessageErreur = 'sp_OAGetProperty MSXML2.ServerXMLHttp.3.0 failed'   end

EXEC @Result = sp_OADestroy @Obj
if @Erreur <> 0 begin set @MessageErreur = 'sp_OADestroy MSXML2.ServerXMLHttp.3.0 failed'   end

select @Result,@Response,@URL

Body:
I am not sure what exactly the reason is without a real url. But I always insert the response to a table variable instead of using @Response OUT to avoid truncated result. Here is what I usually do:

DECLARE @TABLEVAR TABLE (responseXml VARCHAR(MAX))

--skip some codes here

INSERT INTO @TABLEVAR
EXEC @Result = sp_OAGetProperty @Obj, 'responseXML.xml' --, @Response OUT
EXEC sp_OADestroy @Obj

SELECT @Response = responseXml FROM @TABLEVAR


问:
How to fix TypeError with respect to TensorFlow prediction?
I've been trying to perform neural network predictions with TensorFlow and the evaluation works fine but when I put the same data into prediction it gives a type error.

The data in training_data and test_data are both 2d numpy arrays of integers and training_labels and test_labels are 1d numpy arrays of integers.

```<code>model = keras.Sequential([
  keras.layers.Dense(24, activation=tf.nn.selu),
  keras.layers.Dense(10, activation=tf.nn.tanh),
  keras.layers.Dense(5, activation=tf.nn.selu),
  keras.layers.Dense(5, activation=tf.nn.softmax)
])

model.compile(optimizer='SGD',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(training_data, training_labels, epochs=10)

test_loss,test_acc = model.evaluate(test_data, test_labels)

prediction = model.predict(test_data)
</code>```

When taking out the prediction line the code works as expected but it now gives the following error message:

```<code>Traceback (most recent call last):
  File "learner.py", line 132, in <module>
    print("Prediction: " + model.predict(test_data))
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S32') dtype('S32') dtype('S32')
</code>```

I've made sure that all the data is integers so I'm not sure why there's type conflict.

答:
test_data should be the same datatype as type(training_data[0]) when using predict, and it will return a datatype of type(training_labels[0])

In addition,

```<code>print("Prediction: " + model.predict(test_data))
</code>```

must be

```<code>print("Prediction: " + str(model.predict(test_data)))
</code>```

Body:
I've been trying to perform neural network predictions with TensorFlow and the evaluation works fine but when I put the same data into prediction it gives a type error.

The data in training_data and test_data are both 2d numpy arrays of integers and training_labels and test_labels are 1d numpy arrays of integers.

model = keras.Sequential([
  keras.layers.Dense(24, activation=tf.nn.selu),
  keras.layers.Dense(10, activation=tf.nn.tanh),
  keras.layers.Dense(5, activation=tf.nn.selu),
  keras.layers.Dense(5, activation=tf.nn.softmax)
])

model.compile(optimizer='SGD',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(training_data, training_labels, epochs=10)

test_loss,test_acc = model.evaluate(test_data, test_labels)

prediction = model.predict(test_data)

When taking out the prediction line the code works as expected but it now gives the following error message:

Traceback (most recent call last):
  File "learner.py", line 132, in <module>
    print("Prediction: " + model.predict(test_data))
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S32') dtype('S32') dtype('S32')

I've made sure that all the data is integers so I'm not sure why there's type conflict.

Body:
test_data should be the same datatype as type(training_data[0]) when using predict, and it will return a datatype of type(training_labels[0])

In addition,

print("Prediction: " + model.predict(test_data))

must be

print("Prediction: " + str(model.predict(test_data)))


问:
Disabling Python 3.2 ResourceWarning
Python 3.2 introduced ResourceWarning for unclosed system resources (network sockets, files):

Though the code runs clean in production, I am getting a lot of following warnings when running unit tests due to use of third party libraries where the warning occurs. I could fix the library, but on the other hand it were much simpler just to ignore it during the test run.

```<code> block_io-python/block_io/__init__.py:182: ResourceWarning: unclosed <ssl.SSLSocket fd=11, family=AddressFamily.AF_INET, type=SocketType.SOCK_STREAM, proto=6, laddr=('x', 58395), raddr=('x, 443)>
</code>```

What is the way to disable these warnings? I tried the following but no effect:

```<code> warnings.filterwarnings("ignore", category=ResourceWarning)
</code>```

(Run during unit test import time).

答:
This alternative worked for me:

```<code>    def setUp(self):
        if not sys.warnoptions:
            import warnings
            warnings.simplefilter("ignore")
</code>```

See: Standard Library docs - Overriding the default filter

Title: Disabling Python 3.2 ResourceWarning

Body:
Python 3.2 introduced ResourceWarning for unclosed system resources (network sockets, files):

Though the code runs clean in production, I am getting a lot of following warnings when running unit tests due to use of third party libraries where the warning occurs. I could fix the library, but on the other hand it were much simpler just to ignore it during the test run.

 block_io-python/block_io/__init__.py:182: ResourceWarning: unclosed <ssl.SSLSocket fd=11, family=AddressFamily.AF_INET, type=SocketType.SOCK_STREAM, proto=6, laddr=('x', 58395), raddr=('x, 443)>

What is the way to disable these warnings? I tried the following but no effect:

 warnings.filterwarnings("ignore", category=ResourceWarning)

(Run during unit test import time).

Body:
This alternative worked for me:

    def setUp(self):
        if not sys.warnoptions:
            import warnings
            warnings.simplefilter("ignore")

See: Standard Library docs - Overriding the default filter