问:
How to switch tabs in jTabbedPane by clicking a Button?
I have two JTabbedPanes, JTabbedPane1 & 2
How can I press button in JTabbedPane2 to show JTabbedPane1 ?

Here is the code for JTabbedPane:

```<code>public class TabbedPane extends JFrame {

    public TabbedPane() {

        setTitle("Tabbed Pane");
        setSize(300,300);

        JTabbedPane jtp = new JTabbedPane();

       getContentPane().add(jtp);

       JPanel1 jp1 = new JPanel1();//This will create the first tab

       JPanel jp2 = new JPanel2();//This will create the second tab

       //add panel .........

    //example usage
     public static void main (String []args){
        TabbedPane tab = new TabbedPane();
    }

}
</code>```

here is class JPane1:

```<code>...    JLabel label1 = new JLabel();
       label1.setText("This is Tab 1");
       jp1.add(label1);
</code>```

and class Jpane2 with button on int

JButton test = new JButton("Press");
   jp2.add(test);

```<code>ButtonHandler phandler = new ButtonHandler();
test.addActionListener(phandler);
setVisible(true);
</code>```

}
 so problem is here in ActionListener of button on Jpanel2

```<code>class ButtonHandler implements ActionListener{
       public void actionPerformed(ActionEvent e){
              // what i do now ? to call  jpanel 1 show ![alt text][1]
       }
}
</code>```

答:
Just! With:</p>

```<code>JTabbedPane.setSelectedComponnet(component);
</code>```

Body:
I have two JTabbedPanes, JTabbedPane1 & 2
How can I press button in JTabbedPane2 to show JTabbedPane1 ?

Here is the code for JTabbedPane:

public class TabbedPane extends JFrame {

    public TabbedPane() {

        setTitle("Tabbed Pane");
        setSize(300,300);

        JTabbedPane jtp = new JTabbedPane();

       getContentPane().add(jtp);

       JPanel1 jp1 = new JPanel1();//This will create the first tab

       JPanel jp2 = new JPanel2();//This will create the second tab

       //add panel .........

    //example usage
     public static void main (String []args){
        TabbedPane tab = new TabbedPane();
    }

}

here is class JPane1:

...    JLabel label1 = new JLabel();
       label1.setText("This is Tab 1");
       jp1.add(label1);

and class Jpane2 with button on int

JButton test = new JButton("Press");
   jp2.add(test);

ButtonHandler phandler = new ButtonHandler();
test.addActionListener(phandler);
setVisible(true);

}
 so problem is here in ActionListener of button on Jpanel2

class ButtonHandler implements ActionListener{
       public void actionPerformed(ActionEvent e){
              // what i do now ? to call  jpanel 1 show ![alt text][1]
       }
}

Body:
Just! With:

JTabbedPane.setSelectedComponnet(component);


来源: stackexchange

问:
Sparkjava redirect while keeping the browser URL
I have a sparkjava server app running, it serves a static HTML page using this line:

```<code>staticFiles.location("/public");
</code>```

If you go to http://example.com, you will see the HTML page. Now, I want to redirect users from other paths to my homepage, while keeping the browser URL. For example, if you visit http://example.com/message/123, you will still see the HTML page, while the browser URL stays http://example.com/message/123. So redirect.get() won't work here.

答:
In order to serve the same file from different paths, you can do as follows (it looks long but it's pretty simple):

Assuming your project's structure is:

```<code>src
  java
    main
      resources
        public
        templates   (optional folder)
</code>```

On GET request to your homepage a static HTML file that resides in /public is served. Let's call this file index.html.

Now you want to register additional path(s) to serve this file. If you use TemplateEngine you can do it easily. Actually, you'll refer to index.html both as a static file and as a template (with no parameters).

Template engine lets you create the served HTML page dynamically by passing it a map of key-value pairs that you can reference in the template on runtime. But in your case, it will be much simpler because you want to serve a page as-is, statically. Therefore you'll pass an empty map:

```<code>Spark.get("/message/123", (req, res) ->
    new ModelAndView(new HashMap(),
                     "../public/index"),
                     new ThymeleafTemplateEngine()
);
</code>```

Thymeleaf is just an example here, Spark supports few template engines. For each one of them, you can find in the documentation a simple github example of how to use it. For example, This is the Thymeleaf one.

The path ../public/index is because Spark is looking for templates in the templates folder, and you want to target public/index.html as the template.

You'll find the class ThymeleafTemplateEngine in the github link.

Of course you'll have to add the chosen template engine dependency to the project's pom.xml file.

As a result, GET requests to both http://example.com and http://example.com/message/123 will serve index.html while keeping the requested URL.

ContentLicense: CC BY-SA 3.0

Body:
I have a sparkjava server app running, it serves a static HTML page using this line:

staticFiles.location("/public");

If you go to http://example.com, you will see the HTML page. Now, I want to redirect users from other paths to my homepage, while keeping the browser URL. For example, if you visit http://example.com/message/123, you will still see the HTML page, while the browser URL stays http://example.com/message/123. So redirect.get() won't work here.

Body:
In order to serve the same file from different paths, you can do as follows (it looks long but it's pretty simple):

Assuming your project's structure is:

src
  java
    main
      resources
        public
        templates   (optional folder)

On GET request to your homepage a static HTML file that resides in /public is served. Let's call this file index.html.

Now you want to register additional path(s) to serve this file. If you use TemplateEngine you can do it easily. Actually, you'll refer to index.html both as a static file and as a template (with no parameters).

Template engine lets you create the served HTML page dynamically by passing it a map of key-value pairs that you can reference in the template on runtime. But in your case, it will be much simpler because you want to serve a page as-is, statically. Therefore you'll pass an empty map:

Spark.get("/message/123", (req, res) ->
    new ModelAndView(new HashMap(),
                     "../public/index"),
                     new ThymeleafTemplateEngine()
);

Thymeleaf is just an example here, Spark supports few template engines. For each one of them, you can find in the documentation a simple github example of how to use it. For example, This is the Thymeleaf one.

The path ../public/index is because Spark is looking for templates in the templates folder, and you want to target public/index.html as the template.

You'll find the class ThymeleafTemplateEngine in the github link.

Of course you'll have to add the chosen template engine dependency to the project's pom.xml file.

As a result, GET requests to both http://example.com and http://example.com/message/123 will serve index.html while keeping the requested URL.


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
Think of an interface like a Contract.  It's a way to say, "These classes should follow these set of rules."

So in the IAnimal example, it is a way to say, "I MUST be able to call Run, Walk, etc. on classes which implement IAnimal."

Why is this useful?  You may want to build a function which relies on the fact that you must be able to call Run and Walk, for example, on the object.  You could have the following:

```<code>public void RunThenWalk(Monkey m) {
    m.Run();
    m.Walk();
}

public void RunThenWalk(Dog d) {
    d.Run();
    d.Walk();
}
</code>```

... and repeat that for all objects which you know can run and walk.  However, with your IAnimal interface, you can define the function once as follows:

```<code>public void RunThenWalk(IAnimal a) {
    a.Run();
    a.Walk();
}
</code>```

By programming against the interface, you are essentially trusting the classes to implement the intent of the interface.  So in our example, the thought is "I don't care how they Run and Walk, so long as they Run and Walk.  My RunThenWalk will be valid as long as they fulfill that agreement.  It functions perfectly well without knowing anything else about the class."

There is also a good discussion in this related question.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ALassek

Body:
Think of an interface like a Contract.  It's a way to say, "These classes should follow these set of rules."

So in the IAnimal example, it is a way to say, "I MUST be able to call Run, Walk, etc. on classes which implement IAnimal."

Why is this useful?  You may want to build a function which relies on the fact that you must be able to call Run and Walk, for example, on the object.  You could have the following:

public void RunThenWalk(Monkey m) {
    m.Run();
    m.Walk();
}

public void RunThenWalk(Dog d) {
    d.Run();
    d.Walk();
}

... and repeat that for all objects which you know can run and walk.  However, with your IAnimal interface, you can define the function once as follows:

public void RunThenWalk(IAnimal a) {
    a.Run();
    a.Walk();
}

By programming against the interface, you are essentially trusting the classes to implement the intent of the interface.  So in our example, the thought is "I don't care how they Run and Walk, so long as they Run and Walk.  My RunThenWalk will be valid as long as they fulfill that agreement.  It functions perfectly well without knowing anything else about the class."

There is also a good discussion in this related question.

OwnerDisplayName: Larsenal

LastEditorDisplayName: Larsenal


问:
Javascript Disabled
i have a select dropdown list which has 4-5 fields. As soon as a user selects a value in the dropdown i have to assign a value to a hidden parameter on the page. (Using javascript function Onchange). The same hidden parameter is passed on to a hyperlink url whenever a user clicks on to it on a same page.

This works fine when javascript is enabled, but what to do when javascript is disabled ? i know there is noscript tag but how can i achieve above functionality ? can you give me some example code ?

Many Thanks,

答:
The solution to my problem is that i created a url and then overwrite it using noscript tag. on click i was calling a javascript function which was again overwriting the same .

thus when javascript was enabled, onclick function was sending it to popup and when javascript was disabled the noscript tag was overwriting it and redirecting to a another page.

Title: Javascript Disabled


问:
how to enlist multiple records filtered by checkedlistbox
i have a data grid view  and checked list box. checked list box is populated from database items i want create  filter using checked list box's items means to populate data grid view by checking checked list box's items now the problem is that data grid view show only only one record corresponds to checked item but does not display multiple records if multiple checkbox items are checked.

```<code>        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=DESKTOP-50ME4GC\SQLEXPRESS;Initial Catalog=autolab;Integrated Security=True";
        if (pn.CheckedItems.Count != 0)
        {
            // If so, loop through all checked items and print results.
            string s = "";
            int x;
            for (x = 0; x <= pn.CheckedItems.Count - 1; x++)
            {
                s = s + pn.CheckedItems[x].ToString();
            }
            connection.Open();
            SqlCommand cmd = new SqlCommand("SELECT *  from test_report  inner join tests  on test_report.test_name = tests.Test_name WHERE tests.Test_name IN ('" + s + "') ", connection);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            DataTable tbl = new DataTable();

           adapter.Fill(tbl);

            dt.DataSource = tbl;

            connection.Close();

        }
</code>```

答:
First, your string with the item names is composed incorrectly, suppose you have those elements:

```<code>One
Two
Three
</code>```

Your concat would do this:

```<code>OneTwoThree
</code>```

While you want:

```<code>'One','Two','Three'
</code>```

So you need to correct the concat like this:

```<code>        string s = "";
        int x;
        for (x = 0; x <= pn.CheckedItems.Count - 1; x++)
        {
            s = s + "'" + pn.CheckedItems[x].ToString() + "',";
        }

        s = s.Substring(0, s.Length - 1);
</code>```

And correct the query to be this:

```<code>SqlCommand cmd = new SqlCommand("SELECT *  from test_report  inner join tests  on test_report.test_name = tests.Test_name WHERE tests.Test_name IN (" + s + ") ", connection);
</code>```

Body:
i have a data grid view  and checked list box. checked list box is populated from database items i want create  filter using checked list box's items means to populate data grid view by checking checked list box's items now the problem is that data grid view show only only one record corresponds to checked item but does not display multiple records if multiple checkbox items are checked.

        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=DESKTOP-50ME4GC\SQLEXPRESS;Initial Catalog=autolab;Integrated Security=True";
        if (pn.CheckedItems.Count != 0)
        {
            // If so, loop through all checked items and print results.
            string s = "";
            int x;
            for (x = 0; x <= pn.CheckedItems.Count - 1; x++)
            {
                s = s + pn.CheckedItems[x].ToString();
            }
            connection.Open();
            SqlCommand cmd = new SqlCommand("SELECT *  from test_report  inner join tests  on test_report.test_name = tests.Test_name WHERE tests.Test_name IN ('" + s + "') ", connection);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            DataTable tbl = new DataTable();

           adapter.Fill(tbl);

            dt.DataSource = tbl;

            connection.Close();

        }

Body:
First, your string with the item names is composed incorrectly, suppose you have those elements:

One
Two
Three

Your concat would do this:

OneTwoThree

While you want:

'One','Two','Three'

So you need to correct the concat like this:

        string s = "";
        int x;
        for (x = 0; x <= pn.CheckedItems.Count - 1; x++)
        {
            s = s + "'" + pn.CheckedItems[x].ToString() + "',";
        }

        s = s.Substring(0, s.Length - 1);

And correct the query to be this:

SqlCommand cmd = new SqlCommand("SELECT *  from test_report  inner join tests  on test_report.test_name = tests.Test_name WHERE tests.Test_name IN (" + s + ") ", connection);


问:
Add function names to a string in Python
I'm just beginning to learn Python on my own, and I'm trying to write a code that will calculate the end time of a jog.

My code so far looks as follows:

```<code>def elapsed(t):
    t = raw_input('Enter time (hh:mm:ss): ')
    th, tm, ts = t.split(':')
    return int(ts) + int(tm) * 60 + int(th) * 3600

def mile(m):
    m = raw_input('How many miles? ')
    return int(m)

start = elapsed('start')
warmup = elapsed('warmup')
wmile = mile('wmile')
tempo = elapsed('tempo')
tmile = mile('tmile')
cooloff = elapsed('cooloff')
cmile = mile('cmile')

hour = (start + warmup * wmile + tempo * tmile + cooloff * cmile) // 3600
minute = (start + warmup * wmile + tempo * tmile + cooloff * cmile - hour * 3600) // 60
second = (start + warmup * wmile + tempo * tmile + cooloff * cmile - hour * 3600) % 60

print('Your run ended at %02d:%02d:%02d' % (hour, minute, second))
</code>```

In this code, the time prompts are all the same: "Enter time (hh:mm:ss):" I want each prompt to refer to its variable name, e.g., "Enter start time (hh:mm:ss)" or "Enter time (hh:mm:ss): (warmup)". Is there a way to do this?

Note: While this may technically be a duplicate, I have examined the similar questions, but decided that both the questions and the answers provided were on the more unspecific side, and therefore decided to ask my question anyway.

答:
```<code>def enter_time(specify_string):
    print("Please enter the", specify_string, 'time in format hh:mm:ss > ', end='')
    hh, mm, ss = input().split(':')
    return (hh, mm, ss)

start_time = enter_time('start')
finish_time = enter_time('finish')

>>>Please enter the start time in format hh:mm:ss >13:32:34
>>>Please enter the finish time in format hh:mm:ss >12:21:21
>>>start_time
(13, 32, 34)
</code>```

Now you can call the function with string arguments in the function call, and it will generalise the function for different requirements.

It is better to move the time between functions in a more readable format, such as a tuple. You can make more functions, eg:
- Test valid time entered
- Convert tuple to seconds for calculations
- Convert seconds back to tuple format
ect.

Let me know if I misunderstood you.

Body:
I'm just beginning to learn Python on my own, and I'm trying to write a code that will calculate the end time of a jog.

My code so far looks as follows:

def elapsed(t):
    t = raw_input('Enter time (hh:mm:ss): ')
    th, tm, ts = t.split(':')
    return int(ts) + int(tm) * 60 + int(th) * 3600

def mile(m):
    m = raw_input('How many miles? ')
    return int(m)

start = elapsed('start')
warmup = elapsed('warmup')
wmile = mile('wmile')
tempo = elapsed('tempo')
tmile = mile('tmile')
cooloff = elapsed('cooloff')
cmile = mile('cmile')

hour = (start + warmup * wmile + tempo * tmile + cooloff * cmile) // 3600
minute = (start + warmup * wmile + tempo * tmile + cooloff * cmile - hour * 3600) // 60
second = (start + warmup * wmile + tempo * tmile + cooloff * cmile - hour * 3600) % 60

print('Your run ended at %02d:%02d:%02d' % (hour, minute, second))

In this code, the time prompts are all the same: "Enter time (hh:mm:ss):" I want each prompt to refer to its variable name, e.g., "Enter start time (hh:mm:ss)" or "Enter time (hh:mm:ss): (warmup)". Is there a way to do this?

Note: While this may technically be a duplicate, I have examined the similar questions, but decided that both the questions and the answers provided were on the more unspecific side, and therefore decided to ask my question anyway.

Body:
def enter_time(specify_string):
    print("Please enter the", specify_string, 'time in format hh:mm:ss > ', end='')
    hh, mm, ss = input().split(':')
    return (hh, mm, ss)

start_time = enter_time('start')
finish_time = enter_time('finish')

>>>Please enter the start time in format hh:mm:ss >13:32:34
>>>Please enter the finish time in format hh:mm:ss >12:21:21
>>>start_time
(13, 32, 34)

Now you can call the function with string arguments in the function call, and it will generalise the function for different requirements.

It is better to move the time between functions in a more readable format, such as a tuple. You can make more functions, eg:
- Test valid time entered
- Convert tuple to seconds for calculations
- Convert seconds back to tuple format
ect.

Let me know if I misunderstood you.


问:
How to call a function, but not receive a response until there is a value?
I have a function that queries the DOM and returns an array of data attributes.

```<code>var getUIDs = function () {

    $list = $('.foo');

    if ( $list.length ) {

        // loop through all the .foos and build an array
        return fooArray;

    } else {

        setTimeout(function(){
            getUIDs()
        }, 500);

    }

}
</code>```

This function can sometimes be called prior to .foo being present in the DOM. That's why if I check every half second or so, within a few seconds the array will exist and I could send it back.

My question is, is there an established pattern I should follow that allows a function to be called, but will not receive a return value until there is one?

答:
If you're downvoting this, please explain why in the comments!

Are you wanting the code to stall until the data is present? The way I see it, the best way is to ensure the data is there first. It's not really a scripting issue so much as a logic issue.

In this case, I highly recommend arrive.js to add a callback for when the element has arrived in the DOM.

Alternative Bad Way That Can Be Useful in Limited Situations

Another way to do it would be to not return until the condition is met. This will block the browser for up to 30 seconds (so it's very bad for a user-facing website), but it might suit your case:

```<code>var getUIDs = function () {

    $list = $('.foo');
    var startTime = new Date().getTime();
    var currentTime = startTime;

    while ( !$foo.length) {

        currentTime = new Date().getTime();
        if ( (currentTime - startTime) > 30000 ) {
            return null; //or whatever you want to do to indicate an error
        }

    }

    return fooArray;

}
</code>```

Body:
I have a function that queries the DOM and returns an array of data attributes.

var getUIDs = function () {

    $list = $('.foo');

    if ( $list.length ) {

        // loop through all the .foos and build an array
        return fooArray;

    } else {

        setTimeout(function(){
            getUIDs()
        }, 500);

    }

}

This function can sometimes be called prior to .foo being present in the DOM. That's why if I check every half second or so, within a few seconds the array will exist and I could send it back.

My question is, is there an established pattern I should follow that allows a function to be called, but will not receive a return value until there is one?

Body:
If you're downvoting this, please explain why in the comments!

Are you wanting the code to stall until the data is present? The way I see it, the best way is to ensure the data is there first. It's not really a scripting issue so much as a logic issue.

In this case, I highly recommend arrive.js to add a callback for when the element has arrived in the DOM.

Alternative Bad Way That Can Be Useful in Limited Situations

Another way to do it would be to not return until the condition is met. This will block the browser for up to 30 seconds (so it's very bad for a user-facing website), but it might suit your case:

var getUIDs = function () {

    $list = $('.foo');
    var startTime = new Date().getTime();
    var currentTime = startTime;

    while ( !$foo.length) {

        currentTime = new Date().getTime();
        if ( (currentTime - startTime) > 30000 ) {
            return null; //or whatever you want to do to indicate an error
        }

    }

    return fooArray;

}


问:
Rmi in Java - Chat Application with need of modification, but How?
I have made java RMI application - Chat.

Chat Class:

```<code>public class Chat extends UnicastRemoteObject implements ChatInterface  {

    public String name;
    public ChatInterface client=null;

    public Chat(String n)  throws RemoteException {
        this.name=n;
    }
    public String getName() throws RemoteException {
        return this.name;
    }

    public void setClient(ChatInterface c){
        client=c;
    }

    public ChatInterface getClient(){
        return client;
    }

    public void send(String s) throws RemoteException{
        System.out.println(s);
    }
}
</code>```

ChatClient class:

```<code>    import java.rmi.*;
    import java.rmi.server.*;
    import java.util.*;

    public class ChatClient {
        public static void main (String[] argv) {
            try {
                System.setProperty("java.rmi.server.hostname","127.0.0.1");
                System.setSecurityManager(new RMISecurityManager());
                Scanner s=new Scanner(System.in);
                System.out.println("Enter Your name and press Enter:");
                String name=s.nextLine().trim();
                ChatInterface client = new Chat(name);
                ChatInterface server = (ChatInterface)Naming.lookup("rmi://localhost/ABC");
                String msg="["+client.getName()+"] got connected";
                server.send(msg);
                System.out.println("[System] Chat Remote Object is ready:");
                server.setClient(client);

                while(true){
                    msg=s.nextLine().trim();
                    msg="["+client.getName()+"] "+msg;
                    server.send(msg);
                }

            }catch (Exception e) {
                System.out.println("[System] Server failed: " + e);
            }
        }
    }
</code>```

ChatInterface interface:

```<code>public interface ChatInterface extends Remote{
    public String getName() throws RemoteException;
    public void send(String msg) throws RemoteException;
    public void setClient(ChatInterface c)throws RemoteException;
    public ChatInterface getClient() throws RemoteException;
}
</code>```

ChatServer class:

```<code>public class ChatServer {
    public static void main (String[] argv) {
        try {
            System.setProperty("java.rmi.server.hostname","127.0.0.1");
            System.setSecurityManager(new RMISecurityManager());
            Scanner s=new Scanner(System.in);
            System.out.println("Enter Your name and press Enter:");
            String name=s.nextLine().trim();

            Chat server = new Chat(name);

            Naming.rebind("rmi://localhost/ABC", server);

            System.out.println("[System] Chat Remote Object is ready:");

            while(true){
                String msg=s.nextLine().trim();
                if (server.getClient()!=null){
                    ChatInterface client=server.getClient();
                    msg="["+server.getName()+"] "+msg;
                    client.send(msg);
                }
            }
        }catch (Exception e) {
            System.out.println("[System] Server failed: " + e);
        }
    }
}
</code>```

Chat - the same code in both projects

ChatInterface - the same code in both projects too

ChatClient - ChatServer - they ones that have different code

It looks like this: How it looks inside Eclipse (hierarchy)

And problem is, that this chat works something like...
We got all messages (like whole history) but when user send new message.
For example, we have user1, user2, user3.

User1 send message: 'FUN!!!'

User2 and User3 see nothing.

User2 send "okkk"

Now user1 sees still only "FUN!!!"

User2 see "FUN!!!" and "okkk"

And User3 sees nothing, cuz didn't send any message, so have nothing.

And that's bad :/. It's like user have to send something to get messages. Even only "space", but still something. Otherwise he won't get any message.

I need to make this to automatically send all users new messages when they are send by one user. Like "update".'

It needs to be like

User1 got nothing

User2 got nothing

User3 got nothing

Users3 sends 'AAAA'

All users have now 'AAAA'

答:
```<code>public interface ChatInterface extends Remote{
    public String getName() throws RemoteException;
    public void send(String msg) throws RemoteException;
    public void setClient(ChatInterface c)throws RemoteException;
    public ChatInterface getClient() throws RemoteException;
}
</code>```

The problem starts here. The nature of setClient() is that the server only knows about one client at a time. Surely the server should have a list of clients, and the method should be addClient(ChatInterface c).

The purpose of getClient() as a remote method eludes me.

Body:
I have made java RMI application - Chat.

Chat Class:

public class Chat extends UnicastRemoteObject implements ChatInterface  {

    public String name;
    public ChatInterface client=null;

    public Chat(String n)  throws RemoteException {
        this.name=n;
    }
    public String getName() throws RemoteException {
        return this.name;
    }

    public void setClient(ChatInterface c){
        client=c;
    }

    public ChatInterface getClient(){
        return client;
    }

    public void send(String s) throws RemoteException{
        System.out.println(s);
    }
}

ChatClient class:

    import java.rmi.*;
    import java.rmi.server.*;
    import java.util.*;

    public class ChatClient {
        public static void main (String[] argv) {
            try {
                System.setProperty("java.rmi.server.hostname","127.0.0.1");
                System.setSecurityManager(new RMISecurityManager());
                Scanner s=new Scanner(System.in);
                System.out.println("Enter Your name and press Enter:");
                String name=s.nextLine().trim();
                ChatInterface client = new Chat(name);
                ChatInterface server = (ChatInterface)Naming.lookup("rmi://localhost/ABC");
                String msg="["+client.getName()+"] got connected";
                server.send(msg);
                System.out.println("[System] Chat Remote Object is ready:");
                server.setClient(client);

                while(true){
                    msg=s.nextLine().trim();
                    msg="["+client.getName()+"] "+msg;
                    server.send(msg);
                }

            }catch (Exception e) {
                System.out.println("[System] Server failed: " + e);
            }
        }
    }

ChatInterface interface:

public interface ChatInterface extends Remote{
    public String getName() throws RemoteException;
    public void send(String msg) throws RemoteException;
    public void setClient(ChatInterface c)throws RemoteException;
    public ChatInterface getClient() throws RemoteException;
}

ChatServer class:

public class ChatServer {
    public static void main (String[] argv) {
        try {
            System.setProperty("java.rmi.server.hostname","127.0.0.1");
            System.setSecurityManager(new RMISecurityManager());
            Scanner s=new Scanner(System.in);
            System.out.println("Enter Your name and press Enter:");
            String name=s.nextLine().trim();

            Chat server = new Chat(name);

            Naming.rebind("rmi://localhost/ABC", server);

            System.out.println("[System] Chat Remote Object is ready:");

            while(true){
                String msg=s.nextLine().trim();
                if (server.getClient()!=null){
                    ChatInterface client=server.getClient();
                    msg="["+server.getName()+"] "+msg;
                    client.send(msg);
                }
            }
        }catch (Exception e) {
            System.out.println("[System] Server failed: " + e);
        }
    }
}

Chat - the same code in both projects

ChatInterface - the same code in both projects too

ChatClient - ChatServer - they ones that have different code

It looks like this: How it looks inside Eclipse (hierarchy)

And problem is, that this chat works something like...
We got all messages (like whole history) but when user send new message.
For example, we have user1, user2, user3.

User1 send message: 'FUN!!!'

User2 and User3 see nothing.

User2 send "okkk"

Now user1 sees still only "FUN!!!"

User2 see "FUN!!!" and "okkk"

And User3 sees nothing, cuz didn't send any message, so have nothing.

And that's bad :/. It's like user have to send something to get messages. Even only "space", but still something. Otherwise he won't get any message.

I need to make this to automatically send all users new messages when they are send by one user. Like "update".'

It needs to be like

User1 got nothing

User2 got nothing

User3 got nothing

Users3 sends 'AAAA'

All users have now 'AAAA'

Body:
public interface ChatInterface extends Remote{
    public String getName() throws RemoteException;
    public void send(String msg) throws RemoteException;
    public void setClient(ChatInterface c)throws RemoteException;
    public ChatInterface getClient() throws RemoteException;
}

The problem starts here. The nature of setClient() is that the server only knows about one client at a time. Surely the server should have a list of clients, and the method should be addClient(ChatInterface c).

The purpose of getClient() as a remote method eludes me.


问:
Detect physical CapsLock position after sending a KEYEVENTF_KEYUP to the Virtual Keyboard Buffer
I am developing a program that will make the CapsLock key work as a control key under Windows. I understand that this can be trivially done with a registry change. Unfortunately, I am not able to run that registry change, nor am I able to run a device driver.

My idea is to watch the keyscans coming over the virtual keyboard. When I see a CapsLock down event, I will send a CapsLock Up event, a second CapsLock down event, a second CapsLock Up event, and then a control-key down event. All of this code works!  However, I have not been able to catch the physical UP action of the CapsLock key.

I've tried reading the CapsLock Up key with both win32api.GetKeyState() and win32api.GetAsyncKeyState(). After I stuff the CapsLock up event, they both say that the key is up. There seems to be no way to look at the actual hardware and see that it's still down.

Is there a way to catch the events BEFORE they go to the virtual keyboard buffer? If I could do that, I could catch the REAL CapsLock down and Up events. But I can't seem to find it.

I need to be able to do this entirely from the win32 api.

答:
GetKeyState is the state your thread was in when it last received a message. GetAsyncKeyState is the current state. These functions can miss events if you are trying to pull for state changes.

Use a low-level keyboard hook to see all input early in the input processing chain. You can also hook your thread with a normal keyboard hook if you don't care about global events.


问:
How to do tagged logging in Express
A log for a request looks like this:

```<code>Received a new product Widget-1
Started to store product
POST /products 200 52.240 ms - 2
Product stored
</code>```

Where the first, second and fourth lines are logs I created using console.log. The third is done by Morgan.

My problem is that the (asynchronous) function that stores the products in the db is relatively slow so I have logs like this

```<code>Received a new product Widget-1
Started to store product
POST /products 200 52.240 ms - 2
Received a new product Widget-2
Started to store product
POST /products 200 52.240 ms - 2
Product stored
Product stored
</code>```

How can I tag each log line so I can group the logs of a request easily? Something like

```<code>[11111] Received a new product Widget-1
[11111] Started to store product
[11111] POST /products 200 52.240 ms - 2
[aaaaa] Received a new product Widget-2
[aaaaa] Started to store product
[aaaaa] POST /products 200 52.240 ms - 2
[11111] Product stored
[aaaaa] Product stored
</code>```

The tag can any format, I just want to filter the lines that belong to the same request.

I tried this in Express creating a middleware that assigned a random number to a req.id and used that number in each console.log, for example:

```<code>console.log(`[${req.id}] Started to store product`)
</code>```

But I would prefer to define the tag in a middleware or configuration, and then use console.log("Started to store product")

答:
Attaching an unique ID to the req was the right direction.

Pushing it further, we can attach a log() function to the req that will log anything prefixed with the req.id.

Which gives us:

```<code>const myMiddleware = (req, res, next) => {
  req.id = getUniqueId();
  req.log = (...args) => console.log(`[${req.id}]`, ...args);
};
</code>```

... and later use:

```<code>// later
req.log('Started to store product'); // Outputs `[123456] Started to store product`
</code>```

Regarding the fact that you want the Morgan log to be tagged also, this will not be possible to tag it on a per-request basis unless Morgan can be provided a custom log function.

Title: How to do tagged logging in Express

Body:
A log for a request looks like this:

Received a new product Widget-1
Started to store product
POST /products 200 52.240 ms - 2
Product stored

Where the first, second and fourth lines are logs I created using console.log. The third is done by Morgan.

My problem is that the (asynchronous) function that stores the products in the db is relatively slow so I have logs like this

Received a new product Widget-1
Started to store product
POST /products 200 52.240 ms - 2
Received a new product Widget-2
Started to store product
POST /products 200 52.240 ms - 2
Product stored
Product stored

How can I tag each log line so I can group the logs of a request easily? Something like

[11111] Received a new product Widget-1
[11111] Started to store product
[11111] POST /products 200 52.240 ms - 2
[aaaaa] Received a new product Widget-2
[aaaaa] Started to store product
[aaaaa] POST /products 200 52.240 ms - 2
[11111] Product stored
[aaaaa] Product stored

The tag can any format, I just want to filter the lines that belong to the same request.

I tried this in Express creating a middleware that assigned a random number to a req.id and used that number in each console.log, for example:

console.log(`[${req.id}] Started to store product`)

But I would prefer to define the tag in a middleware or configuration, and then use console.log("Started to store product")

Body:
Attaching an unique ID to the req was the right direction.

Pushing it further, we can attach a log() function to the req that will log anything prefixed with the req.id.

Which gives us:

const myMiddleware = (req, res, next) => {
  req.id = getUniqueId();
  req.log = (...args) => console.log(`[${req.id}]`, ...args);
};

... and later use:

// later
req.log('Started to store product'); // Outputs `[123456] Started to store product`

Regarding the fact that you want the Morgan log to be tagged also, this will not be possible to tag it on a per-request basis unless Morgan can be provided a custom log function.


问:
Igloo Software: Confirm successful transfer to local machine
I have a lot of files stored in Igloo that I am copying over to my local machine, and must confirm that everything was indeed copied over successfully without missing any files/folders. There are lots of directories and sub-directories so manually checking that takes a long time. Does anybody know how to use Git/winmerge, Igloo's version control, or another 'diff checker' solution to make sure everything was copied over successfully from Igloo to my local machine?</p>

答:
If you use git to version control your lgloo software, it will make things easier.

Remote git repo: setup your own remote repo, or sign up for github/bitbucket etc and hosted your remote repo there.

Local git repo: make changes for lgloo and sync with remote repo.

First time to sync with local repo to remote:

```<code># In an empty local path
git init
# copy lgloo software in the path
git add .
git commit -m 'init commit'
git remote add origin <URL for remote repo>
git push -u origin master
</code>```

After that, when you want to copy the whole lgloo software into your local machine and check if it copied successfully. You just need to execute the commands in the same local path:

```<code>git pull origin master
git log master..origin/master
</code>```

If there is no output after git log master..origin/master, that means you copied the latest lgloo software successfully.

Body:
If you use git to version control your lgloo software, it will make things easier.

Remote git repo: setup your own remote repo, or sign up for github/bitbucket etc and hosted your remote repo there.

Local git repo: make changes for lgloo and sync with remote repo.

First time to sync with local repo to remote:

# In an empty local path
git init
# copy lgloo software in the path
git add .
git commit -m 'init commit'
git remote add origin <URL for remote repo>
git push -u origin master

After that, when you want to copy the whole lgloo software into your local machine and check if it copied successfully. You just need to execute the commands in the same local path:

git pull origin master
git log master..origin/master

If there is no output after git log master..origin/master, that means you copied the latest lgloo software successfully.


问:
Including template PHP file at the end of functions file
I'm learning basic PHP with a book. Inside the book I have done this example:

```<code><?php
session_start()

if(array_key_exists("taskName", $_GET)) {
    $_SESSION["taskList"][] = $_GET["taskName"];
}

$taskList= [];

if(array_key_exists("taskList", $_SESSION)) {
    $taskList = $_SESSION["taskList"];
}

include "template.php";
</code>```

The "include template.php" at the end of "functions.php" file is used in the book and it seems to work. But, when using in my example, the template.php which is used to be displayed the results, didn't work, here are the template.php part which uses PHP code:

```<code><table>
            <tr>
                <th>Tasks</th>
            </tr>
            <?php foreach($taskList as $task) : ?>
            <tr>
                <td><?=$task?></td>
            </tr>
            <?php endforeach; ?>
        </table>
</code>```

Here are displayed errors:

```<code>Notice: Undefined variable: taskList in C:\xampp\htdocs\to-do-list\template.php on line 27

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\to-do-list\template.php on line 27
</code>```

In my understanding, the template.php isn't getting info from functions.php as the book it gets.

PHP Documentation

In this documentation above have the following example:

```<code><?php
$a = 1;
include 'b.inc';
?>
</code>```

So, b.inc will have the $a var. It's the same what happens in the book.

答:
When I tried below code it works fine on my computer (it produces some output).

File: first.php

```<code><?php
$taskList = [];
$taskList[]=5;
$taskList[]=6;
include 'second.php';
?>
</code>```

File: second.php

```<code><table>
  <tr>
    <th>Tasks</th>
  </tr>
  <?php foreach($taskList as $task) : ?>
    <tr>
      <td><?=$task?></td>
    </tr>
  <?php endforeach; ?>
</table>
</code>```

Body:
I'm learning basic PHP with a book. Inside the book I have done this example:

<?php
session_start()

if(array_key_exists("taskName", $_GET)) {
    $_SESSION["taskList"][] = $_GET["taskName"];
}

$taskList= [];

if(array_key_exists("taskList", $_SESSION)) {
    $taskList = $_SESSION["taskList"];
}

include "template.php";

The "include template.php" at the end of "functions.php" file is used in the book and it seems to work. But, when using in my example, the template.php which is used to be displayed the results, didn't work, here are the template.php part which uses PHP code:

                Tasks

            <?php foreach($taskList as $task) : ?>

                <?=$task?>

            <?php endforeach; ?>

Here are displayed errors:

Notice: Undefined variable: taskList in C:\xampp\htdocs\to-do-list\template.php on line 27

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\to-do-list\template.php on line 27

In my understanding, the template.php isn't getting info from functions.php as the book it gets.

PHP Documentation

In this documentation above have the following example:

<?php
$a = 1;
include 'b.inc';
?>

So, b.inc will have the $a var. It's the same what happens in the book.

Body:
When I tried below code it works fine on my computer (it produces some output).

File: first.php

<?php
$taskList = [];
$taskList[]=5;
$taskList[]=6;
include 'second.php';
?>

File: second.php

<table>
  <tr>
    <th>Tasks</th>
  </tr>
  <?php foreach($taskList as $task) : ?>
    <tr>
      <td><?=$task?></td>
    </tr>
  <?php endforeach; ?>
</table>


问:
Locating a button from outside its activity
I have Firebaselistener class and it listens for the value of 1. When this value is reached I want the button drawable to change. Originally I had this all set up in my main activity and it worked OK using:

```<code>if(dls==1){
m.setBackground(getResources().getDrawable(R.drawable.buttonbkground2));
}
</code>```

from with in my main activity using a valueEventlistener and listening for the value.

But now I've set up a class to do the same thing I can't access the button ids from the main activity.

```<code>public class RewardValueListener  implements ValueEventListener {

FirebaseAuth mAuth;
String userid;
int i;
View view;
String dls;
Button mButton;
Context c;

public RewardValueListener() {

}

@Override
public void onDataChange(DataSnapshot dataSnapshot) {

    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    userid = user.getUid();
    dls = dataSnapshot.child(userid).child("counter").getValue(String.class);
    Log.d("tag", "Value: " + dls);
    i = Integer.parseInt(dls);
    if (i == 1) {

        Log.d("tag", "Congrats " + i);

        mButton.setBackground(c.getResources().getDrawable(R.drawable.buttonbkground2));

    }
}
@Override
public void onCancelled(FirebaseError firebaseError) {

}
</code>```

***Code edit with cricket's answer included

```<code>  public void getButton(Button button,Context context) {
    mButton = button;
    c=context;
  }
</code>```

I know it's something to do with calling the view but how and where do I call it?

Edit

Thanks to @cricket_007 for his answer which works great. Now I have the code working is there away to call my Listener class to change all the buttons in my main activity rather than just one.

I can get it to work if for every button if write the code this way but is there a way to condense it so I don't have to overflow my main activity:

```<code>  RewardValueListener reward1 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward1);
    reward1.getButton(mstreaming,mcontext);
    RewardValueListener reward2 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward2);
    reward2.getButton(mcustom,mcontext);
    RewardValueListener reward3 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward3);
    reward3.getButton(mlauncher,mcontext);
    RewardValueListener reward4 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward4);
    reward4.getButton(mmovies,mcontext);
  etc etc...
</code>```

答:
Just add to the constructor.

```<code>final Button mButton;
final Context mContext;
public RewardValueListener(Context context, Button button) {
    mContext = context;
    mButton = button;
}
</code>```

And use that instead of findViewById for the button, and mContext.getResources()

Note: you'll need to have a button available when you create this class

ContentLicense: CC BY-SA 4.0

Body:
I have Firebaselistener class and it listens for the value of 1. When this value is reached I want the button drawable to change. Originally I had this all set up in my main activity and it worked OK using:

if(dls==1){
m.setBackground(getResources().getDrawable(R.drawable.buttonbkground2));
}

from with in my main activity using a valueEventlistener and listening for the value.

But now I've set up a class to do the same thing I can't access the button ids from the main activity.

public class RewardValueListener  implements ValueEventListener {

FirebaseAuth mAuth;
String userid;
int i;
View view;
String dls;
Button mButton;
Context c;

public RewardValueListener() {

}

@Override
public void onDataChange(DataSnapshot dataSnapshot) {

    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    userid = user.getUid();
    dls = dataSnapshot.child(userid).child("counter").getValue(String.class);
    Log.d("tag", "Value: " + dls);
    i = Integer.parseInt(dls);
    if (i == 1) {

        Log.d("tag", "Congrats " + i);

        mButton.setBackground(c.getResources().getDrawable(R.drawable.buttonbkground2));

    }
}
@Override
public void onCancelled(FirebaseError firebaseError) {

}

***Code edit with cricket's answer included

  public void getButton(Button button,Context context) {
    mButton = button;
    c=context;
  }

I know it's something to do with calling the view but how and where do I call it?

Edit

Thanks to @cricket_007 for his answer which works great. Now I have the code working is there away to call my Listener class to change all the buttons in my main activity rather than just one.

I can get it to work if for every button if write the code this way but is there a way to condense it so I don't have to overflow my main activity:

  RewardValueListener reward1 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward1);
    reward1.getButton(mstreaming,mcontext);
    RewardValueListener reward2 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward2);
    reward2.getButton(mcustom,mcontext);
    RewardValueListener reward3 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward3);
    reward3.getButton(mlauncher,mcontext);
    RewardValueListener reward4 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward4);
    reward4.getButton(mmovies,mcontext);
  etc etc...

Body:
Just add to the constructor.

final Button mButton;
final Context mContext;
public RewardValueListener(Context context, Button button) {
    mContext = context;
    mButton = button;
}

And use that instead of findViewById for the button, and mContext.getResources()

Note: you'll need to have a button available when you create this class


问:
How to find out when a particular table was created in Oracle?
In Oracle, is there a way to find out when a particular table was created?

Similarly, is there a way to find out when a particular row was inserted/last updated?

答:
```<code>SELECT created
  FROM dba_objects
 WHERE object_name = <<your table name>>
   AND owner = <<owner of the table>>
   AND object_type = 'TABLE'
</code>```

will tell you when a table was created (if you don't have access to DBA_OBJECTS, you could use ALL_OBJECTS instead assuming you have SELECT privileges on the table).

The general answer to getting timestamps from a row, though, is that you can only get that data if you have added columns to track that information (assuming, of course, that your application populates the columns as well).  There are various special cases, however.  If the DML happened relatively recently (most likely in the last couple hours), you should be able to get the timestamps from a flashback query.  If the DML happened in the last few days (or however long you keep your archived logs), you could use LogMiner to extract the timestamps but that is going to be a very expensive operation particularly if you're getting timestamps for many rows.  If you build the table with ROWDEPENDENCIES enabled (not the default), you can use

```<code>SELECT scn_to_timestamp( ora_rowscn ) last_modified_date,
       ora_rowscn last_modified_scn,
       <<other columns>>
  FROM <<your table>>
</code>```

to get the last modification date and SCN (system change number) for the row.  By default, though, without ROWDEPENDENCIES, the SCN is only at the block level.  The SCN_TO_TIMESTAMP function also isn't going to be able to map SCN's to timestamps forever.

Body:
SELECT created
  FROM dba_objects
 WHERE object_name = <<your table name>>
   AND owner = <<owner of the table>>
   AND object_type = 'TABLE'

will tell you when a table was created (if you don't have access to DBA_OBJECTS, you could use ALL_OBJECTS instead assuming you have SELECT privileges on the table).

The general answer to getting timestamps from a row, though, is that you can only get that data if you have added columns to track that information (assuming, of course, that your application populates the columns as well).  There are various special cases, however.  If the DML happened relatively recently (most likely in the last couple hours), you should be able to get the timestamps from a flashback query.  If the DML happened in the last few days (or however long you keep your archived logs), you could use LogMiner to extract the timestamps but that is going to be a very expensive operation particularly if you're getting timestamps for many rows.  If you build the table with ROWDEPENDENCIES enabled (not the default), you can use

SELECT scn_to_timestamp( ora_rowscn ) last_modified_date,
       ora_rowscn last_modified_scn,
       <<other columns>>
  FROM <<your table>>

to get the last modification date and SCN (system change number) for the row.  By default, though, without ROWDEPENDENCIES, the SCN is only at the block level.  The SCN_TO_TIMESTAMP function also isn't going to be able to map SCN's to timestamps forever.


问:
Accessing Bloomberg API from client's browser in javascript
Is it possible to access blpapi from javascript running in the client's browser?

I wish to access bloomberg's API from javascript running in the client's browser, in the assumption that the client has an open bloomberg session and therefore bbcomm is running.

Conceptually, this would be the same as accessing the blpapi on the client side from python.

However, all existing solutions I found in js appear to be server-side:

blpapi-node (node-based)

blpapi-httm (creates a server where to post http request)

blpapi-react (cannot make this module work)

答:
Now you can access Bloomberg data natively in JavaScript via Web AppPortal. This allows you to write web based applications that run inside LP Components.

To learn more about Web AppPortal, go to MYAP 5

To download the SDK, please type SDK -> select SDK -> AppPortal Web SDK -> click Install.


问:
Can a struct in UPC have shared array as a field?
I need to store shared array inside a struct in UPC. Is it possible to do?</p>

答:
Struct fields cannot be shared-qualified, for the same reason they cannot be declared with static or extern - a struct field does not carry independent storage-class information (ie because the fields of a struct are always stored contiguously, and could be used for example to declare a stack variable).

However, a struct may contain an array field, and the struct can then be used to define a shared object, eg:

```<code>struct S {
  int array[100];
  int foo;
};
shared struct S data[THREADS];
...
data[MYTHREAD].array[0] = MYTHREAD;
</code>```

However note the distribution of data in this example is one struct per thread, the array field is not independently distributed across threads.

A struct may also contain a pointer to a shared array, eg:

```<code>#include <upc.h>

struct R {
  shared int *sa;
  int bar;
};
...
struct R r;
r.sa = upc_all_alloc(THREADS, sizeof(int));
r.sa[MYTHREAD] = MYTHREAD;
</code>```

in this case the shared array is distributed across threads, but the storage is not embedded in the struct - the struct field is just a pointer-to-shared (and thanks to C rules can be accessed with array syntax).

Body:
Struct fields cannot be shared-qualified, for the same reason they cannot be declared with static or extern - a struct field does not carry independent storage-class information (ie because the fields of a struct are always stored contiguously, and could be used for example to declare a stack variable).

However, a struct may contain an array field, and the struct can then be used to define a shared object, eg:

struct S {
  int array[100];
  int foo;
};
shared struct S data[THREADS];
...
data[MYTHREAD].array[0] = MYTHREAD;

However note the distribution of data in this example is one struct per thread, the array field is not independently distributed across threads.

A struct may also contain a pointer to a shared array, eg:

#include <upc.h>

struct R {
  shared int *sa;
  int bar;
};
...
struct R r;
r.sa = upc_all_alloc(THREADS, sizeof(int));
r.sa[MYTHREAD] = MYTHREAD;

in this case the shared array is distributed across threads, but the storage is not embedded in the struct - the struct field is just a pointer-to-shared (and thanks to C rules can be accessed with array syntax).


问:
Is possible to change a property inside a item and return the item itself?
I have a code like this on my app

var name = 'TesT';
var nameLowercase = name && name.toLowerCase (),
    namesToTest = ['asd', 'asd1', 'TesT'];

var findCorrectName = R.pipe(
    R.map(R.toLower),
    R.any(R.equals(nameLowercase))
);

var hasFoundName = findCorrectName (namesToTest);

return hasFoundName;
```

<p>But, now I need to do a search in a list of objects and the property 'name' must be put to lowercase. When found an object that matches my search, I need to get it. </p>

<p>I've read the documentation but I couldn't find a solution.</p>

<pre class="lang-js prettyprint-override"><code>var name = 'TesT';
var nameLowercase = name && name.toLowercase (),
namesToTest = [ { name : 'asd', otherProperties... },
                { name : 'asd1', otherProperties... },
                { name : 'TesT', otherProperties... }];

var findByCorrectName = R.pipe(
    R.map(
        R.pipe(R.prop('name'), R.toLower)),
        R.find(R.propEq('name', nameLowercase))
    );

var foundObject = findByCorrectName (namesToTest);

return foundObject;
</code>```

答:
I would find this a straightforward way to solve your problem:

```<code>const items = [{name : 'asd', x: 1}, {name : 'asd1', x: 2}, {name : 'TesT', x: 3}];

const byNameCi = curry((name, items) => find(
  where({name: pipe(toLower, equals(toLower(name)))}),
  items,
));

byNameCi('TEST', items); //=> {name: "TesT", x: 3}
</code>```

The curry might not be necessary for your use case, but it would also allow this:

```<code>const findAsd = byNameCi('Asd');
// later
findAsd(items); //=> {name: "asd", x: 1}
</code>```

Note that this returns your original values, without the toLowerCase transformation.  If you want to return ones with transformed names, then I might alter it like this:

```<code>const byTransformedNameCi = curry((name, items) => find(
  where({name: pipe(toLower, equals(toLower(name)))}),
  map(evolve({name: toLower}), items),
));

byTransformedNameCi('TEST', items); //=> {name: "test", x: 3}
</code>```

Or, as you say, using lensProp and over instead of evolve.

While it's probably possible to make these point-free, these are already fairly readable, so I can't see a good reason to spend any effort on it.

You can see these approaches on the Ramda REPL.

You asked in your title about transforming a property and returning the object.  Ramda will not actually alter your data; if you're looking for that, Ramda is not the right library for you.  But it will return a new object with that property transformed, and it has many functions that do this in various ways, including the ones we've already mentioned, assoc, adjust, and others.

Body:
I have a code like this on my app

var name = 'TesT';
var nameLowercase = name && name.toLowerCase (),
    namesToTest = ['asd', 'asd1', 'TesT'];

var findCorrectName = R.pipe(
    R.map(R.toLower),
    R.any(R.equals(nameLowercase))
);

var hasFoundName = findCorrectName (namesToTest);

return hasFoundName;

But, now I need to do a search in a list of objects and the property 'name' must be put to lowercase. When found an object that matches my search, I need to get it.

I've read the documentation but I couldn't find a solution.

var name = 'TesT';
var nameLowercase = name && name.toLowercase (),
namesToTest = [ { name : 'asd', otherProperties... },
                { name : 'asd1', otherProperties... },
                { name : 'TesT', otherProperties... }];

var findByCorrectName = R.pipe(
    R.map(
        R.pipe(R.prop('name'), R.toLower)),
        R.find(R.propEq('name', nameLowercase))
    );

var foundObject = findByCorrectName (namesToTest);

return foundObject;

Body:
I would find this a straightforward way to solve your problem:

const items = [{name : 'asd', x: 1}, {name : 'asd1', x: 2}, {name : 'TesT', x: 3}];

const byNameCi = curry((name, items) => find(
  where({name: pipe(toLower, equals(toLower(name)))}),
  items,
));

byNameCi('TEST', items); //=> {name: "TesT", x: 3}

The curry might not be necessary for your use case, but it would also allow this:

const findAsd = byNameCi('Asd');
// later
findAsd(items); //=> {name: "asd", x: 1}

Note that this returns your original values, without the toLowerCase transformation.  If you want to return ones with transformed names, then I might alter it like this:

const byTransformedNameCi = curry((name, items) => find(
  where({name: pipe(toLower, equals(toLower(name)))}),
  map(evolve({name: toLower}), items),
));

byTransformedNameCi('TEST', items); //=> {name: "test", x: 3}

Or, as you say, using lensProp and over instead of evolve.

While it's probably possible to make these point-free, these are already fairly readable, so I can't see a good reason to spend any effort on it.

You can see these approaches on the <a href="http://ramdajs.com/repl/?v=0.24.1#?const%20items%20%3D%20%5B%7Bname%20%3A%20%27asd%27%2C%20x%3A%201%7D%2C%20%7Bname%20%3A%20%27asd1%27%2C%20x%3A%202%7D%2C%20%7Bname%20%3A%20%27TesT%27%2C%20x%3A%203%7D%5D%3B%0A%0Aconst%20byNameCi%20%3D%20curry%28%28name%2C%20items%29%20%3D%3E%20find%28%0A%20%20where%28%7Bname%3A%20pipe%28toLower%2C%20equals%28toLower%28name%29%29%29%7D%29%2C%0A%20%20items%2C%0A%29%29%3B%0A%0AbyNameCi%28%27TEST%27%2C%20items%29%3B%20%2F%2F%3D%3E%20%7Bname%3A%20%22TesT%22%2C%20x%3A%203%7D%0A%0Aconst%20findAsd%20%3D%20byNameCi%28%27Asd%27%29%3B%0AfindAsd%28items%29%3B%20%2F%2F%3D%3E%20%7Bname%3A%20%22asd%22%2C%20x%3A%201%7D%0A%0A%0Aconst%20byTransformedNameCi%20%3D%20curry%28%28name%2C%20items%29%20%3D%3E%20find%28%0A%20%20where%28%7Bname%3A%20pipe%28toLower%2C%20equals%28toLower%28name%29%29%29%7D%29%2C%0A%20%20map%28evolve%28%7Bname%3A%20toLower%7D%29%2C%20items%29%2C%0A%29%29%3B%0A%0AbyTransformedNameCi%28%27TEST%27%2C%20items%29%3B%20%2F%2F%3D%3E%20%7Bname%3A%20%22TesT%22%2C%20x%3A%203%7D%0A" rel="nofollow noreferrer">Ramda REPL.

You asked in your title about transforming a property and returning the object.  Ramda will not actually alter your data; if you're looking for that, Ramda is not the right library for you.  But it will return a new object with that property transformed, and it has many functions that do this in various ways, including the ones we've already mentioned, assoc, adjust, and others.


问:
Laravel Form Request Dynamic Fields dissapear on Redirect
I have a form, a button to add one more item to form, and Form Request validation file.
All works fine except one thing:
When user adds one more field (after hitting "+Add doc number") and enters value which is already in the DB:

Validation works fine and redirects user to the same page, but now only one field is present:

QUESTION: how to make the all fields present in pic 1 remain in pic 2?

My code:

Form itself:

```<code><form>
  <div class='inputs'>
    <label>Doc number: </label>
    <input type="text" name="doc_fullnumber[1]" value="{{old('doc_fullnumber.1')}}">
  </div>
  <button id='add_item'>Add doc number</button>
  <input type="submit" value="Submit">
</form>
</code>```

a jquery code which adds one more input if user clicks the "button":

```<code>$(document).ready(function(){
    $('#add_item').on('click', function (event) {
        event.preventDefault();
        var i = 2;
        $new_docnumber = $(
            '<br><br>'+
            '<label>Номер док-та: </label>'+
            '<input type="text" name="doc_fullnumber['+i+']" placeholder="Номер док-та" value="{{old('doc_fullnumber.[i]')}}">');
        $('.inputs').append($new_passenger);
    })
})
</code>```

a working form validation in a Laravel's FormRequest file:

```<code>public function rules()
{
    return [

        'doc_fullnumber' => 'unique:tourists'

    ];
}

public function messages()
{
    return ['doc_fullnumber.unique' => 'Doc number is already in DB!'];
}
</code>```

Appreciate any help folks!

答:
try this one

return Redirect::back()->withInput(Input::all());

Body:
I have a form, a button to add one more item to form, and Form Request validation file.
All works fine except one thing:
When user adds one more field (after hitting "+Add doc number") and enters value which is already in the DB:

Validation works fine and redirects user to the same page, but now only one field is present:

QUESTION: how to make the all fields present in pic 1 remain in pic 2?

My code:

Form itself:

<form>

    Doc number:
    <input type="text" name="doc_fullnumber[1]" value="{{old('doc_fullnumber.1')}}">

  <button id='add_item'>Add doc number</button>
  <input type="submit" value="Submit">
</form>

a jquery code which adds one more input if user clicks the "button":

$(document).ready(function(){
    $('#add_item').on('click', function (event) {
        event.preventDefault();
        var i = 2;
        $new_docnumber = $(
            '

'+
            'Номер док-та: '+
            '<input type="text" name="doc_fullnumber['+i+']" placeholder="Номер док-та" value="{{old('doc_fullnumber.[i]')}}">');
        $('.inputs').append($new_passenger);
    })
})

a working form validation in a Laravel's FormRequest file:

public function rules()
{
    return [

        'doc_fullnumber' => 'unique:tourists'

    ];
}

public function messages()
{
    return ['doc_fullnumber.unique' => 'Doc number is already in DB!'];
}

Appreciate any help folks!


问:
Make sure a product has at least one category
Hello wonderful Stackoverflowrians!

I have this DB diagram and I have this postgresql to create the tables:

```<code>CREATE TABLE products (
    prod_id serial PRIMARY KEY,
    name varchar(150) NOT NULL,
    description text,
    purchase_price numeric(10,2) NOT NULL,
    selling_price numeric(10,2) NOT NULL,
    weight numeric(10,2),
    min_quantity int NOT NULL
);

CREATE TABLE categories (
    cat_id serial PRIMARY KEY,
    name varchar(100),
    parent int REFERENCES categories ON DELETE CASCADE
);

CREATE TABLE product_categories (
    prod_id int NOT NULL REFERENCES products,
    cat_id int NOT NULL REFERENCES categories,
    PRIMARY KEY (prod_id, cat_id)
);
</code>```

As you see I have categories with multiple sub-categories, products, and table to make relations between them so I can assign multiple categories to a product.
While writing down the create table queries interesting question pop-up in my mind.

I am not sure if it's even possible but, I am trying to find a way to assure that every product is assigned to least one category. Any ideas?

答:
One method of ensuring that every product is in at least one category is to have a "primary" category in the product table:

```<code>primary_categoryid int not null references categories(cat_id)
</code>```

This does make the primary categoryid "different" from other categories, because it is not in the product_categories table.

If you attempt a solution where you require a row in product_categories, then you have a problem.  The row in product_categories would need to refer to a valid product -- but a product is not valid (by your definition) until it has a category.

Body:
Hello wonderful Stackoverflowrians!

I have this DB diagram and I have this postgresql to create the tables:

CREATE TABLE products (
    prod_id serial PRIMARY KEY,
    name varchar(150) NOT NULL,
    description text,
    purchase_price numeric(10,2) NOT NULL,
    selling_price numeric(10,2) NOT NULL,
    weight numeric(10,2),
    min_quantity int NOT NULL
);

CREATE TABLE categories (
    cat_id serial PRIMARY KEY,
    name varchar(100),
    parent int REFERENCES categories ON DELETE CASCADE
);

CREATE TABLE product_categories (
    prod_id int NOT NULL REFERENCES products,
    cat_id int NOT NULL REFERENCES categories,
    PRIMARY KEY (prod_id, cat_id)
);

As you see I have categories with multiple sub-categories, products, and table to make relations between them so I can assign multiple categories to a product.
While writing down the create table queries interesting question pop-up in my mind.

I am not sure if it's even possible but, I am trying to find a way to assure that every product is assigned to least one category. Any ideas?

Body:
One method of ensuring that every product is in at least one category is to have a "primary" category in the product table:

primary_categoryid int not null references categories(cat_id)

This does make the primary categoryid "different" from other categories, because it is not in the product_categories table.

If you attempt a solution where you require a row in product_categories, then you have a problem.  The row in product_categories would need to refer to a valid product -- but a product is not valid (by your definition) until it has a category.


问:
How do I run Selenium IDE scripts in Selenium RC?
I am new to using the selenium testing tool and would like to know how to run selenium IDE scripts in selenium RC.  I need examples and screenshots please</p>

答:
As far as I know, to run the selenium IDE scripts in RC you have to export them into a particular language (Java, C#, Python). After that, you need to run a RC Server and a RC Client that will send requests to this server.

The first place I would go to get started is this documentation:
http://seleniumhq.org/docs/05_selenium_rc.html


问:
What exactly is stdin?
I am a bit confused regarding the implementation of stdin. What exactly is it? Is it a pointer? I tried to print the size of stdin using sizeof on a 64 bit machine and got 8. I even de-referenced it using *stdin in the %s specifier and got the not used characters in the input stream( all of them). But if I compare its de referenced value inside if I get an error. I know its an input stream. But how is it implemented?

Here is a sample:

```<code>#include<stdio.h>
#include<stdlib.h>

int main(){

    char a[10];

    fgets(a,10,stdin);

    printf("a: %s",a);

    printf("\nstdin: %s",*stdin);

//if(*stdin=="foo"){
//    printf("True");
//}//Error: invalid operands to binary == (have 'FILE' and 'char *')//and casting to char * doesn't help

    printf("\nSize of stdin: %d\n",sizeof(stdin));

    if(stdin!=NULL){
        printf("This statement is always reached");//always printed even in when input is bigger than 10 chars and otherwise
    }

if(!feof(stdin)){
    printf("\nThis statement is also always reached");
}
}
</code>```

When I input

foobar1234567890

I get the result:

a: foobar123

stdin: 4567890

Size of stdin: 8

This statement is always reached

This statement is also always reached

And when I input

foobar

I get the output

a: foobar

stdin:

Size of stdin: 4

This statement is always reached

This statement is also always reached

I understand that stdin is kind of a FILE pointer, but I don't clearly get it. Could anyone explain the above outputs?

答:
stdin,stdout,stderr are 3 opened files for you app to use as the default input file, output file and error out put file.

And those 3 file have open by the system before your app start. And the files description are 1, 2 and 3.

If you close(1), the stdin file will be closed. And then, if you open another file, the stdin will be point to the new file.

All input APIs(scanf, get, ...) without FD are read data from input file, and output APIs without FD are put the value into stdout.

So, if you close(1), and open a new file with return value is 1, the printf will put values into your file.

Title: What exactly is stdin?

Body:
I am a bit confused regarding the implementation of stdin. What exactly is it? Is it a pointer? I tried to print the size of stdin using sizeof on a 64 bit machine and got 8. I even de-referenced it using *stdin in the %s specifier and got the not used characters in the input stream( all of them). But if I compare its de referenced value inside if I get an error. I know its an input stream. But how is it implemented?

Here is a sample:

#include<stdio.h>
#include<stdlib.h>

int main(){

    char a[10];

    fgets(a,10,stdin);

    printf("a: %s",a);

    printf("\nstdin: %s",*stdin);

//if(*stdin=="foo"){
//    printf("True");
//}//Error: invalid operands to binary == (have 'FILE' and 'char *')//and casting to char * doesn't help

    printf("\nSize of stdin: %d\n",sizeof(stdin));

    if(stdin!=NULL){
        printf("This statement is always reached");//always printed even in when input is bigger than 10 chars and otherwise
    }

if(!feof(stdin)){
    printf("\nThis statement is also always reached");
}
}

When I input

foobar1234567890

I get the result:

a: foobar123

stdin: 4567890

Size of stdin: 8

This statement is always reached

This statement is also always reached

And when I input

foobar

I get the output

a: foobar

stdin:

Size of stdin: 4

This statement is always reached

This statement is also always reached

I understand that stdin is kind of a FILE pointer, but I don't clearly get it. Could anyone explain the above outputs?


问:
How do I get a Bootstrap 4 nav to appear on the same line as a header?
Here you can see what it looks like right now.

What it looks like now

How do I get the nav to appear on the right side of the screen while making it be on the same line as the copyright? I cannot seem to get anything to work that I have seen on here so far.

Here is my current code:

```<code><div class="container-fluid footer">
    <div class="spacer"></div>
    <div class="container">
        <h5 style="display: inline">Copyright © 2017 Custom Prop Shop</h5>
        <ul class="nav flex-column flex-sm-row justify-content-end pull-right">
            <li class="nav-item">
                <a class="nav-link" href="request-estimate.html">Request an Estimate</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="our-work.html">Our Work</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="our-clients.html">Our Clients</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="our-story.html">Our Story</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="contact.html">Contact</a>
            </li>
        </ul>
    </div>
    <div class="spacer"></div>
</div>
</code>```

CSS is only controlling color of the text/background and the font-size for this part.

答:
You can use something like this

```<code><div class="container-fluid footer">
    <div class="spacer"></div>
    <div class="container">
        <div class="row">
            <div class="col">
                <h5 style="display: inline">Copyright © 2017 Custom Prop Shop</h5>
            </div>
            <div class="col">
                <ul class="nav flex-column flex-sm-row justify-content-end pull-right">
                    <li class="nav-item">
                        <a class="nav-link" href="request-estimate.html">Request an Estimate</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="our-work.html">Our Work</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="our-clients.html">Our Clients</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="our-story.html">Our Story</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="contact.html">Contact</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div class="spacer"></div>
</div>
</code>```

You can reference Bootstrap Grid Options over here https://v4-alpha.getbootstrap.com/layout/grid/#grid-options

Body:
Here you can see what it looks like right now.

What it looks like now

How do I get the nav to appear on the right side of the screen while making it be on the same line as the copyright? I cannot seem to get anything to work that I have seen on here so far.

Here is my current code:

Copyright © 2017 Custom Prop Shop

                Request an Estimate

                Our Work

                Our Clients

                Our Story

                Contact

CSS is only controlling color of the text/background and the font-size for this part.

Body:
You can use something like this

<div class="container-fluid footer">
    <div class="spacer"></div>
    <div class="container">
        <div class="row">
            <div class="col">
                <h5 style="display: inline">Copyright © 2017 Custom Prop Shop</h5>
            </div>
            <div class="col">
                <ul class="nav flex-column flex-sm-row justify-content-end pull-right">
                    <li class="nav-item">
                        <a class="nav-link" href="request-estimate.html">Request an Estimate</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="our-work.html">Our Work</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="our-clients.html">Our Clients</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="our-story.html">Our Story</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="contact.html">Contact</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div class="spacer"></div>
</div>

You can reference Bootstrap Grid Options over here https://v4-alpha.getbootstrap.com/layout/grid/#grid-options


问:
Reducing the gap between a bullet and text in a list item
How can I reduce default gap between bullet and text in an
?

Item 1

Item 2

Item 3

I want to reduce gap between the bullet and "I".

答:
Here's yet another way.

Add two divs to each li, one for the bullet, one for the text.

Put a bullet character • (or whatever you like, Unicode has plenty) in the bullet div. Put the text in the text div.

Set each li to display:flex.

Pros:

No extra bullet image to add.

No negative margins or anything, won't go outside of parent.

Works on any browser that supports flexbox.

Proper indentation of multiline items.

Use of bullet character means bullet will always be properly vertically aligned with text, no tweaks necessary.

Cons:

Requires extra elements.

Also, if you don't want to hand code all the extra divs, you can just make a normal list and then run this function to transform it, passing your ul as the parameter:

```<code>function fixList (theList) {
  theList.find('li').each(function (_, li) {
    li = $(li);
    $('<div/>').html(li.html()).appendTo(li.empty());
    $('<div/>').text('•').prependTo(li);
  });
}
</code>```

Example:

li {
  font-family: sans-serif;
  list-style-type: none;
  display: flex;
}

li > div:first-child {
  margin-right: 0.75ex; /* set to desired spacing */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li><div>•</div><div>First list item.</div>
  <li><div>•</div><div>Second list item.<br>It's on two lines.</div>
  <li><div>•</div><div>Third <i>list</i> item.</div>
</ul></code>```

Here's an example using the function:

fixList($('ul'));

function fixList (theList) {
  $('li', theList).each(function (_, li) {
    li = $(li);
    $('
').html(li.html()).appendTo(li.empty());
    $('
').text('•').prependTo(li);
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li {
  font-family: sans-serif;
  list-style-type: none;
  display: flex;
}

li > div:first-child {
  margin-right: 0.75ex;
}</code>```

First list item.

Second list item.
It's on two lines.

Third list item.

```

Body:
Here's yet another way.

Add two divs to each li, one for the bullet, one for the text.

Put a bullet character • (or whatever you like, Unicode has plenty) in the bullet div. Put the text in the text div.

Set each li to display:flex.

Pros:

No extra bullet image to add.

No negative margins or anything, won't go outside of parent.

Works on any browser that supports flexbox.

Proper indentation of multiline items.

Use of bullet character means bullet will always be properly vertically aligned with text, no tweaks necessary.

Cons:

Requires extra elements.

Also, if you don't want to hand code all the extra divs, you can just make a normal list and then run this function to transform it, passing your ul as the parameter:

function fixList (theList) {
  theList.find('li').each(function (_, li) {
    li = $(li);
    $('<div/>').html(li.html()).appendTo(li.empty());
    $('<div/>').text('•').prependTo(li);
  });
}

Example:

li {
  font-family: sans-serif;
  list-style-type: none;
  display: flex;
}

li > div:first-child {
  margin-right: 0.75ex; /* set to desired spacing */
}

<ul>
  <li><div>•</div><div>First list item.</div>
  <li><div>•</div><div>Second list item.<br>It's on two lines.</div>
  <li><div>•</div><div>Third <i>list</i> item.</div>
</ul>

Here's an example using the function:

fixList($('ul'));

function fixList (theList) {
  $('li', theList).each(function (_, li) {
    li = $(li);
    $('<div/>').html(li.html()).appendTo(li.empty());
    $('<div/>').text('•').prependTo(li);
  });
}

li {
  font-family: sans-serif;
  list-style-type: none;
  display: flex;
}

li > div:first-child {
  margin-right: 0.75ex;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>First list item.
  <li>Second list item.<br>It's on two lines.
  <li>Third <i>list</i> item.
</ul>


问:
runner technique for weaving elements of linked list
I've been reading the cracking the coding interview book. I am a bit stuck on implementing the runner technique for weaving elements of a linked list. The book goes as follows:

"Suppose you had a linked list a1->a2....->an->b1->b2....bn, and you want to rearrange it into a1->b1->a2->b2->.....an->bn. You don't know the length of the linked list but all you know is that it is an even number.

You could have one pointer p1 (fast pointer) move every two elements for every one move that p2 makes. When p1 hits the end of the linked list, p2 will be at the endpoint. Then, move p1 back to the front and begin "weaving" the elements. On each iteration, p2 selects an element and inserts it after p1."

Now I understand the technique up to the point before weaving starts. So, right before weaving, we basically have (for n=4 elements)

```<code>p1      p2
a1->a2->b1->b2
</code>```

Now, if I understand correctly, I have to move the element pointed to by p2 (i.e. b1) and insert it after p1, in other words

```<code>p1.next = p2
</code>```

which would result in the following list (?)

```<code>a1->b1->b2
</code>```

How does the algorithm proceed from here?

I found this question but it seems to suggest that the above step would result in

```<code>a1->b1->a2->b2
</code>```

which I do not see how. I am probably missing something fundamental here.

答:
If A1 -> A2 -> ... -> AN -> B1 -> B2 ... -> BN is your original linked list, after the first step you'll have P1 and P2 pointing at A1 and B1 respectively. Let's say AN points to null, this can be done easily in the first step.

At each iteration, do these steps:

```<code>temp1 = P1.next
temp2 = P2.next //1

P2.next = P1.next //2
P1.next = P2 //3

P1 = temp1
P2 = temp2 //4
</code>```

Here are the changes at the four positions in the first iteration:

1:

```<code>P1                   P2
⬍                    ⬍
A1 → A2 → ... → AN   B1 → B2 ... → BN
     ⬍                    ⬍
    temp1                temp2
</code>```

2:

```<code>P1   .–––––––––––––––.
⬍    ↓               ↑
A1 → A2 → ... → AN   B1   B2 ... → BN
     ⬍               ⬍    ⬍
    temp1            P2  temp2
</code>```

3:

```<code>P1   .–––––––––––––––.
⬍    ↓               ↑
A1   A2 → ... → AN   B1   B2 ... → BN   //P2 points on B1
↓    ⬍               ↑    ⬍
↓   temp1            ↑   temp2
·––––––––––––––––––––·
</code>```

This is equivalent to:

```<code>P1                   P2
⬍                    ⬍
A1 → B1 → A2 → ... → AN   B2 ... → BN
          ⬍               ⬍
         temp1           temp2
</code>```

4:

```<code>          P1              P2
          ⬍               ⬍
A1 → B1 → A2 → ... → AN   B2 ... → BN
          ⬍               ⬍
         temp1           temp2
</code>```

And you repeat the same until P1 reaches AN.

Body:
I've been reading the cracking the coding interview book. I am a bit stuck on implementing the runner technique for weaving elements of a linked list. The book goes as follows:

"Suppose you had a linked list a1->a2....->an->b1->b2....bn, and you want to rearrange it into a1->b1->a2->b2->.....an->bn. You don't know the length of the linked list but all you know is that it is an even number.

You could have one pointer p1 (fast pointer) move every two elements for every one move that p2 makes. When p1 hits the end of the linked list, p2 will be at the endpoint. Then, move p1 back to the front and begin "weaving" the elements. On each iteration, p2 selects an element and inserts it after p1."

Now I understand the technique up to the point before weaving starts. So, right before weaving, we basically have (for n=4 elements)

p1      p2
a1->a2->b1->b2

Now, if I understand correctly, I have to move the element pointed to by p2 (i.e. b1) and insert it after p1, in other words

p1.next = p2

which would result in the following list (?)

a1->b1->b2

How does the algorithm proceed from here?

I found this question but it seems to suggest that the above step would result in

a1->b1->a2->b2

which I do not see how. I am probably missing something fundamental here.

Body:
If A1 -> A2 -> ... -> AN -> B1 -> B2 ... -> BN is your original linked list, after the first step you'll have P1 and P2 pointing at A1 and B1 respectively. Let's say AN points to null, this can be done easily in the first step.

At each iteration, do these steps:

temp1 = P1.next
temp2 = P2.next //1

P2.next = P1.next //2
P1.next = P2 //3

P1 = temp1
P2 = temp2 //4

Here are the changes at the four positions in the first iteration:

1:

P1                   P2
⬍                    ⬍
A1 → A2 → ... → AN   B1 → B2 ... → BN
     ⬍                    ⬍
    temp1                temp2

2:

P1   .–––––––––––––––.
⬍    ↓               ↑
A1 → A2 → ... → AN   B1   B2 ... → BN
     ⬍               ⬍    ⬍
    temp1            P2  temp2

3:

P1   .–––––––––––––––.
⬍    ↓               ↑
A1   A2 → ... → AN   B1   B2 ... → BN   //P2 points on B1
↓    ⬍               ↑    ⬍
↓   temp1            ↑   temp2
·––––––––––––––––––––·

This is equivalent to:

P1                   P2
⬍                    ⬍
A1 → B1 → A2 → ... → AN   B2 ... → BN
          ⬍               ⬍
         temp1           temp2

4:

          P1              P2
          ⬍               ⬍
A1 → B1 → A2 → ... → AN   B2 ... → BN
          ⬍               ⬍
         temp1           temp2

And you repeat the same until P1 reaches AN.


问:
Setting Nullable Integer to String Containing Nothing yields 0
I've been pulling my hair out over some unexpected behavior from nullable integers.

If I set an Integer to Nothing, it becomes Nothing as expected.

If I set an Integer? to a String that is Nothing, it becomes 0!

Of course I get this whether I explicitly cast the String to Integer? or not.

I realize I could work around this pretty easily but I want to know what I'm missing.

```<code>    Dim NullString As String = Nothing
    Dim NullableInt As Integer? = CType(NullString, Integer?) 'Expected NullableInt to be Nothing, but it's 0!
    NullableInt = Nothing 'This works, of course. NullableInt is Nothing.
</code>```

EDIT: Previously I had my code up here so without the explicit conversion to Integer? and everyone seemed to be fixated on/confused by that. There were a lot of suggestions that Option Strict On would catch this type of thing. However, this is actually a quirk of the string-to-integer conversion rules which predate nullable types, but still impact them.

答:
WHY are you trying to assign a string to an integer????</p>

```<code>    Dim nullInt As Nullable(Of Integer) 'nullInt = Nothing as expected

    'the following should NOT compile and won't with Option Strict On

    nullInt = ""
    nullInt = String.Empty
</code>```

Body:
I've been pulling my hair out over some unexpected behavior from nullable integers.

If I set an Integer to Nothing, it becomes Nothing as expected.

If I set an Integer? to a String that is Nothing, it becomes 0!

Of course I get this whether I explicitly cast the String to Integer? or not.

I realize I could work around this pretty easily but I want to know what I'm missing.

    Dim NullString As String = Nothing
    Dim NullableInt As Integer? = CType(NullString, Integer?) 'Expected NullableInt to be Nothing, but it's 0!
    NullableInt = Nothing 'This works, of course. NullableInt is Nothing.

EDIT: Previously I had my code up here so without the explicit conversion to Integer? and everyone seemed to be fixated on/confused by that. There were a lot of suggestions that Option Strict On would catch this type of thing. However, this is actually a quirk of the string-to-integer conversion rules which predate nullable types, but still impact them.

Body:
WHY are you trying to assign a string to an integer????

    Dim nullInt As Nullable(Of Integer) 'nullInt = Nothing as expected

    'the following should NOT compile and won't with Option Strict On

    nullInt = ""
    nullInt = String.Empty


问:
How Do you Update a Dataset<Row> with records from another Dataset<Row> which have Identical Schema in Spark with JAVA API?
Suppose you have a Dataset A with the following records:

```<code>Dataset A:
    {key1, val1}
    {key2, val2}
    {key3, val3}

Dataset B:
    {key4, val4}
    {key1, valBB}
    {key5, valN}
    {key2, NNNNN}
</code>```

After the "Update" happens this is what the final Dataset should look like:

```<code>Dataset Final:
    {key1, valBB}
    {key2, NNNNN}
    {key3, val3}
    {key4, val4}
    {key5, valN}
</code>```

The approach I have taken thus far, is to convert the two Dataset to a JavaRDD, and then convert the JavaRDD -> JavaPairRDD, and then firstPairRDD.subtractByKey(secondPairRDD). This gives me the records that exist in Dataset A but not in Dataset B. I then reconvert this back to a Dataset. The next step is that i do a Union with DatasetB to give me the updated dataset. for me this isn't quite giving me the result I expected. Did i take the wrong approach? any help would be appreciated.

答:
I ended up finding a more efficient solution:

```<code>    Dataset<Row> existsInAButNotB = A.join(B, A.col("key").equalTo(B.col("key") "left_anti");
    Dataset<Row> Final = existsInAButNotB.union(B);
</code>```

If you have multiple columns which you use as your key, then your solution should look like this:

```<code>Dataset<Row> existsInAButNotB = A.join(B, A.col("key1").equalTo(B.col("key1").and(A.col("key2").equalTo(B.col("key2")) "left_anti");
</code>```

This one liner avoids the user from going into the inefficient RDD world and avoids adding extra code.

take a look at this:

Left Anti join in Spark?

More on Left Anti Join here:

what is the difference between an anti-join and an anti semi join?

Dataset Join API:
https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/Dataset.html#join(org.apache.spark.sql.Dataset,%20org.apache.spark.sql.Column,%20java.lang.String)

Body:
Suppose you have a Dataset A with the following records:

Dataset A:
    {key1, val1}
    {key2, val2}
    {key3, val3}

Dataset B:
    {key4, val4}
    {key1, valBB}
    {key5, valN}
    {key2, NNNNN}

After the "Update" happens this is what the final Dataset should look like:

Dataset Final:
    {key1, valBB}
    {key2, NNNNN}
    {key3, val3}
    {key4, val4}
    {key5, valN}

The approach I have taken thus far, is to convert the two Dataset to a JavaRDD, and then convert the JavaRDD -> JavaPairRDD, and then firstPairRDD.subtractByKey(secondPairRDD). This gives me the records that exist in Dataset A but not in Dataset B. I then reconvert this back to a Dataset. The next step is that i do a Union with DatasetB to give me the updated dataset. for me this isn't quite giving me the result I expected. Did i take the wrong approach? any help would be appreciated.

Body:
I ended up finding a more efficient solution:

    Dataset<Row> existsInAButNotB = A.join(B, A.col("key").equalTo(B.col("key") "left_anti");
    Dataset<Row> Final = existsInAButNotB.union(B);

If you have multiple columns which you use as your key, then your solution should look like this:

Dataset<Row> existsInAButNotB = A.join(B, A.col("key1").equalTo(B.col("key1").and(A.col("key2").equalTo(B.col("key2")) "left_anti");

This one liner avoids the user from going into the inefficient RDD world and avoids adding extra code.

take a look at this:

Left Anti join in Spark?

More on Left Anti Join here:

what is the difference between an anti-join and an anti semi join?

Dataset Join API:
https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/Dataset.html#join(org.apache.spark.sql.Dataset,%20org.apache.spark.sql.Column,%20java.lang.String)