问:
Adding elements to an ArrayList and if the element have the same value in the ArrayList, it can't be added
I am developing a search system. I have this problem with same Coordinate getting add more than once into the search queue. I've add some if statements to filter out these problem but it still occur and I have no idea why. I've not found a way to use LinkedHashSet because I tried to add new object into the list.

```<code>    package pathFinding;

    import java.util.ArrayList;
    import java.util.LinkedHashSet;

    public class SearchOld {
    public static Boolean pathFind(Coord start, Coord end /*, ArraList<Coord> blocked*/){

        boolean arrive = false;
        boolean way = false;

        ArrayList<Node> openList = new ArrayList<Node>();
        ArrayList<Node> closedList = new ArrayList<Node>();
        ArrayList<Node> adjNode = new ArrayList<Node>();
        ArrayList<Coord> emptyList = new ArrayList<Coord>();

        int num = 0;
        Node startNode = new Node(start, start);
        closedList.add(startNode);
        openList.add(startNode);
        System.out.println(openList.get(0).getCoord().getX() + " " + openList.get(0).getCoord().getY());
        a:{while(!arrive){
            all:{for(int i = 0;i<openList.size();i++){
                if(end.getX() == openList.get(i).getCoord().getX() && end.getY() == openList.get(i).getCoord().getY()){
                    arrive = true;
                    break all;
            }
            adjNode.addAll(Adjacent.findAdjacent(openList.get(0).getCoord()));
                for(int j=0;j<adjNode.size();j++){
                    check:{for(int k = 0;k<openList.size();k++){
                        if(adjNode.get(0).getCoord().getX() == openList.get(k).getCoord().getX() && adjNode.get(0).getCoord().getY() == openList.get(k).getCoord().getY()){
                            adjNode.remove(0);
                            System.err.println("X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                            arrive = true;
                            break check;
                        }else{
                            for(int l = 0;l<closedList.size();l++){
                                if(adjNode.get(0).getCoord().getX() == closedList.get(l).getCoord().getX() && adjNode.get(0).getCoord().getY() == closedList.get(l).getCoord().getY()){
                                    /*if(end.getX() == adjNode.get(0).getCoord().getX() && end.getY() == adjNode.get(0).getCoord().getY()){
                                        openList.add(adjNode.get(0));
                                        closedList.add(adjNode.get(0));
                                        break all;
                                }*/
                                    adjNode.remove(0);
                                    break check;
                                }else{
                                    openList.add(adjNode.get(0));
                                    adjNode.remove(0);
                                    break check;
                                }
                            }
                        }
                    }}
                }
            closedList.add(openList.get(0));
            openList.remove(0);
            LinkedHashSet<Node> tempSet = new LinkedHashSet<Node>();
            tempSet.addAll(closedList);
            closedList.clear();
            closedList.addAll(tempSet);
        };}

    };}

        //Coordinate got add many times
        for(int m = 0;m<closedList.size();m++){
            if(closedList.get(m).getCoord().getX() != closedList.get(m).getParent().getX() || closedList.get(m).getCoord().getY() != closedList.get(m).getParent().getY()){
            System.out.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());
        }else{
            System.err.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());

            }
        };
        System.out.println(closedList.size());
        System.out.println(arrive);
        //return closedList;
        return arrive;
    }
}
</code>```

Class Adjacent.java

```<code>public static ArrayList<Node> findAdjacent(Coord coord){
    ArrayList<Node> adj = new ArrayList<Node>();

    if(coord.getX() > 1){
        Node left = new Node(new Coord(coord.getX()-1, coord.getY()), coord);
        adj.add(left);
    }
    if(coord.getX() < 25){
        Node right = new Node(new Coord(coord.getX()+1, coord.getY()), coord);
        adj.add(right);
    }
    if(coord.getY() > 1){
        Node up = new Node(new Coord(coord.getX(), coord.getY()-1), coord);
        adj.add(up);
    }
    if(coord.getY() < 25){
        Node down = new Node(new Coord(coord.getX(), coord.getY()+1), coord);
        adj.add(down);
    }
    return adj;

}
</code>```

The ones in comments mean that I will add later when this problem is fixed. Thanks for helping.

[EDIT]

I've now tried @Dhiraj suggestion on changing the comparing method for comparing Coordinates. But the result is still the same, coordinates getting add to the search queue more than once. I've also clean up the code a bit.

Class Search.java:

```<code>package pathFinding;

import java.util.ArrayList;
import java.util.LinkedHashSet;

public class Search {
public static Boolean pathFind(Coord start, Coord end /*, ArraList<Coord> blocked*/){

        boolean arrive = false;
        boolean way = false;

        ArrayList<Node> openList = new ArrayList<Node>();
        ArrayList<Node> closedList = new ArrayList<Node>();
        ArrayList<Node> adjNode = new ArrayList<Node>();
        ArrayList<Coord> emptyList = new ArrayList<Coord>();

        int num = 0;
        Node startNode = new Node(start, start);
        closedList.add(startNode);
        openList.add(startNode);
        System.out.println(openList.get(0).getCoord().getX() + " " + openList.get(0).getCoord().getY());
        a:{while(arrive == false){
            if(CheckList.checkCoordInNodeArray(openList, end) || CheckList.checkCoordInNodeArray(closedList, end)){
                arrive = true;
                break;
            }
            all:{for(int i = 0;i<openList.size();i++){
                adjNode.addAll(Adjacent.findAdjacent(openList.get(0).getCoord()));
                for(int j=0;j<adjNode.size();j++){
                    if(CheckList.checkCoordInNodeArray(adjNode, end)){
                        arrive = true;
                        break all;
                    }
                    if(CheckList.checkCoordInNodeArray(openList, adjNode.get(0).getCoord()) == false || CheckList.checkCoordInNodeArray(closedList, adjNode.get(0).getCoord()) == false){
                        System.out.println("o " + CheckList.checkCoordInNodeArray(openList, adjNode.get(0).getCoord()) + " X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                        System.out.println("c " + CheckList.checkCoordInNodeArray(closedList, adjNode.get(0).getCoord())+ " X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                        openList.add(adjNode.get(0));
                        adjNode.remove(0);
                        break;
                    }else{

                        adjNode.remove(0);
                        break;
                    }
                }
                closedList.add(openList.get(0));
                openList.remove(0);
                LinkedHashSet<Node> tempSet = new LinkedHashSet<Node>();
                tempSet.addAll(closedList);
                closedList.clear();
                closedList.addAll(tempSet);
            };}

        };}

        //Coordinate got add many times
        System.out.println("CSIZE" + closedList.size());
        for(int m = 0;m<closedList.size();m++){
            if(closedList.get(m).getCoord().getX() != closedList.get(m).getParent().getX() || closedList.get(m).getCoord().getY() != closedList.get(m).getParent().getY()){
                System.out.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());
            }else{
                System.err.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());

            }
        };
        System.out.println(closedList.size());
        System.out.println(arrive);
        //return closedList;
        return arrive;
    }
}
</code>```

[EDIT2]
Here's my CheckList.java

```<code>package pathFinding;

import java.util.ArrayList;

public class CheckList {

    public static boolean checkNodeArray(ArrayList<Node> ar, Node no){
        boolean ava = true;
        for(Node node : ar){
            if(no.equals(node.getCoord())){
                ava  = true;
            }else{
                ava = false;
            }
        }
        return ava;
    }

    public static boolean checkCoordInNodeArray(ArrayList<Node> ar, Coord Coor){
        boolean ava = true;
        for(Node node : ar){
            if(Node.compareNodeCoord(Coor, node)){
                ava  = true;
            }else{
                ava = false;
            }
        }
        return ava;
    }

    public static Coord findCoordInNodeArray(ArrayList<Node> ar, Coord Coor){
        Coord coor = Coor;
        for(Node node : ar){
            if(Node.compareNodeCoord(Coor, node) == true){
                coor = node.getParent();
                break;
            }else{

            }
        }
        if(coor == Coor){
            System.err.println("NotFound");
        }
        return coor;
    }
}
</code>```

And here are my compareNodeCoord()

```<code>public static boolean compareNodeCoord(Node node1, Node node2){
        boolean equal = false;
        if(node1.equals(node2.getCoord())){
            equal = true;
        }else{
            equal = false;
        }
        return equal;
    }
    public static boolean compareNodeCoord(Coord coor1, Node node2){
        boolean equal = false;
        if(coor1.equals(node2.getCoord())){
            equal = true;
        }else{
            equal = false;
        }
        return equal;
    }
</code>```

This problem isn't very big a first but when I start to increase the size of the block traveled, the program will be stuck in an very very long loop.

Sorry if this looks messy. I am very new here and also very new to programming using Java.

答: Use a Set instead of a List. No if's will be needed anymore. And on your own objects make sure they have their own hashCode and equals methods.</p>

Body:
I am developing a search system. I have this problem with same Coordinate getting add more than once into the search queue. I've add some if statements to filter out these problem but it still occur and I have no idea why. I've not found a way to use LinkedHashSet because I tried to add new object into the list.

    package pathFinding;

    import java.util.ArrayList;
    import java.util.LinkedHashSet;

    public class SearchOld {
    public static Boolean pathFind(Coord start, Coord end /*, ArraList<Coord> blocked*/){

        boolean arrive = false;
        boolean way = false;

        ArrayList<Node> openList = new ArrayList<Node>();
        ArrayList<Node> closedList = new ArrayList<Node>();
        ArrayList<Node> adjNode = new ArrayList<Node>();
        ArrayList<Coord> emptyList = new ArrayList<Coord>();

        int num = 0;
        Node startNode = new Node(start, start);
        closedList.add(startNode);
        openList.add(startNode);
        System.out.println(openList.get(0).getCoord().getX() + " " + openList.get(0).getCoord().getY());
        a:{while(!arrive){
            all:{for(int i = 0;i<openList.size();i++){
                if(end.getX() == openList.get(i).getCoord().getX() && end.getY() == openList.get(i).getCoord().getY()){
                    arrive = true;
                    break all;
            }
            adjNode.addAll(Adjacent.findAdjacent(openList.get(0).getCoord()));
                for(int j=0;j<adjNode.size();j++){
                    check:{for(int k = 0;k<openList.size();k++){
                        if(adjNode.get(0).getCoord().getX() == openList.get(k).getCoord().getX() && adjNode.get(0).getCoord().getY() == openList.get(k).getCoord().getY()){
                            adjNode.remove(0);
                            System.err.println("X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                            arrive = true;
                            break check;
                        }else{
                            for(int l = 0;l<closedList.size();l++){
                                if(adjNode.get(0).getCoord().getX() == closedList.get(l).getCoord().getX() && adjNode.get(0).getCoord().getY() == closedList.get(l).getCoord().getY()){
                                    /*if(end.getX() == adjNode.get(0).getCoord().getX() && end.getY() == adjNode.get(0).getCoord().getY()){
                                        openList.add(adjNode.get(0));
                                        closedList.add(adjNode.get(0));
                                        break all;
                                }*/
                                    adjNode.remove(0);
                                    break check;
                                }else{
                                    openList.add(adjNode.get(0));
                                    adjNode.remove(0);
                                    break check;
                                }
                            }
                        }
                    }}
                }
            closedList.add(openList.get(0));
            openList.remove(0);
            LinkedHashSet<Node> tempSet = new LinkedHashSet<Node>();
            tempSet.addAll(closedList);
            closedList.clear();
            closedList.addAll(tempSet);
        };}

    };}

        //Coordinate got add many times
        for(int m = 0;m<closedList.size();m++){
            if(closedList.get(m).getCoord().getX() != closedList.get(m).getParent().getX() || closedList.get(m).getCoord().getY() != closedList.get(m).getParent().getY()){
            System.out.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());
        }else{
            System.err.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());

            }
        };
        System.out.println(closedList.size());
        System.out.println(arrive);
        //return closedList;
        return arrive;
    }
}

Class Adjacent.java

public static ArrayList<Node> findAdjacent(Coord coord){
    ArrayList<Node> adj = new ArrayList<Node>();

    if(coord.getX() > 1){
        Node left = new Node(new Coord(coord.getX()-1, coord.getY()), coord);
        adj.add(left);
    }
    if(coord.getX() < 25){
        Node right = new Node(new Coord(coord.getX()+1, coord.getY()), coord);
        adj.add(right);
    }
    if(coord.getY() > 1){
        Node up = new Node(new Coord(coord.getX(), coord.getY()-1), coord);
        adj.add(up);
    }
    if(coord.getY() < 25){
        Node down = new Node(new Coord(coord.getX(), coord.getY()+1), coord);
        adj.add(down);
    }
    return adj;

}

The ones in comments mean that I will add later when this problem is fixed. Thanks for helping.

[EDIT]

I've now tried @Dhiraj suggestion on changing the comparing method for comparing Coordinates. But the result is still the same, coordinates getting add to the search queue more than once. I've also clean up the code a bit.

Class Search.java:

package pathFinding;

import java.util.ArrayList;
import java.util.LinkedHashSet;

public class Search {
public static Boolean pathFind(Coord start, Coord end /*, ArraList<Coord> blocked*/){

        boolean arrive = false;
        boolean way = false;

        ArrayList<Node> openList = new ArrayList<Node>();
        ArrayList<Node> closedList = new ArrayList<Node>();
        ArrayList<Node> adjNode = new ArrayList<Node>();
        ArrayList<Coord> emptyList = new ArrayList<Coord>();

        int num = 0;
        Node startNode = new Node(start, start);
        closedList.add(startNode);
        openList.add(startNode);
        System.out.println(openList.get(0).getCoord().getX() + " " + openList.get(0).getCoord().getY());
        a:{while(arrive == false){
            if(CheckList.checkCoordInNodeArray(openList, end) || CheckList.checkCoordInNodeArray(closedList, end)){
                arrive = true;
                break;
            }
            all:{for(int i = 0;i<openList.size();i++){
                adjNode.addAll(Adjacent.findAdjacent(openList.get(0).getCoord()));
                for(int j=0;j<adjNode.size();j++){
                    if(CheckList.checkCoordInNodeArray(adjNode, end)){
                        arrive = true;
                        break all;
                    }
                    if(CheckList.checkCoordInNodeArray(openList, adjNode.get(0).getCoord()) == false || CheckList.checkCoordInNodeArray(closedList, adjNode.get(0).getCoord()) == false){
                        System.out.println("o " + CheckList.checkCoordInNodeArray(openList, adjNode.get(0).getCoord()) + " X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                        System.out.println("c " + CheckList.checkCoordInNodeArray(closedList, adjNode.get(0).getCoord())+ " X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                        openList.add(adjNode.get(0));
                        adjNode.remove(0);
                        break;
                    }else{

                        adjNode.remove(0);
                        break;
                    }
                }
                closedList.add(openList.get(0));
                openList.remove(0);
                LinkedHashSet<Node> tempSet = new LinkedHashSet<Node>();
                tempSet.addAll(closedList);
                closedList.clear();
                closedList.addAll(tempSet);
            };}

        };}

        //Coordinate got add many times
        System.out.println("CSIZE" + closedList.size());
        for(int m = 0;m<closedList.size();m++){
            if(closedList.get(m).getCoord().getX() != closedList.get(m).getParent().getX() || closedList.get(m).getCoord().getY() != closedList.get(m).getParent().getY()){
                System.out.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());
            }else{
                System.err.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());

            }
        };
        System.out.println(closedList.size());
        System.out.println(arrive);
        //return closedList;
        return arrive;
    }
}

[EDIT2]
Here's my CheckList.java

package pathFinding;

import java.util.ArrayList;

public class CheckList {

    public static boolean checkNodeArray(ArrayList<Node> ar, Node no){
        boolean ava = true;
        for(Node node : ar){
            if(no.equals(node.getCoord())){
                ava  = true;
            }else{
                ava = false;
            }
        }
        return ava;
    }

    public static boolean checkCoordInNodeArray(ArrayList<Node> ar, Coord Coor){
        boolean ava = true;
        for(Node node : ar){
            if(Node.compareNodeCoord(Coor, node)){
                ava  = true;
            }else{
                ava = false;
            }
        }
        return ava;
    }

    public static Coord findCoordInNodeArray(ArrayList<Node> ar, Coord Coor){
        Coord coor = Coor;
        for(Node node : ar){
            if(Node.compareNodeCoord(Coor, node) == true){
                coor = node.getParent();
                break;
            }else{

            }
        }
        if(coor == Coor){
            System.err.println("NotFound");
        }
        return coor;
    }
}

And here are my compareNodeCoord()

public static boolean compareNodeCoord(Node node1, Node node2){
        boolean equal = false;
        if(node1.equals(node2.getCoord())){
            equal = true;
        }else{
            equal = false;
        }
        return equal;
    }
    public static boolean compareNodeCoord(Coord coor1, Node node2){
        boolean equal = false;
        if(coor1.equals(node2.getCoord())){
            equal = true;
        }else{
            equal = false;
        }
        return equal;
    }

This problem isn't very big a first but when I start to increase the size of the block traveled, the program will be stuck in an very very long loop.

Sorry if this looks messy. I am very new here and also very new to programming using Java.


来源: stackexchange

问:
Byte Array to 2D array
What My code does . is take a snapshot of the map convert it to gray (opencv) and then make it to byte array.
Now what I dont know how to start doing is making this Bytearray to a 2D Array,

here is a block of the code.

```<code>                    Date now = new Date();
                    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss",now);
                    try {
                        StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
                        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old)
                                .permitDiskWrites()
                                .build());
                        String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
                        File imageFile = new File(mPath);
                        FileOutputStream out = new FileOutputStream(imageFile);
                        bitmap.compress(Bitmap.CompressFormat.PNG,90,out);
                        Log.d("Image:","Saved Snashot. Starting covertion");
                        //show snapshot in imageview
                        ImageView imgview = (ImageView) findViewById(R.id.imageView);
                        Bitmap smyBitmap = BitmapFactory.decodeFile(mPath);
                        Bitmap myBitmap = BitmapFactory.decodeFile(mPath);
                        imgview.setImageBitmap(smyBitmap);
                        Mat mat = new Mat(myBitmap.getHeight(),myBitmap.getWidth(),CvType.CV_8UC3);
                        Mat mat1 = new Mat(myBitmap.getHeight(),myBitmap.getWidth(),CvType.CV_8UC1);
                        Imgproc.cvtColor(mat,mat1,Imgproc.COLOR_BGR2GRAY);
                        ImageView imgview2 = (ImageView) findViewById(R.id.imageView2);
                            Mat tmp = new Mat (myBitmap.getWidth(), myBitmap.getHeight(), CvType.CV_8UC1);
                            Utils.bitmapToMat(myBitmap, tmp);
                            Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_RGB2GRAY);
                            Utils.matToBitmap(tmp, myBitmap);
                          //  Utils.matToBitmap(mat1,img);
                        String mPathgray = Environment.getExternalStorageDirectory().toString() + "/" + now + "gray.jpg";
                        File imageFilegray = new File(mPathgray);
                        FileOutputStream gout = new FileOutputStream(imageFilegray);

                        bitmap.compress(Bitmap.CompressFormat.PNG,90,gout);

                        byte[] byteArray = bttobyte(myBitmap);
                        Log.d("location"," " + mPathgray);
                            imgview2.setImageBitmap(myBitmap);

                        Log.d("Activity", "Byte array: "+ Arrays.toString(byteArray));

                    }

                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            mMap.snapshot(callback);
            Log.d("test","test2");
        }
    });

}

public byte[] bttobyte(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}
</code>```

答:
The problem you are trying to solve is actually extracting image data from JPEG encoding in the byte array. It is not as simple as being stored pixel by pixel in a grid of width and height equal to your image size, as you seem to be implying. That is a consequence of using this

```<code>bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
</code>```

For example that byte data actually might encode JFIF format:

0xffd8 - SOI - exactly 1 - start of image
e.g. 0xffe0 - zero or more - e.g. APP0 for JFIF - [some sort of header, either JFIF or EXIF].

0xffdb - DQT - one or more - define quantisation tables. These are the main source of quality in the image.

0xffcn - SOFn - exactly one - start of frame. SOF0 indicates a baseline DCT JPEG

0xffc4 - DHT - one or more - define Huffman tables. These are used in the final lossless encoding steps.

0xffda - SOS - exactly one (for baseline, more than one intermixed with more DHTs if progressive) - start of stream. This is where the actual data starts.

0xffd9 - EOI - exactly one - end of image.

Essentially once you have transformed your bitmap, you need a JPEG decoder to parse this data.

I think what you want is to be working with the original bitmap. For example there are APIs to extract pixel data. That is what you need if I understand what it is you want to do correctly.

Bitmap.getPixels(int[] pixels,
                int offset,
                int stride,
                int x,
                int y,
                int width,
                int height)

The array pixels[] is filled with data. You can then parse the array if you want to store it in a w by h 2D array by iterating copying the data. Something like:

```<code>int offset = 0;
int pixels2d[w][h]= new int[w][h];
for (int[] row : pixels2d) {
    System.arraycopy(pixels, offset, row, 0, row.length);
    offset += row.length;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Byte Array to 2D array

Body:
What My code does . is take a snapshot of the map convert it to gray (opencv) and then make it to byte array.
Now what I dont know how to start doing is making this Bytearray to a 2D Array,

here is a block of the code.

                    Date now = new Date();
                    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss",now);
                    try {
                        StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
                        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old)
                                .permitDiskWrites()
                                .build());
                        String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
                        File imageFile = new File(mPath);
                        FileOutputStream out = new FileOutputStream(imageFile);
                        bitmap.compress(Bitmap.CompressFormat.PNG,90,out);
                        Log.d("Image:","Saved Snashot. Starting covertion");
                        //show snapshot in imageview
                        ImageView imgview = (ImageView) findViewById(R.id.imageView);
                        Bitmap smyBitmap = BitmapFactory.decodeFile(mPath);
                        Bitmap myBitmap = BitmapFactory.decodeFile(mPath);
                        imgview.setImageBitmap(smyBitmap);
                        Mat mat = new Mat(myBitmap.getHeight(),myBitmap.getWidth(),CvType.CV_8UC3);
                        Mat mat1 = new Mat(myBitmap.getHeight(),myBitmap.getWidth(),CvType.CV_8UC1);
                        Imgproc.cvtColor(mat,mat1,Imgproc.COLOR_BGR2GRAY);
                        ImageView imgview2 = (ImageView) findViewById(R.id.imageView2);
                            Mat tmp = new Mat (myBitmap.getWidth(), myBitmap.getHeight(), CvType.CV_8UC1);
                            Utils.bitmapToMat(myBitmap, tmp);
                            Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_RGB2GRAY);
                            Utils.matToBitmap(tmp, myBitmap);
                          //  Utils.matToBitmap(mat1,img);
                        String mPathgray = Environment.getExternalStorageDirectory().toString() + "/" + now + "gray.jpg";
                        File imageFilegray = new File(mPathgray);
                        FileOutputStream gout = new FileOutputStream(imageFilegray);

                        bitmap.compress(Bitmap.CompressFormat.PNG,90,gout);

                        byte[] byteArray = bttobyte(myBitmap);
                        Log.d("location"," " + mPathgray);
                            imgview2.setImageBitmap(myBitmap);

                        Log.d("Activity", "Byte array: "+ Arrays.toString(byteArray));

                    }

                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            mMap.snapshot(callback);
            Log.d("test","test2");
        }
    });

}

public byte[] bttobyte(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}

Body:
The problem you are trying to solve is actually extracting image data from JPEG encoding in the byte array. It is not as simple as being stored pixel by pixel in a grid of width and height equal to your image size, as you seem to be implying. That is a consequence of using this

bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);

For example that byte data actually might encode JFIF format:

0xffd8 - SOI - exactly 1 - start of image
e.g. 0xffe0 - zero or more - e.g. APP0 for JFIF - [some sort of header, either JFIF or EXIF].

0xffdb - DQT - one or more - define quantisation tables. These are the main source of quality in the image.

0xffcn - SOFn - exactly one - start of frame. SOF0 indicates a baseline DCT JPEG

0xffc4 - DHT - one or more - define Huffman tables. These are used in the final lossless encoding steps.

0xffda - SOS - exactly one (for baseline, more than one intermixed with more DHTs if progressive) - start of stream. This is where the actual data starts.

0xffd9 - EOI - exactly one - end of image.

Essentially once you have transformed your bitmap, you need a JPEG decoder to parse this data.

I think what you want is to be working with the original bitmap. For example there are APIs to extract pixel data. That is what you need if I understand what it is you want to do correctly.

Bitmap.getPixels(int[] pixels,
                int offset,
                int stride,
                int x,
                int y,
                int width,
                int height)

The array pixels[] is filled with data. You can then parse the array if you want to store it in a w by h 2D array by iterating copying the data. Something like:

int offset = 0;
int pixels2d[w][h]= new int[w][h];
for (int[] row : pixels2d) {
    System.arraycopy(pixels, offset, row, 0, row.length);
    offset += row.length;
}


问:
How exactly works this header mediator involved in the call of a DSS service call from a WSO2 ESB project?
I am absoluty new in WSO2 and I have the following doubt.

I am working on an ESB project. In the  chain there is this header mediator

```<code><?xml version="1.0" encoding="UTF-8"?>
<api context="/glisTest2" name="glisTest2" xmlns="http://ws.apache.org/ns/synapse">
    <resource methods="GET">
        <inSequence>
            <!-- Create empty message to get all samples from DSS -->
            <payloadFactory media-type="xml">
                <format>
                    <body/>
                </format>
                <args>
                    <arg evaluator="xml" expression="get-property('uri.var.int_val')" xmlns:ns="http://org.apache.synapse/xsd" xmlns:ns3="http://org.apache.synapse/xsd"/>
                </args>
            </payloadFactory>

            <!--
                 Adding an header that defines the action related to the "FindNotProcessed" DSS service
                 used to retrieve all the unprocessed resource on the DB.
             -->
            <header name="Action" scope="default" value="urn:FindNotProcessed"/>

               ...................................................................
               ...................................................................
               ...................................................................
        </inSequence>
</code>```

So as you can see the header mediator is chained after a payloadFactory mediator building an empty message that have to be send to a DSS service.

The header mediator:

```<code><header name="Action" scope="default" value="urn:FindNotProcessed"/>
</code>```

add an header that specify the operation name that have to be called on the DSS service, this operation infact is named FindNotProcessed and it is associated to a defined query.

Ok my doubts are:

1) the value of the value attribute specify the name of the operation that have to be performed on the DSS service, in this case this value is urn:FindNotProcessed.

What exactly means the urn: prefix that is putted before the name of the operation to execute?

2) The header mediator definition contains also this attribute name="Action".

What exactly represent? Is it something like the mediator name or the value have to be setted on Action for some semantic meaning? Is it only a name or exists a set of possible values for this field having semantic behavior?

3) So to call a DSS service the propper way is: create a message with a payloadFactory mediator, chained it with an header mediator that specify the name of the operation that have to be performed on the DSS service and then chain a callout mediator that perform the call. I have done in this way and works, is it the standard way to do it?

答:
1) urn:FindNotProcessed is the SOAPAction name, which is defined in the web service WSDL. urn: is just part of that name, it looks like a namespace but it is not.

2)By setting name="Action" you are telling which HTTP header you are setting. In this case it will set SOAPAction: urn:FindNotProcessed.

3) Exactly, but you can use not only Callout, but Send and Call mediators also, depending of your logic.

Body:
I am absoluty new in WSO2 and I have the following doubt.

I am working on an ESB project. In the  chain there is this header mediator

<?xml version="1.0" encoding="UTF-8"?>
<api context="/glisTest2" name="glisTest2" xmlns="http://ws.apache.org/ns/synapse">
    <resource methods="GET">
        <inSequence>

            <payloadFactory media-type="xml">
                <format>

                </format>
                <args>
                    <arg evaluator="xml" expression="get-property('uri.var.int_val')" xmlns:ns="http://org.apache.synapse/xsd" xmlns:ns3="http://org.apache.synapse/xsd"/>
                </args>
            </payloadFactory>

               ...................................................................
               ...................................................................
               ...................................................................
        </inSequence>

So as you can see the header mediator is chained after a payloadFactory mediator building an empty message that have to be send to a DSS service.

The header mediator:

add an header that specify the operation name that have to be called on the DSS service, this operation infact is named FindNotProcessed and it is associated to a defined query.

Ok my doubts are:

1) the value of the value attribute specify the name of the operation that have to be performed on the DSS service, in this case this value is urn:FindNotProcessed.

What exactly means the urn: prefix that is putted before the name of the operation to execute?

2) The header mediator definition contains also this attribute name="Action".

What exactly represent? Is it something like the mediator name or the value have to be setted on Action for some semantic meaning? Is it only a name or exists a set of possible values for this field having semantic behavior?

3) So to call a DSS service the propper way is: create a message with a payloadFactory mediator, chained it with an header mediator that specify the name of the operation that have to be performed on the DSS service and then chain a callout mediator that perform the call. I have done in this way and works, is it the standard way to do it?


问:
What's a PHP regex to target certain URLs?
I have some basic HTML which I am calling str_replace() on, I need to append all URLs found within an HTML string with a 'generate_book.php?link=', but I need to exclude any external links, eg;

Link  --  this should become  --

Link  --  this should be left alone

Your brain powa is appreciated!

答:
Give this a try:</p>

```<code>$str = preg_replace(
    "(href=\"([^\"]+)\")ie",
    "if(substr('$1',0,7) == 'http://')
        return stripslashes('$1');
     else
        return 'generate_book.php?link='.urlencode(stripslashes('$1'));",
    $str);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Give this a try:

$str = preg_replace(
    "(href=\"([^\"]+)\")ie",
    "if(substr('$1',0,7) == 'http://')
        return stripslashes('$1');
     else
        return 'generate_book.php?link='.urlencode(stripslashes('$1'));",
    $str);


问:
Open a Lightbox in a Featherlight.js Lightbox without double-click - Is it possible?
I would like to open a featherlight lightbox with some html-content. The content contains some small pictures and I would like to use the featherlight for the images too to show bigger sizes.

For example: I added the link to the image in the ajax examples div from http://noelboss.github.io/featherlight/

```<code><div class="ajaxcontent lightbox">
    <h2>This Ligthbox was loaded using ajax</h2>
    <p>With <a href="https://github.com/noelboss/featherlight/#installation">little code</a>, you can build lightboxes that use custom content loaded with ajax...</p><a class="btn btn-default" href="assets/images/droplets.jpg" data-featherlight="image">Image</a>
</div>
</code>```

when the lightbox opens Ihave to double-click on the image/button to let it open.

Is it possible to open it on the first click?

Example

答:
Assuming what you want to do is open a featherlight, and from the content of that featherlight open a nested featherlight (which seems really odd tbh), you can use the afterOpen callback, in which you can open the nested featherlight using $.featherlight(...) or find('.my-button-or-something').trigger('click').

Note that when closing the nested featherlight, the first featherlight will still be opened.

Body:
I would like to open a featherlight lightbox with some html-content. The content contains some small pictures and I would like to use the featherlight for the images too to show bigger sizes.

For example: I added the link to the image in the ajax examples div from http://noelboss.github.io/featherlight/

This Ligthbox was loaded using ajax

With little code, you can build lightboxes that use custom content loaded with ajax...
Image

when the lightbox opens Ihave to double-click on the image/button to let it open.

Is it possible to open it on the first click?

Example


问:
how to make a function that disable the other buttons
I am creating a trivia game that get the user answer from the choice of answer button. i would like to make a function that disable the other buttons (answer choices) when the user had tap on a button as answer. Currently, when user pressed multiple buttons continuously the answer(tapped answer) would be use as the answer for the next questions depending on how many taps. I had tried to put a boolean flag to disable other buttons but it will disable to go to the next question.

Here are my codes for the buttons.

```<code>public void onClick(View v) {
    switch (v.getId()) {
        case (R.id.choice1_Button) :
            if (choice1.getText().equals(answer)) {
                correct = 1;
                sound(correct);
                score += 10;
                Toast.makeText(this, "Brilliant! The answer is correct", Toast.LENGTH_SHORT).show();
                scoreboard(score);
                getNextQuestion(counter);
            }else {
                correct = 0;
                sound(correct);
                Toast.makeText(this, "Nice try. The correct answer is "+answer, Toast.LENGTH_SHORT).show();
                if (score > 0) {
                    score = score - 3;
                }
                if (score < 0){
                    score = 0;
                }
                scoreboard(score);
                getNextQuestion(counter);
            }
            break;
        case (R.id.choice2_Button) :
            if (choice2.getText().equals(answer)) {
                correct = 1;
                sound(correct);
                score += 10;
                Toast.makeText(this, "Brilliant! The answer is correct", Toast.LENGTH_SHORT).show();
                scoreboard(score);
                getNextQuestion(counter);
            }else {
                correct = 0;
                sound(correct);
                Toast.makeText(this, "Nice try. The correct answer is "+answer, Toast.LENGTH_SHORT).show();
                if (score > 0) {
                    score = score - 3;
                }
                if (score < 0){
                    score = 0;
                }
                scoreboard(score);
                getNextQuestion(counter);
            }
            break;
        case (R.id.choice3_Button) :
            if (choice3.getText().equals(answer)) {
                correct = 1;
                sound(correct);
                score += 10;
                Toast.makeText(this, "Brilliant! The answer is correct", Toast.LENGTH_SHORT).show();
                scoreboard(score);
                getNextQuestion(counter);
            }else {
                correct = 0;
                sound(correct);
                Toast.makeText(this, "Nice try. The correct answer is "+answer, Toast.LENGTH_SHORT).show();
                if (score > 0) {
                    score = score - 3;
                }
                if (score < 0){
                    score = 0;
                }
                scoreboard(score);
                getNextQuestion(counter);
            }
            break;
    }
}
</code>```

here is my getNextQuestion method

```<code>private void getNextQuestion(final int i) {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (counter < 6) {
                setQuestion();
            }else {
                // if over 5 do this
                Intent intent = new Intent(Level6.this, NextLevel.class);
                Bundle a = new Bundle();
                a.putInt("score", score);
                a.putInt("level", 6);
                intent.putExtras(a);
                startActivity(intent);
                finish();
            }
        }
    },500);
}
</code>```

Here is my setQuestion() method

```<code>private void setQuestion() {
    emotion_View.setImageResource(questionsLib.getQuestions(counter));
    choice1.setText(questionsLib.getOptions1(counter));
    choice2.setText(questionsLib.getOptions2(counter));
    choice3.setText(questionsLib.getOptions3(counter));
    answer = questionsLib.getCorrectAnswer(counter);
    counter++;

}
</code>```

答:
Make method that disable group of buttons, something like this:

```<code>private void setQuestion(Boolean enable) {
    choice1.setEnabled(enable);
    choice2.setEnabled(enable);
    choice3.setEnabled(enable);
}
</code>```

Then before getNextQuestion execute this method to set buttons disable (setQuestion(false))

After stetting next question enable buttons by method (setQuestion(true))  in your handler.

or you can set it all in your getNextQuestion method:

```<code>private void getNextQuestion(final int i) {
    setQuestion(false); //disable buttons
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (counter < 6) {
                setQuestion();
            }else {
                // if over 5 do this
                Intent intent = new Intent(Level6.this, NextLevel.class);
                Bundle a = new Bundle();
                a.putInt("score", score);
                a.putInt("level", 6);
                intent.putExtras(a);
                startActivity(intent);
                setQuestion(true); //enable buttons
                finish();
            }
        }
    },500);
}
</code>```

Body:
I am creating a trivia game that get the user answer from the choice of answer button. i would like to make a function that disable the other buttons (answer choices) when the user had tap on a button as answer. Currently, when user pressed multiple buttons continuously the answer(tapped answer) would be use as the answer for the next questions depending on how many taps. I had tried to put a boolean flag to disable other buttons but it will disable to go to the next question.

Here are my codes for the buttons.

public void onClick(View v) {
    switch (v.getId()) {
        case (R.id.choice1_Button) :
            if (choice1.getText().equals(answer)) {
                correct = 1;
                sound(correct);
                score += 10;
                Toast.makeText(this, "Brilliant! The answer is correct", Toast.LENGTH_SHORT).show();
                scoreboard(score);
                getNextQuestion(counter);
            }else {
                correct = 0;
                sound(correct);
                Toast.makeText(this, "Nice try. The correct answer is "+answer, Toast.LENGTH_SHORT).show();
                if (score > 0) {
                    score = score - 3;
                }
                if (score < 0){
                    score = 0;
                }
                scoreboard(score);
                getNextQuestion(counter);
            }
            break;
        case (R.id.choice2_Button) :
            if (choice2.getText().equals(answer)) {
                correct = 1;
                sound(correct);
                score += 10;
                Toast.makeText(this, "Brilliant! The answer is correct", Toast.LENGTH_SHORT).show();
                scoreboard(score);
                getNextQuestion(counter);
            }else {
                correct = 0;
                sound(correct);
                Toast.makeText(this, "Nice try. The correct answer is "+answer, Toast.LENGTH_SHORT).show();
                if (score > 0) {
                    score = score - 3;
                }
                if (score < 0){
                    score = 0;
                }
                scoreboard(score);
                getNextQuestion(counter);
            }
            break;
        case (R.id.choice3_Button) :
            if (choice3.getText().equals(answer)) {
                correct = 1;
                sound(correct);
                score += 10;
                Toast.makeText(this, "Brilliant! The answer is correct", Toast.LENGTH_SHORT).show();
                scoreboard(score);
                getNextQuestion(counter);
            }else {
                correct = 0;
                sound(correct);
                Toast.makeText(this, "Nice try. The correct answer is "+answer, Toast.LENGTH_SHORT).show();
                if (score > 0) {
                    score = score - 3;
                }
                if (score < 0){
                    score = 0;
                }
                scoreboard(score);
                getNextQuestion(counter);
            }
            break;
    }
}

here is my getNextQuestion method

private void getNextQuestion(final int i) {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (counter < 6) {
                setQuestion();
            }else {
                // if over 5 do this
                Intent intent = new Intent(Level6.this, NextLevel.class);
                Bundle a = new Bundle();
                a.putInt("score", score);
                a.putInt("level", 6);
                intent.putExtras(a);
                startActivity(intent);
                finish();
            }
        }
    },500);
}

Here is my setQuestion() method

private void setQuestion() {
    emotion_View.setImageResource(questionsLib.getQuestions(counter));
    choice1.setText(questionsLib.getOptions1(counter));
    choice2.setText(questionsLib.getOptions2(counter));
    choice3.setText(questionsLib.getOptions3(counter));
    answer = questionsLib.getCorrectAnswer(counter);
    counter++;

}

Body:
Make method that disable group of buttons, something like this:

private void setQuestion(Boolean enable) {
    choice1.setEnabled(enable);
    choice2.setEnabled(enable);
    choice3.setEnabled(enable);
}

Then before getNextQuestion execute this method to set buttons disable (setQuestion(false))

After stetting next question enable buttons by method (setQuestion(true))  in your handler.

or you can set it all in your getNextQuestion method:

private void getNextQuestion(final int i) {
    setQuestion(false); //disable buttons
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (counter < 6) {
                setQuestion();
            }else {
                // if over 5 do this
                Intent intent = new Intent(Level6.this, NextLevel.class);
                Bundle a = new Bundle();
                a.putInt("score", score);
                a.putInt("level", 6);
                intent.putExtras(a);
                startActivity(intent);
                setQuestion(true); //enable buttons
                finish();
            }
        }
    },500);
}


问:
Google-maps geocoding service
Hi I'm using google documentation in geocoding service.

The script should display the location Casablanca but it still show the default location in austalia

The problem is that geocoder.geocode(...) is not executed

```<code>function initMap() {

var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        scrollwheel: false,
        zoom: 8,
      });
codeAddress(geocoder,map);
}
function codeAddress(geocoder, map)
{
  var addr = "Casablanca";
  geocoder.geocode( {'addr':addr}, function(results, status)
  {
    if (status == google.maps.GeocoderStatus.OK)
    {
      map.setCenter(results[0].geometry.addr);//center the map over the result
      //place a marker at the location
      var marker = new google.maps.Marker(
      {
          map: map,
          position: results[0].geometry.addr
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
   }
  });
}
</code>```

PS:
I'm using GooglMapper https://github.com/bradcornford/Googlmapper

I appreciate any help.

答:
Answer For my problem

```<code>map.setCenter(results[0].geometry.addr);
</code>```

Should be

```<code>map.setCenter(results[0].geometry.location);
</code>```

And

```<code>position: results[0].geometry.addr
</code>```

Should Be

```<code>position: results[0].geometry.location
</code>```

Title: Google-maps geocoding service

Body:
Hi I'm using google documentation in geocoding service.

The script should display the location Casablanca but it still show the default location in austalia

The problem is that geocoder.geocode(...) is not executed

function initMap() {

var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        scrollwheel: false,
        zoom: 8,
      });
codeAddress(geocoder,map);
}
function codeAddress(geocoder, map)
{
  var addr = "Casablanca";
  geocoder.geocode( {'addr':addr}, function(results, status)
  {
    if (status == google.maps.GeocoderStatus.OK)
    {
      map.setCenter(results[0].geometry.addr);//center the map over the result
      //place a marker at the location
      var marker = new google.maps.Marker(
      {
          map: map,
          position: results[0].geometry.addr
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
   }
  });
}

PS:
I'm using GooglMapper https://github.com/bradcornford/Googlmapper

I appreciate any help.

Body:
Answer For my problem

map.setCenter(results[0].geometry.addr);

Should be

map.setCenter(results[0].geometry.location);

And

position: results[0].geometry.addr

Should Be

position: results[0].geometry.location


问:
How to remove files from Caches directory in swift 2.3?
The cache.db-wal file have the sensitive information in my application.Need to remove the cache files in Caches directory.</p>

答:
This should work for you.</p>

```<code>let fileManager = NSFileManager.defaultManager()
let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first! as NSURL
let documentsPath = documentsUrl.path

do {
    if let documentPath = documentsPath
    {
        let fileNames = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")

        for fileName in fileNames {

            if (fileName == "cache.db-wal")
            {
                let filePathName = "\(documentPath)/\(fileName)"
                try fileManager.removeItemAtPath(filePathName)
            }
        }

        let files = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")
    }

} catch {
    print("Could not clear: \(error)")
}
</code>```

Body:
This should work for you.

let fileManager = NSFileManager.defaultManager()
let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first! as NSURL
let documentsPath = documentsUrl.path

do {
    if let documentPath = documentsPath
    {
        let fileNames = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")

        for fileName in fileNames {

            if (fileName == "cache.db-wal")
            {
                let filePathName = "\(documentPath)/\(fileName)"
                try fileManager.removeItemAtPath(filePathName)
            }
        }

        let files = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")
    }

} catch {
    print("Could not clear: \(error)")
}


问:
Hide duplicate post on article page - Wordpress
I'm displaying a article on my page in Wordpress. Then right below that article, Im doing a foreach loop and displaying latest articles. Here is how it looks:

As you can see, "Jeffs Wedding Surprise" displays again in the bottom articles. How can I make it so the same article wont display again in my foreach loop that I'm viewing right now.

Here is how Im looping through the "Similar articles" at the bottom and my featured article:

```<code><?php if( have_posts() ){
            while( have_posts(['posts_per_page'=>100]) ){
                $articles = the_post();
                $thumb_id = get_post_thumbnail_id($articles);
                $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
                $thumb_url = $thumb_url_array[0];
        ?>
            <?php } ?>
            <div class="article-heading">
                <h4><?php the_title(); ?></h4>
            </div>
            <div class="article-background">
                <img src="<?=$thumb_url;?>">
                <?php
                $title = get_the_title();
                $content = the_content();
                if(strlen($content)>0){?>
                    <div class="article-details">
                        <?php $content ?>
                    </div>
                <?php } ?>
            </div>
        <?php } ?>

        <div class="similar-section">
            <h3>Similar Articles</h3>
        </div>
        <?php foreach (get_posts(['post_type' => 'add_article', 'posts_per_page'=>3]) as $articles) {
            $thumb_id = get_post_thumbnail_id($articles);
            $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
            $thumb_url = $thumb_url_array[0];
            $url_to_project = "/previous_work/".$articles->post_name;
            ?>
                <div class="col-md-4">
                    <a class="article-link" href="<?=$url_to_project;?>">
                        <div class="single-article-photo">
                            <img src="<?=$thumb_url;?>">
                        </div>
                        <div class="single-article">
                            <h6><?= $articles->post_title ?></h6>
                            <p><?= substr($articles->post_content,0,200) ?> <span style="text-transform: uppercase; text-decoration: underline">(Read More)</span>...</p>
                        </div>
                    </a>
                </div>
        <?php } ?>
</code>```

答:
You can add condition to check the title/id of main article not display in similar articles.

In main article code

```<code>$title = get_the_title(); // title of main article
</code>```

For similar articles

```<code> foreach (get_posts(['post_type' => 'add_article', 'posts_per_page'=>3]) as $articles) {
    if($title!=$articles->post_title){
      // display article
    }
}
</code>```

Body:
I'm displaying a article on my page in Wordpress. Then right below that article, Im doing a foreach loop and displaying latest articles. Here is how it looks:

As you can see, "Jeffs Wedding Surprise" displays again in the bottom articles. How can I make it so the same article wont display again in my foreach loop that I'm viewing right now.

Here is how Im looping through the "Similar articles" at the bottom and my featured article:

<?php if( have_posts() ){
            while( have_posts(['posts_per_page'=>100]) ){
                $articles = the_post();
                $thumb_id = get_post_thumbnail_id($articles);
                $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
                $thumb_url = $thumb_url_array[0];
        ?>
            <?php } ?>

<?php the_title(); ?>

                <img src="<?=$thumb_url;?>">
                <?php
                $title = get_the_title();
                $content = the_content();
                if(strlen($content)>0){?>

                        <?php $content ?>

                <?php } ?>

        <?php } ?>

Similar Articles

        <?php foreach (get_posts(['post_type' => 'add_article', 'posts_per_page'=>3]) as $articles) {
            $thumb_id = get_post_thumbnail_id($articles);
            $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
            $thumb_url = $thumb_url_array[0];
            $url_to_project = "/previous_work/".$articles->post_name;
            ?>

                    <a class="article-link" href="<?=$url_to_project;?>">

                            <img src="<?=$thumb_url;?>">

<?= $articles->post_title ?>

<?= substr($articles->post_content,0,200) ?> (Read More)...

        <?php } ?>

Body:
You can add condition to check the title/id of main article not display in similar articles.

In main article code

$title = get_the_title(); // title of main article

For similar articles

 foreach (get_posts(['post_type' => 'add_article', 'posts_per_page'=>3]) as $articles) {
    if($title!=$articles->post_title){
      // display article
    }
}


问:
Fast I2C connection, moving to new library
I need a faster communication between the ESP and the ADC, so I found this https://github.com/pasko-zh/brzo_i2c.

Original Wire Example

```<code>#include "Wire.h"
#define PCF8591 0x48
byte a0;

void setup() {
  Wire.begin(13,14);
  Serial.begin(115200);
}

void loop() {
  Wire.beginTransmission(PCF8591);
  Wire.write(0x04);
  Wire.endTransmission();
  Wire.requestFrom(PCF8591, 5);
  a0=Wire.read();
  a0=Wire.read();
  Serial.println(a0);
  delay(1000);
}
</code>```

Brzo I2C example

```<code>#include "brzo_i2c.h"

uint8_t buffer[10];
uint8_t error=0;
float temp=0.0;

uint8_t ICACHE_RAM_ATTR get_temp(float *t) {
   uint8_t bcode=0;
  brzo_i2c_start_transaction(0x48,400);
  buffer[0]=0x04;
  brzo_i2c_write(buffer,1,false);// somewhere here is the error
  brzo_i2c_read(buffer,2,false);// or here
  bcode=brzo_i2c_end_transaction();
  *t=((buffer[0]<<8)|buffer[1]);
  return bcode;
}

void setup(){
  delay(500);
  Serial.begin(115200);
  brzo_i2c_setup(13,14,2000);
}

void loop() {
  error=get_temp(&temp);
  if(error==0){
  Serial.print("Temp = ");
  Serial.println(temp, 8);
} else {
  Serial.print("Brzo error : ");
  Serial.println(error);
}
  delay(500);
}
</code>```

But I always get the same error.

1 : Bus not free

I rewrote it in different ways, changing the frequency, pins and doing multiple transactions. The main reason I don't get it to work is the difference in the API.

There is no ~Wire.requestFrom();in the brzo_i2c lib. So I need to read the value withbrzo_i2c_read(buffer,2,false);`. Anyway, the brzo code does not work. I always get the same error and there is no description in the docs.

Wire reference: https://www.arduino.cc/en/reference/wire

brzo reference: https://github.com/pasko-zh/brzo_i2c/wiki

答:
This is paško, the author of the library brzo_i2c.

First, for further upcoming questions may I kindly ask you to open an issue on the github repo, i.e. bzro_i2c Issues. This is the usual place where people ask questions about the library.

I made a distinction between documentation of the code and the wiki. The readme is short and the brzo_i2c wiki explains many i2c and brzo_i2c related stuff.

In general, an i2c bus is not free if either SCA or SCL is low.

I assume your wiring is correct? How big are your pull-up resistors?

I had a look at the datasheet of the PCF8591. On page 20 table 11 "dynamic characteristics" it says: SCL clock frequency MAX 100 kHz. In your code however, you are selecting 400 kHz, brzo_i2c_start_transaction(0x48,400); So, you should use 100 kHz at maximum. I guess it is a timing problem for the read command after writing the control byte.

Concerning Wire.requestFrom(PCF8591, 5):
Behind the scenes this statement does read 5 bytes and puts them in a receive buffer, i.e. i2c communication takes place: START, send slave address, read first byte, ..., STOP. You can see this in the code of the wire library, where it calls twi_readFrom(.), and the actual i2c communication in the underlying esp8266Core code. Note that calls afterwards to wire.read(.) does not perform any i2c communication, instead it just returns the bytes from the receive buffer.
Now, turning Wire.requestFrom(PCF8591, 5) into brzo_i2c is very simple:

```<code>brzo_i2c_start_transaction(0x48,100);
  brzo_i2c_read(buffer,5,false);
bcode = brzo_i2c_end_transaction();
</code>```

However, I would not do seperate transactions for reads and writes, instead I would combine them -- as long as they belong "together". So your code above, where your writing the control byte and then afterwards reading out the corresponding data is the way to go :-)

btw: From your code I am guessing that you are using an analogue temperature sensor. You may use a digital sensor that has an i2c bus interface, e.g., an ADT7420, code snippet with brzo_i2c is here

Body:
I need a faster communication between the ESP and the ADC, so I found this https://github.com/pasko-zh/brzo_i2c.

Original Wire Example

#include "Wire.h"
#define PCF8591 0x48
byte a0;

void setup() {
  Wire.begin(13,14);
  Serial.begin(115200);
}

void loop() {
  Wire.beginTransmission(PCF8591);
  Wire.write(0x04);
  Wire.endTransmission();
  Wire.requestFrom(PCF8591, 5);
  a0=Wire.read();
  a0=Wire.read();
  Serial.println(a0);
  delay(1000);
}

Brzo I2C example

#include "brzo_i2c.h"

uint8_t buffer[10];
uint8_t error=0;
float temp=0.0;

uint8_t ICACHE_RAM_ATTR get_temp(float *t) {
   uint8_t bcode=0;
  brzo_i2c_start_transaction(0x48,400);
  buffer[0]=0x04;
  brzo_i2c_write(buffer,1,false);// somewhere here is the error
  brzo_i2c_read(buffer,2,false);// or here
  bcode=brzo_i2c_end_transaction();
  *t=((buffer[0]<<8)|buffer[1]);
  return bcode;
}

void setup(){
  delay(500);
  Serial.begin(115200);
  brzo_i2c_setup(13,14,2000);
}

void loop() {
  error=get_temp(&temp);
  if(error==0){
  Serial.print("Temp = ");
  Serial.println(temp, 8);
} else {
  Serial.print("Brzo error : ");
  Serial.println(error);
}
  delay(500);
}

But I always get the same error.

1 : Bus not free

I rewrote it in different ways, changing the frequency, pins and doing multiple transactions. The main reason I don't get it to work is the difference in the API.

There is no ~Wire.requestFrom();in the brzo_i2c lib. So I need to read the value withbrzo_i2c_read(buffer,2,false);`. Anyway, the brzo code does not work. I always get the same error and there is no description in the docs.

Wire reference: https://www.arduino.cc/en/reference/wire

brzo reference: https://github.com/pasko-zh/brzo_i2c/wiki

Body:
This is paško, the author of the library brzo_i2c.

First, for further upcoming questions may I kindly ask you to open an issue on the github repo, i.e. bzro_i2c Issues. This is the usual place where people ask questions about the library.

I made a distinction between documentation of the code and the wiki. The readme is short and the brzo_i2c wiki explains many i2c and brzo_i2c related stuff.

In general, an i2c bus is not free if either SCA or SCL is low.

I assume your wiring is correct? How big are your pull-up resistors?

I had a look at the datasheet of the PCF8591. On page 20 table 11 "dynamic characteristics" it says: SCL clock frequency MAX 100 kHz. In your code however, you are selecting 400 kHz, brzo_i2c_start_transaction(0x48,400); So, you should use 100 kHz at maximum. I guess it is a timing problem for the read command after writing the control byte.

Concerning Wire.requestFrom(PCF8591, 5):
Behind the scenes this statement does read 5 bytes and puts them in a receive buffer, i.e. i2c communication takes place: START, send slave address, read first byte, ..., STOP. You can see this in the code of the wire library, where it calls twi_readFrom(.), and the actual i2c communication in the underlying esp8266Core code. Note that calls afterwards to wire.read(.) does not perform any i2c communication, instead it just returns the bytes from the receive buffer.
Now, turning Wire.requestFrom(PCF8591, 5) into brzo_i2c is very simple:

brzo_i2c_start_transaction(0x48,100);
  brzo_i2c_read(buffer,5,false);
bcode = brzo_i2c_end_transaction();

However, I would not do seperate transactions for reads and writes, instead I would combine them -- as long as they belong "together". So your code above, where your writing the control byte and then afterwards reading out the corresponding data is the way to go :-)

btw: From your code I am guessing that you are using an analogue temperature sensor. You may use a digital sensor that has an i2c bus interface, e.g., an ADT7420, code snippet with brzo_i2c is here


问:
Ruby sort by multiple values?
I have an array of hashes:

```<code>a=[{ 'foo'=>0,'bar'=>1 },
   { 'foo'=>0,'bar'=>2 },
   ... ]
</code>```

I want to sort the array first by each hash's 'foo', then by 'bar'. Google tells me this is how it's done:

```<code>a.sort_by {|h| [ h['foo'],h['bar'] ]}
</code>```

But this gives me the ArgumentError "comparison of Array with Array failed". What does this mean?

Title: Ruby sort by multiple values?

Body:
I have an array of hashes:

a=[{ 'foo'=>0,'bar'=>1 },
   { 'foo'=>0,'bar'=>2 },
   ... ]

I want to sort the array first by each hash's 'foo', then by 'bar'. Google tells me this is how it's done:

a.sort_by {|h| [ h['foo'],h['bar'] ]}

But this gives me the ArgumentError "comparison of Array with Array failed". What does this mean?

Body: a.sort { |a, b| [a['foo'], a['bar']] <=> [b['foo'], b['bar']] }


问:
Mocking service calls that return observables in Angular 2?
I have been trying to mock some service calls that return observables in my Angular app, but i simply can't create a valid observable that will trigger calls like catch() or map() in my code. For example:

My service:

```<code>create(): Observable<any> {
    return this.http
    .post('/api/stuff', { id: 123 })
    .catch(this.handleError)
    .map(this.extractData);
}
</code>```

My spec:

```<code>let authHttpMock = mock(AuthHttp);
when(authHttpMock.post('/api/stuff', { id: 123 })).thenReturn(Observable.create(observer => {
  observer.error(new Error('500!'));
}));

const myService = new MyService(instance(authHttpMock));
myService.create({ id: 123 }).subscribe(
    result => {
    expect(result).toBeTruthy();
    }
);
</code>```

The coverage analysis tells me that the handleError method has never been executed. On the case of a successful observable, it also doesn't go through the extractData method.

Where is that observable going to? How can i return a proper observable in order to test such calls?

答:
Somewhere in your test code I believe you need to have this code:</p>

```<code>AuthHttp.post('/api/stuff', {id : 123 }).subscribe(data => {});
</code>```

Body:
I have been trying to mock some service calls that return observables in my Angular app, but i simply can't create a valid observable that will trigger calls like catch() or map() in my code. For example:

My service:

create(): Observable<any> {
    return this.http
    .post('/api/stuff', { id: 123 })
    .catch(this.handleError)
    .map(this.extractData);
}

My spec:

let authHttpMock = mock(AuthHttp);
when(authHttpMock.post('/api/stuff', { id: 123 })).thenReturn(Observable.create(observer => {
  observer.error(new Error('500!'));
}));

const myService = new MyService(instance(authHttpMock));
myService.create({ id: 123 }).subscribe(
    result => {
    expect(result).toBeTruthy();
    }
);

The coverage analysis tells me that the handleError method has never been executed. On the case of a successful observable, it also doesn't go through the extractData method.

Where is that observable going to? How can i return a proper observable in order to test such calls?

Body:
Somewhere in your test code I believe you need to have this code:

AuthHttp.post('/api/stuff', {id : 123 }).subscribe(data => {});


问:
php multiplication of two cell input by user
```<code>for ($i=1; $i<=3; $i++)
{
print("<tr>");
print("<td>$i</td>");

print("<td><input type='text' name='meter[$i]' class='meter' maxlength='21' id='meter[$i]' /></td>");
                    print("<td><input type='text' name='weight[$i]' maxlength='21' class='weight' id='weight[$i]' size='10' /></td>");
print("<td><input type='text' name='amount[$i]' maxlength='21' class='amount' id='amount[$i]' size='10' /></td>");
print("</tr>");
}
?>
</code>```

i want like this

if i enter 110 in meter and 10 in weight it should give me ans (10/110)*100;
in each column

```(weight/meter)*100```

```  meter  weight  output
    110   | 10   |  9.09
    120   | 12   |  10
    130   | 14   |  10.76```

答:
To have only 2 decimals, you can use javascript value1.toFixed(2):</p>

```<code>print("         var value1 = weight * 100 / meter;");
print("         amountd.value = value1.toFixed(2);");
</code>```

Body:
for ($i=1; $i<=3; $i++)
{
print("
");
print("$i	");

print("<input type='text' name='meter[$i]' class='meter' maxlength='21' id='meter[$i]' />	");
                    print("<input type='text' name='weight[$i]' maxlength='21' class='weight' id='weight[$i]' size='10' />	");
print("<input type='text' name='amount[$i]' maxlength='21' class='amount' id='amount[$i]' size='10' />	");
print("
");
}
?>

i want like this

if i enter 110 in meter and 10 in weight it should give me ans (10/110)*100;
in each column

(weight/meter)*100

  meter  weight  output
    110   | 10   |  9.09
    120   | 12   |  10
    130   | 14   |  10.76

Body:
To have only 2 decimals, you can use javascript value1.toFixed(2):

print("         var value1 = weight * 100 / meter;");
print("         amountd.value = value1.toFixed(2);");


问:
how to change the background color of Fl_Window by pressing Fl_Button
Can anyone tell me, how to change the background color of Fl_Window by pressing Fl_Button. I'm trying to do it this way but it's not working.

```<code>void new_color(Fl_Widget* w, void*){
Fl_Button* b = (Fl_Button*)w;
b->parent()->color(FL_RED);
}

int main()
}
Fl_Window* win = new Fl_Window(...);
win->color(FL_WHITE);
win->begin();

Fl_Button* but = new Fl_Button(...);
but->callback(new_color);

win->end();
...
}
</code>```

thanks!!!

答:
As pointed by cup, redraw does the trick:</p>

```<code>#include <FL/Fl.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Window.H>

int main()
{
    Fl_Window win(200, 200, "Color changer");
    win.color(FL_WHITE);

    Fl_Button but(50, 80, 100, 20, "Click Me!");
    but.callback([](Fl_Widget* w, void*) {
        Fl_Widget* p = w->parent();
        p->color(p->color() == FL_WHITE ? FL_RED : FL_WHITE);
        p->redraw();
    });

    win.show();
    return Fl::run();
}
</code>```

Body:
Can anyone tell me, how to change the background color of Fl_Window by pressing Fl_Button. I'm trying to do it this way but it's not working.

void new_color(Fl_Widget* w, void*){
Fl_Button* b = (Fl_Button*)w;
b->parent()->color(FL_RED);
}

int main()
}
Fl_Window* win = new Fl_Window(...);
win->color(FL_WHITE);
win->begin();

Fl_Button* but = new Fl_Button(...);
but->callback(new_color);

win->end();
...
}

thanks!!!

Body:
As pointed by cup, redraw does the trick:

#include <FL/Fl.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Window.H>

int main()
{
    Fl_Window win(200, 200, "Color changer");
    win.color(FL_WHITE);

    Fl_Button but(50, 80, 100, 20, "Click Me!");
    but.callback([](Fl_Widget* w, void*) {
        Fl_Widget* p = w->parent();
        p->color(p->color() == FL_WHITE ? FL_RED : FL_WHITE);
        p->redraw();
    });

    win.show();
    return Fl::run();
}


问:
Bash script: Replace a line in a file
I have the following script:

```<code>#!/bin/bash

LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1"
NEW_LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline"

#sed -i "/${LINE}/c ${NEW_LINE}" grub.cfg

LINE1="insmod lvm"
NEW_LINE1="insmod lvm x"

sed -i "/${LINE1}/c ${NEW_LINE1}" grub.cfg
</code>```

Can someone tell me why the commented sed does not work (Error: sed: -e expression #1, char 10: extra characters after command), but the uncommented one does, when only the strings are different?

答:
The uncommented line does not work because the delimiter your sed expression uses appears in the thing you are matching and replacing.

```<code>LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1"
NEW_LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline"

sed -i "/${LINE}/c ${NEW_LINE}" grub.cfg
</code>```

Your sed expression will resolve to:

```<code>/linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1/c linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline
</code>```

As you can see, this results in more operations in the expression than sed expects, hence your error message extra characters after command.

If you change your delimiter to a different character it should work:

```<code>sed -i "\:${LINE}:c ${NEW_LINE}" grub.cfg
</code>```

You could also use the s command — try:

```<code>sed -i "s:${LINE}:c ${NEW_LINE}:g" grub.cfg
</code>```

Title: Bash script: Replace a line in a file

Body:
I have the following script:

#!/bin/bash

LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1"
NEW_LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline"

#sed -i "/${LINE}/c ${NEW_LINE}" grub.cfg

LINE1="insmod lvm"
NEW_LINE1="insmod lvm x"

sed -i "/${LINE1}/c ${NEW_LINE1}" grub.cfg

Can someone tell me why the commented sed does not work (Error: sed: -e expression #1, char 10: extra characters after command), but the uncommented one does, when only the strings are different?

Body:
The uncommented line does not work because the delimiter your sed expression uses appears in the thing you are matching and replacing.

LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1"
NEW_LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline"

sed -i "/${LINE}/c ${NEW_LINE}" grub.cfg

Your sed expression will resolve to:

/linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1/c linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline

As you can see, this results in more operations in the expression than sed expects, hence your error message extra characters after command.

If you change your delimiter to a different character it should work:

sed -i "\:${LINE}:c ${NEW_LINE}" grub.cfg

You could also use the s command — try:

sed -i "s:${LINE}:c ${NEW_LINE}:g" grub.cfg


问:
Threading: networking thread, gui thread, backend thread postoffice intermediary class a good setup?
I tend to use the following as my standard threading model, but maybe it isn't such a great model. What other suggestions do people have or do they think this is set up well? This is not for a high performance internet server, though performance is sometimes pretty critical and in those cases I use asynchronous networking methods and reuse buffers, but it is the same model.

There is a gui thread to run the gui.

There is a backend thread that handles anything that is computationally intensive (basically anything the gui can hand off that isn't pretty quick to run) and also is in charge of parsing and acting on incoming messages or gui actions.

There is one or more networking threads that take care of breaking an outgoing send into peices if necessary, recieving packets from various sockets and reassembling them into messages.

There is an intermediary static class which serves as an intermediary between the networking and backend threads. It acts as a post office. Messages that need to go out are posted to it by backend threads and networking threads check the "outbox" of this class to find messages to send and post any incoming messages in a static "inbox" this class has (regardless of the socket they arrive from, though that information is posted with the incoming message) which the backend thread checks to find messages from other machines it should act on.

The gui / backend threading interface tends to be more ad hoc and should probably have its own post office like class or some alternative intermediary?

Any comments/suggestions on this threading setup?

答: My primary concern is that you don't really want to lock yourself into the idea that there can only be one back-end thread.  My normal model is to use the MVC at first, make sure all the data structures I use aren't inherently unsafe for a threaded environment, avoid singletons, and then profile like crazy, splitting things out as I go while trying to minimize the number of condition variables I'm leveraging.  For long asynchronous tasks, I prefer to spawn a new process, particularly if it's something that might want to let the OS give it a differing priority.</p>


问:
Python: Best way to decorate a function only locally
What is the best way to decorate a function, but only in a local scope. For example we have the following:

```<code>def a():
    do stuff
    b()
    do stuff
</code>```

I want to make a function c() that does the same stuff but decorates b so it adds some extra stuff. I found a way to do that but it changes b() globally:

```<code>def c():
    global b
    b = decorator(b)
    a()
</code>```

Is there a way to do that but without changing the function b globally?

答:
Python allow any object to be a callable, not only functions.

You could use something like:

```<code>class A(object):
    def __init__(self, func=b):
        self.func = func
    def __call__(self):
        # do stuff
        self.func()
        # do other stuff
</code>```

Then with a = A(), a() will simply invoke f but if you writec = A(decorator(b)), c() will invoke the decorated version

Body:
What is the best way to decorate a function, but only in a local scope. For example we have the following:

def a():
    do stuff
    b()
    do stuff

I want to make a function c() that does the same stuff but decorates b so it adds some extra stuff. I found a way to do that but it changes b() globally:

def c():
    global b
    b = decorator(b)
    a()

Is there a way to do that but without changing the function b globally?

Body:
Python allow any object to be a callable, not only functions.

You could use something like:

class A(object):
    def __init__(self, func=b):
        self.func = func
    def __call__(self):
        # do stuff
        self.func()
        # do other stuff

Then with a = A(), a() will simply invoke f but if you writec = A(decorator(b)), c() will invoke the decorated version


问:
How to create a file upload button using css3 flexbox and jquery?
Hello
I want to create a multi-select file upload button on website using flexbox css3 html5 and jquery. please help.
thanks in advance.

Also I want to style differently the choose file button and no file selected text

.btn:link,
.btn:visited{

    display: inline-block;
    padding: 10px 30px;
    font-weight: 300;
    text-decoration: none;
    border-radius: 200px;
    -webkit-transition: background-color 0.2s, border 0.2s, color 0.2s;
    transition: background-color 0.2s, border 0.2s, color 0.2s;
}

.fileToUpload:link,
.fileToUpload:visited,
input[type=file]
{
    position: relative;
    margin: 20px 10px;
    padding:10px;
    border: 1px solid #96a9ec;
    color: #fff;
    margin-right: 15px;
}

.btn:hover,
.btn:active
 {
    background-color: #2622de;
}

input[type=file]:hover,
input[type=file]:active {
    border: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<form action="upload.js" method="post" enctype="multipart/form-data" >

<input type="file" name="fileToUpload" class="btn fileToUpload" >

</form>
</div></code>```

答:
i can't to write code for you, you must learing for this.
i just give you simple information for design upload button, in that input, you can't edit because not all browser design same type for upload button, we know HTML is code for browser, and so all browsers can't same type button style, you make one by you self.

you can try this :

input[type=file]{
  display:none;
}

.uploader{
  width:200px;
  display: block;
  cursor:pointer;
}

.uploader div{
  background-color:skyblue;
   position:relative;
   width:50%;
   text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id='upload' type='file' /><label class='uploader' for='upload' ><div>Upload</div></label> </code>```

the point is you must hidden true button, and use a label tag.

Body:
Hello
I want to create a multi-select file upload button on website using flexbox css3 html5 and jquery. please help.
thanks in advance.

Also I want to style differently the choose file button and no file selected text

.btn:link,
.btn:visited{

    display: inline-block;
    padding: 10px 30px;
    font-weight: 300;
    text-decoration: none;
    border-radius: 200px;
    -webkit-transition: background-color 0.2s, border 0.2s, color 0.2s;
    transition: background-color 0.2s, border 0.2s, color 0.2s;
}

.fileToUpload:link,
.fileToUpload:visited,
input[type=file]
{
    position: relative;
    margin: 20px 10px;
    padding:10px;
    border: 1px solid #96a9ec;
    color: #fff;
    margin-right: 15px;
}

.btn:hover,
.btn:active
 {
    background-color: #2622de;
}

input[type=file]:hover,
input[type=file]:active {
    border: 1px solid red;
}

<form action="upload.js" method="post" enctype="multipart/form-data" >

<input type="file" name="fileToUpload" class="btn fileToUpload" >

</form>

Body:
i can't to write code for you, you must learing for this.
i just give you simple information for design upload button, in that input, you can't edit because not all browser design same type for upload button, we know HTML is code for browser, and so all browsers can't same type button style, you make one by you self.

you can try this :

input[type=file]{
  display:none;
}

.uploader{
  width:200px;
  display: block;
  cursor:pointer;
}

.uploader div{
  background-color:skyblue;
   position:relative;
   width:50%;
   text-align:center;
}

<input id='upload' type='file' /><label class='uploader' for='upload' ><div>Upload</div></label>

the point is you must hidden true button, and use a label tag.


问:
Access mainpage content from other page loaded in frame
I'm developing a program in C# & XAML where my MainPage has two frames, one of which is an entire page.

I want to load another page inside the Inner frame of MainPage, which has a number of buttons. By pressing one of them, I want to load the Third Page in my Whole Page Frame (bigger frame).

Any suggestions to make this happen?

答:
"frame" being the name of the frame you want your page to appear on and "ThirdPage" a page item of your project, you could add the code below to the button click event you are talking about: </p>

```<code>frame.NavigationService.Navigate(new ThirdPage());
</code>```

Body:
"frame" being the name of the frame you want your page to appear on and "ThirdPage" a page item of your project, you could add the code below to the button click event you are talking about:

frame.NavigationService.Navigate(new ThirdPage());


问:
Does camel use an implicit read lock for files?
I'm consuming a file using Camel File component as follows:

```<code><from uri="file:myDir?noop=true&filter=myFilter&scheduler=quartz2&scheduler.cron={{schedule}}/>
</code>```

The source location is read only. Camel File documentation says, it won't be using a read lock by default.

But, I'm getting a permission denied exception while running this code.

Endpoint[file://myFile?filter=myFilter&idempotent=true&noop=true&scheduler=quartz2&scheduler.cron={{mySchedule}}
  cannot begin processing file: GenericFile[myDir\myFile] due to: Access
  is denied. Caused by: [java.io.IOException - Access is denied]

Stack Trace java.io.IOException: Permission denied   at
  java.io.UnixFileSystem.createFileExclusively(Native Method)[:1.8.0_66]
  at java.io.File.createNewFile(File.java:1012)[:1.8.0_66]   at
  org.apache.camel.util.FileUtil.createNewFile(FileUtil.java:587)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.MarkerFileExclusiveReadLockStrategy.acquireExclusiveReadLock(MarkerFileExclusiveReadLockStrategy.java:71)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.GenericFileProcessStrategySupport.begin(GenericFileProcessStrategySupport.java:49)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.GenericFileRenameProcessStrategy.begin(GenericFileRenameProcessStrategy.java:35)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:352)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:211)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:175)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:174)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:101)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.pollconsumer.quartz2.QuartzScheduledPollConsumerJob.execute(QuartzScheduledPollConsumerJob.java:59)[org.apache.camel:camel-quartz2:2.15.1.redhat-621090]
  at
  org.quartz.core.JobRunShell.run(JobRunShell.java:202)[org.quartz-scheduler:quartz:2.2.1]
  at
  org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)[org.quartz-scheduler:quartz:2.2.1]

From the stack trace, it appears that, camel is trying to create a readLock and it is causing exception due to lack of of permission.

So, my questions are

Why camel is using a lock, even if default value of read lock is none

If this is expected behavior, how can I consume file from a read only location where I don't have write permission?

UPDATE

I tried setting readLockMarkingFile to false as suggested in one of the answer, but that did n't solve the problem. So, I explicitly set readLock to none. Now, it is working. Don't know, why readLock is not none by default as mentioned in documentation.

答:
The readLock-option only decides whether camel will try to acquire an exclusive read-lock on the file. There is another option called "readLockMarkerFile" which defaults to true, set that option to false and you should be fine.</p>

```<code><from uri="file:myDir?noop=true&filter=myFilter&scheduler=quartz2&scheduler.cron={{schedule}}&readLockMarkerFile=false/>
</code>```

Body:
I'm consuming a file using Camel File component as follows:

<from uri="file:myDir?noop=true&filter=myFilter&scheduler=quartz2&scheduler.cron={{schedule}}/>

The source location is read only. Camel File documentation says, it won't be using a read lock by default.

But, I'm getting a permission denied exception while running this code.

Endpoint[file://myFile?filter=myFilter&idempotent=true&noop=true&scheduler=quartz2&scheduler.cron={{mySchedule}}
  cannot begin processing file: GenericFile[myDir\myFile] due to: Access
  is denied. Caused by: [java.io.IOException - Access is denied]

Stack Trace java.io.IOException: Permission denied   at
  java.io.UnixFileSystem.createFileExclusively(Native Method)[:1.8.0_66]
  at java.io.File.createNewFile(File.java:1012)[:1.8.0_66]   at
  org.apache.camel.util.FileUtil.createNewFile(FileUtil.java:587)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.MarkerFileExclusiveReadLockStrategy.acquireExclusiveReadLock(MarkerFileExclusiveReadLockStrategy.java:71)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.GenericFileProcessStrategySupport.begin(GenericFileProcessStrategySupport.java:49)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.GenericFileRenameProcessStrategy.begin(GenericFileRenameProcessStrategy.java:35)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:352)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:211)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:175)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:174)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:101)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.pollconsumer.quartz2.QuartzScheduledPollConsumerJob.execute(QuartzScheduledPollConsumerJob.java:59)[org.apache.camel:camel-quartz2:2.15.1.redhat-621090]
  at
  org.quartz.core.JobRunShell.run(JobRunShell.java:202)[org.quartz-scheduler:quartz:2.2.1]
  at
  org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)[org.quartz-scheduler:quartz:2.2.1]

From the stack trace, it appears that, camel is trying to create a readLock and it is causing exception due to lack of of permission.

So, my questions are

Why camel is using a lock, even if default value of read lock is none

If this is expected behavior, how can I consume file from a read only location where I don't have write permission?

UPDATE

I tried setting readLockMarkingFile to false as suggested in one of the answer, but that did n't solve the problem. So, I explicitly set readLock to none. Now, it is working. Don't know, why readLock is not none by default as mentioned in documentation.

Body:
The readLock-option only decides whether camel will try to acquire an exclusive read-lock on the file. There is another option called "readLockMarkerFile" which defaults to true, set that option to false and you should be fine.

<from uri="file:myDir?noop=true&amp;filter=myFilter&amp;scheduler=quartz2&amp;scheduler.cron={{schedule}}&amp;readLockMarkerFile=false/>


问:
Is it possible to add a classname to each test case in assertion.xml using gatling?
I want to use the gatling junit report to upload it automatically in Testlink using Hudson but there is no classname tag in the file so I can't link it to a test case. Is there any way to add it?</p>

答: Finally, I don't need to change the junit file! I used the test suite name in testling as a custom field and I configured it in hudson with testlink plugin.</p>


问:
Connect an Arduino Ethernet to localhost:8000
I have an Arduino connected via Ethernet to my computer and a webserver is running on localhost:8000.

computer IP: 192.168.1.5
arduino IP: 192.168.1.6

The connection between Arduino and Computer is technically working and I even could establish a connection between the arduino and the computer on port 80 but when I start the webserver (it is a symfony project) and commandline confirms 'server running on localhost:8000' and try to connect to '192.168.1.5:8000' from the arduino it fails.

What am I doing wrong? Do I have to link the IP and the domain 'localhost' - is so, where?

Thanks a lot and best regards,
Steffen

答: Start the webserver with app/console server:run 0.0.0.0:8000</p>


问:
How to import csv with complex fields
I have the following line in a csv file

```<code>"\"xyz\"; blabla";"u98r34u98r3"
</code>```

This is supposed to contain two fields:

"\"xyz\"; blabla" and "u98r34u98r3"

I'm trying to import it with pandas.read_csv() on python 3.4.3 but it only gives three fields:

xyz", blabla" and u98r34u98r3

I tried my luck with options escapechar=, quotechar= and doublequote= without success.

//edit:

The problem was, that I extracted the specific piece and tried to parse it as string like this:

```<code>from io import StringIO
import pandas as pd
data = u'"\"xyz\"; blabla";"u98r34u98r3"'
pd.read_csv(StringIO(data), sep=";", escapechar="\\")
</code>```

But it worked when parsing the complete file.

答:
Works for me using sep=";" and escapechar="\\" in pandas 0.19.2:

```<code>In [27]: df = pd.read_csv("quote.csv", header=None, sep=";",  escapechar="\\")

In [28]: df
Out[28]:
               0            1
0  "xyz"; blabla  u98r34u98r3

In [29]: df.values
Out[29]: array([['"xyz"; blabla', 'u98r34u98r3']], dtype=object)
</code>```

Title: How to import csv with complex fields

Body:
I have the following line in a csv file

"\"xyz\"; blabla";"u98r34u98r3"

This is supposed to contain two fields:

"\"xyz\"; blabla" and "u98r34u98r3"

I'm trying to import it with pandas.read_csv() on python 3.4.3 but it only gives three fields:

xyz", blabla" and u98r34u98r3

I tried my luck with options escapechar=, quotechar= and doublequote= without success.

//edit:

The problem was, that I extracted the specific piece and tried to parse it as string like this:

from io import StringIO
import pandas as pd
data = u'"\"xyz\"; blabla";"u98r34u98r3"'
pd.read_csv(StringIO(data), sep=";", escapechar="\\")

But it worked when parsing the complete file.

Body:
Works for me using sep=";" and escapechar="\\" in pandas 0.19.2:

In [27]: df = pd.read_csv("quote.csv", header=None, sep=";",  escapechar="\\")

In [28]: df
Out[28]:
               0            1
0  "xyz"; blabla  u98r34u98r3

In [29]: df.values
Out[29]: array([['"xyz"; blabla', 'u98r34u98r3']], dtype=object)