问:
Opening URL's on same browser in different tab from CSV in Python
I am trying to open a list of URLs in new tabs in a single window, but it instead opens them in new windows. Please help. This is my URL.csv

```<code>SN,Title,URL
1,Google,https://google.com
2,youtube,https://youtube.com
</code>```

```<code>import csv

from selenium import webdriver

def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')

    for line in reader:
        url = line["URL"]
        title = line["Title"]
        print(url + title)
        driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
        driver.get(url)

if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)
</code>```

答:
When you put driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver') inside the loop, you are creating a new webdriver instance for each website.

Try something like this:

```<code>import csv
import time

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')
    driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')

    for line in reader:
        url = line["URL"]
        title = line["Title"]
        print(url + title)
        driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
        driver.get(url)

if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)
    time.sleep(9999999)

</code>```

Body:
I am trying to open a list of URLs in new tabs in a single window, but it instead opens them in new windows. Please help. This is my URL.csv

SN,Title,URL
1,Google,https://google.com
2,youtube,https://youtube.com

import csv

from selenium import webdriver

def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')

    for line in reader:
        url = line["URL"]
        title = line["Title"]
        print(url + title)
        driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
        driver.get(url)

if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)

Body:
When you put driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver') inside the loop, you are creating a new webdriver instance for each website.

Try something like this:

import csv
import time

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')
    driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')

    for line in reader:
        url = line["URL"]
        title = line["Title"]
        print(url + title)
        driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
        driver.get(url)

if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)
    time.sleep(9999999)


来源: stackexchange

问:
fork bomb which terminates when flash drive is ejected
I am trying to make a fork bomb which closes itself as soon as the flash drive on which it is stored is removed. This is my code so far:

```<code>:start
start %0
IF EXIST E:\forkbomb.bat goto start
</code>```

For some reason it stays open even once the flash drive is removed, why does the condition not become false once the flash drive is no longer inserted and cause the program to exit? Thanks!

答:
Swap line 1 and 2 ;)

It won't technically be a fork bomb anymore but it will still create many windows who will all banish themselves as soon as the flash drive disappears.

Edit, did some further thinking, and you also need another IF.

```<code>IF EXIST E:\forkbomb.bat start %0
:start
IF EXIST E:\forkbomb.bat goto start
</code>```

In fact you could even try your luck with the original fork bomb design.

Conceptually it didn’t work for you probably because every instance had to be past the highlighted line below at the instance the drive was removed:

```<code>:start
start %0   <<<< this line
IF EXIST E:\forkbomb.bat goto start
</code>```

Because if even one of the instances is before the start then it will keep creating new instances (without the loop). So essentially your fork bomb gets degenerated into a situation where each window creates exactly one new window.

tl;dr without further ado here is my amended solution

```<code>:begin
IF NOT EXIST E:/forkbomb.bat goto end
start %0
goto begin
:end
</code>```

Now that is a full fork bomb and when the drive is removed it will clean up itself as fast as possible.

Cheers

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make a fork bomb which closes itself as soon as the flash drive on which it is stored is removed. This is my code so far:

:start
start %0
IF EXIST E:\forkbomb.bat goto start

For some reason it stays open even once the flash drive is removed, why does the condition not become false once the flash drive is no longer inserted and cause the program to exit? Thanks!

Body:
Swap line 1 and 2 ;)

It won't technically be a fork bomb anymore but it will still create many windows who will all banish themselves as soon as the flash drive disappears.

Edit, did some further thinking, and you also need another IF.

IF EXIST E:\forkbomb.bat start %0
:start
IF EXIST E:\forkbomb.bat goto start

In fact you could even try your luck with the original fork bomb design.

Conceptually it didn’t work for you probably because every instance had to be past the highlighted line below at the instance the drive was removed:

:start
start %0   <<<< this line
IF EXIST E:\forkbomb.bat goto start

Because if even one of the instances is before the start then it will keep creating new instances (without the loop). So essentially your fork bomb gets degenerated into a situation where each window creates exactly one new window.

tl;dr without further ado here is my amended solution

:begin
IF NOT EXIST E:/forkbomb.bat goto end
start %0
goto begin
:end

Now that is a full fork bomb and when the drive is removed it will clean up itself as fast as possible.

Cheers

ContentLicense: CC BY-SA 4.0


问:
Why TypeScript gradual typing should stop compiling this valid code?
In the following code, although everything looks good but TypeScript shows an error which seems strange:

```<code>class Sample {

    private value = 1;

    private incrementValue(): void {
        this.value++;
    }

    private beginTest(): void {

        if (this.value !== 1) {
            throw "bad state!"
        }

        this.incrementValue();

        if (this.value != 2) {
            throw "bad state!"; // ERROR!!: This condition will always return 'true' since the types '1' and '2' have no overlap.
        }
    }
}
</code>```

Why should TypeScript raise such error? I'm changing value by this.incrementValue(). It seems this kind of error should be an more of an IntelliSense Warning rather than a Compile Error.

Possibly it is because of the gradual type system, but as it fails it these situations there should be a compile option to workaround this.

Is there any workaround or special compile option to turn this off?

答:
While TypeScript's type inference is usually very good at inferring types correctly, the language has limited control flow analysis. The lead developer on the TypeScript team at Microsoft argues:

The primary question is: When a function is invoked, what should we assume its side effects are?

One option is to be pessimistic and reset all narrowings, assuming that any function might mutate any object it could possibly get its hands on. Another option is to be optimistic and assume the function doesn't modify any state. Both of these seem to be bad.

— Ryan Cavanaugh, Trade-offs in Control Flow Analysis

Explanation of your example

In the first if-statement TypeScript evaluates this.value as a number type.

Right after the first if-statement, TypeScript determines that this.value is no longer of the type number. Instead it is of the literal type 1.

This is because that any value that is different from 1 (!== 1) would have terminated the function. Therefore, any value that doesn't terminate and instead moves on to the next if-statement, must be the exact literal value 1.

When you call this.incrementValue();, TypeScript isn't aware that the function mutates the state of this.value. By the time you get to the 2nd if statement, TypeScript still believes that this.value is of the literal type 1.

Because of this, it evaluates the 2nd if-statement the same way it would if you had replaced this.value with the number literal 1

```<code>if (1 != 2)
</code>```

(This also throws the exact same error)

Solutions for your problem

As for your problem right now, the simplest solution would be to either:

Tell TypeScript that this.value is a number if ((this.value as number) != 2)

Cast the value to a number if (+this.value != 2)

Add a // @ts-ignore comment on the line above so the TypeScript compiler ignores the error

Solutions for improving TypeScript's control flow analysis

Ryan Cavanaugh mentions a few ideas for improving TypeScript's control flow analysis:

pure modifier on functions that says this function doesn't modify anything. This is a bit impractical as we'd realistically want this on the vast majority of all functions, and it doesn't really solve the problem since lots of functions only modify one thing so you'd really want to say "pure except for m"

volatile property modifier that says this "this property will change without notice". We're not C++ and it's perhaps unclear where you'd apply this and where you wouldn't.

Body:
In the following code, although everything looks good but TypeScript shows an error which seems strange:

class Sample {

    private value = 1;

    private incrementValue(): void {
        this.value++;
    }

    private beginTest(): void {

        if (this.value !== 1) {
            throw "bad state!"
        }

        this.incrementValue();

        if (this.value != 2) {
            throw "bad state!"; // ERROR!!: This condition will always return 'true' since the types '1' and '2' have no overlap.
        }
    }
}

Why should TypeScript raise such error? I'm changing value by this.incrementValue(). It seems this kind of error should be an more of an IntelliSense Warning rather than a Compile Error.

Possibly it is because of the gradual type system, but as it fails it these situations there should be a compile option to workaround this.

Is there any workaround or special compile option to turn this off?

Body:
While TypeScript's type inference is usually very good at inferring types correctly, the language has limited control flow analysis. The lead developer on the TypeScript team at Microsoft argues:

The primary question is: When a function is invoked, what should we assume its side effects are?

One option is to be pessimistic and reset all narrowings, assuming that any function might mutate any object it could possibly get its hands on. Another option is to be optimistic and assume the function doesn't modify any state. Both of these seem to be bad.

— Ryan Cavanaugh, Trade-offs in Control Flow Analysis

Explanation of your example

In the first if-statement TypeScript evaluates this.value as a number type.

Right after the first if-statement, TypeScript determines that this.value is no longer of the type number. Instead it is of the literal type 1.

This is because that any value that is different from 1 (!== 1) would have terminated the function. Therefore, any value that doesn't terminate and instead moves on to the next if-statement, must be the exact literal value 1.

When you call this.incrementValue();, TypeScript isn't aware that the function mutates the state of this.value. By the time you get to the 2nd if statement, TypeScript still believes that this.value is of the literal type 1.

Because of this, it evaluates the 2nd if-statement the same way it would if you had replaced this.value with the number literal 1

if (1 != 2)

(This also throws the exact same error)

Solutions for your problem

As for your problem right now, the simplest solution would be to either:

Tell TypeScript that this.value is a number if ((this.value as number) != 2)

Cast the value to a number if (+this.value != 2)

Add a // @ts-ignore comment on the line above so the TypeScript compiler ignores the error

Solutions for improving TypeScript's control flow analysis

Ryan Cavanaugh mentions a few ideas for improving TypeScript's control flow analysis:

pure modifier on functions that says this function doesn't modify anything. This is a bit impractical as we'd realistically want this on the vast majority of all functions, and it doesn't really solve the problem since lots of functions only modify one thing so you'd really want to say "pure except for m"

volatile property modifier that says this "this property will change without notice". We're not C++ and it's perhaps unclear where you'd apply this and where you wouldn't.


问:
order of functions in Variadic templates
The following code is working! But my question is theoretical if we inverse the two version of index_of in the namespace detail, the compiler says that no function template is matching but why?

```<code>#include <iostream>
using namespace std;

template <typename... Args>
class Pack{
public:
  Pack(){}
};

template <typename T, typename Arg, typename... Args>
bool contains(Pack<Arg, Args...> p)
{
  Pack<Args...> n;
  return std::is_same_v<T,Arg> || contains<T>(n);
}

template <typename T>
bool contains(Pack<> p){
  return false;
}

namespace detail{

  template <typename T>
  int index_of(Pack<> p, int index){
    return -1;
  }

  template <typename T, typename Arg, typename... Args>
  int index_of(Pack<Arg, Args...> p, int index = 0){
    if(is_same_v<T,Arg>) return index;
    Pack<Args...> rest;
    return index_of<T>(rest, index+1);
  }

}

template <typename T, typename... Ts>
int index_of(Pack<Ts...> p)
{
  return detail::index_of<T>(p);
}

int main()
{
  Pack<int,string,double> p;
  cout << contains<int>(p) << endl;
  cout << contains<char>(p) << endl;
  cout << index_of<int>(p) << endl;
}
</code>```

答:
The second index_of itself calls index_of. If it's listed first, then the other index_of is not visible, so it can only be a recursive call; but the recursive call is not viable once only one type remains.

When it's listed second, both versions of index_of are in scope for that call.

Basically, it boils down to the fact that a function has to be declared before it can be called.

Body:
The following code is working! But my question is theoretical if we inverse the two version of index_of in the namespace detail, the compiler says that no function template is matching but why?

#include <iostream>
using namespace std;

template <typename... Args>
class Pack{
public:
  Pack(){}
};

template <typename T, typename Arg, typename... Args>
bool contains(Pack<Arg, Args...> p)
{
  Pack<Args...> n;
  return std::is_same_v<T,Arg> || contains<T>(n);
}

template <typename T>
bool contains(Pack<> p){
  return false;
}

namespace detail{

  template <typename T>
  int index_of(Pack<> p, int index){
    return -1;
  }

  template <typename T, typename Arg, typename... Args>
  int index_of(Pack<Arg, Args...> p, int index = 0){
    if(is_same_v<T,Arg>) return index;
    Pack<Args...> rest;
    return index_of<T>(rest, index+1);
  }

}

template <typename T, typename... Ts>
int index_of(Pack<Ts...> p)
{
  return detail::index_of<T>(p);
}

int main()
{
  Pack<int,string,double> p;
  cout << contains<int>(p) << endl;
  cout << contains<char>(p) << endl;
  cout << index_of<int>(p) << endl;
}


问:
How to use .clone() in a loop or for each array element?
For some reason I have to modify template of the software I use for creating invoices. Invoices are generated in html, therefore, I think that I can do that with Stylish and Grease Monkey (no support from a developer so I have to do this myself).
Basically I have some div elements and tables with no id. I have generated unique id for each element (this part of code works) and what I need now is to clone "#order-"+index+"-details" and prepend it "#order"+index+"lines" where index of "#order-"+index+"-details" matches "#order"+index+"lines" (this part does not).
I know that code is amateur and ugly, but it does not have to be efficient - it must works ;).

```<code>var orders=document.querySelectorAll("div.pages");
    for(var i = 0; i < orders.length; i++){

$("body").find("div.pages").each(function(index){
$(this).attr("id","order-"+index+"-page");
})

$("body").find("div.pages > div:nth-child(1) > table:nth-
child(3)").each(function(index){
$(this).attr("id","order-"+index+"-details");
})

$("body").find("div.pages > div:nth-child(1) > table:nth-
child(7)").each(function(index){
$(this).attr("id","order-"+index+"-lines");
})

$order_details = $("#order-"+index+"-details").clone();
$("#order"+index+"lines").prepend($order_details);

}
</code>```

This part does not work

```<code>$order_details = $("#order-"+index+"-details").clone();
$("#order-"+index+"-lines").prepend($order_details);
</code>```

It works when I am trying:

```<code>$order_details = $("#order-1-details").clone();
$("#order-1-lines").prepend($order_details);

$order_details = $("#order-2-details").clone();
$("#order-2-lines").prepend($order_details);
</code>```

But I need to loop it. Many thanks in advance for all suggestions.

Regards,
Thomas.

答:
```<code>$order_details = $("#order-"+index+"-details").clone();
$("#order"+index+"lines").prepend($order_details);
</code>```

Should be

```<code>$order_details = $("#order-"+i+"-details").clone();
$("#order"+i+"lines").prepend($order_details);
</code>```

It's much more clear if the code is formatted:

```<code>var orders = document.querySelectorAll("div.pages");
for (var i = 0; i < orders.length; i++) {

    $("body").find("div.pages").each(function(index) {
        $(this).attr("id","order-"+index+"-page");
    });

    $("body").find("div.pages > div:nth-child(1) > table:nth-
    child(3)").each(function(index){
        $(this).attr("id","order-"+index+"-details");
    });

    $("body").find("div.pages > div:nth-child(1) > table:nth-
    child(7)").each(function(index){
        $(this).attr("id","order-"+index+"-lines");
    });

    $order_details = $("#order-"+i+"-details").clone();
    $("#order"+i+"lines").prepend($order_details);

}
</code>```

Body:
For some reason I have to modify template of the software I use for creating invoices. Invoices are generated in html, therefore, I think that I can do that with Stylish and Grease Monkey (no support from a developer so I have to do this myself).
Basically I have some div elements and tables with no id. I have generated unique id for each element (this part of code works) and what I need now is to clone "#order-"+index+"-details" and prepend it "#order"+index+"lines" where index of "#order-"+index+"-details" matches "#order"+index+"lines" (this part does not).
I know that code is amateur and ugly, but it does not have to be efficient - it must works ;).

var orders=document.querySelectorAll("div.pages");
    for(var i = 0; i < orders.length; i++){

$("body").find("div.pages").each(function(index){
$(this).attr("id","order-"+index+"-page");
})

$("body").find("div.pages > div:nth-child(1) > table:nth-
child(3)").each(function(index){
$(this).attr("id","order-"+index+"-details");
})

$("body").find("div.pages > div:nth-child(1) > table:nth-
child(7)").each(function(index){
$(this).attr("id","order-"+index+"-lines");
})

$order_details = $("#order-"+index+"-details").clone();
$("#order"+index+"lines").prepend($order_details);

}

This part does not work

$order_details = $("#order-"+index+"-details").clone();
$("#order-"+index+"-lines").prepend($order_details);

It works when I am trying:

$order_details = $("#order-1-details").clone();
$("#order-1-lines").prepend($order_details);

$order_details = $("#order-2-details").clone();
$("#order-2-lines").prepend($order_details);

But I need to loop it. Many thanks in advance for all suggestions.

Regards,
Thomas.

Body:
$order_details = $("#order-"+index+"-details").clone();
$("#order"+index+"lines").prepend($order_details);

Should be

$order_details = $("#order-"+i+"-details").clone();
$("#order"+i+"lines").prepend($order_details);

It's much more clear if the code is formatted:

var orders = document.querySelectorAll("div.pages");
for (var i = 0; i < orders.length; i++) {

    $("body").find("div.pages").each(function(index) {
        $(this).attr("id","order-"+index+"-page");
    });

    $("body").find("div.pages > div:nth-child(1) > table:nth-
    child(3)").each(function(index){
        $(this).attr("id","order-"+index+"-details");
    });

    $("body").find("div.pages > div:nth-child(1) > table:nth-
    child(7)").each(function(index){
        $(this).attr("id","order-"+index+"-lines");
    });

    $order_details = $("#order-"+i+"-details").clone();
    $("#order"+i+"lines").prepend($order_details);

}


问:
How to write database specific custom validator in Rails 3.0?
I need to write a custom validator to check if a record exists in the database or not. Sort of like the opposite of validate uniqueness, however I couldn't find something that could achieve what I wanted in the built in validators.

What I'm attempting to do is check if the referrer exists or not in the Users table. If the referrer's username is "testuser", I want to check in the Users table whether "testuser" actually exists.

I have created a custom validator:

```<code>class ReferrerExistsValidator < ActiveModel::EachValidator
</code>```

However I'm unsure how to proceed to fetch details from there database, any pointers?

答:
Write the following validation class

```<code> class ReferrerExistsValidator < ActiveModel::EachValidator
   def validate_each(object, attribute, value)
     unless User.find_by_username(value)
       object.errors[attribute] << (options[:message] || "referrer does not exist")
     end
   end
 end
</code>```

Add the following to the relevant model

validates :referrer_exists => true

Body:
I need to write a custom validator to check if a record exists in the database or not. Sort of like the opposite of validate uniqueness, however I couldn't find something that could achieve what I wanted in the built in validators.

What I'm attempting to do is check if the referrer exists or not in the Users table. If the referrer's username is "testuser", I want to check in the Users table whether "testuser" actually exists.

I have created a custom validator:

class ReferrerExistsValidator < ActiveModel::EachValidator

However I'm unsure how to proceed to fetch details from there database, any pointers?

Body:
Write the following validation class

 class ReferrerExistsValidator < ActiveModel::EachValidator
   def validate_each(object, attribute, value)
     unless User.find_by_username(value)
       object.errors[attribute] << (options[:message] || "referrer does not exist")
     end
   end
 end

Add the following to the relevant model

validates :referrer_exists => true


问:
How to draw random shapes into my frame with ArrayList?
I am keen to learn how I can finish this project. I want to draw three random shapes in random colors and positions and add them to the list (which later need to be played in the second window).

Here is what I have:

```<code> public
    class Frame extends JFrame { // here was implements Runnable when i
                                 // used Thread

    public  ArrayList<MyShape> shapesList = new ArrayList<MyShape>(30); // create list
    public  JPanel shapePanel;
    public  Timer timer;
    public  final int  NEW_SHAPE_FREQUENCY = 1000;
    public  Rectangle myRect;
    public  Oval myOval;
    public  Line myLine;

 public Frame() {

    super("I do not need title, just 50%");
    setSize(800, 600);
    setDefaultCloseOperation(3);
    setLocationRelativeTo(null);
    setVisible(true);
    setLayout(new BorderLayout());

    shapePanel = new JPanel() {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (MyShape s : shapesList) {
            g.setColor(myOval.color);  // in this line i have
                                       // Exception: NullPointerException
                g.fillRect(((int)(getWidth()*Math.random()*0.8d)),((int)
 (getHeight()*Math.random()*0.8d)), (int) (myRect.x2),(int) myRect.y2);
            }
        }
    };

    add(shapePanel);
    initTimer();

    // Thread t0 = new Thread(this);  // How can i use Threads in this case ??
    // t0.start();

 }

 private void initTimer() {
    timer = new Timer(NEW_SHAPE_FREQUENCY, e -> {
        shapesList.add(new MyShape()); // Add a new shape to the arraylist
        shapePanel.repaint(); // Repaint the panel, so the new shape is
                              // visible
    });
    timer.start();
  }
  /*
    @Override
    public void run() {

        while (true) {
            try {

                Random rand = new Random();
                switch (rand.nextInt(3)+1) {
                    case 1:
                        shapesList.add((Shape)myRect);
                        break;

                    case 2:
                        shapesList.add((Shape)myOval);
                        break;

                    case 3:
                        shapesList.add((Shape)myLine);
                        break;
                }

                repaint();
                Thread.sleep(1000);

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
    */

 }
</code>```

After modification, the Frame class now looks like this. I am newbie with coding in Java sorry about this errors

答:
First of all, take some time and read if multiple jframes is good or bad practice. After that, read how to use Swing Timers, in order to learn how you will make it paint a new shape every second (i am not sure if you want this feature, but it seems so). If you use Thread.sleep() method in a Swing application, the whole GUI will freeze since the thread is sleeping and events will not be able to take place.

The code you gave to us is not an Short, Self Contained, Correct (Compilable), Example since we will have to edit it in order to make it run. For that reason I've created an example in order to show you what i mean in practice. Do not forget to note the comments inside the code.

Code:

```<code>public class RandomShape extends JFrame {
    private static final long serialVersionUID = 6617760910198114903L;
    private static final int NEW_SHAPE_FREQUENCY = 1000; // every second new shape
    private List<Shape> shapes = new ArrayList<>(); // Keep the shapes
    private JPanel shapePanel;
    private Timer timer; //A javax.swing.Timer

    public RandomShape() {
        super("Random shapes");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout()); // set border layout to the content pane
        shapePanel = new JPanel() {
            /*
             * Override paint component in order to add custom painting to this panel. But
             * of course, start by calling super.paintComponent()
             */
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                for (Shape s : shapes) {
                    g.setColor(s.color);
                    g.fillRect(s.x, s.y, s.width, s.height);
                }
            }
        };
        // Add it to the center of the border layout in order to take all window space
        add(shapePanel, BorderLayout.CENTER);
        setSize(400, 400);
        setLocationRelativeTo(null);
        initTimer();
    }

    private void initTimer() {
        timer = new Timer(NEW_SHAPE_FREQUENCY, e -> {
            shapes.add(new Shape()); // Add a new shape to the arraylist
            shapePanel.repaint(); // Repaint the panel, so the new shape is visible
        });
        timer.start();
    }

    private static class Shape {
        private int x, y, height, width;
        private Color color;

        private Shape() {
            x = random(300);
            y = random(300);
            height = random(50);
            width = random(50);
            color = new Color(random(255), random(255), random(255));

        }

        private static int random(int max) {
            return (int) (Math.random() * max);
        }
    }

    public static void main(String[] args) {
        // Start application in its own thread, called Event Dispatch Thread.
        // For more info, read
        // https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(() -> new RandomShape().setVisible(true));
    }
}
</code>```

Preview:

Body:
I am keen to learn how I can finish this project. I want to draw three random shapes in random colors and positions and add them to the list (which later need to be played in the second window).

Here is what I have:

 public
    class Frame extends JFrame { // here was implements Runnable when i
                                 // used Thread

    public  ArrayList<MyShape> shapesList = new ArrayList<MyShape>(30); // create list
    public  JPanel shapePanel;
    public  Timer timer;
    public  final int  NEW_SHAPE_FREQUENCY = 1000;
    public  Rectangle myRect;
    public  Oval myOval;
    public  Line myLine;

 public Frame() {

    super("I do not need title, just 50%");
    setSize(800, 600);
    setDefaultCloseOperation(3);
    setLocationRelativeTo(null);
    setVisible(true);
    setLayout(new BorderLayout());

    shapePanel = new JPanel() {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (MyShape s : shapesList) {
            g.setColor(myOval.color);  // in this line i have
                                       // Exception: NullPointerException
                g.fillRect(((int)(getWidth()*Math.random()*0.8d)),((int)
 (getHeight()*Math.random()*0.8d)), (int) (myRect.x2),(int) myRect.y2);
            }
        }
    };

    add(shapePanel);
    initTimer();

    // Thread t0 = new Thread(this);  // How can i use Threads in this case ??
    // t0.start();

 }

 private void initTimer() {
    timer = new Timer(NEW_SHAPE_FREQUENCY, e -> {
        shapesList.add(new MyShape()); // Add a new shape to the arraylist
        shapePanel.repaint(); // Repaint the panel, so the new shape is
                              // visible
    });
    timer.start();
  }
  /*
    @Override
    public void run() {

        while (true) {
            try {

                Random rand = new Random();
                switch (rand.nextInt(3)+1) {
                    case 1:
                        shapesList.add((Shape)myRect);
                        break;

                    case 2:
                        shapesList.add((Shape)myOval);
                        break;

                    case 3:
                        shapesList.add((Shape)myLine);
                        break;
                }

                repaint();
                Thread.sleep(1000);

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
    */

 }

After modification, the Frame class now looks like this. I am newbie with coding in Java sorry about this errors

Body:
First of all, take some time and read if multiple jframes is good or bad practice. After that, read how to use Swing Timers, in order to learn how you will make it paint a new shape every second (i am not sure if you want this feature, but it seems so). If you use Thread.sleep() method in a Swing application, the whole GUI will freeze since the thread is sleeping and events will not be able to take place.

The code you gave to us is not an Short, Self Contained, Correct (Compilable), Example since we will have to edit it in order to make it run. For that reason I've created an example in order to show you what i mean in practice. Do not forget to note the comments inside the code.

Code:

public class RandomShape extends JFrame {
    private static final long serialVersionUID = 6617760910198114903L;
    private static final int NEW_SHAPE_FREQUENCY = 1000; // every second new shape
    private List<Shape> shapes = new ArrayList<>(); // Keep the shapes
    private JPanel shapePanel;
    private Timer timer; //A javax.swing.Timer

    public RandomShape() {
        super("Random shapes");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout()); // set border layout to the content pane
        shapePanel = new JPanel() {
            /*
             * Override paint component in order to add custom painting to this panel. But
             * of course, start by calling super.paintComponent()
             */
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                for (Shape s : shapes) {
                    g.setColor(s.color);
                    g.fillRect(s.x, s.y, s.width, s.height);
                }
            }
        };
        // Add it to the center of the border layout in order to take all window space
        add(shapePanel, BorderLayout.CENTER);
        setSize(400, 400);
        setLocationRelativeTo(null);
        initTimer();
    }

    private void initTimer() {
        timer = new Timer(NEW_SHAPE_FREQUENCY, e -> {
            shapes.add(new Shape()); // Add a new shape to the arraylist
            shapePanel.repaint(); // Repaint the panel, so the new shape is visible
        });
        timer.start();
    }

    private static class Shape {
        private int x, y, height, width;
        private Color color;

        private Shape() {
            x = random(300);
            y = random(300);
            height = random(50);
            width = random(50);
            color = new Color(random(255), random(255), random(255));

        }

        private static int random(int max) {
            return (int) (Math.random() * max);
        }
    }

    public static void main(String[] args) {
        // Start application in its own thread, called Event Dispatch Thread.
        // For more info, read
        // https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(() -> new RandomShape().setVisible(true));
    }
}

Preview:


问:
How to get nested items in a nested list structure in Java
I'd like to get all nested items from a structure which contains items itself and also items which contain items themselves:
When adding items to this lists, I don't know what kind of item it will be as I am only adding the general type of items (called SuperItem) to this list.
(SubItem and Item as well inherit from SuperItem)

For example, in the end I have a list of this SuperItems which looks like:

SuperItem[SubItem A, SubItem B, Item C, SubItem D]

Though, the Item C also contains SubItems. So if I have a nested structure which looks unfolded like this:

UnfoldedSuperItem[SubItem A, SubItem B, SubItem C1, SubItem C2, SubItem C3, SubItem D]

This is the list I want to get returned. Though, currently I can only get A, B and D from the SuperItem List but not C1, C2 and C3 when calling getAllSubItems().

```<code>public class Item extends SuperItem{
    List<SuperItem> superItems;
    List<SubItem> subItems;

    public Item() {
        super();
        superItems = new LinkedList<>();
        subItems = new LinkedList<>();
    }

    public void addItem(SuperItem s) {
        if (!superItems.contains(s))    {
            superItems.add(s);
        }
    }

    //[... a remove method is also in this class, not included here as not in scope]

    public List<subItem> getAllSubItems() {
        for (superItem s: superItems) {
            if (s.getClass() == SubItem.class) {
                if (!subItems.contains(s)) {
                    subItems.add((SubItem) s);
                }
            } else {
                //if it is a item, somehow call the method getAllSubItems() on itself
            }
        }
        return subItems;
    }
}
</code>```

The only thing that is missing here, is when I came to this C-Item which is not a sub-item. I kinda want to unwrap C to get all the nested items in there.

Also what is important here:
Item can also contain Items itself. So the list can look also like this:

SuperItem[Item A, Item B, Item C, SubItem D]

and unfolded then:

SuperItemUnfolded1[Item A1, Item A2, SubItem B1, SubItem B2, Item C1, Item C2, SubItem D]

and more unfolded then:

SuperItemUnfolded2[SubItem A1.1, SubItem A1.2, SubItem A2.1, SubItem A2.2,SubItem B1, SubItem B2, Item C1.2, etc. etc.])

答:
Perhaps you're looking for something like this:

```<code>public class SuperItem {
   List<Item> superItems = new LinkedList<Item>();
   List<Item> currentSubItems = null;

   public void addItem(Item s, boolean isNewSublist) {
      if (isNewSublist || currentSubItems == null) {
         currentSubItems = new LinkedList<Item>();
         superItems.add(currentSubItems);
      }
      if (!currentSubItems.contains(s))    {
         currentSubItems.add(s);
      }
      ...
   }

   public List<Item> getAllSubItems() {
      List<Item>subItems = new List<Item>();
      for (List<Item> superItem : superItems) {
         for (Item item : superItem.subItems) {
      ...
      return subItems;
   }
}
</code>```

The details will vary depending on exactly what you want to accomlish, but basically it sounds like you:

Want a list of lists, containing "items".

You want to encapsulate this "list of lists" in a class.

The class should provide methods to "add" items, and to "list" items.

One thing I'm not clear about - should "items" be unique within a "sublist", or unique within the entire "list of lists" object?.  I chose the former.

You might also be interested in Java collections like Dictionary, Map or Set.

"Set" might be especially helpful to you:

https://www.tutorialspoint.com/java/java_set_interface.htm

A Set is a Collection that cannot contain duplicate elements. It
  models the mathematical set abstraction.

The Set interface contains only methods inherited from Collection and
  adds the restriction that duplicate elements are prohibited.

Set also adds a stronger contract on the behavior of the equals and
  hashCode operations, allowing Set instances to be compared
  meaningfully even if their implementation types differ.

Body:
I'd like to get all nested items from a structure which contains items itself and also items which contain items themselves:
When adding items to this lists, I don't know what kind of item it will be as I am only adding the general type of items (called SuperItem) to this list.
(SubItem and Item as well inherit from SuperItem)

For example, in the end I have a list of this SuperItems which looks like:

SuperItem[SubItem A, SubItem B, Item C, SubItem D]

Though, the Item C also contains SubItems. So if I have a nested structure which looks unfolded like this:

UnfoldedSuperItem[SubItem A, SubItem B, SubItem C1, SubItem C2, SubItem C3, SubItem D]

This is the list I want to get returned. Though, currently I can only get A, B and D from the SuperItem List but not C1, C2 and C3 when calling getAllSubItems().

public class Item extends SuperItem{
    List<SuperItem> superItems;
    List<SubItem> subItems;

    public Item() {
        super();
        superItems = new LinkedList<>();
        subItems = new LinkedList<>();
    }

    public void addItem(SuperItem s) {
        if (!superItems.contains(s))    {
            superItems.add(s);
        }
    }

    //[... a remove method is also in this class, not included here as not in scope]

    public List<subItem> getAllSubItems() {
        for (superItem s: superItems) {
            if (s.getClass() == SubItem.class) {
                if (!subItems.contains(s)) {
                    subItems.add((SubItem) s);
                }
            } else {
                //if it is a item, somehow call the method getAllSubItems() on itself
            }
        }
        return subItems;
    }
}

The only thing that is missing here, is when I came to this C-Item which is not a sub-item. I kinda want to unwrap C to get all the nested items in there.

Also what is important here:
Item can also contain Items itself. So the list can look also like this:

SuperItem[Item A, Item B, Item C, SubItem D]

and unfolded then:

SuperItemUnfolded1[Item A1, Item A2, SubItem B1, SubItem B2, Item C1, Item C2, SubItem D]

and more unfolded then:

SuperItemUnfolded2[SubItem A1.1, SubItem A1.2, SubItem A2.1, SubItem A2.2,SubItem B1, SubItem B2, Item C1.2, etc. etc.])

Body:
Perhaps you're looking for something like this:

public class SuperItem {
   List<Item> superItems = new LinkedList<Item>();
   List<Item> currentSubItems = null;

   public void addItem(Item s, boolean isNewSublist) {
      if (isNewSublist || currentSubItems == null) {
         currentSubItems = new LinkedList<Item>();
         superItems.add(currentSubItems);
      }
      if (!currentSubItems.contains(s))    {
         currentSubItems.add(s);
      }
      ...
   }

   public List<Item> getAllSubItems() {
      List<Item>subItems = new List<Item>();
      for (List<Item> superItem : superItems) {
         for (Item item : superItem.subItems) {
      ...
      return subItems;
   }
}

The details will vary depending on exactly what you want to accomlish, but basically it sounds like you:

Want a list of lists, containing "items".

You want to encapsulate this "list of lists" in a class.

The class should provide methods to "add" items, and to "list" items.

One thing I'm not clear about - should "items" be unique within a "sublist", or unique within the entire "list of lists" object?.  I chose the former.

You might also be interested in Java collections like Dictionary, Map or Set.

"Set" might be especially helpful to you:

https://www.tutorialspoint.com/java/java_set_interface.htm

A Set is a Collection that cannot contain duplicate elements. It
  models the mathematical set abstraction.

The Set interface contains only methods inherited from Collection and
  adds the restriction that duplicate elements are prohibited.

Set also adds a stronger contract on the behavior of the equals and
  hashCode operations, allowing Set instances to be compared
  meaningfully even if their implementation types differ.


问:
Is gschemas.compiled architecture specific (can I ship it with my python library)?
I'm working on a python library / app that uses Gtk.

Part of my build process uses glib-compile-schemas to create gschemas.compiled.

If I include gschemas.compiled in my library, will this break things, if somebody tries to use my library on something like ARM or 32 bit intel ?

(I would compile this as a post-install thing, but that seems to unsupported in setuptools which I am using).

答:
You should not ship a compiled gschemas.compiled cache as part of your app — instead, you should just ship your *.gschema.xml file. gschemas.compiled is intended as a system-wide cache of all the *.gschema.xml files in (by default) /usr/share/glib-2.0/schemas, and should be regenerated by the package manager after an app installs a new schema.

Debian has a lintian check to prevent packages shipping gschemas.compiled, for example.

There seem to be answers here on askubuntu about how to call glib-compile-schemas in a post-install step using setuptools.

To answer your specific question: yes, you should treat it as potentially architecture-specific.


问:
Prevent 3rd party libraries to get my push notifications
My app is implementing FCM as so as a 3rd party library I use. My Problem is every time I send a notification through the console the 3rd Party has a broadcast receiver registered like this

```<code>    <receiver
        android:name=".ThirdPartyReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </receiver>
</code>```

that is able to get the content of all my notifications, how I can prevent this? atm I'm initializing and using an instance of firebase app using my credentials like this:

```<code>FirebaseOptions.Builder()
        .setApplicationId(id)
        .setApiKey(api)
        .setDatabaseUrl(databaseurl)
        .setGcmSenderId(senderId)
        .setProjectId(projectId)
        .build()
</code>```

But looks like FCM only rely on the packageName to deliver push notifications and any third-party library contained in my project can register to get the push notifications, is there a way to prevent this?

Observation, manually disabling all unknown receivers prevents this, but then the library doesn't get the notifications anymore and I break its functionality.

答:
This is how I would do it (not tested)

Remove other receivers from the app manifest. I think this can be done with tools:node="remove" strategy of manifest merger

```<code><receiver tools:node="remove"
    android:name=".ThirdPartyReceiver"
    android:exported="true"
    android:permission="com.google.android.c2dm.permission.SEND" />
</code>```

Make your own implementation of FirebaseMessagingService follow a proxy pattern, i.e. invoke ThirdPartyReceiver if that's not a message you can handle.

Body:
My app is implementing FCM as so as a 3rd party library I use. My Problem is every time I send a notification through the console the 3rd Party has a broadcast receiver registered like this

    <receiver
        android:name=".ThirdPartyReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </receiver>

that is able to get the content of all my notifications, how I can prevent this? atm I'm initializing and using an instance of firebase app using my credentials like this:

FirebaseOptions.Builder()
        .setApplicationId(id)
        .setApiKey(api)
        .setDatabaseUrl(databaseurl)
        .setGcmSenderId(senderId)
        .setProjectId(projectId)
        .build()

But looks like FCM only rely on the packageName to deliver push notifications and any third-party library contained in my project can register to get the push notifications, is there a way to prevent this?

Observation, manually disabling all unknown receivers prevents this, but then the library doesn't get the notifications anymore and I break its functionality.

Body:
This is how I would do it (not tested)

Remove other receivers from the app manifest. I think this can be done with tools:node="remove" strategy of manifest merger

<receiver tools:node="remove"
    android:name=".ThirdPartyReceiver"
    android:exported="true"
    android:permission="com.google.android.c2dm.permission.SEND" />

Make your own implementation of FirebaseMessagingService follow a proxy pattern, i.e. invoke ThirdPartyReceiver if that's not a message you can handle.


问:
RegEx for capturing scientific citations
I am trying to capture brackets of text that have at least one digit in them (think citations). This is my regex now, and it works fine: https://regex101.com/r/oOHPvO/5

```<code>\((?=.*\d).+?\)
</code>```

So I wanted it to capture (Author 2000) and (2000) but not (Author).

I am trying to use python to capture all these brackets, but in python it also captures the text in the brackets even if they don't have digits.

```<code>import re

with open('text.txt') as f:
    f = f.read()

s = "\((?=.*\d).*?\)"

citations = re.findall(s, f)

citations = list(set(citations))

for c in citations:
    print (c)
</code>```

Any ideas what I am doing wrong?

答:
You may use

```<code>re.findall(r'\([^()\d]*\d[^()]*\)', s)
</code>```

See the regex demo

Details

\( - a ( char

[^()\d]* - 0 or more chars other than (, ) and digit

\d - a digit

[^()]* - 0 or more chars other than (, )

\) - a ) char.

See the regex graph:

Python demo:

```<code>import re
rx = re.compile(r"\([^()\d]*\d[^()]*\)")
s = "Some (Author) and (Author 2000)"
print(rx.findall(s)) # => ['(Author 2000)']
</code>```

To get the results without parentheses, add a capturing group:

```<code>rx = re.compile(r"\(([^()\d]*\d[^()]*)\)")
                    ^                ^
</code>```

See this Python demo.

Body:
I am trying to capture brackets of text that have at least one digit in them (think citations). This is my regex now, and it works fine: https://regex101.com/r/oOHPvO/5

\((?=.*\d).+?\)

So I wanted it to capture (Author 2000) and (2000) but not (Author).

I am trying to use python to capture all these brackets, but in python it also captures the text in the brackets even if they don't have digits.

import re

with open('text.txt') as f:
    f = f.read()

s = "\((?=.*\d).*?\)"

citations = re.findall(s, f)

citations = list(set(citations))

for c in citations:
    print (c)

Any ideas what I am doing wrong?

Body:
You may use

re.findall(r'\([^()\d]*\d[^()]*\)', s)

See the regex demo

Details

\( - a ( char

[^()\d]* - 0 or more chars other than (, ) and digit

\d - a digit

[^()]* - 0 or more chars other than (, )

\) - a ) char.

See the regex graph:

Python demo:

import re
rx = re.compile(r"\([^()\d]*\d[^()]*\)")
s = "Some (Author) and (Author 2000)"
print(rx.findall(s)) # => ['(Author 2000)']

To get the results without parentheses, add a capturing group:

rx = re.compile(r"\(([^()\d]*\d[^()]*)\)")
                    ^                ^

See this Python demo.


问:
How to make drop-down menu view as vertical?

site-nav {
    position: relative;
    top: 0.5em;
    left: 0;
    display: block;
    width: 80%;
    padding: 0.8em 2em 0 0;
    opacity: .95;
    background: none;
  }

 .site-nav ul li {
    display: inline-block;
    margin-left: 1.5em;
    margin-bottom: 0;
  }

 .drop-down {
    display: none;
  }

 ul li:hover ul {
    display:block;
    position: absolute;
    float: none;
    background-color: rgba(1,80,114,0.50);
    height: 9em;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="site-nav">
            <ul>
                <li>PAVEIKTIE DARBI</li>
                <li class="pakalp">PAKALPOJUMI
                    <ul class="drop-down">
                        <li>ĢENERĀLUZŅĒMĒJS</li>
                        <li>PROJEKTU VADĪBA</li>
                        <li>PROJEKTĒŠANA</li>
                        <li>BŪVDARBU VADĪBA</li>
                        <li>MONTĀŽA</li>
                    </ul>
                </li>
                <li>INŽENIERTEHNISKĀS SISTĒMAS</li>
                <li>KONTAKTI</li>
            </ul>
        </nav></code>```

I've been making this web-page for my new business, and I'm stuck with navigation bar - I can't make it drop as a vertical list. Instead it shows as flex. I wrota a lot of code and clearly messed up somewhere, but I can't find where exactly. Tried everything I could find on the internet (didn't check the dark web though), but I can't fix it.

Here is my CSS

```<code>.site-nav {
    position: relative;
    top: 0.5em;
    left: 0;
    display: block;
    width: 80%;
    padding: 0.8em 2em 0 0;
    opacity: .95;
    background: none;
  }

 .site-nav ul li {
    display: inline-block;
    margin-left: 1.5em;
    margin-bottom: 0;
  }

 .drop-down {
    display: none;
  }

 ul li:hover ul {
    display:block;
    position: absolute;
    float: none;
    background-color: rgba(1,80,114,0.50);
    height: 9em;
</code>```

Here is my HTML

```<code><nav class="site-nav">
            <ul>
                <li><a href="#">PAVEIKTIE DARBI</a></li>
                <li class="pakalp"><a href="#">PAKALPOJUMI</a>
                    <ul class="drop-down">
                        <li><a href="#">ĢENERĀLUZŅĒMĒJS</a></li>
                        <li><a href="#">PROJEKTU VADĪBA</a></li>
                        <li><a href="#">PROJEKTĒŠANA</a></li>
                        <li><a href="#">BŪVDARBU VADĪBA</a></li>
                        <li><a href="#">MONTĀŽA</a></li>
                    </ul>
                </li>
                <li><a href="#">INŽENIERTEHNISKĀS SISTĒMAS</a></li>
                <li><a href="#">KONTAKTI</a></li>
            </ul>
        </nav>
</code>```

答:
You are almost there. You need to make some adjustments to your CSS regarding the .dropdown class.

You can read more about flexbox here. Here we mainly set the following flexbox properties for our .dropdown class to get the desired behaviour:

display: flex;
flex-direction: column;
justify-content: space-around;
```

<p>Demo: https://codepen.io/anon/pen/XwqwOd</p>

<pre class="lang-css prettyprint-override"><code>.site-nav {
  position: relative;
  top: 0.5em;
  left: 0;
  display: block;
  width: 80%;
  padding: 0.8em 2em 0 0;
  opacity: 0.95;
  background: none;
}

.site-nav > ul > li {
  display: inline-block;
  margin-left: 1.5em;
  margin-bottom: 0;
}

.drop-down {
  display: none;
  padding: 0;
  flex-direction: column;
  justify-content: space-around;
}

.site-nav > ul > li:hover .drop-down {
  display: flex;
  position: absolute;
  background-color: rgba(1, 80, 114, 0.5);
  height: 9em;
}

.site-nav ul {
  list-style: none;
}
</code>```

Body:
site-nav {
    position: relative;
    top: 0.5em;
    left: 0;
    display: block;
    width: 80%;
    padding: 0.8em 2em 0 0;
    opacity: .95;
    background: none;
  }

 .site-nav ul li {
    display: inline-block;
    margin-left: 1.5em;
    margin-bottom: 0;
  }

 .drop-down {
    display: none;
  }

 ul li:hover ul {
    display:block;
    position: absolute;
    float: none;
    background-color: rgba(1,80,114,0.50);
    height: 9em;

PAVEIKTIE DARBI

PAKALPOJUMI

ĢENERĀLUZŅĒMĒJS

PROJEKTU VADĪBA

PROJEKTĒŠANA

BŪVDARBU VADĪBA

MONTĀŽA

INŽENIERTEHNISKĀS SISTĒMAS

KONTAKTI

I've been making this web-page for my new business, and I'm stuck with navigation bar - I can't make it drop as a vertical list. Instead it shows as flex. I wrota a lot of code and clearly messed up somewhere, but I can't find where exactly. Tried everything I could find on the internet (didn't check the dark web though), but I can't fix it.

Here is my CSS

.site-nav {
    position: relative;
    top: 0.5em;
    left: 0;
    display: block;
    width: 80%;
    padding: 0.8em 2em 0 0;
    opacity: .95;
    background: none;
  }

 .site-nav ul li {
    display: inline-block;
    margin-left: 1.5em;
    margin-bottom: 0;
  }

 .drop-down {
    display: none;
  }

 ul li:hover ul {
    display:block;
    position: absolute;
    float: none;
    background-color: rgba(1,80,114,0.50);
    height: 9em;

Here is my HTML

PAVEIKTIE DARBI

PAKALPOJUMI

ĢENERĀLUZŅĒMĒJS

PROJEKTU VADĪBA

PROJEKTĒŠANA

BŪVDARBU VADĪBA

MONTĀŽA

INŽENIERTEHNISKĀS SISTĒMAS

KONTAKTI

Body:
You are almost there. You need to make some adjustments to your CSS regarding the .dropdown class.

You can read more about flexbox here. Here we mainly set the following flexbox properties for our .dropdown class to get the desired behaviour:

display: flex;
flex-direction: column;
justify-content: space-around;

Demo: https://codepen.io/anon/pen/XwqwOd

.site-nav {
  position: relative;
  top: 0.5em;
  left: 0;
  display: block;
  width: 80%;
  padding: 0.8em 2em 0 0;
  opacity: 0.95;
  background: none;
}

.site-nav > ul > li {
  display: inline-block;
  margin-left: 1.5em;
  margin-bottom: 0;
}

.drop-down {
  display: none;
  padding: 0;
  flex-direction: column;
  justify-content: space-around;
}

.site-nav > ul > li:hover .drop-down {
  display: flex;
  position: absolute;
  background-color: rgba(1, 80, 114, 0.5);
  height: 9em;
}

.site-nav ul {
  list-style: none;
}


问:
Add rows to pandas dataframe using column of dictionaries
I have a dataframe like this:

```<code>matrix = [(222, {'a': 1, 'b':3, 'c':2, 'd':1}),
         (333, {'a': 1, 'b':0, 'c':0, 'd':1})]

df = pd.DataFrame(matrix, columns=['ordernum', 'dict_of item_counts'])
</code>```

```<code>   ordernum               dict_of item_counts
0       222  {'a': 1, 'b': 3, 'c': 2, 'd': 1}
1       333  {'a': 1, 'b': 0, 'c': 0, 'd': 1}
</code>```

and I would like to create a dataframe in which each ordernum is repeated for each dictionary key in dict_of_item_counts that is not 0. I would also like to create a key column that shows the corresponding dictionary key for this row as well as a value column that contains the dictionary values. Finally, I would also an ordernum_index that counts the different rows in the dataframe for each ordernum.

The final dataframe should look like this:

```<code>ordernum      ordernum_index      key     value

222           1                   a       1
222           2                   b       3
222           3                   c       2
222           4                   d       1
333           1                   a       1
333           2                   d       1
</code>```

Any help would be much appreciated :)

答:
You can do this by unpacking your dictionarys while accesing them with iterrows and creating a tuple out of the ordernum, key, value.

Finally to create your ordernum_index we groupby on ordernum and do a cumcount:

```<code>data = [(r['ordernum'], k, v) for _, r in df.iterrows() for k, v in r['dict_of item_counts'].items() ]

new = pd.DataFrame(data, columns=['ordernum', 'key', 'value']).sort_values('ordernum').reset_index(drop=True)

new['ordernum_index'] = new[new['value'].ne(0)].groupby('ordernum').cumcount().add(1)
new.dropna(inplace=True)
</code>```

```<code>   ordernum key  value  ordernum_index
0       222   a      1             1.0
1       222   b      3             2.0
2       222   c      2             3.0
3       222   d      1             4.0
4       333   a      1             1.0
7       333   d      1             2.0
</code>```

Body:
I have a dataframe like this:

matrix = [(222, {'a': 1, 'b':3, 'c':2, 'd':1}),
         (333, {'a': 1, 'b':0, 'c':0, 'd':1})]

df = pd.DataFrame(matrix, columns=['ordernum', 'dict_of item_counts'])

   ordernum               dict_of item_counts
0       222  {'a': 1, 'b': 3, 'c': 2, 'd': 1}
1       333  {'a': 1, 'b': 0, 'c': 0, 'd': 1}

and I would like to create a dataframe in which each ordernum is repeated for each dictionary key in dict_of_item_counts that is not 0. I would also like to create a key column that shows the corresponding dictionary key for this row as well as a value column that contains the dictionary values. Finally, I would also an ordernum_index that counts the different rows in the dataframe for each ordernum.

The final dataframe should look like this:

ordernum      ordernum_index      key     value

222           1                   a       1
222           2                   b       3
222           3                   c       2
222           4                   d       1
333           1                   a       1
333           2                   d       1

Any help would be much appreciated :)

Body:
You can do this by unpacking your dictionarys while accesing them with iterrows and creating a tuple out of the ordernum, key, value.

Finally to create your ordernum_index we groupby on ordernum and do a cumcount:

data = [(r['ordernum'], k, v) for _, r in df.iterrows() for k, v in r['dict_of item_counts'].items() ]

new = pd.DataFrame(data, columns=['ordernum', 'key', 'value']).sort_values('ordernum').reset_index(drop=True)

new['ordernum_index'] = new[new['value'].ne(0)].groupby('ordernum').cumcount().add(1)
new.dropna(inplace=True)

   ordernum key  value  ordernum_index
0       222   a      1             1.0
1       222   b      3             2.0
2       222   c      2             3.0
3       222   d      1             4.0
4       333   a      1             1.0
7       333   d      1             2.0


问:
How can I start PostgreSQL server on Mac OS X?

Final update:

I had forgotten to run the initdb command.

By running this command

```<code>ps auxwww | grep postgres
</code>```

I see that postgres is not running

```<code>> ps auxwww | grep postgres
remcat          1789   0.0  0.0  2434892    480 s000  R+   11:28PM   0:00.00 grep postgres
</code>```

This raises the question:

How do I start the PostgreSQL server?

Update:

```<code>> pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
server starting
sh: /usr/local/var/postgres/server.log: No such file or directory
</code>```

Update 2:

The touch was not successful, so I did this instead:

```<code>> mkdir /usr/local/var/postgres
> vi /usr/local/var/postgres/server.log
> ls /usr/local/var/postgres/
server.log
</code>```

But when I try to start the Ruby on Rails server, I still see this:

Is the server running on host "localhost" and accepting
TCP/IP connections on port 5432?

Update 3:

```<code>> pg_ctl -D /usr/local/var/postgres status
pg_ctl: no server running
</code>```

Update 4:

I found that there wasn't any pg_hba.conf file (only file pg_hba.conf.sample), so I modified the sample and renamed it (to remover the .sample). Here are the contents:

```<code> # IPv4 local connections:
 host    all             all             127.0.0.1/32           trust
 # IPv6 local connections:
 host    all             all             ::1/128                trust
</code>```

But I don't understand this:

```<code>> pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
server starting
> pg_ctl -D /usr/local/var/postgres status
pg_ctl: no server running
</code>```

Also:

```<code>sudo find / -name postgresql.conf
find: /dev/fd/3: Not a directory
find: /dev/fd/4: Not a directory
</code>```

Update 5:

```<code>sudo pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
Password:
pg_ctl: cannot be run as root
Please log in (using, e.g., "su") as the (unprivileged) user that will own the server process.
</code>```

Update 6:

This seems odd:

```<code>> egrep 'listen|port' /usr/local/var/postgres/postgresql.conf
egrep: /usr/local/var/postgres/postgresql.conf: No such file or directory
</code>```

Though, I did do this:

```<code>>sudo find / -name "*postgresql.conf*"
find: /dev/fd/3: Not a directory
find: /dev/fd/4: Not a directory
/usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf.sample
/usr/share/postgresql/postgresql.conf.sample
</code>```

So I did this:

```<code>egrep 'listen|port' /usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf.sample
#listen_addresses = 'localhost'        # what IP address(es) to listen on;
#port = 5432                # (change requires restart)
                # supported by the operating system:
                #   %r = remote host and port
</code>```

So I tried this:

```<code>> cp /usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf.sample /usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf
> cp /usr/share/postgresql/postgresql.conf.sample /usr/share/postgresql/postgresql.conf
</code>```

I am still getting the same "Is the server running?" message.

答:
For completeness sake: Check whether you're inside a Tmux or Screen instance. Starting won't work from there.

From: Error while trying to start PostgreSQL installed via Homebrew: “Operation not permitted”

This solved it for me.

Body:
Final update:

I had forgotten to run the initdb command.

By running this command

ps auxwww | grep postgres

I see that postgres is not running

> ps auxwww | grep postgres
remcat          1789   0.0  0.0  2434892    480 s000  R+   11:28PM   0:00.00 grep postgres

This raises the question:

How do I start the PostgreSQL server?

Update:

> pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
server starting
sh: /usr/local/var/postgres/server.log: No such file or directory

Update 2:

The touch was not successful, so I did this instead:

> mkdir /usr/local/var/postgres
> vi /usr/local/var/postgres/server.log
> ls /usr/local/var/postgres/
server.log

But when I try to start the Ruby on Rails server, I still see this:

Is the server running on host "localhost" and accepting
TCP/IP connections on port 5432?

Update 3:

> pg_ctl -D /usr/local/var/postgres status
pg_ctl: no server running

Update 4:

I found that there wasn't any pg_hba.conf file (only file pg_hba.conf.sample), so I modified the sample and renamed it (to remover the .sample). Here are the contents:

 # IPv4 local connections:
 host    all             all             127.0.0.1/32           trust
 # IPv6 local connections:
 host    all             all             ::1/128                trust

But I don't understand this:

> pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
server starting
> pg_ctl -D /usr/local/var/postgres status
pg_ctl: no server running

Also:

sudo find / -name postgresql.conf
find: /dev/fd/3: Not a directory
find: /dev/fd/4: Not a directory

Update 5:

sudo pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
Password:
pg_ctl: cannot be run as root
Please log in (using, e.g., "su") as the (unprivileged) user that will own the server process.

Update 6:

This seems odd:

> egrep 'listen|port' /usr/local/var/postgres/postgresql.conf
egrep: /usr/local/var/postgres/postgresql.conf: No such file or directory

Though, I did do this:

>sudo find / -name "*postgresql.conf*"
find: /dev/fd/3: Not a directory
find: /dev/fd/4: Not a directory
/usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf.sample
/usr/share/postgresql/postgresql.conf.sample

So I did this:

egrep 'listen|port' /usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf.sample
#listen_addresses = 'localhost'        # what IP address(es) to listen on;
#port = 5432                # (change requires restart)
                # supported by the operating system:
                #   %r = remote host and port

So I tried this:

> cp /usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf.sample /usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf
> cp /usr/share/postgresql/postgresql.conf.sample /usr/share/postgresql/postgresql.conf

I am still getting the same "Is the server running?" message.


问:
One UITableViewCell is controlling others
Does anyone know what's happening here? I've configured a UITableView with CollectionViewCells, and each of these cells is supposed to operate independently of each other, yet when I swipe one it controls another cell which is 3 cells underneath it.

Tried to reconfigure my UITableViewCells and the CollectionViewCells. But I'm not exactly sure what to do

```<code>//TableView controler

import UIKit
import CardsLayout
import CHIPageControl

class eventsFeed: UIViewController, UITableViewDelegate, UITableViewDataSource{

    // Global Variable
    var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        tableView = UITableView(frame: CGRect(x: self.view.bounds.minX, y: self.view.bounds.minY+UIApplication.shared.statusBarFrame.height, width: self.view.bounds.width, height: self.view.bounds.height))

        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        self.view.addSubview(tableView)

        tableView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
        cell.backgroundColor = UIColor.white
        cell.selectionStyle = .none
        return cell
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        return 430.0;//Choose your custom row height
    }

}

//CollectionViewCell for TableView

import UIKit
import CardsLayout

class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {

    var collectionView: UICollectionView!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.horizontal

        collectionView = UICollectionView(frame: CGRect(x: 0, y:0, width: UIScreen.main.bounds.width, height: 410.0), collectionViewLayout: layout)
        collectionView.center = CGPoint(x: 187.5, y: 180)
        collectionView.collectionViewLayout = CardsCollectionViewLayout()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
        collectionView.backgroundColor = UIColor.white

        self.addSubview(collectionView)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
    var colors: [UIColor]  = [
        UIColor(red: 237, green: 37, blue: 78),
        UIColor(red: 249, green: 220, blue: 92),
        UIColor.blue,
        UIColor(red: 1, green: 25, blue: 54),
        UIColor(red: 255, green: 184, blue: 209),
        UIColor(red: 237, green: 37, blue: 78),
        UIColor(red: 249, green: 220, blue: 92)
        ]

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
        cell.layer.cornerRadius = 12.0
        cell.backgroundColor = colors[indexPath.row]

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return colors.count
    }
}
</code>```

Video of issue: https://www.reddit.com/r/iOSProgramming/comments/btcok4/does_anyone_know_whats_happening_here_ive/

答:
Cells are reused. That means that you have to choose different strategy of working with them.

Save somewhere current state for each table view cell (for example in structs in an array) and then configure cell based on this state in cellForRowAt delegate's method.

Body:
Does anyone know what's happening here? I've configured a UITableView with CollectionViewCells, and each of these cells is supposed to operate independently of each other, yet when I swipe one it controls another cell which is 3 cells underneath it.

Tried to reconfigure my UITableViewCells and the CollectionViewCells. But I'm not exactly sure what to do

//TableView controler

import UIKit
import CardsLayout
import CHIPageControl

class eventsFeed: UIViewController, UITableViewDelegate, UITableViewDataSource{

    // Global Variable
    var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        tableView = UITableView(frame: CGRect(x: self.view.bounds.minX, y: self.view.bounds.minY+UIApplication.shared.statusBarFrame.height, width: self.view.bounds.width, height: self.view.bounds.height))

        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        self.view.addSubview(tableView)

        tableView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
        cell.backgroundColor = UIColor.white
        cell.selectionStyle = .none
        return cell
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        return 430.0;//Choose your custom row height
    }

}

//CollectionViewCell for TableView

import UIKit
import CardsLayout

class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {

    var collectionView: UICollectionView!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.horizontal

        collectionView = UICollectionView(frame: CGRect(x: 0, y:0, width: UIScreen.main.bounds.width, height: 410.0), collectionViewLayout: layout)
        collectionView.center = CGPoint(x: 187.5, y: 180)
        collectionView.collectionViewLayout = CardsCollectionViewLayout()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
        collectionView.backgroundColor = UIColor.white

        self.addSubview(collectionView)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
    var colors: [UIColor]  = [
        UIColor(red: 237, green: 37, blue: 78),
        UIColor(red: 249, green: 220, blue: 92),
        UIColor.blue,
        UIColor(red: 1, green: 25, blue: 54),
        UIColor(red: 255, green: 184, blue: 209),
        UIColor(red: 237, green: 37, blue: 78),
        UIColor(red: 249, green: 220, blue: 92)
        ]

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
        cell.layer.cornerRadius = 12.0
        cell.backgroundColor = colors[indexPath.row]

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return colors.count
    }
}

Video of issue: https://www.reddit.com/r/iOSProgramming/comments/btcok4/does_anyone_know_whats_happening_here_ive/


问:
Getting strings recognized as variable names in R
Related: Strings as variable references in R

Possibly related: Concatenate expressions to subset a dataframe

I've simplified the question per the comment request. Here goes with some example data.

```<code>dat <- data.frame(num=1:10,sq=(1:10)^2,cu=(1:10)^3)
set1 <- subset(dat,num>5)
set2 <- subset(dat,num<=5)
</code>```

Now, I'd like to make a bubble plot from these. I have a more complicated data set with 3+ colors and complicated subsets, but I do something like this:

```<code>symbols(set1$sq,set1$cu,circles=set1$num,bg="red")
symbols(set2$sq,set2$cu,circles=set2$num,bg="blue",add=T)
</code>```

I'd like to do a for loop like this:

```<code>colors <- c("red","blue")
sets <- c("set1","set2")
vars <- c("sq","cu","num")

for (i in 1:length(sets)) {
   symbols(sets[[i]][,sq],sets[[i]][,cu],circles=sets[[i]][,num],
   bg=colors[[i]],add=T)
}
</code>```

I know you can have a variable evaluated to specify the column (like var="cu"; set1[,var]; I want to know how to get a variable to specify the data.frame itself (and another to evaluate the column).

Update: Ran across this post on r-bloggers which has this example:

```<code>x <- 42
eval(parse(text = "x"))
[1] 42
</code>```

I'm able to do something like this now:

```<code>eval(parse(text=paste(set[[1]],"$",var1,sep="")))
</code>```

In fiddling with this, I'm finding it interesting that the following are not equivalent:

```<code>vars <- data.frame("var1","var2")
eval(parse(text=paste(set[[1]],"$",var1,sep="")))
eval(parse(text=paste(set[[1]],"[,vars[[1]]]",sep="")))
</code>```

I actually have to do this:

```<code>eval(parse(text=paste(set[[1]],"[,as.character(vars[[1]])]",sep="")))
</code>```

Update2: The above works to output values... but not in trying to plot. I can't do:

```<code>for (i in 1:length(set)) {
symbols(eval(parse(text=paste(set[[i]],"$",var1,sep=""))),
       eval(parse(text=paste(set[[i]],"$",var2,sep=""))),
       circles=paste(set[[i]],".","circles",sep=""),
       fg="white",bg=colors[[i]],add=T)
}
</code>```

I get invalid symbol coordinates. I checked the class of set[[1]] and it's a factor. If I do is.numeric(as.numeric(set[[1]])) I get TRUE. Even if I add that above prior to the eval statement, I still get the error. Oddly, though, I can do this:

```<code>set.xvars <- as.numeric(eval(parse(text=paste(set[[i]],"$",var1,sep=""))))
set.yvars <- as.numeric(eval(parse(text=paste(set[[i]],"$",var2,sep=""))))
symbols(xvars,yvars,circles=data$var3)
</code>```

Why different behavior when stored as a variable vs. executed within the symbol function?

答:
What works best for me is using quote() and eval() together.

For example, let's print each column using a for loop:

```<code>Columns <- names(dat)
for (i in 1:ncol(dat)){
  dat[, eval(quote(Columns[i]))] %>% print
}
</code>```

Body:
Related: Strings as variable references in R

Possibly related: Concatenate expressions to subset a dataframe

I've simplified the question per the comment request. Here goes with some example data.

dat <- data.frame(num=1:10,sq=(1:10)^2,cu=(1:10)^3)
set1 <- subset(dat,num>5)
set2 <- subset(dat,num<=5)

Now, I'd like to make a bubble plot from these. I have a more complicated data set with 3+ colors and complicated subsets, but I do something like this:

symbols(set1$sq,set1$cu,circles=set1$num,bg="red")
symbols(set2$sq,set2$cu,circles=set2$num,bg="blue",add=T)

I'd like to do a for loop like this:

colors <- c("red","blue")
sets <- c("set1","set2")
vars <- c("sq","cu","num")

for (i in 1:length(sets)) {
   symbols(sets[[i]][,sq],sets[[i]][,cu],circles=sets[[i]][,num],
   bg=colors[[i]],add=T)
}

I know you can have a variable evaluated to specify the column (like var="cu"; set1[,var]; I want to know how to get a variable to specify the data.frame itself (and another to evaluate the column).

Update: Ran across this post on r-bloggers which has this example:

x <- 42
eval(parse(text = "x"))
[1] 42

I'm able to do something like this now:

eval(parse(text=paste(set[[1]],"$",var1,sep="")))

In fiddling with this, I'm finding it interesting that the following are not equivalent:

vars <- data.frame("var1","var2")
eval(parse(text=paste(set[[1]],"$",var1,sep="")))
eval(parse(text=paste(set[[1]],"[,vars[[1]]]",sep="")))

I actually have to do this:

eval(parse(text=paste(set[[1]],"[,as.character(vars[[1]])]",sep="")))

Update2: The above works to output values... but not in trying to plot. I can't do:

for (i in 1:length(set)) {
symbols(eval(parse(text=paste(set[[i]],"$",var1,sep=""))),
       eval(parse(text=paste(set[[i]],"$",var2,sep=""))),
       circles=paste(set[[i]],".","circles",sep=""),
       fg="white",bg=colors[[i]],add=T)
}

I get invalid symbol coordinates. I checked the class of set[[1]] and it's a factor. If I do is.numeric(as.numeric(set[[1]])) I get TRUE. Even if I add that above prior to the eval statement, I still get the error. Oddly, though, I can do this:

set.xvars <- as.numeric(eval(parse(text=paste(set[[i]],"$",var1,sep=""))))
set.yvars <- as.numeric(eval(parse(text=paste(set[[i]],"$",var2,sep=""))))
symbols(xvars,yvars,circles=data$var3)

Why different behavior when stored as a variable vs. executed within the symbol function?

Body:
What works best for me is using quote() and eval() together.

For example, let's print each column using a for loop:

Columns <- names(dat)
for (i in 1:ncol(dat)){
  dat[, eval(quote(Columns[i]))] %>% print
}


问:
Need help writing and reading a file with PHP
So for an assignment, I have to create a form where users can post ride shares so other people can see and join their ride. I'm doing this by writing the form to a file data.txt, and reading the file to display all the rides on a board. My only problem is when I get the contents of data.txt, it's all combined together. I need to be able to display each ride separately. How would I go about doing this?

Here is my code so far:
The writing:

```<code>if (isset($_POST['name'])
              && isset($_POST['email'])
              && isset($_POST['date'])
              && isset($_POST['destination'])
              && isset($_POST['msg'])) {
          $name = $_POST['name'];
          $email = $_POST['email'];
          $date = $_POST['date'];
          $destination = $_POST['destination'];
          $msg = $_POST['msg'];

          //TODO the file write here VV, use 'a' instead of 'w' too ADD to the file instead of REWRITING IT.
          $arr = [$name,$email,$date,$destination,$msg];

          $write = json_encode($arr);
          $file = fopen('data.txt', 'a');
          fwrite($file, $write);
          fclose($file);
      }
</code>```

And the reading:

```<code>  $path = 'data.txt';
          $handle = fopen($path, 'r');
          $contents = fread($handle, filesize($path));
          echo $contents;
          fclose($handle);

          $newarr = [json_decode($contents)];

          foreach($newarr as $stuff)
          {
            echo $stuff[0];
          }
</code>```

And the output is something like:

```<code>["Simon Long","example@gmail.com","2109-01-01T01:01","canada","this is a message"] Simon Long
</code>```

Let's say there are multiple postings in there, it would just print them all together. I need a way to separate postings so I can display them nicely on the board.

答:
Use a multidimensional array.

```<code>$arr = [
    "Simon Long","example@gmail.com","2109-01-01T01:01","canada","this is a message",
    "John Doe","john@gmail.com","2109-01-01T01:01","canada","this is a message",
    "Jane Doe","jane@gmail.com","2109-01-01T01:01","canada","this is a message"
];
</code>```

Then you when you add to it just append to the final array and replace the whole file.

```<code>$contents = file_get_contents($path);
$decoded = json_decode($contents);
$decoded[] = [$name,$email,$date,$destination,$msg];
file_put_contents($path, json_encode($decoded)); //replace the entire file.
</code>```

Also just as a side note. isset accepts multiple arguments so you don't need to use it as you are. You can do this:

if (isset($_POST['name'], $_POST['email'], $_POST['date'], $_POST['destination'] ...)

It's also a good idea to sanitise any input from the user.

$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);

Body:
So for an assignment, I have to create a form where users can post ride shares so other people can see and join their ride. I'm doing this by writing the form to a file data.txt, and reading the file to display all the rides on a board. My only problem is when I get the contents of data.txt, it's all combined together. I need to be able to display each ride separately. How would I go about doing this?

Here is my code so far:
The writing:

if (isset($_POST['name'])
              && isset($_POST['email'])
              && isset($_POST['date'])
              && isset($_POST['destination'])
              && isset($_POST['msg'])) {
          $name = $_POST['name'];
          $email = $_POST['email'];
          $date = $_POST['date'];
          $destination = $_POST['destination'];
          $msg = $_POST['msg'];

          //TODO the file write here VV, use 'a' instead of 'w' too ADD to the file instead of REWRITING IT.
          $arr = [$name,$email,$date,$destination,$msg];

          $write = json_encode($arr);
          $file = fopen('data.txt', 'a');
          fwrite($file, $write);
          fclose($file);
      }

And the reading:

  $path = 'data.txt';
          $handle = fopen($path, 'r');
          $contents = fread($handle, filesize($path));
          echo $contents;
          fclose($handle);

          $newarr = [json_decode($contents)];

          foreach($newarr as $stuff)
          {
            echo $stuff[0];
          }

And the output is something like:

["Simon Long","example@gmail.com","2109-01-01T01:01","canada","this is a message"] Simon Long

Let's say there are multiple postings in there, it would just print them all together. I need a way to separate postings so I can display them nicely on the board.

Body:
Use a multidimensional array.

$arr = [
    "Simon Long","example@gmail.com","2109-01-01T01:01","canada","this is a message",
    "John Doe","john@gmail.com","2109-01-01T01:01","canada","this is a message",
    "Jane Doe","jane@gmail.com","2109-01-01T01:01","canada","this is a message"
];

Then you when you add to it just append to the final array and replace the whole file.

$contents = file_get_contents($path);
$decoded = json_decode($contents);
$decoded[] = [$name,$email,$date,$destination,$msg];
file_put_contents($path, json_encode($decoded)); //replace the entire file.

Also just as a side note. isset accepts multiple arguments so you don't need to use it as you are. You can do this:

if (isset($_POST['name'], $_POST['email'], $_POST['date'], $_POST['destination'] ...)

It's also a good idea to sanitise any input from the user.

$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);


问:
How to convert a UTC timestamp to local day, hour, minute in Java?
Given then timestamp 1245613885 that is a timestamp in GMT

How do I turn that into Year, Day, Hour, Minute values in Java using the server's local timezone info?

答:
tl;dr

```<code>Instant                                        // Represent a moment in UTC.
.ofEpochMilli( 1_245_613_885L )                // Parse a count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
.atZone(                                       // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone).
    ZoneId.of( "Asia/Tokyo" )                  // Or "America/Chicago" etc.
)                                              // Returns a `ZonedDateTime` object.
.format(                                       // Generate text representing the value of our `ZonedDateTime` object.
    DateTimeFormatter
    .ofLocalizedDateTime( FormatStyle.FULL )   // Automatically localize the format and content of the string being generated.
    .withLocale( Locale.CANADA_FRENCH )        // Or Locale.US etc.
)                                              // Returns a `String` object.
</code>```

jeudi 15 janvier 1970 à 19 h 00 min 13 s heure normale du Japon

java.time

The modern approach uses the java.time classes that supplanted the terrible date-time classes as of the adoption of JSR 310.

If your input 1245613885 is count of milliseconds since the first moment of 1970 in UTC, then parse as an Instant (a moment in UTC).

```<code>Instant instant = Instant.ofEpochMilli( 1_245_613_885L ) ;
</code>```

Generate a string representing the value of that Instant object using standard ISO 8601 format.

```<code>String output = instant.toString() ;
</code>```

Adjust from UTC to the wall-clock time used by the people of a particular region( a time zone).

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

```<code>ZoneId z = ZoneId.of( "America/Montreal" ) ;
</code>```

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

```<code>ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.
</code>```

Apply a ZoneId to the Instant to get a ZonedDateTime.

```<code>ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment as the `instant`, but different wall-clock time.
</code>```

Generate a string representing the value of that ZonedDateTime object using standard ISO 8601 format extended to append the name of the zone in square brackets.

```<code>String output = zdt.toString() ;
</code>```

For other formats, either specify your own custom formatting pattern or let java.time automatically localize. For either route, use DateTimeFormatter. Search Stack Overflow as this has been handled many times already.

ContentLicense: CC BY-SA 2.5

Body:
tl;dr

Instant                                        // Represent a moment in UTC.
.ofEpochMilli( 1_245_613_885L )                // Parse a count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
.atZone(                                       // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone).
    ZoneId.of( "Asia/Tokyo" )                  // Or "America/Chicago" etc.
)                                              // Returns a `ZonedDateTime` object.
.format(                                       // Generate text representing the value of our `ZonedDateTime` object.
    DateTimeFormatter
    .ofLocalizedDateTime( FormatStyle.FULL )   // Automatically localize the format and content of the string being generated.
    .withLocale( Locale.CANADA_FRENCH )        // Or Locale.US etc.
)                                              // Returns a `String` object.

jeudi 15 janvier 1970 à 19 h 00 min 13 s heure normale du Japon

java.time

The modern approach uses the java.time classes that supplanted the terrible date-time classes as of the adoption of JSR 310.

If your input 1245613885 is count of milliseconds since the first moment of 1970 in UTC, then parse as an Instant (a moment in UTC).

Instant instant = Instant.ofEpochMilli( 1_245_613_885L ) ;

Generate a string representing the value of that Instant object using standard ISO 8601 format.

String output = instant.toString() ;

Adjust from UTC to the wall-clock time used by the people of a particular region( a time zone).

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Apply a ZoneId to the Instant to get a ZonedDateTime.

ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment as the `instant`, but different wall-clock time.

Generate a string representing the value of that ZonedDateTime object using standard ISO 8601 format extended to append the name of the zone in square brackets.

String output = zdt.toString() ;

For other formats, either specify your own custom formatting pattern or let java.time automatically localize. For either route, use DateTimeFormatter. Search Stack Overflow as this has been handled many times already.