问:
Shiny: conditional update of SelectizeInput based on selected levels
I would like to update the selectizeInput using the selected values s_l based on the condition input.c_l_check=='y'

```<code>ShinyUi <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput('s_l', 'D to show:', levels(data$D), selected = levels(data$D)),

      radioButtons("c_l_check", "D to colour:", list("Yes"='y', "No"='n'), selected = 'n'),

      conditionalPanel( condition = "input.c_l_check=='y'",
        selectizeInput( inputId = "c_l", label = "D to color:", multiple  = T, choices = NULL))
      ...

  ))

ShinyServer <- function(input, output, session) {

  # Updating selectize input
  updateSelectizeInput(session, 'c_l', choices = 'input$s_l', server = TRUE)

  ...
}

# Run the application
shinyApp(ui = ShinyUi, server = ShinyServer)
</code>```

However, it is updating using the input$s_l rather than its values.

答:
It should be:
updateSelectizeInput(session, 'c_l', choices = input$s_l, server = TRUE)

that is input$s_l should be without quotes.

EDIT:

Here is a working example:

```<code>data <- data.frame(D = iris$Species)

ShinyUi <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput('s_l', 'D to show:', levels(data$D), selected = levels(data$D)),

      radioButtons("c_l_check", "D to colour:", list("Yes"='y', "No"='n'), selected = 'n'),

      conditionalPanel( condition = "input.c_l_check=='y'",
                        selectizeInput( inputId = "c_l", label = "D to color:", multiple  = T, choices = NULL))

    ),
    mainPanel()
    ))

  ShinyServer <- function(input, output, session) {
    observe({
      # Updating selectize input
      updateSelectizeInput(session, 'c_l', choices = input$s_l, server = TRUE)
    })

  }

  # Run the application
  shinyApp(ui = ShinyUi, server = ShinyServer)
</code>```

Body:
I would like to update the selectizeInput using the selected values s_l based on the condition input.c_l_check=='y'

ShinyUi <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput('s_l', 'D to show:', levels(data$D), selected = levels(data$D)),

      radioButtons("c_l_check", "D to colour:", list("Yes"='y', "No"='n'), selected = 'n'),

      conditionalPanel( condition = "input.c_l_check=='y'",
        selectizeInput( inputId = "c_l", label = "D to color:", multiple  = T, choices = NULL))
      ...

  ))

ShinyServer <- function(input, output, session) {

  # Updating selectize input
  updateSelectizeInput(session, 'c_l', choices = 'input$s_l', server = TRUE)

  ...
}

# Run the application
shinyApp(ui = ShinyUi, server = ShinyServer)

However, it is updating using the input$s_l rather than its values.

Body:
It should be:
updateSelectizeInput(session, 'c_l', choices = input$s_l, server = TRUE)

that is input$s_l should be without quotes.

EDIT:

Here is a working example:

data <- data.frame(D = iris$Species)

ShinyUi <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput('s_l', 'D to show:', levels(data$D), selected = levels(data$D)),

      radioButtons("c_l_check", "D to colour:", list("Yes"='y', "No"='n'), selected = 'n'),

      conditionalPanel( condition = "input.c_l_check=='y'",
                        selectizeInput( inputId = "c_l", label = "D to color:", multiple  = T, choices = NULL))

    ),
    mainPanel()
    ))

  ShinyServer <- function(input, output, session) {
    observe({
      # Updating selectize input
      updateSelectizeInput(session, 'c_l', choices = input$s_l, server = TRUE)
    })

  }

  # Run the application
  shinyApp(ui = ShinyUi, server = ShinyServer)


来源: stackexchange

问:
Creating List in a loop
Is there any way to create a loop which will be creating new List

```<code>static Map<Integer, List> dataMap = new HashMap<>();
public static void dec_hex() {

        // Map<Integer, Integer> dataMap = new HashMap<>();
        // dataMap.put(0, 0);
        List<Integer> ls2 = new ArrayList<Integer>();
        List<Integer> ls3 = new ArrayList<Integer>();
        List<Integer> ls4 = new ArrayList<Integer>();
        List<Integer> ls5 = new ArrayList<Integer>();
        List<Integer> ls6 = new ArrayList<Integer>();
        List<Integer> ls7 = new ArrayList<Integer>();
        List<Integer> ls8 = new ArrayList<Integer>();
        List<Integer> ls9 = new ArrayList<Integer>();
        List<Integer> ls10 = new ArrayList<Integer>();

        System.out.println("Liczby");
        for (int i = 0; i < 201; i++) {
            String hex = Integer.toHexString(i);
            System.out.println("DEC: " + i + " HEX: " + hex);
            //for (int a = 2; a<11 ; a++){
            if (i % 2 == 0) {
                ls2.add(i);
                //myList.add(i);
                dataMap.put(2, ls2);
            }
            if (i % 3 == 0) {
                ls3.add(i);
                //myList.add(i);
                dataMap.put(3, ls3);
            }

            if (i % 4 == 0) {
                ls4.add(i);
                //myList.add(i);
                dataMap.put(4, ls4);
            }
            if (i % 5 == 0) {
                ls5.add(i);
                //myList.add(i);
                dataMap.put(5, ls5);
            }
            if (i % 6 == 0) {
                ls6.add(i);
                //myList.add(i);
                dataMap.put(6, ls6);
            }
            if (i % 7 == 0) {
                ls7.add(i);
                //myList.add(i);
                dataMap.put(7, ls7);
            }
            if (i % 8 == 0) {
                ls8.add(i);
            //  myList.add(i);
                dataMap.put(8, ls8);
            }
            if (i % 9 == 0) {
                ls9.add(i);
                //myList.add(i);
                dataMap.put(9, ls9);
            }
            if (i % 10 == 0) {
                ls10.add(i);
                //myList.add(i);
                dataMap.put(10, ls10);
            }
        }

        //String list = myList.toString();
        //System.out.println(list);
        dataMap.toString();
        System.out.println(dataMap);

    }
</code>```

Is there any way to create a loop to check if number is divisible?
If I'm going to use this

```<code>    for (int a = 2; a<11 ; a++){
 lsa.add(i); // lets say we've got one list
 dataMap.put(a, ls);
}
</code>```

The program won't work correctly cause the numbers will reapeat, cause I'm using the same lsa array.

答:
you can shorten your by checking if the map contains a key, if not create a new list and add your data :</p>

```<code>for (int i = 1; i < 201; i++) {

   for(int j=2;j<11;j++){

      if(i%j==0){

         if(dataMap.containsKey(j){

           dataMap.get(j).add(i);

         }else{

           List<Integer> list = new ArrayList<Integer>();
           list.add(i);
           dataMap.put(j,list);

        }

      }

   }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Creating List in a loop

Body:
Is there any way to create a loop which will be creating new List

static Map<Integer, List> dataMap = new HashMap<>();
public static void dec_hex() {

        // Map<Integer, Integer> dataMap = new HashMap<>();
        // dataMap.put(0, 0);
        List<Integer> ls2 = new ArrayList<Integer>();
        List<Integer> ls3 = new ArrayList<Integer>();
        List<Integer> ls4 = new ArrayList<Integer>();
        List<Integer> ls5 = new ArrayList<Integer>();
        List<Integer> ls6 = new ArrayList<Integer>();
        List<Integer> ls7 = new ArrayList<Integer>();
        List<Integer> ls8 = new ArrayList<Integer>();
        List<Integer> ls9 = new ArrayList<Integer>();
        List<Integer> ls10 = new ArrayList<Integer>();

        System.out.println("Liczby");
        for (int i = 0; i < 201; i++) {
            String hex = Integer.toHexString(i);
            System.out.println("DEC: " + i + " HEX: " + hex);
            //for (int a = 2; a<11 ; a++){
            if (i % 2 == 0) {
                ls2.add(i);
                //myList.add(i);
                dataMap.put(2, ls2);
            }
            if (i % 3 == 0) {
                ls3.add(i);
                //myList.add(i);
                dataMap.put(3, ls3);
            }

            if (i % 4 == 0) {
                ls4.add(i);
                //myList.add(i);
                dataMap.put(4, ls4);
            }
            if (i % 5 == 0) {
                ls5.add(i);
                //myList.add(i);
                dataMap.put(5, ls5);
            }
            if (i % 6 == 0) {
                ls6.add(i);
                //myList.add(i);
                dataMap.put(6, ls6);
            }
            if (i % 7 == 0) {
                ls7.add(i);
                //myList.add(i);
                dataMap.put(7, ls7);
            }
            if (i % 8 == 0) {
                ls8.add(i);
            //  myList.add(i);
                dataMap.put(8, ls8);
            }
            if (i % 9 == 0) {
                ls9.add(i);
                //myList.add(i);
                dataMap.put(9, ls9);
            }
            if (i % 10 == 0) {
                ls10.add(i);
                //myList.add(i);
                dataMap.put(10, ls10);
            }
        }

        //String list = myList.toString();
        //System.out.println(list);
        dataMap.toString();
        System.out.println(dataMap);

    }

Is there any way to create a loop to check if number is divisible?
If I'm going to use this

    for (int a = 2; a<11 ; a++){
 lsa.add(i); // lets say we've got one list
 dataMap.put(a, ls);
}

The program won't work correctly cause the numbers will reapeat, cause I'm using the same lsa array.

Body:
you can shorten your by checking if the map contains a key, if not create a new list and add your data :

for (int i = 1; i < 201; i++) {

   for(int j=2;j<11;j++){

      if(i%j==0){

         if(dataMap.containsKey(j){

           dataMap.get(j).add(i);

         }else{

           List<Integer> list = new ArrayList<Integer>();
           list.add(i);
           dataMap.put(j,list);

        }

      }

   }
}


问:
JPanels are disappearing when scrolling
In my code i transfer the JPanel (Bestellpanel) from frame to frame1. After that, everytime i use the frame1 scrollbar it repaints frame1and my JPanel (Bestellpanel) is gone. That means I need a way to stop my JPanel getting overpainted. I read something about super.paint(); and other methods but I have major problems understanding them.

Here is a code example of my problem:

```<code> import java.awt.Color;
 import javax.swing.JPanel;
 import java.awt.Container;
 import java.awt.Dimension;
 import java.awt.Insets;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JScrollPane;
 import javax.swing.ScrollPaneConstants;

public class weqe {

private static JFrame frame = new JFrame("First Frame");
private static JFrame frame1 = new JFrame("Second Frame");
private static JPanel Bestellpanel = new JPanel();

private static int kunde = 1;

public static void addComponentsToPane(final Container pane) {

    pane.setLayout(null);
    final Insets insets1 = pane.getInsets();
    // Mitn Button

    JButton MitnIcon = new JButton("Mitnehmen");
            MitnIcon.setFocusPainted(false);
            MitnIcon.setVisible(true);

    Dimension size2 = MitnIcon.getPreferredSize();
            MitnIcon.setBounds(1010 + insets1.left, 700 + insets1.top,
                    size2.width + 27, size2.height + 50);

    pane.add(MitnIcon);

    MitnIcon.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e) {

            if (kunde == 1) {

                frame.getContentPane().remove(Bestellpanel);
                Bestellpanel.setLocation(0, 0);
                frame1.getContentPane().add(Bestellpanel);
                Bestellpanel.repaint();
                frame.repaint();

                    }

        }});

    // ScrollPane

    JPanel panel1 = new JPanel();
    panel1.setPreferredSize(new Dimension(2000,800));
    panel1.setVisible(false);

    JScrollPane scrollPane = new JScrollPane (panel1,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
     frame1.add(scrollPane);

    Bestellpanel.setBounds(930 + insets1.left, 50 + insets1.top,size2.width
    + 30, size2.height + 400);

    Bestellpanel.setVisible(true);pane.add(Bestellpanel);
    Bestellpanel.setBackground(Color.green);

        }

   private static void createAndShowGUI() {

        //Create and set up the window.

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane(frame.getContentPane());

        //Size and display the window.
        Insets insets = frame.getInsets();
        Insets insets1 = frame1.getInsets();
        frame.setSize(1200 + insets.left + insets.right,
                      900 + insets.top + insets.bottom);
        frame.setVisible(true);
        frame1.setSize(800 + insets1.left + insets1.right,
                600 + insets1.top + insets1.bottom);
        frame1.setVisible(true);

        frame.add(Bestellpanel);

    }

    public static void main(String[] args) {

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }
    });
    }

    }
</code>```

答:
meinJDialog.setSize(800,800); and panel1.setPreferredSize(new Dimension(2000,800)); most likely are part of your problem, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? (The general consensus says yes and to override getPreferred|Maximum|MinimumSize() methods instead)

Instead of removing/adding the JComponents yourself, try out Card Layout

You don't need to manually change component's visibility, again, check the link in point number 2, for this line: Bestellpanel2.setVisible(true);

Please follow the Java naming conventions: FirstWordUpperCaseClass, firstWordLowerCaseVariable, firstWordLowerCaseMethod() and ALL_WORDS_UPPER_CASE_CONSTANT), so, your code is easier to read and understand for you and for us.

If all the above points don't work, then consider posting a valid Minimal, Complete and Verifiable Example (MCVE) or Short, Self Contained, Correct Example (SSCCE) that demonstrates your issue, has no external dependencies or customizations such as background color / image, etc. It should be indented correctly, as said in the comments above.

Title: JPanels are disappearing when scrolling

Body:
In my code i transfer the JPanel (Bestellpanel) from frame to frame1. After that, everytime i use the frame1 scrollbar it repaints frame1and my JPanel (Bestellpanel) is gone. That means I need a way to stop my JPanel getting overpainted. I read something about super.paint(); and other methods but I have major problems understanding them.

Here is a code example of my problem:

 import java.awt.Color;
 import javax.swing.JPanel;
 import java.awt.Container;
 import java.awt.Dimension;
 import java.awt.Insets;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JScrollPane;
 import javax.swing.ScrollPaneConstants;

public class weqe {

private static JFrame frame = new JFrame("First Frame");
private static JFrame frame1 = new JFrame("Second Frame");
private static JPanel Bestellpanel = new JPanel();

private static int kunde = 1;

public static void addComponentsToPane(final Container pane) {

    pane.setLayout(null);
    final Insets insets1 = pane.getInsets();
    // Mitn Button

    JButton MitnIcon = new JButton("Mitnehmen");
            MitnIcon.setFocusPainted(false);
            MitnIcon.setVisible(true);

    Dimension size2 = MitnIcon.getPreferredSize();
            MitnIcon.setBounds(1010 + insets1.left, 700 + insets1.top,
                    size2.width + 27, size2.height + 50);

    pane.add(MitnIcon);

    MitnIcon.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e) {

            if (kunde == 1) {

                frame.getContentPane().remove(Bestellpanel);
                Bestellpanel.setLocation(0, 0);
                frame1.getContentPane().add(Bestellpanel);
                Bestellpanel.repaint();
                frame.repaint();

                    }

        }});

    // ScrollPane

    JPanel panel1 = new JPanel();
    panel1.setPreferredSize(new Dimension(2000,800));
    panel1.setVisible(false);

    JScrollPane scrollPane = new JScrollPane (panel1,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
     frame1.add(scrollPane);

    Bestellpanel.setBounds(930 + insets1.left, 50 + insets1.top,size2.width
    + 30, size2.height + 400);

    Bestellpanel.setVisible(true);pane.add(Bestellpanel);
    Bestellpanel.setBackground(Color.green);

        }

   private static void createAndShowGUI() {

        //Create and set up the window.

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane(frame.getContentPane());

        //Size and display the window.
        Insets insets = frame.getInsets();
        Insets insets1 = frame1.getInsets();
        frame.setSize(1200 + insets.left + insets.right,
                      900 + insets.top + insets.bottom);
        frame.setVisible(true);
        frame1.setSize(800 + insets1.left + insets1.right,
                600 + insets1.top + insets1.bottom);
        frame1.setVisible(true);

        frame.add(Bestellpanel);

    }

    public static void main(String[] args) {

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }
    });
    }

    }


问:
linking my text file to my java code
I am a beginner at java and doing an exercise where I need to link a text file for my code to read through.

here is the code:

```<code>import javax.swing.*;
import java.util.*;
import java.io.*;

public class Java116 {

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

    String[] namn          = new String[100];
    double[] perMån        = new double[100];
    double[] perMinDag     = new double[100];
    double[] perMinÖvr     = new double[100];
    double[] friaDag       = new double[100];
    double[] friÖvr        = new double[100];

    Scanner fil = new Scanner(new File("mobildata.txt"));
    int n = 0;

    while (fil.hasNext()) {
        namn [n] = fil.next();
        perMån[n]       = fil.nextDouble();
        perMinDag[n]    = fil.nextDouble();
        perMinÖvr[n]    = fil.nextDouble();
        friaDag[n]      = fil.nextDouble();
        friÖvr[n]       = fil.nextDouble();
        n++;
    }

    while (true) {
        String s =JOptionPane.showInputDialog("Hur många minuter ringer du per månad \n" +
        "Under dagrid respettive övrig tid? ");

        if (s == null)
            break;

        Scanner input = new Scanner (s);
        double minDag = input.nextDouble();
        double minÖvr = input.nextDouble();
        double billigast = Double.MAX_VALUE;
        int index = 0;
        for (int i=0; i<n; i++) {
            double antalDag = Math.max(minDag-friaDag[i], 0);
            double antalÖvr = Math.max(minÖvr-friÖvr[i], 0);
            double kostnad  = perMån[i] + antalDag*perMinDag[i] + antalÖvr*perMinÖvr[i];
            if (kostnad < billigast) {
                billigast = kostnad;
                index = i;
            }
        }
        String resultat = String. format("%.2f", billigast);
        JOptionPane.showMessageDialog(null,
                namn[index]+ "är billigast.\n" +"kostnad: " + resultat + "kr / månad" );
    }

}
}
</code>```

the error I get is:

```<code>Exception in thread "main" java.io.FileNotFoundException: mobildata.txt (The
system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at Java116.main(Java116.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code>```

I have added the text file to the java file where all my other files are located when using Intellij

Many thanks in advance !

答:
The application is probably looking in the wrong directory. In IntelliJ IDEA, make sure the Project tool window is open (View -> Tool Windows -> Project). In the Project window, select "Project Files" (see screenshot).

You will then see where your mobildata.txt file is located. Move it (drag-and-drop) to the top-level project folder, which is probably the current working directory when your program runs. Re-run and see if this fixes it.

Title: linking my text file to my java code

Body:
I am a beginner at java and doing an exercise where I need to link a text file for my code to read through.

here is the code:

import javax.swing.*;
import java.util.*;
import java.io.*;

public class Java116 {

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

    String[] namn          = new String[100];
    double[] perMån        = new double[100];
    double[] perMinDag     = new double[100];
    double[] perMinÖvr     = new double[100];
    double[] friaDag       = new double[100];
    double[] friÖvr        = new double[100];

    Scanner fil = new Scanner(new File("mobildata.txt"));
    int n = 0;

    while (fil.hasNext()) {
        namn [n] = fil.next();
        perMån[n]       = fil.nextDouble();
        perMinDag[n]    = fil.nextDouble();
        perMinÖvr[n]    = fil.nextDouble();
        friaDag[n]      = fil.nextDouble();
        friÖvr[n]       = fil.nextDouble();
        n++;
    }

    while (true) {
        String s =JOptionPane.showInputDialog("Hur många minuter ringer du per månad \n" +
        "Under dagrid respettive övrig tid? ");

        if (s == null)
            break;

        Scanner input = new Scanner (s);
        double minDag = input.nextDouble();
        double minÖvr = input.nextDouble();
        double billigast = Double.MAX_VALUE;
        int index = 0;
        for (int i=0; i<n; i++) {
            double antalDag = Math.max(minDag-friaDag[i], 0);
            double antalÖvr = Math.max(minÖvr-friÖvr[i], 0);
            double kostnad  = perMån[i] + antalDag*perMinDag[i] + antalÖvr*perMinÖvr[i];
            if (kostnad < billigast) {
                billigast = kostnad;
                index = i;
            }
        }
        String resultat = String. format("%.2f", billigast);
        JOptionPane.showMessageDialog(null,
                namn[index]+ "är billigast.\n" +"kostnad: " + resultat + "kr / månad" );
    }

}
}

the error I get is:

Exception in thread "main" java.io.FileNotFoundException: mobildata.txt (The
system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at Java116.main(Java116.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

I have added the text file to the java file where all my other files are located when using Intellij

Many thanks in advance !


问:
Mail Reader Sampler connection error
I got an error during execution of Mail Reader sampler. I also tried IMAP but still got the error, any solutions, please ?</p>

```<code> Thread Name: Thread Group 1-1
Sample Start: 2017-06-02 12:20:45 EDT
Load time: 21015
Connect Time: 0
Latency: 0
Size in bytes: 0
Sent bytes:0
Headers size in bytes: 0
Body size in bytes: 0
Sample Count: 1
Error Count: 1
Data type ("text"|"bin"|""):
Response code: 500
Response message: javax.mail.MessagingException: Connect failed;
  nested exception is:
    java.net.ConnectException: Connection timed out: connect
pop3s://enwarali@gmail.com@pop.googlemail.com:995/INBOX[1]

 Response headers:

 SampleResult fields:
ContentType:
DataEncoding: null
</code>```

答:
According to Read Gmail messages on other email clients using POP article:

Incoming Mail (POP) Server pop.gmail.com

Requires SSL: Yes

Port: 995

So try changing your Server Host setting to pop.gmail.com

Also double check the following:

You have enabled POP in Gmail Settings

You can access port 995 of pop.gmail.com server (you can check it using telnet client, i.e. it isn't blocked in your OS firewall, organization, router, etc.

You are not blocked by Gmail for retrieving messages too fast

See Load Testing Your Email Server: How to Send and Receive E-mails with JMeter article for more information on sending and receiving emails using JMeter

Title: Mail Reader Sampler connection error

Body:
I got an error during execution of Mail Reader sampler. I also tried IMAP but still got the error, any solutions, please ?

 Thread Name: Thread Group 1-1
Sample Start: 2017-06-02 12:20:45 EDT
Load time: 21015
Connect Time: 0
Latency: 0
Size in bytes: 0
Sent bytes:0
Headers size in bytes: 0
Body size in bytes: 0
Sample Count: 1
Error Count: 1
Data type ("text"|"bin"|""):
Response code: 500
Response message: javax.mail.MessagingException: Connect failed;
  nested exception is:
    java.net.ConnectException: Connection timed out: connect
pop3s://enwarali@gmail.com@pop.googlemail.com:995/INBOX[1]

 Response headers:

 SampleResult fields:
ContentType:
DataEncoding: null


问:
chai: Cannot read property 'not' of undefined
I am new to chai and mocha and I use the sample code for my first test case. Here is my code.

```<code>var chai = require("chai");
var mocha = require("mocha");
var expect = chai.expect;

describe("Test", function() {
    it("Test", function() {
        expect([1, 2]).to.be.an('array').that.does.not.include(3);
    });
});
</code>```

I run mocha test.js

The result is:

```<code>TypeError: Cannot read property 'not' of undefined
</code>```

What is wrong with me? It seems .does return undefined. I remove .does and it works correctly. What is the correct usage?

The following code works.

```<code>expect([1, 2]).to.be.an('array').that.not.include(3);
</code>```

答:
If I run your code with Chai 4, it works. When I downgrade it to Chai 3 I get the error you get. does was added as a no-op assertion in Chai 4.0.0. You are using a version of Chai that predates 4.0.0.

If you check the releases information, you'll find for version 4.0.0, this:

Add does and but as new no-op assertion. (Related Issues: #700, #339 PRs: #621, #701)

(You can find the same information in the Github release, with the added benefit that the issue numbers are links to the actual issues.)

Body:
I am new to chai and mocha and I use the sample code for my first test case. Here is my code.

var chai = require("chai");
var mocha = require("mocha");
var expect = chai.expect;

describe("Test", function() {
    it("Test", function() {
        expect([1, 2]).to.be.an('array').that.does.not.include(3);
    });
});

I run mocha test.js

The result is:

TypeError: Cannot read property 'not' of undefined

What is wrong with me? It seems .does return undefined. I remove .does and it works correctly. What is the correct usage?

The following code works.

expect([1, 2]).to.be.an('array').that.not.include(3);


问:
Add point when user clicks on Charts - 'LineChartView' (iOS-Charts)
There's a way to implement a method where, when user clicks on chart, I can know the x-y values to insert in my array?

I'm trying to use:

```<code>func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {}
</code>```

but this method shows me the nearest point that I already have.

If I use:

```<code>@IBOutlet var chart: LineChartView!

let tap = UITapGestureRecognizer(target: self, action: #selector(self.longTouch(_:)))
self.chartView.addGestureRecognizer(tap)

func touch(_ sender: UIGestureRecognizer) {
    let touchPoint = sender.location(in: self.chart)
}
</code>```

the 'touchPoint' return the absolute view's x-y and not related to the chart.

Someone can help me? Thanks!

答:
I've resolved adding a gesture recognizer to the view:

```<code>// Gesture Recognizer to add a new value
func addGesture() {
    let gesture = UILongPressGestureRecognizer(target: self, action: #selector(gestureRecognizerShouldBegin(_:)))
    gesture.minimumPressDuration = 0.3
    _chartView?.addGestureRecognizer(gesture)
}
</code>```

in the gesture method I've used the  valueForTouchPoint(point: _) that inerith to the LineChartView.

```<code>func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {

    if gestureRecognizer.state == .began {

        // Recognize the location in the view
        let touchLocation = gestureRecognizer.location(in: self._chartView)
        // The 'x-y' value where user touch the view
        let touchedPoint: CGPoint? = self._chartView?.valueForTouchPoint(point: touchLocation, axis: .right)

        guard let point = touchedPoint else { return false }

        // save the value...

    return true
}
</code>```

And, if I zoom or pan the chart, the method return the correct value x-y values.

Hope this will help someone!

Body:
There's a way to implement a method where, when user clicks on chart, I can know the x-y values to insert in my array?

I'm trying to use:

func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {}

but this method shows me the nearest point that I already have.

If I use:

@IBOutlet var chart: LineChartView!

let tap = UITapGestureRecognizer(target: self, action: #selector(self.longTouch(_:)))
self.chartView.addGestureRecognizer(tap)

func touch(_ sender: UIGestureRecognizer) {
    let touchPoint = sender.location(in: self.chart)
}

the 'touchPoint' return the absolute view's x-y and not related to the chart.

Someone can help me? Thanks!

Body:
I've resolved adding a gesture recognizer to the view:

// Gesture Recognizer to add a new value
func addGesture() {
    let gesture = UILongPressGestureRecognizer(target: self, action: #selector(gestureRecognizerShouldBegin(_:)))
    gesture.minimumPressDuration = 0.3
    _chartView?.addGestureRecognizer(gesture)
}

in the gesture method I've used the  valueForTouchPoint(point: _) that inerith to the LineChartView.

func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {

    if gestureRecognizer.state == .began {

        // Recognize the location in the view
        let touchLocation = gestureRecognizer.location(in: self._chartView)
        // The 'x-y' value where user touch the view
        let touchedPoint: CGPoint? = self._chartView?.valueForTouchPoint(point: touchLocation, axis: .right)

        guard let point = touchedPoint else { return false }

        // save the value...

    return true
}

And, if I zoom or pan the chart, the method return the correct value x-y values.

Hope this will help someone!


问:
Functions with returns 'table' has no begin...end?
If I ever add 'Begin' after 'As' It says incorrect syntax. It works just fine If I'm trying to return one value though.

Instead I should add 'return' after 'as' and open brackets ()

Why is that?

With one value as returns, I can do it fine:

```<code> CREATE FUNCTION MATHEE(@A int,@B int)
 returns int
 as
 begin
    DECLARE @C int

    SET @C = @A + @B

 return @C
 end
</code>```

With table as returns, I cant:

```<code>   CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
BEGIN

RETURN SELECT agent from Agents where agent = @bob and prime > @number
END
</code>```

It says :

Incorrect syntax near 'BEGIN'.

It works fine using brackets and without begin..end though:

```<code>CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
RETURN
(
 SELECT agent from Agents where agent = @bob and prime > @number
)
</code>```

答:
RETURNS TABLE creates an inline table-valued function. It supposed to have a single select wrapped in return as its body:

```<code>CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
returns table
as return (
    select ...
);
</code>```

If you want the begin-end syntax, that is a multi-statement table-valued function, and you will then need to declare the table it returns:

```<code>CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
returns @result table (agent varchar(10) not null)
as
begin
    insert into @result (agent) ... ;
    ...
    return;
end;
</code>```

Body:
If I ever add 'Begin' after 'As' It says incorrect syntax. It works just fine If I'm trying to return one value though.

Instead I should add 'return' after 'as' and open brackets ()

Why is that?

With one value as returns, I can do it fine:

 CREATE FUNCTION MATHEE(@A int,@B int)
 returns int
 as
 begin
    DECLARE @C int

    SET @C = @A + @B

 return @C
 end

With table as returns, I cant:

   CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
BEGIN

RETURN SELECT agent from Agents where agent = @bob and prime > @number
END

It says :

Incorrect syntax near 'BEGIN'.

It works fine using brackets and without begin..end though:

CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
RETURN
(
 SELECT agent from Agents where agent = @bob and prime > @number
)

Body:
RETURNS TABLE creates an inline table-valued function. It supposed to have a single select wrapped in return as its body:

CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
returns table
as return (
    select ...
);

If you want the begin-end syntax, that is a multi-statement table-valued function, and you will then need to declare the table it returns:

CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
returns @result table (agent varchar(10) not null)
as
begin
    insert into @result (agent) ... ;
    ...
    return;
end;


问:
Laravel 5.4 OrderBy through a relationship
I´m triying to order by name through a relationship hasMany. If I order in second foreach, doesn't work, I´m understand that I have to do that on the first foreach but How can I do that?
Maybe I can do that in the Controller but I don´t know how. This is my code:

In the view:

```<code>@foreach($data['tags'] as $tag)
        <tr>

            <td>{!! date('d-m-Y', strtotime($tag->created_at)) !!}</td>

            <td>
                @foreach($tag->langs()->orderBy('name', 'asc')->get() as $tag_lang)
                    @include('panel.partials.list_name', ['value' => $tag_lang, 'route' => 'tags.edit', 'id' => $tag->id, 'name' => $tag_lang->name])
                @endforeach
            </td>
        </tr>
    @endforeach
</code>```

The relationship in Tag:

```<code>public function langs()
{
    return $this->hasMany('App\Models\LangTag');
}
</code>```

The relationship in LangTag:

```<code>public function tag()
{
    return $this->belongsTo('App\Models\Tag');
}
</code>```

The controller:

```<code>public function index()
    {
        $data['tags'] = Tag::paginate(25);
        return view('panel.tags.index', compact('data'));
    }
</code>```

答:
```<code>public function langs()
{
    return $this->hasMany('App\Models\LangTag')->orderBy('name');
}
</code>```

or like this:

```<code>public function index()
{
    $data['tags'] = Tag::all()->langs()->orderBy('name')->paginate(25);
    return view('panel.tags.index', compact('data'));
}
</code>```

Body:
I´m triying to order by name through a relationship hasMany. If I order in second foreach, doesn't work, I´m understand that I have to do that on the first foreach but How can I do that?
Maybe I can do that in the Controller but I don´t know how. This is my code:

In the view:

@foreach($data['tags'] as $tag)

            {!! date('d-m-Y', strtotime($tag->created_at)) !!}

                @foreach($tag->langs()->orderBy('name', 'asc')->get() as $tag_lang)
                    @include('panel.partials.list_name', ['value' => $tag_lang, 'route' => 'tags.edit', 'id' => $tag->id, 'name' => $tag_lang->name])
                @endforeach

    @endforeach

The relationship in Tag:

public function langs()
{
    return $this->hasMany('App\Models\LangTag');
}

The relationship in LangTag:

public function tag()
{
    return $this->belongsTo('App\Models\Tag');
}

The controller:

public function index()
    {
        $data['tags'] = Tag::paginate(25);
        return view('panel.tags.index', compact('data'));
    }

Body:
public function langs()
{
    return $this->hasMany('App\Models\LangTag')->orderBy('name');
}

or like this:

public function index()
{
    $data['tags'] = Tag::all()->langs()->orderBy('name')->paginate(25);
    return view('panel.tags.index', compact('data'));
}


问:
Change seekbar color depending on progress
I have a SeekBar in one of my activites in my app.

That seekbar gives me an importance of the object I create. Importance can be 0,1 or 2.

I'd like to dinamically change the background color of my SeekBar when I'm using it. How can I do that ?

Here are the colors I'd like to use :

Importance 0 : "#ff8080"

Importance 1 :"#ff0000"

Importance 2 :"#4d0000"

Thank you for your help, and tell me if you need more code !

```<code>  BarreImportance.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            if(i==0)
            { //it does not accept my colors..
                BarreImportance.getProgressDrawable().setColorFilter(Color.parseColor("#ff8080"));
            }
            if(i==1)
            {
      //it changes the whole background, not what  I want...          BarreImportance.setBackgroundColor(Color.parseColor("#ff0000"));

        }
</code>```

答: You need to use OnSeekBarChangeListener's onProgressChanged callback and change the color from inside there like this: mySeekBar.getProgressDrawable().setColorFilter(..) and mySeekBar.getThumb().setColorFilter(..)

Body:
I have a SeekBar in one of my activites in my app.

That seekbar gives me an importance of the object I create. Importance can be 0,1 or 2.

I'd like to dinamically change the background color of my SeekBar when I'm using it. How can I do that ?

Here are the colors I'd like to use :

Importance 0 : "#ff8080"

Importance 1 :"#ff0000"

Importance 2 :"#4d0000"

Thank you for your help, and tell me if you need more code !

  BarreImportance.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            if(i==0)
            { //it does not accept my colors..
                BarreImportance.getProgressDrawable().setColorFilter(Color.parseColor("#ff8080"));
            }
            if(i==1)
            {
      //it changes the whole background, not what  I want...          BarreImportance.setBackgroundColor(Color.parseColor("#ff0000"));

        }


问:
UIBezierPath translation transform gives wrong answer
When I attempt to translate a path, to move it to an origin of {0, 0}, the resulting path bounds is in error. (Or, my assumptions are in error).

e.g. the path gives the following bounds info:

```<code>let bezier = UIBezierPath(cgPath: svgPath)
print(bezier.bounds)

// (0.0085, 0.7200, 68.5542, 41.1379)

print(bezier.cgPath.boundingBoxOfPath)

// (0.0085, 0.7200, 68.5542, 41.1379)

print(bezier.cgPath.boundingBox)

// (-1.25, -0.1070, 70.0360, 41.9650)
</code>```

I (attempt to) move the path to the origin:

```<code>let origin = bezier.bounds.origin
bezier.apply(CGAffineTransform(translationX: -origin.x, y: -origin.y))

print(bezier.bounds)

// (0.0, -2.7755, 68.5542, 41.1379)
</code>```

As you can see, the x origin component is correct at 0. But, the y component (-2.7755) has gone all kittywumpus. It should be 0, non?

The same thing happens when I perform the transform on the cgPath property.

Does anyone know what kind of circumstances could cause a UIBezierPath/CGPath to behave like this when translated? After reading the Apple docs, it seems that UIBezierPath/CGPath do not hold a transform state; the points are transformed immediately when the transform is called.

Thanks for any help.

Background:

The path data is from Font-Awesome SVGs, via PocketSVG. All files parse, and most draw OK. But a small subset exhibit the above translation issue. I'd like to know if I'm doing something fundamentally wrong or silly before I go ferreting through the SVG parsing, path-building code looking for defects.

BTW I am not drawing at this stage or otherwise dealing with a context; I am building paths prior to drawing.

[edit]

To check that PocketSVG was giving me properly formed data, I passed the same SVG to SwiftSVG, and got the same path data as PocketSVG, and the same result:

```<code>let svgURL = Bundle.main.url(forResource: "fa-mars-stroke-h", withExtension: "svg")!
var bezier = UIBezierPath.pathWithSVGURL(svgURL)!
print(bezier.bounds)

// (0.0085, 0.7200, 68.5542, 41.1379)

let origin = bezier.bounds.origin
let translation = CGAffineTransform(translationX: -origin.x, y: -origin.y)
bezier.apply(translation)
print(bezier.bounds)

// (0.0, -2.7755, 68.5542, 41.1379)
</code>```

Once again, that y component should be 0, but is not. Very weird.

On a whim, I thought I'd try to apply a transformation again. And, it worked!

```<code>let translation2 = CGAffineTransform(translationX: -bezier.bounds.origin.x, y: -bezier.bounds.origin.y)
bezier.apply(translation2)
print(bezier.bounds)

// (0.0, 0.0, 68.5542491336633, 41.1379438254997)
</code>```

Baffling! Am I overlooking something really basic here?

答: I have tried the same as you and is working for me in Xcode 8.3.2 / iOS 10

Body:
When I attempt to translate a path, to move it to an origin of {0, 0}, the resulting path bounds is in error. (Or, my assumptions are in error).

e.g. the path gives the following bounds info:

let bezier = UIBezierPath(cgPath: svgPath)
print(bezier.bounds)

// (0.0085, 0.7200, 68.5542, 41.1379)

print(bezier.cgPath.boundingBoxOfPath)

// (0.0085, 0.7200, 68.5542, 41.1379)

print(bezier.cgPath.boundingBox)

// (-1.25, -0.1070, 70.0360, 41.9650)

I (attempt to) move the path to the origin:

let origin = bezier.bounds.origin
bezier.apply(CGAffineTransform(translationX: -origin.x, y: -origin.y))

print(bezier.bounds)

// (0.0, -2.7755, 68.5542, 41.1379)

As you can see, the x origin component is correct at 0. But, the y component (-2.7755) has gone all kittywumpus. It should be 0, non?

The same thing happens when I perform the transform on the cgPath property.

Does anyone know what kind of circumstances could cause a UIBezierPath/CGPath to behave like this when translated? After reading the Apple docs, it seems that UIBezierPath/CGPath do not hold a transform state; the points are transformed immediately when the transform is called.

Thanks for any help.

Background:

The path data is from Font-Awesome SVGs, via PocketSVG. All files parse, and most draw OK. But a small subset exhibit the above translation issue. I'd like to know if I'm doing something fundamentally wrong or silly before I go ferreting through the SVG parsing, path-building code looking for defects.

BTW I am not drawing at this stage or otherwise dealing with a context; I am building paths prior to drawing.

[edit]

To check that PocketSVG was giving me properly formed data, I passed the same SVG to SwiftSVG, and got the same path data as PocketSVG, and the same result:

let svgURL = Bundle.main.url(forResource: "fa-mars-stroke-h", withExtension: "svg")!
var bezier = UIBezierPath.pathWithSVGURL(svgURL)!
print(bezier.bounds)

// (0.0085, 0.7200, 68.5542, 41.1379)

let origin = bezier.bounds.origin
let translation = CGAffineTransform(translationX: -origin.x, y: -origin.y)
bezier.apply(translation)
print(bezier.bounds)

// (0.0, -2.7755, 68.5542, 41.1379)

Once again, that y component should be 0, but is not. Very weird.

On a whim, I thought I'd try to apply a transformation again. And, it worked!

let translation2 = CGAffineTransform(translationX: -bezier.bounds.origin.x, y: -bezier.bounds.origin.y)
bezier.apply(translation2)
print(bezier.bounds)

// (0.0, 0.0, 68.5542491336633, 41.1379438254997)

Baffling! Am I overlooking something really basic here?

ContentLicense: CC BY-SA 4.0


问:
where to put time format rules in Rails 3?
I am finding myself repeating typing many strftime which I defined.

Having watch Ryan Bates's railscasts ep 32/33( I think), I created a custom option for the to_s method as in Time.now.to_s, so that I can do Time.now.to_s(:sw), where :sw is my custom method, to retrieve "23 Sep 2010, 5:00PM" for example.

But the problem is, I don't know where to put #sw's definition. Should it be in a file in in the initializer folder? Or should it go in application.rb?

Thanks!

答:
Use "time" instead of "date" in your locales file, since Rails timestamps are datetimes.

in config/locales/en.yml

```<code>en:
  time:
    formats:
      default: "%Y/%m/%d"
      short: "%b %d"
      long: "%B %d, %Y"
</code>```

in app/views/posts/show.html.haml

```<code>  = l post.updated_at
  = l post.created_at, :format => :long
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Use "time" instead of "date" in your locales file, since Rails timestamps are datetimes.

in config/locales/en.yml

en:
  time:
    formats:
      default: "%Y/%m/%d"
      short: "%b %d"
      long: "%B %d, %Y"

in app/views/posts/show.html.haml

  = l post.updated_at
  = l post.created_at, :format => :long


问:
How to do SSRS report on azure platform as a service
We have planned to do SSRS on azure environment but our client not affordable to buy azure virtual machine. Can we do SSRS report on azure platform as a service (PaaS)?</p>

答:
Unfortunately SSRS is not available as PaaS on Azure, it is only available by making an Azure VM (IaaS).

If you intend to embed report viewing within a web application (such as by using Report Viewer) you might be able to get away without using SSRS and using 'local reports' instead, which have a very similar syntax to SSRS reports which are hosted on a server.

Power BI might be an alternative worth considering, but there will be a cost to this also if you want to use the reports within apps or shared between users.


问:
Swift 3- How to get button in UICollectionViewCell work
I am trying to implement an Edit button inside a cell.

Please refer to image:

What I done so far:

MainController:

```<code>class MainController: UICollectionViewController, UICollectionViewDelegateFlowLayout  {
  let imgCellId = "imgCellId"

  override func viewDidLoad() {
    collectionView?.backgroundColor = .white
    collectionView?.register(ImgItemCell.self, forCellWithReuseIdentifier: imgCellId)
  }

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
      cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

      return cell
  }

  func buttonPressed(){
    print("buttonPressed !")
  }

}
</code>```

ImgItemCell:

```<code>import Material

class ImgItemCell: UICollectionViewCell{

   override init(frame: CGRect){
       super.init(frame: frame)

       setupViews()
   }
   ...
   let editButton: RaisedButton = {
       let button = RaisedButton(title: "Edit", titleColor: .black) return button
   }()

  func setupViews(){
     ...
     addSubview(editButton)
     ...
  }

}
</code>```

Result: The button is not clickable. No log is printed when clicking on the button.

In android, I have done this by OnClickListener of button to perform action for each row. How can I do the same in Swift 3?

Solution: (it's working for me)

Hi all thank you for all suggestions, they’re more less the hint for me to come to the solution.

The root cause of my problem is view hierarchy (as @DatForis pointed out)

Explanation: I want a cell contains image and a layout of buttons so that I had view hierarchy as below

```<code>override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
    buttonLayout.addSubView(buttonList)
            buttonList.addSubview(editButton)
            buttonList.addSubview(shareButton)
  }
</code>```

this hierarchy somehow blocked the click event of button.

Therefore, I changed a bit in hierarchy

```<code>  override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
            buttonLayout.addSubview(editButton)
            buttonLayout.addSubview(shareButton)
   }
</code>```

and BAM ! it worked like a charm.

In fact, I need a proper explanation about why the hierarchy impact to children view.

By the way, I think most replies here are workable solution, but I selected @DonMag as final answer, because it’s clean and clear with a cool callback to Controller.

But again, my root problem is from view hierarchy.

答:
I have created the same scenario. The only difference is that I have used UIButton instead of RaisedButton. And it is working perfectly fine.

1.ImgItemCell

```<code>class ImgItemCell: UICollectionViewCell
{
    //MARK: View Lifecycle Methods
    override func awakeFromNib()
    {
        super.awakeFromNib()
        setupViews()
    }

    let editButton: UIButton = {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 50))
        button.setTitle("Edit", for: .normal)
        return button
    }()

    func setupViews()
    {
        addSubview(editButton)
    }
}
</code>```

2.MainController methods

```<code>//MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return 10
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
    cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
    return cell
}

@objc func buttonPressed()
{
    print("buttonPressed !")
}
</code>```

Body:
I am trying to implement an Edit button inside a cell.

Please refer to image:

What I done so far:

MainController:

class MainController: UICollectionViewController, UICollectionViewDelegateFlowLayout  {
  let imgCellId = "imgCellId"

  override func viewDidLoad() {
    collectionView?.backgroundColor = .white
    collectionView?.register(ImgItemCell.self, forCellWithReuseIdentifier: imgCellId)
  }

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
      cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

      return cell
  }

  func buttonPressed(){
    print("buttonPressed !")
  }

}

ImgItemCell:

import Material

class ImgItemCell: UICollectionViewCell{

   override init(frame: CGRect){
       super.init(frame: frame)

       setupViews()
   }
   ...
   let editButton: RaisedButton = {
       let button = RaisedButton(title: "Edit", titleColor: .black) return button
   }()

  func setupViews(){
     ...
     addSubview(editButton)
     ...
  }

}

Result: The button is not clickable. No log is printed when clicking on the button.

In android, I have done this by OnClickListener of button to perform action for each row. How can I do the same in Swift 3?

Solution: (it's working for me)

Hi all thank you for all suggestions, they’re more less the hint for me to come to the solution.

The root cause of my problem is view hierarchy (as @DatForis pointed out)

Explanation: I want a cell contains image and a layout of buttons so that I had view hierarchy as below

override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
    buttonLayout.addSubView(buttonList)
            buttonList.addSubview(editButton)
            buttonList.addSubview(shareButton)
  }

this hierarchy somehow blocked the click event of button.

Therefore, I changed a bit in hierarchy

  override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
            buttonLayout.addSubview(editButton)
            buttonLayout.addSubview(shareButton)
   }

and BAM ! it worked like a charm.

In fact, I need a proper explanation about why the hierarchy impact to children view.

By the way, I think most replies here are workable solution, but I selected @DonMag as final answer, because it’s clean and clear with a cool callback to Controller.

But again, my root problem is from view hierarchy.

Body:
I have created the same scenario. The only difference is that I have used UIButton instead of RaisedButton. And it is working perfectly fine.

1.ImgItemCell

class ImgItemCell: UICollectionViewCell
{
    //MARK: View Lifecycle Methods
    override func awakeFromNib()
    {
        super.awakeFromNib()
        setupViews()
    }

    let editButton: UIButton = {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 50))
        button.setTitle("Edit", for: .normal)
        return button
    }()

    func setupViews()
    {
        addSubview(editButton)
    }
}

2.MainController methods

//MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return 10
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
    cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
    return cell
}

@objc func buttonPressed()
{
    print("buttonPressed !")
}


问:
Delete worksheet when unmodified for XXX amount of time
Question:
Is there a way that I can either delete a worksheet that hasn't been modified for 'X' number of days? Or transfer that inactive page from our active workbook into an archive book?

I'm working on a project that takes all the active worksheets (generated from job #) and summarizes the contained data. The worksheet names are all variable and generated based on data filled into a master sheet.

Once a job is completed, that worksheet will probably never need to be accessed again.

I appreciate any insight!

答:
Stick this in your ThisWorkbook object. It will update the tracker sheet (Sheet1 here) on any change done in any sheet on the workbook. Then on start, if the date difference is greater then a week a go, it will (when uncommented) delete the sheet. Change this if you want to do something different

```<code>Option Explicit
Private Sub Workbook_Open()
    Dim rng As Range
    Dim DayDiff As Long
    Dim c

    DayDiff = 7
    ' Update this to the sheet that you want to keep your timestamp list
    With Sheet1
        Set rng = .Range(.Cells(1, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
        Application.DisplayAlerts = False
        For Each c In rng
            If c.Offset(0, 1) < Now() - DayDiff Then
                Debug.Print c
                'ThisWorkbook.Sheets(c.Value2).Delete
                'Range(c, c.Offset(0, 1)).Delete
            End If
        Next c
        Application.DisplayAlerts = True
    End With
End Sub
Private Sub Workbook_SheetChange(ByVal sh As Object, ByVal Target As Range)
    Dim rng As Range
    Dim c
    ' Update this to the sheet that you want to keep your timestamp list
    With Sheet1
        If Not sh.Name = .Name Then
            Set rng = .Range(.Cells(1, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
            Set c = rng.Find(sh.Name)
            If Not c Is Nothing Then
                c.Offset(0, 1) = Now()
            Else
                With .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row + 1, 1)
                    .Value2 = sh.Name
                    .Offset(0, 1) = Now()
                End With
            End If
        End If
    End With
End Sub
</code>```

Body:
Stick this in your ThisWorkbook object. It will update the tracker sheet (Sheet1 here) on any change done in any sheet on the workbook. Then on start, if the date difference is greater then a week a go, it will (when uncommented) delete the sheet. Change this if you want to do something different

Option Explicit
Private Sub Workbook_Open()
    Dim rng As Range
    Dim DayDiff As Long
    Dim c

    DayDiff = 7
    ' Update this to the sheet that you want to keep your timestamp list
    With Sheet1
        Set rng = .Range(.Cells(1, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
        Application.DisplayAlerts = False
        For Each c In rng
            If c.Offset(0, 1) < Now() - DayDiff Then
                Debug.Print c
                'ThisWorkbook.Sheets(c.Value2).Delete
                'Range(c, c.Offset(0, 1)).Delete
            End If
        Next c
        Application.DisplayAlerts = True
    End With
End Sub
Private Sub Workbook_SheetChange(ByVal sh As Object, ByVal Target As Range)
    Dim rng As Range
    Dim c
    ' Update this to the sheet that you want to keep your timestamp list
    With Sheet1
        If Not sh.Name = .Name Then
            Set rng = .Range(.Cells(1, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
            Set c = rng.Find(sh.Name)
            If Not c Is Nothing Then
                c.Offset(0, 1) = Now()
            Else
                With .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row + 1, 1)
                    .Value2 = sh.Name
                    .Offset(0, 1) = Now()
                End With
            End If
        End If
    End With
End Sub


答:
RETURNS TABLE in an Inline User-Defined Function & these do not have function bodies

There is no function_body delimited by BEGIN and END.

For example if you added set @number += 1 before the RETURN this would also fail to parse.

Title: Functions with returns 'table' has no begin...end?


问:
What is the performance impact of number of documents on the index build complexity?
In mongodb; is the increase of documents number in a collection, with five index, impact the build complexity of index and therefore the performance of insert operation?</p>

答: I found the answer; MongoDB uses a B-tree data structure to build the index. On the other hand, binary tree read, insert, or update operations have a complexity of O(log n), where n is the number of elements. So, yes increase in the Number of Documents in a collection, with multiple indexes, impact the performance of insert operation.</p>


问:
Change mouse cursor when over certain components without affecting other cursor-setting code
I'm using an ancient precursor to the DevExpress QuantumGrid (MasterView) in Delphi XE2 and would like certain cells to effectively act as hyperlinks (change the mouse cursor from crDefault to crHandPoint when over them and trigger an action on click).

The configuration of the grid component is such that individual cells are not their own component, and I will need to find the cell from the mouse cursor coordinates and set the cursor from there.

I think I need to set a few events on my grid object to achieve this, but I'm a little uncomfortable about how these events will interact with code that sets the cursor to an hourglass when doing long-running operations (currently handled using IDisposible to set the cursor back to original when finished) and want to double-check whether there's a better way of doing this before I get started and then find a tonne of edge-cases that leave the mouse cursor in the wrong state.

I think I need to override:

omMouseMove - get XY co-ordinates and set the cursor to hand/arrow

onMouseDown - get XY co-ordinates and 'activate' hyperlink if present (possibly revert to arrow? The hyperlink will usually open a new window and the code called may change the cursor to an hourglass)

onMouseLeave - reset cursor to arrow (this event isn't actually exposed, so
think I'll need to handle messages manually)

This kind of functionality comes as default on a TButton, but I couldn't see in the VCL how it's achieved at first glance, and may be a feature of the underlying Windows control.

答:
I've actually found the solution while browsing around SO.

I'd forgotten that components usually have their own Cursor property, which is how they set the correct mouse cursor type when the pointer is over them (i.e. button behaviour)

By overriding MouseMove to change the cursor to crHandPoint if it's over a hyperlink cell and storing the old cursor property to revert to if it's not over a hyperlink seems to work fine (and separate to the screen.cursor which is set in the long-running code). I need to finish off the code to confirm that it works correctly, so I'll leave the question unanswered for now until I can confirm that everything works as I expected.

edit: adding some code. I've decided to use an interceptor class rather than subclassing the grid and having to register the control - I'll only be using it in one or two places in one app and it saves having to set up everyone else's machines.

```<code>TdxMasterView = class(dxMasterView.TdxMasterView)
private
  FDefaultCursor: TCursor;
  procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
  procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
public
  constructor Create(AOwner: TComponent); override;
end;

constructor TdxMasterView.Create(AOwner: TComponent);
begin
  inherited create(AOwner);
  FDefaultCursor := self.Cursor;
end;

procedure TdxMasterView.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  lvHitTestCode: TdxMasterViewHitTestCode;
  lvNode : TdxMasterViewNode;
  lvColumn: TdxMasterViewColumn;
  lvRowIndex, lvColIndex: integer;
begin
  inherited;
  lvHitTestCode   := self.GetHitTestInfo( Point(X,Y),
                                          lvNode,
                                          lvColumn,
                                          lvRowIndex,
                                          lvColIndex );
  if (lvHitTestCode = htContent) and (lvColumn is TMasterViewClickableColumn) then
  begin
    TMasterViewClickableColumn(lvColumn).onClickContentCell(lvNode);
  end;
end;

procedure TdxMasterView.MouseMove(Shift: TShiftState; X, Y: Integer);
var
  lvHitTestCode: TdxMasterViewHitTestCode;
  lvNode : TdxMasterViewNode;
  lvColumn: TdxMasterViewColumn;
  lvRowIndex, lvColIndex: integer;
begin
  inherited;
  lvHitTestCode   := self.GetHitTestInfo( Point(X,Y),
                                          lvNode,
                                          lvColumn,
                                          lvRowIndex,
                                          lvColIndex );
  if (lvHitTestCode = htContent) and (lvColumn is TMasterViewClickableColumn) then
  begin
    self.cursor := TMasterViewClickableColumn(lvColumn).cursorOnMouseOver;
  end
  else
  begin
    self.cursor := self.FDefaultCursor;
  end;
end;
</code>```

Body:
I've actually found the solution while browsing around SO.

I'd forgotten that components usually have their own Cursor property, which is how they set the correct mouse cursor type when the pointer is over them (i.e. button behaviour)

By overriding MouseMove to change the cursor to crHandPoint if it's over a hyperlink cell and storing the old cursor property to revert to if it's not over a hyperlink seems to work fine (and separate to the screen.cursor which is set in the long-running code). I need to finish off the code to confirm that it works correctly, so I'll leave the question unanswered for now until I can confirm that everything works as I expected.

edit: adding some code. I've decided to use an interceptor class rather than subclassing the grid and having to register the control - I'll only be using it in one or two places in one app and it saves having to set up everyone else's machines.

TdxMasterView = class(dxMasterView.TdxMasterView)
private
  FDefaultCursor: TCursor;
  procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
  procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
public
  constructor Create(AOwner: TComponent); override;
end;

constructor TdxMasterView.Create(AOwner: TComponent);
begin
  inherited create(AOwner);
  FDefaultCursor := self.Cursor;
end;

procedure TdxMasterView.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  lvHitTestCode: TdxMasterViewHitTestCode;
  lvNode : TdxMasterViewNode;
  lvColumn: TdxMasterViewColumn;
  lvRowIndex, lvColIndex: integer;
begin
  inherited;
  lvHitTestCode   := self.GetHitTestInfo( Point(X,Y),
                                          lvNode,
                                          lvColumn,
                                          lvRowIndex,
                                          lvColIndex );
  if (lvHitTestCode = htContent) and (lvColumn is TMasterViewClickableColumn) then
  begin
    TMasterViewClickableColumn(lvColumn).onClickContentCell(lvNode);
  end;
end;

procedure TdxMasterView.MouseMove(Shift: TShiftState; X, Y: Integer);
var
  lvHitTestCode: TdxMasterViewHitTestCode;
  lvNode : TdxMasterViewNode;
  lvColumn: TdxMasterViewColumn;
  lvRowIndex, lvColIndex: integer;
begin
  inherited;
  lvHitTestCode   := self.GetHitTestInfo( Point(X,Y),
                                          lvNode,
                                          lvColumn,
                                          lvRowIndex,
                                          lvColIndex );
  if (lvHitTestCode = htContent) and (lvColumn is TMasterViewClickableColumn) then
  begin
    self.cursor := TMasterViewClickableColumn(lvColumn).cursorOnMouseOver;
  end
  else
  begin
    self.cursor := self.FDefaultCursor;
  end;
end;


问:
How to avoid repeated parsing of XML special characters in JAVA
I am trying to escape XML special characters in a String. The escaping is taken care by a static method as shown below.

```<code>public static String escapeXml10(String response) {
    return StringEscapeUtils.escapeXml10(response);
}
</code>```

Now the issue with such an implementation is that, I get a piece of string which may or may not be parsed. which leads to irregular outputs.

for eg:

& -> &amp (This string is not parsed follows a different flow)

& -> & (This string is parsed once by a flow and now by my code).

Now To get a proper response I am planning to introduce a check in the static metod. as follows by using if Condition.

```<code>public static String escapeXml10(String response) {
    if(response.contains("&")  ||
            response.contains("<")   ||
            response.contains(">")   ||
            response.contains("'") ||
            response.contains(""")){
             return response;
         }else{
             return StringEscapeUtils.escapeXml10(response);
         }
}
</code>```

is this a correct way of implementing, if not please suggest?

答:
1st: What you are doing is escapping, not parsing.

2nd: @JBNizet is right: You have a design issue here. You must know what kind of data you should receive in your input parameters: Weteher it is a escapped, valid XML or an unescapped XML.

3rd: As a general rule, all user data should be processed by the program in its plain -unformatted- form, and with the most specific datatypes: int for integer numbers, float or double for decimals, String for texts, etc.
Then, a proper format should be done just at serializing that data. For example, before serializing to XML, nodes and attributes must be properly placed to form a specific data structure, and user data must be escapped to avoid occurrences of special characters within. Conversely, at the time of reading an XML (=parsing), an unescapping must be done (but this is already done by the parser).

Conclussion: You shouldn't even care by escapping if you use standard XML parsers (DocumentBuilderFactory, SAXParser, XMLInputFactory) and serializers (TransformerFactory, XMLOutputFactory). Neither should care your client apps.

Body:
I am trying to escape XML special characters in a String. The escaping is taken care by a static method as shown below.

public static String escapeXml10(String response) {
    return StringEscapeUtils.escapeXml10(response);
}

Now the issue with such an implementation is that, I get a piece of string which may or may not be parsed. which leads to irregular outputs.

for eg:

& -> &amp (This string is not parsed follows a different flow)

& -> & (This string is parsed once by a flow and now by my code).

Now To get a proper response I am planning to introduce a check in the static metod. as follows by using if Condition.

public static String escapeXml10(String response) {
    if(response.contains("&")  ||
            response.contains("<")   ||
            response.contains(">")   ||
            response.contains("'") ||
            response.contains(""")){
             return response;
         }else{
             return StringEscapeUtils.escapeXml10(response);
         }
}

is this a correct way of implementing, if not please suggest?


问:
First build of Node.JS application in TFS 2015 Update2
I'm trying to build my first (Hello world) app in Node.js.
I was reading following tutorial:
https://www.visualstudio.com/en-us/docs/build/apps/node/nodejs-to-azure

My problem is that after clicking Queue Build I have following alert:
"No agent could be found with the following capabilities: npm, node.js".

And actually... this is true.
Where I can found a specific version to be installed on my TFS server?

Thank you for any help.

答:
It was so easy :-).
I installed Node.Js from official site, and then I restarted VSO Agent in services.msc</p>


问:
WPF DataGrid row template
I'm very novice to WPF, and I faced a problem:

I need to set row template in DataGrid. It should looks like on following image.

Maybe someone knows how to do it?

Thank you in advance!

答:
To customize a DataGrid use DataGridTemplate column. In the example below the, CustomizedUIElement is some other control that has the layout you desire.

```<code><DataGridTemplateColumn Header="ColumnHeader">
     <DataGridTemplateColumn.CellTemplate>
           <DataTemplate>
                 <local:CustomizedUIElement Text="{Binding Path=PropertyToBindTo}"/>
           </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</code>```

Create a UserControl with the layout you want then inject it into the datagrid as shown above.

Title: WPF DataGrid row template

Body:
To customize a DataGrid use DataGridTemplate column. In the example below the, CustomizedUIElement is some other control that has the layout you desire.

<DataGridTemplateColumn Header="ColumnHeader">
     <DataGridTemplateColumn.CellTemplate>
           <DataTemplate>
                 <local:CustomizedUIElement Text="{Binding Path=PropertyToBindTo}"/>
           </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Create a UserControl with the layout you want then inject it into the datagrid as shown above.


问:
React + TypeScript usage of className prop
What is the correct way to type and use the className prop in a custom component? I used to be able to do this:

```<code>class MyComponent extends React.Component<MyProps, {}> {
  ...
}
</code>```

and then use my component via:

```<code><MyComponent className="my-class" />
</code>```

Note that I would not define className in MyProps, though React was previously typed to support this usage.

Now, I am now seeing this type error:

```<code>Property 'className' does not exist on type 'IntrinsicAttributes &
IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{
childr...'
</code>```

What is the correct way to define / type my component that will allow me to use className when using my component?

答:
You can use the HTMLAttributes type, for example:

```<code>class MyComponent extends React.Component<MyProps & React.HTMLAttributes<HTMLDivElement>, {}> {
    render() {
        return <div className={ this.props.className }>My Div</div>
    }
}
</code>```

That way you can pass any of the properties that a html element might need.

If you only need the className property then you can do this:

```<code>class MyComponent extends React.Component<MyProps & { className: string }, {}> {
    render() {
        return <div className={ this.props.className }>My Div</div>
    }
}
</code>```

Or simply add it to your MyProps type.

Body:
What is the correct way to type and use the className prop in a custom component? I used to be able to do this:

class MyComponent extends React.Component<MyProps, {}> {
  ...
}

and then use my component via:

<MyComponent className="my-class" />

Note that I would not define className in MyProps, though React was previously typed to support this usage.

Now, I am now seeing this type error:

Property 'className' does not exist on type 'IntrinsicAttributes &
IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{
childr...'

What is the correct way to define / type my component that will allow me to use className when using my component?

Body:
You can use the HTMLAttributes type, for example:

class MyComponent extends React.Component<MyProps & React.HTMLAttributes<HTMLDivElement>, {}> {
    render() {
        return <div className={ this.props.className }>My Div</div>
    }
}

That way you can pass any of the properties that a html element might need.

If you only need the className property then you can do this:

class MyComponent extends React.Component<MyProps & { className: string }, {}> {
    render() {
        return <div className={ this.props.className }>My Div</div>
    }
}

Or simply add it to your MyProps type.


问:
Skip/Add a View Controller in Navigation Stack
I have three View Controllers embedded in Navigation Controller. I want to go from VC1 to VC3 so that in VC3 the Navigation Item's back button would direct the user to VC2 instead of VC1. I think this should be done either by adding the VC2 to the Navigation Stack between VC1 and VC3 when VC3 is created or by skipping the second View Controller.

I tried this:

```<code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let identifier = segue.identifier {
        switch identifier {
        case "JumpToThirdVCSegue":
            if let secondvc = segue.destinationViewController as? SecondViewController {
                secondvc.performSegueWithIdentifier("ThirdVCSegue", sender: self)
            }
        default: break
        }
    }
}
</code>```

but I couldn't get it working. Perhaps performing a segue isn't possible when the View Controller isn't open yet?

What is the best way to skip a View Controller / add a View Controller in the middle of Navigation Stack? I hope this helps you to understand what I'm trying to do:

答:
You can use method

func setViewControllers(_ viewControllers: [UIViewController],
               animated: Bool)

Here's the documentation (link) that solves the UIViewController skipping problem.
Simply pass all the needed UIViewControllers to it (in navigational order) and the last one will be made as the current active UIViewController (if it already isn't the active one).

Body:
I have three View Controllers embedded in Navigation Controller. I want to go from VC1 to VC3 so that in VC3 the Navigation Item's back button would direct the user to VC2 instead of VC1. I think this should be done either by adding the VC2 to the Navigation Stack between VC1 and VC3 when VC3 is created or by skipping the second View Controller.

I tried this:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let identifier = segue.identifier {
        switch identifier {
        case "JumpToThirdVCSegue":
            if let secondvc = segue.destinationViewController as? SecondViewController {
                secondvc.performSegueWithIdentifier("ThirdVCSegue", sender: self)
            }
        default: break
        }
    }
}

but I couldn't get it working. Perhaps performing a segue isn't possible when the View Controller isn't open yet?

What is the best way to skip a View Controller / add a View Controller in the middle of Navigation Stack? I hope this helps you to understand what I'm trying to do:


问:
UIWebView never displays scroll bar
I have a UIWebView displaying content of multiple pages in length.

The problem is this: a scroll bar never appears while the user is scrolling the content vertically (unlike in Safari, or in other apps using what appears to be UIWebView). I can't see any way to control this programmatically.

Behaviour is the same on iOS 3.1 through 4.2, on both iPhone and iPad, both device and simulator.

Anyone have any ideas?

答:
```<code>[(UIScrollView*)[webview.subviews objectAtIndex:0] setShowsVerticalScrollIndicator:YES];
</code>```

Title: UIWebView never displays scroll bar


问:
POST form data includes GET parameters used to generate the form
This one blew my mind for a while and now I think I know what it is.

I have this basic form that uses POST to submit the values.

```<code><form action="./change" method="post">
    <p class="fieldName">Username (your email address):</p>
    <input type="text" name="thetaname"/>
    <p class="fieldName">Password:</p>
    <input type="password" name="thetaword"/>
    <p class="fieldName">Confirm Password:</p>
    <input type="password" name="confirm"/>
    <input type="hidden" name="authkey" value="djj"/>
    <p class="errorMsg"></p>
    <br><br>
    <input type="submit" value="Submit"/>
</form>
</code>```

and it submits to the same location that originally created the form. The issue seems to be that the form is originally created with a GET parameter on the URL and the form is a POST. When I look at the log, it looks like the GET parameter is included on the post and my Spring app is getting confused.

I'm using GET for the original because I'm emailing the link to the user. I'm using POST on the submit because I want to make sure the passwords and stuff are encrypted.

I'm running NGINX in front of Spring boot and it's returning an empty string from the submit.

The GET is listed as GET only on my method and POST as POST only on my method in my controller.

Ideas?

答: I finally figured out a work-around if not an answer. I simply renamed the second change to change2 and posted to change2. This seems to be working fine.</p>

Body:
This one blew my mind for a while and now I think I know what it is.

I have this basic form that uses POST to submit the values.

<form action="./change" method="post">

Username (your email address):

    <input type="text" name="thetaname"/>

Password:

    <input type="password" name="thetaword"/>

Confirm Password:

    <input type="password" name="confirm"/>
    <input type="hidden" name="authkey" value="djj"/>

    <input type="submit" value="Submit"/>
</form>

and it submits to the same location that originally created the form. The issue seems to be that the form is originally created with a GET parameter on the URL and the form is a POST. When I look at the log, it looks like the GET parameter is included on the post and my Spring app is getting confused.

I'm using GET for the original because I'm emailing the link to the user. I'm using POST on the submit because I want to make sure the passwords and stuff are encrypted.

I'm running NGINX in front of Spring boot and it's returning an empty string from the submit.

The GET is listed as GET only on my method and POST as POST only on my method in my controller.

Ideas?


问:
Find Pattern Matching every column in excel, output as number of time repeating
I have excel file full of alphabets which is "a","b","c" only. There are total 20 columns and 300 rows. I just wanted to find pattern matching in all columns. For example, if i search for 4 rows of pattern matching where there is "aabc","bcdb" and etc the output will be how many times the same pattern repeat from the csv file. If i search for 5 rows of pattern matching where there is "abcaa", "bbaca" and etc  the output will be how many times the same pattern repeat from the csv file. It is not necessary that the matching must be in same rows. If the string pattern occur anywhere else in the file can be considered too. The output may be in the next sheet should be fine.  I have tried in VBA and R using Regex but only counting single cell. Any advice on how to find the pattern matching from the excel file would be greatly appreciated. Thanks in advance.

Excel File:

```<code>    **A         B         C          D**
1     a     |   a     |   a      |   b    |
2     a     |   a     |   a      |   c    |
3     b     |   b     |   b      |   a    |
4     c     |   c     |   c      |   c    |
5     d     |   b     |   d      |   b    |
6     b     |   a     |   b      |   c    |
7     b     |   b     |   b      |   b    |
8     a     |   a     |   a      |   c    |
9     a     |   c     |   a      |   a    |
10    c     |   c     |   c      |   c    |
11    c     |   a     |   c      |   c    |
12    a     |   a     |   a      |   a    |
13    b     |   b     |   a      |   b    |
14    b     |   b     |   b      |   a    |
15    c     |   c     |   c      |   c    |
</code>```

Output Example:
If search for 4 rows

aabc 3

dbba 2

baac 2

so on...

If search for 5 rows

aabcd 2

aacca 3

so on..

答:
In E1 enter:

```<code>=TEXTJOIN("",TRUE,A1:D1)
</code>```

and copy down.  Then copy column E and PasteSpecialValues into column F.
Then apply RemoveDuplicates to column F.
Then in G1 enter:

```<code>=COUNTIF(E:E,F1)
</code>```

and copy down:

Body:
I have excel file full of alphabets which is "a","b","c" only. There are total 20 columns and 300 rows. I just wanted to find pattern matching in all columns. For example, if i search for 4 rows of pattern matching where there is "aabc","bcdb" and etc the output will be how many times the same pattern repeat from the csv file. If i search for 5 rows of pattern matching where there is "abcaa", "bbaca" and etc  the output will be how many times the same pattern repeat from the csv file. It is not necessary that the matching must be in same rows. If the string pattern occur anywhere else in the file can be considered too. The output may be in the next sheet should be fine.  I have tried in VBA and R using Regex but only counting single cell. Any advice on how to find the pattern matching from the excel file would be greatly appreciated. Thanks in advance.

Excel File:

    **A         B         C          D**
1     a     |   a     |   a      |   b    |
2     a     |   a     |   a      |   c    |
3     b     |   b     |   b      |   a    |
4     c     |   c     |   c      |   c    |
5     d     |   b     |   d      |   b    |
6     b     |   a     |   b      |   c    |
7     b     |   b     |   b      |   b    |
8     a     |   a     |   a      |   c    |
9     a     |   c     |   a      |   a    |
10    c     |   c     |   c      |   c    |
11    c     |   a     |   c      |   c    |
12    a     |   a     |   a      |   a    |
13    b     |   b     |   a      |   b    |
14    b     |   b     |   b      |   a    |
15    c     |   c     |   c      |   c    |

Output Example:
If search for 4 rows

aabc 3

dbba 2

baac 2

so on...

If search for 5 rows

aabcd 2

aacca 3

so on..

Body:
In E1 enter:

=TEXTJOIN("",TRUE,A1:D1)

and copy down.  Then copy column E and PasteSpecialValues into column F.
Then apply RemoveDuplicates to column F.
Then in G1 enter:

=COUNTIF(E:E,F1)

and copy down:


问:
why dividing by a constant an xts object in R results in a matrix object (losing the Date column)?
thanks for any help regarding:

why dividing by a constant an xts object in R results in a matrix object (the Date/index column is lost)?
I would expect that the resulting object would be an xts object, like the input xts, with just the column values divided by the constant. Why this happens and how to avoid it?

Example of the problem that I observe.

Code extract:

```<code>TradeProfit <- as.xts(ifelse(is.na(lag(GLD$Signal, 1)) == 0 & GLD$Signal != lag(GLD$Signal, 1), GLD$TotTradCapital, NA ))
TradeProfit <- na.omit(TradeProfit)

TradeProfitPerc <- ifelse(is.na(lag(TradeProfit,1)) == 0, TradeProfit / 100, NA)
TradeProfitPerc <- na.omit(TradeProfitPerc)

> class(TradeProfit)
[1] "xts" "zoo"

> head(TradeProfit)
              Signal
2012-08-15  0.000000
2012-11-02  6.970001
2012-11-06  6.970001
2013-08-09 46.410003
2013-08-14 46.410003
2013-09-27 46.380004

head(TradeProfitPerc)
        Signal
[1,] 0.06970001
[2,] 0.06970001
[3,] 0.46410003
[4,] 0.46410003
[5,] 0.46380004
[6,] 0.46380004

> class(TradeProfitPerc)
[1] "matrix"
>
</code>```

The problem is that TradeProfitPerc looses the Date column/index which I want to retain. Also as TradeProfit is an xts object why the division causes such a strange behavior transforming an xts into a matrix object? How can I keep the xts properties?
Thanks!

答:
Here's a minimal, reproducible example:

```<code>library(quantmod)
getSymbols("GLD")
GLD$GLD.SMA <- SMA(Cl(GLD), 50)
GLD$Signal <- Cl(GLD) > GLD$GLD.SMA

TradeProfit <- as.xts(ifelse(!is.na(lag(GLD$Signal, 1)) &
                             GLD$Signal != lag(GLD$Signal, 1), 100, NA))
TradeProfit <- na.omit(TradeProfit)

TradeProfitPerc <- ifelse(!is.na(lag(TradeProfit,1)), TradeProfit / 100, NA)
TradeProfitPerc <- na.omit(TradeProfitPerc)
</code>```

The problem is that calling is.na on an xts object results in a logical matrix with no row names, and ifelse returns an object with the same shape and attributes as its first argument.  So TradeProfitPerc is a matrix with no row names because that's the structure of the first argument passed to ifelse.

This isn't a problem when calculating TradeProfit because of the & GLD$Signal != lag(GLD$Signal, 1).  The GLD$Signal != lag(GLD$Signal, 1) comparison returns an xts object, and a logical comparison between an xts object and non-xts object yields an xts object.  For example:

```<code>str(FALSE & xts(TRUE, Sys.Date()))
An 'xts' object on 2017-06-05/2017-06-05 containing:
  Data: logi [1, 1] FALSE
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:
 NULL
</code>```

You can avoid this by avoiding ifelse and subsetting directly:

```<code>GLD$TotTradCapital <- 500
# rows where Signal is NA will be FALSE and therefore not included in TradeProfit
TradeProfit <- GLD[GLD$Signal != lag(GLD$Signal, 1), "TotTradCapital"]
TradeProfitPerc <- TradeProfit / 100
</code>```

Body:
thanks for any help regarding:

why dividing by a constant an xts object in R results in a matrix object (the Date/index column is lost)?
I would expect that the resulting object would be an xts object, like the input xts, with just the column values divided by the constant. Why this happens and how to avoid it?

Example of the problem that I observe.

Code extract:

TradeProfit <- as.xts(ifelse(is.na(lag(GLD$Signal, 1)) == 0 & GLD$Signal != lag(GLD$Signal, 1), GLD$TotTradCapital, NA ))
TradeProfit <- na.omit(TradeProfit)

TradeProfitPerc <- ifelse(is.na(lag(TradeProfit,1)) == 0, TradeProfit / 100, NA)
TradeProfitPerc <- na.omit(TradeProfitPerc)

> class(TradeProfit)
[1] "xts" "zoo"

> head(TradeProfit)
              Signal
2012-08-15  0.000000
2012-11-02  6.970001
2012-11-06  6.970001
2013-08-09 46.410003
2013-08-14 46.410003
2013-09-27 46.380004

head(TradeProfitPerc)
        Signal
[1,] 0.06970001
[2,] 0.06970001
[3,] 0.46410003
[4,] 0.46410003
[5,] 0.46380004
[6,] 0.46380004

> class(TradeProfitPerc)
[1] "matrix"
>

The problem is that TradeProfitPerc looses the Date column/index which I want to retain. Also as TradeProfit is an xts object why the division causes such a strange behavior transforming an xts into a matrix object? How can I keep the xts properties?
Thanks!

Body:
Here's a minimal, reproducible example:

library(quantmod)
getSymbols("GLD")
GLD$GLD.SMA <- SMA(Cl(GLD), 50)
GLD$Signal <- Cl(GLD) > GLD$GLD.SMA

TradeProfit <- as.xts(ifelse(!is.na(lag(GLD$Signal, 1)) &
                             GLD$Signal != lag(GLD$Signal, 1), 100, NA))
TradeProfit <- na.omit(TradeProfit)

TradeProfitPerc <- ifelse(!is.na(lag(TradeProfit,1)), TradeProfit / 100, NA)
TradeProfitPerc <- na.omit(TradeProfitPerc)

The problem is that calling is.na on an xts object results in a logical matrix with no row names, and ifelse returns an object with the same shape and attributes as its first argument.  So TradeProfitPerc is a matrix with no row names because that's the structure of the first argument passed to ifelse.

This isn't a problem when calculating TradeProfit because of the & GLD$Signal != lag(GLD$Signal, 1).  The GLD$Signal != lag(GLD$Signal, 1) comparison returns an xts object, and a logical comparison between an xts object and non-xts object yields an xts object.  For example:

str(FALSE & xts(TRUE, Sys.Date()))
An 'xts' object on 2017-06-05/2017-06-05 containing:
  Data: logi [1, 1] FALSE
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:
 NULL

You can avoid this by avoiding ifelse and subsetting directly:

GLD$TotTradCapital <- 500
# rows where Signal is NA will be FALSE and therefore not included in TradeProfit
TradeProfit <- GLD[GLD$Signal != lag(GLD$Signal, 1), "TotTradCapital"]
TradeProfitPerc <- TradeProfit / 100


问:
how to make a function in angularjs executes Synchronously
how i can make storyboard.getAdressTimeLine Synchronously, i want storyboard.drawTimeLine executes untill storyboard.getAdressTimeLine is finished

```<code>for (var i = 0; i < response.data.length; i++) {
var obj=response.data[i];
var date = obj.fixtime.substring(0, 11);
storyboard.getAdressTimeLine(obj.latitude,obj.longitude);
storyboard.drawTimeLine(date + "00:00:00.000+0000", obj.fixtime, "red",0,storyboard.lastAdressTime);
items.push(item);
</code>```

}

答:
Use promises over here this angularjs documentation will help you https://docs.angularjs.org/api/ng/service/$q

If you use promise your function will look like

```<code>storyboard.getAdressTimeLine(obj.latitude,obj.longitude).then(function(){
 storyboard.drawTimeLine(date + "00:00:00.000+0000", obj.fixtime, "red",0,storyboard.lastAdressTime);
})
</code>```

Body:
how i can make storyboard.getAdressTimeLine Synchronously, i want storyboard.drawTimeLine executes untill storyboard.getAdressTimeLine is finished

for (var i = 0; i < response.data.length; i++) {
var obj=response.data[i];
var date = obj.fixtime.substring(0, 11);
storyboard.getAdressTimeLine(obj.latitude,obj.longitude);
storyboard.drawTimeLine(date + "00:00:00.000+0000", obj.fixtime, "red",0,storyboard.lastAdressTime);
items.push(item);

}

Body:
Use promises over here this angularjs documentation will help you https://docs.angularjs.org/api/ng/service/$q

If you use promise your function will look like

storyboard.getAdressTimeLine(obj.latitude,obj.longitude).then(function(){
 storyboard.drawTimeLine(date + "00:00:00.000+0000", obj.fixtime, "red",0,storyboard.lastAdressTime);
})


问:
String array initialization as constructor parameter
In Java, it is completely legal to initialize a String array in the following way:

```<code>String[] s = {"FOO", "BAR"};
</code>```

However, when trying to instantiate a class that takes a String array as a parameter, the following piece of code is NOT allowed:

```<code>Test t = new Test({"test"});
</code>```

But this works again:

```<code>Test t = new Test(new String[] {"test"});
</code>```

Can someone explain why this is?

答:
For you want a simple way to pass a String array, I suggest you use varargs</p>

```<code>class Test {
   public Test(String...args);
}

// same as new Test(new String[] { "test", "one" })
Test t = new Test("test", "one");
</code>```

Body:
In Java, it is completely legal to initialize a String array in the following way:

String[] s = {"FOO", "BAR"};

However, when trying to instantiate a class that takes a String array as a parameter, the following piece of code is NOT allowed:

Test t = new Test({"test"});

But this works again:

Test t = new Test(new String[] {"test"});

Can someone explain why this is?

Body:
For you want a simple way to pass a String array, I suggest you use varargs

class Test {
   public Test(String...args);
}

// same as new Test(new String[] { "test", "one" })
Test t = new Test("test", "one");


问:
Add a Character Between Strings in C++
So basically I'm trying to add a character in the middle of a string. Normally in something like Python, this would be pretty straightforward, but I'm really not sure how to achieve this in C++. What I'm trying to achieve is something like this:

```<code>void converter(){
    converted = ":regional_indicator_" + character + ":";

}
</code>```

So basically, I'm trying to add the variable character of a type char in a string. Should I be storing character as a string instead?

For reference here's all of my code:

```<code>#include <iostream>

using namespace std;

string inputLine;
char character;
string converted;

void input(){
    cout << "Please input the text in which you would like to be converted" << endl;
    cin >> inputLine;
}

void converter(){
    converted = ":regional_indicator_" + character + ":";

}
int main(){
    input();
    for (int i = 0; i < inputLine.length(); i++ ){
        character = tolower(inputLine[i]);
    }
    return 0;
}
</code>```

答:
Append s behind the strings literals to treat them as std::strings instead of const char*s:

```<code>converted = ":regional_indicator_"s + character + ":"s;
</code>```

You would need to do either using namespace std::literals or using namespace std::string_literals for it to work.

On a side note, in C++, it is strange to have a function converter() to modify a global variable using another global variable.  You might want to consider passing character as a parameter to the function instead.

Title: Add a Character Between Strings in C++

Body:
So basically I'm trying to add a character in the middle of a string. Normally in something like Python, this would be pretty straightforward, but I'm really not sure how to achieve this in C++. What I'm trying to achieve is something like this:

void converter(){
    converted = ":regional_indicator_" + character + ":";

}

So basically, I'm trying to add the variable character of a type char in a string. Should I be storing character as a string instead?

For reference here's all of my code:

#include <iostream>

using namespace std;

string inputLine;
char character;
string converted;

void input(){
    cout << "Please input the text in which you would like to be converted" << endl;
    cin >> inputLine;
}

void converter(){
    converted = ":regional_indicator_" + character + ":";

}
int main(){
    input();
    for (int i = 0; i < inputLine.length(); i++ ){
        character = tolower(inputLine[i]);
    }
    return 0;
}

Body:
Append s behind the strings literals to treat them as std::strings instead of const char*s:

converted = ":regional_indicator_"s + character + ":"s;

You would need to do either using namespace std::literals or using namespace std::string_literals for it to work.

On a side note, in C++, it is strange to have a function converter() to modify a global variable using another global variable.  You might want to consider passing character as a parameter to the function instead.


问:
Expecto Test in F# always passes even when forced to fail
I'm trying to get expecto up and running in our test project.

Though it compiles and run fine, I wanted to just make sure it was really working. So I gave it a fail case and it passes.

Did I miss something silly here?

My test setup

```<code>let tests =
    testList "Test Group" [
        test "Testing fail test" {
           let result = false
           Expecto.Expect.isTrue result
        }
    ]

let runTests args =
  runTestsWithArgs defaultConfig args tests
</code>```

Output from the test

```<code>[08:52:06 INF] EXPECTO? Running tests...
[08:52:06 INF] EXPECTO! 1 tests run in 00:00:00.0569286 – 1 passed, 0 ignored, 0 failed, 0 errored. ᕙ໒( ˵ ಠ ╭͜ʖ╮ ಠೃ ˵ )७ᕗ
</code>```

答: All the Expecto.Expect functions take a string parameter at the end that is the message to print on failure. You're not supplying that parameter, so your Expecto.Expect.isTrue result expression has the type string -> unit: it hasn't actually called isTrue yet. (You should see a green wavy line under that expression in your IDE saying that the value is ignored). Add a string to your call, like Expecto.Expect.isTrue result "should fail" and then your test will fail as it's supposed to.

Body:
I'm trying to get expecto up and running in our test project.

Though it compiles and run fine, I wanted to just make sure it was really working. So I gave it a fail case and it passes.

Did I miss something silly here?

My test setup

let tests =
    testList "Test Group" [
        test "Testing fail test" {
           let result = false
           Expecto.Expect.isTrue result
        }
    ]

let runTests args =
  runTestsWithArgs defaultConfig args tests

Output from the test

[08:52:06 INF] EXPECTO? Running tests...
[08:52:06 INF] EXPECTO! 1 tests run in 00:00:00.0569286 – 1 passed, 0 ignored, 0 failed, 0 errored. ᕙ໒( ˵ ಠ ╭͜ʖ╮ ಠೃ ˵ )७ᕗ


问:
Appending character to variable in execute query
I want to execute a dynamic SQL statement, which searches for names whose last name is always a constant and first name is a variable.
Here is a query I have written for selecting a row with name='Test lastname'.

```<code>EXECUTE 'SELECT name FROM users
        WHERE name=$1 lastname'
USING ('Test');
</code>```

This generates a syntax error. Is it possible to do this?

答:
I think you need something like this:

```<code>EXECUTE 'SELECT user_id FROM users
        WHERE name=$1'
USING  Test||' lastname' ;
</code>```

Here Test is variable and 'lastname' is hard coded value

Also another way is as @JorgeCampos mentioned:

```<code>...WHERE name=$1 || '' lastname''' USING 'Test';
</code>```

Body:
I want to execute a dynamic SQL statement, which searches for names whose last name is always a constant and first name is a variable.
Here is a query I have written for selecting a row with name='Test lastname'.

EXECUTE 'SELECT name FROM users
        WHERE name=$1 lastname'
USING ('Test');

This generates a syntax error. Is it possible to do this?

Body:
I think you need something like this:

EXECUTE 'SELECT user_id FROM users
        WHERE name=$1'
USING  Test||' lastname' ;

Here Test is variable and 'lastname' is hard coded value

Also another way is as @JorgeCampos mentioned:

...WHERE name=$1 || '' lastname''' USING 'Test';