问:
How to use some Jackson Deserializer in own custom Deserializer?
I am struggling with mentioned in the question issue.

I need to create some custom deserializer which is more or less type conversion from the standard deserializer (reason is that ZonedDateTime is working for my input, but I don't want to change the type to ZonedDateTime, but keep LocalDateTime).

Bascially what I want to do in my deserializer is to:

Deserialize using ZonedDateTime deserializer (which I found, in reality, is custom InstantDeserializer )

Use .toLocalDateTime and return it.

How can I use it?
Was trying to find it but I can't.

答:
@JsonDeserialize is used to indicate the use of a custom deserializer

```<code>public class Event {
    public String name;
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    private LocalDateTime date;
}
</code>```

And the custom deserializer is as follows:

```<code>public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
    @Override
    public LocalDateTime deserialize(JsonParser jsonparser, DeserializationContext context)
            throws IOException, JsonProcessingException {
        String date = jsonparser.getText();

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(javaTimeModule);
        ZonedDateTime zonedDateTime = mapper.readValue(date, ZonedDateTime.class);
        return zonedDateTime.toLocalDateTime();
    }
}
</code>```

The demo can be accessed in github

Maven dependency

```<code><dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 -->
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.8.9</version>
        </dependency>

    </dependencies>
</code>```

Body:
@JsonDeserialize is used to indicate the use of a custom deserializer

public class Event {
    public String name;
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    private LocalDateTime date;
}

And the custom deserializer is as follows:

public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
    @Override
    public LocalDateTime deserialize(JsonParser jsonparser, DeserializationContext context)
            throws IOException, JsonProcessingException {
        String date = jsonparser.getText();

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(javaTimeModule);
        ZonedDateTime zonedDateTime = mapper.readValue(date, ZonedDateTime.class);
        return zonedDateTime.toLocalDateTime();
    }
}

The demo can be accessed in github

Maven dependency

<dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 -->
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.8.9</version>
        </dependency>

    </dependencies>


来源: stackexchange

问:
XSLT identity transformation
I am new to XSLT and got a technical question about the identity transformation.

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
</code>```

This is a often posted example, but I never found something about the detailed program sequence. I often read that it works recursively. But I am not sure about the detailed process.
The template matches the union of all attribute-nodes and all other nodes except the root-node. Then the xsl:copy copies the current contextnode (there is no for-each?!) (which should be the first in the document) and applies the template again with the same choice of nodes. This will be done until all nodes are processed?

I would like to know how the program flow is in that identity-building.

==FOLLOW-UP==

Ok, thanks for your answers. I know the processing model of XSLT roughly. Please have a look onto the following. I define a template, which should result in a set of all nodes (except the root node). Then I want to see whats in that set of nodes. For that purpose, I use a for-each and select the name of the current context node.

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="@* | node()">
    <xsl:for-each select="node()">
        <xsl:value-of select="name()" />
    </xsl:for-each>
</xsl:template>

</xsl:transform>
</code>```

with that input xml:

```<code><Telefonliste>
    <Eintrag>
        <name>Peter</name>
        <nachname>Pan</nachname>
        <Tel>12345</Tel>
    </Eintrag>
    <Eintrag>
        <name>Max</name>
        <nachname>Mustermann</nachname>
        <Tel>98765</Tel>
    </Eintrag>
</Telefonliste>
</code>```

I would expect, that I get 9 nodes back. (Telefonliste, Eintrag, name, nachname, Tel, Eintrag, name, nachname, Tel) But I get only two nodes back: Eintrag, Eintrag.

Can someone explain that? I thought my matching template matches "all nodes"?

答: The difference between the identity template and your example template using "for-each" is that the identity template uses <xsl:apply-templates/> to process its children. This finds the best matching template rule to process each child, and in each case this is the identity template again, so processing recurses down the tree structure. But in your example template, you process the children of the selected node and output their names, but you make no attempt to apply templates to the children, so there is no recursion.

ContentLicense: CC BY-SA 3.0

Title: XSLT identity transformation

Body:
I am new to XSLT and got a technical question about the identity transformation.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

This is a often posted example, but I never found something about the detailed program sequence. I often read that it works recursively. But I am not sure about the detailed process.
The template matches the union of all attribute-nodes and all other nodes except the root-node. Then the xsl:copy copies the current contextnode (there is no for-each?!) (which should be the first in the document) and applies the template again with the same choice of nodes. This will be done until all nodes are processed?

I would like to know how the program flow is in that identity-building.

==FOLLOW-UP==

Ok, thanks for your answers. I know the processing model of XSLT roughly. Please have a look onto the following. I define a template, which should result in a set of all nodes (except the root node). Then I want to see whats in that set of nodes. For that purpose, I use a for-each and select the name of the current context node.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="@* | node()">
    <xsl:for-each select="node()">
        <xsl:value-of select="name()" />
    </xsl:for-each>
</xsl:template>

</xsl:transform>

with that input xml:

<Telefonliste>
    <Eintrag>
        <name>Peter</name>
        <nachname>Pan</nachname>
        <Tel>12345</Tel>
    </Eintrag>
    <Eintrag>
        <name>Max</name>
        <nachname>Mustermann</nachname>
        <Tel>98765</Tel>
    </Eintrag>
</Telefonliste>

I would expect, that I get 9 nodes back. (Telefonliste, Eintrag, name, nachname, Tel, Eintrag, name, nachname, Tel) But I get only two nodes back: Eintrag, Eintrag.

Can someone explain that? I thought my matching template matches "all nodes"?


问:
Java - Select all item in the menu
I'm using the javax.swing library, and I try to solve this problem:

I have a MenuBar in which I created JMenu, this menu has JCheckBoxMenuItem items. Like this:

```<code>//creating objects:

jMenuBar = new javax.swing.JMenuBar();
jMenuAlgorithms = new javax.swing.JMenu();
jCheckBoxSPEA = new javax.swing.JCheckBoxMenuItem();
jCheckBoxNSGAII = new javax.swing.JCheckBoxMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jCheckBoxMenuEnableAll = new javax.swing.JCheckBoxMenuItem();
jCheckBoxMenuDisableAll = new javax.swing.JCheckBoxMenuItem();

//settings and putting them together:
jCheckBoxSPEA.setSelected(true);
jCheckBoxSPEA.setText("SPEA");
jMenuAlgorithms.add(jCheckBoxSPEA);

jCheckBoxNSGAII.setSelected(true);
jCheckBoxNSGAII.setText("NSGAII");
jMenuAlgorithms.add(jCheckBoxNSGAII);
jMenuAlgorithms.add(jSeparator1);

jCheckBoxMenuEnableAll.setSelected(true);
jCheckBoxMenuEnableAll.setText("Enable all");
jCheckBoxMenuEnableAll.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jCheckBoxMenuEnableAllMouseClicked(evt);
        }
    });
jMenuAlgorithms.add(jCheckBoxMenuEnableAll);

jCheckBoxMenuDisableAll.setText("Disable all");
jMenuAlgorithms.add(jCheckBoxMenuDisableAll);

jMenuBar.add(jMenuAlgorithms);
</code>```

If the user selects jCheckBoxMenuEnableAll item, I would like to select all the items above the separator. If he selects jCheckBoxMenuDisableAll, I would like to deselect all the items above the separator.

As you can see, I've added mouseClicked action to the jCheckBoxMenuEnableAll item. Now, I would like to do something like this:

```<code>private void jCheckBoxMenuEnableAllMouseClicked(java.awt.event.MouseEvent evt) {

    for(JCheckBoxMenuItem item : jMenuAlgorithms){
        item.setSelected(true);
    }
    //deselect then jCheckBoxMenuDisableAll, it's not essential for instance
}
</code>```

But apparently, I can't do the for loop like this, as the menu item isn't an array or Iterable.

Well, just for testing, I had done something very stupid (code below) - I pass all the items in the menu, and if the item is a check box, I make its copy, set ist value to "true" (selected) and then replace the original item by its copy. Very stupid, I know and I absolutely don't want to do like this, however, I didn't find another way to do it. I just wanted to see if this would work. I supposed it should, but it stoll doesn't work. What am I doing wrong? Thank you very, very much for your time.

```<code>private void jCheckBoxMenuEnableAllMouseClicked(java.awt.event.MouseEvent evt) {

    if(jCheckBoxMenuEnableAll.isSelected()){
        for(int i =0; i< jMenuAlgorithms.getItemCount(); i++){ //for all items in the menu, separators included
           if(jMenuAlgorithms.getItem(i) instanceof JCheckBoxMenuItem){
               JCheckBoxMenuItem item = ((JCheckBoxMenuItem)jMenuAlgorithms.getItem(i));
               item.setSelected(true);
               jMenuAlgorithms.insert(item, i);
           }
        }
    }

}
</code>```

答:
I think JPopupMenu#getSubElements() is what you are looking for.

see also: JMenu#getSubElements()

Returns an array of MenuElements containing the submenu for this menu
  component. If popup menu is null returns an empty array. This method
  is required to conform to the MenuElement interface. Note that since
  JSeparators do not conform to the MenuElement interface, this array
  will only contain JMenuItems.

```<code>import java.awt.*;
import java.util.Arrays;
import java.util.stream.Stream;
import javax.swing.*;

public class MenuSubElementsTest {
  public JComponent makeUI() {
    JMenu jMenuAlgorithms = new JMenu("MenuAlgorithms");

    JMenuItem jCheckBoxMenuEnableAll = new JMenuItem("Enable all");
    jCheckBoxMenuEnableAll.addActionListener(e -> {
      for (MenuElement me: jMenuAlgorithms.getPopupMenu().getSubElements()) {
        System.out.println("debug1: " + me.getClass().getName());
        if (me instanceof JCheckBoxMenuItem) {
          ((JCheckBoxMenuItem) me).setSelected(true);
        }
      }
      //or: getJCheckBoxMenuItem(jMenuAlgorithms).forEach(r -> r.setSelected(true));
    });

    JMenuItem jCheckBoxMenuDisableAll = new JMenuItem("Disable all");
    jCheckBoxMenuDisableAll.addActionListener(e -> {
      getJCheckBoxMenuItem(jMenuAlgorithms).forEach(r -> r.setSelected(false));
    });

    jMenuAlgorithms.add(new JCheckBoxMenuItem("SPEA", true));
    jMenuAlgorithms.add(new JCheckBoxMenuItem("NSGAII", true));
    jMenuAlgorithms.addSeparator();
    jMenuAlgorithms.add(jCheckBoxMenuEnableAll);
    jMenuAlgorithms.add(jCheckBoxMenuDisableAll);

    JMenuBar jMenuBar = new JMenuBar();
    jMenuBar.add(jMenuAlgorithms);

    JPanel p = new JPanel(new BorderLayout());
    p.add(jMenuBar, BorderLayout.NORTH);
    return p;
  }
  private static Stream<JCheckBoxMenuItem> getJCheckBoxMenuItem(MenuElement p) {
    Class<JCheckBoxMenuItem> clz = JCheckBoxMenuItem.class;
    return stream(p).filter(clz::isInstance).map(clz::cast);
  }
//   public static Stream<MenuElement> stream(MenuElement p) {
//     return Arrays.stream(p.getSubElements())
//       .map(MenuSubElementsTest::stream).reduce(Stream.of(p), Stream::concat);
//   }
  public static Stream<MenuElement> stream(MenuElement p) {
    return Stream.concat(Stream.of(p), Arrays.stream(p.getSubElements())
      .peek(me -> System.out.println("debug2: " + me.getClass().getName()))
      .flatMap(MenuSubElementsTest::stream));
  }
  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new MenuSubElementsTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}
</code>```

Title: Java - Select all item in the menu

Body:
I'm using the javax.swing library, and I try to solve this problem:

I have a MenuBar in which I created JMenu, this menu has JCheckBoxMenuItem items. Like this:

//creating objects:

jMenuBar = new javax.swing.JMenuBar();
jMenuAlgorithms = new javax.swing.JMenu();
jCheckBoxSPEA = new javax.swing.JCheckBoxMenuItem();
jCheckBoxNSGAII = new javax.swing.JCheckBoxMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jCheckBoxMenuEnableAll = new javax.swing.JCheckBoxMenuItem();
jCheckBoxMenuDisableAll = new javax.swing.JCheckBoxMenuItem();

//settings and putting them together:
jCheckBoxSPEA.setSelected(true);
jCheckBoxSPEA.setText("SPEA");
jMenuAlgorithms.add(jCheckBoxSPEA);

jCheckBoxNSGAII.setSelected(true);
jCheckBoxNSGAII.setText("NSGAII");
jMenuAlgorithms.add(jCheckBoxNSGAII);
jMenuAlgorithms.add(jSeparator1);

jCheckBoxMenuEnableAll.setSelected(true);
jCheckBoxMenuEnableAll.setText("Enable all");
jCheckBoxMenuEnableAll.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jCheckBoxMenuEnableAllMouseClicked(evt);
        }
    });
jMenuAlgorithms.add(jCheckBoxMenuEnableAll);

jCheckBoxMenuDisableAll.setText("Disable all");
jMenuAlgorithms.add(jCheckBoxMenuDisableAll);

jMenuBar.add(jMenuAlgorithms);

If the user selects jCheckBoxMenuEnableAll item, I would like to select all the items above the separator. If he selects jCheckBoxMenuDisableAll, I would like to deselect all the items above the separator.

As you can see, I've added mouseClicked action to the jCheckBoxMenuEnableAll item. Now, I would like to do something like this:

private void jCheckBoxMenuEnableAllMouseClicked(java.awt.event.MouseEvent evt) {

    for(JCheckBoxMenuItem item : jMenuAlgorithms){
        item.setSelected(true);
    }
    //deselect then jCheckBoxMenuDisableAll, it's not essential for instance
}

But apparently, I can't do the for loop like this, as the menu item isn't an array or Iterable.

Well, just for testing, I had done something very stupid (code below) - I pass all the items in the menu, and if the item is a check box, I make its copy, set ist value to "true" (selected) and then replace the original item by its copy. Very stupid, I know and I absolutely don't want to do like this, however, I didn't find another way to do it. I just wanted to see if this would work. I supposed it should, but it stoll doesn't work. What am I doing wrong? Thank you very, very much for your time.

private void jCheckBoxMenuEnableAllMouseClicked(java.awt.event.MouseEvent evt) {

    if(jCheckBoxMenuEnableAll.isSelected()){
        for(int i =0; i< jMenuAlgorithms.getItemCount(); i++){ //for all items in the menu, separators included
           if(jMenuAlgorithms.getItem(i) instanceof JCheckBoxMenuItem){
               JCheckBoxMenuItem item = ((JCheckBoxMenuItem)jMenuAlgorithms.getItem(i));
               item.setSelected(true);
               jMenuAlgorithms.insert(item, i);
           }
        }
    }

}

Body:
I think JPopupMenu#getSubElements() is what you are looking for.

see also: JMenu#getSubElements()

Returns an array of MenuElements containing the submenu for this menu
  component. If popup menu is null returns an empty array. This method
  is required to conform to the MenuElement interface. Note that since
  JSeparators do not conform to the MenuElement interface, this array
  will only contain JMenuItems.

import java.awt.*;
import java.util.Arrays;
import java.util.stream.Stream;
import javax.swing.*;

public class MenuSubElementsTest {
  public JComponent makeUI() {
    JMenu jMenuAlgorithms = new JMenu("MenuAlgorithms");

    JMenuItem jCheckBoxMenuEnableAll = new JMenuItem("Enable all");
    jCheckBoxMenuEnableAll.addActionListener(e -> {
      for (MenuElement me: jMenuAlgorithms.getPopupMenu().getSubElements()) {
        System.out.println("debug1: " + me.getClass().getName());
        if (me instanceof JCheckBoxMenuItem) {
          ((JCheckBoxMenuItem) me).setSelected(true);
        }
      }
      //or: getJCheckBoxMenuItem(jMenuAlgorithms).forEach(r -> r.setSelected(true));
    });

    JMenuItem jCheckBoxMenuDisableAll = new JMenuItem("Disable all");
    jCheckBoxMenuDisableAll.addActionListener(e -> {
      getJCheckBoxMenuItem(jMenuAlgorithms).forEach(r -> r.setSelected(false));
    });

    jMenuAlgorithms.add(new JCheckBoxMenuItem("SPEA", true));
    jMenuAlgorithms.add(new JCheckBoxMenuItem("NSGAII", true));
    jMenuAlgorithms.addSeparator();
    jMenuAlgorithms.add(jCheckBoxMenuEnableAll);
    jMenuAlgorithms.add(jCheckBoxMenuDisableAll);

    JMenuBar jMenuBar = new JMenuBar();
    jMenuBar.add(jMenuAlgorithms);

    JPanel p = new JPanel(new BorderLayout());
    p.add(jMenuBar, BorderLayout.NORTH);
    return p;
  }
  private static Stream<JCheckBoxMenuItem> getJCheckBoxMenuItem(MenuElement p) {
    Class<JCheckBoxMenuItem> clz = JCheckBoxMenuItem.class;
    return stream(p).filter(clz::isInstance).map(clz::cast);
  }
//   public static Stream<MenuElement> stream(MenuElement p) {
//     return Arrays.stream(p.getSubElements())
//       .map(MenuSubElementsTest::stream).reduce(Stream.of(p), Stream::concat);
//   }
  public static Stream<MenuElement> stream(MenuElement p) {
    return Stream.concat(Stream.of(p), Arrays.stream(p.getSubElements())
      .peek(me -> System.out.println("debug2: " + me.getClass().getName()))
      .flatMap(MenuSubElementsTest::stream));
  }
  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new MenuSubElementsTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}


问:
Setup test data for Jmeter and Junit
Is there any way I can setup my test data for load tests that use Jmeter and Junit? I would like to be able to do something like get a  new user from a csv for each thread of a test. </p>

答:
You can configure a CSV dataset to only be read once, but having only ONE row of data in it.

This will work with JUnit, as the following happens: Junit opens Jmeter script and executes JMeter script.  The Jmeter script, when executed, reads from the CSV file, populates all defined data fields and then runs the requests

ContentLicense: CC BY-SA 2.5

Title: Setup test data for Jmeter and Junit


问:
How to list tuples of variant lengths into tables in Django?
I hope anyone can help me.
I query different tables (with different numbers of columns) in my MySQL db to get a preview of the first 100 rows. I want to display the values in a table.
In views.py I have the following piece of code:

```<code>cursor.execute("SELECT column_name FROM information_schema.columns WHERE
table_name = '%s';" %table)
columns = cursor.fetchall()
columns_list = [i[0] for i in columns]
cursor.execute("SELECT * FROM %s LIMIT 100;" %table)
preview = cursor.fetchall()
</code>```

The code in my html template looks like this:

```<code><table>
    <tr>
        {% if columns_list %}
            {% for column in columns_list %}
                <th>{{column}}</th>
            {% endfor %}
        {% endif %}
    </tr>
    <tr>
        {% if preview %}
            {% for row in preview %}
                <td>{{ row.0 }}</td>
                <td>{{ row.1 }}</td>
                <td>{{ row.2 }}</td>
                <td>{{ row.3 }}</td>
    </tr>
            {% endfor %}
        {% endif %}
</table>
</code>```

But this works only if my table has 4 columns.
Is there an easier way to split the tuples and allocate them than using lots of for loops and arrays?

Thanks for your help!

答:
You can use a nested for loop to dynamically generate your table columns:

```<code>{% if preview %}
    {% for row in preview %}
    <tr>
        {% for col in row %}
        <td>{{ col }}</td>
        {% endfor %}
    </tr>
    {% endfor %}
{% endif %}
</code>```

Body:
I hope anyone can help me.
I query different tables (with different numbers of columns) in my MySQL db to get a preview of the first 100 rows. I want to display the values in a table.
In views.py I have the following piece of code:

cursor.execute("SELECT column_name FROM information_schema.columns WHERE
table_name = '%s';" %table)
columns = cursor.fetchall()
columns_list = [i[0] for i in columns]
cursor.execute("SELECT * FROM %s LIMIT 100;" %table)
preview = cursor.fetchall()

The code in my html template looks like this:

        {% if columns_list %}
            {% for column in columns_list %}
                {{column}}
            {% endfor %}
        {% endif %}

        {% if preview %}
            {% for row in preview %}
                {{ row.0 }}
                {{ row.1 }}
                {{ row.2 }}
                {{ row.3 }}

            {% endfor %}
        {% endif %}

But this works only if my table has 4 columns.
Is there an easier way to split the tuples and allocate them than using lots of for loops and arrays?

Thanks for your help!

Body:
You can use a nested for loop to dynamically generate your table columns:

{% if preview %}
    {% for row in preview %}
    <tr>
        {% for col in row %}
        <td>{{ col }}</td>
        {% endfor %}
    </tr>
    {% endfor %}
{% endif %}


问:
C# string interpolation with variable format
I need to format a variable with string interpolation, and the format string is another variable:

here is my sample code:

```<code>static void Main(string[] args)
{
    int i = 12345;

    Console.WriteLine($"Test 1: {i:N5}");

    var formatString = "N5";

    Console.WriteLine($"Test 2: {i:formatString}");
}
</code>```

Test 1 works, Test 2 don't work.

What's the exact syntax for Test 2 ?

答:
The shortest way you can do this 'syntactically' without String.Format, is using ToString:

```<code>$"Test 2: {i.ToString(formatString)}"
</code>```

Body:
I need to format a variable with string interpolation, and the format string is another variable:

here is my sample code:

static void Main(string[] args)
{
    int i = 12345;

    Console.WriteLine($"Test 1: {i:N5}");

    var formatString = "N5";

    Console.WriteLine($"Test 2: {i:formatString}");
}

Test 1 works, Test 2 don't work.

What's the exact syntax for Test 2 ?

Body:
The shortest way you can do this 'syntactically' without String.Format, is using ToString:

$"Test 2: {i.ToString(formatString)}"


问:
How to modify this python script to print into a file?
I saw this script:

https://gist.github.com/koenbollen/645947

however I wanted the print function to print into a file instead to the console.

How is that possible?

Thank you!

答:
Print in python has more parameters.
This should do it for you.

Http://Www.python-course.eu/python3_print.php

```<code>Outfile = open ('new.txt','w')
print (val, file=Outfile, end='')
</code>```

Body:
Print in python has more parameters.
This should do it for you.

Http://Www.python-course.eu/python3_print.php

Outfile = open ('new.txt','w')
print (val, file=Outfile, end='')


问:
Python using regex to extract parts of a string in pandas column
I've got a pandas df column called 'Raw' for which the format is inconsistent. The strings it contains look like that:

```<code>'(1T XXX, Europe)'
'(2T YYYY, Latin America)'
'(3T ZZ/ZZZZ, Europe)'
'(4T XXX XXX, Africa)'
</code>```

The only thing consistent in the strings in 'Raw' is that they start with a digit, includes a comma in the middle followed by a whitespace, and they contain parentheses as well.

Now, I'd like to create two extra columns (Model and Region) in my dataframe:

'Model' would contain the beginning of the string, i.e. everything between the first parenthesis and the comma

'Region' would contain the end of the string, i.e. everything between the whitespace after the comma and the final parenthesis

How do I do that using regex?

答:
If the comma is a reliable separator of your string parts, then you do not need regexp. If df is your dataframe:

```<code>df['Model'] = [x.split(',')[0].replace('(', '') for x in df['Raw']]
df['Region'] = [x.split(',')[1].replace(')', '') for x in df['Raw']]
</code>```

if you want to use regexp is would look something like:

```<code>s = '(1T XXX, Europe)'
m = re.match('\(([\w\s]+),([\w\s]+)\)', s)
model = m.group(1)
region = m.group(2)
</code>```

Body:
I've got a pandas df column called 'Raw' for which the format is inconsistent. The strings it contains look like that:

'(1T XXX, Europe)'
'(2T YYYY, Latin America)'
'(3T ZZ/ZZZZ, Europe)'
'(4T XXX XXX, Africa)'

The only thing consistent in the strings in 'Raw' is that they start with a digit, includes a comma in the middle followed by a whitespace, and they contain parentheses as well.

Now, I'd like to create two extra columns (Model and Region) in my dataframe:

'Model' would contain the beginning of the string, i.e. everything between the first parenthesis and the comma

'Region' would contain the end of the string, i.e. everything between the whitespace after the comma and the final parenthesis

How do I do that using regex?

Body:
If the comma is a reliable separator of your string parts, then you do not need regexp. If df is your dataframe:

df['Model'] = [x.split(',')[0].replace('(', '') for x in df['Raw']]
df['Region'] = [x.split(',')[1].replace(')', '') for x in df['Raw']]

if you want to use regexp is would look something like:

s = '(1T XXX, Europe)'
m = re.match('\(([\w\s]+),([\w\s]+)\)', s)
model = m.group(1)
region = m.group(2)


问:
Javascript -- filter set of links and style
Here is my set of links:

```<code><ul id="power">
    <li><a id="10watt" name="power" href="#">10 watt</a></li>
    <li><a id="25watt" name="power" href="#">25 watt</a>
    <li><a id="30watt" name="power" href="#">30 watt</a>
    <li><a id="40watt" name="power" href="#">40 watt</a>
    <li><a id="50watt" name="power" href="#">50 watt</a>
    <li><a id="60watt" name="power" href="#">60 watt</a>
    <li><a id="75watt" name="power" href="#">75 watt</a>
    <li><a id="100watt" name="power" href="#">100 watt</a>
    <li><a id="120watt" name="power" href="#">120 watt</a>
    <li><a id="150watt" name="power" href="#">150 watt</a>
</ul>
</code>```

and then I have an array:

```<code>var nine = ['25watt','30watt','40watt','50watt','60watt','75watt'];
</code>```

I want to filter the links so the ones not in the array are styled with the "unavailable" class defined in my CSS.  Here is my jQuery.

```<code>if (this.id == '93') {
           $('a [name="power"]').filter(function() {
               if ($.inArray($(this).attr('id'), nine) < 0)
               $(this).addClass('unavailable');
               $(this).removeAttr('href');
           });
      }
</code>```

this.id comes from the previous set of links,  How do I write my filter statement, because what I have isn't working.  Thanks for your help.

答:
This should work:

```<code>$('a[name="power"]').filter(function() {
    return $.inArray($(this).attr('id'), nine) == -1;
}).addClass('unavailable').removeAttr('href');
</code>```

Your selector had a space between a and [name="power"], which means that you were selecting all [name="power"] that are descendants of a, not a itself. Besides that, i corrected the filter function to do the filtering only.

Body:
Here is my set of links:

10 watt

25 watt

30 watt

40 watt

50 watt

60 watt

75 watt

100 watt

120 watt

150 watt

and then I have an array:

var nine = ['25watt','30watt','40watt','50watt','60watt','75watt'];

I want to filter the links so the ones not in the array are styled with the "unavailable" class defined in my CSS.  Here is my jQuery.

if (this.id == '93') {
           $('a [name="power"]').filter(function() {
               if ($.inArray($(this).attr('id'), nine) < 0)
               $(this).addClass('unavailable');
               $(this).removeAttr('href');
           });
      }

this.id comes from the previous set of links,  How do I write my filter statement, because what I have isn't working.  Thanks for your help.

Body:
This should work:

$('a[name="power"]').filter(function() {
    return $.inArray($(this).attr('id'), nine) == -1;
}).addClass('unavailable').removeAttr('href');

Your selector had a space between a and [name="power"], which means that you were selecting all [name="power"] that are descendants of a, not a itself. Besides that, i corrected the filter function to do the filtering only.


问:
Unreachable statement in custom ArrayAdapter
There is a bug in my custom ArrayAdapter. Android Studio keeps underlining View listItemView = convertView;, and showing unreachable statement.

```<code>package com.example.android.miwok;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class WordAdapter extends ArrayAdapter<Word> {

    public WordAdapter(Activity context, ArrayList<Word> words) {
        // Here, we initialize the ArrayAdapter's internal storage for the context and the list.
        // the second argument is used when the ArrayAdapter is populating a single TextView.
        // Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
        // going to use this second argument, so it can be any value. Here, we used 0.
        super(context, 0, words);
    }

        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            return super.getView(position, convertView, parent);

            // Check if the existing view is being reused, otherwise inflate the view
            View listItemView = convertView;

            if (listItemView == null) {
                listItemView = LayoutInflater.from(getContext()).inflate(
                        R.layout.list_item, parent, false);
            }

            // Get the {@link AndroidFlavor} object located at this position in the list
            Word currentWord = getItem(position);

            // Find the TextView in the list_item.xml layout with the ID version_name
            TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
            // Get the version name from the current AndroidFlavor object and
            // set this text on the name TextView
            defaultTextView.setText(currentWord.getDefaultTranslation());

            // Find the TextView in the list_item.xml layout with the ID version_number
            TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);
            // Get the version number from the current AndroidFlavor object and
            // set this text on the number TextView
            miwokTextView.setText(currentWord.getMiwokTranslation());

            // Return the whole list item layout (containing 2 TextViews and an ImageView)
            // so that it can be shown in the ListView
            return listItemView;
        }

}
</code>```

It uses a newly created object of my Word class:

```<code>package com.example.android.miwok;

public class Word {

    /** Default translation for the word */
    private String mDefaultTranslation;

    /** Miwok translation for the word */
    private String mMiwokTranslation;

    /**
     * Create a new Word object.
     *
     * @param defaultTranslation is the word in a language that the user is already familiar with
     *                           (such as English)
     * @param miwokTranslation is the word in the Miwok language
     */
    public Word(String defaultTranslation, String miwokTranslation) {
        mDefaultTranslation = defaultTranslation;
        mMiwokTranslation = miwokTranslation;
    }

    /**
     * Get the default translation of the word.
     */
    public String getDefaultTranslation() {
        return mDefaultTranslation;
    }

    /**
     * Get the Miwok translation of the word.
     */
    public String getMiwokTranslation() {
        return mMiwokTranslation;
    }

}
</code>```

And is called from this Activity:

```<code>package com.example.android.miwok;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import java.util.ArrayList;

public class NumbersActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_numbers);

        // Create a list of words
        ArrayList<Word> words = new ArrayList<Word>();
        words.add(new Word("one", "lutti"));
        words.add(new Word("two", "otiiko"));
        words.add(new Word("three", "tolookosu"));
        words.add(new Word("four", "oyyisa"));
        words.add(new Word("five", "massokka"));
        words.add(new Word("six", "temmokka"));
        words.add(new Word("seven", "kenekaku"));
        words.add(new Word("eight", "kawinta"));
        words.add(new Word("nine", "wo’e"));
        words.add(new Word("ten", "na’aacha"));

        // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
        // adapter knows how to create list items for each item in the list.
        WordAdapter adapter = new WordAdapter(this, words);

        // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
        // There should be a {@link ListView} with the view ID called list, which is declared in the
        // activity_numbers.xml layout file.
        ListView listView = (ListView) findViewById(R.id.list);

        // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
        // {@link ListView} will display list items for each {@link Word} in the list.
        listView.setAdapter(adapter);
    }
}
</code>```

答:
This works ...</p>

```<code>public class WordAdapter extends ArrayAdapter<Word>  {

    /**
     * Create a new {@link WordAdapter} object.
     *
     * @param context is the current context (i.e. Activity) that the adapter is being created in.
     * @param words is the list of {@link Word}s to be displayed.
     * @param //colorResourceId is the resource ID for the background color for this list of words
     */
    public WordAdapter(Activity context, ArrayList<Word> words) {
        super(context, 0, words);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Check if an existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

            // Get the {@link AndroidFlavor} object located at this position in the list
            Word currentWord = getItem(position);

            // Find the TextView in the list_item.xml layout with the ID version_name
            TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
            // Get the version name from the current AndroidFlavor object and
            // set this text on the name TextView
            defaultTextView.setText(currentWord.getDefaultTranslation());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There is a bug in my custom ArrayAdapter. Android Studio keeps underlining View listItemView = convertView;, and showing unreachable statement.

package com.example.android.miwok;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class WordAdapter extends ArrayAdapter<Word> {

    public WordAdapter(Activity context, ArrayList<Word> words) {
        // Here, we initialize the ArrayAdapter's internal storage for the context and the list.
        // the second argument is used when the ArrayAdapter is populating a single TextView.
        // Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
        // going to use this second argument, so it can be any value. Here, we used 0.
        super(context, 0, words);
    }

        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            return super.getView(position, convertView, parent);

            // Check if the existing view is being reused, otherwise inflate the view
            View listItemView = convertView;

            if (listItemView == null) {
                listItemView = LayoutInflater.from(getContext()).inflate(
                        R.layout.list_item, parent, false);
            }

            // Get the {@link AndroidFlavor} object located at this position in the list
            Word currentWord = getItem(position);

            // Find the TextView in the list_item.xml layout with the ID version_name
            TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
            // Get the version name from the current AndroidFlavor object and
            // set this text on the name TextView
            defaultTextView.setText(currentWord.getDefaultTranslation());

            // Find the TextView in the list_item.xml layout with the ID version_number
            TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);
            // Get the version number from the current AndroidFlavor object and
            // set this text on the number TextView
            miwokTextView.setText(currentWord.getMiwokTranslation());

            // Return the whole list item layout (containing 2 TextViews and an ImageView)
            // so that it can be shown in the ListView
            return listItemView;
        }

}

It uses a newly created object of my Word class:

package com.example.android.miwok;

public class Word {

    /** Default translation for the word */
    private String mDefaultTranslation;

    /** Miwok translation for the word */
    private String mMiwokTranslation;

    /**
     * Create a new Word object.
     *
     * @param defaultTranslation is the word in a language that the user is already familiar with
     *                           (such as English)
     * @param miwokTranslation is the word in the Miwok language
     */
    public Word(String defaultTranslation, String miwokTranslation) {
        mDefaultTranslation = defaultTranslation;
        mMiwokTranslation = miwokTranslation;
    }

    /**
     * Get the default translation of the word.
     */
    public String getDefaultTranslation() {
        return mDefaultTranslation;
    }

    /**
     * Get the Miwok translation of the word.
     */
    public String getMiwokTranslation() {
        return mMiwokTranslation;
    }

}

And is called from this Activity:

package com.example.android.miwok;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import java.util.ArrayList;

public class NumbersActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_numbers);

        // Create a list of words
        ArrayList<Word> words = new ArrayList<Word>();
        words.add(new Word("one", "lutti"));
        words.add(new Word("two", "otiiko"));
        words.add(new Word("three", "tolookosu"));
        words.add(new Word("four", "oyyisa"));
        words.add(new Word("five", "massokka"));
        words.add(new Word("six", "temmokka"));
        words.add(new Word("seven", "kenekaku"));
        words.add(new Word("eight", "kawinta"));
        words.add(new Word("nine", "wo’e"));
        words.add(new Word("ten", "na’aacha"));

        // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
        // adapter knows how to create list items for each item in the list.
        WordAdapter adapter = new WordAdapter(this, words);

        // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
        // There should be a {@link ListView} with the view ID called list, which is declared in the
        // activity_numbers.xml layout file.
        ListView listView = (ListView) findViewById(R.id.list);

        // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
        // {@link ListView} will display list items for each {@link Word} in the list.
        listView.setAdapter(adapter);
    }
}

Body:
This works ...

public class WordAdapter extends ArrayAdapter<Word>  {

    /**
     * Create a new {@link WordAdapter} object.
     *
     * @param context is the current context (i.e. Activity) that the adapter is being created in.
     * @param words is the list of {@link Word}s to be displayed.
     * @param //colorResourceId is the resource ID for the background color for this list of words
     */
    public WordAdapter(Activity context, ArrayList<Word> words) {
        super(context, 0, words);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Check if an existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

            // Get the {@link AndroidFlavor} object located at this position in the list
            Word currentWord = getItem(position);

            // Find the TextView in the list_item.xml layout with the ID version_name
            TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
            // Get the version name from the current AndroidFlavor object and
            // set this text on the name TextView
            defaultTextView.setText(currentWord.getDefaultTranslation());


问:
Error during installation of Cairo package on Red Hat (RHEL)
I am working on R and I need to install the Cairo package.

```<code>install.packages("Cairo")
</code>```

Specification
R version 2.15.0 (2012-03-30)
OS : Red Hat Enterprise Linux Server release 6.1 (Santiago)

I'm getting following error message:

```<code>xlib-backend.c:34:74: fatal error: X11/Intrinsic.h: No such file or directory
compilation terminated.
make: *** [xlib-backend.o] Error 1
ERROR: compilation failed for package ‘Cairo’
* removing ‘/usr/local/lib64/R/library/Cairo’

The downloaded source packages are in
    ‘/tmp/RtmpqtvjPA/downloaded_packages’
Updating HTML index of packages in '.Library'
Making packages.html  ... done
Warning message:
In install.packages("Cairo") :
  installation of package ‘Cairo’ had non-zero exit status
</code>```

答:
On Alpine-linux I fixed this using the following:</p>

```<code>apk add cairo-dev
</code>```

Body:
I am working on R and I need to install the Cairo package.

install.packages("Cairo")

Specification
R version 2.15.0 (2012-03-30)
OS : Red Hat Enterprise Linux Server release 6.1 (Santiago)

I'm getting following error message:

xlib-backend.c:34:74: fatal error: X11/Intrinsic.h: No such file or directory
compilation terminated.
make: *** [xlib-backend.o] Error 1
ERROR: compilation failed for package ‘Cairo’
* removing ‘/usr/local/lib64/R/library/Cairo’

The downloaded source packages are in
    ‘/tmp/RtmpqtvjPA/downloaded_packages’
Updating HTML index of packages in '.Library'
Making packages.html  ... done
Warning message:
In install.packages("Cairo") :
  installation of package ‘Cairo’ had non-zero exit status

Body:
On Alpine-linux I fixed this using the following:

apk add cairo-dev


问:
How to set useMongoClient (Mongoose 4.11.0)?
This is the code I use to connect to my database:

```<code>private connectDatabase(databaseUri: string): Promise<Mongoose.Connection> {
    return Mongoose.connect(databaseUri).then(() => {
        debug('Connected to MongoDB at %O', databaseUri);
        return Mongoose.connection;
    });
}
</code>```

Today I updated Mongoose to version 4.11.0 and I got this warning when running my tests:

```<code>(node:4138) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using `connect()`
or `createConnection()`
</code>```

I can't find any information on how to "set useMongoClient".

Do you guys know how to?

答:
Connect to MongoDB with Mongoose 4.11.x (tested with both mLab single instance and MongoDB Atlas replica set):

```
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

const options = {
  promiseLibrary: global.Promise,
  useMongoClient: true,
};

function connect() {
  mongoose.connect(URI, options)
    .then(function() {
      const admin = new mongoose.mongo.Admin(mongoose.connection.db);
      admin.buildInfo(function(err, info) {
        if (err) {
          console.err(`Error getting MongoDB info: ${err}`);
        } else {
          console.log(`Connection to MongoDB (version ${info.version}) opened successfully!`);
        }
      });
    })
    .catch((err) => console.error(`Error connecting to MongoDB: ${err}`));
}

module.exports = connect;
```

Create model:

```
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({...});

module.exports = mongoose.model('User', userSchema);
```

Body:
This is the code I use to connect to my database:

private connectDatabase(databaseUri: string): Promise<Mongoose.Connection> {
    return Mongoose.connect(databaseUri).then(() => {
        debug('Connected to MongoDB at %O', databaseUri);
        return Mongoose.connection;
    });
}

Today I updated Mongoose to version 4.11.0 and I got this warning when running my tests:

(node:4138) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using `connect()`
or `createConnection()`

I can't find any information on how to "set useMongoClient".

Do you guys know how to?

Body:
Connect to MongoDB with Mongoose 4.11.x (tested with both mLab single instance and MongoDB Atlas replica set):

const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

const options = {
  promiseLibrary: global.Promise,
  useMongoClient: true,
};

function connect() {
  mongoose.connect(URI, options)
    .then(function() {
      const admin = new mongoose.mongo.Admin(mongoose.connection.db);
      admin.buildInfo(function(err, info) {
        if (err) {
          console.err(`Error getting MongoDB info: ${err}`);
        } else {
          console.log(`Connection to MongoDB (version ${info.version}) opened successfully!`);
        }
      });
    })
    .catch((err) => console.error(`Error connecting to MongoDB: ${err}`));
}

module.exports = connect;

Create model:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({...});

module.exports = mongoose.model('User', userSchema);


问:
Rename List item when there is the same string multiple time
I have List of names like:

```<code>var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};
</code>```

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

```<code>Allan
Michael
Jhon
Smith
George
Jhon2
</code>```

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

答:
I would do this:</p>

```<code>var result = list.Take(1).ToList();

for (var i = 1; i < list.Count; i++)
{
    var name = list[i];
    var count = list.Take(i - 1).Where(n => n == name).Count() + 1;

    result.Add(count < 2 ? name : name + count.ToString());
}
</code>```

Body:
I have List of names like:

var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

Allan
Michael
Jhon
Smith
George
Jhon2

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

Body:
I would do this:

var result = list.Take(1).ToList();

for (var i = 1; i < list.Count; i++)
{
    var name = list[i];
    var count = list.Take(i - 1).Where(n => n == name).Count() + 1;

    result.Add(count < 2 ? name : name + count.ToString());
}


问:
Why do I always get 403 when fetching data with RestTemplate?
I'm trying to fetch data but always getting 403(Forbidden) with RestTemplate.

But when I try org.apache.http.client.HttpClient instead, everything is OK. I'm also able to get data with Postman on my machine.

The code is quite simple but I don't know what's wrong.

```<code>public Object get() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            Object result = restTemplate.getForObject("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", Object.class);
            return result;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return null;
        }
    }
</code>```

EDIT: appending stack trace

```<code>org.springframework.web.client.HttpClientErrorException: 403 Forbidden
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)
    at com.brawlstone.metaservice.service.SyncService.get(SyncService.java:49)
    at com.brawlstone.metaservice.web.SyncController.getCards(SyncController.java:30)
    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 org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115)
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59)
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2500)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2489)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
Try to add a "User-Agent" header to your request.

Change your code to:

```<code>try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

            Object response = restTemplate.exchange("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", HttpMethod.GET,entity,Object.class);

            System.out.println(response);
        } catch (Exception ex) {
           ex.printStackTrace();

        }
</code>```

Body:
I'm trying to fetch data but always getting 403(Forbidden) with RestTemplate.

But when I try org.apache.http.client.HttpClient instead, everything is OK. I'm also able to get data with Postman on my machine.

The code is quite simple but I don't know what's wrong.

public Object get() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            Object result = restTemplate.getForObject("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", Object.class);
            return result;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return null;
        }
    }

EDIT: appending stack trace

org.springframework.web.client.HttpClientErrorException: 403 Forbidden
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)
    at com.brawlstone.metaservice.service.SyncService.get(SyncService.java:49)
    at com.brawlstone.metaservice.web.SyncController.getCards(SyncController.java:30)
    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 org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115)
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59)
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2500)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2489)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Body:
Try to add a "User-Agent" header to your request.

Change your code to:

try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

            Object response = restTemplate.exchange("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", HttpMethod.GET,entity,Object.class);

            System.out.println(response);
        } catch (Exception ex) {
           ex.printStackTrace();

        }


问:
Bash process substitution and syncing
(Possibly related to Do some programs not accept process substitution for input files?)

In some Bash unit test scripts I'm using the following trick to log and display stdout and stderr of a command:

```<code>command > >(tee "${stdoutF}") 2> >(tee "${stderrF}" >&2)
</code>```

This process produces some output to stdout, so the $stdoutF file gets some data. Then I run another command which does not output any data:

```<code>diff -r "$source" "$target" > >(tee "${stdoutF}") 2> >(tee "${stderrF}" >&2)
</code>```

However, it doesn't look like this process always finishes successfully before the test for emptiness is run (using shunit-ng):

```<code>assertNull 'Unexpected output to stdout' "$(<"$stdoutF")"
</code>```

In a 100 run test this failed 25 times.

Should it be sufficient to call sync before testing the file for emptiness:

```<code>sync
assertNull 'Unexpected output to stdout' "$(<"$stdoutF")"
</code>```

... and/or should it work by forcing the sequence of the commands:

```<code>diff -r "$source" "$target" \
> >(tee "${stdoutF}"; assertNull 'Unexpected output to stdout' "$(<"$stdoutF")")
2> >(tee "${stderrF}" >&2)
</code>```

... and/or is it possible to tee it somehow to assertNull directly instead of a file?

Update: sync is not the answer - See Gilles' response below.

Update 2: Discussion taken further to Save stdout, stderr and stdout+stderr synchronously. Thanks for the answers!

答: Insert a sleep 5 or whatnot in place of sync to answer your last question

Title: Bash process substitution and syncing

Body:
(Possibly related to Do some programs not accept process substitution for input files?)

In some Bash unit test scripts I'm using the following trick to log and display stdout and stderr of a command:

command > >(tee "${stdoutF}") 2> >(tee "${stderrF}" >&2)

This process produces some output to stdout, so the $stdoutF file gets some data. Then I run another command which does not output any data:

diff -r "$source" "$target" > >(tee "${stdoutF}") 2> >(tee "${stderrF}" >&2)

However, it doesn't look like this process always finishes successfully before the test for emptiness is run (using shunit-ng):

assertNull 'Unexpected output to stdout' "$(<"$stdoutF")"

In a 100 run test this failed 25 times.

Should it be sufficient to call sync before testing the file for emptiness:

sync
assertNull 'Unexpected output to stdout' "$(<"$stdoutF")"

... and/or should it work by forcing the sequence of the commands:

diff -r "$source" "$target" \
> >(tee "${stdoutF}"; assertNull 'Unexpected output to stdout' "$(<"$stdoutF")")
2> >(tee "${stderrF}" >&2)

... and/or is it possible to tee it somehow to assertNull directly instead of a file?

Update: sync is not the answer - See Gilles' response below.

Update 2: Discussion taken further to Save stdout, stderr and stdout+stderr synchronously. Thanks for the answers!


问:
How to pass object through activities by reference?
this is my first post here so be gentle :p
Here is the thing, I'm facing a really though issue and after several research i did not manage to figure out a clean solution. Let me explain:

I'm actually developing an android app for restaurant management.
In activity A, i'm able to create some articles with different parameters (picture, name, price ..).
I can also create a menu in which i indicate which articles are included. To do so i run Activity B that contains a dynamic list of the available articles (the ones i created) to be chosen. After picking up some of them the customised chosen objects are sent to Activity A through Parcel. And the chosen article list is updated in the menu.
But here is the thing, as far as i know, using Parcels create another instance of the object. As a result, if i modify or delete an article, the article list included in the menu does not change, and obviously i would like the list in the menu to be automatically updated.

Is there a way to simply pass customised objects through activities by reference?
What could be a clean solution to make the article list in the menu dynamic?

Here is some code:

In Activity A, in the menu interface i click + button to add an article, which run Activity B (the extras is the list of articles already included in the menu before, so in the beginning it's empty).

```<code>//Add article
    FloatingActionButton addArticleButton = (FloatingActionButton)parentActivity.findViewById(R.id.addArticleButton);
    addArticleButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showMenuDetails(menuListView,menuAdapter,currentMenu);
            parentActivity.startActivityForResult(new Intent(parentActivity.getApplicationContext(),ChooseArticleActivity.class).putParcelableArrayListExtra("menuArticleList",currentMenu.getArticles()),PICK_ARTICLES);
        }
    });
</code>```

In activity B: I select Articles in a list of available Articles (the ones i created). After picking up i press OK button to put the list of chosen articles in result Intent as Parcelable Extras

```<code>protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.choose_article_layout);
    initializeLists();

    this.resultIntent = new Intent();
}

private void initializeLists(){
    final ListView articleToChoose = (ListView)findViewById(R.id.articleToChoose);
    final ListView articleChosen = (ListView)findViewById(R.id.articleChosen);

    final ArrayList<Article> articleToChooseList = (ArrayList<Article>)MainActivity.model.getArticleList().getArticleList().clone();
    final ArrayList<Parcelable> articleChosenListParcelable = (ArrayList<Parcelable>)this.getIntent().getParcelableArrayListExtra("menuArticleList");
    final ArticleAdapter articleToChooseAdapter = new ArticleAdapter(getApplicationContext(), articleToChooseList);
    articleToChoose.setAdapter(articleToChooseAdapter);

    ArrayList<Article> articleChosenListTemp = new ArrayList<>();
    ArrayList<Article> articleToRemove = new ArrayList<>();
    for(Parcelable a:articleChosenListParcelable){
        articleChosenListTemp.add((Article)a);
        for(Article article:articleToChooseList){
            if(article.getName().equals(((Article) a).getName())){
                articleToRemove.add(article);
            }
        }
    }
    articleToChooseList.removeAll(articleToRemove);
    articleToChooseAdapter.notifyDataSetChanged();

    final ArrayList<Article> articleChosenList = articleChosenListTemp;

    final ArticleAdapter articleChosenAdapter = new ArticleAdapter(getApplicationContext(),articleChosenList);

    articleChosen.setAdapter(articleChosenAdapter);

    articleChosen.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Article articleClicked = articleChosenAdapter.getItem(position);
            articleChosenList.remove(articleClicked);
            articleToChooseList.add(articleClicked);
            articleChosenAdapter.notifyDataSetChanged();
            articleToChooseAdapter.notifyDataSetChanged();
        }
    });

    articleToChoose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Article articleClicked = articleToChooseAdapter.getItem(position);
            if(!articleChosenList.contains(articleClicked)){
                articleChosenList.add(articleClicked);
                articleToChooseList.remove(articleClicked);
                articleToChooseAdapter.notifyDataSetChanged();
                articleChosenAdapter.notifyDataSetChanged();
            }
        }
    });

    Button okButton = (Button)findViewById(R.id.okButton);
    okButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chosenArticleListAttr = articleChosenList;
            resultIntent.putParcelableArrayListExtra("articleList",chosenArticleListAttr);
            setResult(RESULT_OK,resultIntent);
            finish();
        }
    });

    Button cancelButton = (Button)findViewById(R.id.cancelButton);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}
</code>```

In activity A, in onActivityResult i catch the result and update the list, but the added Articles here are not the same instance as the article list in the model

```<code>if(requestCode==PICK_ARTICLES && resultCode==RESULT_OK){
        ArticleAdapter articleAdapter = (ArticleAdapter) gestionMenusLayout.getMenuArticleListView().getAdapter();

        ArrayList<Parcelable> chosenArticleList = (ArrayList<Parcelable>)data.getParcelableArrayListExtra("articleList");
        gestionMenusLayout.getCurrentMenu().getArticles().clear();
        for(Parcelable a:chosenArticleList){
            gestionMenusLayout.getCurrentMenu().addArticle((Article)a);
        }
        articleAdapter.notifyDataSetChanged();
    }
</code>```

答:
For debugging purpose only, I suggest that you use a public static List
 articleList and call it directly from whether activity A or B

A better but take-alittle-more-effort solution is that you  store the list in a database, and every updates, queries, ... come through it.You can use the server's database (where people usually get articles from), or a offline database like Realm here

Body:
this is my first post here so be gentle :p
Here is the thing, I'm facing a really though issue and after several research i did not manage to figure out a clean solution. Let me explain:

I'm actually developing an android app for restaurant management.
In activity A, i'm able to create some articles with different parameters (picture, name, price ..).
I can also create a menu in which i indicate which articles are included. To do so i run Activity B that contains a dynamic list of the available articles (the ones i created) to be chosen. After picking up some of them the customised chosen objects are sent to Activity A through Parcel. And the chosen article list is updated in the menu.
But here is the thing, as far as i know, using Parcels create another instance of the object. As a result, if i modify or delete an article, the article list included in the menu does not change, and obviously i would like the list in the menu to be automatically updated.

Is there a way to simply pass customised objects through activities by reference?
What could be a clean solution to make the article list in the menu dynamic?

Here is some code:

In Activity A, in the menu interface i click + button to add an article, which run Activity B (the extras is the list of articles already included in the menu before, so in the beginning it's empty).

//Add article
    FloatingActionButton addArticleButton = (FloatingActionButton)parentActivity.findViewById(R.id.addArticleButton);
    addArticleButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showMenuDetails(menuListView,menuAdapter,currentMenu);
            parentActivity.startActivityForResult(new Intent(parentActivity.getApplicationContext(),ChooseArticleActivity.class).putParcelableArrayListExtra("menuArticleList",currentMenu.getArticles()),PICK_ARTICLES);
        }
    });

In activity B: I select Articles in a list of available Articles (the ones i created). After picking up i press OK button to put the list of chosen articles in result Intent as Parcelable Extras

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.choose_article_layout);
    initializeLists();

    this.resultIntent = new Intent();
}

private void initializeLists(){
    final ListView articleToChoose = (ListView)findViewById(R.id.articleToChoose);
    final ListView articleChosen = (ListView)findViewById(R.id.articleChosen);

    final ArrayList
 articleToChooseList = (ArrayList
)MainActivity.model.getArticleList().getArticleList().clone();
    final ArrayList<Parcelable> articleChosenListParcelable = (ArrayList<Parcelable>)this.getIntent().getParcelableArrayListExtra("menuArticleList");
    final ArticleAdapter articleToChooseAdapter = new ArticleAdapter(getApplicationContext(), articleToChooseList);
    articleToChoose.setAdapter(articleToChooseAdapter);

    ArrayList
 articleChosenListTemp = new ArrayList<>();
    ArrayList
 articleToRemove = new ArrayList<>();
    for(Parcelable a:articleChosenListParcelable){
        articleChosenListTemp.add((Article)a);
        for(Article article:articleToChooseList){
            if(article.getName().equals(((Article) a).getName())){
                articleToRemove.add(article);
            }
        }
    }
    articleToChooseList.removeAll(articleToRemove);
    articleToChooseAdapter.notifyDataSetChanged();

    final ArrayList
 articleChosenList = articleChosenListTemp;

    final ArticleAdapter articleChosenAdapter = new ArticleAdapter(getApplicationContext(),articleChosenList);

    articleChosen.setAdapter(articleChosenAdapter);

    articleChosen.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Article articleClicked = articleChosenAdapter.getItem(position);
            articleChosenList.remove(articleClicked);
            articleToChooseList.add(articleClicked);
            articleChosenAdapter.notifyDataSetChanged();
            articleToChooseAdapter.notifyDataSetChanged();
        }
    });

    articleToChoose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Article articleClicked = articleToChooseAdapter.getItem(position);
            if(!articleChosenList.contains(articleClicked)){
                articleChosenList.add(articleClicked);
                articleToChooseList.remove(articleClicked);
                articleToChooseAdapter.notifyDataSetChanged();
                articleChosenAdapter.notifyDataSetChanged();
            }
        }
    });

    Button okButton = (Button)findViewById(R.id.okButton);
    okButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chosenArticleListAttr = articleChosenList;
            resultIntent.putParcelableArrayListExtra("articleList",chosenArticleListAttr);
            setResult(RESULT_OK,resultIntent);
            finish();
        }
    });

    Button cancelButton = (Button)findViewById(R.id.cancelButton);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

In activity A, in onActivityResult i catch the result and update the list, but the added Articles here are not the same instance as the article list in the model

if(requestCode==PICK_ARTICLES && resultCode==RESULT_OK){
        ArticleAdapter articleAdapter = (ArticleAdapter) gestionMenusLayout.getMenuArticleListView().getAdapter();

        ArrayList<Parcelable> chosenArticleList = (ArrayList<Parcelable>)data.getParcelableArrayListExtra("articleList");
        gestionMenusLayout.getCurrentMenu().getArticles().clear();
        for(Parcelable a:chosenArticleList){
            gestionMenusLayout.getCurrentMenu().addArticle((Article)a);
        }
        articleAdapter.notifyDataSetChanged();
    }

Body:
For debugging purpose only, I suggest that you use a public static List<Article> articleList and call it directly from whether activity A or B

A better but take-alittle-more-effort solution is that you  store the list in a database, and every updates, queries, ... come through it.You can use the server's database (where people usually get articles from), or a offline database like Realm here


问:
VBA , Using offset
I am having 4 sht, sht1, sht2, sht3 and sht4.

I am copying the columns E and F from sht 1 to sht3. and then i look into  the corresponding values in sht 2, and paste them in sht3.

I then lookinto in my sht3, if the column "G" has "NO"; then i copy the corresponding rows to sht4.

till, this i have completed coding.

I wanted to look into the column E in sht4, and paste the corresponding ID from sht1. Could someone tell, how i could do it ?

EDIT.

In sht3, i have the rows filled only when there is Id in column F.

In few cases, i dont have column F,means there is no ID.

so, i copy them to sht4. Now i have in sht4, column E Filled. I want to look into the relevant Information of those ID in sht1. I want the Information from each and every column in sht1, except E .

I know we can use Offset, but how do I use it in this case,
I have tried the following code

```<code>Sub nlookup()
Dim i As Long
Dim totalrows As Long
Dim rng As Range
Sheets("sht1").Select
totalrows = ActiveSheet.UsedRange.Rows.Count
Sheets("sht4").Select
For i = 5 To totalrows
Set rng = Sheets("sht2").UsedRange.Find(Cells(i, 5).Value)
'If it is found put its value on the destination sheet
If Not rng Is Nothing Then
Cells(i, 6).Value = rng.Value
Cells(i, 1).Value = rng.Offset(0, 0).Value
Cells(i, 2).Value = rng.Offset(0, 14).Value
Cells(i, 3).Value = rng.Offset(0, 1).Value
Cells(i, 4).Value = rng.Offset(0, 2).Value
Cells(i, 12).Value = rng.Offset(0, 8).Value
Cells(i, 13).Value = rng.Offset(0, 9).Value
End If
Next
End Sub
</code>```

Set rng = Sheets("sht2").UsedRange.Find(Cells(i, 5).Value), there is no Need of looking into this line, i beleive.

答:
Why not just use Cells(i, 4).Value = rng.Cells(i, 6).Value ?
Also get rid of the.Select

```<code>Sub nlookup()
dim sht as Worksheet
Dim i As Long
Dim totalrows As Long
Dim rng As Range

totalrows = Sheets("sht1").UsedRange.Rows.Count
Set sht = Worksheets("sht4")

For i = 5 To totalrows
Set rng = Sheets("sht2").UsedRange.Find(sht.Cells(i, 5).Value)
'If it is found put its value on the destination sheet
If Not rng Is Nothing Then
sht.Cells(i, 6).Value = rng.Value
sht.Cells(i, 1).Value = rng.Cells(i, 1).Value
sht.Cells(i, 2).Value = rng.Cells(i, 16).Value
sht.Cells(i, 3).Value = rng.Cells(i, 4).Value
sht.Cells(i, 4).Value = rng.Cells(i, 6).Value
sht.Cells(i, 12).Value = rng.Cells(i, 20).Value
sht.Cells(i, 13).Value = rng.Cells(i, 22).Value
End If
Next
End Sub
</code>```

Title: VBA , Using offset

Body:
I am having 4 sht, sht1, sht2, sht3 and sht4.

I am copying the columns E and F from sht 1 to sht3. and then i look into  the corresponding values in sht 2, and paste them in sht3.

I then lookinto in my sht3, if the column "G" has "NO"; then i copy the corresponding rows to sht4.

till, this i have completed coding.

I wanted to look into the column E in sht4, and paste the corresponding ID from sht1. Could someone tell, how i could do it ?

EDIT.

In sht3, i have the rows filled only when there is Id in column F.

In few cases, i dont have column F,means there is no ID.

so, i copy them to sht4. Now i have in sht4, column E Filled. I want to look into the relevant Information of those ID in sht1. I want the Information from each and every column in sht1, except E .

I know we can use Offset, but how do I use it in this case,
I have tried the following code

Sub nlookup()
Dim i As Long
Dim totalrows As Long
Dim rng As Range
Sheets("sht1").Select
totalrows = ActiveSheet.UsedRange.Rows.Count
Sheets("sht4").Select
For i = 5 To totalrows
Set rng = Sheets("sht2").UsedRange.Find(Cells(i, 5).Value)
'If it is found put its value on the destination sheet
If Not rng Is Nothing Then
Cells(i, 6).Value = rng.Value
Cells(i, 1).Value = rng.Offset(0, 0).Value
Cells(i, 2).Value = rng.Offset(0, 14).Value
Cells(i, 3).Value = rng.Offset(0, 1).Value
Cells(i, 4).Value = rng.Offset(0, 2).Value
Cells(i, 12).Value = rng.Offset(0, 8).Value
Cells(i, 13).Value = rng.Offset(0, 9).Value
End If
Next
End Sub

Set rng = Sheets("sht2").UsedRange.Find(Cells(i, 5).Value), there is no Need of looking into this line, i beleive.

Body:
Why not just use Cells(i, 4).Value = rng.Cells(i, 6).Value ?
Also get rid of the.Select

Sub nlookup()
dim sht as Worksheet
Dim i As Long
Dim totalrows As Long
Dim rng As Range

totalrows = Sheets("sht1").UsedRange.Rows.Count
Set sht = Worksheets("sht4")

For i = 5 To totalrows
Set rng = Sheets("sht2").UsedRange.Find(sht.Cells(i, 5).Value)
'If it is found put its value on the destination sheet
If Not rng Is Nothing Then
sht.Cells(i, 6).Value = rng.Value
sht.Cells(i, 1).Value = rng.Cells(i, 1).Value
sht.Cells(i, 2).Value = rng.Cells(i, 16).Value
sht.Cells(i, 3).Value = rng.Cells(i, 4).Value
sht.Cells(i, 4).Value = rng.Cells(i, 6).Value
sht.Cells(i, 12).Value = rng.Cells(i, 20).Value
sht.Cells(i, 13).Value = rng.Cells(i, 22).Value
End If
Next
End Sub


问:
Email validation not stopping the web page from submitting the form php
```<code><?php
    var_dump($_POST);
    if(isset($_POST['email'])
        && isset($_POST['name'])) {

            if (empty($_POST["name"])) {
                    $nameErr = "Name is required";
            }
            else {
                    $name = $_POST["name"];
                    var_dump($name);
     // check if name only contains letters and whitespace  for first name
                    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                            $nameErr = "Only letters and white space
                                         allowed";
                    }
            }

            if (empty($_POST["email"])) {
                    $emailErr = "Email is required";
            }
            else {
                    $email = $_POST["email"];
                    var_dump($email);
                    // check if e-mail address is well-formed
                    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            $emailErr = "Invalid email format";
                    }
            }

            if($data = $_POST['name'] . "\n" .
                   $_POST['email'] . "\n" .
                   $_POST['phone'] . "\n" .
                   $_POST['county'] . "\n" .
                   $_POST['floor'] . "\n" .
                   $_POST['descr'] . "\n"){

                    echo "Thank you for your inquery!" . "<br/>" .
                            "an estimator will be with you shortly.";

                    mail('myemail@gmail.com', 'Estimation Request',
                         $data);
            }
    }

    else {
            die('no post data to process');
    }

?>
</code>```

The output:

array(5) { ["name"]=> string(12) "Nicholas Cox" ["email"]=> string(6)
  "######" ["phone"]=> string(10) "0000000000" ["county"]=> string(8)
  "Pinellas" ["descr"]=> string(15) "Thesh " }

string(12) "Nicholas Cox" string(6) "######"

Thank you for your inquery!
an estimator will be with you shortly.\n\nInvalid email format\n

Note: if i missed taking out some of my troubleshooting steps like the random echos or die functions please let me know so i can edit to
  help you be able to read it easier

I have not added validation on the other fields. I'm just trying to get the email and name to work before i add to the others.

Right now, when i add random stuff it will still prompt me with my error message but it still allows anything to be put in the text field AND sends the email. I've watched a few tutorials on youtube and i still can't get it right.

答:
While there are other issues, the problem that made you ask here lies within this condition:

```<code>if ($data = $_POST['name'] . "\n" .
           $_POST['email'] . "\n" .
           $_POST['phone'] . "\n" .
           $_POST['county'] . "\n" .
           $_POST['floor'] . "\n" .
           $_POST['descr'] . "\n")
</code>```

I really don't know what your intention behind it is, but let's take it apart:

$_POST contains strings

. concatenates strings

\n is a line break

Hence, the whole thing, simplified, boils down to:

```<code>if ($data = $someLongStringFromMyPostValues)
</code>```

Now, $data = $something is an assignment and an expression. In PHP (and many other languages), such an assignment evaluates (returns) the value that was assigned. In other words, this sets your $data variable to the long string, but regarding the condition, this is pretty much equivalent to:

```<code>if ($someLongStringFromMyPostValues)
</code>```

Due to type juggling in PHP, a string with something (other than 0) in it will be true. Seeing how you add line breaks to the string, this means that, no matter what is in your $_POST values, this will always evaluate to (again, ignoring $data for now):

```<code>if (true)
</code>```

You are, in no way, regarding the $nameErr or $emailErr variables that you set before that. So, whatever your intention, you need to fix this condition and incorporate your error variables into it.

Body:
<?php
    var_dump($_POST);
    if(isset($_POST['email'])
        && isset($_POST['name'])) {

            if (empty($_POST["name"])) {
                    $nameErr = "Name is required";
            }
            else {
                    $name = $_POST["name"];
                    var_dump($name);
     // check if name only contains letters and whitespace  for first name
                    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                            $nameErr = "Only letters and white space
                                         allowed";
                    }
            }

            if (empty($_POST["email"])) {
                    $emailErr = "Email is required";
            }
            else {
                    $email = $_POST["email"];
                    var_dump($email);
                    // check if e-mail address is well-formed
                    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            $emailErr = "Invalid email format";
                    }
            }

            if($data = $_POST['name'] . "\n" .
                   $_POST['email'] . "\n" .
                   $_POST['phone'] . "\n" .
                   $_POST['county'] . "\n" .
                   $_POST['floor'] . "\n" .
                   $_POST['descr'] . "\n"){

                    echo "Thank you for your inquery!" . "
" .
                            "an estimator will be with you shortly.";

                    mail('myemail@gmail.com', 'Estimation Request',
                         $data);
            }
    }

    else {
            die('no post data to process');
    }

?>

The output:

array(5) { ["name"]=> string(12) "Nicholas Cox" ["email"]=> string(6)
  "######" ["phone"]=> string(10) "0000000000" ["county"]=> string(8)
  "Pinellas" ["descr"]=> string(15) "Thesh " }

string(12) "Nicholas Cox" string(6) "######"

Thank you for your inquery!
an estimator will be with you shortly.\n\nInvalid email format\n

Note: if i missed taking out some of my troubleshooting steps like the random echos or die functions please let me know so i can edit to
  help you be able to read it easier

I have not added validation on the other fields. I'm just trying to get the email and name to work before i add to the others.

Right now, when i add random stuff it will still prompt me with my error message but it still allows anything to be put in the text field AND sends the email. I've watched a few tutorials on youtube and i still can't get it right.

Body:
While there are other issues, the problem that made you ask here lies within this condition:

if ($data = $_POST['name'] . "\n" .
           $_POST['email'] . "\n" .
           $_POST['phone'] . "\n" .
           $_POST['county'] . "\n" .
           $_POST['floor'] . "\n" .
           $_POST['descr'] . "\n")

I really don't know what your intention behind it is, but let's take it apart:

$_POST contains strings

. concatenates strings

\n is a line break

Hence, the whole thing, simplified, boils down to:

if ($data = $someLongStringFromMyPostValues)

Now, $data = $something is an assignment and an expression. In PHP (and many other languages), such an assignment evaluates (returns) the value that was assigned. In other words, this sets your $data variable to the long string, but regarding the condition, this is pretty much equivalent to:

if ($someLongStringFromMyPostValues)

Due to type juggling in PHP, a string with something (other than 0) in it will be true. Seeing how you add line breaks to the string, this means that, no matter what is in your $_POST values, this will always evaluate to (again, ignoring $data for now):

if (true)

You are, in no way, regarding the $nameErr or $emailErr variables that you set before that. So, whatever your intention, you need to fix this condition and incorporate your error variables into it.


问:
DATA attribute for image created from src image
I want to add to the photo the attributes "data-full" and "data-thumb" containing the image address. So for example:

```<code><img data-full="images/photo.jpg" data-thumb="images/photo.jpg" src="images/photo.jpg">
</code>```

Unfortunately, my attempts end in a failure.

Please help me.

答:
If you use jquery then you can do it like this:

This is your html

```<code><img id="myPhoto" src="images/photo.jpg">
</code>```

Then in your jquery

```<code>$(#myPhoto).attr('data-full', 'images/photo.jpg');
$(#myPhoto).attr('data-thumb', 'images/photo.jpg');
</code>```

Body:
I want to add to the photo the attributes "data-full" and "data-thumb" containing the image address. So for example:

Unfortunately, my attempts end in a failure.

Please help me.

Body:
If you use jquery then you can do it like this:

This is your html

<img id="myPhoto" src="images/photo.jpg">

Then in your jquery

$(#myPhoto).attr('data-full', 'images/photo.jpg');
$(#myPhoto).attr('data-thumb', 'images/photo.jpg');