问:
Extract image from ROI (OpenCV)
Given the following code (python)...

```<code># Import the modules
import cv2
from sklearn.externals import joblib
from skimage.feature import hog
import numpy as np
from scipy import ndimage
import PIL
from PIL import Image

# Load the classifier
clf = joblib.load("digits_cls.pkl")

# Read the input image
im = cv2.imread("C:\\Users\\Wkgrp\\Desktop\\test.jpg")

# Convert to grayscale and apply Gaussian filtering
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im_gray = cv2.GaussianBlur(im_gray, (5, 5), 0)

# Threshold the image
ret, im_th = cv2.threshold(im_gray, 90, 255, cv2.THRESH_BINARY_INV)

# Find contours in the image
image, ctrs, hier = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Get rectangles contains each contour
rects = [cv2.boundingRect(ctr) for ctr in ctrs]

# For each rectangular region, calculate HOG features and predict
# the digit using Linear SVM.
for rect in rects:
    # Draw the rectangles
    cv2.rectangle(im, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 255, 0), 3)
    # Make the rectangular region around the digit
    leng = int(rect[3] * 1.6)
    pt1 = int(rect[1] + rect[3] // 2 - leng // 2)
    pt2 = int(rect[0] + rect[2] // 2 - leng // 2)
    roi = im_th[pt1:pt1+leng, pt2:pt2+leng]
    # Resize the image
    roi = cv2.resize(roi, (28, 28), interpolation=cv2.INTER_AREA)
    roi = cv2.dilate(roi, (3, 3))

    # Calculate the HOG features - Number Recognition (Not to print...)
    #roi_hog_fd = hog(roi, orientations=9, pixels_per_cell=(14, 14), cells_per_block=(1, 1), visualise=False)
    #nbr = clf.predict(np.array([roi_hog_fd], 'float64'))
    #cv2.putText(im, str(int(nbr[0])), (rect[0], rect[1]),cv2.FONT_HERSHEY_DUPLEX, 2, (0, 255, 255), 3)

#cv2.imshow("Resulting Image with Rectangular ROIs", im)
#cv2.waitKey()
#cv2.imwrite("C:\\Users\\Wkgrp\\Desktop\\crop\\img_with_ROI.jpg",im)
#cv2.imwrite("C:\\Users\\Wkgrp\\Desktop\\crop\\img_threshold.jpg",im_th)
cv2.imwrite("C:\\Users\\Wkgrp\\Desktop\\crop\\.jpg",roi)

print("NO ERRORS")
</code>```

and the image used into...

Test Image

I can perform ROI and save it. The problem is that the code saves only the first digit (maybe because of the "for rects" at line 32).
What I have to modify to save all the chars recognized (that with the bounding box around)?

Also, think about 10 of the example image. I have to save all of them in a folder, each with the different filename (automatically). How to do it?

Thank you

答:
Here is a code that answer the request.
The only thing is that it doesn't order the chars in a specific way but how it recognize them.</p>

```<code># Import the modules
import cv2
from sklearn.externals import joblib
from skimage.feature import hog
import numpy as np
from scipy import ndimage
import PIL
from PIL import Image

# Load the classifier
clf = joblib.load("digits_cls.pkl")

# Read the input image
im = cv2.imread("C:\\Users\\Bob\\Desktop\\causale.jpg")

# Convert to grayscale and apply Gaussian filtering
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im_gray = cv2.GaussianBlur(im_gray, (5, 5), 0)

# Threshold the image
ret, im_th = cv2.threshold(im_gray, 90, 255, cv2.THRESH_BINARY_INV)

# Find contours in the image
image, ctrs, hier = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Get rectangles contains each contour
rects = [cv2.boundingRect(ctr) for ctr in ctrs]

idx =0

for ctr in ctrs:
    idx += 1
    x,y,w,h = cv2.boundingRect(ctr)
    roi=im[y:y+h,x:x+w]
    cv2.imwrite('C:\\Users\\Bob\\Desktop\\crop\\' + str(idx) + '.jpg', roi)
    #cv2.rectangle(im,(x,y),(x+w,y+h),(200,0,0),2)
    #cv2.imshow('img',roi)
    #cv2.waitKey(0)

'''
# For each rectangular region, calculate HOG features and predict
# the digit using Linear SVM.
for rect in rects:
    # Draw the rectangles
    cv2.rectangle(im, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 255, 0), 3)
    # Make the rectangular region around the digit
    leng = int(rect[3] * 1.6)
    pt1 = int(rect[1] + rect[3] // 2 - leng // 2)
    pt2 = int(rect[0] + rect[2] // 2 - leng // 2)
    roi = im_th[pt1:pt1+leng, pt2:pt2+leng]
    # Resize the image
    roi = cv2.resize(roi, (28, 28), interpolation=cv2.INTER_AREA)
    roi = cv2.dilate(roi, (3, 3))

'''

    # Calculate the HOG features - Number Recognition (Not to print...)
    #roi_hog_fd = hog(roi, orientations=9, pixels_per_cell=(14, 14), cells_per_block=(1, 1), visualise=False)
    #nbr = clf.predict(np.array([roi_hog_fd], 'float64'))
    #cv2.putText(im, str(int(nbr[0])), (rect[0], rect[1]),cv2.FONT_HERSHEY_DUPLEX, 2, (0, 255, 255), 3)

#cv2.imshow("Resulting Image with Rectangular ROIs", im)
#cv2.waitKey()
#cv2.imwrite("C:\\Users\\Bob\\Desktop\\crop\\img_with_ROI.jpg",im)
#cv2.imwrite("C:\\Users\\Bob\\Desktop\\crop\\img_threshold.jpg",im_th)
#cv2.imwrite("C:\\Users\\Bob\\Desktop\\crop\\.jpg",roi)

print("NO ERRORS")
</code>```

Title: Extract image from ROI (OpenCV)

Body:
Given the following code (python)...

# Import the modules
import cv2
from sklearn.externals import joblib
from skimage.feature import hog
import numpy as np
from scipy import ndimage
import PIL
from PIL import Image

# Load the classifier
clf = joblib.load("digits_cls.pkl")

# Read the input image
im = cv2.imread("C:\\Users\\Wkgrp\\Desktop\\test.jpg")

# Convert to grayscale and apply Gaussian filtering
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im_gray = cv2.GaussianBlur(im_gray, (5, 5), 0)

# Threshold the image
ret, im_th = cv2.threshold(im_gray, 90, 255, cv2.THRESH_BINARY_INV)

# Find contours in the image
image, ctrs, hier = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Get rectangles contains each contour
rects = [cv2.boundingRect(ctr) for ctr in ctrs]

# For each rectangular region, calculate HOG features and predict
# the digit using Linear SVM.
for rect in rects:
    # Draw the rectangles
    cv2.rectangle(im, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 255, 0), 3)
    # Make the rectangular region around the digit
    leng = int(rect[3] * 1.6)
    pt1 = int(rect[1] + rect[3] // 2 - leng // 2)
    pt2 = int(rect[0] + rect[2] // 2 - leng // 2)
    roi = im_th[pt1:pt1+leng, pt2:pt2+leng]
    # Resize the image
    roi = cv2.resize(roi, (28, 28), interpolation=cv2.INTER_AREA)
    roi = cv2.dilate(roi, (3, 3))

    # Calculate the HOG features - Number Recognition (Not to print...)
    #roi_hog_fd = hog(roi, orientations=9, pixels_per_cell=(14, 14), cells_per_block=(1, 1), visualise=False)
    #nbr = clf.predict(np.array([roi_hog_fd], 'float64'))
    #cv2.putText(im, str(int(nbr[0])), (rect[0], rect[1]),cv2.FONT_HERSHEY_DUPLEX, 2, (0, 255, 255), 3)

#cv2.imshow("Resulting Image with Rectangular ROIs", im)
#cv2.waitKey()
#cv2.imwrite("C:\\Users\\Wkgrp\\Desktop\\crop\\img_with_ROI.jpg",im)
#cv2.imwrite("C:\\Users\\Wkgrp\\Desktop\\crop\\img_threshold.jpg",im_th)
cv2.imwrite("C:\\Users\\Wkgrp\\Desktop\\crop\\.jpg",roi)

print("NO ERRORS")

and the image used into...

Test Image

I can perform ROI and save it. The problem is that the code saves only the first digit (maybe because of the "for rects" at line 32).
What I have to modify to save all the chars recognized (that with the bounding box around)?

Also, think about 10 of the example image. I have to save all of them in a folder, each with the different filename (automatically). How to do it?

Thank you

Body:
Here is a code that answer the request.
The only thing is that it doesn't order the chars in a specific way but how it recognize them.

# Import the modules
import cv2
from sklearn.externals import joblib
from skimage.feature import hog
import numpy as np
from scipy import ndimage
import PIL
from PIL import Image

# Load the classifier
clf = joblib.load("digits_cls.pkl")

# Read the input image
im = cv2.imread("C:\\Users\\Bob\\Desktop\\causale.jpg")

# Convert to grayscale and apply Gaussian filtering
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im_gray = cv2.GaussianBlur(im_gray, (5, 5), 0)

# Threshold the image
ret, im_th = cv2.threshold(im_gray, 90, 255, cv2.THRESH_BINARY_INV)

# Find contours in the image
image, ctrs, hier = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Get rectangles contains each contour
rects = [cv2.boundingRect(ctr) for ctr in ctrs]

idx =0

for ctr in ctrs:
    idx += 1
    x,y,w,h = cv2.boundingRect(ctr)
    roi=im[y:y+h,x:x+w]
    cv2.imwrite('C:\\Users\\Bob\\Desktop\\crop\\' + str(idx) + '.jpg', roi)
    #cv2.rectangle(im,(x,y),(x+w,y+h),(200,0,0),2)
    #cv2.imshow('img',roi)
    #cv2.waitKey(0)

'''
# For each rectangular region, calculate HOG features and predict
# the digit using Linear SVM.
for rect in rects:
    # Draw the rectangles
    cv2.rectangle(im, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 255, 0), 3)
    # Make the rectangular region around the digit
    leng = int(rect[3] * 1.6)
    pt1 = int(rect[1] + rect[3] // 2 - leng // 2)
    pt2 = int(rect[0] + rect[2] // 2 - leng // 2)
    roi = im_th[pt1:pt1+leng, pt2:pt2+leng]
    # Resize the image
    roi = cv2.resize(roi, (28, 28), interpolation=cv2.INTER_AREA)
    roi = cv2.dilate(roi, (3, 3))

'''

    # Calculate the HOG features - Number Recognition (Not to print...)
    #roi_hog_fd = hog(roi, orientations=9, pixels_per_cell=(14, 14), cells_per_block=(1, 1), visualise=False)
    #nbr = clf.predict(np.array([roi_hog_fd], 'float64'))
    #cv2.putText(im, str(int(nbr[0])), (rect[0], rect[1]),cv2.FONT_HERSHEY_DUPLEX, 2, (0, 255, 255), 3)

#cv2.imshow("Resulting Image with Rectangular ROIs", im)
#cv2.waitKey()
#cv2.imwrite("C:\\Users\\Bob\\Desktop\\crop\\img_with_ROI.jpg",im)
#cv2.imwrite("C:\\Users\\Bob\\Desktop\\crop\\img_threshold.jpg",im_th)
#cv2.imwrite("C:\\Users\\Bob\\Desktop\\crop\\.jpg",roi)

print("NO ERRORS")


来源: stackexchange

问:
Python Tkinter (Beginner level)
I need some help over here!

```<code>import tkinter as tk

class CountVisitors:
    def __int__(self, master):
        self.master = master

        self.button1 = tk.Button(self.master, text="Count", command=self.counting)

        self.button1.pack(side=tk.LEFT)

        self.button_click = 0

    def counting(self):
        self.button_click += 1
        print(self.button_click)

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

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

when I try to run this code, it prompts me an error message:

```<code>Traceback (most recent call last):
    File "C:/Users/Anson/PycharmProjects/improvement/improvement.py", line 26, in <module> main()
    File "C:/Users/Anson/PycharmProjects/improvement/improvement.py", line 21, in main CountVisitors(root)
    TypeError: object() takes no parameters
</code>```

What does it mean?

答:
Your __init__ is misspelled (missing an 'i').

change the line:

```<code>def __int__(self, master):
</code>```

to:

```<code>def __init__(self, master):
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python Tkinter (Beginner level)

Body:
I need some help over here!

import tkinter as tk

class CountVisitors:
    def __int__(self, master):
        self.master = master

        self.button1 = tk.Button(self.master, text="Count", command=self.counting)

        self.button1.pack(side=tk.LEFT)

        self.button_click = 0

    def counting(self):
        self.button_click += 1
        print(self.button_click)

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

if __name__ == "__main__":
    main()

when I try to run this code, it prompts me an error message:

Traceback (most recent call last):
    File "C:/Users/Anson/PycharmProjects/improvement/improvement.py", line 26, in <module> main()
    File "C:/Users/Anson/PycharmProjects/improvement/improvement.py", line 21, in main CountVisitors(root)
    TypeError: object() takes no parameters

What does it mean?

Body:
Your __init__ is misspelled (missing an 'i').

change the line:

def __int__(self, master):

to:

def __init__(self, master):


问:
How to use sql to select an element based on the result of another query
I have two tables, TABLE_1  and TABLE_2.

```<code>TABLE_1 : Line_id | Fail_id
              1        2
              2        3
TABLE_2 : Fail_id | Fail_reason
              1       "nrc"
              2       "lkc"
              3       "llc"
</code>```

How do I get Fail_resason for Line_id = 1 using a single query?I can do this using two queries but I have to use only 1 query.
Please help.

答:
Try below query. This will give you output for all records. You can add WHERE condition if you need to filter output for specific Line_id.

```<code>SELECT t1.Line_id, t2.Fail_reason
 FROM TABLE_1 t1 JOIN TABLE_2 t2 ON t1.Fail_id = t2.Fail_id;
</code>```

Body:
I have two tables, TABLE_1  and TABLE_2.

TABLE_1 : Line_id | Fail_id
              1        2
              2        3
TABLE_2 : Fail_id | Fail_reason
              1       "nrc"
              2       "lkc"
              3       "llc"

How do I get Fail_resason for Line_id = 1 using a single query?I can do this using two queries but I have to use only 1 query.
Please help.

Body:
Try below query. This will give you output for all records. You can add WHERE condition if you need to filter output for specific Line_id.

SELECT t1.Line_id, t2.Fail_reason
 FROM TABLE_1 t1 JOIN TABLE_2 t2 ON t1.Fail_id = t2.Fail_id;


问:
json_encode can not escape single quotation marks?
```<code>$emailFields =  array(
    array(
        'name' => 'comments',
        'type' => 'html',
        'content' => "ahfsd\jfh/sf's askghaskg sadf"
    ),
);
echo json_encode($emailFields);
</code>```

The print is

```<code>[{
    "name": "comments",
    "type": "html",
    "content": "ahfsd\\jfh/sf's askghaskg sadf"
}]
</code>```

Why the json_encode can not escape the '?

答:
If you would like to convert any ` to \u0027 you can do it by using the following code:

```<code>json_encode($emailFields, JSON_HEX_APOS)
</code>```

Or you can map your array and escape the apostrophe on each value.
I'm not sure what you're trying to achieve and why you want to escape it, but I gave you some tools and you will decide by your self.

Body:
$emailFields =  array(
    array(
        'name' => 'comments',
        'type' => 'html',
        'content' => "ahfsd\jfh/sf's askghaskg sadf"
    ),
);
echo json_encode($emailFields);

The print is

[{
    "name": "comments",
    "type": "html",
    "content": "ahfsd\\jfh/sf's askghaskg sadf"
}]

Why the json_encode can not escape the '?

Body:
If you would like to convert any ` to \u0027 you can do it by using the following code:

json_encode($emailFields, JSON_HEX_APOS)

Or you can map your array and escape the apostrophe on each value.
I'm not sure what you're trying to achieve and why you want to escape it, but I gave you some tools and you will decide by your self.


问:
How to dynamically populate ExpandableListView through user input?
I'm building a GPA tracker app and I find that an ExpandableListView is the most appropriate thing to use.  The function is this:

The user clicks on a FAB button and adds a Semester (group/header).
The user clicks on the generated Semester (group/header) and adds a course.

I can add the groups but I couldn't figure out how to dynamically add children for those groups.  Basically, I want to get the ID of the clicked group, start an alertDialog to have the user input the course information and add that information to a List.

I tried to do that with the setOnGroupClickListener(new ExpandableListView.OnGroupClickListener()) method but now I can't expand the group.  This wasn't my final implementation anyways.  I really just wanted to get this logic to work.

These are the Lists and HashMaps that contain my Semester and Course information:

```<code>public class MainActivity extends Activity {

    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader = new ArrayList<>();
    HashMap<String, List<String>> listDataChild = new HashMap<String, List<String>>();
    List<String>listCourses = new ArrayList<>();
    private String semester, course;
</code>```

This is where I am adding my Semesters (group/header)

```<code>private void addSemester() {
        View dialogView = LayoutInflater.from(MainActivity.this).inflate(R.layout.parent_dialog_layout, null);
        final EditText et_semester = (EditText)dialogView.findViewById(R.id.et_semester);

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Create A Semester");
        builder.setView(dialogView);
        builder.setCancelable(false);

        builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                semester = et_semester.getText().toString();
                listDataHeader.add(semester);
            }
        });

        builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        listAdapter.notifyDataSetChanged();
        builder.show();
    }
</code>```

And in my onCreate(), I'm calling my setOnGroupClickListener method to add the children:

```<code>expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, final int groupPosition, long id) {
                parent.smoothScrollToPosition(groupPosition);

                View dialogView = LayoutInflater.from(MainActivity.this).inflate(R.layout.child_dialog_layout, null);
                final EditText et_course = (EditText)dialogView.findViewById(R.id.et_course);

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Create A Course");
                builder.setView(dialogView);
                builder.setCancelable(false);

                builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        course = et_course.getText().toString();
                        listDataChild.put(listDataHeader.get(groupPosition), listCourses);
                    }
                });

                builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                listAdapter.notifyDataSetChanged();
                builder.show();

                return true;
            }

            });
        listAdapter.notifyDataSetChanged();
        }
</code>```

I want to access the clicked group's ID and then add my children to that group.

答:
call notifyDataSetChanged(); inside your Dialog's interface OnClickListener:

```<code>                builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    course = et_course.getText().toString();
                    listDataChild.put(listDataHeader.get(groupPosition), listCourses);
                    notifyDataSetChanged();
                }
            });
</code>```

Body:
I'm building a GPA tracker app and I find that an ExpandableListView is the most appropriate thing to use.  The function is this:

The user clicks on a FAB button and adds a Semester (group/header).
The user clicks on the generated Semester (group/header) and adds a course.

I can add the groups but I couldn't figure out how to dynamically add children for those groups.  Basically, I want to get the ID of the clicked group, start an alertDialog to have the user input the course information and add that information to a List.

I tried to do that with the setOnGroupClickListener(new ExpandableListView.OnGroupClickListener()) method but now I can't expand the group.  This wasn't my final implementation anyways.  I really just wanted to get this logic to work.

These are the Lists and HashMaps that contain my Semester and Course information:

public class MainActivity extends Activity {

    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader = new ArrayList<>();
    HashMap<String, List<String>> listDataChild = new HashMap<String, List<String>>();
    List<String>listCourses = new ArrayList<>();
    private String semester, course;

This is where I am adding my Semesters (group/header)

private void addSemester() {
        View dialogView = LayoutInflater.from(MainActivity.this).inflate(R.layout.parent_dialog_layout, null);
        final EditText et_semester = (EditText)dialogView.findViewById(R.id.et_semester);

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Create A Semester");
        builder.setView(dialogView);
        builder.setCancelable(false);

        builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                semester = et_semester.getText().toString();
                listDataHeader.add(semester);
            }
        });

        builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        listAdapter.notifyDataSetChanged();
        builder.show();
    }

And in my onCreate(), I'm calling my setOnGroupClickListener method to add the children:

expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, final int groupPosition, long id) {
                parent.smoothScrollToPosition(groupPosition);

                View dialogView = LayoutInflater.from(MainActivity.this).inflate(R.layout.child_dialog_layout, null);
                final EditText et_course = (EditText)dialogView.findViewById(R.id.et_course);

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Create A Course");
                builder.setView(dialogView);
                builder.setCancelable(false);

                builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        course = et_course.getText().toString();
                        listDataChild.put(listDataHeader.get(groupPosition), listCourses);
                    }
                });

                builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                listAdapter.notifyDataSetChanged();
                builder.show();

                return true;
            }

            });
        listAdapter.notifyDataSetChanged();
        }

I want to access the clicked group's ID and then add my children to that group.

Body:
call notifyDataSetChanged(); inside your Dialog's interface OnClickListener:

                builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    course = et_course.getText().toString();
                    listDataChild.put(listDataHeader.get(groupPosition), listCourses);
                    notifyDataSetChanged();
                }
            });


问:
Package inputenc Error: Unicode char \u8:β not set up for use with LaTeX
One of my references in Bibdesk contains some latin/Greek character e.g. 'β'. I am getting the error while using the reference in TEXMAKER:
"! Package inputenc Error: Unicode char \u8:β not set up for use with LaTeX."

How can I set it up to work?

答:
Another solution is to use XeTeX, which is more suitable than most other TeX engines for unicode : replace the lines

```<code>\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
</code>```

with

```<code>\usepackage{fontspec}
</code>```

Body:
Another solution is to use XeTeX, which is more suitable than most other TeX engines for unicode : replace the lines

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

with

\usepackage{fontspec}


问:
How should a list be represented in XML?
In XML, how should a list be represented?

With an enclosing list entity:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>
</code>```

Or without:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>
</code>```

答:
IMHO, it depends on the domain.

For the example you gave, I would use the entity to enclose the children, because the children themselves are not necessarily properties of the person, but the list of children is.

Additionally, using an enclosure will help if you ever need to serialize/deserialize.

OwnerDisplayName: Mat

ContentLicense: CC BY-SA 2.5

Body:
In XML, how should a list be represented?

With an enclosing list entity:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>

Or without:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>

OwnerDisplayName: Daniel Schaffer


问:
How to hide console output from Select-AzureRmSubscription
Does anyone know how to hide output from command Select-AzureRmSubscription inside azure workbook which runs as powershell workflow

Thanks

答:
You can use Out-Null. Works for any PowerShell cmdlet.

```<code>Select-AzureRmSubscription | Out-null
</code>```

The Out-Null cmdlet sends its output to NULL, in effect, removing it
  from the pipeline and preventing the output to be displayed at the
  screen.

https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/out-null

Body:
You can use Out-Null. Works for any PowerShell cmdlet.

Select-AzureRmSubscription | Out-null

The Out-Null cmdlet sends its output to NULL, in effect, removing it
  from the pipeline and preventing the output to be displayed at the
  screen.

https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/out-null


问:
How do I get the Rust compiler to dump out the LLVM it generates?
I'd like to see the LLVM that the Rust compiler generates. Even better would be to have it just dump out LLVM and stop. This could be in bitcode format or assembler text. </p>

答:
You can manipulate the RUSTFLAGS environment variable and then perform the build, something like

```<code>RUSTFLAGS="--emit=llvm-ir" cargo build
</code>```

This is useful if you have no direct access to the build command (e.g., when you are building something like Servo, which uses an abstracted build tool called mach).

I know this is more of an edge case, but I found it useful when trying to obtain an IR dump of Servo's code.

Body:
You can manipulate the RUSTFLAGS environment variable and then perform the build, something like

RUSTFLAGS="--emit=llvm-ir" cargo build

This is useful if you have no direct access to the build command (e.g., when you are building something like Servo, which uses an abstracted build tool called mach).

I know this is more of an edge case, but I found it useful when trying to obtain an IR dump of Servo's code.


问:
Center a title but subtitle is center "right"
I need to center a title and in the next line, i have to write a subtitle that ends at the right of the title. Example:

```<code>                     Here is my title
                             subtitle
</code>```

Could someone help me?

答:
I think you would want the two in the same div, but then style them separately.

So something like...

```<code><div>
    <h1 style="text-align: center">Here's my title</h1>
    <br>
    <h3 style="text-align: right">My subtitle</h3>
</div>
</code>```

Note that the size of the div is important, because if it is defined to be the whole length of the browser, this will look really weird. Hopefully this helps.

Body:
I need to center a title and in the next line, i have to write a subtitle that ends at the right of the title. Example:

                     Here is my title
                             subtitle

Could someone help me?

Body:
I think you would want the two in the same div, but then style them separately.

So something like...

<div>
    <h1 style="text-align: center">Here's my title</h1>
    <br>
    <h3 style="text-align: right">My subtitle</h3>
</div>

Note that the size of the div is important, because if it is defined to be the whole length of the browser, this will look really weird. Hopefully this helps.


问:
cannot reslove symbol 'android'
I have written this code in my MapsActivity.java
In code android appears in red color and shows cannot resolve symbol 'android'.</p>

```<code>import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
</code>```

答:
You need to install Google Play services sdk.
In Android Studio, go to Tools->Android->Sdk Manager->Sdk Tools, then
select Google Play Services and hit apply, then rebuild your project.</p>

Title: cannot reslove symbol 'android'

Body:
I have written this code in my MapsActivity.java
In code android appears in red color and shows cannot resolve symbol 'android'.

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;


问:
RecyclerView scrollToPosition not trigger scrollListener
I'm using RecyclerView, with ScrollListener:

```<code>mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener()
{
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState)
        {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            super.onScrolled(recyclerView, dx, dy);
            // Do my logic
        }
 });
</code>```

When I scroll with the finger, the scroll listener triggered fine.

But when I scroll progrematically, like that:

```<code>mRecyclerView.scrollToPosition(LAST_POSITION);
</code>```

The scroll listener is not triggered.

答:
To explicitly trigger onScrollListener over recycler view use:</p>

```<code>recyclerView.smoothScrollBy(x, y);
//x is the horizontal displacement and y is vertical displacement.
</code>```

Body:
I'm using RecyclerView, with ScrollListener:

mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener()
{
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState)
        {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            super.onScrolled(recyclerView, dx, dy);
            // Do my logic
        }
 });

When I scroll with the finger, the scroll listener triggered fine.

But when I scroll progrematically, like that:

mRecyclerView.scrollToPosition(LAST_POSITION);

The scroll listener is not triggered.

Body:
To explicitly trigger onScrollListener over recycler view use:

recyclerView.smoothScrollBy(x, y);
//x is the horizontal displacement and y is vertical displacement.


问:
Microsoft T-SQL to Oracle SQL translation
I've worked with T-SQL for years but I've just moved to an organisation that is going to require writing some Oracle stuff, probably just simple CRUD operations at least until I find my feet. I'm not going to be migrating databases from one to the other simply interacting with existing Oracle databases from an Application Development perspective. Is there are tool or utility available to easily translate T-SQL into Oracle SQL, a keyword mapper is the sort of thing I'm looking for.

P.S. I'm too lazy to RTFM, besides it's not going to be a big part of my role so I just want something to get me up to speed a little faster.

答:
In Oracle SQL Developer, there is a tool called Translation Scratch Editor. You can find it from Tools > Migration.

The Oracle SQL Developer is a free download from Oracle and it is an easy install.

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Michael Prewecki


问:
How do I remove JSON form JSON array with repeated key-value
I have a JSON as follows:

```<code>[{"name": "John", "id": 1},
 {"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]
</code>```

I want to first identify if key "id" has same value. If yes, I want to remove previous JSON with the same "id" so that I get following JSON with unique "id" values in the JSON Array.

```<code>[{"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]
</code>```

How do I achieve this in javascript?

答:
Use Following code. This will solve your problem

    var obj = [{"name": "John", "id": 1}, {"name": "Don", "id": 2}, {"name": "Tom", "id": 3}, {"name": "NewJohn", "id": 1}, {"name": "Tim", "id": 4}];
        var seenNames = {};

    obj = obj.reverse().filter(function(currentObject) {
        if (currentObject.id in seenNames) {
            return false;
        } else {
            seenNames[currentObject.id] = true;
            return true;
        }
    });

    console.log(obj)```

Body:
I have a JSON as follows:

[{"name": "John", "id": 1},
 {"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]

I want to first identify if key "id" has same value. If yes, I want to remove previous JSON with the same "id" so that I get following JSON with unique "id" values in the JSON Array.

[{"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]

How do I achieve this in javascript?


问:
Libgdx android resize and create lifecycle
I am creating a live wallpaper with libgdx. On the create method I init all the things that I want use later.

But when the screen rotates the create method run again and all the things. Is it any way to cache that loaded things to load only once?

答:
You could check if the objects exist in the create method and only if they don't already exist create them. E.g</p>

```<code>if(gameObject == null){
    gameObject = new GameObject(params);
}
</code>```

Body:
You could check if the objects exist in the create method and only if they don't already exist create them. E.g

if(gameObject == null){
    gameObject = new GameObject(params);
}


问:
Jmeter- Load testing EC2 instance, only 50% request are successful
I am trying to load test Nginx installed on an EC2 instance via Jmeter, Everytime I try to load test, only 50% request are successful,

```<code>For Eg:

If I try with 10 users, only 5 response are OK
If I try with 100 users, only 50 response are OK
If I try with 500, only 250 response are OK
</code>```

Any Idea, regarding this strange behavior?

答:
This sounds weird. I would recommend the following troubleshooting techniques:

First of all always check jmeter.log file, it should contain enough information to get to the bottom of your test failure(s).

If JMeter log file doesn't contain any suspicious entries next step would be checking response messages using i.e. View Results In Table and/or View Results Tree listener. This should provide you some high-level information and trends, i.e. you will be able to see if some particular sampler(s) is(are) always failing.

If above steps don't give enough clue to resolve your issue you can temporary enable saving of request and response data to see what is wrong with the failing sampler(s). Add the next lines to user.properties file (located in JMeter's "bin" folder)

```<code>jmeter.save.saveservice.output_format=xml
jmeter.save.saveservice.response_data=true
jmeter.save.saveservice.samplerData=true
jmeter.save.saveservice.requestHeaders=true
jmeter.save.saveservice.responseHeaders=true
jmeter.save.saveservice.url=true
</code>```

and next time your run JMeter test the .jtl results file will contain all the relevant data which can be analyzed using aforementioned View Results Tree listener. Don't forget to revert the change once you fix the script as JMeter listeners are very resource intensive per se and above settings greatly increase disk IO and it may ruin your test.

If none of above helps - check logs on the application under test side, most probably you will get something from them.

Body:
I am trying to load test Nginx installed on an EC2 instance via Jmeter, Everytime I try to load test, only 50% request are successful,

For Eg:

If I try with 10 users, only 5 response are OK
If I try with 100 users, only 50 response are OK
If I try with 500, only 250 response are OK

Any Idea, regarding this strange behavior?

Body:
This sounds weird. I would recommend the following troubleshooting techniques:

First of all always check jmeter.log file, it should contain enough information to get to the bottom of your test failure(s).

If JMeter log file doesn't contain any suspicious entries next step would be checking response messages using i.e. View Results In Table and/or View Results Tree listener. This should provide you some high-level information and trends, i.e. you will be able to see if some particular sampler(s) is(are) always failing.

If above steps don't give enough clue to resolve your issue you can temporary enable saving of request and response data to see what is wrong with the failing sampler(s). Add the next lines to user.properties file (located in JMeter's "bin" folder)

jmeter.save.saveservice.output_format=xml
jmeter.save.saveservice.response_data=true
jmeter.save.saveservice.samplerData=true
jmeter.save.saveservice.requestHeaders=true
jmeter.save.saveservice.responseHeaders=true
jmeter.save.saveservice.url=true

and next time your run JMeter test the .jtl results file will contain all the relevant data which can be analyzed using aforementioned View Results Tree listener. Don't forget to revert the change once you fix the script as JMeter listeners are very resource intensive per se and above settings greatly increase disk IO and it may ruin your test.

If none of above helps - check logs on the application under test side, most probably you will get something from them.


问:
Get clean ids by regex
i need your help again ;-)

How can i extract ids from given string:

```<code>",object|1301,object|5419,object|5364,"
</code>```

Can it solved by a regular expression?

Thank for answers

答:
A Regex Method: Demo

```<code>$in = ",object|1301,object|5419,object|5364,";
var_export(preg_split('/\D+/', $in, 0, PREG_SPLIT_NO_EMPTY));
</code>```

Output:

```<code>array (
  0 => '1301',
  1 => '5419',
  2 => '5364',
)
</code>```

A non-regex method (there will be many ways to do this):

```<code>$in=",object|1301,object|5419,object|5364,";
var_export(array_filter(explode(',object|', rtrim($in, ',')), 'strlen'));
</code>```

(same output)

A preg_match_all() method:

```<code>$in = ",object|1301,object|5419,object|5364,";
var_export(preg_match_all('/\K\d+/', $in, $out) ? $out[0] : []);
</code>```

(same output)

--

Another non-regex method:

```<code>$in = ",object|1301,object|5419,object|5364,";
var_export(explode('|', ltrim(str_replace(',object', '', $in), '|')));
</code>```

(same output)

Title: Get clean ids by regex

Body:
i need your help again ;-)

How can i extract ids from given string:

",object|1301,object|5419,object|5364,"

Can it solved by a regular expression?

Thank for answers

Body:
A Regex Method: Demo

$in = ",object|1301,object|5419,object|5364,";
var_export(preg_split('/\D+/', $in, 0, PREG_SPLIT_NO_EMPTY));

Output:

array (
  0 => '1301',
  1 => '5419',
  2 => '5364',
)

A non-regex method (there will be many ways to do this):

$in=",object|1301,object|5419,object|5364,";
var_export(array_filter(explode(',object|', rtrim($in, ',')), 'strlen'));

(same output)

A preg_match_all() method:

$in = ",object|1301,object|5419,object|5364,";
var_export(preg_match_all('/\K\d+/', $in, $out) ? $out[0] : []);

(same output)

--

Another non-regex method:

$in = ",object|1301,object|5419,object|5364,";
var_export(explode('|', ltrim(str_replace(',object', '', $in), '|')));

(same output)


问:
In Xul, how do I make a XPCOM component call a javascript function?
I want to implement a listener/observer for my XPCOM component, so my javascript code can register to be notified of some events. Is it possible?</p>

答: If I understand you correctly https://developer.mozilla.org/en/Creating_JavaScript_callbacks_in_components might be just the thing you are looking for.</p>


问:
Restrict django FloatField to 2 decimal places
I am looking for a way to limit the FloatField in Django to 2 decimal places has anyone got a clue of how this could be done without having to use a DecimalField.

I tried decimal_places=2but this was just giving me a migration error within the float field so i am thinking this method must only work within DecimalFields.

答:
Since Django 1.8+ you can use a custom validator for FloatField/or any ModelFields:

```<code>def validate_decimals(value):
    try:
        return round(float(value), 2)
    except:
        raise ValidationError(
            _('%(value)s is not an integer or a float  number'),
            params={'value': value},
        )
</code>```

...and in your model you can apply it like this:

```<code>from django.db import models

class MyModel(models.Model):
    even_field = models.FloatField(validators=[validate_decimals])
</code>```

Body:
Since Django 1.8+ you can use a custom validator for FloatField/or any ModelFields:

def validate_decimals(value):
    try:
        return round(float(value), 2)
    except:
        raise ValidationError(
            _('%(value)s is not an integer or a float  number'),
            params={'value': value},
        )

...and in your model you can apply it like this:

from django.db import models

class MyModel(models.Model):
    even_field = models.FloatField(validators=[validate_decimals])


问:
Understanding how to do JUnit testing with Mockito doReturn/when for the methods with return type void
Suppose, I have a test class with two methods as follows:

```<code>public class TestClass {
   @Mock
   TestClass testObject;

   @Test
   public void method1() {
      doReturn("str").when(testObject).method2();

      String s1 = testObject.method2(); // This line gives compilation
      //error. Type mismatch cannot convert from void to string
   }

   @Test
   public void method2() {
   }
</code>```

I am basically trying to mock method2 which is a dependency in method1.

But as you can see, the method2 return type is void. So, I am using doReturn to mock it.

As far as my understanding goes, although the method2 's return type is void, after I mock it, the mocked version of method2 should return String type.

But, as I have commented in method1, it is giving type mismatch.

答:
You are simply getting mocking wrong.

Mocking means: instead of create "real" objects of a specific class, you create a stub/dummy/mock that looks like an object of that class. But in reality - it is not.

Beyond that: mocking can not change the signature of a method. So your idea that you could somehow use mocking to have a void method return something is wrong.

You are simply going down the wrong rabbit hole - what you intend to is not possible.

Body:
Suppose, I have a test class with two methods as follows:

public class TestClass {
   @Mock
   TestClass testObject;

   @Test
   public void method1() {
      doReturn("str").when(testObject).method2();

      String s1 = testObject.method2(); // This line gives compilation
      //error. Type mismatch cannot convert from void to string
   }

   @Test
   public void method2() {
   }

I am basically trying to mock method2 which is a dependency in method1.

But as you can see, the method2 return type is void. So, I am using doReturn to mock it.

As far as my understanding goes, although the method2 's return type is void, after I mock it, the mocked version of method2 should return String type.

But, as I have commented in method1, it is giving type mismatch.


答:
Use the pattern ([0-9]+) to get the numbers from the string.

Example: https://regex101.com/r/6Unuvt/1/

Title: Get clean ids by regex


问:
How to run integration task after run task in gradle?
My Application is Spring boot application exposing some rest api

To run  my integration tests , , first the application need to be up and running , as my application gradle based , how to make sure when i execute  gradle command from command prompt , first application run and the integration tests will run .

```<code>task integration(type: Test, description: 'Runs the integration tests.', group: 'Verification') {
    testClassesDir = sourceSets.integration.output.classesDir
    classpath = sourceSets.integration.runtimeClasspath
    outputs.upToDateWhen { false }
}

task appRunAndIntegrtationTest {
    dependsOn 'run'
    dependsOn 'integration'
    tasks.findByName('integration').mustRunAfter 'run'
}
</code>```

i added above code to build.gradle , but application up and running , thats it , it stayed their only , integration tests are not running , can anyone has idea on this please .

update : @Strelok , as mentioned , the application started up and integration task is not running .

update 1 : i found one gradle plugin

https://github.com/marc0der/gradle-spawn-plugin

i am trying to use like below

```<code>task startServer(type: SpawnProcessTask, dependsOn: 'assemble') {
    command "java -jar ${projectDir}/build/libs/example.jar"
    ready 'Started Application'
}

task stopServer(type: KillProcessTask)
</code>```

but am getting below exception

*> Could not get unknown property 'SpawnProcessTask' for root project 'example-api' of type org.gradle.api.Project.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.*

please someone please suggest on this

答:
You should declare that the integration test task needs to depend on your app run task.

appRun is just an example please use the name of the task that is the precursor for the integration test.

```<code>integration.dependsOn appRun
integration.mustRunAfter appRun
</code>```

Also, it might be like your app is running and blocking the progress of your Gradle build, does the build actually finish or it just hangs until the app stops running?

Body:
My Application is Spring boot application exposing some rest api

To run  my integration tests , , first the application need to be up and running , as my application gradle based , how to make sure when i execute  gradle command from command prompt , first application run and the integration tests will run .

task integration(type: Test, description: 'Runs the integration tests.', group: 'Verification') {
    testClassesDir = sourceSets.integration.output.classesDir
    classpath = sourceSets.integration.runtimeClasspath
    outputs.upToDateWhen { false }
}

task appRunAndIntegrtationTest {
    dependsOn 'run'
    dependsOn 'integration'
    tasks.findByName('integration').mustRunAfter 'run'
}

i added above code to build.gradle , but application up and running , thats it , it stayed their only , integration tests are not running , can anyone has idea on this please .

update : @Strelok , as mentioned , the application started up and integration task is not running .

update 1 : i found one gradle plugin

https://github.com/marc0der/gradle-spawn-plugin

i am trying to use like below

task startServer(type: SpawnProcessTask, dependsOn: 'assemble') {
    command "java -jar ${projectDir}/build/libs/example.jar"
    ready 'Started Application'
}

task stopServer(type: KillProcessTask)

but am getting below exception

*> Could not get unknown property 'SpawnProcessTask' for root project 'example-api' of type org.gradle.api.Project.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.*

please someone please suggest on this

Body:
You should declare that the integration test task needs to depend on your app run task.

appRun is just an example please use the name of the task that is the precursor for the integration test.

integration.dependsOn appRun
integration.mustRunAfter appRun

Also, it might be like your app is running and blocking the progress of your Gradle build, does the build actually finish or it just hangs until the app stops running?


问:
Is css-loader neccessary if you use postcss-loader with appropriate plugins?
I'm using postcss-import to take care of my imports, and cssnano to minify. In my Webpack config I've been using the following setup for css-loader...

```<code>{
  loader: 'css-loader',
  options: {
    url: false,
    import: false,
    minimize: false,
    importLoaders: 1,
    souceMap: true,
  }
}
</code>```

...but when I remove that everything still seems to load fine, so now I just have post-css before style-loader. Can I safely omit css-loader from my css build, or is there some other functionality it provides that is necessary? I've yet to see a webpack.config.js file that doesn't use css-loader, so I want to be cautious here! :)

答:
css-loader basically enables webpack to build your dependencies tree by following the dependencies declared as @import and url() in you CSS files.

From css-loader docs:

The css-loader interprets @import and url() like import/require() and will resolve them.

Since postcss-import handles CSS @imports, you will still need css-loader to bundle any other static asset imported by your stylesheets like images, fonts, etc...

Body:
I'm using postcss-import to take care of my imports, and cssnano to minify. In my Webpack config I've been using the following setup for css-loader...

{
  loader: 'css-loader',
  options: {
    url: false,
    import: false,
    minimize: false,
    importLoaders: 1,
    souceMap: true,
  }
}

...but when I remove that everything still seems to load fine, so now I just have post-css before style-loader. Can I safely omit css-loader from my css build, or is there some other functionality it provides that is necessary? I've yet to see a webpack.config.js file that doesn't use css-loader, so I want to be cautious here! :)


问:
How to align html elements on the same row
If you see the attachment below, three share buttons are not equally margined from the top. Tweet button didn't maintain the consistency, it is little bit up than the other two. How do I make all of them equally distanced from the top?

The code I am working on:

```<code>                            <h2 class="title">Share this blog</h2>

                            <div class="fb-share-button" data-href="http://alfa-blog.com/"
                                 data-layout="button_count" data-size="large" data-mobile-iframe="true">
                                <a class="fb-xfbml-parse-ignore" target="_blank"
                                   href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Falfa-blog.com%2Findex.html&src=sdkpreparse">Share</a>
                            </div>

                            <a href="https://twitter.com/share"
                               data-size="large"
                               class="twitter-share-button" data-show-count="false">Tweet</a>

                            <div class="g-plus" data-action="share" data-height="24" data-href="http://alfa-blog.com/"></div>
</code>```

答:
Put the respective button codes inside a div element which functions as a mask. Like so:

```<code><h2 class="title">Share this blog</h2>

<div class="socialbtn socialbtn-facebook">
  <div class="fb-share-button" data-href="http://alfa-blog.com/" data-layout="button_count" data-size="large" data-mobile-iframe="true">
    <a class="fb-xfbml-parse-ignore" target="_blank" href="[address]">Share</a>
  </div>
</div>

<div class="socialbtn socialbtn-twitter">
  <a href="https://twitter.com/share" data-size="large" class="twitter-share-button" data-show-count="false">Tweet</a>
</div>

<div class="socialbtn socialbtn-googlePlus">
  <div class="g-plus" data-action="share" data-height="24" data-href="http://alfa-blog.com/"></div>
</div>
</code>```

with the CSS code:

```<code>.socialbtn {display:inline-flex;height:25px;width:auto;overflow-y:hidden}
.socialbtn-googlePlus {margin-top:-10px}
.socialbtn-twitter {margin-top:0px}
.socialbtn-facebook {margin-top:-5px}
</code>```

Please correct the respective margins to rectify your situation.

Body:
If you see the attachment below, three share buttons are not equally margined from the top. Tweet button didn't maintain the consistency, it is little bit up than the other two. How do I make all of them equally distanced from the top?

The code I am working on:

Share this blog

                                Share

                            Tweet

Body:
Put the respective button codes inside a div element which functions as a mask. Like so:

<h2 class="title">Share this blog</h2>

<div class="socialbtn socialbtn-facebook">
  <div class="fb-share-button" data-href="http://alfa-blog.com/" data-layout="button_count" data-size="large" data-mobile-iframe="true">
    <a class="fb-xfbml-parse-ignore" target="_blank" href="[address]">Share</a>
  </div>
</div>

<div class="socialbtn socialbtn-twitter">
  <a href="https://twitter.com/share" data-size="large" class="twitter-share-button" data-show-count="false">Tweet</a>
</div>

<div class="socialbtn socialbtn-googlePlus">
  <div class="g-plus" data-action="share" data-height="24" data-href="http://alfa-blog.com/"></div>
</div>

with the CSS code:

.socialbtn {display:inline-flex;height:25px;width:auto;overflow-y:hidden}
.socialbtn-googlePlus {margin-top:-10px}
.socialbtn-twitter {margin-top:0px}
.socialbtn-facebook {margin-top:-5px}

Please correct the respective margins to rectify your situation.


问:
Hide shopping cart if is empty
For a few days in a row I've tried to find a solution to hide an entire section if my shopping cart is empty and only be shown when I add a new item in cart. Shop is made entirely with javascript and jQuery.
Down below I will put the code , even a small idea is good.

P.S: I need to hide  the div.

            $(".add-to-cart").click(function(event){
                event.preventDefault();
                var name = $(this).attr("data-name");
                var price = Number($(this).attr("data-price"));

                shoppingCart.addItemToCart(name, price, 1);
                displayCart();
            });

            $("#clear-cart").click(function(event){
                shoppingCart.clearCart();
                displayCart();
            });

            function displayCart() {
                var cartArray = shoppingCart.listCart();
                console.log(cartArray);
                var output = "";

                for (var i in cartArray) {
                    output += "
"
                        +cartArray[i].name
                        +" <input class='item-count' type='number' data-name='"
                        +cartArray[i].name
                        +"' value='"+cartArray[i].count+"' >"
                        +" x "+cartArray[i].price
                        +" = "+cartArray[i].total
                        +" <button class='plus-item' data-name='"
                        +cartArray[i].name+"'>+</button>"
                        +" <button class='subtract-item' data-name='"
                        +cartArray[i].name+"'>-</button>"
                        +" <button class='delete-item' data-name='"
                        +cartArray[i].name+"'>X</button>"
                        +"
";
                }

                $("#show-cart").html(output);
                $("#count-cart").html( shoppingCart.countCart() );
                $("#total-cart").html( shoppingCart.totalCart() );
            }

            $("#show-cart").on("click", ".delete-item", function(event){
                var name = $(this).attr("data-name");
                shoppingCart.removeItemFromCartAll(name);
                displayCart();
            });

            $("#show-cart").on("click", ".subtract-item", function(event){
                var name = $(this).attr("data-name");
                shoppingCart.removeItemFromCart(name);
                displayCart();
            });

            $("#show-cart").on("click", ".plus-item", function(event){
                var name = $(this).attr("data-name");
                shoppingCart.addItemToCart(name, 0, 1);
                displayCart();
            });

            $("#show-cart").on("change", ".item-count", function(event){
                var name = $(this).attr("data-name");
                var count = Number($(this).val());
                shoppingCart.setCountForItem(name, count);
                displayCart();
            });

            displayCart();

// Shopping Cart functions

var shoppingCart = (function () {
    // Private methods and properties
    var cart = [];

    function Item(name, price, count) {
        this.name = name
        this.price = price
        this.count = count
    }

    function saveCart() {
        localStorage.setItem("shoppingCart", JSON.stringify(cart));
    }

    function loadCart() {
        cart = JSON.parse(localStorage.getItem("shoppingCart"));
        if (cart === null) {
            cart = []
        }
    }

    loadCart();

    // Public methods and properties
    var obj = {};

    obj.addItemToCart = function (name, price, count) {
        for (var i in cart) {
            if (cart[i].name === name) {
                cart[i].count += count;
                saveCart();
                return;
            }
        }

        console.log("addItemToCart:", name, price, count);

        var item = new Item(name, price, count);
        cart.push(item);
        saveCart();
    };

    obj.setCountForItem = function (name, count) {
        for (var i in cart) {
            if (cart[i].name === name) {
                cart[i].count = count;
                break;
            }
        }
        saveCart();
    };

    obj.removeItemFromCart = function (name) { // Removes one item
        for (var i in cart) {
            if (cart[i].name === name) { // "3" === 3 false
                cart[i].count--; // cart[i].count --
                if (cart[i].count === 0) {
                    cart.splice(i, 1);
                }
                break;
            }
        }
        saveCart();
    };

    obj.removeItemFromCartAll = function (name) { // removes all item name
        for (var i in cart) {
            if (cart[i].name === name) {
                cart.splice(i, 1);
                break;
            }
        }
        saveCart();
    };

    obj.clearCart = function () {
        cart = [];
        saveCart();
    }

    obj.countCart = function () { // -> return total count
        var totalCount = 0;
        for (var i in cart) {
            totalCount += cart[i].count;
        }

        return totalCount;
    };

    obj.totalCart = function () { // -> return total cost
        var totalCost = 0;
        for (var i in cart) {
            totalCost += cart[i].price * cart[i].count;
        }
        return totalCost.toFixed(2);
    };

    obj.listCart = function () { // -> array of Items
        var cartCopy = [];
        console.log("Listing cart");
        console.log(cart);
        for (var i in cart) {
            console.log(i);
            var item = cart[i];
            var itemCopy = {};
            for (var p in item) {
                itemCopy[p] = item[p];
            }
            itemCopy.total = (item.price * item.count).toFixed(2);
            cartCopy.push(itemCopy);
        }
        return cartCopy;
    };

    // ----------------------------
    return obj;
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
            <ul>
                <li>Apple $1.22</li>
                <li>Banana $1.33</li>
                <li>Shoe $22.33</li>
                <li>Frisbee $5.22</li>
            </ul>
            <button id="clear-cart">Clear Cart</button>
        </div>

        <div>
            <ul id="show-cart">
                <li>???????</li>
            </ul>
            <div>You have <span id="count-cart">X</span> items in your cart</div>
            <div>Total Cart:$<span id="total-cart"></span></div>
        </div></code>```

答:
You could use the length of cart items as boolean for jQuery toggle()

```<code>let $cartList = $('#show-cart');
$cartList.parent().toggle( $cartList.children().length );
</code>```

Title: Hide shopping cart if is empty

Body:
For a few days in a row I've tried to find a solution to hide an entire section if my shopping cart is empty and only be shown when I add a new item in cart. Shop is made entirely with javascript and jQuery.
Down below I will put the code , even a small idea is good.

P.S: I need to hide  the div.

            $(".add-to-cart").click(function(event){
                event.preventDefault();
                var name = $(this).attr("data-name");
                var price = Number($(this).attr("data-price"));

                shoppingCart.addItemToCart(name, price, 1);
                displayCart();
            });

            $("#clear-cart").click(function(event){
                shoppingCart.clearCart();
                displayCart();
            });

            function displayCart() {
                var cartArray = shoppingCart.listCart();
                console.log(cartArray);
                var output = "";

                for (var i in cartArray) {
                    output += "
"
                        +cartArray[i].name
                        +" <input class='item-count' type='number' data-name='"
                        +cartArray[i].name
                        +"' value='"+cartArray[i].count+"' >"
                        +" x "+cartArray[i].price
                        +" = "+cartArray[i].total
                        +" <button class='plus-item' data-name='"
                        +cartArray[i].name+"'>+</button>"
                        +" <button class='subtract-item' data-name='"
                        +cartArray[i].name+"'>-</button>"
                        +" <button class='delete-item' data-name='"
                        +cartArray[i].name+"'>X</button>"
                        +"
";
                }

                $("#show-cart").html(output);
                $("#count-cart").html( shoppingCart.countCart() );
                $("#total-cart").html( shoppingCart.totalCart() );
            }

            $("#show-cart").on("click", ".delete-item", function(event){
                var name = $(this).attr("data-name");
                shoppingCart.removeItemFromCartAll(name);
                displayCart();
            });

            $("#show-cart").on("click", ".subtract-item", function(event){
                var name = $(this).attr("data-name");
                shoppingCart.removeItemFromCart(name);
                displayCart();
            });

            $("#show-cart").on("click", ".plus-item", function(event){
                var name = $(this).attr("data-name");
                shoppingCart.addItemToCart(name, 0, 1);
                displayCart();
            });

            $("#show-cart").on("change", ".item-count", function(event){
                var name = $(this).attr("data-name");
                var count = Number($(this).val());
                shoppingCart.setCountForItem(name, count);
                displayCart();
            });

            displayCart();

// Shopping Cart functions

var shoppingCart = (function () {
    // Private methods and properties
    var cart = [];

    function Item(name, price, count) {
        this.name = name
        this.price = price
        this.count = count
    }

    function saveCart() {
        localStorage.setItem("shoppingCart", JSON.stringify(cart));
    }

    function loadCart() {
        cart = JSON.parse(localStorage.getItem("shoppingCart"));
        if (cart === null) {
            cart = []
        }
    }

    loadCart();

    // Public methods and properties
    var obj = {};

    obj.addItemToCart = function (name, price, count) {
        for (var i in cart) {
            if (cart[i].name === name) {
                cart[i].count += count;
                saveCart();
                return;
            }
        }

        console.log("addItemToCart:", name, price, count);

        var item = new Item(name, price, count);
        cart.push(item);
        saveCart();
    };

    obj.setCountForItem = function (name, count) {
        for (var i in cart) {
            if (cart[i].name === name) {
                cart[i].count = count;
                break;
            }
        }
        saveCart();
    };

    obj.removeItemFromCart = function (name) { // Removes one item
        for (var i in cart) {
            if (cart[i].name === name) { // "3" === 3 false
                cart[i].count--; // cart[i].count --
                if (cart[i].count === 0) {
                    cart.splice(i, 1);
                }
                break;
            }
        }
        saveCart();
    };

    obj.removeItemFromCartAll = function (name) { // removes all item name
        for (var i in cart) {
            if (cart[i].name === name) {
                cart.splice(i, 1);
                break;
            }
        }
        saveCart();
    };

    obj.clearCart = function () {
        cart = [];
        saveCart();
    }

    obj.countCart = function () { // -> return total count
        var totalCount = 0;
        for (var i in cart) {
            totalCount += cart[i].count;
        }

        return totalCount;
    };

    obj.totalCart = function () { // -> return total cost
        var totalCost = 0;
        for (var i in cart) {
            totalCost += cart[i].price * cart[i].count;
        }
        return totalCost.toFixed(2);
    };

    obj.listCart = function () { // -> array of Items
        var cartCopy = [];
        console.log("Listing cart");
        console.log(cart);
        for (var i in cart) {
            console.log(i);
            var item = cart[i];
            var itemCopy = {};
            for (var p in item) {
                itemCopy[p] = item[p];
            }
            itemCopy.total = (item.price * item.count).toFixed(2);
            cartCopy.push(itemCopy);
        }
        return cartCopy;
    };

    // ----------------------------
    return obj;
})();

Apple $1.22

Banana $1.33

Shoe $22.33

Frisbee $5.22

            <button id="clear-cart">Clear Cart</button>

???????

You have X items in your cart

Total Cart:$

Body:
You could use the length of cart items as boolean for jQuery toggle()

let $cartList = $('#show-cart');
$cartList.parent().toggle( $cartList.children().length );


问:
State-of-art graph partitioner
Is there any state-of-art tool/algorithm for graph 'edge-cut' partitioning?

And same question for 'vertex-cut' partitioning.

Thanks.

答: For vertex-cut partitioning, a popular and performant linear runtime heuristic is HDRF (high-degree vertices replicated first). There is a Github project (Java implementation). This can be considered as state-of-the-art although there are a few newer vertex-cut projects (e.g.  H-load).

Title: State-of-art graph partitioner


问:
Why increasing number of workers (more than number of cores) still decrease execution time?
I always sure that there is no point to have more threads/processes than CPU cores (from the performance perspective). However, my python sample shows me a different result.

```<code>import concurrent.futures
import random
import time

def doSomething(task_num):
    print("executing...", task_num)
    time.sleep(1)  # simulate heavy operation that takes ~ 1 second
    return random.randint(1, 10) * random.randint(1, 500)  # real operation, used random to avoid caches and so on...

def main():
    # This part is not taken in consideration because I don't want to
    # measure the worker creation time
    executor = concurrent.futures.ProcessPoolExecutor(max_workers=60)

    start_time = time.time()

    for i in range(1, 100): # execute 100 tasks
        executor.map(doSomething, [i, ])
    executor.shutdown(wait=True)

    print("--- %s seconds ---" % (time.time() - start_time))

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

Program results:

1 WORKER  --- 100.28233647346497 seconds ---

  2 WORKERS --- 50.26122164726257 seconds ---

  3 WORKERS --- 33.32741022109985 seconds ---

  4 WORKERS --- 25.399883031845093 seconds ---

  5 WORKERS --- 20.434186220169067 seconds ---

  10 WORKERS--- 10.903695344924927 seconds ---

  50 WORKERS--- 6.363946914672852 seconds ---

  60 WORKERS--- 4.819359302520752 seconds ---

How this can work faster having just 4 Logical processors ?

Here is my Computer specifications (Tested on Windows 8 and Ubuntu 14):

CPU Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
   Sockets: 1
   Cores:   2
   Logical processors:    4

答:
The reason is because sleep() only uses a negligible amount of CPU. In this case, it is a poor simulation of actual work performed by a thread.

All sleep() really does is suspend the thread until the timer expires. While the thread is suspended, it doesn't use any CPU cycles.

Body:
I always sure that there is no point to have more threads/processes than CPU cores (from the performance perspective). However, my python sample shows me a different result.

import concurrent.futures
import random
import time

def doSomething(task_num):
    print("executing...", task_num)
    time.sleep(1)  # simulate heavy operation that takes ~ 1 second
    return random.randint(1, 10) * random.randint(1, 500)  # real operation, used random to avoid caches and so on...

def main():
    # This part is not taken in consideration because I don't want to
    # measure the worker creation time
    executor = concurrent.futures.ProcessPoolExecutor(max_workers=60)

    start_time = time.time()

    for i in range(1, 100): # execute 100 tasks
        executor.map(doSomething, [i, ])
    executor.shutdown(wait=True)

    print("--- %s seconds ---" % (time.time() - start_time))

if __name__ == '__main__':
    main()

Program results:

1 WORKER  --- 100.28233647346497 seconds ---

  2 WORKERS --- 50.26122164726257 seconds ---

  3 WORKERS --- 33.32741022109985 seconds ---

  4 WORKERS --- 25.399883031845093 seconds ---

  5 WORKERS --- 20.434186220169067 seconds ---

  10 WORKERS--- 10.903695344924927 seconds ---

  50 WORKERS--- 6.363946914672852 seconds ---

  60 WORKERS--- 4.819359302520752 seconds ---

How this can work faster having just 4 Logical processors ?

Here is my Computer specifications (Tested on Windows 8 and Ubuntu 14):

CPU Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
   Sockets: 1
   Cores:   2
   Logical processors:    4


问:
return the results of sonarqube
I'm trying to write a pipeline as a code and in this pipeline I want to return the result of sonarqube analyze and do a filter if the general note is >=97 continue if it is less return a Notif in slack.
but how can I return a result a of sonarqube</p>

答:
There are so called quality gates in Sonarqube which can be configured to fail the build if necessary.

You will have to configure a webhook between Sonarqube and Jenkins so that you pipeline can ask for the quality gate status.
Further information can be found here: https://jenkins.io/doc/pipeline/steps/sonar/

Note: Especially have a look at the method waitForQualityGate() which does exactly what you intend to do!

Title: return the results of sonarqube


问:
JQuery wrong ID in an inner click
I'm trying to make a colorpicker. Where you got a few colorcubes with the class colorcube.
When clicking, it opens a colorpicker with a few list items who all have a different color.
When clicking on a list items it should return de color/text to de colorcube.

The first colorpick after the document is ready works. But after that it doesnt work properly, because it remembers al the previous colorcube ID's so al the other cube's will also change :(

Is there a way to clear cache or something like that?

```<code>$('.colorcube').click(function() {
    var colorcubeid = $(this).attr("id");
    $('#choicecolor').show();

    $(".li_color").click(function() {
        var colorid = "#" + this.id;
        var colorli = $(colorid).text();
        $('#' + colorcubeid).text(colorli);
        $('#' + colorcubeid).css({ 'background-color': '' + colorli + '' });
        $('#choicecolor').hide();
        savecolor();
    });

});
</code>```

答:
You need to unbind your previous click-handlers, so that they won't be called again.

However I would recommend to avoid that and create a clean instance of the #choicecolor via jQuery templates or similar approaches - saves you a lot of headaches if you do not recycle your control over and over again.

Title: JQuery wrong ID in an inner click

Body:
I'm trying to make a colorpicker. Where you got a few colorcubes with the class colorcube.
When clicking, it opens a colorpicker with a few list items who all have a different color.
When clicking on a list items it should return de color/text to de colorcube.

The first colorpick after the document is ready works. But after that it doesnt work properly, because it remembers al the previous colorcube ID's so al the other cube's will also change :(

Is there a way to clear cache or something like that?

$('.colorcube').click(function() {
    var colorcubeid = $(this).attr("id");
    $('#choicecolor').show();

    $(".li_color").click(function() {
        var colorid = "#" + this.id;
        var colorli = $(colorid).text();
        $('#' + colorcubeid).text(colorli);
        $('#' + colorcubeid).css({ 'background-color': '' + colorli + '' });
        $('#choicecolor').hide();
        savecolor();
    });

});


问:
What is a postgres superuser
I couldn't find the answer in the docs, what exactly is a superuser in postgres? </p>

<p>Does the superuser have all privileges? Is it per database? Per instance? </p>

答:
A superuser in PostgreSQL is a user who bypasses all permission checks.

Superusers can run commands that can destabilize or crash the database server (e.g., create C functions) and access the operating system.

Title: What is a postgres superuser

Body:
I couldn't find the answer in the docs, what exactly is a superuser in postgres?

Does the superuser have all privileges? Is it per database? Per instance?


问:
Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass
When i'm trying to run the test suite, am getting this exception. We are using maven project here and i am done with refreshing, cleaning, reinstalling testNG and then imported the maven projects but then also am getting the same exception. Please suggest any ways that am missing here.

Error console:

```<code>org.testng.TestNGException:
Cannot find class in classpath: EmpClass

at org.testng.xml.XmlClass.loadClass(XmlClass.java:81)
at org.testng.xml.XmlClass.init(XmlClass.java:73)
at org.testng.xml.XmlClass.<init>(XmlClass.java:59)
at org.testng.xml.TestNGContentHandler.startElement(TestNGContentHandler.java:543)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(XMLDTDValidator.java:766)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1350)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2778)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:649)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:333)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:195)
at org.testng.xml.XMLParser.parse(XMLParser.java:39)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:17)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:10)
at org.testng.xml.Parser.parse(Parser.java:168)
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:311)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
</code>```

答: Project>>Clean and Maven>>Update Project worked for me</p>

Body:
When i'm trying to run the test suite, am getting this exception. We are using maven project here and i am done with refreshing, cleaning, reinstalling testNG and then imported the maven projects but then also am getting the same exception. Please suggest any ways that am missing here.

Error console:

org.testng.TestNGException:
Cannot find class in classpath: EmpClass

at org.testng.xml.XmlClass.loadClass(XmlClass.java:81)
at org.testng.xml.XmlClass.init(XmlClass.java:73)
at org.testng.xml.XmlClass.<init>(XmlClass.java:59)
at org.testng.xml.TestNGContentHandler.startElement(TestNGContentHandler.java:543)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(XMLDTDValidator.java:766)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1350)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2778)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:649)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:333)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:195)
at org.testng.xml.XMLParser.parse(XMLParser.java:39)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:17)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:10)
at org.testng.xml.Parser.parse(Parser.java:168)
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:311)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)


问:
Android data binding: can't find setter for attribute android:onClick
I'm getting this error:

Cannot find the setter for attribute 'android:onClick' with parameter type android.view.View.OnClickListener on android.widget.Button. file:/home/itstym/ApkProjects/Reminder/app/src/main/res/layout/activity_main.xml loc:54:27 - 54:61

activity.main.xml

```<code><data class="ActivityMainBinding">
        <variable
            name="login"
            type="com.example.itstym.reminder.loginViewModel" />

        <variable
            name="handler"
            type="com.example.itstym.reminder.LoginHandler" />
    </data>

     <Button
    android:onClick="@{(v) -> handler.onLoginButtonClicked(v,login)}"
    android:id="@+id/submit_button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="16dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="24dp"
    android:text="Sign In"
    app:layout_constraintEnd_toEndOf="@+id/user_password"
    app:layout_constraintStart_toStartOf="@+id/user_password"
    app:layout_constraintTop_toBottomOf="@+id/user_password"/>
</code>```

MainActivity.java

```<code>val handler= LoginHandler(this@MainActivity)
</code>```

LoginHandler.kt

```<code>class LoginHandler(context:Context) {

    fun onLoginButtonClicked(view:View, userInfo: loginViewModel) {
        Log.i("Email is ", userInfo.userEmailAddress)
        Log.i("Password is ", userInfo.userPassword)
    }
}
</code>```

How do I create the setter for the button here? I think I am creating it only for the view, but not for the button setter.

Stacktrace

```<code>at android.databinding.tool.processing.Scope.assertNoError(Scope.java:112)
    at android.databinding.annotationprocessor.ProcessDataBinding.process(ProcessDataBinding.java:91)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$200(JavacProcessingEnvironment.java:91)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment$DiscoveredProcessors$ProcessorStateIterator.runContributingProcs(JavacProcessingEnvironment.java:627)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1033)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1198)
    at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
    at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1068)
    at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:73)
</code>```

Any leads will help!

答:
Your xml should be like this

```<code><data class="ActivityMainBinding">
    <variable
        name="login"
        type="com.example.itstym.reminder.loginViewModel" />

    <variable
        name="handler"
        type="com.example.itstym.reminder.MainActivity" />
</data>

     <Button
        android:onClick="@{(v) -> handler.onLoginButtonClicked(v, login)}"
        android:id="@+id/submit_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="24dp"
        android:text="Sign In"
        app:layout_constraintEnd_toEndOf="@+id/user_password"
        app:layout_constraintStart_toStartOf="@+id/user_password"
        app:layout_constraintTop_toBottomOf="@+id/user_password"/>
</code>```

You can directly get this onClick in your MainActivity. There is no need to create a separate class.

MainActivity.java

```<code>ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setHandler(this);
</code>```

Then in MainActivity you can access this method like:

```<code>public void onLoginButtonClicked(View view, LoginViewModel model) {
   //Do something
}
</code>```

Body:
I'm getting this error:

Cannot find the setter for attribute 'android:onClick' with parameter type android.view.View.OnClickListener on android.widget.Button. file:/home/itstym/ApkProjects/Reminder/app/src/main/res/layout/activity_main.xml loc:54:27 - 54:61

activity.main.xml

<data class="ActivityMainBinding">
        <variable
            name="login"
            type="com.example.itstym.reminder.loginViewModel" />

        <variable
            name="handler"
            type="com.example.itstym.reminder.LoginHandler" />
    </data>

     <Button
    android:onClick="@{(v) -> handler.onLoginButtonClicked(v,login)}"
    android:id="@+id/submit_button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="16dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="24dp"
    android:text="Sign In"
    app:layout_constraintEnd_toEndOf="@+id/user_password"
    app:layout_constraintStart_toStartOf="@+id/user_password"
    app:layout_constraintTop_toBottomOf="@+id/user_password"/>

MainActivity.java

val handler= LoginHandler(this@MainActivity)

LoginHandler.kt

class LoginHandler(context:Context) {

    fun onLoginButtonClicked(view:View, userInfo: loginViewModel) {
        Log.i("Email is ", userInfo.userEmailAddress)
        Log.i("Password is ", userInfo.userPassword)
    }
}

How do I create the setter for the button here? I think I am creating it only for the view, but not for the button setter.

Stacktrace

at android.databinding.tool.processing.Scope.assertNoError(Scope.java:112)
    at android.databinding.annotationprocessor.ProcessDataBinding.process(ProcessDataBinding.java:91)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$200(JavacProcessingEnvironment.java:91)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment$DiscoveredProcessors$ProcessorStateIterator.runContributingProcs(JavacProcessingEnvironment.java:627)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1033)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1198)
    at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
    at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1068)
    at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:73)

Any leads will help!

Body:
Your xml should be like this

<data class="ActivityMainBinding">
    <variable
        name="login"
        type="com.example.itstym.reminder.loginViewModel" />

    <variable
        name="handler"
        type="com.example.itstym.reminder.MainActivity" />
</data>

     <Button
        android:onClick="@{(v) -> handler.onLoginButtonClicked(v, login)}"
        android:id="@+id/submit_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="24dp"
        android:text="Sign In"
        app:layout_constraintEnd_toEndOf="@+id/user_password"
        app:layout_constraintStart_toStartOf="@+id/user_password"
        app:layout_constraintTop_toBottomOf="@+id/user_password"/>

You can directly get this onClick in your MainActivity. There is no need to create a separate class.

MainActivity.java

ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setHandler(this);

Then in MainActivity you can access this method like:

public void onLoginButtonClicked(View view, LoginViewModel model) {
   //Do something
}


问:
Getting a value from XML File (no unique ID for node)
I have a following XML:

<?xml version="1.0"?>
<Objects>
    <Object Type="System.Management.Automation.PSCustomObject">
        <Property Type="System.String" Name="FolderName">Mozilla_Firefox</Property>
        <Property Type="System.Int32" Name="Export">6</Property>
    </Object>
    <Object Type="System.Management.Automation.PSCustomObject">
        <Property Type="" Name="ExportListing"/>
        <Property Type="System.String" Name="FolderName">Notepad</Property>
        <Property Type="System.Int32" Name="ExportCountZips">1</Property>
    </Object>
</Objects>
```

<p>I want to get a value of property 'Export' for particular 'FolderName'.
Here is how I obtain a XML Line with Notepad:</p>

<pre class="lang-bsh prettyprint-override"><code>$t = $xml.Objects.Object.Property |
     ? { $_.Name -eq 'FolderName'} |
     Where '#text' -eq 'Notepad'
</code>```

How to get a proper 'ExportCountZips' with a value of 1?

答:
```<code>$ExportCountZips = ($xml.objects.object.property | Where-Object {$_.Name -eq "ExportCountZips"})."#text"
</code>```

Body:
I have a following XML:

<?xml version="1.0"?>
<Objects>
    <Object Type="System.Management.Automation.PSCustomObject">
        <Property Type="System.String" Name="FolderName">Mozilla_Firefox</Property>
        <Property Type="System.Int32" Name="Export">6</Property>
    </Object>
    <Object Type="System.Management.Automation.PSCustomObject">
        <Property Type="" Name="ExportListing"/>
        <Property Type="System.String" Name="FolderName">Notepad</Property>
        <Property Type="System.Int32" Name="ExportCountZips">1</Property>
    </Object>
</Objects>

I want to get a value of property 'Export' for particular 'FolderName'.
Here is how I obtain a XML Line with Notepad:

$t = $xml.Objects.Object.Property |
     ? { $_.Name -eq 'FolderName'} |
     Where '#text' -eq 'Notepad'

How to get a proper 'ExportCountZips' with a value of 1?


问:
How can I turn off default validation in WPF?
It seems that WPF has some validation rule which is turned on by default. When I enter non numeric text into the bound textbox and tab out it, a read border shows around it. What is going on here? I Have set ValidatesOnExceptions to false, where is the validation rule coming from? I am using version 4.5.2 of the .Net framework.

Here is my XAML

```<code><Window x:Class="WpfApplication2.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApplication2"
            mc:Ignorable="d"
            Title="MainWindow" Height="159.206" Width="193.953">
        <Grid>
            <TextBox x:Name="textBox" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" TextWrapping="Wrap"
                     Text="{Binding Foo, ValidatesOnExceptions=False, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
                     Width="91" Margin="10,10,0,0"/>
            <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23" Margin="10,48,0,0"
                     TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="91"/>
        </Grid>
</Window>
</code>```

Here is the code behind

```<code>namespace WpfApplication2
{
    public partial class MainWindow : Window
    {
        public int Foo { get; set; } = 42;
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}
</code>```

答:
You can never set an int property to anything else than a valid int value.

This "validation", or rather type-safety feature of the programming language, cannot be turned off.

You can however get rid of or customize the the default error template if you want to. Just set the Validation.ErrorTemplate property to an emoty ControlTemplate:

```<code><TextBox x:Name="textBox" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" TextWrapping="Wrap"
        Text="{Binding Foo, ValidatesOnExceptions=False, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
        Width="91" Margin="10,10,0,0">
    <Validation.ErrorTemplate>
        <ControlTemplate />
    </Validation.ErrorTemplate>
</TextBox>
</code>```

Body:
It seems that WPF has some validation rule which is turned on by default. When I enter non numeric text into the bound textbox and tab out it, a read border shows around it. What is going on here? I Have set ValidatesOnExceptions to false, where is the validation rule coming from? I am using version 4.5.2 of the .Net framework.

Here is my XAML

<Window x:Class="WpfApplication2.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApplication2"
            mc:Ignorable="d"
            Title="MainWindow" Height="159.206" Width="193.953">
        <Grid>
            <TextBox x:Name="textBox" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" TextWrapping="Wrap"
                     Text="{Binding Foo, ValidatesOnExceptions=False, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
                     Width="91" Margin="10,10,0,0"/>
            <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23" Margin="10,48,0,0"
                     TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="91"/>
        </Grid>
</Window>

Here is the code behind

namespace WpfApplication2
{
    public partial class MainWindow : Window
    {
        public int Foo { get; set; } = 42;
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

Body:
You can never set an int property to anything else than a valid int value.

This "validation", or rather type-safety feature of the programming language, cannot be turned off.

You can however get rid of or customize the the default error template if you want to. Just set the Validation.ErrorTemplate property to an emoty ControlTemplate:

<TextBox x:Name="textBox" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" TextWrapping="Wrap"
        Text="{Binding Foo, ValidatesOnExceptions=False, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
        Width="91" Margin="10,10,0,0">
    <Validation.ErrorTemplate>
        <ControlTemplate />
    </Validation.ErrorTemplate>
</TextBox>