问:
Adding 2 bcd numbers-mips
I'm trying to add 2 numbers that are stored in 2 registers. each number is in bcd format and has 8 digits.
I'm wondering if I have a better way then just work on every 4 bits at a time.

This is what I started:

```<code>.text

main:
    addi $s2,$zero,00010010001101000101011001111000#num1
    addi $s3,$zero,00010100011110000101001000110110#num2

    addi $t0,$zero,00000000000000000000000000001111#mask

    and $t1,$t0,$s2#geting digit#1 of num1
    and $t2,$t0,$s3#geting digit#2 of num2

    add $t3,$t1,$t2#adding digits
    #checking for overflow
    #doing the same for the rest of the digits

    #add $s4,$s3,$s2
</code>```

答:
The relevant Wikipedia page has an algorithm for packed BCD addition:

uint32_t BCDadd(uint32_t a,uint32_t b)
{
    uint32_t  t1, t2;    // unsigned 32-bit intermediate values

    t1 = a + 0x06666666;
    t2 = t1 ^ b;                   // sum without carry propagation
    t1 = t1 + b;                   // provisional sum
    t2 = t1 ^ t2;                  // all the binary carry bits
    t2 = ~t2 & 0x11111110;         // just the BCD carry bits
    t2 = (t2 >> 2) | (t2 >> 3);    // correction
    return t1 - t2;                // corrected BCD sum
}
```

This should be straight-forward to translate into MIPS assembly.

Title: Adding 2 bcd numbers-mips

Body:
I'm trying to add 2 numbers that are stored in 2 registers. each number is in bcd format and has 8 digits.
I'm wondering if I have a better way then just work on every 4 bits at a time.

This is what I started:

.text

main:
    addi $s2,$zero,00010010001101000101011001111000#num1
    addi $s3,$zero,00010100011110000101001000110110#num2

    addi $t0,$zero,00000000000000000000000000001111#mask

    and $t1,$t0,$s2#geting digit#1 of num1
    and $t2,$t0,$s3#geting digit#2 of num2

    add $t3,$t1,$t2#adding digits
    #checking for overflow
    #doing the same for the rest of the digits

    #add $s4,$s3,$s2

Body:
The relevant Wikipedia page has an algorithm for packed BCD addition:

uint32_t BCDadd(uint32_t a,uint32_t b)
{
    uint32_t  t1, t2;    // unsigned 32-bit intermediate values

    t1 = a + 0x06666666;
    t2 = t1 ^ b;                   // sum without carry propagation
    t1 = t1 + b;                   // provisional sum
    t2 = t1 ^ t2;                  // all the binary carry bits
    t2 = ~t2 & 0x11111110;         // just the BCD carry bits
    t2 = (t2 >> 2) | (t2 >> 3);    // correction
    return t1 - t2;                // corrected BCD sum
}

This should be straight-forward to translate into MIPS assembly.


来源: stackexchange

问:
How can I have this program add the user input into my linked list?
```<code>import java.util.*;

public class TestClass {
static String name;
static String gender;
static String hairColor;

TestClass(String name, String gender, String hairColor){
    this.name=name;
    this.gender=gender;
    this.hairColor=hairColor;

}
public static void main (String[]args) {
    TestClass info = new TestClass(name, gender, hairColor);
    LinkedList<TestClass> linky = new LinkedList<TestClass>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    name=input.nextLine();

    System.out.println("Enter gender ");
    gender=input.nextLine();

    System.out.println("Enter hair color ");
    hairColor=input.nextLine();

    }

}
</code>```

I want to add user input into the linked list but I can't figure out how to. I have tried to use linky.add(name); but that gives an error. How can I add input into the linked list?

答:
You need to add new instance of TestClass to LinkedList like that:

```<code>public static void main(String[] args) {
    LinkedList<TestClass> list = new LinkedList<>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    String name = input.nextLine();

    System.out.println("Enter gender ");
    String gender = input.nextLine();

    System.out.println("Enter hair color ");
    String hairColor = input.nextLine();

    list.add(new TestClass(name, gender, hairColor));
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
import java.util.*;

public class TestClass {
static String name;
static String gender;
static String hairColor;

TestClass(String name, String gender, String hairColor){
    this.name=name;
    this.gender=gender;
    this.hairColor=hairColor;

}
public static void main (String[]args) {
    TestClass info = new TestClass(name, gender, hairColor);
    LinkedList<TestClass> linky = new LinkedList<TestClass>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    name=input.nextLine();

    System.out.println("Enter gender ");
    gender=input.nextLine();

    System.out.println("Enter hair color ");
    hairColor=input.nextLine();

    }

}

I want to add user input into the linked list but I can't figure out how to. I have tried to use linky.add(name); but that gives an error. How can I add input into the linked list?

Body:
You need to add new instance of TestClass to LinkedList like that:

public static void main(String[] args) {
    LinkedList<TestClass> list = new LinkedList<>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    String name = input.nextLine();

    System.out.println("Enter gender ");
    String gender = input.nextLine();

    System.out.println("Enter hair color ");
    String hairColor = input.nextLine();

    list.add(new TestClass(name, gender, hairColor));
}


问:
getting width or height as percentage instead of pixels
I have elements with an external style of height with percentages. when I am trying to save the height as a variable to use, it is saving it as pixels  some times nothing.

html
For example:

```<code><div id='firstDiv'></div>
 <div id='secondDiv'></div>
</code>```

css code

```<code>#firstDiv{
    width:50%;
    height:50%;
}
#secondDiv{
   width:20%;
   height:50%;
}
</code>```

Jquery code

```<code>$('div').each(function (){
   console.log($(this)[0].style.height);
}
</code>```

how can i get it as %?

答: $(this).height() will give height of your divs in percentage(as they have been set in percentage) and will be unit less.

Body:
I have elements with an external style of height with percentages. when I am trying to save the height as a variable to use, it is saving it as pixels  some times nothing.

html
For example:

css code

#firstDiv{
    width:50%;
    height:50%;
}
#secondDiv{
   width:20%;
   height:50%;
}

Jquery code

$('div').each(function (){
   console.log($(this)[0].style.height);
}

how can i get it as %?


问:
How to get the sum of a column up to a certain value?
I have a google sheet that I am using to try and calculate leveling and experience points. Column A has the level and Column B has the exp needed to reach the next level. i.e. To get to Level 3 you need 600 exp.

A   B

1   200

2   400

3   600

...

99   19800

In column I2 I have an integer for an amount of exp (e.g. 2000), in column J2 I want to figure out what level someone would be at if they started from 0.

答:
Put this in column J and ddrag down as required. Rounddown(I2,-2) rounds I2 down to the nearest 100. Index match finds a match in column B and returns the value in column A of the matched row.</p>

```<code>=index(A2:A100,match(ROUNDDOWN(I2,-2),B2:B100,0))
</code>```

Body:
Put this in column J and ddrag down as required. Rounddown(I2,-2) rounds I2 down to the nearest 100. Index match finds a match in column B and returns the value in column A of the matched row.

=index(A2:A100,match(ROUNDDOWN(I2,-2),B2:B100,0))


问:
Using pypdfocr library from within a Python script
How can you run pypdfocr from within a Python script, as opposed to the command line?

This question How to call pypdfocr functions to use them in a python script? approaches the answer I want, but doesn't quite get there.

```<code>import pypdfocr
from pypdfocr import pypdfocr
from pypdfocr.pypdfocr import PyPDFOCR as pocr

filepath = 'C:/myfolder/myPDF.pdf'

newfile = pocr.run_conversion(filepath)
</code>```

This throws an error:

```<code>Unbound method  run_conversion must be called with PyPDFOCR instance as first argument.
</code>```

Can someone help me fill in the (likely obvious) missing piece?

答:
The problem is that you are trying to run run_conversion without an object.

run_conversion is a method of the class PyPDFOCR. So you will need an object of that class to run the method.

Once you have made an PyPDFOCR object (for instance my_ocr), you should be able to write:

```<code>newfile = my_ocr.run_conversion(filepath)
</code>```

Body:
How can you run pypdfocr from within a Python script, as opposed to the command line?

This question How to call pypdfocr functions to use them in a python script? approaches the answer I want, but doesn't quite get there.

import pypdfocr
from pypdfocr import pypdfocr
from pypdfocr.pypdfocr import PyPDFOCR as pocr

filepath = 'C:/myfolder/myPDF.pdf'

newfile = pocr.run_conversion(filepath)

This throws an error:

Unbound method  run_conversion must be called with PyPDFOCR instance as first argument.

Can someone help me fill in the (likely obvious) missing piece?

Body:
The problem is that you are trying to run run_conversion without an object.

run_conversion is a method of the class PyPDFOCR. So you will need an object of that class to run the method.

Once you have made an PyPDFOCR object (for instance my_ocr), you should be able to write:

newfile = my_ocr.run_conversion(filepath)


问:
Add a vertical label to matplotlib colormap legend
This code enables me to plot a colormap of a "3d" array [X,Y,Z] (they are 3 simple np.array of elements). But I can't succeed in adding a vertical written label at the right of the colorbar legend.

```<code>import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure("Color MAP 2D+")

contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")

plt.xlabel("X")
plt.ylabel("Y")
plt.title("Color MAP 2D+")

#Legend
def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)
import matplotlib.ticker as ticker
plt.colorbar(contour, format=ticker.FuncFormatter(fmt))

plt.show()
</code>```

It's anoying to not get an easy answer from google... can someone help me ?

答:
You are looking to add a label to the colorbar object. Thankfully, colorbar has a set_label function.

in short:

```<code>cbar = plt.colorbar(contour, format=ticker.FuncFormatter(fmt))
cbar.set_label('your label here')
</code>```

In a minimal script:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

X = np.random.uniform(-2, 2, 200)
Y = np.random.uniform(-2, 2, 200)
Z = X*np.exp(-X**2 - Y**2)

contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")

def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)

cbar = plt.colorbar(contour, format=ticker.FuncFormatter(fmt))
cbar.set_label('your label here')

plt.show()
</code>```

Body:
This code enables me to plot a colormap of a "3d" array [X,Y,Z] (they are 3 simple np.array of elements). But I can't succeed in adding a vertical written label at the right of the colorbar legend.

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure("Color MAP 2D+")

contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")

plt.xlabel("X")
plt.ylabel("Y")
plt.title("Color MAP 2D+")

#Legend
def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)
import matplotlib.ticker as ticker
plt.colorbar(contour, format=ticker.FuncFormatter(fmt))

plt.show()

It's anoying to not get an easy answer from google... can someone help me ?

Body:
You are looking to add a label to the colorbar object. Thankfully, colorbar has a set_label function.

in short:

cbar = plt.colorbar(contour, format=ticker.FuncFormatter(fmt))
cbar.set_label('your label here')

In a minimal script:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

X = np.random.uniform(-2, 2, 200)
Y = np.random.uniform(-2, 2, 200)
Z = X*np.exp(-X**2 - Y**2)

contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")

def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)

cbar = plt.colorbar(contour, format=ticker.FuncFormatter(fmt))
cbar.set_label('your label here')

plt.show()


问:
MongoDB -moving from localhost to cluster using URI
I currently have a MongoDB based API that's running on a local version of the server, as is default.

I want to move this over so that the interaction is happening with my online server, for which i have a login and URI string.

Where to do I put this?

I'm using SpringBoot in STS if that makes any difference.

答:
You must have added server location somewhere in your code like this

mongodb://localhost:27017

Here, replace localhost with your server IP and port, that's it!


问:
How can i simplify these if-statements?
How can I simplify this and make it still do the same thing?

```<code>package test;

import java.util.Scanner;

public class HI {public static void main(String[] args) {
    String Welcome1 = "Welcome";
    String specialWelcome1 = "Welcome Parzival";
    String joinLogin1 = "What would you like to do?";
    System.out.println(Welcome1);
    System.out.println("Insert your name below");
    Scanner scan = new Scanner(System.in);
    String Person = scan.nextLine();
    if (Person.equals("Parzival")) {
        System.out.println(specialWelcome1);
        System.out.println(joinLogin1);
        String doing1 = scan.nextLine();
        if(doing1.equals("Kill")) {
            System.out.println("What is the password?");
            String killCode = scan.nextLine();
            if(killCode.equals("OASIS kill")){
                System.out.println("Shutting down...");
            }
        if(doing1.equals("Join Game")) {
            System.out.println("Joining...");
        }
        }
}else {
            System.out.println(Welcome1 + " " + Person);
}}}
</code>```

The code looks messy and it is hard to read. I don't know how to fix that.

答:
One thing that seems obvious is that you cannot reduce the number of String messages.
However, you can still remove the clutter by replacing consecutive System.out.println statements with a single System.out.println statement as follows :

Your code :

System.out.println(specialWelcome1);

  System.out.println(joinLogin1);

Formatted code :

System.out.println(specialWelcome1 +"\n"+joinLogin1);

The above formatted code can look ugly for cases where there are many more System.out.println statements.In that case you can make good use of indentations as follows:

```<code>> System.out.println(specialWelcome1
>               +"\n"+joinLogin1
>               +"\n"+joinLogin2
>               +"\n"+joinLogin3
>               +"\n"+joinLogin4
>               +"\n"+joinLogin5
>               +"\n"+joinLogin6
>               +"\n"+joinLogin7
>               );
</code>```

Also, the switch version by Suchen Oguri  is better. You should prefer switch statements over if-else as they are better performance-wise. The if-else will go on checking conditions one-by-one until it finds one that matches, which is not the case with switch statements.

Title: How can i simplify these if-statements?

Body:
How can I simplify this and make it still do the same thing?

package test;

import java.util.Scanner;

public class HI {public static void main(String[] args) {
    String Welcome1 = "Welcome";
    String specialWelcome1 = "Welcome Parzival";
    String joinLogin1 = "What would you like to do?";
    System.out.println(Welcome1);
    System.out.println("Insert your name below");
    Scanner scan = new Scanner(System.in);
    String Person = scan.nextLine();
    if (Person.equals("Parzival")) {
        System.out.println(specialWelcome1);
        System.out.println(joinLogin1);
        String doing1 = scan.nextLine();
        if(doing1.equals("Kill")) {
            System.out.println("What is the password?");
            String killCode = scan.nextLine();
            if(killCode.equals("OASIS kill")){
                System.out.println("Shutting down...");
            }
        if(doing1.equals("Join Game")) {
            System.out.println("Joining...");
        }
        }
}else {
            System.out.println(Welcome1 + " " + Person);
}}}

The code looks messy and it is hard to read. I don't know how to fix that.

Body:
One thing that seems obvious is that you cannot reduce the number of String messages.
However, you can still remove the clutter by replacing consecutive System.out.println statements with a single System.out.println statement as follows :

Your code :

System.out.println(specialWelcome1);

  System.out.println(joinLogin1);

Formatted code :

System.out.println(specialWelcome1 +"\n"+joinLogin1);

The above formatted code can look ugly for cases where there are many more System.out.println statements.In that case you can make good use of indentations as follows:

> System.out.println(specialWelcome1
>               +"\n"+joinLogin1
>               +"\n"+joinLogin2
>               +"\n"+joinLogin3
>               +"\n"+joinLogin4
>               +"\n"+joinLogin5
>               +"\n"+joinLogin6
>               +"\n"+joinLogin7
>               );

Also, the switch version by Suchen Oguri  is better. You should prefer switch statements over if-else as they are better performance-wise. The if-else will go on checking conditions one-by-one until it finds one that matches, which is not the case with switch statements.


问:
dax code for count and distinct count measures (or calculated columns)
I hope somebody can help me with some hints for the following analysis. The students may do some actions for some courses (enroll, join, grant,...) and also the reverse - to cancel the latest action.
The first metric is to count all the action occurred in the system between two dates - these are exposed like a filter/slicer.
Some sample data :

```<code>person-id,person-name,course-name,event,event-rank,startDT,stopDT
11, John, CS101, enrol,1,2000-01-01,2000-03-31
11, John, CS101, grant,2,2000-04-01,2000-04-30
11, John, CS101, cancel,3,2000-04-01,2000-04-30
11, John, PHIL, enrol, 1, 2000-02-01,2000-03-31
11, John, PHIL, grant, 2, 2000-04-01,2000-04-30
</code>```

The data set (ds) is above and I have added the following code for the count metric:

```<code>       evaluate
 sumx(
   addcolumns( ds
        ,"z+", if([event] <> "cancel",1,0)
        ,"z-", if([event] = "cancel",-1,0)
        )
    ,[z+] + [z-])
  }
</code>```

The metric should display : 3 subscriptions (John-CS101 = 1 , John-PHIL=2).

There are some other rules but I don't know how to add them to the DAX code, the cancel date is the same as the above action (non-cancel) and the rank of the cancel-action = the non-cancel-action + 1.

Also there is a need for adding the number for distinct student and course, the composite key . How to add this to the code, please ? (via summarize, rankx)

Regards,
Q

答:
This isn't technically an answer, but more of a recommendation.

It sounds like your challenge is that you have actions that may then be cancelled. There is specific logic that determines whether an action is cancelled or not (i.e. the cancellation has to be the immediate next row and the dates must match).

What I would recommend, which doesn't answer your specific question, is to adjust your data model rather than put the cancellation logic in DAX.

For example, if you could add a column to your data model that flags a row as subsequently cancelled, then all DAX has to do is check that flag to know if an action is cancelled or not. A CALCULATE statement. You don't have to have lots of logic to determine whether the event was cancelled. You entirely eliminate the need for SUMX, which can be slow when working with a lot of rows since it works row by row.

The logic for whether an action is cancelled or not moves to your source system (e.g. SQL or even a calculated column in Excel), or to your ETL (e.g. the Query Editor in Power BI) which are better equipped for such tasks. The logic is applied 1 time and then exists in your data model for all measures, instead of needing to apply the logic each time a measure is used.

I know this doesn't help you solve your logic question, but the reason I make this recommendation is that DAX is fundamentally a giant calculator. It adds things up. It's great at filters (adding some things up but not others), but it works best when everything is reduced to columns that it can sum or count. Once you go beyond that (e.g. wanting to look at the row below to adjust something about the current row), your DAX is going to get very complicated (and slow), whereas a source system or the Query Editor will likely be able to handle such requirements more easily.

Body:
I hope somebody can help me with some hints for the following analysis. The students may do some actions for some courses (enroll, join, grant,...) and also the reverse - to cancel the latest action.
The first metric is to count all the action occurred in the system between two dates - these are exposed like a filter/slicer.
Some sample data :

person-id,person-name,course-name,event,event-rank,startDT,stopDT
11, John, CS101, enrol,1,2000-01-01,2000-03-31
11, John, CS101, grant,2,2000-04-01,2000-04-30
11, John, CS101, cancel,3,2000-04-01,2000-04-30
11, John, PHIL, enrol, 1, 2000-02-01,2000-03-31
11, John, PHIL, grant, 2, 2000-04-01,2000-04-30

The data set (ds) is above and I have added the following code for the count metric:

       evaluate
 sumx(
   addcolumns( ds
        ,"z+", if([event] <> "cancel",1,0)
        ,"z-", if([event] = "cancel",-1,0)
        )
    ,[z+] + [z-])
  }

The metric should display : 3 subscriptions (John-CS101 = 1 , John-PHIL=2).

There are some other rules but I don't know how to add them to the DAX code, the cancel date is the same as the above action (non-cancel) and the rank of the cancel-action = the non-cancel-action + 1.

Also there is a need for adding the number for distinct student and course, the composite key . How to add this to the code, please ? (via summarize, rankx)

Regards,
Q


问:
What is the best way to disable horizontal scroll of UIScrollView?
In UIScrollView, I have content height and width greater than scrollview's size. So basically it can scroll horizontally and vertically. What I want is to scroll vertically only and I manage horizontally scroll using an UIButton by using below code.

```<code> [scrlViewQuestion setContentOffset:CGPointMake(questionWidth, 0) animated:YES];
</code>```

Preventing horizontal scrollview, one can just set scrollview content width lesser than scrollview size but in my case scrollview content width is greater than its size? So what is the best way to solve this?

答:
Set the contentSize of your scrollview to the width of your screen and the actual height of your scrollable content. Set the contentInset to zero for the top, bottom, and right. For the content inset on the left always choose the negated x coordinate of the position you currently want to display.

E.g. if your screen is 320 points wide, and you want to display content with horizontal scrolling fixed at x, but vertical scrolling allowed:

```<code>CGFloat screenWidth = 320.0;
CGSize actualContentSize = CGSizeMake(3000, 3000);

[scrlViewQuestion setContentSize:CGSizeMake(screenWidth, actualContentSize.height)];
[scrlViewQuestion setContentInset:UIEdgeInsetsMake(0, -x, 0, 0)];
</code>```

Body:
In UIScrollView, I have content height and width greater than scrollview's size. So basically it can scroll horizontally and vertically. What I want is to scroll vertically only and I manage horizontally scroll using an UIButton by using below code.

 [scrlViewQuestion setContentOffset:CGPointMake(questionWidth, 0) animated:YES];

Preventing horizontal scrollview, one can just set scrollview content width lesser than scrollview size but in my case scrollview content width is greater than its size? So what is the best way to solve this?

Body:
Set the contentSize of your scrollview to the width of your screen and the actual height of your scrollable content. Set the contentInset to zero for the top, bottom, and right. For the content inset on the left always choose the negated x coordinate of the position you currently want to display.

E.g. if your screen is 320 points wide, and you want to display content with horizontal scrolling fixed at x, but vertical scrolling allowed:

CGFloat screenWidth = 320.0;
CGSize actualContentSize = CGSizeMake(3000, 3000);

[scrlViewQuestion setContentSize:CGSizeMake(screenWidth, actualContentSize.height)];
[scrlViewQuestion setContentInset:UIEdgeInsetsMake(0, -x, 0, 0)];


问:
search an array of Object
Hi I'm trying to create a GUI program that allows the user to search for a certain student using either ID or
name (assume they are both unique) from a student database and then display the information such as name, id , gpa.

like if i search using the name or the id the student info should be display on the lower part of the gui program where the JLabel (student info)

a sample of the student database file

```<code>12345 Mark 3.6
72305 Sam 2.8
12945 Chris 3.1
18325 John 2.5
52341 Drake 2.7
98475 Sara 3.8
24536 Robin 3.1
34765 Ted 3.6
23845 Kelly 3.1
</code>```

i couldn't get why I'm getting an error when searching by name or id?
also how can i display student info after searching ?

and yes i'm using to different searching methods one for the Name and the other for the ID

here's my code

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

 public class GUIProgram extends JFrame implements ActionListener {

JLabel name, id, stInfo;
JButton clearBtn, searchName, searchID;
JTextField nameTxt, idTxt, nameInfo, idInfo, gpaInfo;
int i ;
String n;
public static void main(String[] args) {
    new GUIProgram();
}

public GUIProgram(){
    super("GUIProgram");
    setTitle("Student Database");
    setLayout(new FlowLayout());
    setSize(480, 200);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    JPanel searchPanel = new JPanel(new FlowLayout());
    name = new JLabel("Name: ");
    nameTxt = new JTextField(10);
    id = new JLabel("ID: ");
    idTxt = new JTextField(10);
    clearBtn = new JButton("Clear");
    clearBtn.addActionListener(this);

    searchPanel.add(name);
    searchPanel.add(nameTxt);
    searchPanel.add(id);
    searchPanel.add(idTxt);
    searchPanel.add(clearBtn);
    add(searchPanel,BorderLayout.NORTH);

    JPanel centerPanel = new JPanel(new FlowLayout());
    searchName = new JButton("Search By Name");
    searchID = new JButton("Search By ID");

    centerPanel.add(searchName);
    centerPanel.add(searchID);
    add(centerPanel,BorderLayout.CENTER);

    JPanel infoPanel = new JPanel(new FlowLayout());

    stInfo = new JLabel("Student Info: ");
    nameInfo = new JTextField(10);
    nameInfo.setEditable(false);
    idInfo = new JTextField(10);
    idInfo.setEditable(false);
    gpaInfo = new JTextField(10);
    gpaInfo.setEditable(false);

    infoPanel.add(stInfo);
    infoPanel.add(nameInfo);
    infoPanel.add(idInfo);
    infoPanel.add(gpaInfo);

    add(infoPanel,BorderLayout.SOUTH);

    searchID.addActionListener(this);
    searchName.addActionListener(this);

    setVisible(true);

}

public void actionPerformed(ActionEvent ae) {
    Object source = ae.getSource();
    if (source == clearBtn);
    nameTxt.setText("");
    idTxt.setText("");

    try{
        Scanner file = new Scanner(new File("StudentDB.txt"));

        ArrayList<Integer> id = new ArrayList<Integer>();
        ArrayList<String> name = new ArrayList<String>();
        ArrayList<Double> gpa = new ArrayList<Double>();

        while(file.hasNext()){
            id.add(file.nextInt());
            name.add(file.next());
            gpa.add(file.nextDouble());
        }

        Student [] stList = new Student[9];
        for(int i = 0; i < name.size(); i++){
            stList[i] = new Student(id.get(i), name.get(i), gpa.get(i));
        }

        n = nameTxt.getText();
        i = Integer.parseInt(idTxt.getText());
        try {

            if(source == searchName){
                linearSearch(stList, n);

            }
            else if(source == searchID){
                binarySearch(stList, i);
            }
        }catch(InputMismatchException e){
            JOptionPane.showMessageDialog(null, "Input Mismatch Exception");
        }

    }catch(InputMismatchException | FileNotFoundException e){
        JOptionPane.showMessageDialog(null, "Input Mismatch Exception");
    }

}

/*static final int NONE = -1; // not a legal index
static int linearSearch(int id, Student[] a) {
for (int i = 0; i < a.length; i++) {
    if (id == a[i])
return i;
}
return NONE;
}*/

static final int NONE = -1;  // not a legal index
static int linearSearch(Student[] a, String name) {
    for (int p = 0; p < a.length; p++) {
        if (name.equals(a[p]))

            return p;
        }
    return NONE;
    }

public static int binarySearch(Student[] a, int x) {
    int low = 0;
    int high = a.length - 1;
    int mid;

    while (low <= high) {
        mid = (low + high) / 2;

        if (a[mid].compareTo(x) < 0) {
            low = mid + 1;
        } else if (a[mid].compareTo(x) > 0) {
            high = mid - 1;
        } else {
            return mid;
        }
    }

    return -1;
}

class Student implements Comparable{
     int iDNumber;
     String name;
     double gpa;

    public Student(int iDNumber, String name, double gpa){
        this.iDNumber = iDNumber;
        this.name = name;
        this.gpa = gpa;
    }
    public int getiDNumber() {
        return iDNumber;
    }
    public void setiDNumber(int newId) {
        this.iDNumber = newId;
    }
    public void setGpa(double newGpa) {
        this.gpa = newGpa;
    }
    public void setName(String newName) {
        this.name = newName;
    }
    public String getName() {
        return name;
    }
    public double getGPA() {
        return gpa;
    }

    public String toString(){
        return iDNumber+"\t"+name+"\t"+gpa;
    }

    public int compareTo(Object o) {
        if(o == null) {
            throw new NullPointerException();
            }
        else if(o.getClass()!= getClass()) {
                throw new ClassCastException();
            }
        else if(o.getClass()== getClass()) {
                Student st = (Student) o;
                return iDNumber - st.getiDNumber();
            }
            else {

                Student st = (Student) o;
                return (int) (gpa - st.getGPA());
        }
    }

} // end of st

class ComparatorId implements Comparator {
    public int compare(Object o1, Object o2) {
        if(o1 == null | o2 == null)
            throw new NullPointerException();
        else {
            if(!(o1 instanceof Student) | !(o2 instanceof Student))
                throw new ClassCastException();
            else {
                Student st1 = (Student) o1;
                Student st2 = (Student) o2;
                return st1.getiDNumber() - st2.getiDNumber();
            }
        }
    }
} // End of ComparatorId class

class ComparatorGPA implements Comparator {
    public int compare(Object o1, Object o2) {

        if(o1 == null | o2 == null)
            throw new NullPointerException();
        else {
            if(!(o1 instanceof Student) | !(o2 instanceof Student))
                throw new ClassCastException();
            else {
                Student st1 = (Student) o1;
                Student st2 = (Student) o2;
                return Double.compare(st1.getGPA(), st2.getGPA());

        //  return ((Student) o1).getGPA().compareTo2((Student) o2).getGPA()));
         // return (int)(((Student) o1).getGPA()).compareTo2((Double)o1.getGPA());
    }
        }
    }
} // End of ComparatorGPA class

class ComparatorName implements Comparator {
    public int compare(Object o1, Object o2) {
        return ((Student) o1).getName().compareTo(((Student) o2).getName());

    }
}// End of ComparatorName class
}
</code>```

the program looks like this

答:
There are a few problems with the code you have written, mainly just small bugs.

The item that is giving you the error is the line i=Integer.parseInt(idTxt.getText()); as this line tries to get whatever is in the idTxt box and convert it to an int. This works fine if you put in a number there but when you do not and only want to search by name it leaves it blank or "". It tries to parse that empty string since you parse it before checking if the action source is equal to searchID. If you do the parsing once you know there is a number in the Text field you will not get the error.
EG:

```<code>if(source == searchID){
   i=Integer.parseInt(idTxt.getText());
}
</code>```

Also, in your LinearSearch method you are doing name.equals(a[p]) you are seeing if a String object is equal to a Student object. You could instead do something like name.compareTo(a[p].getName()) which would directly compare the two Strings to see if they are equal.

Finally, you are using a binary search of the Student ID which you could use if you first sort the Student Array because binary search only works on sorted Arrays. I would just use an overloaded version of your LinearSearch method that takes an int and compares against the id in the Student object.

Title: search an array of Object

Body:
Hi I'm trying to create a GUI program that allows the user to search for a certain student using either ID or
name (assume they are both unique) from a student database and then display the information such as name, id , gpa.

like if i search using the name or the id the student info should be display on the lower part of the gui program where the JLabel (student info)

a sample of the student database file

12345 Mark 3.6
72305 Sam 2.8
12945 Chris 3.1
18325 John 2.5
52341 Drake 2.7
98475 Sara 3.8
24536 Robin 3.1
34765 Ted 3.6
23845 Kelly 3.1

i couldn't get why I'm getting an error when searching by name or id?
also how can i display student info after searching ?

and yes i'm using to different searching methods one for the Name and the other for the ID

here's my code

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

 public class GUIProgram extends JFrame implements ActionListener {

JLabel name, id, stInfo;
JButton clearBtn, searchName, searchID;
JTextField nameTxt, idTxt, nameInfo, idInfo, gpaInfo;
int i ;
String n;
public static void main(String[] args) {
    new GUIProgram();
}

public GUIProgram(){
    super("GUIProgram");
    setTitle("Student Database");
    setLayout(new FlowLayout());
    setSize(480, 200);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    JPanel searchPanel = new JPanel(new FlowLayout());
    name = new JLabel("Name: ");
    nameTxt = new JTextField(10);
    id = new JLabel("ID: ");
    idTxt = new JTextField(10);
    clearBtn = new JButton("Clear");
    clearBtn.addActionListener(this);

    searchPanel.add(name);
    searchPanel.add(nameTxt);
    searchPanel.add(id);
    searchPanel.add(idTxt);
    searchPanel.add(clearBtn);
    add(searchPanel,BorderLayout.NORTH);

    JPanel centerPanel = new JPanel(new FlowLayout());
    searchName = new JButton("Search By Name");
    searchID = new JButton("Search By ID");

    centerPanel.add(searchName);
    centerPanel.add(searchID);
    add(centerPanel,BorderLayout.CENTER);

    JPanel infoPanel = new JPanel(new FlowLayout());

    stInfo = new JLabel("Student Info: ");
    nameInfo = new JTextField(10);
    nameInfo.setEditable(false);
    idInfo = new JTextField(10);
    idInfo.setEditable(false);
    gpaInfo = new JTextField(10);
    gpaInfo.setEditable(false);

    infoPanel.add(stInfo);
    infoPanel.add(nameInfo);
    infoPanel.add(idInfo);
    infoPanel.add(gpaInfo);

    add(infoPanel,BorderLayout.SOUTH);

    searchID.addActionListener(this);
    searchName.addActionListener(this);

    setVisible(true);

}

public void actionPerformed(ActionEvent ae) {
    Object source = ae.getSource();
    if (source == clearBtn);
    nameTxt.setText("");
    idTxt.setText("");

    try{
        Scanner file = new Scanner(new File("StudentDB.txt"));

        ArrayList<Integer> id = new ArrayList<Integer>();
        ArrayList<String> name = new ArrayList<String>();
        ArrayList<Double> gpa = new ArrayList<Double>();

        while(file.hasNext()){
            id.add(file.nextInt());
            name.add(file.next());
            gpa.add(file.nextDouble());
        }

        Student [] stList = new Student[9];
        for(int i = 0; i < name.size(); i++){
            stList[i] = new Student(id.get(i), name.get(i), gpa.get(i));
        }

        n = nameTxt.getText();
        i = Integer.parseInt(idTxt.getText());
        try {

            if(source == searchName){
                linearSearch(stList, n);

            }
            else if(source == searchID){
                binarySearch(stList, i);
            }
        }catch(InputMismatchException e){
            JOptionPane.showMessageDialog(null, "Input Mismatch Exception");
        }

    }catch(InputMismatchException | FileNotFoundException e){
        JOptionPane.showMessageDialog(null, "Input Mismatch Exception");
    }

}

/*static final int NONE = -1; // not a legal index
static int linearSearch(int id, Student[] a) {
for (int i = 0; i < a.length; i++) {
    if (id == a[i])
return i;
}
return NONE;
}*/

static final int NONE = -1;  // not a legal index
static int linearSearch(Student[] a, String name) {
    for (int p = 0; p < a.length; p++) {
        if (name.equals(a[p]))

            return p;
        }
    return NONE;
    }

public static int binarySearch(Student[] a, int x) {
    int low = 0;
    int high = a.length - 1;
    int mid;

    while (low <= high) {
        mid = (low + high) / 2;

        if (a[mid].compareTo(x) < 0) {
            low = mid + 1;
        } else if (a[mid].compareTo(x) > 0) {
            high = mid - 1;
        } else {
            return mid;
        }
    }

    return -1;
}

class Student implements Comparable{
     int iDNumber;
     String name;
     double gpa;

    public Student(int iDNumber, String name, double gpa){
        this.iDNumber = iDNumber;
        this.name = name;
        this.gpa = gpa;
    }
    public int getiDNumber() {
        return iDNumber;
    }
    public void setiDNumber(int newId) {
        this.iDNumber = newId;
    }
    public void setGpa(double newGpa) {
        this.gpa = newGpa;
    }
    public void setName(String newName) {
        this.name = newName;
    }
    public String getName() {
        return name;
    }
    public double getGPA() {
        return gpa;
    }

    public String toString(){
        return iDNumber+"\t"+name+"\t"+gpa;
    }

    public int compareTo(Object o) {
        if(o == null) {
            throw new NullPointerException();
            }
        else if(o.getClass()!= getClass()) {
                throw new ClassCastException();
            }
        else if(o.getClass()== getClass()) {
                Student st = (Student) o;
                return iDNumber - st.getiDNumber();
            }
            else {

                Student st = (Student) o;
                return (int) (gpa - st.getGPA());
        }
    }

} // end of st

class ComparatorId implements Comparator {
    public int compare(Object o1, Object o2) {
        if(o1 == null | o2 == null)
            throw new NullPointerException();
        else {
            if(!(o1 instanceof Student) | !(o2 instanceof Student))
                throw new ClassCastException();
            else {
                Student st1 = (Student) o1;
                Student st2 = (Student) o2;
                return st1.getiDNumber() - st2.getiDNumber();
            }
        }
    }
} // End of ComparatorId class

class ComparatorGPA implements Comparator {
    public int compare(Object o1, Object o2) {

        if(o1 == null | o2 == null)
            throw new NullPointerException();
        else {
            if(!(o1 instanceof Student) | !(o2 instanceof Student))
                throw new ClassCastException();
            else {
                Student st1 = (Student) o1;
                Student st2 = (Student) o2;
                return Double.compare(st1.getGPA(), st2.getGPA());

        //  return ((Student) o1).getGPA().compareTo2((Student) o2).getGPA()));
         // return (int)(((Student) o1).getGPA()).compareTo2((Double)o1.getGPA());
    }
        }
    }
} // End of ComparatorGPA class

class ComparatorName implements Comparator {
    public int compare(Object o1, Object o2) {
        return ((Student) o1).getName().compareTo(((Student) o2).getName());

    }
}// End of ComparatorName class
}

the program looks like this

Body:
There are a few problems with the code you have written, mainly just small bugs.

The item that is giving you the error is the line i=Integer.parseInt(idTxt.getText()); as this line tries to get whatever is in the idTxt box and convert it to an int. This works fine if you put in a number there but when you do not and only want to search by name it leaves it blank or "". It tries to parse that empty string since you parse it before checking if the action source is equal to searchID. If you do the parsing once you know there is a number in the Text field you will not get the error.
EG:

if(source == searchID){
   i=Integer.parseInt(idTxt.getText());
}

Also, in your LinearSearch method you are doing name.equals(a[p]) you are seeing if a String object is equal to a Student object. You could instead do something like name.compareTo(a[p].getName()) which would directly compare the two Strings to see if they are equal.

Finally, you are using a binary search of the Student ID which you could use if you first sort the Student Array because binary search only works on sorted Arrays. I would just use an overloaded version of your LinearSearch method that takes an int and compares against the id in the Student object.


问:
Knockout.js reset the value of a select back to its default value when if another select is used
I am working on a Data Table that is populated 1 of 3 ways.
1. Live Search
2. Select box 1 (searchCategory)
3. Select box 2 (searchTCA)

I have everything working except for one issue that I am unable to figure out.

When the user selects one of the options in either select box, I would like the other one to reset to default.

I am still learning knockout, so any help would be greatly appreciated.

Thank You-

Here is my HTML:

```<code> <div class="row">
 <div class="col-sm-12">
     <form id="requestForm" class="request-form form-horizontal">
         <div class="form-group">
             <label for="searchInput" class="col-sm-3 control-label">Search</label>
             <div class="col-sm-9">
                 <input id="searchInput" type="text" name="searchInput" class="form-control" placeholder="What are you looking for?" onfocus="this.value=''" data-bind="textInput: query, valueUpdate: 'keyup'" autocomplete="off" />
             </div>
        </div>
        <div class="form-group">
            <label for="searchCategory" class="col-sm-3 control-label">View by Category</label>
            <div class="col-sm-9">
                <select id="searchCategory" data-bind="options: availableCategories, value: selectedCategory, optionsCaption: 'Search by Category'"></select>
            </div>
        </div>
        <div class="form-group">
            <label for="searchTCA" class="col-sm-3 control-label">View by TCA Method</label>
            <div class="col-sm-9">
                <select id="searchTCA" data-bind="options: availableTcaMethods, value: selectedTcaMethod, optionsCaption: 'Search by TCA Method'"></select>
            </div>
       </div>
   </form>
 </div>
</code>```

Here is the JS:

```<code> define(function (require) {
"use strict";

var $ = require("jquery"),
    ko = require("knockout"),
    komapping = require("komapping"),
    bootstrap = require("bootstrap"),
    $embedElement = $("#Architectural-Guidebook");

if ($embedElement.length) {

    function ArchitecturalGuidebookViewModel(dduration) {
        var self = this;

        self.specifications = ko.observableArray([]);
        debugger;

        self.availableCategories = ko.observable();
        self.selectedCategory = ko.observable();

        self.availableTcaMethods = ko.observable();
        self.selectedTcaMethod = ko.observable();

        self.availableCategories = ko.dependentObservable(function () {
            var types = ko.utils.arrayMap(self.specifications(), function (item) { return item.Category; });
            return ko.utils.arrayGetDistinctValues(types).sort();
        });

        self.availableTcaMethods = ko.dependentObservable(function () {
            var types = ko.utils.arrayMap(self.specifications(), function (item) { return item.TcaMethod; });
            return ko.utils.arrayGetDistinctValues(types).sort();
        });

        self.specifications($.parseJSON(window.jsonModel));

        self.query = ko.observable('What are you looking for?');

        // Search
        self.pageNumber = ko.observable(0);
        self.filterSpecifications = ko.computed(function () {
            self.pageNumber(0);
            return ko.utils.arrayFilter(self.specifications(), function (i) {
                var filterLogic =
                    (i.TcaMethod.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Title.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Category.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Application.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Category === self.selectedCategory() && self.query('What are you looking for?')) ||
                    (i.TcaMethod === self.selectedTcaMethod() && self.query('What are you looking for?'));
                return filterLogic;
            });
        });

        // Pagination
        self.nbPerPage = 8;
        self.totalPages = ko.computed(function () {
            var div = Math.floor(self.filterSpecifications().length / self.nbPerPage);
            div += self.filterSpecifications().length % self.nbPerPage > 0 ? 1 : 0;
            return div - 1;
        });

        self.paginated = ko.computed(function () {
            var first = self.pageNumber() * self.nbPerPage;
            return self.filterSpecifications().slice(first, first +
                      self.nbPerPage);
        });

        self.hasPrevious = ko.computed(function () {
            return self.pageNumber() !== 0;
        });

        self.hasNext = ko.computed(function () {
            return self.pageNumber() !== self.totalPages();
        });

        self.next = function () {
            if (self.pageNumber() < self.totalPages()) {
                self.pageNumber(self.pageNumber() + 1);
            }
        };

        self.previous = function () {
            if (self.pageNumber() !== 0) {
                self.pageNumber(self.pageNumber() - 1);
            }
        };

    };

    ko.applyBindings(new ArchitecturalGuidebookViewModel());

  }

});
</code>```

答:
You can subscribe to the selectedCategory and selectedTcaMethod observables and set the other dropdown's value to undefined when one of them changes.

Also, you are clearing the input's value on focus. This will only clear the input and not query observable's value. So, filterSpecifications computed property doesn't get triggered onfocus even though the input is cleared. Instead, you could use the event binding to call a function onfocus.

Here's a minimal working snippet:

var viewModel = function() {
  var self = this;

  self.selectedCategory = ko.observable();
  self.selectedTcaMethod = ko.observable();

  self.availableCategories = ko.observableArray(["Category 1"]);
  self.availableTcaMethods = ko.observableArray(["TCA 1"]);

  self.selectedCategory.subscribe(function() {
    // if condition added to avoid cyclic subscribe triggers
    if (self.selectedCategory())
      self.selectedTcaMethod(undefined);
  })
  self.selectedTcaMethod.subscribe(function() {
    // if condition added to avoid cyclic subscribe triggers
    if (self.selectedTcaMethod())
      self.selectedCategory(undefined);
  });

  self.query = ko.observable('What are you looking for?');

  self.onFocus = function() {
    // clear the input on focus
    self.query('');
  };

  self.filterSpecifications = ko.computed(() => {
    self.query() + self.selectedCategory() + self.selectedTcaMethod();
    console.log("computed");
  });
}

ko.applyBindings(new viewModel());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<input data-bind="textInput: query, valueUpdate: 'keyup', event: { focus: onFocus }" type="text" placeholder="What are you looking for?" />

<select id="searchCategory" data-bind="options: availableCategories, value: selectedCategory, optionsCaption: 'Search by Category'"></select>

<select id="searchTCA" data-bind="options: availableTcaMethods, value: selectedTcaMethod, optionsCaption: 'Search by TCA Method'"></select></code>```

Body:
I am working on a Data Table that is populated 1 of 3 ways.
1. Live Search
2. Select box 1 (searchCategory)
3. Select box 2 (searchTCA)

I have everything working except for one issue that I am unable to figure out.

When the user selects one of the options in either select box, I would like the other one to reset to default.

I am still learning knockout, so any help would be greatly appreciated.

Thank You-

Here is my HTML:

     <form id="requestForm" class="request-form form-horizontal">

             Search

                 <input id="searchInput" type="text" name="searchInput" class="form-control" placeholder="What are you looking for?" onfocus="this.value=''" data-bind="textInput: query, valueUpdate: 'keyup'" autocomplete="off" />

            View by Category

                <select id="searchCategory" data-bind="options: availableCategories, value: selectedCategory, optionsCaption: 'Search by Category'"></select>

            View by TCA Method

                <select id="searchTCA" data-bind="options: availableTcaMethods, value: selectedTcaMethod, optionsCaption: 'Search by TCA Method'"></select>

   </form>

Here is the JS:

 define(function (require) {
"use strict";

var $ = require("jquery"),
    ko = require("knockout"),
    komapping = require("komapping"),
    bootstrap = require("bootstrap"),
    $embedElement = $("#Architectural-Guidebook");

if ($embedElement.length) {

    function ArchitecturalGuidebookViewModel(dduration) {
        var self = this;

        self.specifications = ko.observableArray([]);
        debugger;

        self.availableCategories = ko.observable();
        self.selectedCategory = ko.observable();

        self.availableTcaMethods = ko.observable();
        self.selectedTcaMethod = ko.observable();

        self.availableCategories = ko.dependentObservable(function () {
            var types = ko.utils.arrayMap(self.specifications(), function (item) { return item.Category; });
            return ko.utils.arrayGetDistinctValues(types).sort();
        });

        self.availableTcaMethods = ko.dependentObservable(function () {
            var types = ko.utils.arrayMap(self.specifications(), function (item) { return item.TcaMethod; });
            return ko.utils.arrayGetDistinctValues(types).sort();
        });

        self.specifications($.parseJSON(window.jsonModel));

        self.query = ko.observable('What are you looking for?');

        // Search
        self.pageNumber = ko.observable(0);
        self.filterSpecifications = ko.computed(function () {
            self.pageNumber(0);
            return ko.utils.arrayFilter(self.specifications(), function (i) {
                var filterLogic =
                    (i.TcaMethod.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Title.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Category.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Application.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Category === self.selectedCategory() && self.query('What are you looking for?')) ||
                    (i.TcaMethod === self.selectedTcaMethod() && self.query('What are you looking for?'));
                return filterLogic;
            });
        });

        // Pagination
        self.nbPerPage = 8;
        self.totalPages = ko.computed(function () {
            var div = Math.floor(self.filterSpecifications().length / self.nbPerPage);
            div += self.filterSpecifications().length % self.nbPerPage > 0 ? 1 : 0;
            return div - 1;
        });

        self.paginated = ko.computed(function () {
            var first = self.pageNumber() * self.nbPerPage;
            return self.filterSpecifications().slice(first, first +
                      self.nbPerPage);
        });

        self.hasPrevious = ko.computed(function () {
            return self.pageNumber() !== 0;
        });

        self.hasNext = ko.computed(function () {
            return self.pageNumber() !== self.totalPages();
        });

        self.next = function () {
            if (self.pageNumber() < self.totalPages()) {
                self.pageNumber(self.pageNumber() + 1);
            }
        };

        self.previous = function () {
            if (self.pageNumber() !== 0) {
                self.pageNumber(self.pageNumber() - 1);
            }
        };

    };

    ko.applyBindings(new ArchitecturalGuidebookViewModel());

  }

});

Body:
You can subscribe to the selectedCategory and selectedTcaMethod observables and set the other dropdown's value to undefined when one of them changes.

Also, you are clearing the input's value on focus. This will only clear the input and not query observable's value. So, filterSpecifications computed property doesn't get triggered onfocus even though the input is cleared. Instead, you could use the event binding to call a function onfocus.

Here's a minimal working snippet:

var viewModel = function() {
  var self = this;

  self.selectedCategory = ko.observable();
  self.selectedTcaMethod = ko.observable();

  self.availableCategories = ko.observableArray(["Category 1"]);
  self.availableTcaMethods = ko.observableArray(["TCA 1"]);

  self.selectedCategory.subscribe(function() {
    // if condition added to avoid cyclic subscribe triggers
    if (self.selectedCategory())
      self.selectedTcaMethod(undefined);
  })
  self.selectedTcaMethod.subscribe(function() {
    // if condition added to avoid cyclic subscribe triggers
    if (self.selectedTcaMethod())
      self.selectedCategory(undefined);
  });

  self.query = ko.observable('What are you looking for?');

  self.onFocus = function() {
    // clear the input on focus
    self.query('');
  };

  self.filterSpecifications = ko.computed(() => {
    self.query() + self.selectedCategory() + self.selectedTcaMethod();
    console.log("computed");
  });
}

ko.applyBindings(new viewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<input data-bind="textInput: query, valueUpdate: 'keyup', event: { focus: onFocus }" type="text" placeholder="What are you looking for?" />

<select id="searchCategory" data-bind="options: availableCategories, value: selectedCategory, optionsCaption: 'Search by Category'"></select>

<select id="searchTCA" data-bind="options: availableTcaMethods, value: selectedTcaMethod, optionsCaption: 'Search by TCA Method'"></select>


问:
Vue 2.5 template with Webpack and Typescript
The documentation says that a vue-cli template for typescript is comming soon, but currently none is availible. The official vue guide only shows a recommended tsconfig.json file.

I assume there's lots of additional work getting the all the magic inside webpack to play. And using an old starterkit based on an outdated version of webpack will, based on previous projects, give me hours of future headache.

So, If somebody already have gone through the trouble of creating a vue/vuex/webpack/typescript I'd be really happy if you could share it.

Thanks

答:
Well, I feel the release of the official vue-cli template is close. But since I have no clue how close it is, maybe yu can start with ducksoupdev's template here (and good news, it says it is already for Vue@2.5):

https://github.com/ducksoupdev/vue-webpack-typescript

Apparently, it does not contain vuex initializations, but can be a good starting point. All in all, the actual official templates do not include vuex neither.


问:
iPhone orientation - two boxes
My iPhone app has two boxes with content. When user switch the orientation of a phone boxes change the position like this:

Portrait

```<code>|---------|
| BUTTON1 |
| BUTTON2 |
|---------|
|         |
| BUTTON3 |
| BUTTON4 |
|         |
|---------|
</code>```

Landscape

```<code>|---------|---------------|
| BUTTON1 |    BUTTON3    |
| BUTTON2 |    BUTTON4    |
|---------|---------------|
</code>```

What is the right way to go? Two XIBs, other tricks? Should I resize elements manually in code?

答:
You can use this method in your view controller:

```<code>- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;
</code>```

To adjust the boxes'/views' frames. I believe they will be animated automatically.

Check the docs for more info.

ContentLicense: CC BY-SA 2.5

Title: iPhone orientation - two boxes

Body:
My iPhone app has two boxes with content. When user switch the orientation of a phone boxes change the position like this:

Portrait

|---------|
| BUTTON1 |
| BUTTON2 |
|---------|
|         |
| BUTTON3 |
| BUTTON4 |
|         |
|---------|

Landscape

|---------|---------------|
| BUTTON1 |    BUTTON3    |
| BUTTON2 |    BUTTON4    |
|---------|---------------|

What is the right way to go? Two XIBs, other tricks? Should I resize elements manually in code?

Body:
You can use this method in your view controller:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;

To adjust the boxes'/views' frames. I believe they will be animated automatically.

Check the docs for more info.


问:
iTunes-style NSWindow subclass?
Is there an open-source library for Cocoa to create a window following iTunes' style?  That is the window controls are laid out vertically instead of horizontally:

I find it space-saving and good for utility-type applications that doesn't need a window title.

答:
Just a modified version based on @Regexident 's for new macOS. The view hierarchy changed for new macOS UI, so the original version does not work. The modified code is as follows (works on macOS 10.13):

```<code>- (void)verticalizeButtonsForWindow:(NSWindow *)aWindow {
    // New view hierarchy.
    NSView *titleBarContainerView = aWindow.contentView.superview.subviews[1];
    titleBarContainerView.frame = NSMakeRect(titleBarContainerView.frame.origin.x, titleBarContainerView.frame.origin.y - 60.0 + titleBarContainerView.frame.size.height, titleBarContainerView.frame.size.width, 60.0);
    NSView *titleBarView = titleBarContainerView.subviews[0];
    titleBarView.frame = NSMakeRect(0.0, 0.0, titleBarView.frame.size.width, 60.0);
    NSArray *titleBarSubviews = titleBarView.subviews;

    NSView *closeButton = [titleBarSubviews objectAtIndex:0];
    NSRect closeButtonFrame = [closeButton frame];

    NSView *minimizeButton = [titleBarSubviews objectAtIndex:2];
    NSRect minimizeButtonFrame = [minimizeButton frame];

    NSView *zoomButton = [titleBarSubviews objectAtIndex:1];
    NSRect zoomButtonFrame = [zoomButton frame];

    // Coordinate changed: add instead of minus.
    [minimizeButton setFrame:NSMakeRect(closeButtonFrame.origin.x, closeButtonFrame.origin.y + 20.0, minimizeButtonFrame.size.width, minimizeButtonFrame.size.height)];
    [zoomButton setFrame:NSMakeRect(closeButtonFrame.origin.x, closeButtonFrame.origin.y + 40.0, zoomButtonFrame.size.width, zoomButtonFrame.size.height)];
}
</code>```

Result screenshot:

Title: iTunes-style NSWindow subclass?

Body:
Just a modified version based on @Regexident 's for new macOS. The view hierarchy changed for new macOS UI, so the original version does not work. The modified code is as follows (works on macOS 10.13):

- (void)verticalizeButtonsForWindow:(NSWindow *)aWindow {
    // New view hierarchy.
    NSView *titleBarContainerView = aWindow.contentView.superview.subviews[1];
    titleBarContainerView.frame = NSMakeRect(titleBarContainerView.frame.origin.x, titleBarContainerView.frame.origin.y - 60.0 + titleBarContainerView.frame.size.height, titleBarContainerView.frame.size.width, 60.0);
    NSView *titleBarView = titleBarContainerView.subviews[0];
    titleBarView.frame = NSMakeRect(0.0, 0.0, titleBarView.frame.size.width, 60.0);
    NSArray *titleBarSubviews = titleBarView.subviews;

    NSView *closeButton = [titleBarSubviews objectAtIndex:0];
    NSRect closeButtonFrame = [closeButton frame];

    NSView *minimizeButton = [titleBarSubviews objectAtIndex:2];
    NSRect minimizeButtonFrame = [minimizeButton frame];

    NSView *zoomButton = [titleBarSubviews objectAtIndex:1];
    NSRect zoomButtonFrame = [zoomButton frame];

    // Coordinate changed: add instead of minus.
    [minimizeButton setFrame:NSMakeRect(closeButtonFrame.origin.x, closeButtonFrame.origin.y + 20.0, minimizeButtonFrame.size.width, minimizeButtonFrame.size.height)];
    [zoomButton setFrame:NSMakeRect(closeButtonFrame.origin.x, closeButtonFrame.origin.y + 40.0, zoomButtonFrame.size.width, zoomButtonFrame.size.height)];
}

Result screenshot:


问:
May a call to std::lock pass a resource that is already locked by the calling thread?
I was researching possible implementations for the std::lock function and stumbled upon an implementation posted on the code review community.

Quoting the accepted answer (emphasis mine):

No this does not meet the definition of std::lock().

It (std::lock) guarantees that no matter what order you specify the
  locks in the parameter list you will not fall into a deadlock
  situation.

[...]

This also means that if a lock in the list is already locked it must
  be released so that the locks are acquired in the correct order.

I cannot find a conclusive answer whether or not the last statement is correct.

My question: is it allowed (i.e. defined behavior) to pass a locked resource, owned by the calling thread, as an argument to the standard std::lock function?

```<code>std::mutex m1, m2;
m1.lock();
std::lock(m1, m2);
</code>```

My gut feeling says this is actually not allowed. The function expects two or more Lockable objects and there is no way to check if a Lockable object is already locked by the current thread of execution. So it seems impossible to implement std::lock that way.

答:
My local draft of the standard says of lock, in 30.4.3/5

Effects: All arguments are locked via a sequence of calls to lock(), try_lock(), or unlock() on each
  argument. The sequence of calls shall not result in deadlock, but is otherwise unspecified. [ Note: A
  deadlock avoidance algorithm such as try-and-back-off must be used, but the specific algorithm is not
  specified to avoid over-constraining implementations. — end note ] If a call to lock() or try_lock()
  throws an exception, unlock() shall be called for any argument that had been locked by a call to
  lock() or try_lock().

So, it's clear that it may release locks acquired while working, but it doesn't say anything about whether locks held before entry may be have been released when it exits.

Presumably, so long as either

it succeeds and all lockables are locked, or

it throws, and exactly those lockables previously locked by this thread still are (no previously un-held locks held, and no previously-locked items now released)

it shouldn't make any difference what happens inside. Note that the language "... a sequence of calls ... on each argument" certainly seems to allow calling unlock on something locked before entry.

Body:
I was researching possible implementations for the std::lock function and stumbled upon an implementation posted on the code review community.

Quoting the accepted answer (emphasis mine):

No this does not meet the definition of std::lock().

It (std::lock) guarantees that no matter what order you specify the
  locks in the parameter list you will not fall into a deadlock
  situation.

[...]

This also means that if a lock in the list is already locked it must
  be released so that the locks are acquired in the correct order.

I cannot find a conclusive answer whether or not the last statement is correct.

My question: is it allowed (i.e. defined behavior) to pass a locked resource, owned by the calling thread, as an argument to the standard std::lock function?

std::mutex m1, m2;
m1.lock();
std::lock(m1, m2);

My gut feeling says this is actually not allowed. The function expects two or more Lockable objects and there is no way to check if a Lockable object is already locked by the current thread of execution. So it seems impossible to implement std::lock that way.


问:
Theory behind object oriented programming
Alonzo Church's lambda calculus is the mathematical theory behind functional languages. Has object oriented programming some formal theory ?</p>

答:
In 2000 in my degree thesys I proposed this model; very shortly:

```<code>y + 1 = f(u, x)
x + 1 = g(u, x)
</code>```

where:

u: input

y: output

x: state

f: output function

g: state function

Formally it's very similar to finite state machine, but the difference is that U, Y, S are set not finite, but infinite (numerable) and f and g are Touring Machine (TM).

f and g togheter form a class; if we add an initial state x0 we have an object. So OOP in something more than a TM a TM is a specific case of OOP. Note that the state x is of a different level than the state "inside" the TM. Inside the TM there are not side effect, the x state count for side effect.

Body:
In 2000 in my degree thesys I proposed this model; very shortly:

y + 1 = f(u, x)
x + 1 = g(u, x)

where:

u: input

y: output

x: state

f: output function

g: state function

Formally it's very similar to finite state machine, but the difference is that U, Y, S are set not finite, but infinite (numerable) and f and g are Touring Machine (TM).

f and g togheter form a class; if we add an initial state x0 we have an object. So OOP in something more than a TM a TM is a specific case of OOP. Note that the state x is of a different level than the state "inside" the TM. Inside the TM there are not side effect, the x state count for side effect.


问:
Laravel - Getting user details for method used in both web and api routes
I have a project in Laravel where I am using the same method for both a web and api route. So for example i would have the following:

```<code>//routes/web.php
Route::post("/import-results", "ImportController@doImport");

//routes/api.php
Route::post("/import-results/{auto}", "ImportController@doImport");
</code>```

So regardless of the route the doImport() function will be called in the ImportContoller.

The import controller has a function like this (there is validation in the function but I have taken it out for simplicity):

```<code>public function doImport($auto = null){
   $importData = new DataImport();
   $importData->type = $_POST['type'];
   $importData->data = $_POST['data'];
   $importData->user = Auth::user()->name;
   $importData->save();

   $data = [
      "success" => true,
      "message" => "Message Here!"
   ]

   if($auto){
      return json_encode($data);
   }else{
      return view('import-message', $data);
   }
}
</code>```

As you can see this method uses Auth::user()->name; to identify which user imported the data. This is fine if i am logging in and using a regular web route but what about if i'm using an API and using basic auth where no sessions are created and I don't want sessions to persist if the api routes are called.

How do i get the user info when calling API routes?

Also for the web routes i have customised my login as i'm using ldap but essentially the login happens by doing $this->guard()->login($user, false); in a class with the AuthenticatesUsers trait.

I could do this for my API routes too but does this creates a session and how do i clear this session once the request has ended? Or is there a better way??

答:
To make session work for both page submitting and api. You need work in web.php

Make both route in web.php

```<code>   //Web.php
   Route::post("/import-results", "ImportController@doImport");

   Route::post("/api/import-results/{auto}", "ImportController@doImport");
</code>```

api.php is stateless mean no session exist in api.php . It's working with token based like JWT.

Body:
I have a project in Laravel where I am using the same method for both a web and api route. So for example i would have the following:

//routes/web.php
Route::post("/import-results", "ImportController@doImport");

//routes/api.php
Route::post("/import-results/{auto}", "ImportController@doImport");

So regardless of the route the doImport() function will be called in the ImportContoller.

The import controller has a function like this (there is validation in the function but I have taken it out for simplicity):

public function doImport($auto = null){
   $importData = new DataImport();
   $importData->type = $_POST['type'];
   $importData->data = $_POST['data'];
   $importData->user = Auth::user()->name;
   $importData->save();

   $data = [
      "success" => true,
      "message" => "Message Here!"
   ]

   if($auto){
      return json_encode($data);
   }else{
      return view('import-message', $data);
   }
}

As you can see this method uses Auth::user()->name; to identify which user imported the data. This is fine if i am logging in and using a regular web route but what about if i'm using an API and using basic auth where no sessions are created and I don't want sessions to persist if the api routes are called.

How do i get the user info when calling API routes?

Also for the web routes i have customised my login as i'm using ldap but essentially the login happens by doing $this->guard()->login($user, false); in a class with the AuthenticatesUsers trait.

I could do this for my API routes too but does this creates a session and how do i clear this session once the request has ended? Or is there a better way??

Body:
To make session work for both page submitting and api. You need work in web.php

Make both route in web.php

   //Web.php
   Route::post("/import-results", "ImportController@doImport");

   Route::post("/api/import-results/{auto}", "ImportController@doImport");

api.php is stateless mean no session exist in api.php . It's working with token based like JWT.


问:
VBA - Custom Plugin works perfectly on laptop however does not work on other computers
I am currently having issues with a custom plugin that I was assigned from my boss which was not fully tested and developed at the time it was assigned. It is a letter template generator that takes values from Access (Letter Type, account Type, agent list,etc) which generates a sheet in excel which the user can enter values into based on the bookmarks within the word document.

The communication between Access and Excel appears to be fine, the issue is when the data is going from excel to word there is a part of my code removes the word.formfields replaces them with bookmarks and changes the value afterwards based on the user entry within the excel sheet, this section of the code works fine on my work laptop and my work desktop but not on the desktop of the advisors who are using the tool.

The strange thing about it is that the deleting of the word.formfield is fine it's just the changing of the bookmark that is not working. The following is the code that appears to be malfunctioning on only some computers:

The if statement that is below to update the bookmark is to check for specific bookmarks to assign them, unfortunately I cannot link that code here.

I have already Checked the other computer's security settings and version numbers and they are the same as mine so I really have no idea what could be causing this...

Update Bookmark:

```<code>        ElseIf wdDoc.Bookmarks.Exists(arrDefault(1, i)) Then
        updateBookmark CStr(arrDefault(1, i)), arrDefault(2, i), arrDefault(3, i)
        End If
</code>```

Update Bookmark Subroutine:

```<code>Private Sub updateBookmark(bookmarkname As String, bookmarkValue As Variant, ValueType As String)
Dim BMRange As Word.Range
    DeleteFormFields (bookmarkname)
    Set BMRange = wdapp.ActiveDocument.Bookmarks(bookmarkname).Range
'if the language is French
If InStr(1, UCase(strLang), "FRENCH") <> 0 Then
    Select Case ValueType
    Case "Date"
         If bookmarkname = "TodaysDate" Then
            BMRange.Text = bookmarkValue
        Else
            BMRange.Text = CStr(Application.WorksheetFunction.Text(bookmarkValue, "[$-040c]d mmmm, yyyy"))
        End If
    Case "String", "Long", "Integer"
        BMRange.Text = bookmarkValue
    Case "Currency"
        BMRange.Text = Format(bookmarkValue, "$#,##0.00")
    End Select
'if the language is English
Else
    Select Case ValueType

    Case "String", "Long", "Integer"
        BMRange.Text = bookmarkValue
    Case "Currency"
        BMRange.Text = Format(bookmarkValue, "$#,##0.00")
    Case "Date"
        If bookmarkname = "TodaysDate" Then BMRange.Text = Format(bookmarkValue, "MMMM D, YYYY")
        BMRange.Text = Format(bookmarkValue, "MMMM D YYYY")
    End Select
End If
    wdapp.ActiveDocument.Bookmarks.Add bookmarkname, BMRange
End Sub
</code>```

答: I found the answer! There was a missing ValueType called "Month" This was making the bookmark not update.... as for the references they were fine... Thanks to those who took the time to look into this.</p>

Body:
I am currently having issues with a custom plugin that I was assigned from my boss which was not fully tested and developed at the time it was assigned. It is a letter template generator that takes values from Access (Letter Type, account Type, agent list,etc) which generates a sheet in excel which the user can enter values into based on the bookmarks within the word document.

The communication between Access and Excel appears to be fine, the issue is when the data is going from excel to word there is a part of my code removes the word.formfields replaces them with bookmarks and changes the value afterwards based on the user entry within the excel sheet, this section of the code works fine on my work laptop and my work desktop but not on the desktop of the advisors who are using the tool.

The strange thing about it is that the deleting of the word.formfield is fine it's just the changing of the bookmark that is not working. The following is the code that appears to be malfunctioning on only some computers:

The if statement that is below to update the bookmark is to check for specific bookmarks to assign them, unfortunately I cannot link that code here.

I have already Checked the other computer's security settings and version numbers and they are the same as mine so I really have no idea what could be causing this...

Update Bookmark:

        ElseIf wdDoc.Bookmarks.Exists(arrDefault(1, i)) Then
        updateBookmark CStr(arrDefault(1, i)), arrDefault(2, i), arrDefault(3, i)
        End If

Update Bookmark Subroutine:

Private Sub updateBookmark(bookmarkname As String, bookmarkValue As Variant, ValueType As String)
Dim BMRange As Word.Range
    DeleteFormFields (bookmarkname)
    Set BMRange = wdapp.ActiveDocument.Bookmarks(bookmarkname).Range
'if the language is French
If InStr(1, UCase(strLang), "FRENCH") <> 0 Then
    Select Case ValueType
    Case "Date"
         If bookmarkname = "TodaysDate" Then
            BMRange.Text = bookmarkValue
        Else
            BMRange.Text = CStr(Application.WorksheetFunction.Text(bookmarkValue, "[$-040c]d mmmm, yyyy"))
        End If
    Case "String", "Long", "Integer"
        BMRange.Text = bookmarkValue
    Case "Currency"
        BMRange.Text = Format(bookmarkValue, "$#,##0.00")
    End Select
'if the language is English
Else
    Select Case ValueType

    Case "String", "Long", "Integer"
        BMRange.Text = bookmarkValue
    Case "Currency"
        BMRange.Text = Format(bookmarkValue, "$#,##0.00")
    Case "Date"
        If bookmarkname = "TodaysDate" Then BMRange.Text = Format(bookmarkValue, "MMMM D, YYYY")
        BMRange.Text = Format(bookmarkValue, "MMMM D YYYY")
    End Select
End If
    wdapp.ActiveDocument.Bookmarks.Add bookmarkname, BMRange
End Sub


问:
Java Sqlite table is created but not showing in sqlite studio
I'm having an issue trying to create a table in an sqlite database i've created called ticketDB, in my program i'd like to create a table in that database and this is what the code looks like.

```<code>try{

    Connection c = dbConnection.getConnection();
    Statement stmt = c.createStatement();

    String sql = "CREATE TABLE IF NOT EXISTS notes" +
                           "(ID INT PRIMARY KEY     NOT NULL," +
                           " NAME           TEXT    NOT NULL, " +
                           " AGE            INT     NOT NULL, " +
                           " ADDRESS        CHAR(50), " +
                           " SALARY         REAL)";
    stmt.executeUpdate(sql);
    stmt.close();
    c.close();

    }catch(Exception e2) {System.out.print(e2);}
</code>```

dbConnection is a class that will connect to my database. When i run the code it shows that it connects to the database but does not show any errors so im assuming the database is being created but it does not show up in sqlite studio. Please help I've been researching into this for days with no results.

答:
```<code>"jdbc:sqlite:ticketDB.sqlite"
</code>```

There is no path. You are creating a new database file in some random directory.

Body:
I'm having an issue trying to create a table in an sqlite database i've created called ticketDB, in my program i'd like to create a table in that database and this is what the code looks like.

try{

    Connection c = dbConnection.getConnection();
    Statement stmt = c.createStatement();

    String sql = "CREATE TABLE IF NOT EXISTS notes" +
                           "(ID INT PRIMARY KEY     NOT NULL," +
                           " NAME           TEXT    NOT NULL, " +
                           " AGE            INT     NOT NULL, " +
                           " ADDRESS        CHAR(50), " +
                           " SALARY         REAL)";
    stmt.executeUpdate(sql);
    stmt.close();
    c.close();

    }catch(Exception e2) {System.out.print(e2);}

dbConnection is a class that will connect to my database. When i run the code it shows that it connects to the database but does not show any errors so im assuming the database is being created but it does not show up in sqlite studio. Please help I've been researching into this for days with no results.

Body:
"jdbc:sqlite:ticketDB.sqlite"

There is no path. You are creating a new database file in some random directory.


问:
React - Child Components as Behaviors?
I'm trying to inject capabilities into a parent component via child decorators.  For example,

```<code><OpenLayers>
    <GeoJsonLayer url="https://openlayers.org/en/master/examples/data/geojson/countries.geojson"/>
</OpenLayers>
</code>```

I'm having to use a context to do it, but I'm interpreting that as a warning sign, since there are many places that say, 'if you're using context you're probably doing something wrong'.  It seems like child.props.parent should already exist but, again, the fact that I'm looking for that must be another warning sign.

Perhaps it's the parent's responsibility to iterate through it's children and invoke methods on them that modify themselves?  But where would that be done?
 How to get access to the component instance?

How can a child modify its parent without the parent having explicit knowledge of the child?  I'm looking for existing pattern that allows child components to modify the behavior of the parent component that don't invoke using "context".

Here are the two approaches I've tried so far.  The first seems to be better design but the second allows me to extend the  capabilities via introducing child components (e.g. ):

```<code>    // one alternative is to not use child components but properties...
    this.props.geoJsonUrl && GeoJsonLayer.addGeoJsonLayer(map, this.props.geoJsonUrl);

    // another is to use child components and pass parent to a handler..
    Children.forEach(this.props.children, c => {
        c;
        if (typeof c === "string") return;
        if (typeof c === "number") return;
        let child: any = c;
        if (child.type === GeoJsonLayer) {
            GeoJsonLayer.addGeoJsonLayer(map, c.props.url);
        }
    });

    // I would prefer that the child trigger a cascading event that the parent could receive
    // and process
</code>```

Using props only:

```<code>        <OpenLayers
            orientation={orientation}
            controls={{ mousePosition: true }}
            bingImagerySet="AerialWithLabels"
            labels={true}
            setCenter={setCenter}
            center={this.state.center}
            zoom={this.state.zoom}
            geoJsonUrl="http://openlayers.org/en/master/examples/data/geojson/countries.geojson"/>
</code>```

Using child:

```<code>        <OpenLayers
            orientation={orientation}
            controls={{ zoom: true, zoomToExtent: true }}
            setCenter={setCenter}
            center={this.state.center}
            zoom={this.state.zoom}
            osm={false}>
            <GeoJsonLayer url="http://openlayers.org/en/master/examples/data/geojson/countries.geojson" />
        </OpenLayers>
</code>```

答:
Take a look at Lifting State Up.

You would have some kind of a LayerController that has a list of layers in its state, and an addLayer that should be invoked on each Layer's mount, then, you pass the list of layers to the intermediate OpenLayers component through props.

Title: React - Child Components as Behaviors?

Body:
I'm trying to inject capabilities into a parent component via child decorators.  For example,

<OpenLayers>
    <GeoJsonLayer url="https://openlayers.org/en/master/examples/data/geojson/countries.geojson"/>
</OpenLayers>

I'm having to use a context to do it, but I'm interpreting that as a warning sign, since there are many places that say, 'if you're using context you're probably doing something wrong'.  It seems like child.props.parent should already exist but, again, the fact that I'm looking for that must be another warning sign.

Perhaps it's the parent's responsibility to iterate through it's children and invoke methods on them that modify themselves?  But where would that be done?
 How to get access to the component instance?

How can a child modify its parent without the parent having explicit knowledge of the child?  I'm looking for existing pattern that allows child components to modify the behavior of the parent component that don't invoke using "context".

Here are the two approaches I've tried so far.  The first seems to be better design but the second allows me to extend the  capabilities via introducing child components (e.g. ):

    // one alternative is to not use child components but properties...
    this.props.geoJsonUrl && GeoJsonLayer.addGeoJsonLayer(map, this.props.geoJsonUrl);

    // another is to use child components and pass parent to a handler..
    Children.forEach(this.props.children, c => {
        c;
        if (typeof c === "string") return;
        if (typeof c === "number") return;
        let child: any = c;
        if (child.type === GeoJsonLayer) {
            GeoJsonLayer.addGeoJsonLayer(map, c.props.url);
        }
    });

    // I would prefer that the child trigger a cascading event that the parent could receive
    // and process

Using props only:

        <OpenLayers
            orientation={orientation}
            controls={{ mousePosition: true }}
            bingImagerySet="AerialWithLabels"
            labels={true}
            setCenter={setCenter}
            center={this.state.center}
            zoom={this.state.zoom}
            geoJsonUrl="http://openlayers.org/en/master/examples/data/geojson/countries.geojson"/>

Using child:

        <OpenLayers
            orientation={orientation}
            controls={{ zoom: true, zoomToExtent: true }}
            setCenter={setCenter}
            center={this.state.center}
            zoom={this.state.zoom}
            osm={false}>
            <GeoJsonLayer url="http://openlayers.org/en/master/examples/data/geojson/countries.geojson" />
        </OpenLayers>


问:
How to check if a button hasn't been clicked in a certain amount of time (Javascript)
I am making a story kind of html page where you anger the narrator by pressing "t". He says "I bet you can't go a full 5 seconds without pressing t."

Anyone know how I could check if a button isn't clicked within 5 seconds, and if it is clicked make something else happen as well.

I tried to use seconds to solve this problem, as I am very new to JavaScript, this is currently being worked on.

```<code>  function timenow() {
    var now = today.getSeconds();
  }
  function timelater() {
    var later = today.getSeconds();
  }

  function clicked() {
    if (!document.getElementById("form-search") && document.getElementById("fake-search").value == "t") {
      if (a==8) {
        alert("Alright Smart Guy, lets just delete everything on the page!");
        document.body.style.opacity = "0";
        document.getElementById("google_search").style.cursor= "wait";
        a+=1;
      }
      else if (a==9) {
        alert("You know what... I'm done, I'm Done! If you can not press t for 5 seconds, I'll give you everything back.");
        a+=1;
        timenow();
        setTimeout(timelater(), 5000);
        console.log(now);
        console.log(later);
      }
    else {
      null;
    }
</code>```

答:
You'd first make a placeholder for your timer and initialize it through a click event handler. Anytime between the 5s you check whether the key t has been pressed and if the timer is still going. Within that conditional you provide further functionality.

UPDATE: To assign the same functionality to keyup and keypress events, simply extract the callback into its' own function detectKey and pass that function into both event handlers:

let timer;

document.querySelector('.start').addEventListener('click', () => {
  timer = setTimeout(() => {
    alert("Time's up! You didn't press the letter");
  }, 5000);
});

document.addEventListener('keyup', detectKey);

document.addEventListener('keypress', detectKey);

function detectKey(e) {
  const key = String.fromCharCode(e.keyCode).toLowerCase() === 't';

  if (key && timer) {
    clearTimeout(timer);

    timer = null;

    alert('You pressed the letter!');
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="start">Start</button></code>```

Body:
I am making a story kind of html page where you anger the narrator by pressing "t". He says "I bet you can't go a full 5 seconds without pressing t."

Anyone know how I could check if a button isn't clicked within 5 seconds, and if it is clicked make something else happen as well.

I tried to use seconds to solve this problem, as I am very new to JavaScript, this is currently being worked on.

  function timenow() {
    var now = today.getSeconds();
  }
  function timelater() {
    var later = today.getSeconds();
  }

  function clicked() {
    if (!document.getElementById("form-search") && document.getElementById("fake-search").value == "t") {
      if (a==8) {
        alert("Alright Smart Guy, lets just delete everything on the page!");
        document.body.style.opacity = "0";
        document.getElementById("google_search").style.cursor= "wait";
        a+=1;
      }
      else if (a==9) {
        alert("You know what... I'm done, I'm Done! If you can not press t for 5 seconds, I'll give you everything back.");
        a+=1;
        timenow();
        setTimeout(timelater(), 5000);
        console.log(now);
        console.log(later);
      }
    else {
      null;
    }

Body:
You'd first make a placeholder for your timer and initialize it through a click event handler. Anytime between the 5s you check whether the key t has been pressed and if the timer is still going. Within that conditional you provide further functionality.

UPDATE: To assign the same functionality to keyup and keypress events, simply extract the callback into its' own function detectKey and pass that function into both event handlers:

let timer;

document.querySelector('.start').addEventListener('click', () => {
  timer = setTimeout(() => {
    alert("Time's up! You didn't press the letter");
  }, 5000);
});

document.addEventListener('keyup', detectKey);

document.addEventListener('keypress', detectKey);

function detectKey(e) {
  const key = String.fromCharCode(e.keyCode).toLowerCase() === 't';

  if (key && timer) {
    clearTimeout(timer);

    timer = null;

    alert('You pressed the letter!');
  }
}

<button class="start">Start</button>


问:
How can I have this program add the user input into my linked list?
```<code>import java.util.*;

public class TestClass {
static String name;
static String gender;
static String hairColor;

TestClass(String name, String gender, String hairColor){
    this.name=name;
    this.gender=gender;
    this.hairColor=hairColor;

}
public static void main (String[]args) {
    TestClass info = new TestClass(name, gender, hairColor);
    LinkedList<TestClass> linky = new LinkedList<TestClass>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    name=input.nextLine();

    System.out.println("Enter gender ");
    gender=input.nextLine();

    System.out.println("Enter hair color ");
    hairColor=input.nextLine();

    }

}
</code>```

I want to add user input into the linked list but I can't figure out how to. I have tried to use linky.add(name); but that gives an error. How can I add input into the linked list?

答:
```<code>import java.util.*;

public class TestClass {
    // These should (most likely) not be static
    // Read up on what 'static' means
    String name;
    String gender;
    String hairColor;

    TestClass(String name, String gender, String hairColor){
        this.name = name;
        this.gender = gender;
        this.hairColor = hairColor;
    }

    public static void main (String[]args) {
        LinkedList<TestClass> linky = new LinkedList<TestClass>();

        Scanner input = new Scanner(System.in);

        System.out.println("Enter name ");
        String name = input.nextLine();

        System.out.println("Enter gender ");
        String gender = input.nextLine();

        System.out.println("Enter hair color ");
        String hairColor = input.nextLine();

        TestClass info = new TestClass(name, gender, hairColor);

        linky.add(info);
    }
}
</code>```

Since linky is a LinkedList<TestClass> with generic type TestClass it can only hold objects of type TestClass so when you try to linky.add(name) it wont work

To print out the contents of the list you will need to iterate through the list and print each element, if the list contained Strings or something with an Overridden toString method, then you could simply call:

```<code>for(String str : linky){
    System.out.println(str);
}
</code>```

BUT this will not work because linky contains TestClasses. Therefor you could do this (but you should probably define geter methods for the fields of TestClass):

```<code>for(TestClass testClass : linky){
    System.out.println("Name: " + testClass.name);
    System.out.println("Gender: " + testClass.gender);
    System.out.println("Hair Color: " + testClass.hairColor);
}
</code>```

OR in TestClass you could override the toString method inherited from its superclass Object

```<code>// In TestClass
@Override
public String toString(){
    // Format this however you like
    return "Name :" + this.name + "; Gender: " + this.gender + "; Hair Color: " + this.hairColor;
}
</code>```

Then all you would need to do is this:

```<code>for(TestClass testClass : linky){
    // println(testClass) calls testClass.toString()
    // giving you the formatted data from TestClass
    System.out.println(testClass);
}
</code>```

Body:
import java.util.*;

public class TestClass {
static String name;
static String gender;
static String hairColor;

TestClass(String name, String gender, String hairColor){
    this.name=name;
    this.gender=gender;
    this.hairColor=hairColor;

}
public static void main (String[]args) {
    TestClass info = new TestClass(name, gender, hairColor);
    LinkedList<TestClass> linky = new LinkedList<TestClass>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    name=input.nextLine();

    System.out.println("Enter gender ");
    gender=input.nextLine();

    System.out.println("Enter hair color ");
    hairColor=input.nextLine();

    }

}

I want to add user input into the linked list but I can't figure out how to. I have tried to use linky.add(name); but that gives an error. How can I add input into the linked list?

Body:
import java.util.*;

public class TestClass {
    // These should (most likely) not be static
    // Read up on what 'static' means
    String name;
    String gender;
    String hairColor;

    TestClass(String name, String gender, String hairColor){
        this.name = name;
        this.gender = gender;
        this.hairColor = hairColor;
    }

    public static void main (String[]args) {
        LinkedList<TestClass> linky = new LinkedList<TestClass>();

        Scanner input = new Scanner(System.in);

        System.out.println("Enter name ");
        String name = input.nextLine();

        System.out.println("Enter gender ");
        String gender = input.nextLine();

        System.out.println("Enter hair color ");
        String hairColor = input.nextLine();

        TestClass info = new TestClass(name, gender, hairColor);

        linky.add(info);
    }
}

Since linky is a LinkedList<TestClass> with generic type TestClass it can only hold objects of type TestClass so when you try to linky.add(name) it wont work

To print out the contents of the list you will need to iterate through the list and print each element, if the list contained Strings or something with an Overridden toString method, then you could simply call:

for(String str : linky){
    System.out.println(str);
}

BUT this will not work because linky contains TestClasses. Therefor you could do this (but you should probably define geter methods for the fields of TestClass):

for(TestClass testClass : linky){
    System.out.println("Name: " + testClass.name);
    System.out.println("Gender: " + testClass.gender);
    System.out.println("Hair Color: " + testClass.hairColor);
}

OR in TestClass you could override the toString method inherited from its superclass Object

// In TestClass
@Override
public String toString(){
    // Format this however you like
    return "Name :" + this.name + "; Gender: " + this.gender + "; Hair Color: " + this.hairColor;
}

Then all you would need to do is this:

for(TestClass testClass : linky){
    // println(testClass) calls testClass.toString()
    // giving you the formatted data from TestClass
    System.out.println(testClass);
}