问:
How to read XML to a list of POJOs in Java?
I'm new to XML and im trying to read in an XML page and store its contents in an arraylist.

So far i seem to have been able to get the arraylist filled with the first content, as when i tried an isEmpty, it returned false. so there is definitely containing something.
However, when i try to call the overided tostring method, or even try to call any individual category for that matter, it just returns empty?

can anyone help?

heres the code im working with:

```<code>package test;

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class xmlmx {

   public static void main(String[] args) {
      ArrayList<Anime> list = new ArrayList<Anime>();
      try {
         File inputFile = new File("c:\\code\\ad\\XMLDB.xml");
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(inputFile);
         doc.getDocumentElement().normalize();
         System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
         NodeList nList = doc.getElementsByTagName("Anime");
         System.out.println("----------------------------");

         for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
               Element eElement = (Element) nNode;
               list.add(new Anime(eElement.getAttribute("ID"),
                                  eElement.getAttribute("name"),
                                  eElement.getAttribute("altname"),
                                  eElement.getAttribute("seasons"),
                                  eElement.getAttribute("episodes"),
                                  eElement.getAttribute("status"),
                                  eElement.getAttribute("DS"),
                                  eElement.getAttribute("have"),
                                  eElement.getAttribute("left"),
                                  eElement.getAttribute("plot"),
                                  eElement.getAttribute("connect"),
                                  eElement.getAttribute("image")));
               System.out.println(list.get(0).toString());
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
</code>```

the arraylist is of type anime, a class here:

```<code>    package test;

class Anime{
    private String ID;
    private String name;
    private String altname;
    private String seasons;
    private String episodes;
    private String status;
    private String DS;
    private String have;
    private String left;
    private String plot;
    private String connect;
    private String image;

    public Anime(String ID,
                 String name,
                 String altname,
                 String seasons,
                 String episodes,
                 String status,
                 String DS,
                 String have,
                 String left,
                 String plot,
                 String connect,
                 String image) {
        this.ID = ID;
        this.name = name;
        this.altname = altname;
        this.seasons = seasons;
        this.episodes = episodes;
        this.status = status;
        this.DS = DS;
        this.have = have;
        this.left = left;
        this.plot = plot;
        this.connect = connect;
        this.image = image;
    }

/*
 getters and setters here...
*/
    @Override
    public String toString() {
        return "Anime [ID=" + ID +
               ", name=" + name +
               ", altname=" + altname +
               ", seasons=" + seasons +
               ", episodes=" + episodes +
               ", status=" + status +
               ", DS=" + DS +
               ", have=" + have +
               ", left=" + left +
               ", plot=" + plot +
               ", connect=" + connect +
               ", image=" + image + "]";
    }
}
</code>```

finally, heres the xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Anime>
    <record ID="BL1">
        <name>Bleach</name>
        <altname>Burichi</altname>
        <seasons>16</seasons>
        <episodes>366</episodes>
        <status>Finished</status>
        <sound>Dubbed</sound>
        <have>All</have>
        <left>-/-</left>
        <plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
        <connect>Bleach movies</connect>
        <image>images/bleach.jpg</image>
    </record>
</Anime>
</code>```

any help would be greatly appreciated, thank you

答:
Use an ObjectMapper like Jackson FasterXML!

```<code>new XmlMapper().readValue(yourDataAsInputStream, Anime.class);
</code>```

or for a list

```<code>new XmlMapper().readValue(yourDataAsInputStream, new TypeReference<List<Anime>>(){});
</code>```

Full Example:

```<code>package stack47711679;

import java.util.List;
import org.junit.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class HowToReadXmlToAPojoIn2017 {

    @Test
    public void readXmlToPojo() throws Exception {
        ObjectMapper mapper = new XmlMapper();
        Anime pojo = mapper.readValue(Thread.currentThread().getContextClassLoader().getResourceAsStream("47711679.xml"), Anime.class);
        System.out.println(pojo+"");
    }
    @Test
    public void readXmlToListOfPojo() throws Exception {
        ObjectMapper mapper = new XmlMapper();
        List<Anime> pojos = mapper.readValue(Thread.currentThread().getContextClassLoader().getResourceAsStream("47711679_v2.xml"), new TypeReference<List<Anime>>(){});
        System.out.println(pojos+"");
    }
}
</code>```

Your POJO Anime.java

```<code>package stack47711679;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

public class Anime{
    @JacksonXmlProperty(isAttribute = true)
    public String  id;
    public String name;
    public String altname;
    public String seasons;
    public String episodes;
    public String status;
    public String DS;
    public String have;
    public String left;
    public String plot;
    public String connect;
    public String image;
    public String sound;
    public Anime(){
    }

    @Override
    public String toString() {
        return "Anime [ID=" + id +
           ", name=" + name +
           ", altname=" + altname +
           ", seasons=" + seasons +
           ", episodes=" + episodes +
           ", status=" + status +
           ", DS=" + DS +
           ", have=" + have +
           ", left=" + left +
           ", plot=" + plot +
           ", connect=" + connect +
           ", sound=" + sound +
           ", image=" + image + "]";
    }
}
</code>```

With Testdata:

47711679.xml

```<code><?xml version="1.0" encoding="UTF-8"?>

<Anime id="1">
    <name>Bleach</name>
    <altname>Burichi</altname>
    <seasons>16</seasons>
    <episodes>366</episodes>
    <status>Finished</status>
    <sound>Dubbed</sound>
    <have>All</have>
    <left>-/-</left>
    <plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
    <connect>Bleach movies</connect>
    <image>images/bleach.jpg</image>
</Anime>
</code>```

47711679_v2.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Animes>
<Anime id="1">
    <name>Bleach</name>
    <altname>Burichi</altname>
    <seasons>16</seasons>
    <episodes>366</episodes>
    <status>Finished</status>
    <sound>Dubbed</sound>
    <have>All</have>
    <left>-/-</left>
    <plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
    <connect>Bleach movies</connect>
    <image>images/bleach.jpg</image>
</Anime>
<Anime id="2">
    <name>Something</name>
    <altname>else</altname>
    <seasons>21</seasons>
    <episodes>34</episodes>
    <status>to be continued</status>
    <sound>Dubbed</sound>
    <have>All</have>
    <left>-/-</left>
    <plot>Yes it has one</plot>
    <connect>Bleach movies</connect>
    <image>images/bleach.jpg</image>
</Anime>
</Animes>
</code>```

Prints:
For the list in 47711679_v2.xml:

```<code>[Anime [ID=1, name=Bleach, altname=Burichi, seasons=16, episodes=366, status=Finished, DS=null, have=All, left=-/-, plot=Ichigo gets grim reaper powers, fights reapers, hollows and everything in between, connect=Bleach movies, sound=Dubbed, image=images/bleach.jpg], Anime [ID=2, name=Something, altname=else, seasons=21, episodes=34, status=to be continued, DS=null, have=All, left=-/-, plot=Yes it has one, connect=Bleach movies, sound=Dubbed, image=images/bleach.jpg]]
</code>```

And for the single entry 47711679.xml:

```<code>Anime [ID=1, name=Bleach, altname=Burichi, seasons=16, episodes=366, status=Finished, DS=null, have=All, left=-/-, plot=Ichigo gets grim reaper powers, fights reapers, hollows and everything in between, connect=Bleach movies, sound=Dubbed, image=images/bleach.jpg]
</code>```

I used jackson 2.8.6.

```<code><dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.8.6</version>
    </dependency>
</code>```

Body:
I'm new to XML and im trying to read in an XML page and store its contents in an arraylist.

So far i seem to have been able to get the arraylist filled with the first content, as when i tried an isEmpty, it returned false. so there is definitely containing something.
However, when i try to call the overided tostring method, or even try to call any individual category for that matter, it just returns empty?

can anyone help?

heres the code im working with:

package test;

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class xmlmx {

   public static void main(String[] args) {
      ArrayList<Anime> list = new ArrayList<Anime>();
      try {
         File inputFile = new File("c:\\code\\ad\\XMLDB.xml");
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(inputFile);
         doc.getDocumentElement().normalize();
         System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
         NodeList nList = doc.getElementsByTagName("Anime");
         System.out.println("----------------------------");

         for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
               Element eElement = (Element) nNode;
               list.add(new Anime(eElement.getAttribute("ID"),
                                  eElement.getAttribute("name"),
                                  eElement.getAttribute("altname"),
                                  eElement.getAttribute("seasons"),
                                  eElement.getAttribute("episodes"),
                                  eElement.getAttribute("status"),
                                  eElement.getAttribute("DS"),
                                  eElement.getAttribute("have"),
                                  eElement.getAttribute("left"),
                                  eElement.getAttribute("plot"),
                                  eElement.getAttribute("connect"),
                                  eElement.getAttribute("image")));
               System.out.println(list.get(0).toString());
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

the arraylist is of type anime, a class here:

    package test;

class Anime{
    private String ID;
    private String name;
    private String altname;
    private String seasons;
    private String episodes;
    private String status;
    private String DS;
    private String have;
    private String left;
    private String plot;
    private String connect;
    private String image;

    public Anime(String ID,
                 String name,
                 String altname,
                 String seasons,
                 String episodes,
                 String status,
                 String DS,
                 String have,
                 String left,
                 String plot,
                 String connect,
                 String image) {
        this.ID = ID;
        this.name = name;
        this.altname = altname;
        this.seasons = seasons;
        this.episodes = episodes;
        this.status = status;
        this.DS = DS;
        this.have = have;
        this.left = left;
        this.plot = plot;
        this.connect = connect;
        this.image = image;
    }

/*
 getters and setters here...
*/
    @Override
    public String toString() {
        return "Anime [ID=" + ID +
               ", name=" + name +
               ", altname=" + altname +
               ", seasons=" + seasons +
               ", episodes=" + episodes +
               ", status=" + status +
               ", DS=" + DS +
               ", have=" + have +
               ", left=" + left +
               ", plot=" + plot +
               ", connect=" + connect +
               ", image=" + image + "]";
    }
}

finally, heres the xml:

<?xml version="1.0" encoding="UTF-8"?>
<Anime>
    <record ID="BL1">
        <name>Bleach</name>
        <altname>Burichi</altname>
        <seasons>16</seasons>
        <episodes>366</episodes>
        <status>Finished</status>
        <sound>Dubbed</sound>
        <have>All</have>
        <left>-/-</left>
        <plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
        <connect>Bleach movies</connect>
        <image>images/bleach.jpg</image>
    </record>
</Anime>

any help would be greatly appreciated, thank you

Body:
Use an ObjectMapper like Jackson FasterXML!

new XmlMapper().readValue(yourDataAsInputStream, Anime.class);

or for a list

new XmlMapper().readValue(yourDataAsInputStream, new TypeReference<List<Anime>>(){});

Full Example:

package stack47711679;

import java.util.List;
import org.junit.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class HowToReadXmlToAPojoIn2017 {

    @Test
    public void readXmlToPojo() throws Exception {
        ObjectMapper mapper = new XmlMapper();
        Anime pojo = mapper.readValue(Thread.currentThread().getContextClassLoader().getResourceAsStream("47711679.xml"), Anime.class);
        System.out.println(pojo+"");
    }
    @Test
    public void readXmlToListOfPojo() throws Exception {
        ObjectMapper mapper = new XmlMapper();
        List<Anime> pojos = mapper.readValue(Thread.currentThread().getContextClassLoader().getResourceAsStream("47711679_v2.xml"), new TypeReference<List<Anime>>(){});
        System.out.println(pojos+"");
    }
}

Your POJO Anime.java

package stack47711679;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

public class Anime{
    @JacksonXmlProperty(isAttribute = true)
    public String  id;
    public String name;
    public String altname;
    public String seasons;
    public String episodes;
    public String status;
    public String DS;
    public String have;
    public String left;
    public String plot;
    public String connect;
    public String image;
    public String sound;
    public Anime(){
    }

    @Override
    public String toString() {
        return "Anime [ID=" + id +
           ", name=" + name +
           ", altname=" + altname +
           ", seasons=" + seasons +
           ", episodes=" + episodes +
           ", status=" + status +
           ", DS=" + DS +
           ", have=" + have +
           ", left=" + left +
           ", plot=" + plot +
           ", connect=" + connect +
           ", sound=" + sound +
           ", image=" + image + "]";
    }
}

With Testdata:

47711679.xml

<?xml version="1.0" encoding="UTF-8"?>

<Anime id="1">
    <name>Bleach</name>
    <altname>Burichi</altname>
    <seasons>16</seasons>
    <episodes>366</episodes>
    <status>Finished</status>
    <sound>Dubbed</sound>
    <have>All</have>
    <left>-/-</left>
    <plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
    <connect>Bleach movies</connect>
    <image>images/bleach.jpg</image>
</Anime>

47711679_v2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Animes>
<Anime id="1">
    <name>Bleach</name>
    <altname>Burichi</altname>
    <seasons>16</seasons>
    <episodes>366</episodes>
    <status>Finished</status>
    <sound>Dubbed</sound>
    <have>All</have>
    <left>-/-</left>
    <plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
    <connect>Bleach movies</connect>
    <image>images/bleach.jpg</image>
</Anime>
<Anime id="2">
    <name>Something</name>
    <altname>else</altname>
    <seasons>21</seasons>
    <episodes>34</episodes>
    <status>to be continued</status>
    <sound>Dubbed</sound>
    <have>All</have>
    <left>-/-</left>
    <plot>Yes it has one</plot>
    <connect>Bleach movies</connect>
    <image>images/bleach.jpg</image>
</Anime>
</Animes>

Prints:
For the list in 47711679_v2.xml:

[Anime [ID=1, name=Bleach, altname=Burichi, seasons=16, episodes=366, status=Finished, DS=null, have=All, left=-/-, plot=Ichigo gets grim reaper powers, fights reapers, hollows and everything in between, connect=Bleach movies, sound=Dubbed, image=images/bleach.jpg], Anime [ID=2, name=Something, altname=else, seasons=21, episodes=34, status=to be continued, DS=null, have=All, left=-/-, plot=Yes it has one, connect=Bleach movies, sound=Dubbed, image=images/bleach.jpg]]

And for the single entry 47711679.xml:

Anime [ID=1, name=Bleach, altname=Burichi, seasons=16, episodes=366, status=Finished, DS=null, have=All, left=-/-, plot=Ichigo gets grim reaper powers, fights reapers, hollows and everything in between, connect=Bleach movies, sound=Dubbed, image=images/bleach.jpg]

I used jackson 2.8.6.

<dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.8.6</version>
    </dependency>


来源: stackexchange

问:
Apache HttpClient process HttpResponse
I'm trying to use Google's URL shortener API.

The response I get should look like:

```<code>200

cache-control:  no-cache, no-store, max-age=0, must-revalidate
content-encoding:  gzip
content-length:  106
content-type:  application/json; charset=UTF-8
date:  Thu, 07 Dec 2017 23:39:07 GMT
etag:  "qQqhpr1RL6vGc3-0yacNoUjh_Uc/W5VD-15ZqaQDW9L-OELlMzo1ih4"
expires:  Mon, 01 Jan 1990 00:00:00 GMT
pragma:  no-cache
server:  GSE
vary:  Origin, X-Origin

{
 "kind": "urlshortener#url",
 "id": "[SHORTENED URL HERE]",
 "longUrl": "http://www.facebook.com/"
}
</code>```

I want to be able to process the Json returned so that I can access the 'id' field and get the shortened URL.

However the response that I am getting looks like this:

```<code>Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: Mon, 01 Jan 1990 00:00:00 GMT
Date: Fri, 08 Dec 2017 10:10:37 GMT
ETag: "qQqhpr1RL6vGc3-0yacNoUjh_Uc/W5VD-15ZqaQDW9L-OELlMzo1ih4"
Vary: Origin
Vary: X-Origin
Content-Type: application/json; charset=UTF-8
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alt-Svc: hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=":443"; ma=2592000; v="41,39,38,37,35"
Transfer-Encoding: chunked
</code>```

I would appreciate it if someone could help me to figure out how to get access to the 'id' Json field so that I can get the shortened URL.

My code for this is:

```<code>HttpPost httppost = new HttpPost("https://www.googleapis.com/urlshortener/v1/url?key=[MY_API_KEY]);
String jsondata = "{\"longUrl\": \"http://www.facebook.com/\"}";

StringEntity jsonparam = new StringEntity(jsondata);
jsonparam.setContentType("application/json;charset=utf-8");
jsonparam.setChunked(false);

httppost.addHeader("content-type", "application/json;charset=UTF-8");
httppost.setEntity(jsonparam);

HttpClient httpclient = HttpClientBuilder.create().build();
HttpResponse httpresponse = httpclient.execute(httppost);

Header[] headers = httpresponse.getAllHeaders();
for (Header header : headers) {
    System.out.println(header);
}
</code>```

答:
To read the body content you should do the following

```<code>try(InputStream content = httpresponse.getEntity().getContent())
        {
            //With apache
            String jsonResponse = IOUtils.toString(content, "UTF-8");
            System.out.println(jsonResponse);
        } catch (UnsupportedOperationException | IOException e)
        {
            //Do something here, e.g. LOG
        }
</code>```

If you are using apache IOUtil you will need the following dependency
https://mvnrepository.com/artifact/commons-io/commons-io

It is good practice to validate the returned status code to ensure that content is included e.g. 200.

Other methods of transforming the InputStream to a String can be found here.

Once loaded to a String you can use libraries such as GSON or using help from here. By converting to a Java object you can more easily retrieve the id field.

ContentLicense: CC BY-SA 3.0

Title: Apache HttpClient process HttpResponse

Body:
I'm trying to use Google's URL shortener API.

The response I get should look like:

200

cache-control:  no-cache, no-store, max-age=0, must-revalidate
content-encoding:  gzip
content-length:  106
content-type:  application/json; charset=UTF-8
date:  Thu, 07 Dec 2017 23:39:07 GMT
etag:  "qQqhpr1RL6vGc3-0yacNoUjh_Uc/W5VD-15ZqaQDW9L-OELlMzo1ih4"
expires:  Mon, 01 Jan 1990 00:00:00 GMT
pragma:  no-cache
server:  GSE
vary:  Origin, X-Origin

{
 "kind": "urlshortener#url",
 "id": "[SHORTENED URL HERE]",
 "longUrl": "http://www.facebook.com/"
}

I want to be able to process the Json returned so that I can access the 'id' field and get the shortened URL.

However the response that I am getting looks like this:

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: Mon, 01 Jan 1990 00:00:00 GMT
Date: Fri, 08 Dec 2017 10:10:37 GMT
ETag: "qQqhpr1RL6vGc3-0yacNoUjh_Uc/W5VD-15ZqaQDW9L-OELlMzo1ih4"
Vary: Origin
Vary: X-Origin
Content-Type: application/json; charset=UTF-8
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alt-Svc: hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=":443"; ma=2592000; v="41,39,38,37,35"
Transfer-Encoding: chunked

I would appreciate it if someone could help me to figure out how to get access to the 'id' Json field so that I can get the shortened URL.

My code for this is:

HttpPost httppost = new HttpPost("https://www.googleapis.com/urlshortener/v1/url?key=[MY_API_KEY]);
String jsondata = "{\"longUrl\": \"http://www.facebook.com/\"}";

StringEntity jsonparam = new StringEntity(jsondata);
jsonparam.setContentType("application/json;charset=utf-8");
jsonparam.setChunked(false);

httppost.addHeader("content-type", "application/json;charset=UTF-8");
httppost.setEntity(jsonparam);

HttpClient httpclient = HttpClientBuilder.create().build();
HttpResponse httpresponse = httpclient.execute(httppost);

Header[] headers = httpresponse.getAllHeaders();
for (Header header : headers) {
    System.out.println(header);
}

Body:
To read the body content you should do the following

try(InputStream content = httpresponse.getEntity().getContent())
        {
            //With apache
            String jsonResponse = IOUtils.toString(content, "UTF-8");
            System.out.println(jsonResponse);
        } catch (UnsupportedOperationException | IOException e)
        {
            //Do something here, e.g. LOG
        }

If you are using apache IOUtil you will need the following dependency
https://mvnrepository.com/artifact/commons-io/commons-io

It is good practice to validate the returned status code to ensure that content is included e.g. 200.

Other methods of transforming the InputStream to a String can be found here.

Once loaded to a String you can use libraries such as GSON or using help from here. By converting to a Java object you can more easily retrieve the id field.


问:
Regular expressions in Notepad++. How make pattern that could be use in a few lines
I have to Find and Replace some lines for one click in Notepad++!

How can I to do that?

Text:

```<code>//A lot of code
 int i = n << 3;
 cout << "message1";
 cout << "message1" << var1 <<"message2"<< var2 << /* undefened length */ << var50;
 cout << "messageA1" << endl;
 cout << "messageA1" << varA1 <<"messageA2"<< varA2 <<  /* undefened length */ << endl << varA67 << endl;
//A lot of code
</code>```

Find: "SomeAwesomePattern";

Replace: "SomeAwesomeReplacerFor"

Result:

```<code>//A lot of code
int i = n << 3;
Console.Write("message1");
Console.Write("message1" + var1 + "message2" + var2 + /* undefened length */ + var50);
Console.Write("messageA1" + "\n");
Console.Write("messageA1" + varA1 + "messageA2" + varA2 + /* undefened length */+"\n" + varA67 +"\n");
//A lot of code
</code>```

Operations:

replace  cout <<  by  Console.Write(

   replace << endl by "\n"

  rpelace << by +
 rpelace ; by );

  It must ignor
   all text that didn't start with cout

答:
To answer as a general exercise, run

replace all cout.*<<.*\K<< with  +, many times until it can't match.

replace all cout.*<<.*\Kendl with "\\n", many times

replace all cout.*<<.*\K(?<!\))(?=;) with \)

replace all cout.*<<with Console.Write\(

from perlre

\K (Keep the stuff left of the \K)

(?<!..) A zero-width negative lookbehind assertion.

(?=..) A zero-width positive lookahead assertion.

Body:
I have to Find and Replace some lines for one click in Notepad++!

How can I to do that?

Text:

//A lot of code
 int i = n << 3;
 cout << "message1";
 cout << "message1" << var1 <<"message2"<< var2 << /* undefened length */ << var50;
 cout << "messageA1" << endl;
 cout << "messageA1" << varA1 <<"messageA2"<< varA2 <<  /* undefened length */ << endl << varA67 << endl;
//A lot of code

Find: "SomeAwesomePattern";

Replace: "SomeAwesomeReplacerFor"

Result:

//A lot of code
int i = n << 3;
Console.Write("message1");
Console.Write("message1" + var1 + "message2" + var2 + /* undefened length */ + var50);
Console.Write("messageA1" + "\n");
Console.Write("messageA1" + varA1 + "messageA2" + varA2 + /* undefened length */+"\n" + varA67 +"\n");
//A lot of code

Operations:

replace  cout <<  by  Console.Write(

   replace << endl by "\n"

  rpelace << by +
 rpelace ; by );

  It must ignor
   all text that didn't start with cout


问:
Zabbix Upgrade - Database upgrade failed
EDIT : I should have created this post on ServerFault, wrong tab, sorry.

I'm trying to upgrade my Zabbix Server today (MySQL DB).
Current version is 2.4.8, I want to update it to 3.4.4

Installation went well. When I start the zabbix-server process, the database starts upgrading, and it then stops with the following error message :

```<code>[Z3005] query failed: [1034] Incorrect key file for table 'alerts'; try to repair it [alter table alerts add p_eventid bigint unsigned]
</code>```

So, I stopped zabbix-server, did the "alter table alerts add p_eventid bigint unsigned", restarted zabbix-server, and now got this error message :

```<code>[Z3005] query failed: [1060] Duplicate column name 'p_eventid' [alter table alerts add p_eventid bigint unsigned]
</code>```

Which is a bit troubling for me, as the error message is different, but the proposed solution is still the same, and has been done already.

I did some research, found out this ZBX bug report that can be useful but I have no idea how to apply the workaround, as I'm no expert in SQL. As far as I can tell, I have a missing index in the alerts table (alerts_7). I tried to create it with the following command, after googling a bit :

```<code>create INDEX on alerts (p_eventid) USING BTREE;
</code>```

Still got an error (the second one).

Anyone had that situation already, and found out how to solve it ?

答: Finally had some time to work on this, the problem was that the tmp directory was too small for the upgrade operation. After changing the tmp path in the my.cnf, and restarting the upgrade, everything worked as expected !</p>

Body:
EDIT : I should have created this post on ServerFault, wrong tab, sorry.

I'm trying to upgrade my Zabbix Server today (MySQL DB).
Current version is 2.4.8, I want to update it to 3.4.4

Installation went well. When I start the zabbix-server process, the database starts upgrading, and it then stops with the following error message :

[Z3005] query failed: [1034] Incorrect key file for table 'alerts'; try to repair it [alter table alerts add p_eventid bigint unsigned]

So, I stopped zabbix-server, did the "alter table alerts add p_eventid bigint unsigned", restarted zabbix-server, and now got this error message :

[Z3005] query failed: [1060] Duplicate column name 'p_eventid' [alter table alerts add p_eventid bigint unsigned]

Which is a bit troubling for me, as the error message is different, but the proposed solution is still the same, and has been done already.

I did some research, found out this ZBX bug report that can be useful but I have no idea how to apply the workaround, as I'm no expert in SQL. As far as I can tell, I have a missing index in the alerts table (alerts_7). I tried to create it with the following command, after googling a bit :

create INDEX on alerts (p_eventid) USING BTREE;

Still got an error (the second one).

Anyone had that situation already, and found out how to solve it ?


问:
Autocomplete from 10 000 items in .NET
I've got an in memory collection of around 10K objects. I want to give users the ability to type part of the item name or description and display an autocomplete list. What is an efficient way to do it? I really need the fastest possible response time, users are very fast.

Thanks a lot,
Mary

答:
This is not a .net specific answer, but the usual approach to this problem is to create an index and pre-compute your auto-complete lists which are stored in a hierarchical map-of-maps-of-maps-of...-of-maps-of-lists structure (see below). It's basically an implementation of a trie.

Basically, you have a hash map (REAL hash map, with O(1) implementation), with keys being possible substrings. For each key string "XYZ", it points to a map containing data for all objects containing "XYZ"; with keys "XYZA", "XYZB", ...etc... Then once you reach N characters (N maps deep), your last map value is a LIST of all actual objects from your collection which contain that N-character string.

Then you go over your collection, and for each object compute all possible substrings of length M through N (I assume you only want to autocomplete if >=M characters is typed; and too-long substrings are useless) and populate the maps.

The data structure is as follows:

```<code>TopMap => {
          'A' => Map_for_A
          'B' => Map_for_B
              ...
          }

Map_For_A => {
          'AA' => Map_for_AA
          'AB' => Map_for_AB
              ...
          }
Map_For_AB => {
          'ABC' => Map_for_ABC
          'ABD' => Map_for_ABD
              ...
          }
Map_For_ABD => {
          'ABDE' => List_For_ABDE
          'ABDX' => List_For_ABDX
          }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Autocomplete from 10 000 items in .NET

Body:
This is not a .net specific answer, but the usual approach to this problem is to create an index and pre-compute your auto-complete lists which are stored in a hierarchical map-of-maps-of-maps-of...-of-maps-of-lists structure (see below). It's basically an implementation of a trie.

Basically, you have a hash map (REAL hash map, with O(1) implementation), with keys being possible substrings. For each key string "XYZ", it points to a map containing data for all objects containing "XYZ"; with keys "XYZA", "XYZB", ...etc... Then once you reach N characters (N maps deep), your last map value is a LIST of all actual objects from your collection which contain that N-character string.

Then you go over your collection, and for each object compute all possible substrings of length M through N (I assume you only want to autocomplete if >=M characters is typed; and too-long substrings are useless) and populate the maps.

The data structure is as follows:

TopMap => {
          'A' => Map_for_A
          'B' => Map_for_B
              ...
          }

Map_For_A => {
          'AA' => Map_for_AA
          'AB' => Map_for_AB
              ...
          }
Map_For_AB => {
          'ABC' => Map_for_ABC
          'ABD' => Map_for_ABD
              ...
          }
Map_For_ABD => {
          'ABDE' => List_For_ABDE
          'ABDX' => List_For_ABDX
          }


问:
I do not understand this PHP Code, what is it doing?
How to read php

i'm learning php, I wrote this.  (It is from a book)

```<code>   <?php if(!empty($data)):  ?>
        <ul>
             <?php foreach ($data as $dataprint): ?>
                  <li><?= $dataprint ?></li>
             <?php endforeach ?>
        </ul>
</code>```

I am unable to understand some of the code in this section.

 1. Why are there colons on line 1 and 3?

 2. What does the '<?= $dataprint ?> ) and why does it not have the standard 'PHP' word?

 3. why is there an equal mark in the next?

答:
You can write loops in php many type...
1)eg: if(condition){...code...}else{...code...} or if(condition): means, in place of "{" you can use ":" and for ending the loop use "endif"
2) Your point no 2 is written in shortcode in php for that you have to enabled shortcode in php.ini</p>

Body:
How to read php

i'm learning php, I wrote this.  (It is from a book)

   <?php if(!empty($data)):  ?>

             <?php foreach ($data as $dataprint): ?>

<?= $dataprint ?>

             <?php endforeach ?>

I am unable to understand some of the code in this section.

 1. Why are there colons on line 1 and 3?

 2. What does the '<?= $dataprint ?> ) and why does it not have the standard 'PHP' word?

 3. why is there an equal mark in the next?


问:
Hibernate ConstraintViolationException on SELECT query
I have a Persistent Class with multi-field unique constraint on it. But defined unique constraint is not sufficient for me because on one those field non-equal but similar values are unique too.

I implement a checkUniqueConstraint method.
In add and update  methods of DAO class, I call checkUniqueConstraint before adding or updating persist object.

checkUniqueConstraint method just run a SELECT query to find object similar to input and throw a check Exception where find some ones.

```<code>public class PersistClassDao {
public void checkUniqueConstraint(PersistClass persistObject) throws DuplicateEntityException {
    /**
    * creating a query string that find persist objects similar to input parameter.
    **/
    try {
        PersistClass result = (PersistClass) query.uniqueResult();
        if(result != null && (persistObject.getId() == null  || persistObject.getId() != result.getId())){
            throw new DuplicateEntityException(exceptionMessage, "");
        }
    } catch (NonUniqueResultException e) {
        throw new DuplicateEntityException(exceptionMessage);
    }
}

public long add(/* field of new persistObject*/) throws DuplicateEntityException {
    //creates a transisent instance of persistObject
    PersistClass newObject = getPersistClass(/* field of new persistObject*/);
    checkUniqueConstraint(newObject);
    try {
        getCurrentSession().save(newObject);
        getCurrentSession().flush();
        return newObject.getId();
    } catch (ConstraintViolationException e) {
        throw new DuplicateEntityException();
    }
}
</code>```

I have a transactionl service mehod for add and another for update.

When I run my test that

First add 2 persistObjects (through service method).

Then update one (through service method) them so that be similar to the other

I expect that DuplicatException be thrown

But really a org.hibernate.exception. ConstraintViolationException  thrown through checkUniqueConstraint!!

Why?

答:
Hibernate will only flush before select if there is any insert / update operation before the select. By default, Hibernate does not immediately commit changes to the DB when save or update is called. This is to take advantage of JDBC batching to improve performance. Hibernate will only flush changes to the db when session is closed, transaction is committed or a select is issued to the DB. This flush before select is necessary because without the prior changes being flushed to the DB, the query result might not be correct.

So your insert/update is actually a object creation/updation being called before the find method, and is only flushed down to the DB prior to the select.

Body:
I have a Persistent Class with multi-field unique constraint on it. But defined unique constraint is not sufficient for me because on one those field non-equal but similar values are unique too.

I implement a checkUniqueConstraint method.
In add and update  methods of DAO class, I call checkUniqueConstraint before adding or updating persist object.

checkUniqueConstraint method just run a SELECT query to find object similar to input and throw a check Exception where find some ones.

public class PersistClassDao {
public void checkUniqueConstraint(PersistClass persistObject) throws DuplicateEntityException {
    /**
    * creating a query string that find persist objects similar to input parameter.
    **/
    try {
        PersistClass result = (PersistClass) query.uniqueResult();
        if(result != null && (persistObject.getId() == null  || persistObject.getId() != result.getId())){
            throw new DuplicateEntityException(exceptionMessage, "");
        }
    } catch (NonUniqueResultException e) {
        throw new DuplicateEntityException(exceptionMessage);
    }
}

public long add(/* field of new persistObject*/) throws DuplicateEntityException {
    //creates a transisent instance of persistObject
    PersistClass newObject = getPersistClass(/* field of new persistObject*/);
    checkUniqueConstraint(newObject);
    try {
        getCurrentSession().save(newObject);
        getCurrentSession().flush();
        return newObject.getId();
    } catch (ConstraintViolationException e) {
        throw new DuplicateEntityException();
    }
}

I have a transactionl service mehod for add and another for update.

When I run my test that

First add 2 persistObjects (through service method).

Then update one (through service method) them so that be similar to the other

I expect that DuplicatException be thrown

But really a org.hibernate.exception. ConstraintViolationException  thrown through checkUniqueConstraint!!

Why?


答:
You didn't say which User Interface you are using. If you are using ASP.NET Web forms, you can use AutoComplete control from AjaxControlToolkit.

Here you can find a demonstration: http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/AutoComplete/AutoComplete.aspx

Title: Autocomplete from 10 000 items in .NET

Body:
I've got an in memory collection of around 10K objects. I want to give users the ability to type part of the item name or description and display an autocomplete list. What is an efficient way to do it? I really need the fastest possible response time, users are very fast.

Thanks a lot,
Mary


问:
Adding sorted and unsorted integer to list box in C#
Within my system I have a text box and button that allows the user to input an integer to the list box. However, I want to include two radio buttons - sorted and unsorted, so that the user has to select whether they want the integer to be sorted or unsorted when added.

This is the code I have so far for the add button;

```<code>private void buttonAdd_Click(object sender, EventArgs e)
{
    listBoxAddedIntegers.Items.Add(textBoxInsert.Text);
    textBoxInsert.Text = string.Empty;
    //MessageBox.Show(listBoxAddedIntegers.SelectedIndex.ToString());
    MessageBox.Show(listBoxAddedIntegers.Items.Count.ToString());
}
</code>```

this is the code for the radio button 'sorted;

```<code>private void radioButtonSorted_CheckedChanged(object sender, EventArgs e)
{
   radioButtonSorted.Checked = true;
}
</code>```

and this is the code for the 'unsorted' radio button -

```<code>private void radioButtonUnsorted_CheckedChanged(object sender, EventArgs e)
{
   radioButtonSorted.Checked = false;
}
</code>```

Does anyone have any suggestions on how to add an integer to the list, so that when the user selects the radio button 'sorted' and then clicks add integer, the integer is then added to the sorted list? Thank you.

答:
this will sort all the items from your list box if sorted is checked, still i don't think its necessary to have 2 redio buttons. you can replace that with single checkbox   </p>

```<code>                List<int> numbers = new List<int>();
                private void buttonAdd_Click(object sender, EventArgs e)
                {
                    if (radioButtonSorted.Checked)
                    {
                        numbers.Clear();

                        if (!string.IsNullOrEmpty(textBoxInsert.Text))
                            numbers.Add(int.Parse(textBoxInsert.Text));

                        foreach (var item in listBoxAddedIntegers.Items)
                        {
                            if (item != null)
                                numbers.Add(int.Parse(item.ToString()));
                        }

                        listBoxAddedIntegers.Items.Clear();
                        numbers.Sort();
                        foreach (var number in numbers)
                            listBoxAddedIntegers.Items.Add(number);
                    }
                    else
                        listBoxAddedIntegers.Items.Add(textBoxInsert.Text);

                    textBoxInsert.Text = string.Empty;
                    //MessageBox.Show(listBoxAddedIntegers.SelectedIndex.ToString());
                    MessageBox.Show(listBoxAddedIntegers.Items.Count.ToString());
                    }
</code>```

Body:
Within my system I have a text box and button that allows the user to input an integer to the list box. However, I want to include two radio buttons - sorted and unsorted, so that the user has to select whether they want the integer to be sorted or unsorted when added.

This is the code I have so far for the add button;

private void buttonAdd_Click(object sender, EventArgs e)
{
    listBoxAddedIntegers.Items.Add(textBoxInsert.Text);
    textBoxInsert.Text = string.Empty;
    //MessageBox.Show(listBoxAddedIntegers.SelectedIndex.ToString());
    MessageBox.Show(listBoxAddedIntegers.Items.Count.ToString());
}

this is the code for the radio button 'sorted;

private void radioButtonSorted_CheckedChanged(object sender, EventArgs e)
{
   radioButtonSorted.Checked = true;
}

and this is the code for the 'unsorted' radio button -

private void radioButtonUnsorted_CheckedChanged(object sender, EventArgs e)
{
   radioButtonSorted.Checked = false;
}

Does anyone have any suggestions on how to add an integer to the list, so that when the user selects the radio button 'sorted' and then clicks add integer, the integer is then added to the sorted list? Thank you.

Body:
this will sort all the items from your list box if sorted is checked, still i don't think its necessary to have 2 redio buttons. you can replace that with single checkbox

                List<int> numbers = new List<int>();
                private void buttonAdd_Click(object sender, EventArgs e)
                {
                    if (radioButtonSorted.Checked)
                    {
                        numbers.Clear();

                        if (!string.IsNullOrEmpty(textBoxInsert.Text))
                            numbers.Add(int.Parse(textBoxInsert.Text));

                        foreach (var item in listBoxAddedIntegers.Items)
                        {
                            if (item != null)
                                numbers.Add(int.Parse(item.ToString()));
                        }

                        listBoxAddedIntegers.Items.Clear();
                        numbers.Sort();
                        foreach (var number in numbers)
                            listBoxAddedIntegers.Items.Add(number);
                    }
                    else
                        listBoxAddedIntegers.Items.Add(textBoxInsert.Text);

                    textBoxInsert.Text = string.Empty;
                    //MessageBox.Show(listBoxAddedIntegers.SelectedIndex.ToString());
                    MessageBox.Show(listBoxAddedIntegers.Items.Count.ToString());
                    }


问:
how to display UIViewController from a NSObject class?
There is a current view as UIViewController which call "LoginView" but I'm not in, I'm in a NSObject class and I want to call, display an other UIViewController which is call "MapView". How can I do this?

The problem is like above screenshot.

答:
I used like this in my NSObject class:

```<code>[[[UIApplication sharedApplication] delegate].window.rootViewController presentViewController:yourMapViewContorller animated:YES completion:nil];
</code>```

I hope it's useful.

Body:
I used like this in my NSObject class:

[[[UIApplication sharedApplication] delegate].window.rootViewController presentViewController:yourMapViewContorller animated:YES completion:nil];

I hope it's useful.


问:
Why does my 'transform' not work?

.rotate {
  display: block;
  width: 64px;
  height: 64px;
  border: 2px black dashed;
  animation: rotate 40s linear infinite;
  border-radius: 50%;
  transform: scale(1.8);
  position: relative;
  top: 50px;
  left: 50px;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="rotate"></div></code>```

if you take a look at the fiddle, the "transform: scale(1.8);" didn't work. Is there any other alternatives to make the border bigger?

答:
There you go. The transform isn't working when you're trying to scale in the initial rotate class is because, its gradually changing because of the rotating animation. You have to fix/scale the width or height initially and your border size then apply the animation on it as shown.

.rotate {
 display: block;
 width: 115px;
 height: 115px;
 border: 4px black dashed;
 animation: rotate 40s linear infinite;
 border-radius: 50%;
  position: relative;
  top: 50px;
  left: 50px;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);}
  100% {
    transform: rotate(360deg);
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="rotate"></div></code>```

Title: Why does my 'transform' not work?

Body:
.rotate {
  display: block;
  width: 64px;
  height: 64px;
  border: 2px black dashed;
  animation: rotate 40s linear infinite;
  border-radius: 50%;
  transform: scale(1.8);
  position: relative;
  top: 50px;
  left: 50px;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

if you take a look at the fiddle, the "transform: scale(1.8);" didn't work. Is there any other alternatives to make the border bigger?

Body:
There you go. The transform isn't working when you're trying to scale in the initial rotate class is because, its gradually changing because of the rotating animation. You have to fix/scale the width or height initially and your border size then apply the animation on it as shown.

.rotate {
 display: block;
 width: 115px;
 height: 115px;
 border: 4px black dashed;
 animation: rotate 40s linear infinite;
 border-radius: 50%;
  position: relative;
  top: 50px;
  left: 50px;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);}
  100% {
    transform: rotate(360deg);
    }
}

<div class="rotate"></div>


问:
Getting back to my application after sending sms using intent
I have been searching for this, found many threads specifying on this. But things are not working for me. Tried setting "exit_on_sent" and also tried using startAcitivityForResult. Here is the code snippet I was trying with</p>

```<code>Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("smsto:" + phoneNumbers)); // phoneNumbers is a list of phone numbers to which i need to send messages at the same time
sendIntent.putExtra("sms_body", context.getResources().getString(R.string.message_body));
sendIntent.putExtra("exit_on_sent", true);
context.startActivity(sendIntent);
</code>```

答:
My requirement is to go back to my application after sending message.

When you use ACTION_SENDTO, or ACTION_VIEW, or other Intent actions, you are launching a third-party app to go do something. In this case, you are launching a third-party app to send an SMS message.

There are ~2 billion Android devices in use, spread across ~10,000 device models. There will be dozens, if not hundreds, of different pre-installed SMS clients across those device models. Users are also welcome to install other SMS clients from the Play Store or other app distribution channels.

What happens when your app starts up one of those hundreds of SMS clients is up to the developers of those SMS clients, not you.

If you want control over the entire user experience, send the SMS message yourself, using SmsManager, as Ankit pointed out. If you want to use the user's preferred SMS client, stick with ACTION_SENDTO, but what happens at that point is up to the SMS client developers and the user, not you.

Body:
I have been searching for this, found many threads specifying on this. But things are not working for me. Tried setting "exit_on_sent" and also tried using startAcitivityForResult. Here is the code snippet I was trying with

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("smsto:" + phoneNumbers)); // phoneNumbers is a list of phone numbers to which i need to send messages at the same time
sendIntent.putExtra("sms_body", context.getResources().getString(R.string.message_body));
sendIntent.putExtra("exit_on_sent", true);
context.startActivity(sendIntent);


问:
Maybe in room not returning data but if i do query with aysnctask it returns data?
I am trying to get data from room using maybe/Flowable  its returns nothing but if i try with AsyncTask its returns data .

Here my query:

```<code>@Query("SELECT * FROM Media WHERE path LIKE :path")
Maybe<Media> getMediaByPathTest(String path);
</code>```

and code in Activity:

```<code>                AppDatabase.getInstance(getActivity()).mediaDao()
                    .getMediaByPathTest(getCurrentMedia().getPath())
                    .observeOn(Schedulers.io())
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .subscribe(media -> {

                                if (media != null && media.isFavourite()) {
                                    Toast.makeText(SingleMediaActivity.this,
                                            "Bingo I m favorite", Toast.LENGTH_SHORT).show();
                                }

                            }, throwable -> {
                            }
                            , () -> {
                            });
</code>```

its show error

W/System.err: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

what i am doing wrong and how to do it right?

答:
You switched around the observeOn and subscribeOn. You're subscribed on the main thread (preventing you from accessing the database). Simply switch those:</p>

```<code>.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
</code>```

Body:
I am trying to get data from room using maybe/Flowable  its returns nothing but if i try with AsyncTask its returns data .

Here my query:

@Query("SELECT * FROM Media WHERE path LIKE :path")
Maybe<Media> getMediaByPathTest(String path);

and code in Activity:

                AppDatabase.getInstance(getActivity()).mediaDao()
                    .getMediaByPathTest(getCurrentMedia().getPath())
                    .observeOn(Schedulers.io())
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .subscribe(media -> {

                                if (media != null && media.isFavourite()) {
                                    Toast.makeText(SingleMediaActivity.this,
                                            "Bingo I m favorite", Toast.LENGTH_SHORT).show();
                                }

                            }, throwable -> {
                            }
                            , () -> {
                            });

its show error

W/System.err: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

what i am doing wrong and how to do it right?

Body:
You switched around the observeOn and subscribeOn. You're subscribed on the main thread (preventing you from accessing the database). Simply switch those:

.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())


问:
robolectric java.lang.NoSuchFieldException: sSystem
While doing UnitTest by using robolectric, I receive the error

java.lang.NoSuchFieldException: sSystem

Please give me an advice.

Description

Integrated robolectric error

```<code>java.lang.RuntimeException: java.lang.RuntimeException: java.lang.NoSuchFieldException: sSystem

at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:332)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:259)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:41)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:199)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.RuntimeException: java.lang.NoSuchFieldException: sSystem
at org.robolectric.util.ReflectionHelpers.setStaticField(ReflectionHelpers.java:174)
at org.robolectric.shadows.ShadowAssetManager.reset(ShadowAssetManager.java:780)
at org.robolectric.Shadows.reset(Shadows.java:1644)
at org.robolectric.Robolectric.reset(Robolectric.java:35)
at org.robolectric.internal.ParallelUniverse.resetStaticState(ParallelUniverse.java:52)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:319)
... 19 more
Caused by: java.lang.NoSuchFieldException: sSystem
at java.lang.Class.getDeclaredField(Class.java:2070)
at org.robolectric.util.ReflectionHelpers.setStaticField(ReflectionHelpers.java:172)
... 24 more
</code>```

Steps to Reproduce

Robolectric & Android Version

```<code>compileSdkVersion 25
buildToolsVersion "25.0.2"
minSdkVersion 15
targetSdkVersion 25
testCompile 'org.robolectric:robolectric:3.2.2'
</code>```

答:
I've had this in a kotlin test and fixed it by opening up my test-class:

```<code>@RunWith(RobolectricTestRunner::class)
@Config(sdk = [23], constants = BuildConfig::class)
open class MyExampleTest {
</code>```

Applied to java this means your test class shouldn't be final

.

Body:
While doing UnitTest by using robolectric, I receive the error

java.lang.NoSuchFieldException: sSystem

Please give me an advice.

Description

Integrated robolectric error

java.lang.RuntimeException: java.lang.RuntimeException: java.lang.NoSuchFieldException: sSystem

at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:332)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:259)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:41)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:199)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.RuntimeException: java.lang.NoSuchFieldException: sSystem
at org.robolectric.util.ReflectionHelpers.setStaticField(ReflectionHelpers.java:174)
at org.robolectric.shadows.ShadowAssetManager.reset(ShadowAssetManager.java:780)
at org.robolectric.Shadows.reset(Shadows.java:1644)
at org.robolectric.Robolectric.reset(Robolectric.java:35)
at org.robolectric.internal.ParallelUniverse.resetStaticState(ParallelUniverse.java:52)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:319)
... 19 more
Caused by: java.lang.NoSuchFieldException: sSystem
at java.lang.Class.getDeclaredField(Class.java:2070)
at org.robolectric.util.ReflectionHelpers.setStaticField(ReflectionHelpers.java:172)
... 24 more

Steps to Reproduce

Robolectric & Android Version

compileSdkVersion 25
buildToolsVersion "25.0.2"
minSdkVersion 15
targetSdkVersion 25
testCompile 'org.robolectric:robolectric:3.2.2'

Body:
I've had this in a kotlin test and fixed it by opening up my test-class:

@RunWith(RobolectricTestRunner::class)
@Config(sdk = [23], constants = BuildConfig::class)
open class MyExampleTest {

Applied to java this means your test class shouldn't be final

.


问:
How to get ttl along with the value for a key in redis/redisson
I am storing a Key and value in Redis using redisson java client .
Example as below

```<code>RMapCache<String, Integer> mapCache = redisson.getMapCache("test");

    // with ttl = 10 seconds
    Integer prevValue = mapCache.put("1", 10, 10, TimeUnit.SECONDS);
</code>```

Is there a way I can get the remaining ttl for the key when I do a get on the mapCahce ?

答:
Currently you can do that using RKeys and querying for the keys you are interested in

```<code>RKeys rkeys = redissonClient.getKeys();
long ttl = rkeys.remainTimeToLive(key);
</code>```

It would be nice although to have a wrapper that exposes both the value and the ttl of a key

Body:
I am storing a Key and value in Redis using redisson java client .
Example as below

RMapCache<String, Integer> mapCache = redisson.getMapCache("test");

    // with ttl = 10 seconds
    Integer prevValue = mapCache.put("1", 10, 10, TimeUnit.SECONDS);

Is there a way I can get the remaining ttl for the key when I do a get on the mapCahce ?

Body:
Currently you can do that using RKeys and querying for the keys you are interested in

RKeys rkeys = redissonClient.getKeys();
long ttl = rkeys.remainTimeToLive(key);

It would be nice although to have a wrapper that exposes both the value and the ttl of a key


问:
nhibernate reference parent class in child class
Is it possible to refer to a parent object in a child object using nhibernate?  What I have been doing up until now is putting the parent Id in the child class, allowing me to determine what the parent of any child is at runtime.

Someone has told me that I can instead refer to the entire parent object in my child, and not just the parent id, without running into recursion issues.

What I currently do is this:

```<code>Child child = (Child)session.Get(typeof(Child), childId);
</code>```

Then I can get hold of my parentId like so:

```<code>int parentId = child.ParentId;
</code>```

What I want to do is this:

```<code>Child child = (Child)session.Get(typeof(Child), childId);

int parentId = child.**Parent**.Id;

string parentName = child.**Parent**.Name
</code>```

Here is an example of how I define my classes

```<code>public class Parent
{
public int Id { get; set; }
public string Name { get; set; }

// A list of child objects
public IList<Child> Children { get; set; }
}

public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; } // this is what I use now

// public Parent MyParent { get; set; } // this is what I want to use
}
</code>```

My nHibernate mapping files:

```<code>   <class name="Parent" table="parents" lazy="false">
        <id name="Id">
            <generator class="identity" />
        </id>
        <property name="Name" />
        <bag name="Children" cascade="all" lazy="false" >
            <key column="ParentId" />
            <one-to-many class="Child"/>
        </bag>

        <!-- Do I put anything in here to refer to my parent object in my child object?-->
    </class>

   <class name="Child" table="Children" lazy="false">
        <id name="Id">
            <generator class="identity" />
        </id>
        <property name="ParentId" />
        <property name="Name" />

        <!-- Do I put anything in here to refer to my parent object in my child object?-->
    </class>
</code>```

Any help gratefully appreciated!

答:
sure this is possible: </p>

```<code><!-- Set inverse to true on the one-to-many to tell
     NHibernate this relation is mapped from both sides -->
<bag name="Children" cascade="all" lazy="false" inverse="true">
    <key column="ParentId" />
    <one-to-many class="Child"/>
</bag>

<class name="Child" table="Children" lazy="false">
    <id name="Id">
        <generator class="identity" />
    </id>
    <property name="ParentId" />
    <!-- Use this to map the Parent object -->
    <many-to-one name="MyParent" class="Parent" column="ParentId"/>
<property name="Name" />
    </class>
</code>```

Body:
Is it possible to refer to a parent object in a child object using nhibernate?  What I have been doing up until now is putting the parent Id in the child class, allowing me to determine what the parent of any child is at runtime.

Someone has told me that I can instead refer to the entire parent object in my child, and not just the parent id, without running into recursion issues.

What I currently do is this:

Child child = (Child)session.Get(typeof(Child), childId);

Then I can get hold of my parentId like so:

int parentId = child.ParentId;

What I want to do is this:

Child child = (Child)session.Get(typeof(Child), childId);

int parentId = child.**Parent**.Id;

string parentName = child.**Parent**.Name

Here is an example of how I define my classes

public class Parent
{
public int Id { get; set; }
public string Name { get; set; }

// A list of child objects
public IList<Child> Children { get; set; }
}

public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; } // this is what I use now

// public Parent MyParent { get; set; } // this is what I want to use
}

My nHibernate mapping files:

   <class name="Parent" table="parents" lazy="false">
        <id name="Id">
            <generator class="identity" />
        </id>
        <property name="Name" />
        <bag name="Children" cascade="all" lazy="false" >
            <key column="ParentId" />
            <one-to-many class="Child"/>
        </bag>

    </class>

   <class name="Child" table="Children" lazy="false">
        <id name="Id">
            <generator class="identity" />
        </id>
        <property name="ParentId" />
        <property name="Name" />

    </class>

Any help gratefully appreciated!

Body:
sure this is possible:

<!-- Set inverse to true on the one-to-many to tell
     NHibernate this relation is mapped from both sides -->
<bag name="Children" cascade="all" lazy="false" inverse="true">
    <key column="ParentId" />
    <one-to-many class="Child"/>
</bag>

<class name="Child" table="Children" lazy="false">
    <id name="Id">
        <generator class="identity" />
    </id>
    <property name="ParentId" />
    <!-- Use this to map the Parent object -->
    <many-to-one name="MyParent" class="Parent" column="ParentId"/>
<property name="Name" />
    </class>


问:
Using AddressOf Dynamically
I'm adding buttons to form at runtime using the following code :

```<code>Private Sub AddNewButton(ByVal btnName As String, ByVal btnText As String)
    Dim myButtons As New VIBlend.WinForms.Controls.vButton

    With myButtons
        .Size = New Size(200, 60)
        .Visible = True
        .Location = New Point(55, 33)
        .Text = btnText
        .Name = btnName
        .Font = New Font("Times New Roman", 12, FontStyle.Bold, GraphicsUnit.Point)
    End With

    AddHandler myButtons.Click, AddressOf btnName & "_Click"

    btnsPanel.Controls.Add(myButtons)

End Sub
</code>```

Code works fine but Vb.net doesn't allow me to assign AddressOf a sub procedure using variable AddressOf btnName & "_Click" says AddressOf operand must be the name of method, the problem is I don't know which button is going to be created and which procedure is it going to call, I want to assign AddressOf procedure using variable
Is it possible or do I have any other choice ?

答:
The question, though old, lacks a direct and complete answer. Here it is, a fully dynamicall handler of a (dynamic) button:</p>

```<code>    Dim SubName As String = dr("SubToRun").ToString
    Dim Pareameter1 As String = dr("Pareameter1").ToString
    Dim Pareameter2 As String = dr("Pareameter2").ToString
    Dim Pareameter3 As Int32 = ValPareameter3
    AddHandler btn.Click, Sub(s, e)
                              CallByName(Me, SubName, CallType.Method, Pareameter1, Pareameter2, Pareameter1)
                          End Sub
</code>```

Title: Using AddressOf Dynamically

Body:
I'm adding buttons to form at runtime using the following code :

Private Sub AddNewButton(ByVal btnName As String, ByVal btnText As String)
    Dim myButtons As New VIBlend.WinForms.Controls.vButton

    With myButtons
        .Size = New Size(200, 60)
        .Visible = True
        .Location = New Point(55, 33)
        .Text = btnText
        .Name = btnName
        .Font = New Font("Times New Roman", 12, FontStyle.Bold, GraphicsUnit.Point)
    End With

    AddHandler myButtons.Click, AddressOf btnName & "_Click"

    btnsPanel.Controls.Add(myButtons)

End Sub

Code works fine but Vb.net doesn't allow me to assign AddressOf a sub procedure using variable AddressOf btnName & "_Click" says AddressOf operand must be the name of method, the problem is I don't know which button is going to be created and which procedure is it going to call, I want to assign AddressOf procedure using variable
Is it possible or do I have any other choice ?

Body:
The question, though old, lacks a direct and complete answer. Here it is, a fully dynamicall handler of a (dynamic) button:

    Dim SubName As String = dr("SubToRun").ToString
    Dim Pareameter1 As String = dr("Pareameter1").ToString
    Dim Pareameter2 As String = dr("Pareameter2").ToString
    Dim Pareameter3 As Int32 = ValPareameter3
    AddHandler btn.Click, Sub(s, e)
                              CallByName(Me, SubName, CallType.Method, Pareameter1, Pareameter2, Pareameter1)
                          End Sub


答:
Not that hard really. Increase the height and width manually and increase the border-width.

.rotate {
  display: block;
  width: 115px;
  height: 115px;
  border: 4px black dashed;
  animation: rotate 40s linear infinite;
  border-radius: 50%;
  position: relative;
  top: 50px;
  left: 50px;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="rotate"></div></code>```

Title: Why does my 'transform' not work?

Body:
Not that hard really. Increase the height and width manually and increase the border-width.

.rotate {
  display: block;
  width: 115px;
  height: 115px;
  border: 4px black dashed;
  animation: rotate 40s linear infinite;
  border-radius: 50%;
  position: relative;
  top: 50px;
  left: 50px;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

<div class="rotate"></div>


问:
What's the replacement for jwt.key-uri in spring boot 2
We are using spring boot 1 oauth with following properties.

security.oauth2.resource.jwt.key-uri

Somehow it was missing from spring boot2, any replacement for that?

答:
I asked the same question in the gitter chat.

Dave Syer said:

Those features were removed. They are migrating to Spring Security.
  But slowly. The plan is to have a shim jar that you can use in the
  transition period. but that's not done yet @rwinch said he was going
  to publish something after Spring One (i.e. next week earliest)

So there is no replacement yet. They removed some resource server Autoconfiguration from spring-boot. And they did not yet add it back to spring-security. But this will come soon.

So all you can do at the moment is to copy over the needed code from spring-boot 1.5.

EDIT

In the meantime there is a project that helps you to get the spring-security-oauth autoconfiguration in spring-boot 2 - see https://github.com/spring-projects/spring-security-oauth2-boot

See also the spring boot 1.5->2.0 migration guide - https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide#oauth2


问:
How to get part of filename into a variable?
I have a lot of .csv files and I'd like to parse the file names.

The file names are in this format:

```<code>name.surname.csv
</code>```

How can I write a function that populates two variables with the components of the file name?

```<code>A = name
B = surname
</code>```

答:
Simple use str.split() method and this function.</p>

```<code>def split_names(input:str):
    splitted = input.split(".")
    return splitted[0], splitted[1]

A, B = split_names("name.surname.csv")
</code>```

Body:
I have a lot of .csv files and I'd like to parse the file names.

The file names are in this format:

name.surname.csv

How can I write a function that populates two variables with the components of the file name?

A = name
B = surname

Body:
Simple use str.split() method and this function.

def split_names(input:str):
    splitted = input.split(".")
    return splitted[0], splitted[1]

A, B = split_names("name.surname.csv")


问:
Can't remove unexpected reverse indents from flexbox cols with 100% height
I don't understand, why I get this indents at the bottom:

I want to split row into cols of equal height, to make same height borders between cols. But somehow I get reverse indents. I don't use floats, so why they appeared? I need to write height:100%, because I need to have these borders. How to remove this bug and save the same height of cols? This is my code:

*,
*:before,
*:after {
  box-sizing: border-box;
}

.container {
  padding-right: 50px;
  padding-left: 50px;
  background-color: #fff;
  box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.36);
}

.container {
  position: relative;
}

.container:before,
.container:after {
  content: "";
  display: table;
}

.container:after {
  clear: both;
}

.row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -50px;
  margin-left: -50px;
}

.row.no-gutters [class^='col-'],
.row.no-gutters .col {
  padding-left: 0;
  padding-right: 0;
}

[class^='col-'],
.col {
  position: relative;
  width: 100%;
  flex: 0 0 100%;
  max-width: 100%;
  min-height: 1px;
  padding-right: 50px;
  padding-left: 50px;
}

.col-lg-3 {
  flex: 0 0 33.33333%;
  max-width: 33.33333%;
}

.feature {
  position: relative;
  flex: 0 1 auto;
  height: 100%;
  margin: 29px 0 0;
  padding: 8px 50px 0;
  text-align: center;
}

.feature__h {
  margin: 26px 0 30px;
  font-weight: 400;
  font-size: 29.23px;
  color: #2e3035;
}

.feature__p {
  margin: 1px 0 20px;
  line-height: 1.4;
  color: #828285;
}

.col+.col>.feature {
  border-left: 1px solid #2e3035;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://necolas.github.io/normalize.css/7.0.0/normalize.css" rel="stylesheet" />
<div class="container">
  <div class="row no-gutters">
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
  </div>
  <!--.row-->
</div>
<!--.container--></code>```

答:
It's the combination of height: 100% and margin: 29px 0 0 on .feature that cause an overflow.

Assuming the margin were set so one can see the shadow, remove the margin from the .feature and instead add a bottom margin on the .container

You also used flex: 0 1 auto; on .feature, though since its parent is not a flex container, it won't apply and were removed.

Stack snippet

*,
*:before,
*:after {
  box-sizing: border-box;
}

.container {
  padding-right: 50px;
  padding-left: 50px;
  background-color: #fff;
  box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.36);
  margin-bottom: 20px;                      /*  added  */
}

.container {
  position: relative;
}

.container:before,
.container:after {
  content: "";
  display: table;
}

.container:after {
  clear: both;
}

.row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -50px;
  margin-left: -50px;
}

.row.no-gutters [class^='col-'],
.row.no-gutters .col {
  padding-left: 0;
  padding-right: 0;
}

[class^='col-'],
.col {
  position: relative;
  width: 100%;
  flex: 0 0 100%;
  max-width: 100%;
  min-height: 1px;
  padding-right: 50px;
  padding-left: 50px;
  padding-top: 26px;
}

.col-lg-3 {
  flex: 0 0 33.33333%;
  max-width: 33.33333%;
}

.feature {
  position: relative;
  /*flex: 0 1 auto;                             not needed  */
  height: 100%;
  padding: 8px 50px 0;
  text-align: center;
}

.feature__h {
  margin: 26px 0 30px;
  font-weight: 400;
  font-size: 29.23px;
  color: #2e3035;
}

.feature__p {
  margin: 1px 0 20px;
  line-height: 1.4;
  color: #828285;
}

.col+.col>.feature {
  border-left: 1px solid #2e3035;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://necolas.github.io/normalize.css/7.0.0/normalize.css" rel="stylesheet" />
<div class="container">
  <div class="row no-gutters">
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
  </div>
  <!--.row-->
</div>
<!--.container--></code>```

Updated

Using height: 100% on .feature might cause you issue cross browsers, instead you could remove it and add display: flex to the .col-lg-3.

With this you take advantage of the flex "row" item's property align-items, which defaults to stretch, and will make the .feature equally high.

Stack snippet

*,
*:before,
*:after {
  box-sizing: border-box;
}

.container {
  padding-right: 50px;
  padding-left: 50px;
  background-color: #fff;
  box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.36);
  margin-bottom: 20px;                       /*  added  */
}

.container {
  position: relative;
}

.container:before,
.container:after {
  content: "";
  display: table;
}

.container:after {
  clear: both;
}

.row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -50px;
  margin-left: -50px;
}

.row.no-gutters [class^='col-'],
.row.no-gutters .col {
  padding-left: 0;
  padding-right: 0;
}

[class^='col-'],
.col {
  position: relative;
  width: 100%;
  flex: 0 0 100%;
  max-width: 100%;
  min-height: 1px;
  padding-right: 50px;
  padding-left: 50px;
  padding-top: 26px;
}

.col-lg-3 {
  flex: 0 0 33.33333%;
  max-width: 33.33333%;
  display: flex;                             /*  added  */
}

.feature {
  position: relative;
  padding: 8px 50px 0;
  text-align: center;
}

.feature__h {
  margin: 26px 0 30px;
  font-weight: 400;
  font-size: 29.23px;
  color: #2e3035;
}

.feature__p {
  margin: 1px 0 20px;
  line-height: 1.4;
  color: #828285;
}

.col+.col>.feature {
  border-left: 1px solid #2e3035;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://necolas.github.io/normalize.css/7.0.0/normalize.css" rel="stylesheet" />
<div class="container">
  <div class="row no-gutters">
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
  </div>
  <!--.row-->
</div>
<!--.container--></code>```

Body:
I don't understand, why I get this indents at the bottom:

I want to split row into cols of equal height, to make same height borders between cols. But somehow I get reverse indents. I don't use floats, so why they appeared? I need to write height:100%, because I need to have these borders. How to remove this bug and save the same height of cols? This is my code:

*,
*:before,
*:after {
  box-sizing: border-box;
}

.container {
  padding-right: 50px;
  padding-left: 50px;
  background-color: #fff;
  box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.36);
}

.container {
  position: relative;
}

.container:before,
.container:after {
  content: "";
  display: table;
}

.container:after {
  clear: both;
}

.row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -50px;
  margin-left: -50px;
}

.row.no-gutters [class^='col-'],
.row.no-gutters .col {
  padding-left: 0;
  padding-right: 0;
}

[class^='col-'],
.col {
  position: relative;
  width: 100%;
  flex: 0 0 100%;
  max-width: 100%;
  min-height: 1px;
  padding-right: 50px;
  padding-left: 50px;
}

.col-lg-3 {
  flex: 0 0 33.33333%;
  max-width: 33.33333%;
}

.feature {
  position: relative;
  flex: 0 1 auto;
  height: 100%;
  margin: 29px 0 0;
  padding: 8px 50px 0;
  text-align: center;
}

.feature__h {
  margin: 26px 0 30px;
  font-weight: 400;
  font-size: 29.23px;
  color: #2e3035;
}

.feature__p {
  margin: 1px 0 20px;
  line-height: 1.4;
  color: #828285;
}

.col+.col>.feature {
  border-left: 1px solid #2e3035;
}

<link href="https://necolas.github.io/normalize.css/7.0.0/normalize.css" rel="stylesheet" />

feature 1

          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text

feature 1

          text text text text text text text text text text text text text text text text

feature 1

          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text

Body:
It's the combination of height: 100% and margin: 29px 0 0 on .feature that cause an overflow.

Assuming the margin were set so one can see the shadow, remove the margin from the .feature and instead add a bottom margin on the .container

You also used flex: 0 1 auto; on .feature, though since its parent is not a flex container, it won't apply and were removed.

Stack snippet

*,
*:before,
*:after {
  box-sizing: border-box;
}

.container {
  padding-right: 50px;
  padding-left: 50px;
  background-color: #fff;
  box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.36);
  margin-bottom: 20px;                      /*  added  */
}

.container {
  position: relative;
}

.container:before,
.container:after {
  content: "";
  display: table;
}

.container:after {
  clear: both;
}

.row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -50px;
  margin-left: -50px;
}

.row.no-gutters [class^='col-'],
.row.no-gutters .col {
  padding-left: 0;
  padding-right: 0;
}

[class^='col-'],
.col {
  position: relative;
  width: 100%;
  flex: 0 0 100%;
  max-width: 100%;
  min-height: 1px;
  padding-right: 50px;
  padding-left: 50px;
  padding-top: 26px;
}

.col-lg-3 {
  flex: 0 0 33.33333%;
  max-width: 33.33333%;
}

.feature {
  position: relative;
  /*flex: 0 1 auto;                             not needed  */
  height: 100%;
  padding: 8px 50px 0;
  text-align: center;
}

.feature__h {
  margin: 26px 0 30px;
  font-weight: 400;
  font-size: 29.23px;
  color: #2e3035;
}

.feature__p {
  margin: 1px 0 20px;
  line-height: 1.4;
  color: #828285;
}

.col+.col>.feature {
  border-left: 1px solid #2e3035;
}

<link href="https://necolas.github.io/normalize.css/7.0.0/normalize.css" rel="stylesheet" />
<div class="container">
  <div class="row no-gutters">
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
  </div>
  <!--.row-->
</div>
<!--.container-->

Updated

Using height: 100% on .feature might cause you issue cross browsers, instead you could remove it and add display: flex to the .col-lg-3.

With this you take advantage of the flex "row" item's property align-items, which defaults to stretch, and will make the .feature equally high.

Stack snippet

*,
*:before,
*:after {
  box-sizing: border-box;
}

.container {
  padding-right: 50px;
  padding-left: 50px;
  background-color: #fff;
  box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.36);
  margin-bottom: 20px;                       /*  added  */
}

.container {
  position: relative;
}

.container:before,
.container:after {
  content: "";
  display: table;
}

.container:after {
  clear: both;
}

.row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -50px;
  margin-left: -50px;
}

.row.no-gutters [class^='col-'],
.row.no-gutters .col {
  padding-left: 0;
  padding-right: 0;
}

[class^='col-'],
.col {
  position: relative;
  width: 100%;
  flex: 0 0 100%;
  max-width: 100%;
  min-height: 1px;
  padding-right: 50px;
  padding-left: 50px;
  padding-top: 26px;
}

.col-lg-3 {
  flex: 0 0 33.33333%;
  max-width: 33.33333%;
  display: flex;                             /*  added  */
}

.feature {
  position: relative;
  padding: 8px 50px 0;
  text-align: center;
}

.feature__h {
  margin: 26px 0 30px;
  font-weight: 400;
  font-size: 29.23px;
  color: #2e3035;
}

.feature__p {
  margin: 1px 0 20px;
  line-height: 1.4;
  color: #828285;
}

.col+.col>.feature {
  border-left: 1px solid #2e3035;
}

<link href="https://necolas.github.io/normalize.css/7.0.0/normalize.css" rel="stylesheet" />
<div class="container">
  <div class="row no-gutters">
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
    <div class="col-lg-3 col">
      <section class="feature">
        <h3 class="feature__h">feature 1</h3>
        <p class="feature__p">
          text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
        </p>
      </section>
      <!--.feature-->
    </div>
    <!--col-->
  </div>
  <!--.row-->
</div>
<!--.container-->


问:
Eval Smarty Code inside a Smarty Template
is there a way to evaluate Smarty Code inside an existing Smarty template? For example, I may have the following construct:

smartyTemplate.tpl

```<code><body>
  <div id="dynamicPart">
     {$valueFromDatabase}
  </div>
</body>
</code>```

Whereas the Smarty variable $valueFromDatabase contains another Smarty Template which I would like to be inserted in place of the variable and then evaluated as a template (with all the logic expressions in replacements neccessary).

答:
```<code>{eval var=$valueFromDatabase}
</code>```

will work

Body:
is there a way to evaluate Smarty Code inside an existing Smarty template? For example, I may have the following construct:

smartyTemplate.tpl

     {$valueFromDatabase}

Whereas the Smarty variable $valueFromDatabase contains another Smarty Template which I would like to be inserted in place of the variable and then evaluated as a template (with all the logic expressions in replacements neccessary).

Body:
{eval var=$valueFromDatabase}

will work