问:
Recursion with Hash Map Values as Key
I have a HashMap>.
1={2,3}, 2={4,5} , 3={6,7} ..

The value List 's elements itself are keys in the same HashMap.

Considering 1 as my root, I want to retrieve the values in the order 1,2,3,4,5,6,7...

Trying it using recursion with no success!!! ;-(

My Code:

```<code>package WrapperClasses;

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

import Collections.BinaryTree.Node;

// Class name should be "Source",
// otherwise solution won't be accepted
public class Source3_Try2 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // Declare the variable
        int a;
        // Read the variable from STDIN
        a = in.nextInt();
        String key, value;
        HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
        ArrayList<String> keyList = new ArrayList<String>();
        for (int i = 0; i < a; i++) {
            ArrayList<String> al = new ArrayList<String>();
            key = in.next();
            value = in.next();
            if (hm.containsKey(key)) {
                al = hm.get(key);
            } else {
                keyList.add(key);
            }
            al.add(value);
            hm.put(key, al);

        }
        ArrayList<Node> nodeList = new ArrayList<Node>();
        String f = in.next();
        BinaryTree bt = new BinaryTree();
        bt.insertNode(f);
        ArrayList<String> valueList= hm.get(f);
        insertInTree(bt,valueList,hm,0,0);
        for (String k : keyList) {
            if (!k.equalsIgnoreCase(f)) {
            }
        }
        // Output the variable to STDOUT

        bt.inorderTraversal(bt.root);

    }

    public static void insertInTree(BinaryTree bt , ArrayList<String> valueList,HashMap<String, ArrayList<String>> hm, int flag, int size){
        for(String v : valueList){
            bt.insertNode(v);
        }
        if(flag==size){
        for(String v2 : valueList){
            flag++;
            insertInTree(bt,hm.get(v2),hm,flag,valueList.size());
        }
        }
    }

    // InnerClass: Binary Tree Implementaion - Starts
            static class BinaryTree {
                class Node {
                    String data;
                    Node left;
                    Node right;
                    Node parent;

                    public Node(String data) {
                        this.data = data;
                        this.left = null;
                        this.right = null;
                    }
                }

                public Node root;

                public BinaryTree() {
                    root = null;
                }

                public void insertNode(String data) {
                    Node newNode = new Node(data);
                    if (root == null) {
                        root = newNode;
                        return;
                    } else {
                        Queue<Node> queue = new LinkedList<Node>();
                        queue.add(root);
                        while (true) {
                            Node node = queue.remove();
                            if (node.left != null && node.right != null) {
                                queue.add(node.left);
                                queue.add(node.right);
                            } else {
                                if (node.left == null) {
                                    newNode.parent=node;
                                    node.left = newNode;
                                    queue.add(node.left);
                                } else {
                                    newNode.parent=node;
                                    node.right = newNode;
                                    queue.add(node.right);
                                }
                                break;
                            }
                        }
                    }
                }

                public void inorderTraversal(Node node) {
                    if (root == null) {
                        System.out.println("Tree is empty");
                        return;
                    } else {
                        System.out.print(node.data + "\n");
                        if (node.left != null)
                            inorderTraversal(node.left);
                        if (node.right != null) {
                            inorderTraversal(node.right);
                        }
                    }
                }
            } // InnerClass: Binary Tree Implementaion - Ends
}
</code>```

CL Input:

5

London Paris

London Rome

Paris Berlin

Paris Amsterdam

Rome Venice

London

Expected Output:

London

Paris

Berlin

Amsterdam

Rome

Venice

答:
```<code>package WrapperClasses;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.text.*;
import java.math.*;
import java.util.regex.*;

import Collections.BinaryTree.Node;

// Class name should be "Source",
// otherwise solution won't be accepted
public class Source3_MyOptimization {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // Declare the variable
        int a;
        // Read the variable from STDIN
        a = in.nextInt();
        String key, value;
        HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
        ArrayList<String> keyList = new ArrayList<String>();
        for (int i = 0; i < a; i++) {
            ArrayList<String> al = new ArrayList<String>();
            key = in.next();
            value = in.next();
            if (hm.containsKey(key)) {
                al = hm.get(key);
            } else {
                keyList.add(key);
            }
            al.add(value);
            hm.put(key, al);
        }

        System.out.println("hm: " + hm);

        for (Map.Entry<String, ArrayList<String>> hmEntry : hm.entrySet()) {
            String key1 = hmEntry.getKey();
            ArrayList<String> value1 = hmEntry.getValue();
            System.out.println(key1 + " :" + value1);
        }

        for (String key2 : hm.keySet()) {
            ArrayList<String> value2 = hm.get(key2);
            System.out.println(key2 + " :" + value2);
        }

        Iterator itr = hm.entrySet().iterator();
        while (itr.hasNext()) {
            Map.Entry<String, ArrayList<String>> hmE = (Map.Entry<String, ArrayList<String>>) itr.next();
            String key3 = hmE.getKey();
            ArrayList<String> value3 = hmE.getValue();
            System.out.println(key3 + " :" + value3);
        }

        Iterator itr2 = hm.keySet().iterator();
        while (itr2.hasNext()) {
            String key4 = (String) itr2.next();
            ArrayList<String> value4 = hm.get(key4);
            System.out.println(key4 + " :" + value4);
        }

        String f = in.next();
        BinaryTree bt = new BinaryTree();
        bt.insertNode(f);
        ArrayList<String> valueList = hm.get(f);
        Queue<String> queue = new LinkedList<String>();
        queue.addAll(valueList);
        queueForInsert(bt, hm, queue);
        bt.inorderTraversal(bt.root);
    }

    public static void queueForInsert(BinaryTree bt, HashMap<String, ArrayList<String>> hm, Queue<String> queue) {
        while(!queue.isEmpty()){
        bt.insertNode(queue.peek());
        if(hm.containsKey(queue.peek())){
        queue.addAll(hm.get(queue.remove()));
        }
        else{
            queue.remove();
        }
        queueForInsert(bt, hm, queue);
        }
    }

    // InnerClass: Binary Tree Implementaion - Starts
    static class BinaryTree {
        class Node {
            String data;
            Node left;
            Node right;
            Node parent;

            public Node(String data) {
                this.data = data;
                this.left = null;
                this.right = null;
            }
        }

        public Node root;

        public BinaryTree() {
            root = null;
        }

        public void insertNode(String data) {
            Node newNode = new Node(data);
            if (root == null) {
                root = newNode;
                return;
            } else {
                Queue<Node> queue = new LinkedList<Node>();
                queue.add(root);
                while (true) {
                    Node node = queue.remove();
                    if (node.left != null && node.right != null) {
                        queue.add(node.left);
                        queue.add(node.right);
                    } else {
                        if (node.left == null) {
                            newNode.parent = node;
                            node.left = newNode;
                            queue.add(node.left);
                        } else {
                            newNode.parent = node;
                            node.right = newNode;
                            queue.add(node.right);
                        }
                        break;
                    }
                }
            }
        }

        public void inorderTraversal(Node node) {
            if (root == null) {
                System.out.println("Tree is empty");
                return;
            } else {
                System.out.print(node.data + "\n");
                if (node.left != null)
                    inorderTraversal(node.left);
                if (node.right != null) {
                    inorderTraversal(node.right);
                }
            }
        }
    } // InnerClass: Binary Tree Implementaion - Ends
}
</code>```

Title: Recursion with Hash Map Values as Key

Body:
I have a HashMap>.
1={2,3}, 2={4,5} , 3={6,7} ..

The value List 's elements itself are keys in the same HashMap.

Considering 1 as my root, I want to retrieve the values in the order 1,2,3,4,5,6,7...

Trying it using recursion with no success!!! ;-(

My Code:

package WrapperClasses;

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

import Collections.BinaryTree.Node;

// Class name should be "Source",
// otherwise solution won't be accepted
public class Source3_Try2 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // Declare the variable
        int a;
        // Read the variable from STDIN
        a = in.nextInt();
        String key, value;
        HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
        ArrayList<String> keyList = new ArrayList<String>();
        for (int i = 0; i < a; i++) {
            ArrayList<String> al = new ArrayList<String>();
            key = in.next();
            value = in.next();
            if (hm.containsKey(key)) {
                al = hm.get(key);
            } else {
                keyList.add(key);
            }
            al.add(value);
            hm.put(key, al);

        }
        ArrayList<Node> nodeList = new ArrayList<Node>();
        String f = in.next();
        BinaryTree bt = new BinaryTree();
        bt.insertNode(f);
        ArrayList<String> valueList= hm.get(f);
        insertInTree(bt,valueList,hm,0,0);
        for (String k : keyList) {
            if (!k.equalsIgnoreCase(f)) {
            }
        }
        // Output the variable to STDOUT

        bt.inorderTraversal(bt.root);

    }

    public static void insertInTree(BinaryTree bt , ArrayList<String> valueList,HashMap<String, ArrayList<String>> hm, int flag, int size){
        for(String v : valueList){
            bt.insertNode(v);
        }
        if(flag==size){
        for(String v2 : valueList){
            flag++;
            insertInTree(bt,hm.get(v2),hm,flag,valueList.size());
        }
        }
    }

    // InnerClass: Binary Tree Implementaion - Starts
            static class BinaryTree {
                class Node {
                    String data;
                    Node left;
                    Node right;
                    Node parent;

                    public Node(String data) {
                        this.data = data;
                        this.left = null;
                        this.right = null;
                    }
                }

                public Node root;

                public BinaryTree() {
                    root = null;
                }

                public void insertNode(String data) {
                    Node newNode = new Node(data);
                    if (root == null) {
                        root = newNode;
                        return;
                    } else {
                        Queue<Node> queue = new LinkedList<Node>();
                        queue.add(root);
                        while (true) {
                            Node node = queue.remove();
                            if (node.left != null && node.right != null) {
                                queue.add(node.left);
                                queue.add(node.right);
                            } else {
                                if (node.left == null) {
                                    newNode.parent=node;
                                    node.left = newNode;
                                    queue.add(node.left);
                                } else {
                                    newNode.parent=node;
                                    node.right = newNode;
                                    queue.add(node.right);
                                }
                                break;
                            }
                        }
                    }
                }

                public void inorderTraversal(Node node) {
                    if (root == null) {
                        System.out.println("Tree is empty");
                        return;
                    } else {
                        System.out.print(node.data + "\n");
                        if (node.left != null)
                            inorderTraversal(node.left);
                        if (node.right != null) {
                            inorderTraversal(node.right);
                        }
                    }
                }
            } // InnerClass: Binary Tree Implementaion - Ends
}

CL Input:

5

London Paris

London Rome

Paris Berlin

Paris Amsterdam

Rome Venice

London

Expected Output:

London

Paris

Berlin

Amsterdam

Rome

Venice


来源: stackexchange

问:
SwiftUI HStack with wrap and dynamic height
I have this view to show text tags on multiple lines which I got from SwiftUI HStack with Wrap, but when I add it in a VStack the tags overlap any other view that I put below.
The tags are shown properly but the height of the view itself is not calculated inside the VStack.
How can I make this view use the height of is content?

```<code>import SwiftUI

struct TestWrappedLayout: View {
    @State var platforms = ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4"]

    var body: some View {
        GeometryReader { geometry in
            self.generateContent(in: geometry)
        }
    }

    private func generateContent(in g: GeometryProxy) -> some View {
        var width = CGFloat.zero
        var height = CGFloat.zero

        return ZStack(alignment: .topLeading) {
            ForEach(self.platforms, id: \.self) { platform in
                self.item(for: platform)
                    .padding([.horizontal, .vertical], 4)
                    .alignmentGuide(.leading, computeValue: { d in
                        if (abs(width - d.width) > g.size.width)
                        {
                            width = 0
                            height -= d.height
                        }
                        let result = width
                        if platform == self.platforms.last! {
                            width = 0 //last item
                        } else {
                            width -= d.width
                        }
                        return result
                    })
                    .alignmentGuide(.top, computeValue: {d in
                        let result = height
                        if platform == self.platforms.last! {
                            height = 0 // last item
                        }
                        return result
                    })
            }
        }
    }

    func item(for text: String) -> some View {
        Text(text)
            .padding(.all, 5)
            .font(.body)
            .background(Color.blue)
            .foregroundColor(Color.white)
            .cornerRadius(5)
    }
}

struct TestWrappedLayout_Previews: PreviewProvider {
    static var previews: some View {
        TestWrappedLayout()
    }
}
</code>```

Example code:

```<code>struct ExampleTagsView: View {
    var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                Text("Platforms:")
                TestWrappedLayout()

                Text("Other Platforms:")
                TestWrappedLayout()
            }
        }
    }
}

struct ExampleTagsView_Previews: PreviewProvider {
    static var previews: some View {
        ExampleTagsView()
    }
}
</code>```

Result:

答:
I just managed to solve this by moving the GeometryReader up to the ExampleTagsView and using platforms.first instead of last inside .alignmentGuide

Full code:

```<code>import SwiftUI

struct ExampleTagsView: View {
    var body: some View {
        GeometryReader { geometry in
            ScrollView(.vertical) {
                VStack(alignment: .leading) {
                    Text("Platforms:")
                    TestWrappedLayout(geometry: geometry)

                    Text("Other Platforms:")
                    TestWrappedLayout(geometry: geometry)
                }
            }
        }
    }
}

struct ExampleTagsView_Previews: PreviewProvider {
    static var previews: some View {
        ExampleTagsView()
    }
}

struct TestWrappedLayout: View {
    @State var platforms = ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4", "PlayStation 5", "Ni", "Xct5Box", "PlayStatavtion", "PlvayStation 2", "PlayStatiadfon 3", "PlaySdatation 4", "PlaySdtation 5"]
    let geometry: GeometryProxy

    var body: some View {
        self.generateContent(in: geometry)
    }

    private func generateContent(in g: GeometryProxy) -> some View {
        var width = CGFloat.zero
        var height = CGFloat.zero

        return ZStack(alignment: .topLeading) {
            ForEach(self.platforms, id: \.self) { platform in
                self.item(for: platform)
                    .padding([.horizontal, .vertical], 4)
                    .alignmentGuide(.leading, computeValue: { d in
                        if (abs(width - d.width) > g.size.width)
                        {
                            width = 0
                            height -= d.height
                        }
                        let result = width
                        if platform == self.platforms.first! {
                            width = 0 //last item
                        } else {
                            width -= d.width
                        }
                        return result
                    })
                    .alignmentGuide(.top, computeValue: {d in
                        let result = height
                        if platform == self.platforms.first! {
                            height = 0 // last item
                        }
                        return result
                    })
            }
        }
    }

    func item(for text: String) -> some View {
        Text(text)
            .padding(.all, 5)
            .font(.body)
            .background(Color.blue)
            .foregroundColor(Color.white)
            .cornerRadius(5)
    }
}

</code>```

Result:

ContentLicense: CC BY-SA 4.0

Body:
I have this view to show text tags on multiple lines which I got from SwiftUI HStack with Wrap, but when I add it in a VStack the tags overlap any other view that I put below.
The tags are shown properly but the height of the view itself is not calculated inside the VStack.
How can I make this view use the height of is content?

import SwiftUI

struct TestWrappedLayout: View {
    @State var platforms = ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4"]

    var body: some View {
        GeometryReader { geometry in
            self.generateContent(in: geometry)
        }
    }

    private func generateContent(in g: GeometryProxy) -> some View {
        var width = CGFloat.zero
        var height = CGFloat.zero

        return ZStack(alignment: .topLeading) {
            ForEach(self.platforms, id: \.self) { platform in
                self.item(for: platform)
                    .padding([.horizontal, .vertical], 4)
                    .alignmentGuide(.leading, computeValue: { d in
                        if (abs(width - d.width) > g.size.width)
                        {
                            width = 0
                            height -= d.height
                        }
                        let result = width
                        if platform == self.platforms.last! {
                            width = 0 //last item
                        } else {
                            width -= d.width
                        }
                        return result
                    })
                    .alignmentGuide(.top, computeValue: {d in
                        let result = height
                        if platform == self.platforms.last! {
                            height = 0 // last item
                        }
                        return result
                    })
            }
        }
    }

    func item(for text: String) -> some View {
        Text(text)
            .padding(.all, 5)
            .font(.body)
            .background(Color.blue)
            .foregroundColor(Color.white)
            .cornerRadius(5)
    }
}

struct TestWrappedLayout_Previews: PreviewProvider {
    static var previews: some View {
        TestWrappedLayout()
    }
}

Example code:

struct ExampleTagsView: View {
    var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                Text("Platforms:")
                TestWrappedLayout()

                Text("Other Platforms:")
                TestWrappedLayout()
            }
        }
    }
}

struct ExampleTagsView_Previews: PreviewProvider {
    static var previews: some View {
        ExampleTagsView()
    }
}

Result:

Body:
I just managed to solve this by moving the GeometryReader up to the ExampleTagsView and using platforms.first instead of last inside .alignmentGuide

Full code:

import SwiftUI

struct ExampleTagsView: View {
    var body: some View {
        GeometryReader { geometry in
            ScrollView(.vertical) {
                VStack(alignment: .leading) {
                    Text("Platforms:")
                    TestWrappedLayout(geometry: geometry)

                    Text("Other Platforms:")
                    TestWrappedLayout(geometry: geometry)
                }
            }
        }
    }
}

struct ExampleTagsView_Previews: PreviewProvider {
    static var previews: some View {
        ExampleTagsView()
    }
}

struct TestWrappedLayout: View {
    @State var platforms = ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4", "PlayStation 5", "Ni", "Xct5Box", "PlayStatavtion", "PlvayStation 2", "PlayStatiadfon 3", "PlaySdatation 4", "PlaySdtation 5"]
    let geometry: GeometryProxy

    var body: some View {
        self.generateContent(in: geometry)
    }

    private func generateContent(in g: GeometryProxy) -> some View {
        var width = CGFloat.zero
        var height = CGFloat.zero

        return ZStack(alignment: .topLeading) {
            ForEach(self.platforms, id: \.self) { platform in
                self.item(for: platform)
                    .padding([.horizontal, .vertical], 4)
                    .alignmentGuide(.leading, computeValue: { d in
                        if (abs(width - d.width) > g.size.width)
                        {
                            width = 0
                            height -= d.height
                        }
                        let result = width
                        if platform == self.platforms.first! {
                            width = 0 //last item
                        } else {
                            width -= d.width
                        }
                        return result
                    })
                    .alignmentGuide(.top, computeValue: {d in
                        let result = height
                        if platform == self.platforms.first! {
                            height = 0 // last item
                        }
                        return result
                    })
            }
        }
    }

    func item(for text: String) -> some View {
        Text(text)
            .padding(.all, 5)
            .font(.body)
            .background(Color.blue)
            .foregroundColor(Color.white)
            .cornerRadius(5)
    }
}

Result:


问:
A little confused with Big O
So I have a quick question on how to verify the big O of a function.

for example: a quicksort algorithm sorting an array of 5000000 element yields a time interval of 0.008524 seconds, running the same algorithm with 1000000 element yields 0.017909.  How would I check the big O if my quicksort is/is not big O of n*log(n)??

What I think I understand: n increased by 2  thus the runtime should increase by 2*log(2)?

f(n) = 0.008524 -> n log (n)

f(2n) = 0.017909 ->2n*log(2n)

答:
There are a couple of points to keep in mind: first and foremost that as you change sizes, the hardware (at least on a typical computer) will have an effect as well. Particularly, when your data becomes to large to fit in a particular size of cache, you can expect to see a substantial jump in run-time that's completely independent of the algorithm in question.

To get a good idea of the algorithm proper, you should (probably) start by comparing to some algorithm with a really obvious complexity, but working with the same size of data. For one obvious possibility, time how long it takes to fill your array with random numbers. At least assuming a reasonably typical PRNG, that should certainly be linear.

Then time your algorithm, and see how it changes relative to the linear algorithm for the same sizes. For example, you might use some code like this:

```<code>#include <vector>
#include <algorithm>
#include <iostream>
#include <time.h>
#include <string>
#include <iomanip>

class timer {
    clock_t begin;
    std::ostream &os;
    std::string d;
public:
    timer(std::string const &delim = "\n", std::ostream &rep=std::cout)
        : os(rep), begin(clock()), d(delim)
    {}
    ~timer() { os << double(clock()-begin)/CLOCKS_PER_SEC << d; }
};

int main() {
    static const unsigned int meg = 1024 * 1024;

    std::cout << std::setw(10) << "Size" << "\tfill\tsort\n";
    for (unsigned size=10000; size <512*meg; size *= 2) {
        std::vector<int> numbers(size);
        std::cout << std::setw(10) << size << "\t";
        {
            timer fill_time("\t");
            std::fill_n(numbers.begin(), size, 0);
            for (int i=0; i<size; i++)
                numbers[i] = rand();
        }
        {
            timer sort_time;
            std::sort(numbers.begin(), numbers.end());
        }
    }
    return 0;
}
</code>```

If I graph both the time to fill and the time to sort, I get something like this:

Since our sizes are exponential, our linear algorithm shows a (roughly) exponential curve. The time to sort is obviously growing (somewhat) faster still.

Edit: In fairness, I should probably add that log(N) grows so slowly that for almost any practical amount of data, it contributes very little. For most practical purposes, you can just about treat quicksort (for example) as being linear on the size, just with a somewhat greater constant factor than filling memory. Growing the size linearly and graphing the results makes this more apparent:

If you look carefully, you can probably see the upper line showing just a slight upward curve from the "log(N)" factor. On the other hand, I'm not sure I'd have noticed any curvature at all if I hadn't already known that it should be there.

ContentLicense: CC BY-SA 3.0

Title: A little confused with Big O

Body:
There are a couple of points to keep in mind: first and foremost that as you change sizes, the hardware (at least on a typical computer) will have an effect as well. Particularly, when your data becomes to large to fit in a particular size of cache, you can expect to see a substantial jump in run-time that's completely independent of the algorithm in question.

To get a good idea of the algorithm proper, you should (probably) start by comparing to some algorithm with a really obvious complexity, but working with the same size of data. For one obvious possibility, time how long it takes to fill your array with random numbers. At least assuming a reasonably typical PRNG, that should certainly be linear.

Then time your algorithm, and see how it changes relative to the linear algorithm for the same sizes. For example, you might use some code like this:

#include <vector>
#include <algorithm>
#include <iostream>
#include <time.h>
#include <string>
#include <iomanip>

class timer {
    clock_t begin;
    std::ostream &os;
    std::string d;
public:
    timer(std::string const &delim = "\n", std::ostream &rep=std::cout)
        : os(rep), begin(clock()), d(delim)
    {}
    ~timer() { os << double(clock()-begin)/CLOCKS_PER_SEC << d; }
};

int main() {
    static const unsigned int meg = 1024 * 1024;

    std::cout << std::setw(10) << "Size" << "\tfill\tsort\n";
    for (unsigned size=10000; size <512*meg; size *= 2) {
        std::vector<int> numbers(size);
        std::cout << std::setw(10) << size << "\t";
        {
            timer fill_time("\t");
            std::fill_n(numbers.begin(), size, 0);
            for (int i=0; i<size; i++)
                numbers[i] = rand();
        }
        {
            timer sort_time;
            std::sort(numbers.begin(), numbers.end());
        }
    }
    return 0;
}

If I graph both the time to fill and the time to sort, I get something like this:

Since our sizes are exponential, our linear algorithm shows a (roughly) exponential curve. The time to sort is obviously growing (somewhat) faster still.

Edit: In fairness, I should probably add that log(N) grows so slowly that for almost any practical amount of data, it contributes very little. For most practical purposes, you can just about treat quicksort (for example) as being linear on the size, just with a somewhat greater constant factor than filling memory. Growing the size linearly and graphing the results makes this more apparent:

If you look carefully, you can probably see the upper line showing just a slight upward curve from the "log(N)" factor. On the other hand, I'm not sure I'd have noticed any curvature at all if I hadn't already known that it should be there.


问:
Does jQuery use clone in appendTo / prependTo
Hello guys I'm writing a little version of jquery(not all of that) for my website.(for shortnize my code)

i reached to prependTo and appendTo methods which raise a question for me:

Does jQuery use clone method or cloneNode method to build this functions?

Thanks....

答:
According to the appentTo() docs, it depends if you're targeting one existing element or more than one.

We can also select an element on the page and insert it into another:

```<code>$( "h2" ).appendTo( $( ".container" ) );
</code>```

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned) and a new set consisting of the inserted element is returned:

```<code><div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
  <h2>Greetings</h2>
</div>
</code>```

If there is more than one target element, however, cloned copies of the inserted element will be created for each target except the last, and that new set (the original element plus clones) is returned.

Body:
According to the appentTo() docs, it depends if you're targeting one existing element or more than one.

We can also select an element on the page and insert it into another:

$( "h2" ).appendTo( $( ".container" ) );

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned) and a new set consisting of the inserted element is returned:

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
  <h2>Greetings</h2>
</div>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target except the last, and that new set (the original element plus clones) is returned.


问:
How to use predict() function in Markov chain
I am trying to create a function sing Markov Chain to make future predictions, but it's giving me a warning message. Please help.

My R version is 3.6.1.

答:
The Problem

The issue you're having is that you're passing a vector of length > 1 to the argument t0 in rmarkovchain(), when it expects t0 to be of length exactly one. Think about your predict function:

```<code>predict <- function(initial_state, t) {
    prediction <- rmarkovchain(n = t, object = mcWeather, t0 = initial_state)[t]
    prediction
}
</code>```

When a vector of length greater than one is passed as the argument initial_state, then rmarkovchain() gets a value for t0 that is more than one element, which causes problems with markovchainSequence(), which it calls.

Why does this cause a problem? We can see from help("markovchainSequence") that it expects t0 is of length one:

Arguments

...[Some content omitted]...

t0    The initial state

(emphasis added). So, when it does some checking about the t0 value, it uses if(), which expects a logical vector of only length one. That's why when it checks

```<code>if (!(t0 %in% markovchain@states))
</code>```

if you've passed a vector of length more than one as t0, you get a warning; the if() function expects only one logical value, so it will use only the first logical value in the resulting vector. That's why you get the warning, it's also why all your predictions are the same.

The Solution

So, how do we fix it? We alter your function slightly to handle vectors of length greater than one for initial_state:

```<code>predict <- function(initial_state, t) {
    prediction <- sapply(initial_state, function(state) {
        rmarkovchain(n = t, object = mcWeather, t0 = state)[t]
    })
    return(prediction)
}
</code>```

This goes across the values passed in initial_state and predicts for them one at a time, as markovchainSequence() would expect. We can see that it works as expected:

```<code>x <- data.frame("AccountNo" = 1:5,
                "CurrentState" = c("sunny", "sunny", "rain" , "cloudy" ,"rain"),
                stringsAsFactors = FALSE)

set.seed(42)
x$Prediction3 <- predict(x$CurrentState,3)
x

  AccountNo CurrentState Prediction3
1         1        sunny       sunny
2         2        sunny       sunny
3         3         rain       sunny
4         4       cloudy        rain
5         5         rain       sunny
</code>```

Body:
The Problem

The issue you're having is that you're passing a vector of length > 1 to the argument t0 in rmarkovchain(), when it expects t0 to be of length exactly one. Think about your predict function:

predict <- function(initial_state, t) {
    prediction <- rmarkovchain(n = t, object = mcWeather, t0 = initial_state)[t]
    prediction
}

When a vector of length greater than one is passed as the argument initial_state, then rmarkovchain() gets a value for t0 that is more than one element, which causes problems with markovchainSequence(), which it calls.

Why does this cause a problem? We can see from help("markovchainSequence") that it expects t0 is of length one:

Arguments

...[Some content omitted]...

t0    The initial state

(emphasis added). So, when it does some checking about the t0 value, it uses if(), which expects a logical vector of only length one. That's why when it checks

if (!(t0 %in% markovchain@states))

if you've passed a vector of length more than one as t0, you get a warning; the if() function expects only one logical value, so it will use only the first logical value in the resulting vector. That's why you get the warning, it's also why all your predictions are the same.

The Solution

So, how do we fix it? We alter your function slightly to handle vectors of length greater than one for initial_state:

predict <- function(initial_state, t) {
    prediction <- sapply(initial_state, function(state) {
        rmarkovchain(n = t, object = mcWeather, t0 = state)[t]
    })
    return(prediction)
}

This goes across the values passed in initial_state and predicts for them one at a time, as markovchainSequence() would expect. We can see that it works as expected:

x <- data.frame("AccountNo" = 1:5,
                "CurrentState" = c("sunny", "sunny", "rain" , "cloudy" ,"rain"),
                stringsAsFactors = FALSE)

set.seed(42)
x$Prediction3 <- predict(x$CurrentState,3)
x

  AccountNo CurrentState Prediction3
1         1        sunny       sunny
2         2        sunny       sunny
3         3         rain       sunny
4         4       cloudy        rain
5         5         rain       sunny


问:
Get non-overlapping distinct intervals from a set of intervals Python
Given a set of intervals, I would like to find non-overlapping distinct intervals from a set of intervals.

For example:

Input: [[1,10], [5,20], [6,21], [17,25], [22,23], [24,50] ,[30,55], [60,70]]

Output: [[1,5], [21,22], [23,24], [25,30], [50,55], [60,70]]

How can I do that?

What I have currently tried:

```<code>gene_bounds_list = [[1,10],[5,20], [6,21],[17,25],[22,23], [24,50],[30,55],[60,70]]
overlap_list = []
nonoverlap_list = []
nonoverlap_list.append(gene_bounds_list[0])

for i in range(1, len(gene_bounds_list)):
    curr_gene_bounds = gene_bounds_list[i]
    prev_gene_bounds = nonoverlap_list[-1]

    if curr_gene_bounds[0]<prev_gene_bounds[0]:
        if curr_gene_bounds[1]<prev_gene_bounds[0]: #case1
            continue
        if curr_gene_bounds[1] < prev_gene_bounds[1]:  #case2
            nonoverlap_list[-1][0] = curr_gene_bounds[1]
        if curr_gene_bounds[1]>prev_gene_bounds[1]:
            # previous gene was completely overlapping within current gene,
            # so replace previous gene by current (bigger) gene and put previous gene into overlap list
            overlap_list.append(nonoverlap_list[-1])
            new_bound = [gene_bounds_list[i][0], gene_bounds_list[i][1]]
            nonoverlap_list.pop()
            nonoverlap_list.append([new_bound[0], new_bound[1]])

    elif curr_gene_bounds[0] > prev_gene_bounds[0] and curr_gene_bounds[1] < prev_gene_bounds[1]:
        # completely within another gene
        overlap_list.append([curr_gene_bounds[0], curr_gene_bounds[1]])

    elif curr_gene_bounds[0] < prev_gene_bounds[1]:
        # partially overlapping with another gene
        new_bound = [nonoverlap_list[-1][1], curr_gene_bounds[1]]
        nonoverlap_list[-1][1] = curr_gene_bounds[0]
        nonoverlap_list.append([new_bound[0], new_bound[1]])

    else:
        # not overlapping with another gene
        nonoverlap_list.append([gene_bounds_list[i][0], gene_bounds_list[i][1]])

unique_data = [list(x) for x in set(tuple(x) for x in gene_bounds_list)]
within_overlapping_intervals = []

for small in overlap_list:
    for master in unique_data:
        if (small[0]==master[0] and small[1]==master[1]):
            continue
        if (small[0]>master[0] and small[1]<master[1]):
            if(small not in within_overlapping_intervals):
                within_overlapping_intervals.append([small[0], small[1]])

for o in within_overlapping_intervals:
    nonoverlap_list.append(o)  # append the overlapping intervals

nonoverlap_list.sort(key=lambda tup: tup[0])
flat_data = sorted([x for sublist in nonoverlap_list for x in sublist])
new_gene_intervals = [flat_data[i:i + 2] for i in range(0, len(flat_data), 2)]
print(new_gene_intervals)
</code>```

However, this gives me an output of: [[1, 5], [6, 10], [17, 20], [21, 22], [23, 24], [25, 30], [50, 55], [60, 70]]

Any ideas of how I can remove the unwanted intervals?

答:
Plot the intervals on a timeline. As the range is just 10**5, we can use the memory. Plotting and scanning can be done in linear time.

```<code>intervals = [[1,10], [5,20], [6,21], [17,25], [22,23], [24,50] ,[30,55], [60,70]]

max_ = max(intervals, key=lambda x: x[1])[1]
timeline = [0] * (max_ + 1)

# mark plots
for start, end in intervals:
    timeline[start] += 1
    timeline[end] -= 1

# make the timeline
for i in range(1, len(timeline)):
    timeline[i] += timeline[i - 1]

# scan
result = []
for i, item in enumerate(timeline):
    if i == 0:
        continue
    prev = timeline[i - 1]
    if item == 1 and prev != 1:
        result.append([i, i + 1])
    elif item == 1 and prev == 1:
        result[-1][1] = i + 1
        end = i

print(result)
</code>```

EDIT:
As the range is updated to ~10^8, this won't work.

Body:
Given a set of intervals, I would like to find non-overlapping distinct intervals from a set of intervals.

For example:

Input: [[1,10], [5,20], [6,21], [17,25], [22,23], [24,50] ,[30,55], [60,70]]

Output: [[1,5], [21,22], [23,24], [25,30], [50,55], [60,70]]

How can I do that?

What I have currently tried:

gene_bounds_list = [[1,10],[5,20], [6,21],[17,25],[22,23], [24,50],[30,55],[60,70]]
overlap_list = []
nonoverlap_list = []
nonoverlap_list.append(gene_bounds_list[0])

for i in range(1, len(gene_bounds_list)):
    curr_gene_bounds = gene_bounds_list[i]
    prev_gene_bounds = nonoverlap_list[-1]

    if curr_gene_bounds[0]<prev_gene_bounds[0]:
        if curr_gene_bounds[1]<prev_gene_bounds[0]: #case1
            continue
        if curr_gene_bounds[1] < prev_gene_bounds[1]:  #case2
            nonoverlap_list[-1][0] = curr_gene_bounds[1]
        if curr_gene_bounds[1]>prev_gene_bounds[1]:
            # previous gene was completely overlapping within current gene,
            # so replace previous gene by current (bigger) gene and put previous gene into overlap list
            overlap_list.append(nonoverlap_list[-1])
            new_bound = [gene_bounds_list[i][0], gene_bounds_list[i][1]]
            nonoverlap_list.pop()
            nonoverlap_list.append([new_bound[0], new_bound[1]])

    elif curr_gene_bounds[0] > prev_gene_bounds[0] and curr_gene_bounds[1] < prev_gene_bounds[1]:
        # completely within another gene
        overlap_list.append([curr_gene_bounds[0], curr_gene_bounds[1]])

    elif curr_gene_bounds[0] < prev_gene_bounds[1]:
        # partially overlapping with another gene
        new_bound = [nonoverlap_list[-1][1], curr_gene_bounds[1]]
        nonoverlap_list[-1][1] = curr_gene_bounds[0]
        nonoverlap_list.append([new_bound[0], new_bound[1]])

    else:
        # not overlapping with another gene
        nonoverlap_list.append([gene_bounds_list[i][0], gene_bounds_list[i][1]])

unique_data = [list(x) for x in set(tuple(x) for x in gene_bounds_list)]
within_overlapping_intervals = []

for small in overlap_list:
    for master in unique_data:
        if (small[0]==master[0] and small[1]==master[1]):
            continue
        if (small[0]>master[0] and small[1]<master[1]):
            if(small not in within_overlapping_intervals):
                within_overlapping_intervals.append([small[0], small[1]])

for o in within_overlapping_intervals:
    nonoverlap_list.append(o)  # append the overlapping intervals

nonoverlap_list.sort(key=lambda tup: tup[0])
flat_data = sorted([x for sublist in nonoverlap_list for x in sublist])
new_gene_intervals = [flat_data[i:i + 2] for i in range(0, len(flat_data), 2)]
print(new_gene_intervals)

However, this gives me an output of: [[1, 5], [6, 10], [17, 20], [21, 22], [23, 24], [25, 30], [50, 55], [60, 70]]

Any ideas of how I can remove the unwanted intervals?

Body:
Plot the intervals on a timeline. As the range is just 10**5, we can use the memory. Plotting and scanning can be done in linear time.

intervals = [[1,10], [5,20], [6,21], [17,25], [22,23], [24,50] ,[30,55], [60,70]]

max_ = max(intervals, key=lambda x: x[1])[1]
timeline = [0] * (max_ + 1)

# mark plots
for start, end in intervals:
    timeline[start] += 1
    timeline[end] -= 1

# make the timeline
for i in range(1, len(timeline)):
    timeline[i] += timeline[i - 1]

# scan
result = []
for i, item in enumerate(timeline):
    if i == 0:
        continue
    prev = timeline[i - 1]
    if item == 1 and prev != 1:
        result.append([i, i + 1])
    elif item == 1 and prev == 1:
        result[-1][1] = i + 1
        end = i

print(result)

EDIT:
As the range is updated to ~10^8, this won't work.


答:
Ok, here is a bit more generic & improved variant (for the solution initially introduced in SwiftUI HStack with Wrap)

Tested with Xcode 11.4 / iOS 13.4

Note: as height of view is calculated dynamically the result works in run-time, not in Preview

```<code>struct TagCloudView: View {
    var tags: [String]

    @State private var totalHeight
          = CGFloat.zero       // << variant for ScrollView/List
    //    = CGFloat.infinity   // << variant for VStack

    var body: some View {
        VStack {
            GeometryReader { geometry in
                self.generateContent(in: geometry)
            }
        }
        .frame(height: totalHeight)// << variant for ScrollView/List
        //.frame(maxHeight: totalHeight) // << variant for VStack
    }

    private func generateContent(in g: GeometryProxy) -> some View {
        var width = CGFloat.zero
        var height = CGFloat.zero

        return ZStack(alignment: .topLeading) {
            ForEach(self.tags, id: \.self) { tag in
                self.item(for: tag)
                    .padding([.horizontal, .vertical], 4)
                    .alignmentGuide(.leading, computeValue: { d in
                        if (abs(width - d.width) > g.size.width)
                        {
                            width = 0
                            height -= d.height
                        }
                        let result = width
                        if tag == self.tags.last! {
                            width = 0 //last item
                        } else {
                            width -= d.width
                        }
                        return result
                    })
                    .alignmentGuide(.top, computeValue: {d in
                        let result = height
                        if tag == self.tags.last! {
                            height = 0 // last item
                        }
                        return result
                    })
            }
        }.background(viewHeightReader($totalHeight))
    }

    private func item(for text: String) -> some View {
        Text(text)
            .padding(.all, 5)
            .font(.body)
            .background(Color.blue)
            .foregroundColor(Color.white)
            .cornerRadius(5)
    }

    private func viewHeightReader(_ binding: Binding<CGFloat>) -> some View {
        return GeometryReader { geometry -> Color in
            let rect = geometry.frame(in: .local)
            DispatchQueue.main.async {
                binding.wrappedValue = rect.size.height
            }
            return .clear
        }
    }
}

struct TestTagCloudView : View {
    var body: some View {
        VStack {
            Text("Header").font(.largeTitle)
            TagCloudView(tags: ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4"])
            Text("Some other text")
            Divider()
            Text("Some other cloud")
            TagCloudView(tags: ["Apple", "Google", "Amazon", "Microsoft", "Oracle", "Facebook"])
        }
    }
}
</code>```

Title: SwiftUI HStack with wrap and dynamic height

Body:
Ok, here is a bit more generic & improved variant (for the solution initially introduced in SwiftUI HStack with Wrap)

Tested with Xcode 11.4 / iOS 13.4

Note: as height of view is calculated dynamically the result works in run-time, not in Preview

struct TagCloudView: View {
    var tags: [String]

    @State private var totalHeight
          = CGFloat.zero       // << variant for ScrollView/List
    //    = CGFloat.infinity   // << variant for VStack

    var body: some View {
        VStack {
            GeometryReader { geometry in
                self.generateContent(in: geometry)
            }
        }
        .frame(height: totalHeight)// << variant for ScrollView/List
        //.frame(maxHeight: totalHeight) // << variant for VStack
    }

    private func generateContent(in g: GeometryProxy) -> some View {
        var width = CGFloat.zero
        var height = CGFloat.zero

        return ZStack(alignment: .topLeading) {
            ForEach(self.tags, id: \.self) { tag in
                self.item(for: tag)
                    .padding([.horizontal, .vertical], 4)
                    .alignmentGuide(.leading, computeValue: { d in
                        if (abs(width - d.width) > g.size.width)
                        {
                            width = 0
                            height -= d.height
                        }
                        let result = width
                        if tag == self.tags.last! {
                            width = 0 //last item
                        } else {
                            width -= d.width
                        }
                        return result
                    })
                    .alignmentGuide(.top, computeValue: {d in
                        let result = height
                        if tag == self.tags.last! {
                            height = 0 // last item
                        }
                        return result
                    })
            }
        }.background(viewHeightReader($totalHeight))
    }

    private func item(for text: String) -> some View {
        Text(text)
            .padding(.all, 5)
            .font(.body)
            .background(Color.blue)
            .foregroundColor(Color.white)
            .cornerRadius(5)
    }

    private func viewHeightReader(_ binding: Binding<CGFloat>) -> some View {
        return GeometryReader { geometry -> Color in
            let rect = geometry.frame(in: .local)
            DispatchQueue.main.async {
                binding.wrappedValue = rect.size.height
            }
            return .clear
        }
    }
}

struct TestTagCloudView : View {
    var body: some View {
        VStack {
            Text("Header").font(.largeTitle)
            TagCloudView(tags: ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4"])
            Text("Some other text")
            Divider()
            Text("Some other cloud")
            TagCloudView(tags: ["Apple", "Google", "Amazon", "Microsoft", "Oracle", "Facebook"])
        }
    }
}


问:
Generate JSON schema
Im trying a setup a Microsoft flow. In short, I need to take JSON data retrieved from a device, and parse it so that i could reference it in the Flows below. In order to parse, i need to provide the JSON Schema to Flow. Microsoft Flow has an option to generate it from a sample payload (the results returned from the API call), but it's not generating it correctly. I'm hoping someone can help me. I need the correct JSON Schema.

The data returned from the API:

[
  null,
  [
    {
      "user_id": 2003,
      "user_label": "Test1"
    },
    {
      "user_id": 2004,
      "user_label": "Test2"
    }
  ]
]```
</div>
</div>
</p>

<p><strong>Scheme generated in Flow from the above sample payload:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{
    "type": "array",
    "items": {}
}</code>```

I then tried to generate the Schema from just the data. That seemed to work, but when the Flow runs, I get a Json validation error.

Tried generating from just the data like this:

{
      "user_id": 2003,
      "user_label": "Test1"
    }```
</div>
</div>
</p>

<p><strong>This generated the scheme like this:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{
    "type": "object",
    "properties": {
        "user_id": {
            "type": "number"
        },
        "user_label": {
            "type": "string"
        }
    }
}</code>```

答:
So you have 2 things going on, the nested object array, and the null.

You'll need another Parse JSON after the first Parse JSON.  And you'll want to filter out the null before the second Parse JSON.

It took me a while to figure out, but I hope this helps.

Start by adding the Parse JSON step to whatever step is outputting the JSON.

Now, filter the array, make sure you use the 'Expression' when comparing with null.

Add the second Parse JSON, you'll notice that you won't have the option to select the output "Item" of the Filter array step, so select 'Parse JSON' - Item  for now (we will change this to use the output of the Filter JSON step in a moment)

The step should automatically change to an 'Apply to each'.  In the Parse JSON 2, generate the schema with

```<code>[
    {
      "user_id": 2003,
      "user_label": "Test1"
    },
    {
      "user_id": 2004,
      "user_label": "Test2"
    }
  ]
</code>```

Then, modify the 'Select an output from previous steps field' and change it (from the Body of the Parse JSON step) to the Body of the Filter Array step

Finally, add an action after Parse JSON 2 and select one of the fields in Parse JSON 2, this will automatically change that step to a nested Apply to each

You should end up with something like this:

Title: Generate JSON schema

Body:
Im trying a setup a Microsoft flow. In short, I need to take JSON data retrieved from a device, and parse it so that i could reference it in the Flows below. In order to parse, i need to provide the JSON Schema to Flow. Microsoft Flow has an option to generate it from a sample payload (the results returned from the API call), but it's not generating it correctly. I'm hoping someone can help me. I need the correct JSON Schema.

The data returned from the API:

[
  null,
  [
    {
      "user_id": 2003,
      "user_label": "Test1"
    },
    {
      "user_id": 2004,
      "user_label": "Test2"
    }
  ]
]

Scheme generated in Flow from the above sample payload:

{
    "type": "array",
    "items": {}
}

I then tried to generate the Schema from just the data. That seemed to work, but when the Flow runs, I get a Json validation error.

Tried generating from just the data like this:

{
      "user_id": 2003,
      "user_label": "Test1"
    }

This generated the scheme like this:

{
    "type": "object",
    "properties": {
        "user_id": {
            "type": "number"
        },
        "user_label": {
            "type": "string"
        }
    }
}

Body:
So you have 2 things going on, the nested object array, and the null.

You'll need another Parse JSON after the first Parse JSON.  And you'll want to filter out the null before the second Parse JSON.

It took me a while to figure out, but I hope this helps.

Start by adding the Parse JSON step to whatever step is outputting the JSON.

Now, filter the array, make sure you use the 'Expression' when comparing with null.

Add the second Parse JSON, you'll notice that you won't have the option to select the output "Item" of the Filter array step, so select 'Parse JSON' - Item  for now (we will change this to use the output of the Filter JSON step in a moment)

The step should automatically change to an 'Apply to each'.  In the Parse JSON 2, generate the schema with

[
    {
      "user_id": 2003,
      "user_label": "Test1"
    },
    {
      "user_id": 2004,
      "user_label": "Test2"
    }
  ]

Then, modify the 'Select an output from previous steps field' and change it (from the Body of the Parse JSON step) to the Body of the Filter Array step

Finally, add an action after Parse JSON 2 and select one of the fields in Parse JSON 2, this will automatically change that step to a nested Apply to each

You should end up with something like this:


问:
How can I add an existing workbook sheet to another existing workbook with openpyxl?
I am trying to create an new excel that contains the first sheet of a list of excel files.

I tried the following but of course line wb.create_sheet(sheet) doesn't work.

```<code>wb = Workbook('new.xlsx')

for i in range(len(file_list)):
    excel = load_workbook(file_list[i], read_only=False)
    sheet = excel[excel.sheetnames[0]]
    sheet.Name = tab_names_list[i]

    wb.create_sheet(sheet)

wb.save('new.xlsx')
</code>```

At the same time replacing   wb.create_sheet(sheet) with wb.copy_worksheet(sheet) gives the error ValueError: Cannot copy worksheets in read-only or write-only mode

答:
This may not work for you but this is what I use in a similar application. It does require pandas dataframes, I'm not sure if you're using them or not. </p>

```<code>file_list = [file_1, file_2]
sheet_names = ['file1_name', 'file2_name']

writer = pd.ExcelWriter("workbook_name.xlsx", engine='xlsxwriter')

for file, s_names in zip(file_list, sheet_names):
    file.to_excel(writer, sheet_name=s_names)
writer.save()

</code>```

Body:
I am trying to create an new excel that contains the first sheet of a list of excel files.

I tried the following but of course line wb.create_sheet(sheet) doesn't work.

wb = Workbook('new.xlsx')

for i in range(len(file_list)):
    excel = load_workbook(file_list[i], read_only=False)
    sheet = excel[excel.sheetnames[0]]
    sheet.Name = tab_names_list[i]

    wb.create_sheet(sheet)

wb.save('new.xlsx')

At the same time replacing   wb.create_sheet(sheet) with wb.copy_worksheet(sheet) gives the error ValueError: Cannot copy worksheets in read-only or write-only mode

Body:
This may not work for you but this is what I use in a similar application. It does require pandas dataframes, I'm not sure if you're using them or not.

file_list = [file_1, file_2]
sheet_names = ['file1_name', 'file2_name']

writer = pd.ExcelWriter("workbook_name.xlsx", engine='xlsxwriter')

for file, s_names in zip(file_list, sheet_names):
    file.to_excel(writer, sheet_name=s_names)
writer.save()


问:
How to stop my Tkinter window from freezing?
Below is the main function I use in order to run two files of python but once I click on the buttuon my window freezes.Please tell me a way to perform multi threaading so that I can click both the buttons at once.</p>

```<code>import pandas as pd

import numpy as np

from tkinter import *

from tkinter.ttk import *

from tkinter import messagebox

import threading

import Test1

import Test2

# In[ ]:

def Load1():

    Test1.func()

    messagebox.showinfo( "Successful","Reconcilation Complete")

def Load2():

    Test2.func()

    try:

        messagebox.showinfo( "Successful","Reconcilation Complete")

    except Exception as inst:

        messagebox.showinfo( "Unsuccessful",inst)

root = Tk()

root.geometry('375x100')

root.title("Reco")

root.configure(background="LightBlue2")

style = Style()

style.configure('TButton', background = 'SeaGreen2', font =

               ('calibri', 20, 'bold'))

btn1 = Button(root, text = 'Tier Recon', command =threading.Thread(target=Load1).start )

btn1.grid(row = 1, column = 3, pady = 10, padx = 100)

btn2 = Button(root, text = 'View Recon', command =threading.Thread(target=Load2).start)

btn2.grid(row = 2, column = 3, pady = 10, padx = 100)

root.mainloop()
</code>```

答:
I have assumed your Test1 and Test2 functions are somewhat infinite so I have created this as the format for my Test1.py and Test2.py:

```<code># Test1.py / Test2.py
import tkinter as tk
def func():
    while True:
        root = tk.Tk()
        root.mainloop()
</code>```

Now with your code I would thoroughly recommend moving away from your current format and moving to Object Oriented Programming as it will save you many headaches in the future!

This here is the code I have written to make it work:

import tkinter as tk
import tkinter.ttk as ttk
import Test1
import Test2

class reco_win:
    def __init__(self, master):
        self.master = master
        self.master.geometry('375x100')
        self.master.configure(background="LightBlue2")
        style = ttk.Style()
        style.configure('TButton', background = 'SeaGreen2', font =
                ('calibri', 20, 'bold'))

        btn1 = ttk.Button(self.master, text = 'Tier Recon', command = lambda: self.master.after(1, self.load1))

        btn1.grid(row = 1, column = 3, pady = 10, padx = 100)

        btn2 = ttk.Button(self.master, text = 'View Recon', command =lambda: self.master.after(1, self.load1))

        btn2.grid(row = 2, column = 3, pady = 10, padx = 100)

    def load1(self):
        Test1.func()

    def load2(self):
        Test2.func()

def main():
    root = tk.Tk()
    reco_win(root)
    root.mainloop()

if __name__ == '__main__':
    main()
```

<h3>The important bit in this code:</h3>

<pre class="lang-py prettyprint-override"><code>self.master.after(1, self.load1)
</code>```

What this line of code does is after 1 millisecond it will asynchronously start a new thread and execute the function Test1.func().

This means that you don't have to worry about the issues with managing the multithreading module in python and you can instead work on writing more code!

Hope this helps,

James

P.S.

If you are using a tk.Tk() window in your Test1/Test2.py you could instead use a tk.TopLevel window which would allow you to rewrite this code to read like so:

```<code>import tkinter as tk
import tkinter.ttk as ttk
import Test1
import Test2

class reco_win:
    def __init__(self, master):
        self.master = master
        self.master.geometry('375x100')
        self.master.configure(background="LightBlue2")
        style = ttk.Style()
        style.configure('TButton', background = 'SeaGreen2', font =
                ('calibri', 20, 'bold'))

        btn1 = ttk.Button(self.master, text = 'Tier Recon', command = self.load1)

        btn1.grid(row = 1, column = 3, pady = 10, padx = 100)

        btn2 = ttk.Button(self.master, text = 'View Recon', command =self.load2)

        btn2.grid(row = 2, column = 3, pady = 10, padx = 100)

    def load1(self):
        top = tk.Toplevel()
        tk.Label(top, text="Hello").grid(row=0, column=0)

    def load2(self):
        top2 = tk.Toplevel()
        tk.Label(top2, text="Hello 2").grid(row=0, column=0)

def main():
    root = tk.Tk()
    reco_win(root)
    root.mainloop()

if __name__ == '__main__':
    main()
</code>```

Body:
Below is the main function I use in order to run two files of python but once I click on the buttuon my window freezes.Please tell me a way to perform multi threaading so that I can click both the buttons at once.

import pandas as pd

import numpy as np

from tkinter import *

from tkinter.ttk import *

from tkinter import messagebox

import threading

import Test1

import Test2

# In[ ]:

def Load1():

    Test1.func()

    messagebox.showinfo( "Successful","Reconcilation Complete")

def Load2():

    Test2.func()

    try:

        messagebox.showinfo( "Successful","Reconcilation Complete")

    except Exception as inst:

        messagebox.showinfo( "Unsuccessful",inst)

root = Tk()

root.geometry('375x100')

root.title("Reco")

root.configure(background="LightBlue2")

style = Style()

style.configure('TButton', background = 'SeaGreen2', font =

               ('calibri', 20, 'bold'))

btn1 = Button(root, text = 'Tier Recon', command =threading.Thread(target=Load1).start )

btn1.grid(row = 1, column = 3, pady = 10, padx = 100)

btn2 = Button(root, text = 'View Recon', command =threading.Thread(target=Load2).start)

btn2.grid(row = 2, column = 3, pady = 10, padx = 100)

root.mainloop()

Body:
I have assumed your Test1 and Test2 functions are somewhat infinite so I have created this as the format for my Test1.py and Test2.py:

# Test1.py / Test2.py
import tkinter as tk
def func():
    while True:
        root = tk.Tk()
        root.mainloop()

Now with your code I would thoroughly recommend moving away from your current format and moving to Object Oriented Programming as it will save you many headaches in the future!

This here is the code I have written to make it work:

import tkinter as tk
import tkinter.ttk as ttk
import Test1
import Test2

class reco_win:
    def __init__(self, master):
        self.master = master
        self.master.geometry('375x100')
        self.master.configure(background="LightBlue2")
        style = ttk.Style()
        style.configure('TButton', background = 'SeaGreen2', font =
                ('calibri', 20, 'bold'))

        btn1 = ttk.Button(self.master, text = 'Tier Recon', command = lambda: self.master.after(1, self.load1))

        btn1.grid(row = 1, column = 3, pady = 10, padx = 100)

        btn2 = ttk.Button(self.master, text = 'View Recon', command =lambda: self.master.after(1, self.load1))

        btn2.grid(row = 2, column = 3, pady = 10, padx = 100)

    def load1(self):
        Test1.func()

    def load2(self):
        Test2.func()

def main():
    root = tk.Tk()
    reco_win(root)
    root.mainloop()

if __name__ == '__main__':
    main()

The important bit in this code:

self.master.after(1, self.load1)

What this line of code does is after 1 millisecond it will asynchronously start a new thread and execute the function Test1.func().

This means that you don't have to worry about the issues with managing the multithreading module in python and you can instead work on writing more code!

Hope this helps,

James

P.S.

If you are using a tk.Tk() window in your Test1/Test2.py you could instead use a tk.TopLevel window which would allow you to rewrite this code to read like so:

import tkinter as tk
import tkinter.ttk as ttk
import Test1
import Test2

class reco_win:
    def __init__(self, master):
        self.master = master
        self.master.geometry('375x100')
        self.master.configure(background="LightBlue2")
        style = ttk.Style()
        style.configure('TButton', background = 'SeaGreen2', font =
                ('calibri', 20, 'bold'))

        btn1 = ttk.Button(self.master, text = 'Tier Recon', command = self.load1)

        btn1.grid(row = 1, column = 3, pady = 10, padx = 100)

        btn2 = ttk.Button(self.master, text = 'View Recon', command =self.load2)

        btn2.grid(row = 2, column = 3, pady = 10, padx = 100)

    def load1(self):
        top = tk.Toplevel()
        tk.Label(top, text="Hello").grid(row=0, column=0)

    def load2(self):
        top2 = tk.Toplevel()
        tk.Label(top2, text="Hello 2").grid(row=0, column=0)

def main():
    root = tk.Tk()
    reco_win(root)
    root.mainloop()

if __name__ == '__main__':
    main()


问:
Why do queries with shorter inverted lists perform better on CPU's when compared to GPU's
Moreover, why do queries with longer inverted list perform better on GPU's?

I read this result in a paper called Using Graphics Processors for High Performance IR querying.

答:
Queries with longer lists work better on GPUs, because GPUs are highly parallel, and search is a mostly parallel problem.

However, GPUs (and other massively parallel computers) don't process things the same way few-core CPUs do. Like with any other problem, there is non-negligible work to be done to set up the problem for the GPU. For small problem sizes, this overhead swamps out any speedup provided by the GPUs.


问:
is it possible to make 2 condition that you write string stament and int stagement and make an operation with them in java
I want the program that if user doesn't write any value in bookno jtexfield which is named issbook_text in my program,it would give a error message like 'no way'
I wrote those codes but normally I expected it to work like I wish but it doesn't .what is my mistake ,I could not find it for days.</p>

```<code>    public class lib {
    public lib()
    {
        gui();

    }
     int kitapno[]=new int[10];
     int kitapnoindex;
     int quantity[]=new int[10];
     int quantityindex;
     int kitapadetleri;

public void gui()
    {
  public void actionPerformed(ActionEvent e)
    {String issbookno_string=issbookno_text.getText();
    int issbookno_int=Integer.parseInt(issbookno_string);

    Date pt_issbook=new Date();
    DateFormat ptformat_issbook=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
   if(issbookno_string.equals(""))//if user don't fill out the issbook
      name
   {  JOptionPane.showMessageDialog(issbook_window,"no way");//print no
        way to display
    }
   else

   for(int i=0;i<kitapno.length;i++)
 {  if(issbookno_int==kitapno[i])
  {   row_issue[0]=kitapno[i];

   row_issue[1]=issstudentid_text.getText();

   row_issue[2]=issstudentname_text.getText();

   row_issue[3]=issstudentcontact_text.getText();

   row_issue[4]=ptformat_issbook.format(pt_issbook);

   JOptionPane.showMessageDialog(issbook_window,"You have been succesfully issued a book");

   model_issue.addRow(row_issue);
    }

                                            }
                                        }               });[enter image description here][1]
</code>```

答:
```<code>if(issbookno_string.equals(""))//if user don't fill out the issbook
      name
   {  JOptionPane.showMessageDialog(issbook_window,"no way");//print no
        way to display
    }
</code>```

I'm not sure if this is because of the formatting or not, but // is used for single line comments, which means the "name" in the "if user don't fill out the issbook name" comment and "way to display" in the "print no way to display" aren't actually being commented, as they are on separate lines from the double slash. In order to add multi line comments, you could enclose the comments with /* instead.

Body:
I want the program that if user doesn't write any value in bookno jtexfield which is named issbook_text in my program,it would give a error message like 'no way'
I wrote those codes but normally I expected it to work like I wish but it doesn't .what is my mistake ,I could not find it for days.

    public class lib {
    public lib()
    {
        gui();

    }
     int kitapno[]=new int[10];
     int kitapnoindex;
     int quantity[]=new int[10];
     int quantityindex;
     int kitapadetleri;

public void gui()
    {
  public void actionPerformed(ActionEvent e)
    {String issbookno_string=issbookno_text.getText();
    int issbookno_int=Integer.parseInt(issbookno_string);

    Date pt_issbook=new Date();
    DateFormat ptformat_issbook=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
   if(issbookno_string.equals(""))//if user don't fill out the issbook
      name
   {  JOptionPane.showMessageDialog(issbook_window,"no way");//print no
        way to display
    }
   else

   for(int i=0;i<kitapno.length;i++)
 {  if(issbookno_int==kitapno[i])
  {   row_issue[0]=kitapno[i];

   row_issue[1]=issstudentid_text.getText();

   row_issue[2]=issstudentname_text.getText();

   row_issue[3]=issstudentcontact_text.getText();

   row_issue[4]=ptformat_issbook.format(pt_issbook);

   JOptionPane.showMessageDialog(issbook_window,"You have been succesfully issued a book");

   model_issue.addRow(row_issue);
    }

                                            }
                                        }               });[enter image description here][1]

Body:
if(issbookno_string.equals(""))//if user don't fill out the issbook
      name
   {  JOptionPane.showMessageDialog(issbook_window,"no way");//print no
        way to display
    }

I'm not sure if this is because of the formatting or not, but // is used for single line comments, which means the "name" in the "if user don't fill out the issbook name" comment and "way to display" in the "print no way to display" aren't actually being commented, as they are on separate lines from the double slash. In order to add multi line comments, you could enclose the comments with /* instead.


问:
Unlimited 6 sided dice roller
Need help with a JavaScript assignment from School but don't know how I should do it and was hoping for some tips?

We're supposed to create a 6 sided dice roller program and the user will have the option to choose between how many dices should be rolled, min 1 and max 5 dices.

The sum of the amount of dices used should always be displayed on the page. But if a number 6 is thrown, then this should make the program disregard it to the sum and instead throw two new dices, there should be an error message displaying this when it happens.

When all the dices are thrown the total sum of all the dices should be displayed and how many times you threw the dices.

I've managed to create this so far but I'm not sure how I should do regarding the number 6 or even if I'm on the right path here?

JS

```<code>function rollDice() {
  var numDice = document.getElementById("diceNum").value;
  var container = document.getElementById("dieContainer");

  container.innerHTML = "";

  for (var i = 0; i < numDice; i++) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
  };

  var x, text;
  x = document.getElementById("diceNum").value;

  if (isNaN(x) || x < 1 || x > 5) {
    window.alert('Input not valid');
    document.getElementById("dieContainer").style.display = "none";
  } else {
    document.getElementById("dieContainer").style.display = "block";
  }
};
</code>```

EDIT
I updated it to this now

```<code>let diceThrows = numDice;
let sum = 0;
while(diceThrows > 0) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    if(diceRoll == 6) {
        diceThrows += 2;
        console.log("You got a 6 och two new dices were thrown");
        document.getElementById("msg").innerHTML = "You got a 6 och two new dices were thrown";
    } else {
        sum += diceRoll;
        console.log(sum);
        document.getElementById("msg").innerHTML = "Result: " + sum;
    }
    container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
    diceThrows -= 1;
}
</code>```

I managed to display the results, but wondering now if there is a way display the results without them getting reset every time you use the function?

答:
You can do something like this:

function rollDice() {
  var numDice = Number(document.getElementById("diceNum").value);
  if (isNaN(numDice) || numDice < 1 || numDice > 5) {
    window.alert('Input not valid');
    return
  }

  var container = document.getElementById("dieContainer");

  container.innerHTML = "";

  var total = 0

  for (var i = 0; i < numDice; i++) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    container.innerHTML += '
' + diceRoll + '
';
    if(diceRoll === 6) {
      //Increase the maximum by 1 (because ignore 6: -1; add two: +2)
      numDice++
      //Decrease the current by 1 (to ignore the 6)
      i--
      continue
    }
    total += diceRoll
  };
  document.getElementById("diceTotal").innerText = total
  document.getElementById("diceCount").innerText = numDice
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="diceNum">
<button onclick="rollDice()" >Roll Dice</button><br>
Total (without 6s): <span id="diceTotal" ></span><br>
Count of rolls (without 6s): <span id="diceCount" ></span><br>
<div id="dieContainer" ></div></code>```

Title: Unlimited 6 sided dice roller

Body:
Need help with a JavaScript assignment from School but don't know how I should do it and was hoping for some tips?

We're supposed to create a 6 sided dice roller program and the user will have the option to choose between how many dices should be rolled, min 1 and max 5 dices.

The sum of the amount of dices used should always be displayed on the page. But if a number 6 is thrown, then this should make the program disregard it to the sum and instead throw two new dices, there should be an error message displaying this when it happens.

When all the dices are thrown the total sum of all the dices should be displayed and how many times you threw the dices.

I've managed to create this so far but I'm not sure how I should do regarding the number 6 or even if I'm on the right path here?

JS

function rollDice() {
  var numDice = document.getElementById("diceNum").value;
  var container = document.getElementById("dieContainer");

  container.innerHTML = "";

  for (var i = 0; i < numDice; i++) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    container.innerHTML += '
' + diceRoll + '
';
  };

  var x, text;
  x = document.getElementById("diceNum").value;

  if (isNaN(x) || x < 1 || x > 5) {
    window.alert('Input not valid');
    document.getElementById("dieContainer").style.display = "none";
  } else {
    document.getElementById("dieContainer").style.display = "block";
  }
};

EDIT
I updated it to this now

let diceThrows = numDice;
let sum = 0;
while(diceThrows > 0) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    if(diceRoll == 6) {
        diceThrows += 2;
        console.log("You got a 6 och two new dices were thrown");
        document.getElementById("msg").innerHTML = "You got a 6 och two new dices were thrown";
    } else {
        sum += diceRoll;
        console.log(sum);
        document.getElementById("msg").innerHTML = "Result: " + sum;
    }
    container.innerHTML += '
' + diceRoll + '
';
    diceThrows -= 1;
}

I managed to display the results, but wondering now if there is a way display the results without them getting reset every time you use the function?

Body:
You can do something like this:

function rollDice() {
  var numDice = Number(document.getElementById("diceNum").value);
  if (isNaN(numDice) || numDice < 1 || numDice > 5) {
    window.alert('Input not valid');
    return
  }

  var container = document.getElementById("dieContainer");

  container.innerHTML = "";

  var total = 0

  for (var i = 0; i < numDice; i++) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
    if(diceRoll === 6) {
      //Increase the maximum by 1 (because ignore 6: -1; add two: +2)
      numDice++
      //Decrease the current by 1 (to ignore the 6)
      i--
      continue
    }
    total += diceRoll
  };
  document.getElementById("diceTotal").innerText = total
  document.getElementById("diceCount").innerText = numDice
}

<input type="number" id="diceNum">
<button onclick="rollDice()" >Roll Dice</button><br>
Total (without 6s): <span id="diceTotal" ></span><br>
Count of rolls (without 6s): <span id="diceCount" ></span><br>
<div id="dieContainer" ></div>


问:
How to create an empty EventHandler in C#?
I want to create an EventHandler without any methods attached to it. It's important to do it on the runtime rather than on compile time. Later on I can add the methods then invoke the event.

```<code>EventHandler eventHandler = new EventHandler(); // Compiler error

if(some_condition)
{
    eventHandler += (sender, e) =>
    {
        Console.WriteLine("some condition is true");
    };
}
else
{
    eventHandler += (sender, e) =>
    {
        Console.WriteLine("some condition is false");
    };
}

eventHandler?.Invoke(this, EventArgs.Empty);
</code>```

I'm having problems with only the first line of code. It doesn't let me create a new EventHandler with no parameters. But if I add an emtpy lambda, it does.

```<code>EventHandler eventHandler = new EventHandler((sender, e) => { });
</code>```

It looks ugly to have an empty lambda, but if I remove it, I can't compile the program. How should I initialize the eventHandler?

答:
There is no way to instanciate and empty EventHandler instance. The usual way would be to declare an event in your class like below:

```<code>class Example
{
    event EventHandler Event;

    void AddHandlerAndInvoke(bool condition)
    {
        if (condition)
        {
           Event += (s, e) => Console.WriteLine("true");
        }
        else
        {
            Event += (s, e) => Console.WriteLine("true");
        }

        Event?.Invoke(this, EventArgs.Empty);
    }
}
</code>```

This will create an event than can be will call (be handled by) EventHandler instances.

Body:
I want to create an EventHandler without any methods attached to it. It's important to do it on the runtime rather than on compile time. Later on I can add the methods then invoke the event.

EventHandler eventHandler = new EventHandler(); // Compiler error

if(some_condition)
{
    eventHandler += (sender, e) =>
    {
        Console.WriteLine("some condition is true");
    };
}
else
{
    eventHandler += (sender, e) =>
    {
        Console.WriteLine("some condition is false");
    };
}

eventHandler?.Invoke(this, EventArgs.Empty);

I'm having problems with only the first line of code. It doesn't let me create a new EventHandler with no parameters. But if I add an emtpy lambda, it does.

EventHandler eventHandler = new EventHandler((sender, e) => { });

It looks ugly to have an empty lambda, but if I remove it, I can't compile the program. How should I initialize the eventHandler?

Body:
There is no way to instanciate and empty EventHandler instance. The usual way would be to declare an event in your class like below:

class Example
{
    event EventHandler Event;

    void AddHandlerAndInvoke(bool condition)
    {
        if (condition)
        {
           Event += (s, e) => Console.WriteLine("true");
        }
        else
        {
            Event += (s, e) => Console.WriteLine("true");
        }

        Event?.Invoke(this, EventArgs.Empty);
    }
}

This will create an event than can be will call (be handled by) EventHandler instances.


答:
As per @Andreas comment below, it appears as though the domManip method can clone nodes if the correct conditions are met.
https://github.com/jquery/jquery/blob/master/src/manipulation.js#L310

```<code>    append: function() {
        return domManip( this, arguments, function( elem ) {
            if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
                var target = manipulationTarget( this, elem );
                target.appendChild( elem );
            }
        } );
    },
</code>```

Title: Does jQuery use clone in appendTo / prependTo

Body:
Hello guys I'm writing a little version of jquery(not all of that) for my website.(for shortnize my code)

i reached to prependTo and appendTo methods which raise a question for me:

Does jQuery use clone method or cloneNode method to build this functions?

Thanks....

Body:
As per @Andreas comment below, it appears as though the domManip method can clone nodes if the correct conditions are met.
https://github.com/jquery/jquery/blob/master/src/manipulation.js#L310

    append: function() {
        return domManip( this, arguments, function( elem ) {
            if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
                var target = manipulationTarget( this, elem );
                target.appendChild( elem );
            }
        } );
    },


问:
Getting java.io.EOFException while reading a SQLite file from temp directory
I am seeing an EOFException exception while reading a SQLite file from temp directory. Following is the code for reading the file. And also the exception is not seen always. Consider out of 50K files it is coming for 3 to 4 times.

```<code>public static byte[] decompressLzmaStream(InputStream inputStream, int size)
    throws CompressorException, IOException {

    if(size < 1) {
        size = 1024 * 100;
    }

    try(LZMACompressorInputStream lzmaInputStream =
                                           new LZMACompressorInputStream(inputStream);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(size)) {
        byte[] buffer = new byte[size];

        int length;
        while (-1 != (length = lzmaInputStream.read(buffer))) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        byteArrayOutputStream.flush();
        return byteArrayOutputStream.toByteArray();
    }
}
</code>```

I am using the following dependency for the decompression

```<code> <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.20</version>
</dependency>
</code>```

The exception is thrown at  while (-1 != (length = lzmaInputStream.read(buffer))) { line. Following is the exception.

```<code>java.io.EOFException: null at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:290)
at org.tukaani.xz.rangecoder.RangeDecoderFromStream.normalize(Unknown Source)
at org.tukaani.xz.rangecoder.RangeDecoder.decodeBit(Unknown Source)
at org.tukaani.xz.lzma.LZMADecoder.decode(Unknown Source)
at org.tukaani.xz.LZMAInputStream.read(Unknown Source)
at org.apache.commons.compress.compressors.lzma.
    LZMACompressorInputStream.read(LZMACompressorInputStream.java:62)
at java.io.InputStream.read(InputStream.java:101)
</code>```

Anyone have any idea about the following constructor of commons-compress.

```<code>// I am using this constructor of LZMACompressorInputStream

public LZMACompressorInputStream(InputStream inputStream) throws IOException {
    this.in = new LZMAInputStream(this.countingStream = new CountingInputStream(inputStream), -1);
}

// This is added in later version of commons-compress, what is memoryLimitInKb
public LZMACompressorInputStream(InputStream inputStream, int memoryLimitInKb) throws IOException {
    try {
        this.in = new LZMAInputStream(this.countingStream = new CountingInputStream(inputStream), memoryLimitInKb);
    } catch (MemoryLimitException var4) {
        throw new org.apache.commons.compress.MemoryLimitException((long)var4.getMemoryNeeded(), var4.getMemoryLimit(), var4);
    }
}
</code>```

As I read for LZMA streams we need to pass the uncompressed size to the constructor here --> https://issues.apache.org/jira/browse/COMPRESS-286?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel&focusedCommentId=14109417#comment-14109417

答:
An LZMA decoder needs to know when the compressed stream ends. If uncompressed size was known during compression, the header of the stream (located at the beginning of the stream)
will contain the uncompressed size. When the output of the decoder reaches this size, the decoder knows that the
end of the stream is reached. If uncompressed size was not kown during compression, the header will
not contain the size. In this case the encoder assumes that the stream is explicitely terminated with an
end of stream marker.

Since LZMA streams are also used in container formats like 7z and xz, the LZMAOutputStream
and LZMAInputStream classes also provide contructors for reading/writing streams without an header.

COMPRESS-286 is about decompressing a 7z archive that contains an entry with LZMA compression. A 7z archive contains LZMA streams without an header. The information that is usually stored in the header of the LZMA is stored separated from the stream.
Apache commons SevenZFile class for reading 7z archives creates LZMAInputStream objects with the following constructor:

```<code>LZMAInputStream(InputStream in, long uncompSize, byte propsByte, int dictSize)
</code>```

The additional parameters of the constructor represent the information that is usually stored in the header at the beginning of the LZMA stream. The fix of COMPRESS-286 ensured that also the uncompressed size (was missing before) is handed over to the LZMAInputStream.

LZMACompressorInputStream makes also use of LZMAInputStream but it assumes that the compressed stream contains an explicit header. Therefore it is not possible to hand over the information through it's constructor.

The memoryLimitInKb parameter only limits the memory that is used for decompression and has nothing to do with uncompressed size. Main contributor to required memory is the selected size of the dictionary. This size is specified during compression and is also stored in the header of the stream. Its maximum value is 4 GB. Usually the size of the dictionary is smaller than the uncompressed size. A dictionary greater than the uncompressed size is an absolute waste of memory. A corrupted LZMA header can easily lead to an OOM error and a manipulated stream even opens the doors for a denial of service attacks. Therefore it is wise to limit maximum memory usage when you read an unverified LZMA stream.

To sum it up: Since you do not read a 7z archive with an LZMA compressed entry, COMPRESS-286 has nothing to do with your issue. But the similar stacktrace may be an indicator that something is wrong with the headers of your stream.

Ensure that data is compressed with an instance of LZACompressorOutputStream(automatically selects
dictionary size, all other parameters and ensures that a header is written). If you should use  LZAOutputStream directly, make sure that you use an instance that actually writes a header.

Body:
I am seeing an EOFException exception while reading a SQLite file from temp directory. Following is the code for reading the file. And also the exception is not seen always. Consider out of 50K files it is coming for 3 to 4 times.

public static byte[] decompressLzmaStream(InputStream inputStream, int size)
    throws CompressorException, IOException {

    if(size < 1) {
        size = 1024 * 100;
    }

    try(LZMACompressorInputStream lzmaInputStream =
                                           new LZMACompressorInputStream(inputStream);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(size)) {
        byte[] buffer = new byte[size];

        int length;
        while (-1 != (length = lzmaInputStream.read(buffer))) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        byteArrayOutputStream.flush();
        return byteArrayOutputStream.toByteArray();
    }
}

I am using the following dependency for the decompression

 <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.20</version>
</dependency>

The exception is thrown at  while (-1 != (length = lzmaInputStream.read(buffer))) { line. Following is the exception.

java.io.EOFException: null at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:290)
at org.tukaani.xz.rangecoder.RangeDecoderFromStream.normalize(Unknown Source)
at org.tukaani.xz.rangecoder.RangeDecoder.decodeBit(Unknown Source)
at org.tukaani.xz.lzma.LZMADecoder.decode(Unknown Source)
at org.tukaani.xz.LZMAInputStream.read(Unknown Source)
at org.apache.commons.compress.compressors.lzma.
    LZMACompressorInputStream.read(LZMACompressorInputStream.java:62)
at java.io.InputStream.read(InputStream.java:101)

Anyone have any idea about the following constructor of commons-compress.

// I am using this constructor of LZMACompressorInputStream

public LZMACompressorInputStream(InputStream inputStream) throws IOException {
    this.in = new LZMAInputStream(this.countingStream = new CountingInputStream(inputStream), -1);
}

// This is added in later version of commons-compress, what is memoryLimitInKb
public LZMACompressorInputStream(InputStream inputStream, int memoryLimitInKb) throws IOException {
    try {
        this.in = new LZMAInputStream(this.countingStream = new CountingInputStream(inputStream), memoryLimitInKb);
    } catch (MemoryLimitException var4) {
        throw new org.apache.commons.compress.MemoryLimitException((long)var4.getMemoryNeeded(), var4.getMemoryLimit(), var4);
    }
}

As I read for LZMA streams we need to pass the uncompressed size to the constructor here --> https://issues.apache.org/jira/browse/COMPRESS-286?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel&focusedCommentId=14109417#comment-14109417

Body:
An LZMA decoder needs to know when the compressed stream ends. If uncompressed size was known during compression, the header of the stream (located at the beginning of the stream)
will contain the uncompressed size. When the output of the decoder reaches this size, the decoder knows that the
end of the stream is reached. If uncompressed size was not kown during compression, the header will
not contain the size. In this case the encoder assumes that the stream is explicitely terminated with an
end of stream marker.

Since LZMA streams are also used in container formats like 7z and xz, the LZMAOutputStream
and LZMAInputStream classes also provide contructors for reading/writing streams without an header.

COMPRESS-286 is about decompressing a 7z archive that contains an entry with LZMA compression. A 7z archive contains LZMA streams without an header. The information that is usually stored in the header of the LZMA is stored separated from the stream.
Apache commons SevenZFile class for reading 7z archives creates LZMAInputStream objects with the following constructor:

LZMAInputStream(InputStream in, long uncompSize, byte propsByte, int dictSize)

The additional parameters of the constructor represent the information that is usually stored in the header at the beginning of the LZMA stream. The fix of COMPRESS-286 ensured that also the uncompressed size (was missing before) is handed over to the LZMAInputStream.

LZMACompressorInputStream makes also use of LZMAInputStream but it assumes that the compressed stream contains an explicit header. Therefore it is not possible to hand over the information through it's constructor.

The memoryLimitInKb parameter only limits the memory that is used for decompression and has nothing to do with uncompressed size. Main contributor to required memory is the selected size of the dictionary. This size is specified during compression and is also stored in the header of the stream. Its maximum value is 4 GB. Usually the size of the dictionary is smaller than the uncompressed size. A dictionary greater than the uncompressed size is an absolute waste of memory. A corrupted LZMA header can easily lead to an OOM error and a manipulated stream even opens the doors for a denial of service attacks. Therefore it is wise to limit maximum memory usage when you read an unverified LZMA stream.

To sum it up: Since you do not read a 7z archive with an LZMA compressed entry, COMPRESS-286 has nothing to do with your issue. But the similar stacktrace may be an indicator that something is wrong with the headers of your stream.

Ensure that data is compressed with an instance of LZACompressorOutputStream(automatically selects
dictionary size, all other parameters and ensures that a header is written). If you should use  LZAOutputStream directly, make sure that you use an instance that actually writes a header.


问:
Which way of iterating array and changing element by map is more efficient?
I have a question about map.As you know by using map we can iterate arrays and able to change the element of arrays.To do that there are two ways and I listed them below.Which way has less complexity and more performance?(In the examples arrays are not big but think about the real world like 500 elements in an array)

```<code>var numbers = [4, 9, 16, 25];
numbers=numbers.map(e=>{
 return e=e*2;
})
</code>```

In this approach assigning each returned value to current array.

```<code>numbers.map((e,a)=>{
  numbers[a]=e*2;
})
</code>```

In this one on each iteration we need to go to array by index to find element and I think this is worse than above but Im not sure.

答:
The fastest way to change a value of an array is to iterate the index and update the item.

This approach is faset than forEach or map, because it does not have the overhead of this and it does not need the feature of the supplied structure of the callback.

var numbers = [4, 9, 16, 25];

for (let i = 0; i < numbers.length; i++) numbers[i] *= 2;

console.log(numbers);```

Body:
I have a question about map.As you know by using map we can iterate arrays and able to change the element of arrays.To do that there are two ways and I listed them below.Which way has less complexity and more performance?(In the examples arrays are not big but think about the real world like 500 elements in an array)

var numbers = [4, 9, 16, 25];
numbers=numbers.map(e=>{
 return e=e*2;
})

In this approach assigning each returned value to current array.

numbers.map((e,a)=>{
  numbers[a]=e*2;
})

In this one on each iteration we need to go to array by index to find element and I think this is worse than above but Im not sure.


问:
Jquery $(this) node and its use
I am trying to understand some jquery code that uses a $(this) node.  What is it used for and when can it be used?

```<code>$("li").hover(border, noBorder);
function border()
{
    $(this).css("border", "1px solid black");
}
</code>```

答:
this is used to access the current iterated value on a loop
For example you have a table with 'n' rows ,the following code will alert each row content using this</p>

```<code>$(document).ready(function(){
    $('table#tableid tr').each(function(){

    alert($(this).html());

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

Title: Jquery $(this) node and its use

Body:
I am trying to understand some jquery code that uses a $(this) node.  What is it used for and when can it be used?

$("li").hover(border, noBorder);
function border()
{
    $(this).css("border", "1px solid black");
}

Body:
this is used to access the current iterated value on a loop
For example you have a table with 'n' rows ,the following code will alert each row content using this

$(document).ready(function(){
    $('table#tableid tr').each(function(){

    alert($(this).html());

    });
});