问:
How do I pass text input from one JTextField to a variable in another class?
I am trying to create a student registration program in which the user inputs data in a JFrame in a JTextField and that data is stored into a variable in another class.
package acgregistration;

```<code>import java.util.*;
/**
*
* @author Frank
*/
public class AcgRegistration {

public static void main(String[] args) {

    memberDialogBox memberDialogBox = new memberDialogBox();

}

}

    package acgregistration;

    /**
     *
     * @author Frank
     */
    class acgMember {
 private String name;
 private int num;
 private String email;

 public acgMember(String name, int number, String email) {
    this.name = name;
    this.num = number;
    this.email = email;
 }

 public String getName() {
    return name;
 }

 public void setName(String name) {
    this.name = name;
 }

 public int getNum() {
    return num;
 }

 public void setNum(int num) {
     this.num = num;
 }

 public String getEmail() {
    return email;
 }

 public void setEmail(String email) {
    this.email = email;
 }
 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;

 /**
 *
 * @author Frank
 */
 public class memberDialogBox {

 String options[] = {"Student","Faculty/Staff"};
 JComboBox choices = new JComboBox(options);
 JButton b = new JButton("Confirm");
 JLabel l = new JLabel("Select your ACG Status");

 public memberDialogBox(){
  frame();
 }

 public void frame(){

  JFrame f = new JFrame();
  f.setVisible(true);
  f.setSize(210,150);
  f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  JPanel p = new JPanel();
  p.add(choices);
  p.add(b);
  p.add(l);

  f.add(p);

  b.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){

          String s = choices.getSelectedItem().toString();
          if ("Student".equals(choices.getSelectedItem())){

               studentDialogBox student = new studentDialogBox();
    //This code gives me an error code saying I should call
   //acgMemberModel

          }
          else{
                 facultyDialogBox faculty= new facultyDialogBox();
              }

        f.dispose();
          }

  });
  }

 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class studentDialogBox {
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private acgMemberModel model;

public studentDialogBox(acgMemberModel model) {
    this.model = model;
    frame();
}

public void frame() {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.add(nameField);
    panel.add(emailField);
    panel.add(numberField);
    panel.add(confirmButton);
    frame.add(panel);

    confirmButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String number = numberField.getText();
            String email = emailField.getText();
            acgMember member = new acgMember(name,
   Integer.valueOf(number), email);
            model.addNew(member);
        }
    });

   }
 }

class acgMemberModel {
private List<acgMember> members = new ArrayList<>();

public void addNew(acgMember member) {
    members.add(member);
}

public List<acgMember> getMembers() {
    return Collections.unmodifiableList(members);
}
}
</code>```

I'm basically trying to do this for all the text fields and then save it into an ArrayList or a Hashmap ( basically the end result). My only question is, how would i store text field inputs from one class to another?
Any help would be highly appreciated! Thank you!

答:
Just create new instance of Member every time when you populate fields and push button in result of this action listener will invoked and you will grab all data from text field and pass it to new instance constructor. Every time you create new Member pass it to MemberModel separate class.

P.S. you need to read something about naming convention of java language especially about variables, you made mistake in way to set action listener to a TextField instead of Button because your variable names completely meaningless. I refactor code in way to change all variable names to human readable form and fix mistake in my solution because all that conventions has not been used.

```<code>import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        MemberModel model = new MemberModel();
        StudentsToOutputListener outputListener
                = new StudentsToOutputListener(model, new FileOutput(new File("path to your default file")));
        Window studentDialog = new StudentDialogBox(model);
        Window facilityDialog = new FacultyDialogBox();
        Window memberDialog = new MemberDialogBox(studentDialog, facilityDialog);
        memberDialog.show();
    }
}

class Member {
    private String name;
    private int number;
    private String email;

    public Member(String name, int number, String email) {
        this.name = name;
        this.number = number;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Member{" +
                "name='" + name + '\'' +
                ", number=" + number +
                ", email='" + email + '\'' +
                '}';
    }
}

interface Window {
    void show();
}

interface Output {
    void output(List<Member> members);
}

interface Listener {
    void update();
}

class MemberDialogBox implements Window {
    private JFrame frame = new JFrame();
    private JComboBox<Window> choiceComboBox = new JComboBox<>();
    private JButton confirmButton = new JButton("Confirm");
    private JLabel selectLabel = new JLabel("Select your ACG Status");

    public MemberDialogBox(Window... windows) {
        for (Window window : windows) {
            choiceComboBox.addItem(window);
        }
        frame();
    }

    public void show() {
        frame.setVisible(true);
    }

    public void frame() {
        frame = new JFrame();
        frame.setSize(210, 150);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(choiceComboBox);
        panel.add(confirmButton);
        panel.add(selectLabel);
        frame.add(panel);

        confirmButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Window window = (Window) choiceComboBox.getSelectedItem();
                window.show();
                frame.dispose();
            }

        });
    }

}

class StudentDialogBox implements Window, Listener, Output {
    private JTextField nameField = new JTextField("", 20);
    private JTextField emailField = new JTextField("", 20);
    private JTextField numberField = new JTextField("", 20);
    private JButton confirmButton = new JButton("Confirm");
    private JButton saveButton = new JButton("Save students to file");
    private JFrame frame;
    private JList<Member> list = new JList<>();
    private MemberModel model;

    public StudentDialogBox(MemberModel model) {
        this.model = model;
        model.addListener(this);
        frame();
    }

    public void show() {
        frame.setVisible(true);
    }

    public void output(List<Member> members) {
        list.setListData(members.toArray(new Member[]{}));
    }

    public void update() {
        model.outputStudentsTo(this);
    }

    public void frame() {
        frame = new JFrame();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(nameField);
        panel.add(emailField);
        panel.add(numberField);
        panel.add(confirmButton);
        panel.add(list);
        panel.add(saveButton);
        frame.add(panel);

        saveButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.showSaveDialog(frame);
                File selectedFile = fileChooser.getSelectedFile();
                Output output = new FileOutput(selectedFile);
                model.outputStudentsTo(output);
            }
        });

        confirmButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String name = nameField.getText();
                String number = numberField.getText();
                String email = emailField.getText();
                Member member = new Member(name, Integer.valueOf(number), email);
                model.addNewStudent(member);
            }
        });

    }

    public String toString() {
        return "Student";
    }
}

class FacultyDialogBox implements Window {

    public void show() {
        System.out.println("you need to implement FacultyDialogBox " +
                "in similar way than StudentDialog box");
    }

    public String toString() {
        return "Faculty/Stuff";
    }
}

class MemberModel {
    private List<Member> students = new ArrayList<>();
    private List<Member> stuff = new ArrayList<>();
    private List<Listener> listeners = new ArrayList<>();

    public void addListener(Listener listener) {
        listeners.add(listener);
    }

    private void notifyListeners() {
        for (Listener listener : listeners) {
            listener.update();
        }
    }

    public void addNewStudent(Member member) {
        students.add(member);
        notifyListeners();
    }

    public void addNewStuff(Member member) {
        stuff.add(member);
        notifyListeners();
    }

    public void outputStudentsTo(Output output) {
        output.output(Collections.unmodifiableList(students));
    }

    public void outputStuffTo(Output output) {
        output.output(Collections.unmodifiableList(stuff));
    }
}

class FileOutput implements Output {
    private final File destination;

    public FileOutput(File destination) {
        this.destination = destination;
    }

    public void output(List<Member> members) {
        try (BufferedWriter file = new BufferedWriter(new FileWriter(destination))) {
            for (Member member : members) {
                file.write(member.toString());
                file.write("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

class StudentsToOutputListener implements Listener {
    private final MemberModel model;
    private final Output output;

    public StudentsToOutputListener(MemberModel model, Output output) {
        this.model = model;
        this.output = output;
        model.addListener(this);
    }

    public void update() {
        model.outputStudentsTo(output);
    }
}
</code>```

I update answer to you question clarification, i understand what do you want to implement and fix your program, also i refactor this code and make it more in oop style and more readable, but you need to implement by yourself second dialog Facility in similar way than Student dialog box. Also you need to place every class in this source to different *.java file.

Body:
I am trying to create a student registration program in which the user inputs data in a JFrame in a JTextField and that data is stored into a variable in another class.
package acgregistration;

import java.util.*;
/**
*
* @author Frank
*/
public class AcgRegistration {

public static void main(String[] args) {

    memberDialogBox memberDialogBox = new memberDialogBox();

}

}

    package acgregistration;

    /**
     *
     * @author Frank
     */
    class acgMember {
 private String name;
 private int num;
 private String email;

 public acgMember(String name, int number, String email) {
    this.name = name;
    this.num = number;
    this.email = email;
 }

 public String getName() {
    return name;
 }

 public void setName(String name) {
    this.name = name;
 }

 public int getNum() {
    return num;
 }

 public void setNum(int num) {
     this.num = num;
 }

 public String getEmail() {
    return email;
 }

 public void setEmail(String email) {
    this.email = email;
 }
 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;

 /**
 *
 * @author Frank
 */
 public class memberDialogBox {

 String options[] = {"Student","Faculty/Staff"};
 JComboBox choices = new JComboBox(options);
 JButton b = new JButton("Confirm");
 JLabel l = new JLabel("Select your ACG Status");

 public memberDialogBox(){
  frame();
 }

 public void frame(){

  JFrame f = new JFrame();
  f.setVisible(true);
  f.setSize(210,150);
  f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  JPanel p = new JPanel();
  p.add(choices);
  p.add(b);
  p.add(l);

  f.add(p);

  b.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){

          String s = choices.getSelectedItem().toString();
          if ("Student".equals(choices.getSelectedItem())){

               studentDialogBox student = new studentDialogBox();
    //This code gives me an error code saying I should call
   //acgMemberModel

          }
          else{
                 facultyDialogBox faculty= new facultyDialogBox();
              }

        f.dispose();
          }

  });
  }

 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class studentDialogBox {
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private acgMemberModel model;

public studentDialogBox(acgMemberModel model) {
    this.model = model;
    frame();
}

public void frame() {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.add(nameField);
    panel.add(emailField);
    panel.add(numberField);
    panel.add(confirmButton);
    frame.add(panel);

    confirmButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String number = numberField.getText();
            String email = emailField.getText();
            acgMember member = new acgMember(name,
   Integer.valueOf(number), email);
            model.addNew(member);
        }
    });

   }
 }

class acgMemberModel {
private List<acgMember> members = new ArrayList<>();

public void addNew(acgMember member) {
    members.add(member);
}

public List<acgMember> getMembers() {
    return Collections.unmodifiableList(members);
}
}

I'm basically trying to do this for all the text fields and then save it into an ArrayList or a Hashmap ( basically the end result). My only question is, how would i store text field inputs from one class to another?
Any help would be highly appreciated! Thank you!

Body:
Just create new instance of Member every time when you populate fields and push button in result of this action listener will invoked and you will grab all data from text field and pass it to new instance constructor. Every time you create new Member pass it to MemberModel separate class.

P.S. you need to read something about naming convention of java language especially about variables, you made mistake in way to set action listener to a TextField instead of Button because your variable names completely meaningless. I refactor code in way to change all variable names to human readable form and fix mistake in my solution because all that conventions has not been used.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        MemberModel model = new MemberModel();
        StudentsToOutputListener outputListener
                = new StudentsToOutputListener(model, new FileOutput(new File("path to your default file")));
        Window studentDialog = new StudentDialogBox(model);
        Window facilityDialog = new FacultyDialogBox();
        Window memberDialog = new MemberDialogBox(studentDialog, facilityDialog);
        memberDialog.show();
    }
}

class Member {
    private String name;
    private int number;
    private String email;

    public Member(String name, int number, String email) {
        this.name = name;
        this.number = number;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Member{" +
                "name='" + name + '\'' +
                ", number=" + number +
                ", email='" + email + '\'' +
                '}';
    }
}

interface Window {
    void show();
}

interface Output {
    void output(List<Member> members);
}

interface Listener {
    void update();
}

class MemberDialogBox implements Window {
    private JFrame frame = new JFrame();
    private JComboBox<Window> choiceComboBox = new JComboBox<>();
    private JButton confirmButton = new JButton("Confirm");
    private JLabel selectLabel = new JLabel("Select your ACG Status");

    public MemberDialogBox(Window... windows) {
        for (Window window : windows) {
            choiceComboBox.addItem(window);
        }
        frame();
    }

    public void show() {
        frame.setVisible(true);
    }

    public void frame() {
        frame = new JFrame();
        frame.setSize(210, 150);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(choiceComboBox);
        panel.add(confirmButton);
        panel.add(selectLabel);
        frame.add(panel);

        confirmButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Window window = (Window) choiceComboBox.getSelectedItem();
                window.show();
                frame.dispose();
            }

        });
    }

}

class StudentDialogBox implements Window, Listener, Output {
    private JTextField nameField = new JTextField("", 20);
    private JTextField emailField = new JTextField("", 20);
    private JTextField numberField = new JTextField("", 20);
    private JButton confirmButton = new JButton("Confirm");
    private JButton saveButton = new JButton("Save students to file");
    private JFrame frame;
    private JList<Member> list = new JList<>();
    private MemberModel model;

    public StudentDialogBox(MemberModel model) {
        this.model = model;
        model.addListener(this);
        frame();
    }

    public void show() {
        frame.setVisible(true);
    }

    public void output(List<Member> members) {
        list.setListData(members.toArray(new Member[]{}));
    }

    public void update() {
        model.outputStudentsTo(this);
    }

    public void frame() {
        frame = new JFrame();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(nameField);
        panel.add(emailField);
        panel.add(numberField);
        panel.add(confirmButton);
        panel.add(list);
        panel.add(saveButton);
        frame.add(panel);

        saveButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.showSaveDialog(frame);
                File selectedFile = fileChooser.getSelectedFile();
                Output output = new FileOutput(selectedFile);
                model.outputStudentsTo(output);
            }
        });

        confirmButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String name = nameField.getText();
                String number = numberField.getText();
                String email = emailField.getText();
                Member member = new Member(name, Integer.valueOf(number), email);
                model.addNewStudent(member);
            }
        });

    }

    public String toString() {
        return "Student";
    }
}

class FacultyDialogBox implements Window {

    public void show() {
        System.out.println("you need to implement FacultyDialogBox " +
                "in similar way than StudentDialog box");
    }

    public String toString() {
        return "Faculty/Stuff";
    }
}

class MemberModel {
    private List<Member> students = new ArrayList<>();
    private List<Member> stuff = new ArrayList<>();
    private List<Listener> listeners = new ArrayList<>();

    public void addListener(Listener listener) {
        listeners.add(listener);
    }

    private void notifyListeners() {
        for (Listener listener : listeners) {
            listener.update();
        }
    }

    public void addNewStudent(Member member) {
        students.add(member);
        notifyListeners();
    }

    public void addNewStuff(Member member) {
        stuff.add(member);
        notifyListeners();
    }

    public void outputStudentsTo(Output output) {
        output.output(Collections.unmodifiableList(students));
    }

    public void outputStuffTo(Output output) {
        output.output(Collections.unmodifiableList(stuff));
    }
}

class FileOutput implements Output {
    private final File destination;

    public FileOutput(File destination) {
        this.destination = destination;
    }

    public void output(List<Member> members) {
        try (BufferedWriter file = new BufferedWriter(new FileWriter(destination))) {
            for (Member member : members) {
                file.write(member.toString());
                file.write("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

class StudentsToOutputListener implements Listener {
    private final MemberModel model;
    private final Output output;

    public StudentsToOutputListener(MemberModel model, Output output) {
        this.model = model;
        this.output = output;
        model.addListener(this);
    }

    public void update() {
        model.outputStudentsTo(output);
    }
}

I update answer to you question clarification, i understand what do you want to implement and fix your program, also i refactor this code and make it more in oop style and more readable, but you need to implement by yourself second dialog Facility in similar way than Student dialog box. Also you need to place every class in this source to different *.java file.


来源: stackexchange

问:
how to write a recurrence relation for a given piece of code
In my algorithm and data structures class we were given a few recurrence relations either to solve or that we can see the complexity of an algorithm.

At first, I thought that the mere purpose of these relations is to jot down the complexity of a recursive divide-and-conquer algorithm. Then I came across a question in the MIT assignments, where one is asked to provide a recurrence relation for an iterative algorithm.

How would I actually come up with a recurrence relation myself, given some code? What are the necessary steps?

Is it actually correct that I can jot down any case i.e. worst, best, average case with such a relation?

Could possibly someone give a simple example on how a piece of code is turned into a recurrence relation?

Cheers,
Andrew

答:
To find the running time of an algorithm we need to firstly able to write an expression for the algorithm and that expression tells the running time for each step. So you need to walk through each of the steps of an algorithm to find the expression.
For example, suppose we defined a predicate, isSorted, which would take as input an array a and the size, n, of the array and would return true if and only if the array was sorted in increasing order.

```<code>bool isSorted(int *a, int n) {
   if (n == 1)
      return true;       // a 1-element array is always sorted
   for (int i = 0; i < n-1; i++) {
      if (a[i] > a[i+1]) // found two adjacent elements out of order
         return false;
   }
   return true;         // everything's in sorted order
}
</code>```

Clearly, the size of the input here will simply be n, the size of the array. How many steps will be performed in the worst case, for input n?

The first if statement counts as 1 step

The for loop will execute n−1 times in the worst case (assuming the internal test doesn't kick us out), for a total time of n−1 for the loop test and the increment of the index.

Inside the loop, there's another if statement which will be executed once per iteration for a total of n−1 time, at worst.

The last return will be executed once.

So, in the worst case, we'll have done 1+(n−1)+(n−1)+1

computations, for a total run time T(n)≤1+(n−1)+(n−1)+1=2n and so we have the timing function T(n)=O(n).

So in brief what  we have done is-->>

1.For a parameter 'n' which gives the size of the input we assume that each simple statements that are executed once will take constant time,for simplicity assume one

2.The iterative statements like loops and inside body will take variable time depending upon the input.
Which has solution T(n)=O(n), just as with the non-recursive version, as it happens.

3.So your task is to go step by step and write down the function in terms of n to calulate the time complexity

For recursive algorithms, you do the same thing, only this time you add the time taken by each recursive call, expressed as a function of the time it takes on its input.
For example, let's rewrite, isSorted as a recursive algorithm:

```<code>bool isSorted(int *a, int n) {
   if (n == 1)
      return true;
   if (a[n-2] > a[n-1])         // are the last two elements out of order?
      return false;
   else
      return isSorted(a, n-1); // is the initial part of the array sorted?
}
</code>```

In this case we still walk through the algorithm, counting: 1 step for the first if plus 1 step for the second if, plus the time isSorted will take on an input of size n−1, which will be T(n−1), giving a recurrence relation

T(n)≤1+1+T(n−1)=T(n−1)+O(1)

Which has solution T(n)=O(n), just as with the non-recursive version, as it happens.

Simple Enough!! Practice More to write the recurrence relation of various algorithms keeping in mind how much time each step will be executed in algorithm

ContentLicense: CC BY-SA 3.0

Body:
To find the running time of an algorithm we need to firstly able to write an expression for the algorithm and that expression tells the running time for each step. So you need to walk through each of the steps of an algorithm to find the expression.
For example, suppose we defined a predicate, isSorted, which would take as input an array a and the size, n, of the array and would return true if and only if the array was sorted in increasing order.

bool isSorted(int *a, int n) {
   if (n == 1)
      return true;       // a 1-element array is always sorted
   for (int i = 0; i < n-1; i++) {
      if (a[i] > a[i+1]) // found two adjacent elements out of order
         return false;
   }
   return true;         // everything's in sorted order
}

Clearly, the size of the input here will simply be n, the size of the array. How many steps will be performed in the worst case, for input n?

The first if statement counts as 1 step

The for loop will execute n−1 times in the worst case (assuming the internal test doesn't kick us out), for a total time of n−1 for the loop test and the increment of the index.

Inside the loop, there's another if statement which will be executed once per iteration for a total of n−1 time, at worst.

The last return will be executed once.

So, in the worst case, we'll have done 1+(n−1)+(n−1)+1

computations, for a total run time T(n)≤1+(n−1)+(n−1)+1=2n and so we have the timing function T(n)=O(n).

So in brief what  we have done is-->>

1.For a parameter 'n' which gives the size of the input we assume that each simple statements that are executed once will take constant time,for simplicity assume one

2.The iterative statements like loops and inside body will take variable time depending upon the input.
Which has solution T(n)=O(n), just as with the non-recursive version, as it happens.

3.So your task is to go step by step and write down the function in terms of n to calulate the time complexity

For recursive algorithms, you do the same thing, only this time you add the time taken by each recursive call, expressed as a function of the time it takes on its input.
For example, let's rewrite, isSorted as a recursive algorithm:

bool isSorted(int *a, int n) {
   if (n == 1)
      return true;
   if (a[n-2] > a[n-1])         // are the last two elements out of order?
      return false;
   else
      return isSorted(a, n-1); // is the initial part of the array sorted?
}

In this case we still walk through the algorithm, counting: 1 step for the first if plus 1 step for the second if, plus the time isSorted will take on an input of size n−1, which will be T(n−1), giving a recurrence relation

T(n)≤1+1+T(n−1)=T(n−1)+O(1)

Which has solution T(n)=O(n), just as with the non-recursive version, as it happens.

Simple Enough!! Practice More to write the recurrence relation of various algorithms keeping in mind how much time each step will be executed in algorithm


问:
Robolectric unable to find resource ID when running test
I am new to Robolectric testing in Android Studio and when I try to run tests, the same error appears which states android.content.res.Resources$NotFoundException: Unable to find resource ID #0x0 in packages. I made sure that the JUnit Working Directory was $MODULE_DIR$, but it still didn't work. Adding testOptions.unitTests.includeAndroidResources to my build.gradle file doesn't do anything either. Here is what the test file looks like:

```<code>@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
public class StartActivityTests {

    StartActivity activity;

    @Before
    public void setUp() throws Exception {
        activity = Robolectric.buildActivity(StartActivity.class)
            .create()
            .resume()
            .get();
    }

    @Test
    public void shouldNotBeNull() throws Exception
    {
        assertNotNull(activity);
    }

    @Test
    public void clickingNewGame_shouldStartAvatarRoomActivity() {
        StartActivity activity = Robolectric.setupActivity(StartActivity.class);
        activity.findViewById(R.id.newUserButtonFirstPage).performClick();

        Intent expectedIntent = new Intent(activity, AvatarRoomActivity.class);
        Intent actual = ShadowApplication.getInstance().getNextStartedActivity();
        assertEquals(expectedIntent.getComponent(), actual.getComponent());
    }
}
</code>```

Please help! It would be greatly appreciated!

答: I changed my SDK to 27 in the build.gradle file and the Robolectric tests succeeded.</p>

Body:
I am new to Robolectric testing in Android Studio and when I try to run tests, the same error appears which states android.content.res.Resources$NotFoundException: Unable to find resource ID #0x0 in packages. I made sure that the JUnit Working Directory was $MODULE_DIR$, but it still didn't work. Adding testOptions.unitTests.includeAndroidResources to my build.gradle file doesn't do anything either. Here is what the test file looks like:

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
public class StartActivityTests {

    StartActivity activity;

    @Before
    public void setUp() throws Exception {
        activity = Robolectric.buildActivity(StartActivity.class)
            .create()
            .resume()
            .get();
    }

    @Test
    public void shouldNotBeNull() throws Exception
    {
        assertNotNull(activity);
    }

    @Test
    public void clickingNewGame_shouldStartAvatarRoomActivity() {
        StartActivity activity = Robolectric.setupActivity(StartActivity.class);
        activity.findViewById(R.id.newUserButtonFirstPage).performClick();

        Intent expectedIntent = new Intent(activity, AvatarRoomActivity.class);
        Intent actual = ShadowApplication.getInstance().getNextStartedActivity();
        assertEquals(expectedIntent.getComponent(), actual.getComponent());
    }
}

Please help! It would be greatly appreciated!


问:
T-SQL hierarchy query
I have a table with hierarchical data:

This is a sample of data with id, parent id, name, code (which is sometimes not filled), level and isroot column. In real scenario there will be more levels than just 2 but now let's look at the simplified example.

What I need to do is to loop over all records and find rows where id is not filled at any level of the hierarchy:

Rows with id ranging should be returned from 6 till 10 because they do not have code filled in at any point of the hierarchy

Rows from 1 till 5 should not be returned because code was mentioned somewhere in the hierarchy.

How should one solve this problem with T-SQL?

The only solution that came to my mind was recursivity (cte or WHILE) but I what I was trying to implement was too complex and did not solve the problem.

答:
Slightly different than @DhruvJoshi's answer, since it may be useful:</p>
```<code>WITH recCTE AS
(
    SELECT
        id,
        parent_id,
        CASE WHEN CODE IS NOT NULL THEN 1 ELSE 0 END as code_check,
        1 as depth,
        CAST(id as VARCHAR(50)) as path
    FROM table
    WHERE isRootLevel = 1
    UNION ALL
    SELECT
        table.id,
        table.parent_id,
        CASE WHEN CODE IS NOT NULL OR reccte.code_check = 1 THEN 1 ELSE 0 END,
        depth + 1 as depth,
        reccte.path + CAST(table.id AS varchar(10)) as path
    FROM
        recCTE
        INNER JOIN table ON
            recCTE.ID = table.parent_id
    WHERE depth < 20 /*just in case you start cycling/endless looping*/
)
SELECT * FROM recCTE where code_check = 0 ORDER BY path, depth;
</code>```

Title: T-SQL hierarchy query

Body:
Slightly different than @DhruvJoshi's answer, since it may be useful:

WITH recCTE AS
(
    SELECT
        id,
        parent_id,
        CASE WHEN CODE IS NOT NULL THEN 1 ELSE 0 END as code_check,
        1 as depth,
        CAST(id as VARCHAR(50)) as path
    FROM table
    WHERE isRootLevel = 1
    UNION ALL
    SELECT
        table.id,
        table.parent_id,
        CASE WHEN CODE IS NOT NULL OR reccte.code_check = 1 THEN 1 ELSE 0 END,
        depth + 1 as depth,
        reccte.path + CAST(table.id AS varchar(10)) as path
    FROM
        recCTE
        INNER JOIN table ON
            recCTE.ID = table.parent_id
    WHERE depth < 20 /*just in case you start cycling/endless looping*/
)
SELECT * FROM recCTE where code_check = 0 ORDER BY path, depth;

ContentLicense: CC BY-SA 4.0


问:
Fetch current ADFS credential on the mobile device?
I’m new to ADFS. The mobile device is already in domain (authenticated via ADFS already). I’m working on a mobile app and I don’t want the user to input manually user name and password again, just use the the current ADFS credential to fetch the token. Is that possible? And how to do it? Thanks.</p>

答:
IWA is what you are after and that only works on a browser if it is configured. IE is the only browser that does this by default.

On mobile, I suspect you also need to attach the device by DRS or via Intune?


问:
How can I make this python code shorter and more efficient
This is my attempt at doing a higher/lower game.

```<code>import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))
if choice < number:
    print("Higher")
elif choice > number:
    print("Lower")
else:
    print("Well done!")
while choice != number:
    choice = int(input("Pick again: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")
</code>```

I'm new to python and I'm just wondering is there a way of shortening the code to make it more efficient? Don't think there is a need for two 'if/elif/else' statements but can't see a way to merge them. Sorry if it's a stupid question!

Updated Code:

```<code>import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
    choice = int(input("Please pick a number: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")
</code>```

答:
the if/else statements can be put on one line:

```<code>import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
    choice = int(input("Please pick a number: "))
    s = 'Higher' if choice < number else ('Lower' if choice > number else 'Well done!')
    print(s)
</code>```

If you want to minimize the number of characters, change the var names to just "initials" like:

```<code>import random
print("A game of Higher or Lower")
n = random.randint(1, 100)
c = ""
while c != n:
    c = int(input("Please pick a number: "))
    s = 'Higher' if c < n else ('Lower' if c > n else 'Well done!')
    print(s)
</code>```

Body:
This is my attempt at doing a higher/lower game.

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))
if choice < number:
    print("Higher")
elif choice > number:
    print("Lower")
else:
    print("Well done!")
while choice != number:
    choice = int(input("Pick again: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")

I'm new to python and I'm just wondering is there a way of shortening the code to make it more efficient? Don't think there is a need for two 'if/elif/else' statements but can't see a way to merge them. Sorry if it's a stupid question!

Updated Code:

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
    choice = int(input("Please pick a number: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")

Body:
the if/else statements can be put on one line:

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
    choice = int(input("Please pick a number: "))
    s = 'Higher' if choice < number else ('Lower' if choice > number else 'Well done!')
    print(s)

If you want to minimize the number of characters, change the var names to just "initials" like:

import random
print("A game of Higher or Lower")
n = random.randint(1, 100)
c = ""
while c != n:
    c = int(input("Please pick a number: "))
    s = 'Higher' if c < n else ('Lower' if c > n else 'Well done!')
    print(s)


问:
how do i keep form data after submitting the form using javascript?
When i submit this form, the values just disappears from the textboxes. I like them to stay printed in the textboxes. How do i do that?</p>

```<code><form id="myform" method="get" action="" onSubmit="hello();">

       <input id="hour" type="text" name="hour" style="width:30px; text-align:center;" /> :
       <input id="minute" type="text" name="minute" style="width:30px; text-align:center;" />
       <br/>
       <input type="submit" value="Validate!" />
    </form>

    <style type="text/css">
    .error {
        color: red;
        font: 10pt verdana;
        padding-left: 10px
    }
    </style>
<script type="text/javascript">
function hello(){

    var hour = $("#hour").html();
    alert(hour);
}
    $(function() {
        // validate contact form on keyup and submit
        $("#myform").validate({
            //set the rules for the fild names
            rules: {
                hour: {
                    required: true,
                    minlength: 1,
                    maxlength: 2,
                    range:[0,23]
                },
                minute: {
                    required: true,
                    minlength: 1,
                    maxlength: 2,
                    range:[0,60]
                },
            },
            //set messages to appear inline
            messages: {
                hour: "Please enter a valid hour",
                minute: "Please enter a valid minute"
            }
        });

    });
    </script>
</code>```

答:
In the form tag, include onsubmit ="return false" to avoid form reset.
For example:

```<code><form name = "inputNumbers" onsubmit ="return false">
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When i submit this form, the values just disappears from the textboxes. I like them to stay printed in the textboxes. How do i do that?

<form id="myform" method="get" action="" onSubmit="hello();">

       <input id="hour" type="text" name="hour" style="width:30px; text-align:center;" /> :
       <input id="minute" type="text" name="minute" style="width:30px; text-align:center;" />

       <input type="submit" value="Validate!" />
    </form>

Body:
In the form tag, include onsubmit ="return false" to avoid form reset.
For example:

<form name = "inputNumbers" onsubmit ="return false">


问:
Finding specific elements in a list
I am trying to write a code that counts the number of specific colors in a single line of code, so far I have:

```<code>cars = input('Cars: ')
print('red:', cars.count("red"))
print('blue:', cars.count("blue"))
</code>```

But how do I get it to accept "blueish" or "bluey" as well as "blue"?

答:
you can use a structure as followed:

```<code>a=input('cars:')
if 'blue' in a:
    blue+=1
if 'red' in a:
    red+=1
print(red, blue)
</code>```

the structure reads the user input, then searches for the specific color that also includes the phrases you wanted to be covered like blueish, detecting one, it outputs the correct number

Title: Finding specific elements in a list

Body:
I am trying to write a code that counts the number of specific colors in a single line of code, so far I have:

cars = input('Cars: ')
print('red:', cars.count("red"))
print('blue:', cars.count("blue"))

But how do I get it to accept "blueish" or "bluey" as well as "blue"?

Body:
you can use a structure as followed:

a=input('cars:')
if 'blue' in a:
    blue+=1
if 'red' in a:
    red+=1
print(red, blue)

the structure reads the user input, then searches for the specific color that also includes the phrases you wanted to be covered like blueish, detecting one, it outputs the correct number


问:
Two images comprising the background for a div?
I need to create the following in CSS and have it work on IE7+ (and Firefox if possible):

Everything is done except the background!

The quotation is different each time, so the background needs to automatically adjust in height.

It also needs to auto adjust to the width of the container it's placed within. By this, I mean the gradient cannot stretch. The background needs to be the fade-in left gradient, then the background colour, then the fade-out right gradient.

Here's my current code - now on JSFiddle:

HTML

```<code><div id="ehs-quotecontainer">
    <div id="ehs-bgleft">
    </div>
    <div id="ehs-bgright">
    </div>
    <div class="ehs-marks" id="ehs-marktop">
        “
    </div>
    <span class="ehs-quotetext">Once you believe anything, you stop thinking about it.</span>
    <div class="ehs-marks" id="ehs-markbottom">
        ”
    </div>
</div>
</code>```

CSS

```<code>#ehs-quotecontainer  {
    padding-top:8px;
    padding-bottom:8px;
    background-color:#F7F8FA;
    text-align:center;
}
#ehs-bgleft {
    background:transparent url(../images/ehsbgleft.jpg) repeat-y scroll right top;
}
#ehs-bgright {
    background:transparent url(../images/ehsbgright.jpg) repeat-y scroll right top;
}
.ehs-marks {
    height:20px;
    color:#8B8C90;
    font-size:5.0em;
}
#ehs-marktop {
    float:left;
    margin-top:-18px;
}
#ehs-markbottom {
    float:right;
    margin-top:-5px;
}
.ehs-quotetext {
    padding-left:4px;
    padding-right:4px;
    color:#000;
    font-size:1.1em;
    font-style:italic;
}
</code>```

Any ideas on how to make the background work correctly?

答:
Could you create a single image, with the gradient meeting in the middle? If so, you can use:

```<code>#ehs-quotecontainer {
    background: (YOUR_OUTER_EDGE_COLOR) url(../images/ehsbgMerged.jpg) repeat-y center center;
}
</code>```

Provided you have defined edges of your box (which it seems you have), this will always center the gradiant image on your text.

I should add, that if your image is too narrow, your background color will blend with the edges of the image rather than spread out the middle, which might not be what you're looking for.

Body:
I need to create the following in CSS and have it work on IE7+ (and Firefox if possible):

Everything is done except the background!

The quotation is different each time, so the background needs to automatically adjust in height.

It also needs to auto adjust to the width of the container it's placed within. By this, I mean the gradient cannot stretch. The background needs to be the fade-in left gradient, then the background colour, then the fade-out right gradient.

Here's my current code - now on JSFiddle:

HTML

        “

    Once you believe anything, you stop thinking about it.

        ”

CSS

#ehs-quotecontainer  {
    padding-top:8px;
    padding-bottom:8px;
    background-color:#F7F8FA;
    text-align:center;
}
#ehs-bgleft {
    background:transparent url(../images/ehsbgleft.jpg) repeat-y scroll right top;
}
#ehs-bgright {
    background:transparent url(../images/ehsbgright.jpg) repeat-y scroll right top;
}
.ehs-marks {
    height:20px;
    color:#8B8C90;
    font-size:5.0em;
}
#ehs-marktop {
    float:left;
    margin-top:-18px;
}
#ehs-markbottom {
    float:right;
    margin-top:-5px;
}
.ehs-quotetext {
    padding-left:4px;
    padding-right:4px;
    color:#000;
    font-size:1.1em;
    font-style:italic;
}

Any ideas on how to make the background work correctly?

Body:
Could you create a single image, with the gradient meeting in the middle? If so, you can use:

#ehs-quotecontainer {
    background: (YOUR_OUTER_EDGE_COLOR) url(../images/ehsbgMerged.jpg) repeat-y center center;
}

Provided you have defined edges of your box (which it seems you have), this will always center the gradiant image on your text.

I should add, that if your image is too narrow, your background color will blend with the edges of the image rather than spread out the middle, which might not be what you're looking for.


问:
How to enter a character in a C program in windows without display on screen and also without pausing the screen?
I'm trying to make a game program in C.
How to get a char or input without displaying and pausing the screen?</p>

答:
You mentioned you want to make a game in C.

Create your own window.
Capture and Process events.

This sounds a bit much for a beginner but actually it is not.
Use a library like SDL2 to help you with that.

Here is a tutorial series that walks you through some of the basics of game making.


问:
Writing C# GUI over a C++ dll or C++ exe
I have a C++ console Exe which does some progamming. Now i wanted to write a C# GUI which does some of the programming that the C++ exe does. I was thinking of few approaches,

Write the C# GUI with all programming in C++ done from scratch.(I do not want to do this for the amount of rework it entails)

Build a C++ dll which does the programming and have it imported in GUI app.(Now here i have a concern. How do i capture the output of the routines in c++ dll and display it in GUI? Should i return the output as string for every routine that the app calls.? Since i dont know managed c++ iam going to build an unmanaged C++ dll. )

答:
Probably the best way to go here is use P/Invoke or Platform Invoke.  Depending on the structure or your C++ dll interface you may want to wrap it in a pure C interface; it is easiest if your interface uses only blittable types.  If you limit your dll interface to blittable types (Int32, Single, Boolean, Int32[], Single[], Double[] - the basics) you will not need to do any complex marshaling of data between the managed (C#) and unmanaged (C) memory spaces.

For example, in your c# code you define the available calls in your C/C++ dll using the DllImport attribute.

```<code>[DllImport, "ExactDllName.dll"]
static extern boolean OneOfMyCoolCRoutines([In] Double[] x, [In] Double[] y, [Out] Double result)
</code>```

The little [In]'s and [Out]'s are not strictly required, but they can speed things along.  Now having added your "ExactDllName.dll" as a reference to your C# project, you can call your C/C++ function from your C# code.

```<code>fixed(Double *x = &x[0], *y = &y[0] )
{
   Boolean returnValue = OneOfMyCoolCRoutines(x, y, r);
}
</code>```

Note that I'm essentially passing pointers back and fourth between my dll and C# code.  That can cause memory bugs because the locations of those arrays may be changed by the CLR garbage collector, but the C/C++ dll will know nothing of it.  So to guard against that, I've simply fixed those pointers in my C#, and now they won't move in memory while my dll is operating on those arrays.  This is now unsafe code and I'll need to compile my C# code w/ that flag.

There are many fine details to language interop, but that should get you rolling.  Sticking to a stateless C interface of blittable types is a great policy if possible.  That will keep your language interop code the cleanest.

Good luck,

Paul

Body:
Probably the best way to go here is use P/Invoke or Platform Invoke.  Depending on the structure or your C++ dll interface you may want to wrap it in a pure C interface; it is easiest if your interface uses only blittable types.  If you limit your dll interface to blittable types (Int32, Single, Boolean, Int32[], Single[], Double[] - the basics) you will not need to do any complex marshaling of data between the managed (C#) and unmanaged (C) memory spaces.

For example, in your c# code you define the available calls in your C/C++ dll using the DllImport attribute.

[DllImport, "ExactDllName.dll"]
static extern boolean OneOfMyCoolCRoutines([In] Double[] x, [In] Double[] y, [Out] Double result)

The little [In]'s and [Out]'s are not strictly required, but they can speed things along.  Now having added your "ExactDllName.dll" as a reference to your C# project, you can call your C/C++ function from your C# code.

fixed(Double *x = &x[0], *y = &y[0] )
{
   Boolean returnValue = OneOfMyCoolCRoutines(x, y, r);
}

Note that I'm essentially passing pointers back and fourth between my dll and C# code.  That can cause memory bugs because the locations of those arrays may be changed by the CLR garbage collector, but the C/C++ dll will know nothing of it.  So to guard against that, I've simply fixed those pointers in my C#, and now they won't move in memory while my dll is operating on those arrays.  This is now unsafe code and I'll need to compile my C# code w/ that flag.

There are many fine details to language interop, but that should get you rolling.  Sticking to a stateless C interface of blittable types is a great policy if possible.  That will keep your language interop code the cleanest.

Good luck,

Paul


问:
Lambda type with variable number of args in Kotlin?
Is it possible to receive as an inline lambda parameter a function type which has a guaranteed return type R but a variable number of arguments?  For simplicity, consider the following:

```<code>inline fun <R> Boolean?.tfn(tru:()->R, fls:()->R, nul:()->R) =
  if (this == null) nul() else if (this) tru() else fls()
</code>```

Let's assume I have other inline functions that also take lambda parameters that might be of type (A)->R or (A,B)->R or (A,B,C)->R, whose parameters I'd like to pass to this function.  They will all provide an R but they all must be invoked to get the R, without knowing the number/type/values of the parameters in this function.  Is there a way to generically modify the function above to:

capture the generic case of any lambda parameter returning R for its inputs

avoid any changes to the other inline functions that will be calling this function

maintain the inline efficiencies

答:
This is impossible

Kotlin uses static, strong typing, and the compiler needs to know the exact type of the lambda parameters at compile time.
Internally lambdas are actually implementations of one of the kotlin.jvm.functions interfaces (for JVM or Android), like this one:

```<code>/* A function that takes 1 argument. */
public interface Function1<in P1, out R>
</code>```

These interfaces define the exact number of parameters and their types. Because of that it's not possible to create a vararg lambda in Kotlin.
This is of course related to the fact, that vararg in JVM is just a syntax sugar that internally uses ordinary arrays, but is not a type system construct by itself, so you can't treat varargs like types.

Dependent types

One suggestion to solve your problem is to use an Array or a Collection as a function parameter, or pass in arbitrary Function<R>, but this solution is limited in the way that there is no way for to statically  enforce the same amount of the parameters of each passed function, because type system itself doesn't know about the size of collection/array or parameter count of Function<R>.

To solve your problem entirely you need a language with dependent type
system.

Body:
Is it possible to receive as an inline lambda parameter a function type which has a guaranteed return type R but a variable number of arguments?  For simplicity, consider the following:

inline fun <R> Boolean?.tfn(tru:()->R, fls:()->R, nul:()->R) =
  if (this == null) nul() else if (this) tru() else fls()

Let's assume I have other inline functions that also take lambda parameters that might be of type (A)->R or (A,B)->R or (A,B,C)->R, whose parameters I'd like to pass to this function.  They will all provide an R but they all must be invoked to get the R, without knowing the number/type/values of the parameters in this function.  Is there a way to generically modify the function above to:

capture the generic case of any lambda parameter returning R for its inputs

avoid any changes to the other inline functions that will be calling this function

maintain the inline efficiencies

Body:
This is impossible

Kotlin uses static, strong typing, and the compiler needs to know the exact type of the lambda parameters at compile time.
Internally lambdas are actually implementations of one of the kotlin.jvm.functions interfaces (for JVM or Android), like this one:

/* A function that takes 1 argument. */
public interface Function1<in P1, out R>

These interfaces define the exact number of parameters and their types. Because of that it's not possible to create a vararg lambda in Kotlin.
This is of course related to the fact, that vararg in JVM is just a syntax sugar that internally uses ordinary arrays, but is not a type system construct by itself, so you can't treat varargs like types.

Dependent types

One suggestion to solve your problem is to use an Array or a Collection as a function parameter, or pass in arbitrary Function<R>, but this solution is limited in the way that there is no way for to statically  enforce the same amount of the parameters of each passed function, because type system itself doesn't know about the size of collection/array or parameter count of Function<R>.

To solve your problem entirely you need a language with dependent type
system.


问:
CDH Community Edition Rolling Upgrade from 5.7 to 5.13
Can someone let me know how can I perform Rolling Upgrade of CDH from 5.7 to 5.13? I could not find much in Cloudera documentation regarding rolling upgrade of CDH Community Edition?

EDIT

As per the discussion below I can do upgrades manually stopping, upgrading (via "1 Click Install" )and starting the nodes. In a cluster like below

3 Hbase Master (1 Active & 2 standby)

4 Region Servers

4 Data Nodes

1 Primary & 1 Secondary Name Node

3 Journal Node

4 Nodemanager

3 Resource Manager (1 Active & 2 standby)

What should be the order of stopping, upgrading & starting of components? Is it like below:-

Stop, Upgrade & Start all data nodes one by one.

Stop, Upgrade & Start region servers one by one

Stop, Upgrade & Start Upgrade HBase standby nodes one by one

Stop, Upgrade & Start Secondary Name Node

Upgrade Primary Name Node

Upgrade Journal Nodes

Upgrade HBase Master

Stop, upgrade & Start standby Resource Manager one by one

Stop, upgrade & Start Active Resource Manager

Stop, Upgrade & Start Nodemanagers one by one.

If I don't follow any order and update the services in the nodes in parallel, will I face any issue (as this is just a minor version upgrade)?

If I am taking the entire cluster down by stopping all the services in all the nodes and upgrading and then starting? What order should I follow while starting the services?

答:
I think you have to do it manually since you are using Community Version.

A rolling upgrade allows you to upgrade your cluster software and
  restart the upgraded services without taking the cluster offline.
  Performing a rolling upgrade requires the following:

CDH was installed using Cloudera Manager and parcels. You can migrate your cluster from using packages to using parcels.

The cluster uses a Cloudera Enterprise license.

The upgrade overview page has the information you need, but it generally follows

Backup Cloudera Manager database

Upgrade Cloudera Manager server

Upgrade Cloudera Manager Agents on all hosts

Upgrade CDH parcels

Reboot cluster. Try to do it per service. For example, make sure all Cloudera agents are healthly before starting Hadoop services. Then start the namenode(s), and datanodes, followed by resourcemanager(s), etc.

If you are not using Cloudera Manager, you will have to go through the command line upgrade procedures.

Before Upgrading to the Latest Release of CDH

Upgrade CDH to latest

From those you listed, you would stop all services before doing anything. For example, HBase isn't going to work if the datanodes and namenodes are down.

Build a dependency tree, and shut it down from the most dependent services. Meaning, HBase off, then YARN (one resource manager at a time), then HDFS (datanodes, then namenodes and journalnodes). Then upgrade and start them in reverse order.

The second link there says this order for upgrades

NameNode into safemode

Stop all Hadoop services

Backup the namenode

Download the 1-click packages

Upgrade YARN (which requires upgrading Zookeeper)

Upgrade JournalNodes

Start HDFS Service

Start YARN

Upgrade rest of components


问:
Using Rails, or JavaScript, how do you connect webpages with active status?
So I have two webpages that are being connected. On page one, the Landing Page, there is a dropdown menu with two options: Print or Mug. Both of these are anchor tags. The idea is that the user clicks on the dropdown and chooses Print or Mug of that image and is then redirected to the order page.

The Order Page has two sections: Print or Mug, list of images. The Print/Mug option are utilizing buttons and the images have a container around each of them for being marked as selected.

What I'm trying to do is whenever the user clicks on Print on the Landing Page the Order Page is loaded with Print being marked active and that associated image. Right now I can't get any of that to work. For the Landing Page I have:

```<code>    <div class="btn-group">
  <button type="button" class="btn merch dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    MERCH
    <span class="fa fa-angle-down" style="font-size:16px;"></span>
  </button>
  <ul class="dropdown-menu">
    <li>
      <a href="/order" aria-pressed="false">Print</a>
    </li>
    <li>
      <a href="/order" data-toggle="button" aria-pressed="false">Mug</a>
    </li>
  </ul>
</div>
</code>```

For the Order Page I have:

```<code>    <% if params[:active] == 'Print'%>
  <button type="button" class="btn wk-prd-btn wk-click button-toggle active" style="margin-right: 15px; border-radius: 1px;" data-toggle="button" aria-pressed="false">
    PRINT</button>
  <button type="button" class="btn wk-prd-btn wk-click button-toggle" style="border-radius: 1px;">
    MUG</button>

  <% elsif params[:active] == 'Mug'%>
    <button type="button" class="btn wk-prd-btn wk-click button-toggle" style="margin-right: 15px; border-radius: 1px;" data-toggle="button" aria-pressed="false">
      PRINT</button>
    <button type="button" class="btn wk-prd-btn wk-click button-toggle active" style="border-radius: 1px;">
      MUG</button>

  <% else %>
    <button type="button" class="btn wk-prd-btn wk-click button-toggle" style="margin-right: 15px; border-radius: 1px;" data-toggle="button" aria-pressed="false">
      PRINT</button>
    <button type="button" class="btn wk-prd-btn wk-click button-toggle active" style="border-radius: 1px;">
      MUG</button>

  <% end %>
</code>```

I really need to keep the Landing Page as is with the dropdown menu. What am I missing on the connection?

EDIT: Looks like I should probably using JS to do an eventlistener. Any advice for a JS noob?

答:
I assume you're generating your HTML from an html.erb file. In which case, your link_to should look something like (I'm guessing about your path name):

```<code><%= link_to 'Print', new_order_path(active: 'Print'), ... %>
</code>```

That will add a active='Print' query string to your URL which will then be passed onto your OrdersController.

Body:
So I have two webpages that are being connected. On page one, the Landing Page, there is a dropdown menu with two options: Print or Mug. Both of these are anchor tags. The idea is that the user clicks on the dropdown and chooses Print or Mug of that image and is then redirected to the order page.

The Order Page has two sections: Print or Mug, list of images. The Print/Mug option are utilizing buttons and the images have a container around each of them for being marked as selected.

What I'm trying to do is whenever the user clicks on Print on the Landing Page the Order Page is loaded with Print being marked active and that associated image. Right now I can't get any of that to work. For the Landing Page I have:

  <button type="button" class="btn merch dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    MERCH

  </button>

      Print

      Mug

For the Order Page I have:

    <% if params[:active] == 'Print'%>
  <button type="button" class="btn wk-prd-btn wk-click button-toggle active" style="margin-right: 15px; border-radius: 1px;" data-toggle="button" aria-pressed="false">
    PRINT</button>
  <button type="button" class="btn wk-prd-btn wk-click button-toggle" style="border-radius: 1px;">
    MUG</button>

  <% elsif params[:active] == 'Mug'%>
    <button type="button" class="btn wk-prd-btn wk-click button-toggle" style="margin-right: 15px; border-radius: 1px;" data-toggle="button" aria-pressed="false">
      PRINT</button>
    <button type="button" class="btn wk-prd-btn wk-click button-toggle active" style="border-radius: 1px;">
      MUG</button>

  <% else %>
    <button type="button" class="btn wk-prd-btn wk-click button-toggle" style="margin-right: 15px; border-radius: 1px;" data-toggle="button" aria-pressed="false">
      PRINT</button>
    <button type="button" class="btn wk-prd-btn wk-click button-toggle active" style="border-radius: 1px;">
      MUG</button>

  <% end %>

I really need to keep the Landing Page as is with the dropdown menu. What am I missing on the connection?

EDIT: Looks like I should probably using JS to do an eventlistener. Any advice for a JS noob?

Body:
I assume you're generating your HTML from an html.erb file. In which case, your link_to should look something like (I'm guessing about your path name):

<%= link_to 'Print', new_order_path(active: 'Print'), ... %>

That will add a active='Print' query string to your URL which will then be passed onto your OrdersController.


问:
I want to reorder an array of strings
I have an array of String ["a", "b", "c", "d"]. My task is to add them to a listView in order like this:

row ==> d

row ==> c d

row ==> b c d

row ==> a b c d

For now I have created an empty String and through a for loop I added an array of items to it by + but problem is if I use this method, the ListView will look like:

row ==> d

row ==> d c

row ==> d c b

row ==> d c b a

This is what I have done:
...

```<code>String arrNaslovi[] = reverse.split(" ");
String deli = "";

for(int i=arrNaslovi.length-1; i>=0; i--) {
    deli += arrNaslovi[i] + " ";
    arrayNaslovi.add(deli);
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayNaslovi);
    ListView listView = findViewById(R.id.listView);
    listView.setAdapter(adapter);
</code>```

答:
After creating the array you can use
  Collections.reverse(arrayNaslovi);

Title: I want to reorder an array of strings

Body:
I have an array of String ["a", "b", "c", "d"]. My task is to add them to a listView in order like this:

row ==> d

row ==> c d

row ==> b c d

row ==> a b c d

For now I have created an empty String and through a for loop I added an array of items to it by + but problem is if I use this method, the ListView will look like:

row ==> d

row ==> d c

row ==> d c b

row ==> d c b a

This is what I have done:
...

String arrNaslovi[] = reverse.split(" ");
String deli = "";

for(int i=arrNaslovi.length-1; i>=0; i--) {
    deli += arrNaslovi[i] + " ";
    arrayNaslovi.add(deli);
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayNaslovi);
    ListView listView = findViewById(R.id.listView);
    listView.setAdapter(adapter);


Title: How can I get the differences between the OrderStop date and the OrderStart date in the next column?

Body:
How can I get the differences between the OrderStop and the OrderStart in the next column?

For example, row 1 has OrderStop date of 1/31/2007 I want to count the days between the next start date 1/26/2007 I know they are overlaps.

ID  OrderStart  OrderStop
132 4/14/2006   1/31/2007
132 1/26/2007   3/14/2007
132 2/1/2007    3/2/2007
132 3/2/2007    3/14/2007
132 3/14/2007   1/8/2010
132 11/26/2008  1/20/2011
132 1/8/2010    7/14/2010
132 7/14/2010   8/15/2012
132 8/15/2012   1/17/2013
132 1/17/2013   3/22/2013
132 3/21/2013   5/2/2013
132 5/2/2013    8/2/2013
132 5/22/2013   8/2/2013
132 7/29/2013   3/6/2014
132 3/5/2014    7/16/2014
132 7/16/2014   6/19/2015
132 8/21/2014   6/19/2015
132 6/19/2015   4/1/2016
132 6/25/2015   9/9/2015
132 4/1/2016    5/3/2016
132 5/3/2016    7/27/2016
132 8/15/2016   11/2/2016

I am trying to accomplished the below. How can I create a SQL statement that can accomplish this?

132 4/14/2006   1/31/2007
132 1/26/2007   4/1/2016
132 4/1/2016    7/27/2016
132 8/15/2016   11/2/2016

Body:
Consumable sample data makes things much easier for us. So does the version of SQL server. Below is a solution that uses 2012's LEAD functionality. The second one is for pre-2012 systems; it accomplishes the same thing but requires a self join and will not be as efficient.

declare @orders table (id int, orderStart date, orderStop date);
insert @orders
values
(132,'4/14/2006 ','1/31/2007'),
(132,'1/26/2007 ','3/14/2007'),
(132,'2/1/2007  ','3/2/2007 '),
(132,'3/2/2007  ','3/14/2007'),
(132,'3/14/2007 ','1/8/2010 '),
(132,'11/26/2008','1/20/2011'),
(132,'1/8/2010  ','7/14/2010'),
(132,'7/14/2010 ','8/15/2012'),
(132,'8/15/2012 ','1/17/2013'),
(132,'1/17/2013 ','3/22/2013'),
(132,'3/21/2013 ','5/2/2013 '),
(132,'5/2/2013  ','8/2/2013 '),
(132,'5/22/2013 ','8/2/2013 '),
(132,'7/29/2013 ','3/6/2014 '),
(132,'3/5/2014  ','7/16/2014'),
(132,'7/16/2014 ','6/19/2015'),
(132,'8/21/2014 ','6/19/2015'),
(132,'6/19/2015 ','4/1/2016 '),
(132,'6/25/2015 ','9/9/2015 '),
(132,'4/1/2016  ','5/3/2016 '),
(132,'5/3/2016  ','7/27/2016'),
(132,'8/15/2016 ','11/2/2016');

select *,
  nextStart   = lead(orderStart,1) over (order by orderStart),
  daysBetween = abs(datediff(day,lead(orderStart,1) over (order by orderStart), orderStop))
from @orders
order by orderStart;

with preSort as
(
  select *, rn = row_number() over (order by orderstart)
    from @orders
)
select p2.id, p2.orderStart, p2.orderStop , nextStart = p1.orderStart,
  daysBetween = abs(datediff(day, p2.orderStop, p1.orderStart))
from preSort p1 join preSort p2 on p1.rn = p2.rn+1
order by p1.orderStart;

Both Return

id          orderStart orderStop  nextStart  daysBetween
----------- ---------- ---------- ---------- -----------
132         2006-04-14 2007-01-31 2007-01-26 5
132         2007-01-26 2007-03-14 2007-02-01 41
132         2007-02-01 2007-03-02 2007-03-02 0
132         2007-03-02 2007-03-14 2007-03-14 0
132         2007-03-14 2010-01-08 2008-11-26 408
132         2008-11-26 2011-01-20 2010-01-08 377
132         2010-01-08 2010-07-14 2010-07-14 0
132         2010-07-14 2012-08-15 2012-08-15 0
132         2012-08-15 2013-01-17 2013-01-17 0
132         2013-01-17 2013-03-22 2013-03-21 1
132         2013-03-21 2013-05-02 2013-05-02 0
132         2013-05-02 2013-08-02 2013-05-22 72
132         2013-05-22 2013-08-02 2013-07-29 4
132         2013-07-29 2014-03-06 2014-03-05 1
132         2014-03-05 2014-07-16 2014-07-16 0
132         2014-07-16 2015-06-19 2014-08-21 302
132         2014-08-21 2015-06-19 2015-06-19 0
132         2015-06-19 2016-04-01 2015-06-25 281
132         2015-06-25 2015-09-09 2016-04-01 205
132         2016-04-01 2016-05-03 2016-05-03 0
132         2016-05-03 2016-07-27 2016-08-15 19
132         2016-08-15 2016-11-02 NULL       NULL


问:
C beginner: How to copy the arguments from *argv[] to an array of strings using a while loop?
I'm learning C and I am an absolute beginner. I'm trying to do an exercice but after several trials I can't solve it.
I have to copy the arguments in *argv[] to an array of strings *states[] using a while loop so each

```<code>printf("You've mentioned the state %s.\n", states[i]);
</code>```

prints out the name of a state I should have input as an argument. I think the only header I must use is stdio.h.

Thank you in advance for your help.

EDIT. So far I've only tried  things like this

```<code>char *states[];
i = 1;
states[i] = argv[i];
if(argc > 1) {
    while(i < argc){
        printf("You've mentioned the state %s.\n", states[i]);
        i++;
    }
}
</code>```

But, of course, I get an error because of the states[i] = argv[i]; statement.

答:
You can do something like this:

```<code>char* states[argc];
int i = 0;
while (i < argc) {
     strcpy(states[i], argv[i]);
}
</code>```

You have to include

Body:
I'm learning C and I am an absolute beginner. I'm trying to do an exercice but after several trials I can't solve it.
I have to copy the arguments in *argv[] to an array of strings *states[] using a while loop so each

printf("You've mentioned the state %s.\n", states[i]);

prints out the name of a state I should have input as an argument. I think the only header I must use is stdio.h.

Thank you in advance for your help.

EDIT. So far I've only tried  things like this

char *states[];
i = 1;
states[i] = argv[i];
if(argc > 1) {
    while(i < argc){
        printf("You've mentioned the state %s.\n", states[i]);
        i++;
    }
}

But, of course, I get an error because of the states[i] = argv[i]; statement.

Body:
You can do something like this:

char* states[argc];
int i = 0;
while (i < argc) {
     strcpy(states[i], argv[i]);
}

You have to include


问:
Using jQuery and Web Services to send email
I am trying to add sending email functionality to a pure html site. I created an ASP.Net project in VS 2017 and added the html files to it. On the page that has "Contact Us" form, I added jQuery to use web service to send email. I keep getting error and not sure how to debug it. I tested the method in web service separately and it works fine, it send out the email which means something must be wrong in my jQuery. I need help with this and see if anyone can spot what I am missing.

When I run it, I get status code 500 returned.

```<code><section id="contact" class="bg-light">
    <div class="container">
        <div class="row">
            <div class="col-sm-12 ml-sm-auto col-md-10 pt-4">
                <h1>Contact us</h1>

                <form id="sendmail" method="POST" action="">
                    <div class="form-group">
                        <input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Email Address">
                    </div>
                    <div class="form-group">
                        <input type="email" class="form-control" id="inputName" aria-describedby="nameHelp" placeholder="First and Last Name">
                    </div>
                    <div class="form-group">
                        <input type="email" class="form-control" id="inputPhone" aria-describedby="phoneHelp" placeholder="Contact Number">
                    </div>
                    <div class="form-group">
                        <label for="inputMsg">Feedback/Questions</label>
                        <textarea class="form-control" id="inputMsg" rows="3"></textarea>
                    </div>
                    <button type="submit" id="btnSubmit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
</section>

<script type="text/javascript">
    $("#btnSubmit").click(function () {
        debugger
        $("#sendmail").validate();

        if ($("#sendmail").valid()) {
            $.ajax({
                type: "POST",
                url: "/services/easg.asmx/SendEmail",
                cache: false,
                contentType: "application/json; charset=utf-8",
                data: "{ 'Msg': '" + $("#inputMsg").val() + "', " + "'To': 'someone@somewhere.com'," + "'From': '" + $("#inputEmail").val() + "'," + "'Name': '" + $("#inputName").val() + "'," + "'Subject': 'Guide Feedback'," + "'Phone': '" + $("#inputPhone").val() + "'" + "}",
                dataType: "json",
                complete: function (transport) {
                    alert(transport.status);
                    if (transport.status == 200) {
                        alert('Your message was sent; thank you for your feedback');
                    }
                    else {
                        alert("Failed to send feedback; please try again later. Status Code: " + transport.status);
                    }
                }
            });
        }
        //so that the page doesn't post back
        return false;
    });
</script>
</code>```

Web Service:

```<code>namespace EAStyleGuide
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]

    public class easg : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]

        private void SendEmail(string Msg, string To, string From, string Name, string Subject, string Phone)
        {
            using (var message = new MailMessage())
            {
                message.From = new MailAddress(From);
                message.To.Add(new MailAddress(To));
                message.Subject = Subject;
                message.Body = GetMailBody(From, Msg, Phone, Name);
                message.Priority = MailPriority.Normal;
                message.IsBodyHtml = false;

                SmtpClient sc = new SmtpClient("mailrelay.blah.com");
                sc.Credentials = new NetworkCredential();

            try
            {
                sc.Send(message);
            }
            catch (SmtpFailedRecipientsException FRE)
            {
            }
            catch (SmtpException smtpEx)
            {
            }
            catch (Exception generalEx)
            {
            }
        }
        return;
    }
</code>```

There is a "Services" folder at the root of project with easg.asmx in it.

答:
After some debugging as a result of comments on the question above...

respnseText was "Unknown web method SendEmail. Parameter name: methodName"

This means that the framework isn't able to find the web method at all based on the request being made.  Looking closer, the web method appears to be restricted to GET requests:

```<code>[ScriptMethod(UseHttpGet = true)]
</code>```

However, you're making a POST request:

```<code>type: "POST",
</code>```

You'll need to change one or the other.  Which is up to you.

Body:
I am trying to add sending email functionality to a pure html site. I created an ASP.Net project in VS 2017 and added the html files to it. On the page that has "Contact Us" form, I added jQuery to use web service to send email. I keep getting error and not sure how to debug it. I tested the method in web service separately and it works fine, it send out the email which means something must be wrong in my jQuery. I need help with this and see if anyone can spot what I am missing.

When I run it, I get status code 500 returned.

Contact us

                <form id="sendmail" method="POST" action="">

                        <input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Email Address">

                        <input type="email" class="form-control" id="inputName" aria-describedby="nameHelp" placeholder="First and Last Name">

                        <input type="email" class="form-control" id="inputPhone" aria-describedby="phoneHelp" placeholder="Contact Number">

                        Feedback/Questions
                        <textarea class="form-control" id="inputMsg" rows="3"></textarea>

                    <button type="submit" id="btnSubmit" class="btn btn-primary">Submit</button>
                </form>

Web Service:

namespace EAStyleGuide
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]

    public class easg : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]

        private void SendEmail(string Msg, string To, string From, string Name, string Subject, string Phone)
        {
            using (var message = new MailMessage())
            {
                message.From = new MailAddress(From);
                message.To.Add(new MailAddress(To));
                message.Subject = Subject;
                message.Body = GetMailBody(From, Msg, Phone, Name);
                message.Priority = MailPriority.Normal;
                message.IsBodyHtml = false;

                SmtpClient sc = new SmtpClient("mailrelay.blah.com");
                sc.Credentials = new NetworkCredential();

            try
            {
                sc.Send(message);
            }
            catch (SmtpFailedRecipientsException FRE)
            {
            }
            catch (SmtpException smtpEx)
            {
            }
            catch (Exception generalEx)
            {
            }
        }
        return;
    }

There is a "Services" folder at the root of project with easg.asmx in it.

Body:
After some debugging as a result of comments on the question above...

respnseText was "Unknown web method SendEmail. Parameter name: methodName"

This means that the framework isn't able to find the web method at all based on the request being made.  Looking closer, the web method appears to be restricted to GET requests:

[ScriptMethod(UseHttpGet = true)]

However, you're making a POST request:

type: "POST",

You'll need to change one or the other.  Which is up to you.


问:
Flexbox with fixed header and footer and scrollable content
I am trying to make a flexbox design work. I am not an HTML/css expert. :(

I have a flexbox design with fixed header and footer and content that occupies the rest of the available real estate of the page.

When I put data in the content area which is longer than that available space the content is scrolling. But I want to achieve a different thing.

I would like to have several divs (below each other) in the content area and each div should be as high as the content area (even if the content is small) so I have a kind of paging inside the content area.

A couple of days I have tried a lot and read a lot but can't get it  working. How can I make a div inside the scrollable content area occupy the whole space (height) ?

答:
It sounds like what you want are multiple elements in the content section that basically take up the entire page in size, but that you can scroll through.

Let's call these elements in the content section "slide"s.

The easiest way to achieve this would be to set the minimum dimensions of these elements, something like -

```<code>.content .slide {
  min-width:100vw;
  min-height:100vh;
}
</code>```

This will make sure, even if the content within the slide's doesn't take up the entire space, it will remain at full size.

Body:
It sounds like what you want are multiple elements in the content section that basically take up the entire page in size, but that you can scroll through.

Let's call these elements in the content section "slide"s.

The easiest way to achieve this would be to set the minimum dimensions of these elements, something like -

.content .slide {
  min-width:100vw;
  min-height:100vh;
}

This will make sure, even if the content within the slide's doesn't take up the entire space, it will remain at full size.


问:
rxjs: Does forkJoin need at least one call to next to complete?
I have two observables which I would like to forkJoin:

```<code>  var goodObservable = Rx.Observable.create( function(observer){
    observer.next('something');
    observer.complete();
  });

  var badObservable = Rx.Observable.create( function(observer){
    observer.complete();
  });

  var forkJoinedObservable = Rx.Observable.forkJoin([goodObservable, badObservable]);

  forkJoinedObservable.subscribe(function(results){
    console.log(results);
  });
</code>```

One of those observables only calls complete. Now I have found that the forkJoined observables never gets triggered. I will have to call observer.next() in the badObservable in order to make the subscription on forkJoin to be executed.

My expected behaviour would be that the forkJoin-subscribes would be executed with an array containing just one item: ['something']

Is this a bug, or did I not understand the concept correctly?

I have made a plunkr for this: https://plnkr.co/edit/QaA9DwyWAmTGbthvguPK?p=preview

答:
forkJoin() emits the last emitted item from each observable. There's no item to emit in this case, so the operator doesn't emit.

A pragmatic solution would be to call .startsWith(defaultValue) on each observable, so forkJoin() can complete as well.

```<code>var goodObservable = Rx.Observable.create( function(observer){
  observer.next('something');
  observer.complete();
});

var badObservable = Rx.Observable.create( function(observer){
  observer.complete();
}).startWith(null);

var forkJoinedObservable = Rx.Observable.forkJoin([goodObservable, badObservable]);

forkJoinedObservable.subscribe(function(results){
  console.log(results);
});
</code>```

About emitting values just for the observables that have emitted, this wouldn't work, because then you wouldn't know which one didn't emit. Of course, it could have emitted null. But given this is achievable by combining operators, I don't think it's gonna change.

Body:
I have two observables which I would like to forkJoin:

  var goodObservable = Rx.Observable.create( function(observer){
    observer.next('something');
    observer.complete();
  });

  var badObservable = Rx.Observable.create( function(observer){
    observer.complete();
  });

  var forkJoinedObservable = Rx.Observable.forkJoin([goodObservable, badObservable]);

  forkJoinedObservable.subscribe(function(results){
    console.log(results);
  });

One of those observables only calls complete. Now I have found that the forkJoined observables never gets triggered. I will have to call observer.next() in the badObservable in order to make the subscription on forkJoin to be executed.

My expected behaviour would be that the forkJoin-subscribes would be executed with an array containing just one item: ['something']

Is this a bug, or did I not understand the concept correctly?

I have made a plunkr for this: https://plnkr.co/edit/QaA9DwyWAmTGbthvguPK?p=preview

Body:
forkJoin() emits the last emitted item from each observable. There's no item to emit in this case, so the operator doesn't emit.

A pragmatic solution would be to call .startsWith(defaultValue) on each observable, so forkJoin() can complete as well.

var goodObservable = Rx.Observable.create( function(observer){
  observer.next('something');
  observer.complete();
});

var badObservable = Rx.Observable.create( function(observer){
  observer.complete();
}).startWith(null);

var forkJoinedObservable = Rx.Observable.forkJoin([goodObservable, badObservable]);

forkJoinedObservable.subscribe(function(results){
  console.log(results);
});

About emitting values just for the observables that have emitted, this wouldn't work, because then you wouldn't know which one didn't emit. Of course, it could have emitted null. But given this is achievable by combining operators, I don't think it's gonna change.


问:
add new fragment on pageview swipe
I want to add a new fragment everytime I swype right on the last fragment or left on the first one, dynamically. This fragment will be add to my adapater that will be set to my viewPager. Right now I have a static number of fragments defined in the setupViewPager and they "load" in the OnCreate method. Here is my code:</p>

```<code>import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.support.android.designlibdemo.Diafragment;
import com.support.android.designlibdemo.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    private ViewPager viewPager;

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        viewPager = findViewById(R.id.viewpager);
        if (viewPager != null) {
            setupViewPager(viewPager);
        }

        Intent intent = getIntent();
        String nome = intent.getStringExtra("nome");

        View headerView = navigationView.getHeaderView(0);
        TextView navUsername = headerView.findViewById(R.id.tv_drawerUsername);
        navUsername.setText(nome);

        TabLayout tabLayout = findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {

        SimpleDateFormat sdf = new SimpleDateFormat("EEE");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        date = calendar.getTime();

        String day = sdf.format(date);

        Adapter adapter = new Adapter(getSupportFragmentManager());
        adapter.addFragment(new Diafragment(), day);

        calendar.add(Calendar.DATE, 1);
        date = calendar.getTime();
        String dayplusone = sdf.format(date);
        adapter.addFragment(new Diafragment(), dayplusone);

        calendar.add(Calendar.DATE, 1);
        date = calendar.getTime();
        String dayplustwo = sdf.format(date);
        adapter.addFragment(new Diafragment(), dayplustwo);

        viewPager.setAdapter(adapter);
    }

    static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

        public Adapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }
}
</code>```

答: Just extend ViewPager and override onInterceptTouchEvent() like shown in here https://stackoverflow.com/a/13347008/2000083</p>

Title: add new fragment on pageview swipe

Body:
I want to add a new fragment everytime I swype right on the last fragment or left on the first one, dynamically. This fragment will be add to my adapater that will be set to my viewPager. Right now I have a static number of fragments defined in the setupViewPager and they "load" in the OnCreate method. Here is my code:

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.support.android.designlibdemo.Diafragment;
import com.support.android.designlibdemo.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    private ViewPager viewPager;

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        viewPager = findViewById(R.id.viewpager);
        if (viewPager != null) {
            setupViewPager(viewPager);
        }

        Intent intent = getIntent();
        String nome = intent.getStringExtra("nome");

        View headerView = navigationView.getHeaderView(0);
        TextView navUsername = headerView.findViewById(R.id.tv_drawerUsername);
        navUsername.setText(nome);

        TabLayout tabLayout = findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {

        SimpleDateFormat sdf = new SimpleDateFormat("EEE");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        date = calendar.getTime();

        String day = sdf.format(date);

        Adapter adapter = new Adapter(getSupportFragmentManager());
        adapter.addFragment(new Diafragment(), day);

        calendar.add(Calendar.DATE, 1);
        date = calendar.getTime();
        String dayplusone = sdf.format(date);
        adapter.addFragment(new Diafragment(), dayplusone);

        calendar.add(Calendar.DATE, 1);
        date = calendar.getTime();
        String dayplustwo = sdf.format(date);
        adapter.addFragment(new Diafragment(), dayplustwo);

        viewPager.setAdapter(adapter);
    }

    static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

        public Adapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }
}


问:
C++ Searching for a word in a CSV file
I am trying to create a program that stores data from a CSV file and then searches it for key words.
I have this code, and there are no errors shown, but it wont run the program past asking for 'Enter word: '</p>

```<code>#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>

using namespace std;

int main(){

    vector<string> student(860);
    vector<string> question(860);
    vector<string> answer(860);

    int count = 0;
    string word;

    ifstream file("data2.csv");

    if (!file.is_open())
        cerr << "File not found" << endl;

    while (file.good()){

        for (int i = 0; i < 860; i++){

            getline(file, student[i], ',');
            getline(file, question[i], ',');
            getline(file, answer[i], ',');
        }
    }

    cout << "Enter word: ";
    cin >> word;

    for (int j = 0; j < 860; j++){
        if (answer[j].find(word) != std::string::npos){
            cout << student[j] << question[j] << answer[j] << endl;
            count++;
        }
    }

    cout << count;

    return 0;
}
</code>```

答:
the error is in getline, the first call to it, extracts the word until the comma the second call until the 2nd comma, the 3r call to third comma past the to the next new line (the next student's name).

So the next iteration in the getline call, will fetch the question as the students name then the answer as the question then the next students name as the answer, a total mess!!! ;) So you will never find the word you are looking for, thus no result. Get it?

to fix this, try to change the last getline to getline(file, answer[i]);

Title: C++ Searching for a word in a CSV file

Body:
I am trying to create a program that stores data from a CSV file and then searches it for key words.
I have this code, and there are no errors shown, but it wont run the program past asking for 'Enter word: '

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>

using namespace std;

int main(){

    vector<string> student(860);
    vector<string> question(860);
    vector<string> answer(860);

    int count = 0;
    string word;

    ifstream file("data2.csv");

    if (!file.is_open())
        cerr << "File not found" << endl;

    while (file.good()){

        for (int i = 0; i < 860; i++){

            getline(file, student[i], ',');
            getline(file, question[i], ',');
            getline(file, answer[i], ',');
        }
    }

    cout << "Enter word: ";
    cin >> word;

    for (int j = 0; j < 860; j++){
        if (answer[j].find(word) != std::string::npos){
            cout << student[j] << question[j] << answer[j] << endl;
            count++;
        }
    }

    cout << count;

    return 0;
}


问:
Make the banner image scale proportionately with the available space in the viewport
I have a banner 900px width and 150px height, if I make the screen smaller then 900px using google chrome, I want it to adjust automatically, like scaling proportionately.
This is the code I am using:

```<code><meta name="viewport" content="width=device-width, initial-scale=1"> .........some other code......

.banner {
  background: silver;
  padding: 20px 0;
  max-width: 100%;
  overflow: auto;
}
</code>```

What would be the suggestions to achieve what I am seeking?

答:
What does it do right now?

Try: width: 100%; max-width: 900px

Body:
I have a banner 900px width and 150px height, if I make the screen smaller then 900px using google chrome, I want it to adjust automatically, like scaling proportionately.
This is the code I am using:

<meta name="viewport" content="width=device-width, initial-scale=1"> .........some other code......

.banner {
  background: silver;
  padding: 20px 0;
  max-width: 100%;
  overflow: auto;
}

What would be the suggestions to achieve what I am seeking?