问:
WPF error message: Partial declaration must not specify different base classes
Why do I have this error message for a UserControl:

Partial declaration of
  MyNamespace.MyUserControl must not
  specify different base classes

Just because I inherited from another UserControl class I created in another namespace whereas this other namespace is referenced in the XAML as

```<code>xmlns:my="clr-namespace:ReferedNamespace;assembly=ReferedNamespace"
</code>```

答:
I wanted to add this piece of information. In Visual Studio 2017, There is a bug which I haven't had time to dig into with much depth, but it causes this error. (from the OP)

Overview: When declaring a partial class as an x:Class for a resource xaml file, it will cause this error, and after removing the declaration, the error will persist.

To reproduce this bug, (or if you are here because you are getting this error message)

Step 1:  Create a new WPF Project.

Step 2:  Create a new Resource File

Step 3:  Change the resource files name-space to the projects main namespace (remove the bit at the end.)

Step 4: In the resource files declaration/header section, add an x:Class declaration specifying your MainWindow (default startup window object) as the Class for that resource file.  (EG:  x:Class=MainWindow)

Step 5: Clean/Rebuild Solution

Step 6: You should now be getting this error from the OP. So remove the x:Class Declaration from your header on the Resource File, and save/clean/rebuild the project.

If the bug was reproduced, the error should remain, even though you have removed the x:Class declaration from the resource file.

The only solution I could find for this bug, is to delete the projects Bin folder, and any other folder with builds in it.

After deleting them, Clean/Rebuild your project, and the error should be gone.

Body:
Why do I have this error message for a UserControl:

Partial declaration of
  MyNamespace.MyUserControl must not
  specify different base classes

Just because I inherited from another UserControl class I created in another namespace whereas this other namespace is referenced in the XAML as

xmlns:my="clr-namespace:ReferedNamespace;assembly=ReferedNamespace"


来源: stackexchange

问:
Google Sheets removing leading spaces query results
My sheet is pulling data from another sheet with:

```<code>=QUERY('WHERE TO SEND STUDENTS'!A:D, "select B,C,D where A<>'' order by D",1)
</code>```

Some of the contents of D has a leading space which causes it to be at the top of the column. Is there a way to remove this leading space and then sort the column D?

答:
You really don't need the if statement, this will do it:</p>

```<code>=arrayformula(query(TRIM('WHERE TO SEND STUDENTS'!A:D),"select Col2, Col3, Col4 where Col2 <> '' order by Col4", 1 ) )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My sheet is pulling data from another sheet with:

=QUERY('WHERE TO SEND STUDENTS'!A:D, "select B,C,D where A<>'' order by D",1)

Some of the contents of D has a leading space which causes it to be at the top of the column. Is there a way to remove this leading space and then sort the column D?

Body:
You really don't need the if statement, this will do it:

=arrayformula(query(TRIM('WHERE TO SEND STUDENTS'!A:D),"select Col2, Col3, Col4 where Col2 <> '' order by Col4", 1 ) )


问:
Can you reuse a fragment in multiple activities but with different functionalities?
Say I have a fragment that has three buttons and I want to reuse it for at least three activities, but I want those buttons to do different things for each activity. For example, in ActivityA, I want button1 to open Google Maps while in ActivityB, button1 goes to the music player. Is this possible or even the right way?</p>

答: Of course you can. Just create an interface for the Fragment, let's say FragmentCallback, with your desired callback method, onButtonClick() for instance. In the onAttached() of your Fragment, cast the Activity to your new interface and store it in a variable private FragmentCallback callback;. Each Activity using this Fragment must implement this callback interface. Then call the callbacks onButtonClick() method in your Fragments onButtonClick() method. That's it - a very common pattern.


问:
Formula using Variables with VBA
I am wrestling with the syntax of this one line of some code. the formula with "IfError" seems to have the wrong syntax. I believe I have the quotes in the right places. </p>

```<code>    Dim j As Integer
    Dim MidPointE As String
    Dim Dist As String
    Dim Allocation As String

    MidPointE = "AM"
    Dist = "AN"
    Allocation = "AO"

   for J= 1 to 300
     Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE &  CustomerLast & ", "")"
    Cells(j, Allocation).Formula = "=" & Allocation & j & "* S" & CustomerLast

     Next J
</code>```

答:
You can also assign multiple formulas at the same time:

```<code>Range("AN1:AN300").Formula = "=IFERROR(AM1 / AM$" &  CustomerLast & ", """")"
Range("AO1:AO300").Formula = "=AO1 * S$" & CustomerLast
</code>```

I also recommend looking into Excel Tables and Structured References

To avoid the circular reference issue, you can calculate the formulas and assign the values directly:

```<code>Range("AN1:AN300") = Evaluate("IFERROR(AM1:AM300 / AM$" &  CustomerLast & ", """")")
Range("AO1:AO300") = Evaluate("INDEX(AO1:AO300 * S$" & CustomerLast & ",)")
</code>```

Title: Formula using Variables with VBA

Body:
I am wrestling with the syntax of this one line of some code. the formula with "IfError" seems to have the wrong syntax. I believe I have the quotes in the right places.

    Dim j As Integer
    Dim MidPointE As String
    Dim Dist As String
    Dim Allocation As String

    MidPointE = "AM"
    Dist = "AN"
    Allocation = "AO"

   for J= 1 to 300
     Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE &  CustomerLast & ", "")"
    Cells(j, Allocation).Formula = "=" & Allocation & j & "* S" & CustomerLast

     Next J

Body:
You can also assign multiple formulas at the same time:

Range("AN1:AN300").Formula = "=IFERROR(AM1 / AM$" &  CustomerLast & ", """")"
Range("AO1:AO300").Formula = "=AO1 * S$" & CustomerLast

I also recommend looking into Excel Tables and Structured References

To avoid the circular reference issue, you can calculate the formulas and assign the values directly:

Range("AN1:AN300") = Evaluate("IFERROR(AM1:AM300 / AM$" &  CustomerLast & ", """")")
Range("AO1:AO300") = Evaluate("INDEX(AO1:AO300 * S$" & CustomerLast & ",)")


问:
Generate a “where in” statement using the Criteria API in Hibernate
I put in place the following specification that represents the predicate construction for querying Students based on their age and their ClassRoom's teachers' name (one student can have one or more classroom)

```<code>public class StudentSpecification implements Specification<Student> {

  private final Integer age;

  public StudentSpecification(Integer age){
    this.age = age;
  }

  @Override
  public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
      List<Predicate> predicates = new ArrayList<>();

      predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.<Integert>get(age), Integer.valueOf(v)));

      SetJoin<Student, ClassRoom> classRooms = root.join(Student_.classRooms);

      predicates.add(criteriaBuilder.equal(classRooms.get(ClassRoom_.teacher), "Marta"));
      predicates.add(criteriaBuilder.equal(classRooms.get(ClassRoom_.teacher), "Fowler"));

      return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
  }
}
</code>```

Here is an example of data :

```<code>Student
_____________________________________________
ID     CLASSROOM_ID     NAME         AGE
2      120              Pascal       22
8      120              Bryan        21

ClassRoom
_____________________________________________
ID     CLASSROOM_ID     TEACHER
1      120              Marta
2      120              McAllister
2      120              Fowler
</code>```

The specification returns nothing.

When I see the generated statement, I understand why it doesn't work :

```<code> where
  classRooms.teacher=?
  and classRooms.teacher=?
</code>```

I was expecting something like :

```<code>where
  students0.classroom_id in (
    select classrooms0.classroom_id where
    classRooms.teacher=?
  )
  and students0.classroom_id in (
    select classrooms0.classroom_id where
    classRooms.teacher=?
  )
</code>```

Question : how can make a query with the Criteria API work in my case ?

答:
You will need Subquery to achieve what you want if you need to stick with Criteria API. Otherwise, HQL can be a better choice for the sake of readability compared to the verbosity of Criteria API.

The idea is to generate individual queries and make a manual join through a predicate. So no need for a Join or SetJoin.

First, note that there are some mistakes in your code. The most obvious one is the path you used to reach the age field. You should use the generated metamodel instead of hard coded strings.

```<code>predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get(Student_.age), age));
</code>```

instead of :

```<code>predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.<Integert>get(age), Integer.valueOf(v)));
</code>```

Then, here is the complete solution :

```<code>public static Specification<Student> withTeacherAndName(){
  return new Specification<Student>() {

    @Override
    public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> criteriaQuery,
        CriteriaBuilder criteriaBuilder) {

      List<Predicate> predicates = new ArrayList<>();
      predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get(Student_.age), 20));

      Subquery<String> sq1 = criteriaQuery.subquery(String.class);
      Root<Classroom> classroomRoot = sq1.from(Classroom.class);
      sq1.select(classroomRoot.get(Classroom_.classroomId));
      sq1.where(criteriaBuilder.equal(classroomRoot.get(Classroom_.teacher), "Marta"));

      Subquery<String> sq2 = criteriaQuery.subquery(String.class);
      Root<Classroom> classroomRoot2 = sq2.from(Classroom.class);
      sq2.select(classroomRoot2.get(Classroom_.classroomId));
      sq2.where(criteriaBuilder.equal(classroomRoot2.get(Classroom_.teacher), "Fowler"));

      criteriaQuery.where(criteriaBuilder.equal(root.get(Student_.classroomId), sq1));
      criteriaQuery.where(criteriaBuilder.equal(root.get(Student_.classroomId), sq2));

      return criteriaBuilder.and(predicates.toArray(new Predicate[]{}));
    }
  };
}
</code>```

So basically you are creating a subquery for each criteria.
The code needs a refactoring (a loop for example).

Body:
I put in place the following specification that represents the predicate construction for querying Students based on their age and their ClassRoom's teachers' name (one student can have one or more classroom)

public class StudentSpecification implements Specification<Student> {

  private final Integer age;

  public StudentSpecification(Integer age){
    this.age = age;
  }

  @Override
  public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
      List<Predicate> predicates = new ArrayList<>();

      predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.<Integert>get(age), Integer.valueOf(v)));

      SetJoin<Student, ClassRoom> classRooms = root.join(Student_.classRooms);

      predicates.add(criteriaBuilder.equal(classRooms.get(ClassRoom_.teacher), "Marta"));
      predicates.add(criteriaBuilder.equal(classRooms.get(ClassRoom_.teacher), "Fowler"));

      return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
  }
}

Here is an example of data :

Student
_____________________________________________
ID     CLASSROOM_ID     NAME         AGE
2      120              Pascal       22
8      120              Bryan        21

ClassRoom
_____________________________________________
ID     CLASSROOM_ID     TEACHER
1      120              Marta
2      120              McAllister
2      120              Fowler

The specification returns nothing.

When I see the generated statement, I understand why it doesn't work :

 where
  classRooms.teacher=?
  and classRooms.teacher=?

I was expecting something like :

where
  students0.classroom_id in (
    select classrooms0.classroom_id where
    classRooms.teacher=?
  )
  and students0.classroom_id in (
    select classrooms0.classroom_id where
    classRooms.teacher=?
  )

Question : how can make a query with the Criteria API work in my case ?

Body:
You will need Subquery to achieve what you want if you need to stick with Criteria API. Otherwise, HQL can be a better choice for the sake of readability compared to the verbosity of Criteria API.

The idea is to generate individual queries and make a manual join through a predicate. So no need for a Join or SetJoin.

First, note that there are some mistakes in your code. The most obvious one is the path you used to reach the age field. You should use the generated metamodel instead of hard coded strings.

predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get(Student_.age), age));

instead of :

predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.<Integert>get(age), Integer.valueOf(v)));

Then, here is the complete solution :

public static Specification<Student> withTeacherAndName(){
  return new Specification<Student>() {

    @Override
    public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> criteriaQuery,
        CriteriaBuilder criteriaBuilder) {

      List<Predicate> predicates = new ArrayList<>();
      predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get(Student_.age), 20));

      Subquery<String> sq1 = criteriaQuery.subquery(String.class);
      Root<Classroom> classroomRoot = sq1.from(Classroom.class);
      sq1.select(classroomRoot.get(Classroom_.classroomId));
      sq1.where(criteriaBuilder.equal(classroomRoot.get(Classroom_.teacher), "Marta"));

      Subquery<String> sq2 = criteriaQuery.subquery(String.class);
      Root<Classroom> classroomRoot2 = sq2.from(Classroom.class);
      sq2.select(classroomRoot2.get(Classroom_.classroomId));
      sq2.where(criteriaBuilder.equal(classroomRoot2.get(Classroom_.teacher), "Fowler"));

      criteriaQuery.where(criteriaBuilder.equal(root.get(Student_.classroomId), sq1));
      criteriaQuery.where(criteriaBuilder.equal(root.get(Student_.classroomId), sq2));

      return criteriaBuilder.and(predicates.toArray(new Predicate[]{}));
    }
  };
}

So basically you are creating a subquery for each criteria.
The code needs a refactoring (a loop for example).


问:
Robust React Native element finding using Appium
I'm using React Native to develop an app that requires end-to-end testing.

Coming from a Selenium WebDriver background, it seems to me that element finding in Appium can be very awkward compared to WebDriver, since native components only have ID and a single non-user-defined class.

Is there a way I can add some sort of metadata to elements to make them easy to find?

Say if I have a table with complex elements inside a cell, and I need to first find the right row, then the cell, and then find the right components to manipulate inside the cell.

Ideally I'd want to be able to enumerate rows by searching for something like "myTargetRows". That would give me a list of rows.

If I understand it correctly, no two components can have the same ID in native applications, so I can't use ID just like that, right? (I.e. use the same ID, "myTargetRows", for multiple row components).

If not, should I use numbered IDs like "myTargetRow0", "myTargetRow1", etc, and then use XPath to partially match the ID?

Isn't there a better way?

If I can do something like that, can I then just chain those findElement calls to find the right nested elements I want?

P.s.: I don't want to hardcode the exact component hierarchies in my locators to avoid invalidating them should I move anything around in my views, so those point-and-click solutions won't help.

P.s. 2: Solutions must work both on Android and iOS, even if I need to implement some sort of abstraction for it myself.

答: Take a look at article in Sauce Labs blog, thats a good a example of dealing with RN apps.</p>


问:
boostrap customize
I am working with Bootstrap, how can you customize the carousel?

Any suggestions?

https://v4-alpha.getbootstrap.com/components/carousel/

答:
.active.carousel-item-right, .carousel-item-next {
    -webkit-transform: translate3d(0,100%,0);
            transform: translate3d(0,100%,0);
}
.active.carousel-item-left, .carousel-item-prev {
    -webkit-transform: translate3d(0,-100%,0);
            transform: translate3d(0,-100%,0);
}
```

<p>... should do. See it in action: </p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.carousel-item.active.carousel-item-right,
.carousel-item.carousel-item-next {
    -webkit-transform: translate3d(0,100%,0);
            transform: translate3d(0,100%,0);
}
.carousel-item.active.carousel-item-left,
.carousel-item.carousel-item-prev {
    -webkit-transform: translate3d(0,-100%,0);
            transform: translate3d(0,-100%,0);
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

      <img class="d-block w-100" data-src="holder.js/800x400?auto=yes&bg=777&fg=555&text=First slide" alt="First slide [800x400]" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15fc214ab4b%20text%20%7B%20fill%3A%23555%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15fc214ab4b%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22285.9296875%22%20y%3D%22217.7%22%3EFirst%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true">

      <img class="d-block w-100" data-src="holder.js/800x400?auto=yes&bg=666&fg=444&text=Second slide" alt="Second slide [800x400]" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15fc214ab4f%20text%20%7B%20fill%3A%23444%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15fc214ab4f%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23666%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22247.3203125%22%20y%3D%22217.7%22%3ESecond%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true">

      <img class="d-block w-100" data-src="holder.js/800x400?auto=yes&bg=555&fg=333&text=Third slide" alt="Third slide [800x400]" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15fc214ab52%20text%20%7B%20fill%3A%23333%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15fc214ab52%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23555%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22277.0078125%22%20y%3D%22217.7%22%3EThird%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true">

    Previous

    Next

```

Note: In the example, I had to make the selectors stronger, by adding .carousel-item to them, but that's only because bootstrap.css gets loaded after the snippet CSS, (which I think is a bug and it's clearly wrong). In real life, the code on top will suffice, as long as you it load after bootstrap(.min).css

Title: boostrap customize

Body:
.active.carousel-item-right, .carousel-item-next {
    -webkit-transform: translate3d(0,100%,0);
            transform: translate3d(0,100%,0);
}
.active.carousel-item-left, .carousel-item-prev {
    -webkit-transform: translate3d(0,-100%,0);
            transform: translate3d(0,-100%,0);
}

... should do. See it in action:

.carousel-item.active.carousel-item-right,
.carousel-item.carousel-item-next {
    -webkit-transform: translate3d(0,100%,0);
            transform: translate3d(0,100%,0);
}
.carousel-item.active.carousel-item-left,
.carousel-item.carousel-item-prev {
    -webkit-transform: translate3d(0,-100%,0);
            transform: translate3d(0,-100%,0);
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item">
      <img class="d-block w-100" data-src="holder.js/800x400?auto=yes&amp;bg=777&amp;fg=555&amp;text=First slide" alt="First slide [800x400]" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15fc214ab4b%20text%20%7B%20fill%3A%23555%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15fc214ab4b%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22285.9296875%22%20y%3D%22217.7%22%3EFirst%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true">
    </div>
    <div class="carousel-item active">
      <img class="d-block w-100" data-src="holder.js/800x400?auto=yes&amp;bg=666&amp;fg=444&amp;text=Second slide" alt="Second slide [800x400]" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15fc214ab4f%20text%20%7B%20fill%3A%23444%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15fc214ab4f%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23666%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22247.3203125%22%20y%3D%22217.7%22%3ESecond%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true">
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" data-src="holder.js/800x400?auto=yes&amp;bg=555&amp;fg=333&amp;text=Third slide" alt="Third slide [800x400]" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15fc214ab52%20text%20%7B%20fill%3A%23333%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15fc214ab52%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23555%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22277.0078125%22%20y%3D%22217.7%22%3EThird%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

Note: In the example, I had to make the selectors stronger, by adding .carousel-item to them, but that's only because bootstrap.css gets loaded after the snippet CSS, (which I think is a bug and it's clearly wrong). In real life, the code on top will suffice, as long as you it load after bootstrap(.min).css


问:
Python Logging - Extra Output?
I'm building a Logger class for a project, and I have specified an output, which presents logs in the format

```<code>2017-05-16 13:29:17,573 - Geospatial - INFO - Using only New York Geolocations
2017-05-16 13:29:18,325 - Server - INFO - Successfully launched AppLogs consumer
</code>```

But the console is also printing this line, which I do not want.

INFO:Server:Successfully launched AppLogs consumer

The logger is printing the correct output to the output file. I thought maybe it had something to do with the handlers, but I wasn't able to block it with the modifications I tried. Any thoughts would be appreciated.

Here's the class:

```<code>import os
import logging
import logging.config
import yaml

class Logger():

    #Types of Logs: debug, info, warning & error

    def __init__(self, name):

        with open("config.yml", 'r') as ymlfile:
            cfg = yaml.load(ymlfile)

        if 'file_name' in cfg['logging']:
            file_name = cfg['logging']['file_name']
        else:
            file_name = 'application'

        if 'folder_name' in cfg['logging']:
            folder_name = cfg['logging']['folder_name']
        else:
            folder_name = 'logs'

        if not os.path.exists('{}/'.format(folder_name)):
            os.makedirs(folder_name)
        file_name = os.path.join(os.getcwd(),
                                 '{}/{}.log'.format(folder_name, file_name))

        name = name.replace('.log','')

        if name.lower() in cfg['logging']:

            if cfg['logging'][name.lower()] == 'info':
                level = logging.INFO
            elif cfg['logging'][name.lower()] == 'debug':
                level = logging.DEBUG
            elif cfg['logging'][name.lower()] == 'error':
                level = logging.ERROR
            else:
                level = logging.DEBUG
        else:
            level = logging.DEBUG

        logger = logging.getLogger('{}'.format(name))
        logger.setLevel(level)

        # create formatter
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        handler = logging.FileHandler(file_name)
        handler.setFormatter(formatter)
        handler.setLevel(level)
        logger.addHandler(handler)

        ch = logging.StreamHandler()
        ch.setLevel(level)

        # add formatter to ch
        ch.setFormatter(formatter)

        # add ch to logger
        logger.addHandler(ch)

        self._logger = logger

    def get(self):
        return self._logger
</code>```

答:
This is because of:

ch = logging.StreamHandler()

as this creates an handler that outputs things on console, see https://docs.python.org/2/library/logging.handlers.html#streamhandler

Remove it, and the associated addHandler call, to remove output on console if you do not want it.

Title: Python Logging - Extra Output?

Body:
I'm building a Logger class for a project, and I have specified an output, which presents logs in the format

2017-05-16 13:29:17,573 - Geospatial - INFO - Using only New York Geolocations
2017-05-16 13:29:18,325 - Server - INFO - Successfully launched AppLogs consumer

But the console is also printing this line, which I do not want.

INFO:Server:Successfully launched AppLogs consumer

The logger is printing the correct output to the output file. I thought maybe it had something to do with the handlers, but I wasn't able to block it with the modifications I tried. Any thoughts would be appreciated.

Here's the class:

import os
import logging
import logging.config
import yaml

class Logger():

    #Types of Logs: debug, info, warning & error

    def __init__(self, name):

        with open("config.yml", 'r') as ymlfile:
            cfg = yaml.load(ymlfile)

        if 'file_name' in cfg['logging']:
            file_name = cfg['logging']['file_name']
        else:
            file_name = 'application'

        if 'folder_name' in cfg['logging']:
            folder_name = cfg['logging']['folder_name']
        else:
            folder_name = 'logs'

        if not os.path.exists('{}/'.format(folder_name)):
            os.makedirs(folder_name)
        file_name = os.path.join(os.getcwd(),
                                 '{}/{}.log'.format(folder_name, file_name))

        name = name.replace('.log','')

        if name.lower() in cfg['logging']:

            if cfg['logging'][name.lower()] == 'info':
                level = logging.INFO
            elif cfg['logging'][name.lower()] == 'debug':
                level = logging.DEBUG
            elif cfg['logging'][name.lower()] == 'error':
                level = logging.ERROR
            else:
                level = logging.DEBUG
        else:
            level = logging.DEBUG

        logger = logging.getLogger('{}'.format(name))
        logger.setLevel(level)

        # create formatter
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        handler = logging.FileHandler(file_name)
        handler.setFormatter(formatter)
        handler.setLevel(level)
        logger.addHandler(handler)

        ch = logging.StreamHandler()
        ch.setLevel(level)

        # add formatter to ch
        ch.setFormatter(formatter)

        # add ch to logger
        logger.addHandler(ch)

        self._logger = logger

    def get(self):
        return self._logger


问:
Pull data from multiple tables in Rails
I am new in Ruby on Rails and I am trying to make a book registration website. Everything works fine except category section. When a user assign a category to his book, my database copies book_categories.id and put it in book.book_categories_id. The website also have a profile page, where you can view user's book(s). My problem is to display a category.name, I searched a lot of similar problems but I have not found the right answer.

Here is my book controller:

```<code>before_action :set_book, except: [:index, :new, :create]
before_action :authenticate_user!, except: [:show]

def show
  @photos = @book.photos
end

def index
  @books = current_user.books
end

def new
  @book = current_user.books.build
end

def create
  @book = current_user.books.build(books_params)
  if @book.save
    redirect_to listing_book_path(@book), notice: "Saved."
  else
    flash[:alert] = "Failed."
    render :new
  end
end

private
  def set_book
    @book = Book.find(params[:id])
  end

  def book_params
    params.require(:book).permit(:book_categories_id, :book_name, :summary, :address, :price, :company_name)
  end
</code>```

As long as I understand, I have to allow my controller to have access to my category table but I do not know how. Also, all of my categories store in seed.rb.

This is my BookCategory.rb model:

```<code>class BookCategory < ActiveRecord::Base
  has_many :books, :foreign_key => :book_categories_id
end
</code>```

Book.rb model:

```<code>class Book < ApplicationRecord
  belongs_to :user, :foreign_key => 'user_id'
  has_many :photos, dependent: :delete_all

  validates :book_name, presence: true
  validates :book_categories_id, presence: true

  def cover_photo
    if self.photos.length > 0
      self.photos[0].image.url
    else
      "default/image-default.jpg"
    end
  end

end
</code>```

My schema.rb:

```<code>create_table "book_categories", force: :cascade do |t|
  t.string "name"
  t.string "subcategory"
  t.text "description"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

create_table "book", force: :cascade do |t|
  t.string "book_name"
  t.text "summary"
  t.string "address"
  t.decimal "price", precision: 8, scale: 2
  t.boolean "active"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.integer "user_id"
  t.float "latitude"
  t.float "longitude"
  t.string "company_name"
  t.integer "book_categories_id"
  t.index ["book_categories_id"], name: "index_books_on_book_categories_id"
end
</code>```

Usually, when I type @book_categories.name, I get an error:

```<code>undefined method `name' for nil:NilClass
</code>```

And at the very end, it says Parameters: {"id"=>"15"} whereas the category.id is different, and it passes book.id instead.

What I am doing wrong?

答:
First fix the naming problem you have going. I don't know how the books table got called "book" instead of "books" in the schema, but you might have to fix that first.

Then category should be singular everywhere except the database table name. You need to make a migration to fix the foreign key and its index in the books table something like this:

```<code>class FixCategoryNaming < ActiveRecord::Migration
  def change
    remove_column :books, :book_categories_id
    add_reference :books, :book_category, index: true, foreign_key: true
  end
end
</code>```

Then run rails db:migrate and check the schema looks ok

Then in the BookCategory class change the line to simply

```<code>has_many :books
</code>```

You need to add this line to your Book class

```<code>belongs_to :book_category
</code>```

and change the validation for book_category to be this

```<code>validates :book_category_id, presence: true
</code>```

Then in the view for book index you have a @books variable. You can get the book name and category name for each book like this:

```<code><% @books.each do |book| %>
  <p><%= book.book_name %></p>
  <p><%= book.book_categories.name %></p>
<% end %>
</code>```

Title: Pull data from multiple tables in Rails

Body:
I am new in Ruby on Rails and I am trying to make a book registration website. Everything works fine except category section. When a user assign a category to his book, my database copies book_categories.id and put it in book.book_categories_id. The website also have a profile page, where you can view user's book(s). My problem is to display a category.name, I searched a lot of similar problems but I have not found the right answer.

Here is my book controller:

before_action :set_book, except: [:index, :new, :create]
before_action :authenticate_user!, except: [:show]

def show
  @photos = @book.photos
end

def index
  @books = current_user.books
end

def new
  @book = current_user.books.build
end

def create
  @book = current_user.books.build(books_params)
  if @book.save
    redirect_to listing_book_path(@book), notice: "Saved."
  else
    flash[:alert] = "Failed."
    render :new
  end
end

private
  def set_book
    @book = Book.find(params[:id])
  end

  def book_params
    params.require(:book).permit(:book_categories_id, :book_name, :summary, :address, :price, :company_name)
  end

As long as I understand, I have to allow my controller to have access to my category table but I do not know how. Also, all of my categories store in seed.rb.

This is my BookCategory.rb model:

class BookCategory < ActiveRecord::Base
  has_many :books, :foreign_key => :book_categories_id
end

Book.rb model:

class Book < ApplicationRecord
  belongs_to :user, :foreign_key => 'user_id'
  has_many :photos, dependent: :delete_all

  validates :book_name, presence: true
  validates :book_categories_id, presence: true

  def cover_photo
    if self.photos.length > 0
      self.photos[0].image.url
    else
      "default/image-default.jpg"
    end
  end

end

My schema.rb:

create_table "book_categories", force: :cascade do |t|
  t.string "name"
  t.string "subcategory"
  t.text "description"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

create_table "book", force: :cascade do |t|
  t.string "book_name"
  t.text "summary"
  t.string "address"
  t.decimal "price", precision: 8, scale: 2
  t.boolean "active"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.integer "user_id"
  t.float "latitude"
  t.float "longitude"
  t.string "company_name"
  t.integer "book_categories_id"
  t.index ["book_categories_id"], name: "index_books_on_book_categories_id"
end

Usually, when I type @book_categories.name, I get an error:

undefined method `name' for nil:NilClass

And at the very end, it says Parameters: {"id"=>"15"} whereas the category.id is different, and it passes book.id instead.

What I am doing wrong?

Body:
First fix the naming problem you have going. I don't know how the books table got called "book" instead of "books" in the schema, but you might have to fix that first.

Then category should be singular everywhere except the database table name. You need to make a migration to fix the foreign key and its index in the books table something like this:

class FixCategoryNaming < ActiveRecord::Migration
  def change
    remove_column :books, :book_categories_id
    add_reference :books, :book_category, index: true, foreign_key: true
  end
end

Then run rails db:migrate and check the schema looks ok

Then in the BookCategory class change the line to simply

has_many :books

You need to add this line to your Book class

belongs_to :book_category

and change the validation for book_category to be this

validates :book_category_id, presence: true

Then in the view for book index you have a @books variable. You can get the book name and category name for each book like this:

<% @books.each do |book| %>
  <p><%= book.book_name %></p>
  <p><%= book.book_categories.name %></p>
<% end %>


问:
Install xslt_process on ProstgreSQL 8.4 Windows if it was not installed when PostgreSQL was
Is this possible? If so how?

I have looked at Libxslt which is what it uses but it seems to involve installing a bunch of binaries and still will not be available as PostgreSQL function...

UPDATE: I ended up having problems using xlst_process() on large transformations which caused PostgreSQL to crash and ended up using FOP invoked by a plpythonu function.

答:
xslt_process() requires Libxml to be installed, available (by adding Windows PATH Environment variables) and the xslt_process() function to be created

Solution:

Download and extract the zip: libxslt-1.1.26.win32.zip from ftp://ftp.zlatkovic.com/libxml/ to place on your dirve

Add the location of xsltproc.exe to your Windows PATH environment varible such as: "C:\libxml\libxslt-1.1.26.win32\bin". You will know this is working when you can run it from the cmd line.

libxml2.dll, libxslt.dll and iconv.dll which are also required by xsltproc.exe (they can downloaded using the above link but I found them to already be in my PostgreSQL\8.4\bin dir) and need to have their location added to the Windows PATH too, such as: "C:\PostgreSQL\8.4\bin"

Run the SQL (which I copied from the bottom of "PostgreSQL\8.4\share\contrib\pgxml.sql"):
```
CREATE OR REPLACE FUNCTION xslt_process(text,text,text)
RETURNS text
AS '$libdir/pgxml'
LANGUAGE C STRICT VOLATILE;

-- the function checks for the correct argument count

CREATE OR REPLACE FUNCTION xslt_process(text,text)
RETURNS text
AS '$libdir/pgxml'
LANGUAGE C STRICT IMMUTABLE;
  </li>
</ol>

<p>```

The Libxml windows binaries are helpfully maintained and provided by: http://www.zlatkovic.com/libxml.en.html

(NOTE: Windows User enviroment varibles do not require a restart but are only avaliable to the user, so my tip is add the varibles to System and User PATH's)

Body:
xslt_process() requires Libxml to be installed, available (by adding Windows PATH Environment variables) and the xslt_process() function to be created

Solution:

Download and extract the zip: libxslt-1.1.26.win32.zip from ftp://ftp.zlatkovic.com/libxml/ to place on your dirve

Add the location of xsltproc.exe to your Windows PATH environment varible such as: "C:\libxml\libxslt-1.1.26.win32\bin". You will know this is working when you can run it from the cmd line.

libxml2.dll, libxslt.dll and iconv.dll which are also required by xsltproc.exe (they can downloaded using the above link but I found them to already be in my PostgreSQL\8.4\bin dir) and need to have their location added to the Windows PATH too, such as: "C:\PostgreSQL\8.4\bin"

Run the SQL (which I copied from the bottom of "PostgreSQL\8.4\share\contrib\pgxml.sql"):

CREATE OR REPLACE FUNCTION xslt_process(text,text,text)
RETURNS text
AS '$libdir/pgxml'
LANGUAGE C STRICT VOLATILE;

-- the function checks for the correct argument count

CREATE OR REPLACE FUNCTION xslt_process(text,text)
RETURNS text
AS '$libdir/pgxml'
LANGUAGE C STRICT IMMUTABLE;

The Libxml windows binaries are helpfully maintained and provided by: http://www.zlatkovic.com/libxml.en.html

(NOTE: Windows User enviroment varibles do not require a restart but are only avaliable to the user, so my tip is add the varibles to System and User PATH's)

ContentLicense: CC BY-SA 2.5


问:
Boolean attribute in python object
It requires isgood to be a string only. I want it to be boolean.
Also self.__isgood = goodornot should throw an error, why not?

```<code>class Animal:
    Name = ""
    isgood = None

    def setisgood(self,goodornot):
        self.__isgood = goodornot

    def nameset(self,name):
        self.Name = name

dog = Animal()
dog.setisgood(False)
dog.nameset("jaang")
print("Your pet is:"+dog.isgood)
</code>```

答:
```<code>print("Your pet is:"+dog.isgood)
</code>```

is attempting to concatenate a boolean and a string, which cannot be done. In order to do so, you either need to convert dog.isgood into a string

```<code>print("Your pet is:" + str(dog.isgood))
</code>```

like TheoretiCAL suggested in the comments, or use format

```<code>print("Your pet is:{}".format(dog.isgood))
</code>```

like Ignacio Vazquez-Abrams answer, or

```<code>print("Your pet is:%s" % dog.isgood)
</code>```

or,

```<code>print("Your pet is:", dog.isgood)
</code>```

All of these examples will result in the following output:

```<code>Your pet is:False
</code>```

Edit:
Thank you juanpa for pointing this out. The spacing on the class is incorrect and should be causing an issue (I guess I assumed initially that it was just a copy paste thing).

```<code>class Animal:
    def __init__(self):
        self.Name = ""
        self.isgood = None

    def setisgood(self,goodornot):
        self.isgood = goodornot

    def nameset(self,name):
        self.Name = name

dog = Animal()
dog.setisgood(False)
dog.nameset("jaang")
print("Your pet is:", dog.isgood)
</code>```

Title: Boolean attribute in python object

Body:
It requires isgood to be a string only. I want it to be boolean.
Also self.__isgood = goodornot should throw an error, why not?

class Animal:
    Name = ""
    isgood = None

    def setisgood(self,goodornot):
        self.__isgood = goodornot

    def nameset(self,name):
        self.Name = name

dog = Animal()
dog.setisgood(False)
dog.nameset("jaang")
print("Your pet is:"+dog.isgood)

Body:
print("Your pet is:"+dog.isgood)

is attempting to concatenate a boolean and a string, which cannot be done. In order to do so, you either need to convert dog.isgood into a string

print("Your pet is:" + str(dog.isgood))

like TheoretiCAL suggested in the comments, or use format

print("Your pet is:{}".format(dog.isgood))

like Ignacio Vazquez-Abrams answer, or

print("Your pet is:%s" % dog.isgood)

or,

print("Your pet is:", dog.isgood)

All of these examples will result in the following output:

Your pet is:False

Edit:
Thank you juanpa for pointing this out. The spacing on the class is incorrect and should be causing an issue (I guess I assumed initially that it was just a copy paste thing).

class Animal:
    def __init__(self):
        self.Name = ""
        self.isgood = None

    def setisgood(self,goodornot):
        self.isgood = goodornot

    def nameset(self,name):
        self.Name = name

dog = Animal()
dog.setisgood(False)
dog.nameset("jaang")
print("Your pet is:", dog.isgood)


问:
WordPress Category custom fields
Hi I want to filter posts with custom category fields. I created custom field and it's working.

```<code>/*  Custom Field for Categories.
    ======================================== */

// Add new term page
function my_taxonomy_add_meta_fields( $taxonomy ) { ?>
    <div class="form-field term-group">
        <label for="show_category">
          <?php _e( 'Show Category', 'codilight-lite' ); ?> <input type="checkbox" id="show_category" name="show_category" value="yes" />
        </label>
    </div><?php
}
add_action( 'category_add_form_fields', 'my_taxonomy_add_meta_fields', 10, 2 );

// Edit term page
function my_taxonomy_edit_meta_fields( $term, $taxonomy ) {
    $show_category = get_term_meta( $term->term_id, 'show_category', true ); ?>

    <tr class="form-field term-group-wrap">
        <th scope="row">
            <label for="show_category"><?php _e( 'Show Category', 'codilight-lite' ); ?></label>
        </th>
        <td>
            <input type="checkbox" id="show_category" name="show_category" value="yes" <?php echo ( $show_category ) ? checked( $show_category, 'yes' ) : ''; ?>/>
        </td>
    </tr><?php
}
add_action( 'category_edit_form_fields', 'my_taxonomy_edit_meta_fields', 10, 2 );

// Save custom meta
function my_taxonomy_save_taxonomy_meta( $term_id, $tag_id ) {
    if ( isset( $_POST[ 'show_category' ] ) ) {
        update_term_meta( $term_id, 'show_category', 'yes' );
    } else {
        update_term_meta( $term_id, 'show_category', '' );
    }
}
add_action( 'created_category', 'my_taxonomy_save_taxonomy_meta', 10, 2 );
add_action( 'edited_category', 'my_taxonomy_save_taxonomy_meta', 10, 2 );
</code>```

Now I want to filter posts which show category select box checked yes. I'm trying query like this but it's not working

```<code>$argswp = array(
'post_type' => "post",
'tax_query' => array( array(
    'taxonomy' => 'season',
    'field' => 'slug',
    'terms' => 'yes'
    )),
);

$the_query = new WP_Query($argswp);
</code>```

I tried slug or id in field section by the way it's still not working. How can I fix this?

答:
I found the solution</p>

```<code>$seasons = get_categories(
    array(
        'orderby'    => 'name',
        'order'      => 'ASC',
        'hide_empty' => '0',
        'meta_query' => array(
            array(
                'key'     => 'show_category',
                'value'   => 'yes',
                'compare' => '=',
            )
        )
    )
);
</code>```

Title: WordPress Category custom fields

Body:
Hi I want to filter posts with custom category fields. I created custom field and it's working.

/*  Custom Field for Categories.
    ======================================== */

// Add new term page
function my_taxonomy_add_meta_fields( $taxonomy ) { ?>

          <?php _e( 'Show Category', 'codilight-lite' ); ?> <input type="checkbox" id="show_category" name="show_category" value="yes" />

<?php
}
add_action( 'category_add_form_fields', 'my_taxonomy_add_meta_fields', 10, 2 );

// Edit term page
function my_taxonomy_edit_meta_fields( $term, $taxonomy ) {
    $show_category = get_term_meta( $term->term_id, 'show_category', true ); ?>

            <?php _e( 'Show Category', 'codilight-lite' ); ?>

            <input type="checkbox" id="show_category" name="show_category" value="yes" <?php echo ( $show_category ) ? checked( $show_category, 'yes' ) : ''; ?>/>

<?php
}
add_action( 'category_edit_form_fields', 'my_taxonomy_edit_meta_fields', 10, 2 );

// Save custom meta
function my_taxonomy_save_taxonomy_meta( $term_id, $tag_id ) {
    if ( isset( $_POST[ 'show_category' ] ) ) {
        update_term_meta( $term_id, 'show_category', 'yes' );
    } else {
        update_term_meta( $term_id, 'show_category', '' );
    }
}
add_action( 'created_category', 'my_taxonomy_save_taxonomy_meta', 10, 2 );
add_action( 'edited_category', 'my_taxonomy_save_taxonomy_meta', 10, 2 );

Now I want to filter posts which show category select box checked yes. I'm trying query like this but it's not working

$argswp = array(
'post_type' => "post",
'tax_query' => array( array(
    'taxonomy' => 'season',
    'field' => 'slug',
    'terms' => 'yes'
    )),
);

$the_query = new WP_Query($argswp);

I tried slug or id in field section by the way it's still not working. How can I fix this?

Body:
I found the solution

$seasons = get_categories(
    array(
        'orderby'    => 'name',
        'order'      => 'ASC',
        'hide_empty' => '0',
        'meta_query' => array(
            array(
                'key'     => 'show_category',
                'value'   => 'yes',
                'compare' => '=',
            )
        )
    )
);


问:
ERROR in Entry module not found
This is the error:

SyntaxError: Unexpected token } in JSON at position 322. But JSON file
  is correct.

JSON file:

```<code>    {
      "name": "gl",
      "version": "1.0.0",
      "description": "GL online CV",
      "main": "index.html",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "Alex Guzhyk",
      "license": "ISC",
      "dependencies": {
        "express": "^4.16.2",
        "react": "^16.1.1",
        "react-dom": "^16.1.1",
      },
      "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "babel-preset-env": "^1.6.1",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "webpack": "^3.8.1",
        }
    }
</code>```

答:
Validate your JSON to know if the format is correct.

Remove the trailing comma at the end of the collection.

```<code>{
      "name": "gl",
      "version": "1.0.0",
      "description": "GL online CV",
      "main": "index.html",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "Alex Guzhyk",
      "license": "ISC",
      "dependencies": {
        "express": "^4.16.2",
        "react": "^16.1.1",
        "react-dom": "^16.1.1"
      },
      "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "babel-preset-env": "^1.6.1",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "webpack": "^3.8.1"
        }
    }
</code>```

You can check it here:
https://jsonlint.com/

Title: ERROR in Entry module not found

Body:
This is the error:

SyntaxError: Unexpected token } in JSON at position 322. But JSON file
  is correct.

JSON file:

    {
      "name": "gl",
      "version": "1.0.0",
      "description": "GL online CV",
      "main": "index.html",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "Alex Guzhyk",
      "license": "ISC",
      "dependencies": {
        "express": "^4.16.2",
        "react": "^16.1.1",
        "react-dom": "^16.1.1",
      },
      "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "babel-preset-env": "^1.6.1",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "webpack": "^3.8.1",
        }
    }

Body:
Validate your JSON to know if the format is correct.

Remove the trailing comma at the end of the collection.

{
      "name": "gl",
      "version": "1.0.0",
      "description": "GL online CV",
      "main": "index.html",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "Alex Guzhyk",
      "license": "ISC",
      "dependencies": {
        "express": "^4.16.2",
        "react": "^16.1.1",
        "react-dom": "^16.1.1"
      },
      "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "babel-preset-env": "^1.6.1",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "webpack": "^3.8.1"
        }
    }

You can check it here:
https://jsonlint.com/


问:
handle exceptions in stream java 8
I have a string:

```<code>"1, 2, 3 , -4"
</code>```

it is split by ", ".
I have a function to convert a number to a enum type which works fine. I want to use java 8 to convert this string to a list of enum objects.

```<code>Pattern pattern = Pattern.compile(", ");
List<f> fList = pattern.splitAsStream(str)
  .map(s -> {
    try {
      return this.getEnumObject(Integer.valueOf(s), f.class);
    }
    catch (NoEleException e) {
      e.printStackTrace();
    }
  })
  .collect(Collectors.toList());
</code>```

This gives me an error:

```<code>missing return type.
</code>```

How could I fix it?

答: Currently, if an exception occurs no result will be returned hence the compilation error. You'll need to return a value after the catch block .

Title: handle exceptions in stream java 8

Body:
I have a string:

"1, 2, 3 , -4"

it is split by ", ".
I have a function to convert a number to a enum type which works fine. I want to use java 8 to convert this string to a list of enum objects.

Pattern pattern = Pattern.compile(", ");
List<f> fList = pattern.splitAsStream(str)
  .map(s -> {
    try {
      return this.getEnumObject(Integer.valueOf(s), f.class);
    }
    catch (NoEleException e) {
      e.printStackTrace();
    }
  })
  .collect(Collectors.toList());

This gives me an error:

missing return type.

How could I fix it?


问:
C#, iTextSharp 5.5.10 Shown "Cannot access a closed file." on document close command
I don't know how to solve this because the document seem close before the actual command even I put command to open it again. Please help.

This is my code. When I click the button it will do this and the error will occur at doc.close() line. It shown "Cannot access a closed file." Even I put doc.open() above.

```<code>private void run_Click(object sender, EventArgs e)
    {
        Document doc = new Document(PageSize.A4);

        using(FileStream op = new FileStream("text.pdf", FileMode.Create))
        {
            PdfWriter wri = PdfWriter.GetInstance(doc, op);
            Paragraph p = new Paragraph("test");
            doc.Open();
            doc.Add(p);
        }

        using (FileStream op = new FileStream("text.pdf", FileMode.Append, FileAccess.Write))
        {

            PdfWriter wri = PdfWriter.GetInstance(doc, op);
            Paragraph p = new Paragraph("test2");
            doc.Open();
            doc.Add(p);
            doc.Close();
        }

    }
</code>```

答:
First of all, it is not a correct way to add some contents to an existing PDF by appending a PDF file. If you want to add contents to an existing PDF, please check ITextSharp insert text to an existing pdf.

However, if you just want it to work, you just need to create a new Document instance every time.

```<code>private void run_Click(object sender, EventArgs e)
{
    Document doc = new Document(PageSize.A4);

    using(FileStream op = new FileStream("text.pdf", FileMode.Create))
    {
        PdfWriter wri = PdfWriter.GetInstance(doc, op);
        Paragraph p = new Paragraph("test");
        doc.Open();
        doc.Add(p);
    }

    using (FileStream op = new FileStream("text.pdf", FileMode.Append, FileAccess.Write))
    {
        doc = new Document(PageSize.A4); // this is the fix
        PdfWriter wri = PdfWriter.GetInstance(doc, op);
        Paragraph p = new Paragraph("test2");
        doc.Open();
        doc.Add(p);
        doc.Close();
    }
}
</code>```

Body:
I don't know how to solve this because the document seem close before the actual command even I put command to open it again. Please help.

This is my code. When I click the button it will do this and the error will occur at doc.close() line. It shown "Cannot access a closed file." Even I put doc.open() above.

private void run_Click(object sender, EventArgs e)
    {
        Document doc = new Document(PageSize.A4);

        using(FileStream op = new FileStream("text.pdf", FileMode.Create))
        {
            PdfWriter wri = PdfWriter.GetInstance(doc, op);
            Paragraph p = new Paragraph("test");
            doc.Open();
            doc.Add(p);
        }

        using (FileStream op = new FileStream("text.pdf", FileMode.Append, FileAccess.Write))
        {

            PdfWriter wri = PdfWriter.GetInstance(doc, op);
            Paragraph p = new Paragraph("test2");
            doc.Open();
            doc.Add(p);
            doc.Close();
        }

    }

Body:
First of all, it is not a correct way to add some contents to an existing PDF by appending a PDF file. If you want to add contents to an existing PDF, please check ITextSharp insert text to an existing pdf.

However, if you just want it to work, you just need to create a new Document instance every time.

private void run_Click(object sender, EventArgs e)
{
    Document doc = new Document(PageSize.A4);

    using(FileStream op = new FileStream("text.pdf", FileMode.Create))
    {
        PdfWriter wri = PdfWriter.GetInstance(doc, op);
        Paragraph p = new Paragraph("test");
        doc.Open();
        doc.Add(p);
    }

    using (FileStream op = new FileStream("text.pdf", FileMode.Append, FileAccess.Write))
    {
        doc = new Document(PageSize.A4); // this is the fix
        PdfWriter wri = PdfWriter.GetInstance(doc, op);
        Paragraph p = new Paragraph("test2");
        doc.Open();
        doc.Add(p);
        doc.Close();
    }
}


问:
Git/Github: How to transfer changes from one repository to another
Steps I have made:

I found a project in Github that I thought I could contribute.

I cloned it directly without creating a Fork.

I made my changes

Now that I want to upload my changes, I realized that I was not working in a fork.

How do I manage to upload my changes to the repository of the fork in order to do a Pull Request from the fork to the original repository?

答:
Add another git remote with your repo URL and then push to it:

```<code>git remote add myrepo git@github.com:your-user/repo
git push myrepo master
</code>```

You can push to master or to any remote branch you want.

Both repos should share the root tree, which is the case if you have forked it.

As an alternative, you could change your current origin remote and then push normally to origin:

```<code>git remote set-url origin git@github.com:your-user/repo
git push origin master
</code>```

Body:
Add another git remote with your repo URL and then push to it:

git remote add myrepo git@github.com:your-user/repo
git push myrepo master

You can push to master or to any remote branch you want.

Both repos should share the root tree, which is the case if you have forked it.

As an alternative, you could change your current origin remote and then push normally to origin:

git remote set-url origin git@github.com:your-user/repo
git push origin master


问:
How to get Sql Temp Table Join with column values that are not in table, replaced by 0
I have 5 temp tables that I want to combine into a new temp table via the month_year column and the prod_id. Where the columns are not prod_id or month_year and values are not available, I want that column's value(e.g. job_amt or received_qty) to be 0.

```<code>#tmp_spoilt_good_job_amt
month_year  job_amt     spoil   good    prod_id
07-2017         40      10        20    2
08-2017         827     0         210   3
09-2017         27      1         27    2
09-2017         732     22        345   3
10-2017         50      0         6     2
10-2017         1130    55        50    3
11-2017         300     0         0     4

#tmp_received_qty
month_year  received_qty    prod_id
 08-2017    32                 2
 08-2017    2500               3
 09-2017    2200               2
 11-2017    2500               4

#tmp_purchase_qty
month_year  purchase_qty    prod_id
 09-2017    11                 2

#tmp_opening_balance
month_year  opening_balance   prod_id
08-2017              32         2
08-2017             2500        3
09-2017               22        2
09-2017             2300        3
10-2017             2163        2
10-2017             2023        3
11-2017             2500        4

#tmp_closing_balance
month_year  closing_balance     prod_id
08-2017         2300                3
08-2017         32                  2
09-2017         2213                2
09-2017         1998                3
10-2017         1687                3
10-2017         2163                2
11-2017         2400                4
</code>```

I tried some inner joins but the values were repeating or some were not reflecting. what query could I use to get these combined?

I am looking for the following output:

答:
```<code>CREATE TABLE #table_with_all_months_prod_ids_using_cross_join (month_year, prod_id)
GO

INSERT #table_with_all_months_prod_ids_using_cross_join
SELECT t1.month_year, t2.prod_id
FROM monthyeartable t1
CROSS JOIN prodidtable t2

SELECT DISTINCT t0.month_year, t0.prod_id, ISNULL(t1.job_amt,0), ISNULL(t1.spoil,0), ISNULL(t1.good,0), ISNULL(t2.received_qty,0), ISNULL(t3.purchase_qty,0), ISNULL(t4.opening_balance,0), ISNULL(t5.closing_balance,0)
        FROM #table_with_all_months_prod_ids_using_cross_join t0
        LEFT JOIN #tmp_spoilt_good_job_amt t1 ON t0.month_year = t1.month_year AND t0.prod_id = t1.prod_id
        LEFT JOIN #tmp_received_qty t2 ON t0.month_year = t2.month_year AND t0.prod_id = t2.prod_id
        LEFT JOIN #tmp_purchase_qty t3 ON t0.month_year = t3.month_year AND t0.prod_id = t3.prod_id
        LEFT JOIN #tmp_opening_balance t4 ON t0.month_year = t4.month_year AND t0.prod_id = t4.prod_id
        LEFT JOIN #tmp_closing_balance t5 ON t0.month_year = t5.month_year AND t0.prod_id = t5.prod_id
WHERE NOT (t1.job_amt IS NULL AND t1.spoil IS NULL AND t1.good IS NULL AND t2.received_qty IS NULL AND t3.purchase_qty IS NULL AND t4.opening_balance IS NULL AND t5.closing_balance IS NULL)
</code>```

Body:
I have 5 temp tables that I want to combine into a new temp table via the month_year column and the prod_id. Where the columns are not prod_id or month_year and values are not available, I want that column's value(e.g. job_amt or received_qty) to be 0.

#tmp_spoilt_good_job_amt
month_year  job_amt     spoil   good    prod_id
07-2017         40      10        20    2
08-2017         827     0         210   3
09-2017         27      1         27    2
09-2017         732     22        345   3
10-2017         50      0         6     2
10-2017         1130    55        50    3
11-2017         300     0         0     4

#tmp_received_qty
month_year  received_qty    prod_id
 08-2017    32                 2
 08-2017    2500               3
 09-2017    2200               2
 11-2017    2500               4

#tmp_purchase_qty
month_year  purchase_qty    prod_id
 09-2017    11                 2

#tmp_opening_balance
month_year  opening_balance   prod_id
08-2017              32         2
08-2017             2500        3
09-2017               22        2
09-2017             2300        3
10-2017             2163        2
10-2017             2023        3
11-2017             2500        4

#tmp_closing_balance
month_year  closing_balance     prod_id
08-2017         2300                3
08-2017         32                  2
09-2017         2213                2
09-2017         1998                3
10-2017         1687                3
10-2017         2163                2
11-2017         2400                4

I tried some inner joins but the values were repeating or some were not reflecting. what query could I use to get these combined?

I am looking for the following output:


问:
PHP ecommerce API?
Is there such a thing as an open source PHP ecommerce API? That is, just the API (i.e., not a whole CMS etc.). I just want some sort of "library" I can invoke from my own code. All of the open source ecommerce solutions that I've run across (such as http://www.opencart.com/) include a whole UI, etc., which I don't want.

答:
You are most probably looking for the wrong thing. The "CMS", a.k.a. Shopping Cart System, is just a CMS, there is no API and there can't be one, it's just a content management system.

What you're most probably looking for is a payment system API? Like PayPal API, or 2CO API, the payment functions of which you can invoke from your code, like [Pay $20!], which transfers over to a PayPal Pay page, and they take the payment processing on from there.

Otherwise, you may also be interested in Google Checkout https://checkout.google.com/sell/ which has its own API, more information here: http://code.google.com/apis/checkout/

...or the eBay API http://developer.ebay.com/common/api/ if you want to connect your code to and use eBay for all processing.

If this does not answer your question, please provide more information as to the requirements you are actually expecting from this "API".

Title: PHP ecommerce API?


问:
Sorting an Array with the SORT_STRING flag cause a NOTICE: Array to string conversion
My code (PHP)

The array

```<code>switch (strtoupper($OBJType))
   {
    case "FILE" :
         $SortWith = "A:";
         break;
    case "DIR" :
         $SortWith = "B:";
         break;
    Default:
         $SortWith = "C:";
   }

$dirArray[] = array(
                    'SortBy' => $SortWith,
                    'Data' => $OBJ
                   );
</code>```

My attempt to sort it

```<code>sort(($dirArray),SORT_STRING);
</code>```

The above creates the "Array to string conversion " notice in the error log file. I tried the following but I'm not sure its working; The array contains a sublist of files and directories from the current directory. I would like all files to float to the top with directories on the bottom. File and DIR names should be sorted withing the return list. I'm think I need to use array_multisort but I can't figure it out - any help would be appreciated

答:
OK So after a bunch of searching and trying to wrap my head around what I found. I used this code. I think it is working but I have to test some more. I'm open to suggestions if there are better/easier ways ... </p>

```<code>//First Sort Item
$SA1 = array();
foreach ($dirArray as $sVal)
        {
          $SA1[] = $sVal['SortBy'];
        }
//Second Sort Item
$SA2 = array();
foreach ($dirArray as $dVal)
        {
          $SA2[] = $dVal['Data'];
        }
//print "<BR> SA1 "; print_r($SA1); print "<BR> SA2 "; print_r($SA2);
array_multisort($SA1,  SORT_ASC, SORT_STRING, $dirArray, $SA2,  SORT_ASC, SORT_STRING, $dirArray);
</code>```

Body:
My code (PHP)

The array

switch (strtoupper($OBJType))
   {
    case "FILE" :
         $SortWith = "A:";
         break;
    case "DIR" :
         $SortWith = "B:";
         break;
    Default:
         $SortWith = "C:";
   }

$dirArray[] = array(
                    'SortBy' => $SortWith,
                    'Data' => $OBJ
                   );

My attempt to sort it

sort(($dirArray),SORT_STRING);

The above creates the "Array to string conversion " notice in the error log file. I tried the following but I'm not sure its working; The array contains a sublist of files and directories from the current directory. I would like all files to float to the top with directories on the bottom. File and DIR names should be sorted withing the return list. I'm think I need to use array_multisort but I can't figure it out - any help would be appreciated

Body:
OK So after a bunch of searching and trying to wrap my head around what I found. I used this code. I think it is working but I have to test some more. I'm open to suggestions if there are better/easier ways ...

//First Sort Item
$SA1 = array();
foreach ($dirArray as $sVal)
        {
          $SA1[] = $sVal['SortBy'];
        }
//Second Sort Item
$SA2 = array();
foreach ($dirArray as $dVal)
        {
          $SA2[] = $dVal['Data'];
        }
//print "<BR> SA1 "; print_r($SA1); print "<BR> SA2 "; print_r($SA2);
array_multisort($SA1,  SORT_ASC, SORT_STRING, $dirArray, $SA2,  SORT_ASC, SORT_STRING, $dirArray);


答: You can create Null Object like MissingElement,  return it in catch and them filter it out after map. </p>

Title: handle exceptions in stream java 8


问:
Product removal from cart not working in MVC Music Store (AJAX)
I am new to asp.net MVC. I am working in MVC Music Store. I am almost done with coding part but i stuck while doing remove item from cart part.

The code I use on the View Page is the following:

```
</div>
</div>
</p>

<p>Here is the action link </p>

```
            <a href="#" class="RemoveLink" data-id="<%:item.RecordId %>">Remove from cart

```

<p>http://localhost:14652/ShoppingCart# When i click on Remove cart link, it changes to this url. </p>

```//
    // AJAX: /ShoppingCart/RemoveFromCart/5
    [HttpPost]
    public ActionResult RemoveFromCart(int id)
    {
        // Remove the item from the cart
        var cart = ShoppingCart.GetCart(this.HttpContext);

        // Get the name of the album to display confirmation
        string albumName = storeDB.Carts
            .Single(item => item.RecordId == id).Album.Title;

        // Remove from cart
        int itemCount = cart.RemoveFromCart(id);

        // Display the confirmation message
        var results = new ShoppingCartRemoveViewModel
        {
            Message = Server.HtmlEncode(albumName) +
                " has been removed from your shopping cart.",
            CartTotal = cart.GetTotal(),
            CartCount = cart.GetCount(),
            ItemCount = itemCount,
            DeleteId = id
        };
        return Json(results);
    }
```

Kindly help me with this.

答:
I had the same problem.  I had to change the following line from

```<code><script src="/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
</code>```

to

```<code><script src="/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
</code>```

and everything worked after that.  I could not believe it was so simple.

Body:
I am new to asp.net MVC. I am working in MVC Music Store. I am almost done with coding part but i stuck while doing remove item from cart part.

The code I use on the View Page is the following:

Here is the action link

            <a href="#" class="RemoveLink" data-id="<%:item.RecordId %>">Remove from cart

http://localhost:14652/ShoppingCart# When i click on Remove cart link, it changes to this url.

//
    // AJAX: /ShoppingCart/RemoveFromCart/5
    [HttpPost]
    public ActionResult RemoveFromCart(int id)
    {
        // Remove the item from the cart
        var cart = ShoppingCart.GetCart(this.HttpContext);

        // Get the name of the album to display confirmation
        string albumName = storeDB.Carts
            .Single(item => item.RecordId == id).Album.Title;

        // Remove from cart
        int itemCount = cart.RemoveFromCart(id);

        // Display the confirmation message
        var results = new ShoppingCartRemoveViewModel
        {
            Message = Server.HtmlEncode(albumName) +
                " has been removed from your shopping cart.",
            CartTotal = cart.GetTotal(),
            CartCount = cart.GetCount(),
            ItemCount = itemCount,
            DeleteId = id
        };
        return Json(results);
    }

Kindly help me with this.

Body:
I had the same problem.  I had to change the following line from

<script src="/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>

to

<script src="/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>

and everything worked after that.  I could not believe it was so simple.


问:
PhantomJS failing to load Google Maps
My end goal is to open a local html file with javascript embedded, creating a map with polygons, and take a screenshot of it using PhantomJS. I have written a simple JS file to do this:

```<code>var page = require('webpage').create();
page.open('https://www.google.com/maps', function(status) {
  console.log('State: ' + status);
  if(status === 'success') {
      page.render('example.pdf', {format: 'pdf', quality: '100'});
  }
  phantom.exit();
});
</code>```

This returns the error:

```<code>ReferenceError: Can't find variable: google
</code>```

I've tried this on a local html file and on other websites using google maps and I keep getting the same error. I have been successful in taking a screenshot of other websites without google maps. Searching the internet it doesn't seem like people have had issues like this, and have been successful in taking screenshots of pages with google maps...so I'm wondering what could be wrong.

Another note: I installed PhantomJS as a gem in my rails project and am running the javascript file through the rails console using this gem. I have tried it using the standard installation of PhantomJS (v 2.0.0) and it still didn't work.

答:
you should give puppeter a go, it makes that easy:</p>

```<code>const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({path: 'example.pdf'});

  await browser.close();
})();
</code>```

Title: PhantomJS failing to load Google Maps

Body:
My end goal is to open a local html file with javascript embedded, creating a map with polygons, and take a screenshot of it using PhantomJS. I have written a simple JS file to do this:

var page = require('webpage').create();
page.open('https://www.google.com/maps', function(status) {
  console.log('State: ' + status);
  if(status === 'success') {
      page.render('example.pdf', {format: 'pdf', quality: '100'});
  }
  phantom.exit();
});

This returns the error:

ReferenceError: Can't find variable: google

I've tried this on a local html file and on other websites using google maps and I keep getting the same error. I have been successful in taking a screenshot of other websites without google maps. Searching the internet it doesn't seem like people have had issues like this, and have been successful in taking screenshots of pages with google maps...so I'm wondering what could be wrong.

Another note: I installed PhantomJS as a gem in my rails project and am running the javascript file through the rails console using this gem. I have tried it using the standard installation of PhantomJS (v 2.0.0) and it still didn't work.

Body:
you should give puppeter a go, it makes that easy:

const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({path: 'example.pdf'});

  await browser.close();
})();


问:
Dispose C# DLL marked for COM interop
I created a vanilla C# dll and marked it for COM inter op. The dll is a plain user form with no functionality as this is an experiment.

I registered the DLL and opened active x test container and instantiated my COM object. It shows up in the test container and i can view the exposed methods of the control - these are the default methods and not created by me.

i then exit from the active x test container and i noticed that test container was still lurking around in task manager and that i had to kill the process manually. This leads me to believe that the test container still holds a reference to my C# dll exposed for com inter op.

The default dispose method in the designer.cs is

```<code> protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);

   }
</code>```

When i used the test container with Quick time, it invoked quick time as expected and when i closed the test container it disposed correctly and did not leave a footprint in the task manager.

The question - is there a specific thing that i must do in my dispose method? Also, this may not be relevant, but when i create a test project and it launches my c# control and i click on the close button, it closes my test form but the test application ins still running in debug mode - the run button is disabled.

答: In addition to overriding Dispose(bool) you need to override IDisposable.Dispose() in that method you call Dispose(true) then call GC.SurpressFinalize(this). Also you have to call Dispose() on all members that implement IDisposable in the override of Dispose(bool)</p>

Title: Dispose C# DLL marked for COM interop

Body:
I created a vanilla C# dll and marked it for COM inter op. The dll is a plain user form with no functionality as this is an experiment.

I registered the DLL and opened active x test container and instantiated my COM object. It shows up in the test container and i can view the exposed methods of the control - these are the default methods and not created by me.

i then exit from the active x test container and i noticed that test container was still lurking around in task manager and that i had to kill the process manually. This leads me to believe that the test container still holds a reference to my C# dll exposed for com inter op.

The default dispose method in the designer.cs is

 protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);

   }

When i used the test container with Quick time, it invoked quick time as expected and when i closed the test container it disposed correctly and did not leave a footprint in the task manager.

The question - is there a specific thing that i must do in my dispose method? Also, this may not be relevant, but when i create a test project and it launches my c# control and i click on the close button, it closes my test form but the test application ins still running in debug mode - the run button is disabled.

OwnerDisplayName: SpaceghostAli


问:
bufferReader or InputStreamReader always throws exception
I created a java program that would just read a webpages code... google's for example and it works fine.  However I have tried to implement the same code in an android application both in the emulator and on the actual device-Droid X.

I've tried two separate ways and have found either way it is the same line that throws the IOException.  It is the line that creates the new bufferReader.  I don't know if it is the bufferReader or the InputStreamReader.  Also I don't really know how to get anymore information out of the exceptions other than to print out IOException.  Here is the important code stripped down. Thanks.

```
try
        {
//method 1
         URL page = new URL("http://192.168.1.108/score.php");
         URLConnection pageconnection = page.openConnection();
         BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    pageconnection.getInputStream()));

//method 2
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            BufferedReader rd  = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((inputLine = rd.readLine()) != null)
            System.out.println(inputLine);

          in.close();
          rd.close();
            HscoreText.setText("It Worked!");
        }
        catch(MalformedURLException e)
        {
         HscoreText.setText("MalformedURL");
        }
        catch (IOException e)
        {
         HscoreText.setText("IOException");
        }
```

答:
Or shameless plug you can use Resty and don't bother with URLConnection and stuff.

```<code>Resty r = new Resty();
String text = r.text("http://192.168.1.108/score.php").toString();
</code>```

It will honor the content encoding and gets out of your way otherwise.

Body:
I created a java program that would just read a webpages code... google's for example and it works fine.  However I have tried to implement the same code in an android application both in the emulator and on the actual device-Droid X.

I've tried two separate ways and have found either way it is the same line that throws the IOException.  It is the line that creates the new bufferReader.  I don't know if it is the bufferReader or the InputStreamReader.  Also I don't really know how to get anymore information out of the exceptions other than to print out IOException.  Here is the important code stripped down. Thanks.

try
        {
//method 1
         URL page = new URL("http://192.168.1.108/score.php");
         URLConnection pageconnection = page.openConnection();
         BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    pageconnection.getInputStream()));

//method 2
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            BufferedReader rd  = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((inputLine = rd.readLine()) != null)
            System.out.println(inputLine);

          in.close();
          rd.close();
            HscoreText.setText("It Worked!");
        }
        catch(MalformedURLException e)
        {
         HscoreText.setText("MalformedURL");
        }
        catch (IOException e)
        {
         HscoreText.setText("IOException");
        }

Body:
Or shameless plug you can use Resty and don't bother with URLConnection and stuff.

Resty r = new Resty();
String text = r.text("http://192.168.1.108/score.php").toString();

It will honor the content encoding and gets out of your way otherwise.


问:
Define TabLayout style in theme
I have two different styles of TabLayout in my app:

```<code><style name="TabLayoutPower" parent="Widget.Design.TabLayout">
    <item name="tabSelectedTextColor">@android:color/white</item>
    <item name="tabTextColor">@android:color/white</item>
</style>

<style name="TabLayoutFree" parent="Widget.Design.TabLayout">
    <item name="tabSelectedTextColor">@android:color/black</item>
    <item name="tabTextColor">@android:color/black</item>
</style>
</code>```

How can I define the default TabLayout style for a theme? I cannot find any info which item name should I use to build my theme. I'd like to add the TabLayout the same way I added my listview:

```<code><style name="Free" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/black</item>
        <item name="colorPrimaryDark">@color/black</item>
        <item name="colorAccent">@color/main_red</item>
        <item name="android:windowBackground">@color/main_bg_light</item>
        <item name="android:listViewStyle">@style/MyListView</item>
    </style>
</code>```

答:
```<code>    <style name="Base.Widget.Design.TabLayout" parent="">
        <item name="tabSelectedTextColor">@android:color/white</item>
        <item name="tabTextColor">@android:color/white</item>
    </style>

<style name="Free" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/black</item>
        <item name="colorPrimaryDark">@color/black</item>
        <item name="colorAccent">@color/main_red</item>
        <item name="android:windowBackground">@color/main_bg_light</item>
        <item name="android:listViewStyle">@style/MyListView</item>
<item name="android:tabWidgetStyle">@style/Base.Widget.Design.TabLayout</item>
    </style>
</code>```

Title: Define TabLayout style in theme

Body:
I have two different styles of TabLayout in my app:

How can I define the default TabLayout style for a theme? I cannot find any info which item name should I use to build my theme. I'd like to add the TabLayout the same way I added my listview:


问:
How to subscribe to a Durable TOPIC using Apache camel / Spring-boot?
Whenever i start my subscriber, it is not appearing on my activeMQ under "Active Durable Topic Subscribers" section. Which means it is not a durable topic subscriber yet. How can i make it durable subscriber?

```<code>JmsComponent jmsComponent = JmsComponent
        .jmsComponentTransacted(connectionFactory, jmsTransactionManager);
// TODO
jmsComponent.setClientId(subscriptionClientId);
jmsComponent.setDurableSubscriptionName(subscriptionName);
jmsComponent.setSubscriptionDurable(true); // This is enabled by default
//jmsComponent.setMaxConcurrentConsumers(maxConcurrentConsumers);
jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);

return jmsComponent;
</code>```

P.S: It works fine for Non-durable subscribers. I added the below code in an attempt to make it durable. Am i missing something ? Do i need to add anything else?

```<code>jmsComponent.setClientId(subscriptionClientId);
jmsComponent.setDurableSubscriptionName(subscriptionName);
jmsComponent.setSubscriptionDurable(true); // This is enabled by default
</code>```

答:
I got it working by passing the subscription details as query string param as below;

myapp.jms.topic.inbound1=jms:topic:myFirstTopic?clientId=ABC&durableSubscriptionName=ABC

myapp.jms.topic.inbound2=jms:topic:mysecondTopic?clientId=XYZ&durableSubscriptionName=XYZ

ContentLicense: CC BY-SA 4.0

Body:
Whenever i start my subscriber, it is not appearing on my activeMQ under "Active Durable Topic Subscribers" section. Which means it is not a durable topic subscriber yet. How can i make it durable subscriber?

JmsComponent jmsComponent = JmsComponent
        .jmsComponentTransacted(connectionFactory, jmsTransactionManager);
// TODO
jmsComponent.setClientId(subscriptionClientId);
jmsComponent.setDurableSubscriptionName(subscriptionName);
jmsComponent.setSubscriptionDurable(true); // This is enabled by default
//jmsComponent.setMaxConcurrentConsumers(maxConcurrentConsumers);
jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);

return jmsComponent;

P.S: It works fine for Non-durable subscribers. I added the below code in an attempt to make it durable. Am i missing something ? Do i need to add anything else?

jmsComponent.setClientId(subscriptionClientId);
jmsComponent.setDurableSubscriptionName(subscriptionName);
jmsComponent.setSubscriptionDurable(true); // This is enabled by default


问:
Creating a dynamic URL in WordPress
I am making an e-commerce site with WordPress, Woocommerce, and BuddyPress. We allow members to upload images of their products. The product category name is the same as the member's username. So if exampleUser1 uploads a product image, that product is given the category 'exampleUser1'.

This is a temporary method that my team and I are using so members can see all of their products on one page (product-category page).

I want to create a dynamic URL that I can display via a button that links to the product-category page of the logged in user. I have researched how to do this using functions.php and passing variables to the URL but am having no luck getting anything to work.

Thank you for your help!

答:
You should change the category to a constant value for all users like productImage or something. Then no need for a dynamic URL, the same URL will work for all users. Just create a page template and use WP_Query in the loop like this:</p>

```<code>$author = get_current_user_id();
$args = array(
    'author' => $author,
    'post_status' => 'any',
    'category_name' => 'productImage',
    'post_type' => 'attachment'
);
$query = new WP_Query( $args );
</code>```

Title: Creating a dynamic URL in WordPress

Body:
You should change the category to a constant value for all users like productImage or something. Then no need for a dynamic URL, the same URL will work for all users. Just create a page template and use WP_Query in the loop like this:

$author = get_current_user_id();
$args = array(
    'author' => $author,
    'post_status' => 'any',
    'category_name' => 'productImage',
    'post_type' => 'attachment'
);
$query = new WP_Query( $args );


问:
How to get average, median, mean stats from a file which has numbers in first column?
I have a file in which I have numbers in seconds like below:

```<code>0.01033
0.003797
0.02648
0.007583
0.007491
0.028038
0.012794
0.00524
0.019655
0.019643
0.012969
0.011087
0.044564
</code>```

What is the best way by which I can get "average", "mean", "median", "95th percentile" and "99th percentile" from this file? I have this file in my linux box so I need some linux command by which I can get those stats.

答:
In case you're not bound to any specific tool, try GNU datamash - a nice tool for "command-line statistical operations" on textual files.

To get mean, median, percentile 95 and percentile 99 values for first column/field (note, fields are TAB-separated by default):

```<code>$ datamash --header-out mean 1 median 1 perc:95 1 perc:99 1  < file
mean(field-1)   median(field-1) perc:95(field-1)    perc:99(field-1)
0.016128538461538   0.012794    0.0346484   0.04258088
</code>```

Body:
I have a file in which I have numbers in seconds like below:

0.01033
0.003797
0.02648
0.007583
0.007491
0.028038
0.012794
0.00524
0.019655
0.019643
0.012969
0.011087
0.044564

What is the best way by which I can get "average", "mean", "median", "95th percentile" and "99th percentile" from this file? I have this file in my linux box so I need some linux command by which I can get those stats.

Body:
In case you're not bound to any specific tool, try GNU datamash - a nice tool for "command-line statistical operations" on textual files.

To get mean, median, percentile 95 and percentile 99 values for first column/field (note, fields are TAB-separated by default):

$ datamash --header-out mean 1 median 1 perc:95 1 perc:99 1  < file
mean(field-1)   median(field-1) perc:95(field-1)    perc:99(field-1)
0.016128538461538   0.012794    0.0346484   0.04258088


问:
ValueError: Floating point image RGB values must be in the 0..1 range. while using matplotlib
I want to visualize weights of the layer of a neural network. I'm using pytorch.

```<code>import torch
import torchvision.models as models
from matplotlib import pyplot as plt

def plot_kernels(tensor, num_cols=6):
    if not tensor.ndim==4:
        raise Exception("assumes a 4D tensor")
    if not tensor.shape[-1]==3:
        raise Exception("last dim needs to be 3 to plot")
    num_kernels = tensor.shape[0]
    num_rows = 1+ num_kernels // num_cols
    fig = plt.figure(figsize=(num_cols,num_rows))
    for i in range(tensor.shape[0]):
        ax1 = fig.add_subplot(num_rows,num_cols,i+1)
        ax1.imshow(tensor[i])
        ax1.axis('off')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])

    plt.subplots_adjust(wspace=0.1, hspace=0.1)
    plt.show()
vgg = models.vgg16(pretrained=True)
mm = vgg.double()
filters = mm.modules
body_model = [i for i in mm.children()][0]
layer1 = body_model[0]
tensor = layer1.weight.data.numpy()
plot_kernels(tensor)
</code>```

The above gives this error ValueError: Floating point image RGB values must be in the 0..1 range.

My question is should I normalize and take absolute value of the weights to overcome this error or is there anyother way ?
If I normalize and use absolute value I think the meaning of the graphs change.

```<code>[[[[ 0.02240197 -1.22057354 -0.55051649]
   [-0.50310904  0.00891289  0.15427093]
   [ 0.42360783 -0.23392732 -0.56789106]]

  [[ 1.12248898  0.99013627  1.6526649 ]
   [ 1.09936976  2.39608836  1.83921957]
   [ 1.64557672  1.4093554   0.76332706]]

  [[ 0.26969245 -1.2997849  -0.64577204]
   [-1.88377869 -2.0100112  -1.43068039]
   [-0.44531786 -1.67845118 -1.33723605]]]

 [[[ 0.71286005  1.45265901  0.64986968]
   [ 0.75984162  1.8061738   1.06934202]
   [-0.08650422  0.83452386 -0.04468433]]

  [[-1.36591709 -2.01630116 -1.54488969]
   [-1.46221244 -2.5365622  -1.91758668]
   [-0.88827479 -1.59151018 -1.47308767]]

  [[ 0.93600738  0.98174071  1.12213969]
   [ 1.03908169  0.83749604  1.09565806]
   [ 0.71188802  0.85773659  0.86840987]]]

 [[[-0.48592842  0.2971966   1.3365227 ]
   [ 0.47920835 -0.18186836  0.59673625]
   [-0.81358945  1.23862112  0.13635623]]

  [[-0.75361633 -1.074965    0.70477796]
   [ 1.24439156 -1.53563368 -1.03012812]
   [ 0.97597247  0.83084011 -1.81764793]]

  [[-0.80762428 -0.62829626  1.37428832]
   [ 1.01448071 -0.81775147 -0.41943246]
   [ 1.02848887  1.39178836 -1.36779451]]]

 ...,
 [[[ 1.28134537 -0.00482408  0.71610934]
   [ 0.95264435 -0.09291686 -0.28001019]
   [ 1.34494913  0.64477581  0.96984017]]

  [[-0.34442815 -1.40002513  1.66856039]
   [-2.21281362 -3.24513769 -1.17751861]
   [-0.93520379 -1.99811196  0.72937071]]

  [[ 0.63388056 -0.17022935  2.06905985]
   [-0.7285465  -1.24722099  0.30488953]
   [ 0.24900314 -0.19559766  1.45432627]]]

 [[[-0.80684513  2.1764245  -0.73765725]
   [-1.35886598  1.71875226 -1.73327696]
   [-0.75233924  2.14700699 -0.71064663]]

  [[-0.79627383  2.21598244 -0.57396138]
   [-1.81044972  1.88310981 -1.63758397]
   [-0.6589964   2.013237   -0.48532376]]

  [[-0.3710472   1.4949851  -0.30245575]
   [-1.25448656  1.20453358 -1.29454732]
   [-0.56755757  1.30994892 -0.39370224]]]

 [[[-0.67361742 -3.69201088 -1.23768616]
   [ 3.12674141  1.70414758 -1.76272404]
   [-0.22565465  1.66484773  1.38172317]]

  [[ 0.28095332 -2.03035069  0.69989491]
   [ 1.97936332  1.76992691 -1.09842575]
   [-2.22433758  0.52577412  0.18292744]]

  [[ 0.48471382 -1.1984663   1.57565165]
   [ 1.09911084  1.31910467 -0.51982772]
   [-2.76202297 -0.47073677  0.03936549]]]]
</code>```

答:
It sounds as if you already know your values are not in that range.  Yes, you must re-scale them to the range 0.0 - 1.0.  I suggest that you want to retain visibility of negative vs positive, but that you let 0.5 be your new "neutral" point.  Scale such that current 0.0 values map to 0.5, and your most extreme value (largest magnitude) scale to 0.0 (if negative) or 1.0 (if positive).

Thanks for the vectors.  It looks like your values are in the range -2.25 to +2.0.  I suggest a rescaling new = (1/(2*2.25)) * old + 0.5

Body:
I want to visualize weights of the layer of a neural network. I'm using pytorch.

import torch
import torchvision.models as models
from matplotlib import pyplot as plt

def plot_kernels(tensor, num_cols=6):
    if not tensor.ndim==4:
        raise Exception("assumes a 4D tensor")
    if not tensor.shape[-1]==3:
        raise Exception("last dim needs to be 3 to plot")
    num_kernels = tensor.shape[0]
    num_rows = 1+ num_kernels // num_cols
    fig = plt.figure(figsize=(num_cols,num_rows))
    for i in range(tensor.shape[0]):
        ax1 = fig.add_subplot(num_rows,num_cols,i+1)
        ax1.imshow(tensor[i])
        ax1.axis('off')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])

    plt.subplots_adjust(wspace=0.1, hspace=0.1)
    plt.show()
vgg = models.vgg16(pretrained=True)
mm = vgg.double()
filters = mm.modules
body_model = [i for i in mm.children()][0]
layer1 = body_model[0]
tensor = layer1.weight.data.numpy()
plot_kernels(tensor)

The above gives this error ValueError: Floating point image RGB values must be in the 0..1 range.

My question is should I normalize and take absolute value of the weights to overcome this error or is there anyother way ?
If I normalize and use absolute value I think the meaning of the graphs change.

[[[[ 0.02240197 -1.22057354 -0.55051649]
   [-0.50310904  0.00891289  0.15427093]
   [ 0.42360783 -0.23392732 -0.56789106]]

  [[ 1.12248898  0.99013627  1.6526649 ]
   [ 1.09936976  2.39608836  1.83921957]
   [ 1.64557672  1.4093554   0.76332706]]

  [[ 0.26969245 -1.2997849  -0.64577204]
   [-1.88377869 -2.0100112  -1.43068039]
   [-0.44531786 -1.67845118 -1.33723605]]]

 [[[ 0.71286005  1.45265901  0.64986968]
   [ 0.75984162  1.8061738   1.06934202]
   [-0.08650422  0.83452386 -0.04468433]]

  [[-1.36591709 -2.01630116 -1.54488969]
   [-1.46221244 -2.5365622  -1.91758668]
   [-0.88827479 -1.59151018 -1.47308767]]

  [[ 0.93600738  0.98174071  1.12213969]
   [ 1.03908169  0.83749604  1.09565806]
   [ 0.71188802  0.85773659  0.86840987]]]

 [[[-0.48592842  0.2971966   1.3365227 ]
   [ 0.47920835 -0.18186836  0.59673625]
   [-0.81358945  1.23862112  0.13635623]]

  [[-0.75361633 -1.074965    0.70477796]
   [ 1.24439156 -1.53563368 -1.03012812]
   [ 0.97597247  0.83084011 -1.81764793]]

  [[-0.80762428 -0.62829626  1.37428832]
   [ 1.01448071 -0.81775147 -0.41943246]
   [ 1.02848887  1.39178836 -1.36779451]]]

 ...,
 [[[ 1.28134537 -0.00482408  0.71610934]
   [ 0.95264435 -0.09291686 -0.28001019]
   [ 1.34494913  0.64477581  0.96984017]]

  [[-0.34442815 -1.40002513  1.66856039]
   [-2.21281362 -3.24513769 -1.17751861]
   [-0.93520379 -1.99811196  0.72937071]]

  [[ 0.63388056 -0.17022935  2.06905985]
   [-0.7285465  -1.24722099  0.30488953]
   [ 0.24900314 -0.19559766  1.45432627]]]

 [[[-0.80684513  2.1764245  -0.73765725]
   [-1.35886598  1.71875226 -1.73327696]
   [-0.75233924  2.14700699 -0.71064663]]

  [[-0.79627383  2.21598244 -0.57396138]
   [-1.81044972  1.88310981 -1.63758397]
   [-0.6589964   2.013237   -0.48532376]]

  [[-0.3710472   1.4949851  -0.30245575]
   [-1.25448656  1.20453358 -1.29454732]
   [-0.56755757  1.30994892 -0.39370224]]]

 [[[-0.67361742 -3.69201088 -1.23768616]
   [ 3.12674141  1.70414758 -1.76272404]
   [-0.22565465  1.66484773  1.38172317]]

  [[ 0.28095332 -2.03035069  0.69989491]
   [ 1.97936332  1.76992691 -1.09842575]
   [-2.22433758  0.52577412  0.18292744]]

  [[ 0.48471382 -1.1984663   1.57565165]
   [ 1.09911084  1.31910467 -0.51982772]
   [-2.76202297 -0.47073677  0.03936549]]]]