问:
Apache HttpClient doesn't get content of pages using pagination links. I get 200 status but html has no content
I'm trying to web crawl pages of content with Apache HttpClient. I get status 200 when requesting the next page using the link from pagination but HTML shows 500 in the body and no content. Postman works fine and gets content even when using links from pagination.

Main class

public static void main(String[] args) {
        String url = "https://www.cochranelibrary.com/cdsr/reviews/topics";
        MyContentFetcher myContentFetcher = new MyContentFetcher();
        MyParser myParser = new MyParser();
        try {
            // Load Topic list page
            String topicsPage = myContentFetcher.loadHTML(url);

            // Getting all the topics.
            Map<Integer, MyNode> topics = myParser.getTopicList(topicsPage);

            // Print all the topics and ask user to choose one
            for (int id : topics.keySet())
                System.out.println("-> " + id + " <- " + topics.get(id).getTopic());
            System.out.println("********************");
            System.out.print("Enter ID number from the list above to get reviews or enter anything else to exit:\n");
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String id = reader.readLine();

            // Validate user input, get the link and topic and cout the choice.
            if (isNumber(id)) {
                int idNum = Integer.parseInt(id);
                if (idNum <= topics.size() && idNum > 0) {
                    String topic = topics.get(idNum).getTopic();
                    String link = topics.get(idNum).getLink();
                    System.out.println("You picked: " + topic + link + "\n***************************");
                    // Loading first page of reviews
                    myParser.loadReviews(myContentFetcher.loadHTML(link), topic);
                    // Getting links to other pages
                    Queue<String> paginationLinks = myParser.getLinks();

                    // --------------> WORKS FINE UNTIL HERE <--------------
                    // Problem starts here....
                    // Load list of reviews for chosen topic
                    while(!paginationLinks.isEmpty()) {
                        String page = myContentFetcher.loadHTML(paginationLinks.remove());
                        myParser.loadReviews(page, topic);
                    }
                }
            }
            System.out.println("Exiting...");

        } catch (IOException e) {
            System.out.println("There was a problem...");
        }
```

<p>!!!! Here is the class that fetches HTML. I'm probably doing something wrong here...</p>

<pre class="lang-java prettyprint-override"><code>import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

import java.util.Scanner;

public class MyContentFetcher {

    public MyContentFetcher() {
    }

    String loadHTML(String url) throws IOException {
        // Create configurations for
        RequestConfig config = RequestConfig.custom()
                .setCircularRedirectsAllowed(true)
                .setCookieSpec(CookieSpecs.STANDARD)
                .build();
        // Creating a HttpClient object
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(config)
                .build();
        // Creating a HttpGet object
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("User-Agent", "Mozilla/5.0 (Linux; Android 8.1.0; Pixel Build/OPM4.171019.021.D1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.109 Mobile Safari/537.36 EdgA/42.0.0.2057");
        CloseableHttpResponse httpResponse = httpClient.execute(httpget);
        Scanner sc = new Scanner(httpResponse.getEntity().getContent());
        StringBuilder page = new StringBuilder("");
        while(sc.hasNext())
            page.append(sc.nextLine()).append(" ");
        httpResponse.close();
        httpClient.close();
        return page.toString();
    }
}
</code>```

Here is the parser. Parser doesn't have any problems (Parse perfectly fine and as needed)

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class MyParser {

    private Map<String, String> topics;
    private Document htmlPage;
    private Element reviewBlock;

    public MyParser(){}

    // Loads all topics from the Cochrane Library into a map -> (Topic Name, Link)
    public Map<Integer, MyNode> getTopicList(String page) {
        Map<Integer, MyNode> topics= new HashMap<Integer, MyNode>();
        htmlPage = Jsoup.parse(page);
        // Get 'a' element that is inside 'li' with a class name of browse-by-list-item
        int i = 1;
        MyNode info;
        for(Element element : htmlPage.body().select("li.browse-by-list-item > a")) {
            info = new MyNode(element.select("button").text(),
                    element.select("a").attr("href").trim());
            topics.put(i, info);
            i++;
        }
        return topics;
    }

    // Loads Reviews
    public void loadReviews(String page, String topic) throws IOException {
        htmlPage = Jsoup.parse(page);
        // Get all review blocks
        System.out.println("**************************\n" + page + "\n**************************\n");
        for(Element element : htmlPage.body().select(".search-results-item-body")){
            reviewBlock = element;
            String review = getLink() + " | " + topic + " | " + getTitle() + " | " + getAuthor() + " | " + getDate();
            System.out.println(review);
        }
    }

    Queue<String> getLinks(){
        System.out.println("GETTING LINKS");
        Queue<String> links = new LinkedList<>();
        for(Element element : htmlPage.body().select("li.pagination-page-list-item > a")) {
            links.add(element.attr("href"));
        }
        return links;
    }

    private String getLink(){
        return "https://www.cochranelibrary.com" + reviewBlock.select("a").attr("href");
    }

    public String getTitle(){
        return reviewBlock.selectFirst("a").text();
    }

    public String getAuthor(){
        return reviewBlock.selectFirst("div.search-result-authors").text();
    }

    public String getDate(){
        String result = reviewBlock.select("div.search-result-date > div").text();
        try {
            SimpleDateFormat fmt = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
            Date d = fmt.parse(result);
            fmt.applyPattern("yyyy-MM-dd");
            result = fmt.format(d);
        } catch (ParseException e) {
            System.out.println("Failed parsing the date...");
        }
        return result;
    }
```

答:
To solve this problem I created a session and used cookie store and used CloseableHttpResponse to close the response after each time I fetch the page. Here is the fragment of the code that make it work:

RequestConfig config = RequestConfig.custom()
                .setCircularRedirectsAllowed(true)
                .build();
        httpClient = HttpClients.custom()
                .setDefaultRequestConfig(config)
                .setMaxConnPerRoute(100)
                .build();
        CookieStore cookieStore = new BasicCookieStore();
        httpContext = new BasicHttpContext();
        httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

HttpGet httpget = new HttpGet(url);
        httpget.setHeader("User-Agent", "Whatever");
        StringBuilder page = new StringBuilder("");
        try {
            CloseableHttpResponse response = httpClient.execute(httpget, httpContext);
            System.out.println(response.getStatusLine());
            Scanner sc = new Scanner(response.getEntity().getContent());
            while (sc.hasNext())
                page.append(sc.nextLine()).append(" ");
            sc.close();
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return page.toString();
```

Body:
I'm trying to web crawl pages of content with Apache HttpClient. I get status 200 when requesting the next page using the link from pagination but HTML shows 500 in the body and no content. Postman works fine and gets content even when using links from pagination.

Main class

public static void main(String[] args) {
        String url = "https://www.cochranelibrary.com/cdsr/reviews/topics";
        MyContentFetcher myContentFetcher = new MyContentFetcher();
        MyParser myParser = new MyParser();
        try {
            // Load Topic list page
            String topicsPage = myContentFetcher.loadHTML(url);

            // Getting all the topics.
            Map<Integer, MyNode> topics = myParser.getTopicList(topicsPage);

            // Print all the topics and ask user to choose one
            for (int id : topics.keySet())
                System.out.println("-> " + id + " <- " + topics.get(id).getTopic());
            System.out.println("********************");
            System.out.print("Enter ID number from the list above to get reviews or enter anything else to exit:\n");
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String id = reader.readLine();

            // Validate user input, get the link and topic and cout the choice.
            if (isNumber(id)) {
                int idNum = Integer.parseInt(id);
                if (idNum <= topics.size() && idNum > 0) {
                    String topic = topics.get(idNum).getTopic();
                    String link = topics.get(idNum).getLink();
                    System.out.println("You picked: " + topic + link + "\n***************************");
                    // Loading first page of reviews
                    myParser.loadReviews(myContentFetcher.loadHTML(link), topic);
                    // Getting links to other pages
                    Queue<String> paginationLinks = myParser.getLinks();

                    // --------------> WORKS FINE UNTIL HERE <--------------
                    // Problem starts here....
                    // Load list of reviews for chosen topic
                    while(!paginationLinks.isEmpty()) {
                        String page = myContentFetcher.loadHTML(paginationLinks.remove());
                        myParser.loadReviews(page, topic);
                    }
                }
            }
            System.out.println("Exiting...");

        } catch (IOException e) {
            System.out.println("There was a problem...");
        }

!!!! Here is the class that fetches HTML. I'm probably doing something wrong here...

import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

import java.util.Scanner;

public class MyContentFetcher {

    public MyContentFetcher() {
    }

    String loadHTML(String url) throws IOException {
        // Create configurations for
        RequestConfig config = RequestConfig.custom()
                .setCircularRedirectsAllowed(true)
                .setCookieSpec(CookieSpecs.STANDARD)
                .build();
        // Creating a HttpClient object
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(config)
                .build();
        // Creating a HttpGet object
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("User-Agent", "Mozilla/5.0 (Linux; Android 8.1.0; Pixel Build/OPM4.171019.021.D1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.109 Mobile Safari/537.36 EdgA/42.0.0.2057");
        CloseableHttpResponse httpResponse = httpClient.execute(httpget);
        Scanner sc = new Scanner(httpResponse.getEntity().getContent());
        StringBuilder page = new StringBuilder("");
        while(sc.hasNext())
            page.append(sc.nextLine()).append(" ");
        httpResponse.close();
        httpClient.close();
        return page.toString();
    }
}

Here is the parser. Parser doesn't have any problems (Parse perfectly fine and as needed)

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class MyParser {

    private Map<String, String> topics;
    private Document htmlPage;
    private Element reviewBlock;

    public MyParser(){}

    // Loads all topics from the Cochrane Library into a map -> (Topic Name, Link)
    public Map<Integer, MyNode> getTopicList(String page) {
        Map<Integer, MyNode> topics= new HashMap<Integer, MyNode>();
        htmlPage = Jsoup.parse(page);
        // Get 'a' element that is inside 'li' with a class name of browse-by-list-item
        int i = 1;
        MyNode info;
        for(Element element : htmlPage.body().select("li.browse-by-list-item > a")) {
            info = new MyNode(element.select("button").text(),
                    element.select("a").attr("href").trim());
            topics.put(i, info);
            i++;
        }
        return topics;
    }

    // Loads Reviews
    public void loadReviews(String page, String topic) throws IOException {
        htmlPage = Jsoup.parse(page);
        // Get all review blocks
        System.out.println("**************************\n" + page + "\n**************************\n");
        for(Element element : htmlPage.body().select(".search-results-item-body")){
            reviewBlock = element;
            String review = getLink() + " | " + topic + " | " + getTitle() + " | " + getAuthor() + " | " + getDate();
            System.out.println(review);
        }
    }

    Queue<String> getLinks(){
        System.out.println("GETTING LINKS");
        Queue<String> links = new LinkedList<>();
        for(Element element : htmlPage.body().select("li.pagination-page-list-item > a")) {
            links.add(element.attr("href"));
        }
        return links;
    }

    private String getLink(){
        return "https://www.cochranelibrary.com" + reviewBlock.select("a").attr("href");
    }

    public String getTitle(){
        return reviewBlock.selectFirst("a").text();
    }

    public String getAuthor(){
        return reviewBlock.selectFirst("div.search-result-authors").text();
    }

    public String getDate(){
        String result = reviewBlock.select("div.search-result-date > div").text();
        try {
            SimpleDateFormat fmt = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
            Date d = fmt.parse(result);
            fmt.applyPattern("yyyy-MM-dd");
            result = fmt.format(d);
        } catch (ParseException e) {
            System.out.println("Failed parsing the date...");
        }
        return result;
    }


来源: stackexchange

问:
Use of function inside a for loop
I am trying to call functions inside a for loop, but I am not successful.
Is it possible to call functions in Python 3.x like you call subroutines in Excel?

Here is the code I tried but I do not get any output.

```<code>def my_fun1(i):
    x=+i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)
</code>```

答:
Your code contains a wrong logic and I am also assuming that the variable x is globally defined. See below.

```<code>def my_fun1(i):
    x=+i#I am assuming you want this x+=i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)

</code>```

ContentLicense: CC BY-SA 4.0

Title: Use of function inside a for loop

Body:
I am trying to call functions inside a for loop, but I am not successful.
Is it possible to call functions in Python 3.x like you call subroutines in Excel?

Here is the code I tried but I do not get any output.

def my_fun1(i):
    x=+i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)

Body:
Your code contains a wrong logic and I am also assuming that the variable x is globally defined. See below.

def my_fun1(i):
    x=+i#I am assuming you want this x+=i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)


问:
Difficulty understanding the benefits of BEM
I am trying to learn BEM and having difficulty appreciating it's benefits.  As an example, I went to Tailwind's Utility-First page to grab this code:

```<code><div class="chat-notification">
  <div class="chat-notification__logo-wrapper">
    <img class="chat-notification__logo" src="/img/logo.svg" alt="ChitChat Logo">
  </div>
  <div class="chat-notification__content">
    <h4 class="chat-notification__title">ChitChat</h4>
    <p class="chat-notification__message">You have a new message!</p>
  </div>
</div>

  .chat-notification {
    display: flex;
    max-width: 24rem;
    margin: 0 auto;
    padding: 1.5rem;
    border-radius: 0.5rem;
    background-color: #fff;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  }
  .chat-notification__logo-wrapper {
    flex-shrink: 0;
  }
  .chat-notification__logo {
    height: 3rem;
    width: 3rem;
  }
  .chat-notification__content {
    margin-left: 1.5rem;
    padding-top: 0.25rem;
  }
  .chat-notification__title {
    color: #1a202c;
    font-size: 1.25rem;
    line-height: 1.25;
  }
  .chat-notification__message {
    color: #718096;
    font-size: 1rem;
    line-height: 1.5;
  }
</code>```

When I look at it, I can't help but think it should be simplified to just

```<code><div class="chat-notification">
  <img src="logo.jpg" alt="ChitChat Logo">
  <h4>ChitChat</h4>
  <p>You have a new message!</p>
</div>

.chat-notification {
  position:relative;
    max-width: 24rem;
    margin: 0 auto;
    padding: 1.5rem;
    border-radius: 0.5rem;
    background-color: #fff;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  box-sizing:border-box;
  padding-left: 3.5rem;
}
.chat-notification img {
  position:absolute;
  top:0;
  left:0;
  clip: rect(0,200,400,0);
    width: 3rem;
}
.chat-notification h4 {
    color: #1a202c;
    font-size: 1.25rem;
    line-height: 1.25;
}
.chat-notification p {
    color: #718096;
    font-size: 1rem;
    line-height: 1.5;
}
</code>```

I basically simplified the HTML and got rid of unnecessary wrappers, divitis, classitis.  My question is why are class descriptors like __logo-wrapper and __title useful when tags like img, h4, p are already quite distinctive and semantic?

答:
The non-BEM CSS is tightly coupled to the HTML, I.e. changes to the HTML will likely lead to changes to the CSS. I’d argue this goes against SOLID coding principles, breaking the open-closed and possibly the single responsibility principle.

It’d be better if the CSS wasn’t so tightly coupled to the HTML.

BEM helps with this by allowing you to create an abstract structure of CSS classes that aren’t strictly tied to the HTML elements and can be applied more flexibly.

It comes at a cost that you and your team need to remember what that abstraction is but I feel it’s minimal because BEM is a fairly simple model.

You can also run into issues in large codebases where naming collisions can occur, but there are tools to help you get around this, such as CSS Modules.

Personally I love BEM and use it whenever I can.

Body:
I am trying to learn BEM and having difficulty appreciating it's benefits.  As an example, I went to Tailwind's Utility-First page to grab this code:

ChitChat

You have a new message!

  .chat-notification {
    display: flex;
    max-width: 24rem;
    margin: 0 auto;
    padding: 1.5rem;
    border-radius: 0.5rem;
    background-color: #fff;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  }
  .chat-notification__logo-wrapper {
    flex-shrink: 0;
  }
  .chat-notification__logo {
    height: 3rem;
    width: 3rem;
  }
  .chat-notification__content {
    margin-left: 1.5rem;
    padding-top: 0.25rem;
  }
  .chat-notification__title {
    color: #1a202c;
    font-size: 1.25rem;
    line-height: 1.25;
  }
  .chat-notification__message {
    color: #718096;
    font-size: 1rem;
    line-height: 1.5;
  }

When I look at it, I can't help but think it should be simplified to just

ChitChat

You have a new message!

.chat-notification {
  position:relative;
    max-width: 24rem;
    margin: 0 auto;
    padding: 1.5rem;
    border-radius: 0.5rem;
    background-color: #fff;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  box-sizing:border-box;
  padding-left: 3.5rem;
}
.chat-notification img {
  position:absolute;
  top:0;
  left:0;
  clip: rect(0,200,400,0);
    width: 3rem;
}
.chat-notification h4 {
    color: #1a202c;
    font-size: 1.25rem;
    line-height: 1.25;
}
.chat-notification p {
    color: #718096;
    font-size: 1rem;
    line-height: 1.5;
}

I basically simplified the HTML and got rid of unnecessary wrappers, divitis, classitis.  My question is why are class descriptors like __logo-wrapper and __title useful when tags like img, h4, p are already quite distinctive and semantic?


问:
ArcGIS Javascript API 4.14 popup field attributes not showing
I am using webamp to show the map created in ArcGIS (Javascript API in PHP website). In the map, a popup also appears when clicking on the layer's points. Recently I have updated the version 4.14 from 4.13. After updating it, the popup is not working properly. I have a custom popup template. After research in the documentation, I came to know there required a return function to show the custom div on the popup. The below code I have added to show my custom popups.

```<code>var template = { content: function(){ var div = document.createElement("div"); div.className = "myClass"; div.innerHTML = "<span>My custom content!</span>"; return div; } }

layers[layerIndex].popupTemplate = template;
</code>```

Now the popup appears fine. But I have to show the field values on the popup. I have used the required field attributes in double brackets eg: {Name}. But in the latest version, the field values are not appearing when I used the same.

The code I have used in version 4.13 and it was working,

```<code>popupTemplate = {
title: "{Name}",
content: '<div id="popup_address">{Address}</div><div class="right"><div href="#" id="popupRight" class="toggle"><p onClick="openPopupDetails({FACILITYID})">+</p></div></div>' };

layers[layerIndex].popupTemplate = popupTemplate;
</code>```

Please help me to fix this issue.

Thanks.

The complete code for the Webmap and custom popup
map.js

```<code>// The map classes and includ1a65d527bfd04cc180c87edf0908907bes
require([
  "esri/views/MapView",
  "esri/WebMap",
  "esri/widgets/Search",
  "esri/widgets/Zoom",
  "esri/widgets/Locate"
], function(MapView, WebMap, Search, Zoom, Locate) {
  var webmap = new WebMap({
    portalItem: {
      id: "d1ca798d8c7d4afab8983d911df8326b"
    }
  });

  var view = new MapView({
    map: webmap,
    container: "map",
    center: [-95.9406, 41.26],
    zoom: 16,
    maxZoom: 21,
    minZoom: 13,
    basemap: "topo",

    ui: {
      components: ["attribution"]
    }
  });

  webmap
    .load()
    .then(function() {
      return webmap.basemap.load();
    })
    .then(function() {
      let allLayers = webmap.allLayers;
      console.log(allLayers);

      var promises = allLayers.map(function(layer) {
        return layer.load();
      });
      return Promise.all(promises.toArray());
    })
    .then(function(layers) {
      // Position of the popup in relation to the selected feature.
      view.popup.alignment = "top-center";
      // To disable the collapse functionality
      view.popup.collapseEnabled = false;
      // A spinner appear at the pointer
      view.popup.spinnerEnabled = false;
      // To disable the dock (The popup will be appear in bottom or any corner of the window)
      view.popup.dockEnabled = false;
      // Disable the pagination
      view.popup.featureNavigationEnabled = false;
      // Popup template details, Keep only name and address in the popup and avoid all other details
      view.popup.viewModel.actions.getItemAt(0).visible = false;

      // view.on("click", function(event) {
      // keep a delay to align the popup and the pointer together positioned to the map center
      // Add animation only if the browser not IE
      // });

      layers.forEach(function(popupLayers, layerIndex) {
        console.log(popupLayers);

        var template = {
          title: "{Name}",
          content: function() {
            var div = document.createElement("div");
            div.className = "myClass";
            div.innerHTML = "<span>{Address}</span>";
            return div;
          }
        };
        layers[layerIndex].popupTemplate = template;

        // popupTemplate = {
        //   title: "{Name}",
        //   content:
        //     '<div id="popup_address">{Address}</div><div class="right"><div href="#" id="popupRight" class="toggle"><p onClick="openPopupDetails({FACILITYID})">+</p></div></div>'
        // };
        // layers[layerIndex].popupTemplate = popupTemplate;
      });

      // To close the popup when hit on esc button
      document.onkeyup = function(evt) {
        var key = evt.keyCode;
        if (key == 27) {
          view.popup.close();
        }
      };
    })
    .catch(function(error) {
      //   console.log(error);
    });
});
</code>```

Index.php

```<code><html>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="initial-scale=1,maximum-scale=1,user-scalable=no"
    />

<title>Load a basic WebMap - 4.14</title>

    <style>
      html,
      body,
      #map {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>

    <link
      rel="stylesheet"
      href="https://js.arcgis.com/4.14/esri/themes/light/main.css"
    />

    <script src="https://js.arcgis.com/4.14/"></script>
<script src="map.js"></script>
  </head>

  <body>
    <div id="map"></div>
  </body>
</html>
</code>```

I have modified the code,

```<code> for (let i = 2; i < layers.length; i++) {
        var template = {
          title: "{Name}",
          content: function() {
            var div = document.createElement("div");
            div.innerHTML =
              '<div id="popup_address">{Address}</div><div class="right"><div href="#" id="popupRight" class="toggle"><p onClick="openPopupDetails({FACILITYID})">+</p></div></div>';
            return div;
          }
        };
        layers[i].popupTemplate = template;
        console.log(layer[i]);
      }
</code>```

When I apply custom div, the {Address} part is not rendering. It appears like {Address} itself.

答:
I think you are a bit confuse, you still can use a string, or you can use a function for the content of the popup template. So if you want to use a function, you can use something like this,

```<code>popupTemplate = {
    title: "{Name}",
    content: popupContentChange
}

layers[layerIndex].popupTemplate = template;

function popupContentChange(feature) {
    let div = document.createElement("div");
    div.className = "myClass";
    div.innerHTML = "<span>"+feature.graphic.attributes.Address+"</span>";
    return div;
}
</code>```

There are several examples in the API documentation, take a look there. Just to reference one, ArcGIS JavaScript API Examples - Intro to Popups

Here an example I made for you taking your code as base adding some fixes to display what you want.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="initial-scale=1,maximum-scale=1,user-scalable=no"
    />
    <title>Sketch Feature Coords</title>
    <link
      rel="stylesheet"
      href="https://js.arcgis.com/4.14/esri/themes/light/main.css"
    />

```
</div>
</div>
</p>

<p>If you want to use a function as content, you have to set the <code>outFields</code> parameter to include the fields you want to use in the function. The selected feature is pass as a parameter to the function, and inside you use <code>feature.graphic.attributes</code> to access the attributes. This should work,</p>

```var template = {
    title: "{Name}",
    // content: "Address: {Address}"
    content: function(feature) {
        console.log(feature);
        var div = document.createElement("div");
        div.className = "myClass";
        div.innerHTML = "Address:"+feature.graphic.attributes.Address+"";
        return div;
    },
    outFields: ["Name", "Address"]
};
```

Body:
I am using webamp to show the map created in ArcGIS (Javascript API in PHP website). In the map, a popup also appears when clicking on the layer's points. Recently I have updated the version 4.14 from 4.13. After updating it, the popup is not working properly. I have a custom popup template. After research in the documentation, I came to know there required a return function to show the custom div on the popup. The below code I have added to show my custom popups.

var template = { content: function(){ var div = document.createElement("div"); div.className = "myClass"; div.innerHTML = "My custom content!"; return div; } }

layers[layerIndex].popupTemplate = template;

Now the popup appears fine. But I have to show the field values on the popup. I have used the required field attributes in double brackets eg: {Name}. But in the latest version, the field values are not appearing when I used the same.

The code I have used in version 4.13 and it was working,

popupTemplate = {
title: "{Name}",
content: '
{Address}

+

' };

layers[layerIndex].popupTemplate = popupTemplate;

Please help me to fix this issue.

Thanks.

The complete code for the Webmap and custom popup
map.js

// The map classes and includ1a65d527bfd04cc180c87edf0908907bes
require([
  "esri/views/MapView",
  "esri/WebMap",
  "esri/widgets/Search",
  "esri/widgets/Zoom",
  "esri/widgets/Locate"
], function(MapView, WebMap, Search, Zoom, Locate) {
  var webmap = new WebMap({
    portalItem: {
      id: "d1ca798d8c7d4afab8983d911df8326b"
    }
  });

  var view = new MapView({
    map: webmap,
    container: "map",
    center: [-95.9406, 41.26],
    zoom: 16,
    maxZoom: 21,
    minZoom: 13,
    basemap: "topo",

    ui: {
      components: ["attribution"]
    }
  });

  webmap
    .load()
    .then(function() {
      return webmap.basemap.load();
    })
    .then(function() {
      let allLayers = webmap.allLayers;
      console.log(allLayers);

      var promises = allLayers.map(function(layer) {
        return layer.load();
      });
      return Promise.all(promises.toArray());
    })
    .then(function(layers) {
      // Position of the popup in relation to the selected feature.
      view.popup.alignment = "top-center";
      // To disable the collapse functionality
      view.popup.collapseEnabled = false;
      // A spinner appear at the pointer
      view.popup.spinnerEnabled = false;
      // To disable the dock (The popup will be appear in bottom or any corner of the window)
      view.popup.dockEnabled = false;
      // Disable the pagination
      view.popup.featureNavigationEnabled = false;
      // Popup template details, Keep only name and address in the popup and avoid all other details
      view.popup.viewModel.actions.getItemAt(0).visible = false;

      // view.on("click", function(event) {
      // keep a delay to align the popup and the pointer together positioned to the map center
      // Add animation only if the browser not IE
      // });

      layers.forEach(function(popupLayers, layerIndex) {
        console.log(popupLayers);

        var template = {
          title: "{Name}",
          content: function() {
            var div = document.createElement("div");
            div.className = "myClass";
            div.innerHTML = "{Address}";
            return div;
          }
        };
        layers[layerIndex].popupTemplate = template;

        // popupTemplate = {
        //   title: "{Name}",
        //   content:
        //     '
{Address}

+

'
        // };
        // layers[layerIndex].popupTemplate = popupTemplate;
      });

      // To close the popup when hit on esc button
      document.onkeyup = function(evt) {
        var key = evt.keyCode;
        if (key == 27) {
          view.popup.close();
        }
      };
    })
    .catch(function(error) {
      //   console.log(error);
    });
});

Index.php

    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="initial-scale=1,maximum-scale=1,user-scalable=no"
    />

<title>Load a basic WebMap - 4.14</title>

    <link
      rel="stylesheet"
      href="https://js.arcgis.com/4.14/esri/themes/light/main.css"
    />

I have modified the code,

 for (let i = 2; i < layers.length; i++) {
        var template = {
          title: "{Name}",
          content: function() {
            var div = document.createElement("div");
            div.innerHTML =
              '
{Address}

+

';
            return div;
          }
        };
        layers[i].popupTemplate = template;
        console.log(layer[i]);
      }

When I apply custom div, the {Address} part is not rendering. It appears like {Address} itself.

Body:
I think you are a bit confuse, you still can use a string, or you can use a function for the content of the popup template. So if you want to use a function, you can use something like this,

popupTemplate = {
    title: "{Name}",
    content: popupContentChange
}

layers[layerIndex].popupTemplate = template;

function popupContentChange(feature) {
    let div = document.createElement("div");
    div.className = "myClass";
    div.innerHTML = "<span>"+feature.graphic.attributes.Address+"</span>";
    return div;
}

There are several examples in the API documentation, take a look there. Just to reference one, ArcGIS JavaScript API Examples - Intro to Popups

Here an example I made for you taking your code as base adding some fixes to display what you want.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="initial-scale=1,maximum-scale=1,user-scalable=no"
    />
    <title>Sketch Feature Coords</title>
    <link
      rel="stylesheet"
      href="https://js.arcgis.com/4.14/esri/themes/light/main.css"
    />
    <script src="https://js.arcgis.com/4.14/"></script>
    <style>
      html,
      body,
      #map {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>
    <script>
      require([
        "esri/views/MapView",
        "esri/WebMap",
        "esri/widgets/Search",
        "esri/widgets/Zoom",
        "esri/widgets/Locate"
      ], function(MapView, WebMap, Search, Zoom, Locate) {
        var webmap = new WebMap({
          portalItem: {
            id: "d1ca798d8c7d4afab8983d911df8326b"
          }
        });

        var view = new MapView({
          map: webmap,
          container: "map",
          center: [-95.9406, 41.26],
          zoom: 16,
          maxZoom: 21,
          minZoom: 13,
          basemap: "topo",
          ui: {
            components: ["attribution"]
          }
        });
        webmap
          .load()
          .then(function() {
            return webmap.basemap.load();
          })
          .then(function() {
            let allLayers = webmap.allLayers;
            console.log(allLayers);
            var promises = allLayers.map(function(layer) {
              return layer.load();
            });
            return Promise.all(promises.toArray());
          })
          .then(function(layers) {
            // Position of the popup in relation to the selected feature.
            view.popup.alignment = "top-center";
            // To disable the collapse functionality
            view.popup.collapseEnabled = false;
            // A spinner appear at the pointer
            view.popup.spinnerEnabled = false;
            // To disable the dock (The popup will be appear in bottom or any corner of the window)
            view.popup.dockEnabled = false;
            // Disable the pagination
            view.popup.featureNavigationEnabled = false;
            // Popup template details, Keep only name and address in the popup and avoid all other details
            view.popup.viewModel.actions.getItemAt(0).visible = false;

            // it is only going to work on the last two layers
            // those are the one that have fields: Name and Address
            for (let i = 2; i < layers.length; i++) {
              var template = {
                title: "{Name}",
                content: "<span>Address: {Address}</span>"
              };
              layers[i].popupTemplate = template;
              console.log(layer[i]);
            }

            // To close the popup when hit on esc button
            document.onkeyup = function(evt) {
              var key = evt.keyCode;
              if (key == 27) {
                view.popup.close();
              }
            };
          })
          .catch(function(error) {
            console.log(error);
          });
    });
    </script>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>

If you want to use a function as content, you have to set the outFields parameter to include the fields you want to use in the function. The selected feature is pass as a parameter to the function, and inside you use feature.graphic.attributes to access the attributes. This should work,

var template = {
    title: "{Name}",
    // content: "<span>Address: {Address}</span>"
    content: function(feature) {
        console.log(feature);
        var div = document.createElement("div");
        div.className = "myClass";
        div.innerHTML = "<span>Address:"+feature.graphic.attributes.Address+"</span>";
        return div;
    },
    outFields: ["Name", "Address"]
};


问:
How can I access router params in JSX?
Am trying to edit post by it's id and I would like pass the id a a prop to the EditPost component how do I go about it?</p>

```<code>  render() {
    return (
      <Router>
      <Switch >
        <Route path="/edit/:id">
          <EditPost index={/*what do I do here?*/} />
        </Route>
      </Switch>
      </Router>
    );
  }
</code>```

答:
In your EditPost component you can do it like this:

```<code>import { useParams } from "react-router-dom";

const EditPost = () => {
  const params = useParams();

  return <p>Your Post ID is: {params.id}</p>
}

export default EditPost;
</code>```

And make your route as:

```<code><Route path="/edit/:id">
  <EditPost />
</Route>
</code>```

Hope this works for you.

Title: How can I access router params in JSX?

Body:
Am trying to edit post by it's id and I would like pass the id a a prop to the EditPost component how do I go about it?

  render() {
    return (
      <Router>
      <Switch >
        <Route path="/edit/:id">
          <EditPost index={/*what do I do here?*/} />
        </Route>
      </Switch>
      </Router>
    );
  }

Body:
In your EditPost component you can do it like this:

import { useParams } from "react-router-dom";

const EditPost = () => {
  const params = useParams();

  return <p>Your Post ID is: {params.id}</p>
}

export default EditPost;

And make your route as:

<Route path="/edit/:id">
  <EditPost />
</Route>

Hope this works for you.


问:
'import ase' does not load submodule 'ase.io'
I experienced a problem using the 'import module' instead of the 'from module import ...' syntax. This clearly shows that my understanding of loading modules is not sufficient. As far as I find elsewhere, this difference is mainly a style issue, but this does not explains the following situation.

I installed ase using

```<code>sudo apt install python3-ase
</code>```

I tried the following:

```<code>import ase
ase.io.read
</code>```

which outputs

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ase' has no attribute 'io'
</code>```

However, when trying

```<code>from ase.io import read
read
</code>```

or - also possible -

```<code>from ase.io import read
import ase
ase.io.read
</code>```

I get the output

```<code><function read at 0x7f33dc721730>
</code>```

The latter is the desired result as I want to use the ase.io.read function to read a .cif file.

More about the origin of the problem is shown in the following python session:

```<code>import sys
import ase
sys.modules['ase']
</code>```

module 'ase' from '/home/vanbeverj/Programs/anaconda3/envs/abienv/lib/python3.6/site-packages/ase/init.py'

```<code>dir(ase)
</code>```

['Atom', 'Atoms', 'LooseVersion', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'version', 'ase', 'atom', 'atoms', 'calculators', 'cell', 'constraints', 'data', 'dft', 'formula', 'geometry', 'np', 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

```<code>from ase.io import read
dir(ase)
</code>```

['Atom', 'Atoms', 'LooseVersion', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'version', 'ase', 'atom', 'atoms', 'calculators', 'cell', 'constraints', 'data', 'dft', 'formula', 'geometry', 'io', 'np', 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

The 'dir(ase)' commands have clearly different outputs. What happens with e.g. the io submodule? Can someone explains me what is going on under the hood?

答:
I think it seems like tkinter.
In tkinter,if we want to use ttk,we must use

```<code>import tkinter
from tkinter import ttk
</code>```

if we use

```<code>import tkinter

.......
btn = tkinter.ttk.Button(xxxxxx)
</code>```

Then it will show AttributeError: module 'tkinter' has no attribute 'ttk'.

You can see the ase module source.In ase > __init__.py file,import ase means that import all of class or function in __init__.py.

from ase import io,maybe it means that it will import the io module(io is a independent .py file) in ase folder

Body:
I experienced a problem using the 'import module' instead of the 'from module import ...' syntax. This clearly shows that my understanding of loading modules is not sufficient. As far as I find elsewhere, this difference is mainly a style issue, but this does not explains the following situation.

I installed ase using

sudo apt install python3-ase

I tried the following:

import ase
ase.io.read

which outputs

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ase' has no attribute 'io'

However, when trying

from ase.io import read
read

or - also possible -

from ase.io import read
import ase
ase.io.read

I get the output

<function read at 0x7f33dc721730>

The latter is the desired result as I want to use the ase.io.read function to read a .cif file.

More about the origin of the problem is shown in the following python session:

import sys
import ase
sys.modules['ase']

module 'ase' from '/home/vanbeverj/Programs/anaconda3/envs/abienv/lib/python3.6/site-packages/ase/init.py'

dir(ase)

['Atom', 'Atoms', 'LooseVersion', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'version', 'ase', 'atom', 'atoms', 'calculators', 'cell', 'constraints', 'data', 'dft', 'formula', 'geometry', 'np', 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

from ase.io import read
dir(ase)

['Atom', 'Atoms', 'LooseVersion', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'version', 'ase', 'atom', 'atoms', 'calculators', 'cell', 'constraints', 'data', 'dft', 'formula', 'geometry', 'io', 'np', 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

The 'dir(ase)' commands have clearly different outputs. What happens with e.g. the io submodule? Can someone explains me what is going on under the hood?

Body:
I think it seems like tkinter.
In tkinter,if we want to use ttk,we must use

import tkinter
from tkinter import ttk

if we use

import tkinter

.......
btn = tkinter.ttk.Button(xxxxxx)

Then it will show AttributeError: module 'tkinter' has no attribute 'ttk'.

You can see the ase module source.In ase > __init__.py file,import ase means that import all of class or function in __init__.py.

from ase import io,maybe it means that it will import the io module(io is a independent .py file) in ase folder


问:
Set value to a variable in a CASE statement
Background:
I have a tabel called History. In this table i have 3 different columns that represents 3 different types of adresses (domestic adress, foreign adress and other adress). A record set from this tabel may contain values for one, more or none of these adress types. I am therefore trying to retrieve the adresstype and it's value by using a CASE statement and assigning the value to a variable.

Question:
I get no errors in my query but it returns nothing. What am i doing wrong?

```<code>DECLARE @vAdress AS VARCHAR(50)

SELECT H.FIRSTNAME, H.LASTNAME, @vAdress, C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
AND @vAdress = CASE
                   WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
                   WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
                   ELSE H.O_ADRESS
               END
</code>```

答:
you should not use a variable and do not use the case statement within the where clause. Try this:</p>

```<code>SELECT H.FIRSTNAME, H.LASTNAME, CASE
                   WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
                   WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
                   ELSE H.O_ADRESS
               END as vAdress, C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
</code>```

Body:
Background:
I have a tabel called History. In this table i have 3 different columns that represents 3 different types of adresses (domestic adress, foreign adress and other adress). A record set from this tabel may contain values for one, more or none of these adress types. I am therefore trying to retrieve the adresstype and it's value by using a CASE statement and assigning the value to a variable.

Question:
I get no errors in my query but it returns nothing. What am i doing wrong?

DECLARE @vAdress AS VARCHAR(50)

SELECT H.FIRSTNAME, H.LASTNAME, @vAdress, C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'
AND @vAdress = CASE
                   WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
                   WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
                   ELSE H.O_ADRESS
               END

Body:
you should not use a variable and do not use the case statement within the where clause. Try this:

SELECT H.FIRSTNAME, H.LASTNAME, CASE
                   WHEN H.D_ADRESS IS NOT NULL THEN H.D_ADRESS
                   WHEN H.F_ADRESS IS NOT NULL THEN H.F_ADRESS
                   ELSE H.O_ADRESS
               END as vAdress, C.COUNTRY
FROM History H
LEFT JOIN COUNTRY C
ON H.COUNTRYCODE = C.COUNTRYCODE
WHERE H.EMAILADRESS = 'johndoe.doe@test.com'


答:
Have you tried the strptime(string, format) function from the datetime module ? Since all of your string are in the same date format, you can easily loop through them

https://docs.python.org/3/library/datetime.html?highlight=strptime#datetime.datetime.strptime

Title: How to convert date from string format in python

Body:
I have below table. I want to count timedelta between first and second date, second and third and so on in a for loop…
I really do not want to convert my dates in table to integer set to use timedelta() function. Is there any function in python which can convert str like: ’30.06.2019’ or 30/06/2019 to date ?
Perfect would be convert all tab[i][2] to date and then count time date between them in a loop.

tab = [ [21091705,  0,'30.06.2019'],
        [21091705,  653777,'29.06.2019'],
        [21091705,  653842,'29.06.2019'],
        [21091705,  641701,'28.06.2019'],
        [21091705,  642000,'27.06.2019'],
        [21091705,  0,'25.06.2019'],
        [21091705,  642030,'25.06.2019'],
        [21091705,  642030,'25.06.2019'],
        [21091705,  637030,'25.06.2019'],
        [21091705,  0,'25.06.2019'],
        [21091705,  0,'17.05.2019'],
        [21091705,  0,'25.06.2019']
        ]


问:
Ab initio to read comma delimited values
What should be my DML for input file which has data like 1,2,34,43,66

The problem which i am facing when i put the below DML

record
decimal(",") val;
end;

is that the last number is not getting read properly.

Is there any way to read this by only using Input file component.

答:
I presume you want to read each number as a record. The problem is: data is not compatible with your desire, last number is not delimited by a ",".

If you can't change the data, you could read all the input in a single record, using:

```<code>record
 string("\n") val;
end
</code>```

then use a normalize component to split the record:

```<code>out :: length(in) =
begin
  out :: length_of(string_split(in.val, ","));
end;

out :: normalize(in, index) =
begin
   let string(";")[5] my_vec;
   my_vec =  string_split(in.val, ",");
   out.val :: decimal_lpad( my_vec[index], 5 );
end;
</code>```

(there are probably better solutions, I am still not an expert, but there wasn't an answer yet)

Body:
I presume you want to read each number as a record. The problem is: data is not compatible with your desire, last number is not delimited by a ",".

If you can't change the data, you could read all the input in a single record, using:

record
 string("\n") val;
end

then use a normalize component to split the record:

out :: length(in) =
begin
  out :: length_of(string_split(in.val, ","));
end;

out :: normalize(in, index) =
begin
   let string(";")[5] my_vec;
   my_vec =  string_split(in.val, ",");
   out.val :: decimal_lpad( my_vec[index], 5 );
end;

(there are probably better solutions, I am still not an expert, but there wasn't an answer yet)


问:
How to test an aspect with SpringBootTest?
I created a simple aspect in Spring using Spring Boot 2.1.6.RELEASE.
It basically logs the total time spent on a method.

```<code>@Aspect
@Component
public class TimeLoggerAspect {

  private static final Logger log = LoggerFactory.getLogger(TimeLoggerAspect.class);

  @Around("@annotation(demo.TimeLogger)")
  public Object methodTimeLogger(ProceedingJoinPoint joinPoint)
          throws Throwable {
    long startTime = System.currentTimeMillis();

    Object proceed = joinPoint.proceed();

    long totalTime = System.currentTimeMillis() - startTime;
    log.info("Method " + joinPoint.getSignature() + ": " + totalTime + "ms");

    return proceed;
  }
}
</code>```

the aspect is triggered by a TimeLogger annotation

```<code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TimeLogger {
}
</code>```

and is used in a component like this

```<code>@Component
public class DemoComponent {
  @TimeLogger
  public void sayHello() {
    System.out.println("hello");
  }
}
</code>```

A spring boot demo application will invoke sayHello via the run method of the CommandLineRunner interface.

```<code>@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

  @Autowired
  private DemoComponent demoComponent;

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

  @Override
  public void run(String... args) throws Exception {
    demoComponent.sayHello();
  }
}
</code>```

For completeness, I add my modifications in build.gradle: adding libraries for aop, spring test and jupiter (junit).

```<code>    compile("org.springframework.boot:spring-boot-starter-aop")

    testCompile("org.springframework.boot:spring-boot-starter-test")
    testCompile("org.junit.jupiter:junit-jupiter-api")
    testRuntime("org.junit.jupiter:junit-jupiter-engine")
</code>```

Running the application will output (trimmed for readability)

```<code>hello
... TimeLoggerAspect : Method void demo.DemoComponent.sayHello(): 4ms

</code>```

So far, so good. Now I create a test based on @SpringBootTest annotation and jupiter.

```<code>import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {DemoComponent.class, TimeLoggerAspect.class})
public class DemoComponentFailTest {

  @Autowired
  private DemoComponent demoComponent;

  @Test
  public void shouldLogMethodTiming() {
      demoComponent.sayHello();
  }
}
</code>```

and here I get the output

```<code>hello
</code>```

No output from the TimeLoggerAspect, since it seems it is not being triggered.

Is something missing to trigger the aspect in the test? Or are there other ways of testing the aspect in spring boot?

答:
You have to put @EnableAspectJAutoProxy with your file @Configuration that declares the bean with @Aspect.

```<code>@Aspect
@Configuration
@EnableAspectJAutoProxy
public class TimeLoggerAspect {

  private static final Logger log = LoggerFactory.getLogger(TimeLoggerAspect.class);

  @Around("@annotation(demo.TimeLogger)")
  public Object methodTimeLogger(ProceedingJoinPoint joinPoint)
          throws Throwable {
    long startTime = System.currentTimeMillis();

    Object proceed = joinPoint.proceed();

    long totalTime = System.currentTimeMillis() - startTime;
    log.info("Method " + joinPoint.getSignature() + ": " + totalTime + "ms");

    return proceed;
  }
}
</code>```

I think that will do the work.

Body:
I created a simple aspect in Spring using Spring Boot 2.1.6.RELEASE.
It basically logs the total time spent on a method.

@Aspect
@Component
public class TimeLoggerAspect {

  private static final Logger log = LoggerFactory.getLogger(TimeLoggerAspect.class);

  @Around("@annotation(demo.TimeLogger)")
  public Object methodTimeLogger(ProceedingJoinPoint joinPoint)
          throws Throwable {
    long startTime = System.currentTimeMillis();

    Object proceed = joinPoint.proceed();

    long totalTime = System.currentTimeMillis() - startTime;
    log.info("Method " + joinPoint.getSignature() + ": " + totalTime + "ms");

    return proceed;
  }
}

the aspect is triggered by a TimeLogger annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TimeLogger {
}

and is used in a component like this

@Component
public class DemoComponent {
  @TimeLogger
  public void sayHello() {
    System.out.println("hello");
  }
}

A spring boot demo application will invoke sayHello via the run method of the CommandLineRunner interface.

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

  @Autowired
  private DemoComponent demoComponent;

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

  @Override
  public void run(String... args) throws Exception {
    demoComponent.sayHello();
  }
}

For completeness, I add my modifications in build.gradle: adding libraries for aop, spring test and jupiter (junit).

    compile("org.springframework.boot:spring-boot-starter-aop")

    testCompile("org.springframework.boot:spring-boot-starter-test")
    testCompile("org.junit.jupiter:junit-jupiter-api")
    testRuntime("org.junit.jupiter:junit-jupiter-engine")

Running the application will output (trimmed for readability)

hello
... TimeLoggerAspect : Method void demo.DemoComponent.sayHello(): 4ms

So far, so good. Now I create a test based on @SpringBootTest annotation and jupiter.

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {DemoComponent.class, TimeLoggerAspect.class})
public class DemoComponentFailTest {

  @Autowired
  private DemoComponent demoComponent;

  @Test
  public void shouldLogMethodTiming() {
      demoComponent.sayHello();
  }
}

and here I get the output

hello

No output from the TimeLoggerAspect, since it seems it is not being triggered.

Is something missing to trigger the aspect in the test? Or are there other ways of testing the aspect in spring boot?

Body:
You have to put @EnableAspectJAutoProxy with your file @Configuration that declares the bean with @Aspect.

@Aspect
@Configuration
@EnableAspectJAutoProxy
public class TimeLoggerAspect {

  private static final Logger log = LoggerFactory.getLogger(TimeLoggerAspect.class);

  @Around("@annotation(demo.TimeLogger)")
  public Object methodTimeLogger(ProceedingJoinPoint joinPoint)
          throws Throwable {
    long startTime = System.currentTimeMillis();

    Object proceed = joinPoint.proceed();

    long totalTime = System.currentTimeMillis() - startTime;
    log.info("Method " + joinPoint.getSignature() + ": " + totalTime + "ms");

    return proceed;
  }
}

I think that will do the work.


问:
Submit button won't line up vertically with other fields on the same line
Can anybody shed some light on why this submit button won't line up vertically with the other form fields on the line?

http://www.e-fluential.com/offline/castoff/

答:
add css style to submit button like this:

.submit{float:right;margin-top:-2px}

and adjust margin-right to your needs then

ContentLicense: CC BY-SA 3.0


问:
Character Encoding in POST JSON Request
I am sending a POST JSON Request to my application.

```<code>POST /CharSetTest/Test HTTP/1.1
Host: localhost:8090
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 1637b92b-5896-4765-63c5-d04ad73ea9f1

{
  "SampleRequest": {
    "FullName": "関連当"
  }
}
</code>```

My CXF JAXRS Consumer is defined as below.

```<code>@POST
@Produces("application/json; charset=UTF-8")
@Consumes("application/json; charset=UTF-8")
public Response testCharSet(@Encoded String jsonBody);
</code>```

But the Japanese Character (関連当) that I sent as POST request is not encoded and results in some junk characters "é¢é£å½äºè"

Using SoapUI results in "?????" characters.

This Junk characters differs from client to client from where I hit the request. How Could I encode my POST Request ?

答:
I had a similar problem and solved it bu setting HttpServletResponse instance's character encoding to utf-8 :  </p>

```<code>response.setCharacterEncoding("utf-8");
</code>```

Title: Character Encoding in POST JSON Request

Body:
I am sending a POST JSON Request to my application.

POST /CharSetTest/Test HTTP/1.1
Host: localhost:8090
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 1637b92b-5896-4765-63c5-d04ad73ea9f1

{
  "SampleRequest": {
    "FullName": "関連当"
  }
}

My CXF JAXRS Consumer is defined as below.

@POST
@Produces("application/json; charset=UTF-8")
@Consumes("application/json; charset=UTF-8")
public Response testCharSet(@Encoded String jsonBody);

But the Japanese Character (関連当) that I sent as POST request is not encoded and results in some junk characters "é¢é£å½äºè"

Using SoapUI results in "?????" characters.

This Junk characters differs from client to client from where I hit the request. How Could I encode my POST Request ?

Body:
I had a similar problem and solved it bu setting HttpServletResponse instance's character encoding to utf-8 :

response.setCharacterEncoding("utf-8");


问:
Visualising two very different distributions in one plot
This is more of a "how would you do it" than a "how to do it" question.

I have two groups, "a" and "b". "b" consists of responses that are normally distributed, more or less, bounded between 0-1. "a", however, is mostly 1-s.

The process that generated the data is a questionnaire. People in group "b" made mistakes, people in group "a" mostly figured it out.

How do I visualise these data side by side? Boxplots are messed up because the median of one of the groups is basically 1. Violin plots mess up the widths.

Here is a reproducible example with the rough idea.

```<code>library(tidyverse)

d = tibble(
  val= c(
    rnorm(100, mean = 0.5, sd = 0.25),
    rnorm(5, mean = 0.5, sd = 0.25),
    rep(1, 95)
  ),
  var = c(
    rep('a', 100), rep('b', 100)
  )
) %>%
  filter(
    val >= 0,
    val <= 1
         )

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_jitter() +
  geom_violin()

# No.

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_boxplot()

# No-no.

</code>```

答:
To my mind, interesting visualizations can also be accomplished with the nice {ggridges} package, for example with

```<code>d %>%
  ggplot() +
  aes(x = val, y = var) +
  ggridges::stat_density_ridges(quantile_lines = TRUE) +
  ggridges::theme_ridges()
</code>```

Edit: yes, the smoothing on the tails is indeed unfortunate in that case, maybe using geom_density_riges(stat = "binline") instead of stat_density_ridges() would do the trick here? But again, not optimal I guess...

Body:
This is more of a "how would you do it" than a "how to do it" question.

I have two groups, "a" and "b". "b" consists of responses that are normally distributed, more or less, bounded between 0-1. "a", however, is mostly 1-s.

The process that generated the data is a questionnaire. People in group "b" made mistakes, people in group "a" mostly figured it out.

How do I visualise these data side by side? Boxplots are messed up because the median of one of the groups is basically 1. Violin plots mess up the widths.

Here is a reproducible example with the rough idea.

library(tidyverse)

d = tibble(
  val= c(
    rnorm(100, mean = 0.5, sd = 0.25),
    rnorm(5, mean = 0.5, sd = 0.25),
    rep(1, 95)
  ),
  var = c(
    rep('a', 100), rep('b', 100)
  )
) %>%
  filter(
    val >= 0,
    val <= 1
         )

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_jitter() +
  geom_violin()

# No.

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_boxplot()

# No-no.

Body:
To my mind, interesting visualizations can also be accomplished with the nice {ggridges} package, for example with

d %>%
  ggplot() +
  aes(x = val, y = var) +
  ggridges::stat_density_ridges(quantile_lines = TRUE) +
  ggridges::theme_ridges()

Edit: yes, the smoothing on the tails is indeed unfortunate in that case, maybe using geom_density_riges(stat = "binline") instead of stat_density_ridges() would do the trick here? But again, not optimal I guess...


问:
Interactions pane unresponsive when I test this code
This is my first post so if there are formatting issues, I'm sorry.
So long story short, every time I compile this code in DrJava the interactions pane becomes unresponsive, but the program itself is fine.

```<code>import java.util.Scanner;
import java.lang.Math;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.*;
class Main {

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter words, enter STOP to stop the loop.");
    ArrayList <String>words = new ArrayList
      <String>();
    boolean end = false;
    while(end == false){
     String stop = "STOP";
     String word = "";
     for(int i = 0; Objects.equals(stop, word); i++){
       word = scan.nextLine();
       if(Objects.equals(stop, word) && i > 2){
         System.out.print(words.size());
         words.remove(0);
         words.remove(i);
         System.out.println(words);
         end = true;
       } else if(Objects.equals(stop, word) && i < 2){
         System.out.print(words.size());
         System.out.println(words);
         end = true;
       } else {
         words.add(i, word);
       }
       System.out.println();
    }
   }
  }
}
</code>```

The objective of this code is: Write a Java program that allows a user to input words at the command line.  Your program should stop accepting words when the user enters "STOP".  Store the words in an ArrayList.  The word STOP should not be stored in the list.

Next, print the size of the list, followed by the contents of the list.

Then, remove the first and last words stored in the list, but only if the list has a length greater than two.  Finally, reprint the contents of the list.

This is a class assignment, so I am not trying to get the answer to the coding problem itself, but rather just the reason the interactions pane isn't responding. Thanks in advance!

答: Removing the for-loop: for(int i = 0; Objects.equals(stop, word); i++), as @MZ97 suggested, caused the interaction pane work as normal.</p>

Body:
This is my first post so if there are formatting issues, I'm sorry.
So long story short, every time I compile this code in DrJava the interactions pane becomes unresponsive, but the program itself is fine.

import java.util.Scanner;
import java.lang.Math;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.*;
class Main {

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter words, enter STOP to stop the loop.");
    ArrayList <String>words = new ArrayList
      <String>();
    boolean end = false;
    while(end == false){
     String stop = "STOP";
     String word = "";
     for(int i = 0; Objects.equals(stop, word); i++){
       word = scan.nextLine();
       if(Objects.equals(stop, word) && i > 2){
         System.out.print(words.size());
         words.remove(0);
         words.remove(i);
         System.out.println(words);
         end = true;
       } else if(Objects.equals(stop, word) && i < 2){
         System.out.print(words.size());
         System.out.println(words);
         end = true;
       } else {
         words.add(i, word);
       }
       System.out.println();
    }
   }
  }
}

The objective of this code is: Write a Java program that allows a user to input words at the command line.  Your program should stop accepting words when the user enters "STOP".  Store the words in an ArrayList.  The word STOP should not be stored in the list.

Next, print the size of the list, followed by the contents of the list.

Then, remove the first and last words stored in the list, but only if the list has a length greater than two.  Finally, reprint the contents of the list.

This is a class assignment, so I am not trying to get the answer to the coding problem itself, but rather just the reason the interactions pane isn't responding. Thanks in advance!


问:
SQL query for group by result in different column
I Have table having 2 columns

Column1 Value
   A     10
   B     20
   C     11
   A     40
   B     30
   C     22
```

<p>I Want Result like</p>

<pre class="lang-none prettyprint-override"><code>Column1 Value1 Value2
A       10      40
B       20      30
C       11      22
</code>```

Is there any query or store Procdure to get such Output

答:
If there's more then 2 Value columns then MIN & MAX won't do.

Then you can use ROW_NUMBER to calculate numbered values, and use that in a PIVOT

```<code>SELECT *
FROM
(
    SELECT Column1, [Value]
    , Col = CONCAT('Value', ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY [Value]))
    FROM YourTable
) Src
PIVOT (
    MAX([Value])
     -- add more columns here
    FOR Col IN (Value1, Value2)
) Pvt
</code>```

Body:
I Have table having 2 columns

Column1 Value
   A     10
   B     20
   C     11
   A     40
   B     30
   C     22

I Want Result like

Column1 Value1 Value2
A       10      40
B       20      30
C       11      22

Is there any query or store Procdure to get such Output

Body:
If there's more then 2 Value columns then MIN & MAX won't do.

Then you can use ROW_NUMBER to calculate numbered values, and use that in a PIVOT

SELECT *
FROM
(
    SELECT Column1, [Value]
    , Col = CONCAT('Value', ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY [Value]))
    FROM YourTable
) Src
PIVOT (
    MAX([Value])
     -- add more columns here
    FOR Col IN (Value1, Value2)
) Pvt


问:
sql - Increment number over some specific record occurrences
I'm using Amazon Redshift. I have a flag column containing either 0 or 1 based on a certain condition and everything sorted by ascending time, and I want a number (DesiredPartition) to increment whenever there's a 1 Flag. This is not possible with partitioning ofcourse.

```<code>| DesiredPartition | FlagValue | Time |
|------------------|-----------|------|
| 1                | 0         |      |
| 1                | 0         |      |
| 1                | 0         |      |
| 2                | 1         |      |
| 2                | 0         |      |
| 2                | 0         |      |
| 3                | 1         |      |
| 3                | 0         |      |
| 3                | 0         |      |
</code>```

If I export all the data into a csv, and use a for loop in a programming language, then ofcourse it's very simple, but definitely not feasible. But I can't think of anything, and can't find anything with an sql query based approach.

答:
You don't say which database engine you are using, so I'll assume it's a modern one that implements window functions.

Use SUM() as a window function, as in:

```<code>select *,
  sum(flagvalue) over(order by time) as desired_partition
from t
</code>```

Body:
I'm using Amazon Redshift. I have a flag column containing either 0 or 1 based on a certain condition and everything sorted by ascending time, and I want a number (DesiredPartition) to increment whenever there's a 1 Flag. This is not possible with partitioning ofcourse.

| DesiredPartition | FlagValue | Time |
|------------------|-----------|------|
| 1                | 0         |      |
| 1                | 0         |      |
| 1                | 0         |      |
| 2                | 1         |      |
| 2                | 0         |      |
| 2                | 0         |      |
| 3                | 1         |      |
| 3                | 0         |      |
| 3                | 0         |      |

If I export all the data into a csv, and use a for loop in a programming language, then ofcourse it's very simple, but definitely not feasible. But I can't think of anything, and can't find anything with an sql query based approach.

Body:
You don't say which database engine you are using, so I'll assume it's a modern one that implements window functions.

Use SUM() as a window function, as in:

select *,
  sum(flagvalue) over(order by time) as desired_partition
from t


问:
Large Binary (byte[]) File transfer through WCF
I am trying to build a WCF service that allows me to send large binary files from clients to the service.

However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond)

The Error I get if I try to send the 4.91MB file is:

Exception Message: An error occurred while receiving the HTTP response to http://localhost:56198/Service.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

Inner Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.

Inner Exception Message: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Inner Exception Message: An existing connection was forcibly closed by the remote host

This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method.

I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error.

I am going to paste my  sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well.

Service Web.Config

```<code><system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00"
      openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00"
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
      messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest"
      useDefaultWebProxy="true">
      <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
        maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
    <services>
        <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService">
                <identity>
                    <dns value="localhost"/>
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="DragDrop.Service.ServiceBehavior">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="false"/>
      <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>
</code>```

Client (Asp.net page) Web.Config

```<code><system.serviceModel>
<bindings>
   <basicHttpBinding>
      <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
         openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
         allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
         maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
         messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse"
         useDefaultWebProxy="true">
         <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
            maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
         <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
               realm="">
               <extendedProtectionPolicy policyEnforcement="Never" />
            </transport>
            <message clientCredentialType="UserName" algorithmSuite="Default" />
         </security>
      </binding>
   </basicHttpBinding>
</bindings>

<behaviors>
  <endpointBehaviors>
    <behavior name="debuggingBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="2147483646" />
    </behavior>
  </endpointBehaviors>
</behaviors>

<client>
   <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding"
      bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService"
      name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" />
</client>
</system.serviceModel>
</code>```

答:
(While I agree that streaming transfer would be preferrable, the below should make it work without any other changes)

You also need to increase the maximum message length in the Web.config:

```<code><configuration>
  <system.web>
  <httpRuntime maxMessageLength="409600"
    executionTimeoutInSeconds="300"/>
  </system.web>
</configuration>
</code>```

This will set the maximum message length to 400 MB (parameter is in kB). Check this MSDN page for more information.

Body:
I am trying to build a WCF service that allows me to send large binary files from clients to the service.

However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond)

The Error I get if I try to send the 4.91MB file is:

Exception Message: An error occurred while receiving the HTTP response to http://localhost:56198/Service.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

Inner Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.

Inner Exception Message: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Inner Exception Message: An existing connection was forcibly closed by the remote host

This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method.

I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error.

I am going to paste my  sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well.

Service Web.Config

<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00"
      openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00"
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
      messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest"
      useDefaultWebProxy="true">
      <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
        maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
    <services>
        <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService">
                <identity>
                    <dns value="localhost"/>
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="DragDrop.Service.ServiceBehavior">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="false"/>
      <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>

Client (Asp.net page) Web.Config

<system.serviceModel>
<bindings>
   <basicHttpBinding>
      <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
         openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
         allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
         maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
         messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse"
         useDefaultWebProxy="true">
         <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
            maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
         <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
               realm="">
               <extendedProtectionPolicy policyEnforcement="Never" />
            </transport>
            <message clientCredentialType="UserName" algorithmSuite="Default" />
         </security>
      </binding>
   </basicHttpBinding>
</bindings>

<behaviors>
  <endpointBehaviors>
    <behavior name="debuggingBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="2147483646" />
    </behavior>
  </endpointBehaviors>
</behaviors>

<client>
   <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding"
      bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService"
      name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" />
</client>
</system.serviceModel>

Body:
(While I agree that streaming transfer would be preferrable, the below should make it work without any other changes)

You also need to increase the maximum message length in the Web.config:

<configuration>
  <system.web>
  <httpRuntime maxMessageLength="409600"
    executionTimeoutInSeconds="300"/>
  </system.web>
</configuration>

This will set the maximum message length to 400 MB (parameter is in kB). Check this MSDN page for more information.


问:
How to resolve WARNING:The value 4 (type int) in a string field was converted to u'4' (type string) in Ansible?
I have decoded the extra variables in an Ansible playbook. I am passing the extra variables as encoded format. I am decoding the extra variables and parsing the key and value in my code. The code is:

```<code>meta="{"hostname":"oracleserver","username":"root","password":"admin@123","new_disk":"/dev/sdb","vg_name":"ts","lv_name":"tsdev","mnt_point":"/dev/sdb1","lv_size":"3G"}"
</code>```

I have passed the encoded meta var as base64encode as below:

```<code>ansible-playbook init.yml -e meta=eyJob3N0bmFtZSI6Im9yYWNsZXNlcnZlciIsInVzZXJuYW1lIjoicm9vdCIsInBhc3N3b3JkIjoiYWRtaW5AMTIzIiwibmV3X2Rpc2siOiIvZGV2L3NkYiIsInZnX25hbWUiOiJ0cyIsImx2X25hbWUiOiJ0c2RldiIsIm1udF9wb2ludCI6Ii9kZXYvc2RiMSIsImx2X3NpemUiOiIzRyJ9
</code>```

```<code>- name: creating the custom inventory at run time
  hosts: localhost
  tasks:
    - name: Getting the meta json data
      set_fact:
        decoded_meta_data: "{{ meta | b64decode }}"
    - name: extracting the  hostname from meta data
      set_fact:
        hostname: "{{ decoded_meta_data.hostname }}"
    - debug: msg="{{ decoded_meta_data}} {{ decoded_meta_data.hostname}} {{ decoded_meta_data.lv_size }}"
</code>```

After decoding the value, I am getting the output and warning as:

```<code>PLAY [creating the custom inventory at run time] ****************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************************
ok: [localhost]

TASK [Getting the meta json data] *******************************************************************************************************************
ok: [localhost]

TASK [extracting the  hostname from meta data] ******************************************************************************************************
ok: [localhost]

TASK [debug] ****************************************************************************************************************************************
ok: [localhost] => {
    "msg": "{'username': u'root', 'mnt_point': u'/dev/sdb1', 'new_disk': u'/dev/sdb', 'lv_name': u'tsdev', 'hostname': u'oracleserver', 'vg_name': u'ts', 'lv_size': u'3G', 'password': u'admin@123'} oracleserver 3G"
}
</code>```

[WARNING]: The value 4 (type int) in a string field was converted to u'4' (type string). If this does not look like what you expect, quote the entire value to ensure it does not change.

答:
You can add the following lines in the the defaults section of ~/.ansible.cfg</p>
```<code>/etc/ansible/ansible.cfg
[defaults]
string_conversion_action = ignore
</code>```

Body:
I have decoded the extra variables in an Ansible playbook. I am passing the extra variables as encoded format. I am decoding the extra variables and parsing the key and value in my code. The code is:

meta="{"hostname":"oracleserver","username":"root","password":"admin@123","new_disk":"/dev/sdb","vg_name":"ts","lv_name":"tsdev","mnt_point":"/dev/sdb1","lv_size":"3G"}"

I have passed the encoded meta var as base64encode as below:

ansible-playbook init.yml -e meta=eyJob3N0bmFtZSI6Im9yYWNsZXNlcnZlciIsInVzZXJuYW1lIjoicm9vdCIsInBhc3N3b3JkIjoiYWRtaW5AMTIzIiwibmV3X2Rpc2siOiIvZGV2L3NkYiIsInZnX25hbWUiOiJ0cyIsImx2X25hbWUiOiJ0c2RldiIsIm1udF9wb2ludCI6Ii9kZXYvc2RiMSIsImx2X3NpemUiOiIzRyJ9

- name: creating the custom inventory at run time
  hosts: localhost
  tasks:
    - name: Getting the meta json data
      set_fact:
        decoded_meta_data: "{{ meta | b64decode }}"
    - name: extracting the  hostname from meta data
      set_fact:
        hostname: "{{ decoded_meta_data.hostname }}"
    - debug: msg="{{ decoded_meta_data}} {{ decoded_meta_data.hostname}} {{ decoded_meta_data.lv_size }}"

After decoding the value, I am getting the output and warning as:

PLAY [creating the custom inventory at run time] ****************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************************
ok: [localhost]

TASK [Getting the meta json data] *******************************************************************************************************************
ok: [localhost]

TASK [extracting the  hostname from meta data] ******************************************************************************************************
ok: [localhost]

TASK [debug] ****************************************************************************************************************************************
ok: [localhost] => {
    "msg": "{'username': u'root', 'mnt_point': u'/dev/sdb1', 'new_disk': u'/dev/sdb', 'lv_name': u'tsdev', 'hostname': u'oracleserver', 'vg_name': u'ts', 'lv_size': u'3G', 'password': u'admin@123'} oracleserver 3G"
}

[WARNING]: The value 4 (type int) in a string field was converted to u'4' (type string). If this does not look like what you expect, quote the entire value to ensure it does not change.

Body:
You can add the following lines in the the defaults section of ~/.ansible.cfg

/etc/ansible/ansible.cfg
[defaults]
string_conversion_action = ignore


问:
ngx-color-picker dialog box closes after clicking outside
I have used ngx-color-picker in our project. but the issue I am getting is, whenever I click outside of a dialog, it closes. I don't want to close the dialog if it is clicked outside of the dialog. Is there any inbuilt event in ngx-color-picker which takes care of this situation?

I used this package:
    https://www.npmjs.com/package/ngx-color-picker

Any help will be much appreciated.

答:
Doesn't cpCloseClickOutside do the job?

```<code>[cpCloseClickOutside]        // Close the color picker dialog when user clicks outside (true).
</code>```

Body:
Doesn't cpCloseClickOutside do the job?

[cpCloseClickOutside]        // Close the color picker dialog when user clicks outside (true).


问:
Jenkins Pipeline - Run job on parallel on multiple remote hosts
I have a Jenkins job with string parameter  Name = "HOST". I am trying to run one script remotely by connecting to the HOST. It works fine. Similarly, if I enter multiple host names in the HOST parameter, the job has to run on those multiple machines on parallel. How to achieve this?

If anybody has any code for this, please do share. Appreciate this help!

答:
An easy way to run a job on different machines in parallel is to use the declarative Matrix.

Pipeline example:

```<code> pipeline {
        agent none
        stages {
            stage('Matrix stage') {
                matrix {
                    agent {
                        label "${NODE}"
                    }
                    axes {
                        axis {
                            name 'NODE'
                            values 'node1', 'node2', 'node3'
                        }
                    }
                    stages {
                        stage('Parallel stage') {
                            steps {
                                echo "Run on ${NODE}"
                            }
                        }
                    }
                }
            }
        }
    }
</code>```

This pipleline will execute the defined stages on ['node1', 'node2', 'node3'] in parallel.

Note that declarative Matrix is a native declarative Pipelines feature, so no additional Plugin installation needed.

Body:
An easy way to run a job on different machines in parallel is to use the declarative Matrix.

Pipeline example:

 pipeline {
        agent none
        stages {
            stage('Matrix stage') {
                matrix {
                    agent {
                        label "${NODE}"
                    }
                    axes {
                        axis {
                            name 'NODE'
                            values 'node1', 'node2', 'node3'
                        }
                    }
                    stages {
                        stage('Parallel stage') {
                            steps {
                                echo "Run on ${NODE}"
                            }
                        }
                    }
                }
            }
        }
    }

This pipleline will execute the defined stages on ['node1', 'node2', 'node3'] in parallel.

Note that declarative Matrix is a native declarative Pipelines feature, so no additional Plugin installation needed.


答:
If you write the component with class component, you can use next approach. Here is the component

```<code>const EditPost = ({ match }) => {
  let { id } = match.params
  // ...
}
</code>```

or the same with hook:

```<code>const EditPost = () => {
  let { id } = useParams();
  // ...
}
</code>```

And then in router you can use it like this:

```<code><Router>
  <div>
    <Switch>
      <Route path="/blog/:slug" component={BlogPost} />
    </Switch>
  </div>
</Router>
</code>```

Title: How can I access router params in JSX?

Body:
Am trying to edit post by it's id and I would like pass the id a a prop to the EditPost component how do I go about it?

  render() {
    return (
      <Router>
      <Switch >
        <Route path="/edit/:id">
          <EditPost index={/*what do I do here?*/} />
        </Route>
      </Switch>
      </Router>
    );
  }

Body:
If you write the component with class component, you can use next approach. Here is the component

const EditPost = ({ match }) => {
  let { id } = match.params
  // ...
}

or the same with hook:

const EditPost = () => {
  let { id } = useParams();
  // ...
}

And then in router you can use it like this:

<Router>
  <div>
    <Switch>
      <Route path="/blog/:slug" component={BlogPost} />
    </Switch>
  </div>
</Router>


问:
Dropdown menu behind text
I tried to create a drop down menu. That's what I did so far:
http://gegensinn.org/test.html
(I made the drop down menu visible at all time for "debugging")

I think the problem is quite obvious: The menu is behind the text.

First I thought I could fix this with z-index.

Although I'm not quite sure which element has to get the z-index property.

I tried to set the whole menu to z-index:100; and at the same time set the z-index:1; of  .main.

Afterwards I tried to set only the z-index of
 and   but nothing worked.

答: add position relative to li and position absolute to sub ul and then z-index

Title: Dropdown menu behind text


问:
github markdown no longer displays images
A month or 2 ago I wrote a markdown file for my github page and it contained png files.
Today I was looking ad the markdown file on github and all images were removed. If I click on one I get the message: The image "link to image" cannot be displayed because it contains errors.

This is the link as the git hub page gives me
https://raw.githubusercontent.com/bask185/State-Machine-Scripts/master/images/handleWheel.png

And this is how I try to display the file in the markdown file.
 exclamation mark [handleWheel ] (https://raw.githubusercontent.com/bask185/State-Machine-Scripts/master/images/handleWheel.png)

It worked once so I did something right once. Did github changed or did I do something wrong?
Can I salvage my images?

答:
It looks like the images were linked to a relative path in your repository. You earlier had an images/ directory with the images that were shown in the markdown file, but this was removed in this commit.

If you browse the repository at the previous commit, you can see the images. The image corresponding to the link in your question, for example, is here.

This thread discusses various ways to add images to Markdown files in GitHub.


问:
How to convert classic cronjobs to cron expressions for quartz-scheduler
I am used to cronjobs like this:

0 1 * * *

In the java library quartz-scheduler they use cron expressions.

0 0 1 1/1 * ? *

Is there a way directly from quartz-scheduler or a other possability to convert or use the old cronjobs in quartz-scheduler?

Edit: I found something for JS: https://www.npmjs.com/package/cron-to-quartz is there a way in Java?

答:
Found some library in Java that might help you: https://github.com/jmrozanec/cron-utils. Although, I haven't used it personally.

The JS code from the library that you've found doesn't seem very complex, so the alternative would be to replicate that one in Java.

BTW, what's your need for such a conversion, can you give us more context? Is it something automatic that needs to be performed, or is it a one-time conversion only?


问:
Greatest of 3 numbers code not working for specific numbers
I'm a beginner to Python. I have written code to find the greatest of 3 numbers which is working fine other than these numbers 100,10,20 which are provided as input. I'm getting the output as "The largest number is 20" but my expectation is is should be "The largest number is 100"
My code is as follows:

```<code>a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")

if (a > b) and (a > c):
    lnum = a

elif (b > a) and (b > c):
    lnum = b

else:
    lnum = c

print("The largest number is", lnum)
</code>```

Can anyone help me to understand why the output is showing 20 as greatest instead of 100?

答:
Your variables are strings, you must convert them to ints like this:</p>

```<code>a = int(input('Enter 1st value'))
</code>```

Body:
I'm a beginner to Python. I have written code to find the greatest of 3 numbers which is working fine other than these numbers 100,10,20 which are provided as input. I'm getting the output as "The largest number is 20" but my expectation is is should be "The largest number is 100"
My code is as follows:

a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")

if (a > b) and (a > c):
    lnum = a

elif (b > a) and (b > c):
    lnum = b

else:
    lnum = c

print("The largest number is", lnum)

Can anyone help me to understand why the output is showing 20 as greatest instead of 100?

Body:
Your variables are strings, you must convert them to ints like this:

a = int(input('Enter 1st value'))


问:
How do I connect a Laravel app to a Lumen api service together?
We are working on a project that allows users to register and login from a laravel app to an api service built with lumen, but the issue we are having is how do we authenticate the laravel app the same time, after a successful authentication from lumen.

答:
The landing page, (even if it's on the main domain) should submit to the dashboard domain and authenticate user using JWT (Json Web Token) or laravel passport (which uses it too)

Let the dashboard send the login request. The api should provide a token of authentification which the dashboard keeps in session for use in further requests.

The dashboard should only communicate with the API and not directly with the database. It will help with your project's future modification.