问:
AbstractSet.removeAll() method not working properly
The code shown below does output:

[b]

[a, b]

However I would expect it to print two identical lines in the output.

```<code>import java.util.*;

public class Test{
    static void test(String... abc) {
        Set<String> s = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
        s.addAll(Arrays.asList("a", "b"));
        s.removeAll(Arrays.asList(abc));
        System.out.println(s);
    }

    public static void main(String[] args) {
        test("A");
        test("A", "C");
    }
}
</code>```

The spec clearly states that removeAll

"Removes all this collection's elements that are also contained in the
  specified collection."

So from my understanding current behavior is unpredictable . Please help me understand this

答:
The reason is because the comparator String.CASE_INSENSITIVE_ORDER you use is not consistent with equals.

As stated by TreeSet:

Note that the ordering maintained by a set (whether or not an explicit comparator is provided)
  must be consistent with equals if it is to correctly implement the Set interface.

Consistency with equals as stated by Comparable:

The natural ordering for a class C is said to be consistent with equals if and only if
  e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2)
  for every e1 and e2 of class C.

And as an example for the case insensitive comparator you use:

```<code>"a".compareTo("A") == 0 => true
</code>```

while

```<code>"a".equals("A") => false
</code>```

Body:
The code shown below does output:

[b]

[a, b]

However I would expect it to print two identical lines in the output.

import java.util.*;

public class Test{
    static void test(String... abc) {
        Set<String> s = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
        s.addAll(Arrays.asList("a", "b"));
        s.removeAll(Arrays.asList(abc));
        System.out.println(s);
    }

    public static void main(String[] args) {
        test("A");
        test("A", "C");
    }
}

The spec clearly states that removeAll

"Removes all this collection's elements that are also contained in the
  specified collection."

So from my understanding current behavior is unpredictable . Please help me understand this

Body:
The reason is because the comparator String.CASE_INSENSITIVE_ORDER you use is not consistent with equals.

As stated by TreeSet:

Note that the ordering maintained by a set (whether or not an explicit comparator is provided)
  must be consistent with equals if it is to correctly implement the Set interface.

Consistency with equals as stated by Comparable:

The natural ordering for a class C is said to be consistent with equals if and only if
  e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2)
  for every e1 and e2 of class C.

And as an example for the case insensitive comparator you use:

"a".compareTo("A") == 0 => true

while

"a".equals("A") => false


来源: stackexchange

问:
Filtering specific data from a group of data in angularjs
I want to filter only specific data in angularjs.

here is my object,

```<code>$scope.studyTeamObj;
</code>```

In this object,I have object like this

```<code>{"Study_Team": [
{
  "designation": {
    "Emp_Name": "mdrf",
    "Emp_Id": 2,
    "Designation": "Research Dietitian",
    "DesignationID": 20
  }
}
]
}
</code>```

I want to filter like this.only two datas are enough.How can I do?

```<code>{
"Study_Team":[
{
  "Emp_Id":1,
  "DesignationID":20,
}
]
}
</code>```

答:
I presume you need an Angular filter without modifying the original object:

var angularApp = angular.module("app", []);
angularApp.filter("studyTeam", function(){
          return function(obj){
              var studyTeamArr = obj.Study_Team;
              return studyTeamArr.map(function(obj){
                       var desig = angular.copy(obj.designation);
                       delete desig.Emp_Name;
                       delete desig.Designation;
                       return desig;

               });
          } });

angularApp.controller("angCtrl", function($scope, $filter){

$scope.studyTeamObj = {"Study_Team": [
{
  "designation": {
    "Emp_Name": "mdrf",
    "Emp_Id": 2,
    "Designation": "Research Dietitian",
    "DesignationID": 20
  }
}
]
};

console.log( JSON.stringify( $filter('studyTeam')($scope.studyTeamObj)) );

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
<div ng-controller="angCtrl">

</div>

</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to filter only specific data in angularjs.

here is my object,

$scope.studyTeamObj;

In this object,I have object like this

{"Study_Team": [
{
  "designation": {
    "Emp_Name": "mdrf",
    "Emp_Id": 2,
    "Designation": "Research Dietitian",
    "DesignationID": 20
  }
}
]
}

I want to filter like this.only two datas are enough.How can I do?

{
"Study_Team":[
{
  "Emp_Id":1,
  "DesignationID":20,
}
]
}

Body:
I presume you need an Angular filter without modifying the original object:

var angularApp = angular.module("app", []);
angularApp.filter("studyTeam", function(){
          return function(obj){
              var studyTeamArr = obj.Study_Team;
              return studyTeamArr.map(function(obj){
                       var desig = angular.copy(obj.designation);
                       delete desig.Emp_Name;
                       delete desig.Designation;
                       return desig;

               });
          } });

angularApp.controller("angCtrl", function($scope, $filter){

$scope.studyTeamObj = {"Study_Team": [
{
  "designation": {
    "Emp_Name": "mdrf",
    "Emp_Id": 2,
    "Designation": "Research Dietitian",
    "DesignationID": 20
  }
}
]
};

console.log( JSON.stringify( $filter('studyTeam')($scope.studyTeamObj)) );

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
<div ng-controller="angCtrl">

</div>

</div>


问:
html/jquery how to hover div with its child when mouseenter
my idea is to create this:
https://blog.hubspot.com/hs-fs/hubfs/dubsat-contact-us-cities.gif?t=1490783992392&width=690&height=585&name=dubsat-contact-us-cities.gif

but the text has to be in div's with a picture not just fading in and fading out pictures. heres my shot:

#first{
    position: absolute;

}
#second{
    position: absolute;

    -webkit-transition: all 500ms ease-in-out;
    -moz-transition: all 500ms ease-in-out;
    -ms-transition: all 500ms ease-in-out;
    -o-transition: all 500ms ease-in-out;
    transition: all 500ms ease-in-out;
    position: absolute;
}
.text-box {
    position: absolute;
    height: 100%;
    text-align: center;
    width: 100%;
}
.text-box:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>

    </head>
    <h1 id="third">Kontaktai</h1>
    <!-- <div class="image">-->

    <div id="first" onmouseenter="showSecondImage()" onmouseleave="hideSecondImage()">
        <h4 class="text-box ">whyyyy</h4>
        <img class="img-responsive" src="http://kids.nationalgeographic.com/content/dam/kids/photos/animals/Mammals/H-P/photoark-lion.png.adapt.945.1.jpg" >
    </div>

    <div id="second">
        <h4 class="text-box">why its not working</h4>
        <img class="img-responsive" src="http://i.dailymail.co.uk/i/pix/2015/06/09/16/03BB5E5A0000044D-3117010-image-a-25_1433862086692.jpg" >
    </div>
    <script>
        $(".unbinded").unbind();
        function  showSecondImage() {
            document.getElementById('second').style.opacity=1;
        }
        function  hideSecondImage() {
            document.getElementById('second').style.opacity=0;
        }
    </script></code>```

why is not not working properly? i though i need to unbind onmouseenter and onmouseleave eventlisteners and bind the picture to listen when mouse enters..  any answers appreciated, im new to this.

答:
You can do this with CSS alone by hiding #second initially, then triggering it to show when you hover either #first or #second

#first {
  position: absolute;
}

#second {
  position: absolute;
  -webkit-transition: all 500ms ease-in-out;
  -moz-transition: all 500ms ease-in-out;
  -ms-transition: all 500ms ease-in-out;
  -o-transition: all 500ms ease-in-out;
  transition: all 500ms ease-in-out;
  opacity: 0;
}

.text-box {
  position: absolute;
  height: 100%;
  text-align: center;
  width: 100%;
}

.text-box:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

#first:hover + #second, #second:hover {
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 id="third">Kontaktai</h1>

<div id="first">
  <h4 class="text-box ">whyyyy</h4>
  <img class="img-responsive" src="http://kids.nationalgeographic.com/content/dam/kids/photos/animals/Mammals/H-P/photoark-lion.png.adapt.945.1.jpg">
</div>

<div id="second">
  <h4 class="text-box">why its not working</h4>
  <img class="img-responsive" src="http://i.dailymail.co.uk/i/pix/2015/06/09/16/03BB5E5A0000044D-3117010-image-a-25_1433862086692.jpg">
</div></code>```

Body:
my idea is to create this:
https://blog.hubspot.com/hs-fs/hubfs/dubsat-contact-us-cities.gif?t=1490783992392&width=690&height=585&name=dubsat-contact-us-cities.gif

but the text has to be in div's with a picture not just fading in and fading out pictures. heres my shot:

#first{
    position: absolute;

}
#second{
    position: absolute;

    -webkit-transition: all 500ms ease-in-out;
    -moz-transition: all 500ms ease-in-out;
    -ms-transition: all 500ms ease-in-out;
    -o-transition: all 500ms ease-in-out;
    transition: all 500ms ease-in-out;
    position: absolute;
}
.text-box {
    position: absolute;
    height: 100%;
    text-align: center;
    width: 100%;
}
.text-box:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

Kontaktai

whyyyy

why its not working

why is not not working properly? i though i need to unbind onmouseenter and onmouseleave eventlisteners and bind the picture to listen when mouse enters..  any answers appreciated, im new to this.

Body:
You can do this with CSS alone by hiding #second initially, then triggering it to show when you hover either #first or #second

#first {
  position: absolute;
}

#second {
  position: absolute;
  -webkit-transition: all 500ms ease-in-out;
  -moz-transition: all 500ms ease-in-out;
  -ms-transition: all 500ms ease-in-out;
  -o-transition: all 500ms ease-in-out;
  transition: all 500ms ease-in-out;
  opacity: 0;
}

.text-box {
  position: absolute;
  height: 100%;
  text-align: center;
  width: 100%;
}

.text-box:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

#first:hover + #second, #second:hover {
  opacity: 1;
}

<h1 id="third">Kontaktai</h1>

<div id="first">
  <h4 class="text-box ">whyyyy</h4>
  <img class="img-responsive" src="http://kids.nationalgeographic.com/content/dam/kids/photos/animals/Mammals/H-P/photoark-lion.png.adapt.945.1.jpg">
</div>

<div id="second">
  <h4 class="text-box">why its not working</h4>
  <img class="img-responsive" src="http://i.dailymail.co.uk/i/pix/2015/06/09/16/03BB5E5A0000044D-3117010-image-a-25_1433862086692.jpg">
</div>


问:
Giving database context to object Factory
There is a question I always ask myself when I'm using a Factory pattern inside my code (C#, but it applies to any language I suppose).

I have a "Service" that takes care of interacting with my database, do stuff with objects and interacts with my object model.

This Service uses a Factory sometimes to delegate the instanciation of an object.
But this factory obviously needs to interact by itself with the database to instanciate my object properly.
Is it a good/bad practice to pass the Database context to the Create method for example?

Like this :

```<code>var myNewObject = MyFactory.Create(myDatabaseContext);
</code>```

the other way would be to let the Service always be the only one to talk with the database.

```<code>var myNewObject = MyFactory.Create();
var extraProperty = myDatabaseContext.Get(something);
myNewObject.extraProp = extraProperty;
</code>```

Any advices?

答:
The idea of passing the database context into the factory create method is called method injection. This is a form of dependency injection, so you are on the right track.

You can use dependency injection to manage your database context inside of your factory via the constructor. The factory could look something like this:

```<code>public class MyFactory
{
    private readonly IMyDbContext dbContext;

    public MyFactory(IMyDbContext dbContext)
    {
        this.dbContext = dbContext;
    }

    public object Create()
    {
        // Use the dbContext, etc
    }
}
</code>```

Constructor injection is usually favored because it leaves method signatures less cluttered. We will also most likely have one type of database context so there will be no need to take advantage of polymorphism based on some other runtime information.

You can choose to use a Dependency Injection Container like Ninject or, my favorite, SimpleInjector to manage the dependencies for you.

It is OK to have the DbContext only used by the factory. One thing you may want to watch out for is that a user of your factory may not realize that the factory is calling to the database. This could be a bad thing and have negative performance implications. Typically, construction information is passed into the factory method, not initialized into the factory method from the DB. You could even take it a step further and use the Repository Pattern to abstract away some more of the data access logic if you think it is necessary and you don't have that already.

To learn more about Dependency Injection, in case you are unfamiliar, you can start here.

My ideal structure may look like this:

```<code>public class MyFactory : IFactory
{
    public object Create(object someProperty)
    {
        // build object
    }
}

public class MyService
{
    private readonly IMyDbContext dbContext;
    private readonly IFactory factory;

    public MyService(IMyDbContext dbContext, IFactory factory)
    {
        this.dbContext = dbContext;
        this.factory = factory;
    }

    public void DoWork()
    {
        var property = dbContext.Get(something);
        var newObj = factory.Create(property);
        // Use stuff
    }
}
</code>```

Body:
There is a question I always ask myself when I'm using a Factory pattern inside my code (C#, but it applies to any language I suppose).

I have a "Service" that takes care of interacting with my database, do stuff with objects and interacts with my object model.

This Service uses a Factory sometimes to delegate the instanciation of an object.
But this factory obviously needs to interact by itself with the database to instanciate my object properly.
Is it a good/bad practice to pass the Database context to the Create method for example?

Like this :

var myNewObject = MyFactory.Create(myDatabaseContext);

the other way would be to let the Service always be the only one to talk with the database.

var myNewObject = MyFactory.Create();
var extraProperty = myDatabaseContext.Get(something);
myNewObject.extraProp = extraProperty;

Any advices?

Body:
The idea of passing the database context into the factory create method is called method injection. This is a form of dependency injection, so you are on the right track.

You can use dependency injection to manage your database context inside of your factory via the constructor. The factory could look something like this:

public class MyFactory
{
    private readonly IMyDbContext dbContext;

    public MyFactory(IMyDbContext dbContext)
    {
        this.dbContext = dbContext;
    }

    public object Create()
    {
        // Use the dbContext, etc
    }
}

Constructor injection is usually favored because it leaves method signatures less cluttered. We will also most likely have one type of database context so there will be no need to take advantage of polymorphism based on some other runtime information.

You can choose to use a Dependency Injection Container like Ninject or, my favorite, SimpleInjector to manage the dependencies for you.

It is OK to have the DbContext only used by the factory. One thing you may want to watch out for is that a user of your factory may not realize that the factory is calling to the database. This could be a bad thing and have negative performance implications. Typically, construction information is passed into the factory method, not initialized into the factory method from the DB. You could even take it a step further and use the Repository Pattern to abstract away some more of the data access logic if you think it is necessary and you don't have that already.

To learn more about Dependency Injection, in case you are unfamiliar, you can start here.

My ideal structure may look like this:

public class MyFactory : IFactory
{
    public object Create(object someProperty)
    {
        // build object
    }
}

public class MyService
{
    private readonly IMyDbContext dbContext;
    private readonly IFactory factory;

    public MyService(IMyDbContext dbContext, IFactory factory)
    {
        this.dbContext = dbContext;
        this.factory = factory;
    }

    public void DoWork()
    {
        var property = dbContext.Get(something);
        var newObj = factory.Create(property);
        // Use stuff
    }
}


问:
two domains, same tracking snippet?
I am not well-versed in analytics.
I have set up a page (example2.com) for a client who already has a site (example1.com). The two sites serve different content but under the same "business umbrella". They sent me the analytics tracking snippet that they use on example1.com and said to use that on example2.com, which I have done.

I am uncertain if this will work, but do not want to question them directly at this stage.

Should they have set up a new property for example2.com? I am afraid they know as little as I do and that we are creating problems with our collective ignorance. Or is it all just a question of how they prefer to track?

答:
Technically this would work. They can collect data under a single tracking id and then use "views" (the areas in the interface where you actually see the data) that filter by hostname.

So in one view you would exclude views from domain2.com, in the other view you'd exclude domain1.com and you would have two sets of reports, one for each domain.

One reason to do this would be if you wanted to have a "rollup view", i.e. if you want to know how many pageviews and sessions you have for both of your domains combined.

While it is not exactly recommended by Google to have two independent domains in one property you won't get rollup reporting any other way in the free version of GA, so that would be a valid reason to track this way.

There are resources that are shared between views, but not between properties (i.e. custom dimensions/metrics) and some of the data might not necessarily make sense in a rollup report (e.g. averages do not make sense when calculated over two different data sets; also the rollup report will lump similar page paths together) but for many sites this would not be a problem.

So if they set up their views properly this would be okay and even useful (although it does not quite match the intended use for properties and views).

Title: two domains, same tracking snippet?


问:
Hibernate or JPA?
With Spring 3.0 is it recommended to use hibernate or JPA.What are the advantages and disadvantages of both of them when used with Spring 3.0 ?

Note : We are also suppose to use it with Spring Data Access.

答:
I would say, JPA implementation provided by Hibernate. Why? Because

It would be easier to switch to some other JPA implementation later, if you you ever need to

Hibernate is the one of the major and most popular ORM around

Lot of books available

Extensive documentation, awesome reference material

Easy to get support on SO, and elsewhere

Actually, I don't mind to use Hibernate exclusive features too. I don't see any problem in sticking with Hibernate, just because its not an standard. And by the way, what makes you think Spring is standard. Its not, and you are fine with it, because it works. Similar thing can be said for Hibernate. Hibernate sometimes get hairy, if you don't know well what you are doing.

ContentLicense: CC BY-SA 2.5

Title: Hibernate or JPA?


问:
Making a Simple Calculator
I'm trying to build a simple calculator for a class but for some reason the program keeps crashing.

I looked around and didn't see anything that can tell me what's wrong so I figured I'll ask here.

Now the trick is that we only learned up to if/else statements so that's the only functions we can use.

```<code>#include <stdio.h>

void main() {
  float num1, num2;
  int type;
  char oper;

  printf_s("Please enter your choise:\n1. Decimal calculator.\n2. Binary            calculator.\n");
  scanf_s("%d", &type);

  if (type == 1) {
    printf_s("Please enter the equation you want to solve and then press Enter:\n");
    scanf_s("%f %c %f",&num1,&oper,&num2);
  }
}
</code>```

Anyone has any idea what's wrong here? Everytime I input 1 + 1 for example the program crashes.

Thank you!

答:
Your problem is that scanf_s requires a buffer size specifier after every %c %s and %[.  See this post for a similar problem. Indeed, scanf does not have this issue, what you actually did was put the value of the address of num2 as the buffer size specifier for %c in:

```<code>scanf_s("%f %c %f",&num1,&oper,&num2);
</code>```

Note that even printf_s has additional requirements

The fix here while still using scanf_s is this:

```<code>#include <stdio.h>

int main() {
    float num1, num2;
    int type;
    char oper;
    const int oper_buff_size = 1;

    printf_s("Please enter your choise:\n1. Decimal calculator.\n2. Binary            calculator.\n");
    scanf_s("%d", &type);

    if (type == 1) {
        printf_s("Please enter the equation you want to solve and then press Enter:\n");
        // note oper_buff_size, the buffer size of the char pointer
        scanf_s("%f %c %f", &num1, &oper, oper_buff_size, &num2);
        // test to show this works
        printf_s("Entered: %f %c %f", num1, oper, num2);
    }
    return 0;
}
</code>```

You may be asking why we need to specify the length of a %c format, considering it should just be the size of a char in bytes.  I believe this is because you are required to put the pointer of a character for format, so you don't know if what you pointed to was a char * array or just a pointer to a char (as in this case)

I would also add an addendum, though this is not why your program failed, avoid using cross platform incompatible quirks, such as void main, as it makes it harder for people to find the real problems in your code.  Do not use void main(), use int main(...) and return 0; instead.  Void main is not valid in standard C or C++, it is a quirk of the Microsoft visual studio implementation of the language.

Title: Making a Simple Calculator

Body:
I'm trying to build a simple calculator for a class but for some reason the program keeps crashing.

I looked around and didn't see anything that can tell me what's wrong so I figured I'll ask here.

Now the trick is that we only learned up to if/else statements so that's the only functions we can use.

#include <stdio.h>

void main() {
  float num1, num2;
  int type;
  char oper;

  printf_s("Please enter your choise:\n1. Decimal calculator.\n2. Binary            calculator.\n");
  scanf_s("%d", &type);

  if (type == 1) {
    printf_s("Please enter the equation you want to solve and then press Enter:\n");
    scanf_s("%f %c %f",&num1,&oper,&num2);
  }
}

Anyone has any idea what's wrong here? Everytime I input 1 + 1 for example the program crashes.

Thank you!

Body:
Your problem is that scanf_s requires a buffer size specifier after every %c %s and %[.  See this post for a similar problem. Indeed, scanf does not have this issue, what you actually did was put the value of the address of num2 as the buffer size specifier for %c in:

scanf_s("%f %c %f",&num1,&oper,&num2);

Note that even printf_s has additional requirements

The fix here while still using scanf_s is this:

#include <stdio.h>

int main() {
    float num1, num2;
    int type;
    char oper;
    const int oper_buff_size = 1;

    printf_s("Please enter your choise:\n1. Decimal calculator.\n2. Binary            calculator.\n");
    scanf_s("%d", &type);

    if (type == 1) {
        printf_s("Please enter the equation you want to solve and then press Enter:\n");
        // note oper_buff_size, the buffer size of the char pointer
        scanf_s("%f %c %f", &num1, &oper, oper_buff_size, &num2);
        // test to show this works
        printf_s("Entered: %f %c %f", num1, oper, num2);
    }
    return 0;
}

You may be asking why we need to specify the length of a %c format, considering it should just be the size of a char in bytes.  I believe this is because you are required to put the pointer of a character for format, so you don't know if what you pointed to was a char * array or just a pointer to a char (as in this case)

I would also add an addendum, though this is not why your program failed, avoid using cross platform incompatible quirks, such as void main, as it makes it harder for people to find the real problems in your code.  Do not use void main(), use int main(...) and return 0; instead.  Void main is not valid in standard C or C++, it is a quirk of the Microsoft visual studio implementation of the language.


问:
Removing empty lists from csv file in Python 3
I have been working on code that takes rows from csv file and transfer them into the lists of integers for further mathematical operations. However, if a row turns out to be empty, it causes problems. Also, the user will not know which row is empty, so the solution should be general rather than pointing at a row and removing it. Here is the code:

```<code>import csv
import statistics as st

def RepresentsInt(i):
    try:
       int(i)
       return True
    except ValueError:
       return False
l = []

with open('Test.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')

    for row in reader:
        l.append([int(r) if RepresentsInt(r) else 0 for r in row])

    for row in l:

        row=[x for x in row if x!=0]
        row.sort()
        print(row)
</code>```

I've tried l=[row for row in l if row!=[]] and ...

```<code>if row==[]:
    l.remove(row)
</code>```

... but both do nothing, and there is no error code for either. Here is my csv file:

```<code>1,2,5,4
2,3
43,65,34,56,7

0,5
7,8,9,6,5

33,45,65,4
</code>```

If I run the code, I will get [] for row 4 and 6 (which are empty).

答:
This worked on my machine:</p>

```<code>import csv

def RepresentsInt(i):
    try:
       int(i)
       return True
    except ValueError:
       return False
l = []

with open('Test.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')

    for row in reader:
        l.append([int(r) for r in row if RepresentsInt(r)])

    rows = [row for row in l if row]
    for row in rows:
        print(row)
</code>```

Body:
I have been working on code that takes rows from csv file and transfer them into the lists of integers for further mathematical operations. However, if a row turns out to be empty, it causes problems. Also, the user will not know which row is empty, so the solution should be general rather than pointing at a row and removing it. Here is the code:

import csv
import statistics as st

def RepresentsInt(i):
    try:
       int(i)
       return True
    except ValueError:
       return False
l = []

with open('Test.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')

    for row in reader:
        l.append([int(r) if RepresentsInt(r) else 0 for r in row])

    for row in l:

        row=[x for x in row if x!=0]
        row.sort()
        print(row)

I've tried l=[row for row in l if row!=[]] and ...

if row==[]:
    l.remove(row)

... but both do nothing, and there is no error code for either. Here is my csv file:

1,2,5,4
2,3
43,65,34,56,7

0,5
7,8,9,6,5

33,45,65,4

If I run the code, I will get [] for row 4 and 6 (which are empty).

Body:
This worked on my machine:

import csv

def RepresentsInt(i):
    try:
       int(i)
       return True
    except ValueError:
       return False
l = []

with open('Test.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')

    for row in reader:
        l.append([int(r) for r in row if RepresentsInt(r)])

    rows = [row for row in l if row]
    for row in rows:
        print(row)


问:
UIScrollView within UICollectionViewCell Not Working
I have a UICollectionView with a custom UICollectionViewCell. The UICollectionView scrolls horizontally, with each cell occupying all of the visible screen.

The UICollectionViewCell has a UIView subview, which in turn has a UIScrollView subview.

The UIScrollView is intended to scroll vertically, but it's not scrolling at all. I've tried setting the scroll view's contentSize with no success.

I suspect that the UIScrollView is not getting any touch events rather than it being a size issue.

Any suggestions?

EDIT >>

I'm now sure it's an event problem rather than anything specific to the UIScrollView.

I've now overridden the pointInside: method in the UIView in the UICollectionViewCell and can see that it now returns false every time I tap on it. In that case you'd think that the tap event would propagate to the next subview , but the UIView still isn't getting events. I've tried adding a UIGestureRecognizer to the UIView but it never registers a tap.

Could there be anything here intercepting the events that I'm not aware of?

答:
I'm not sure if this was your problem, but it was mine - and I'm putting it here in case anyone else comes across this for the same reason.  I wanted to put a UIScrollView inside a UICollectionReusableView but by accident I had created my custom class as;

```<code>class CustomCellHeader: UICollectionViewCell {

}
</code>```

instead of;

```<code>class CustomCellHeader: UICollectionReusableView {

}
</code>```

Once I changed that, the UIScrollView within my header cell came to life!

Body:
I'm not sure if this was your problem, but it was mine - and I'm putting it here in case anyone else comes across this for the same reason.  I wanted to put a UIScrollView inside a UICollectionReusableView but by accident I had created my custom class as;

class CustomCellHeader: UICollectionViewCell {

}

instead of;

class CustomCellHeader: UICollectionReusableView {

}

Once I changed that, the UIScrollView within my header cell came to life!


问:
Jms How to know subscriber is not alive anymore
I have a distributed system application that uses JBoss as an application server. I have a client application that serves as a simulation engine. When client is up, it sends an registration message(JMS message)  to Server, then some field is set in the database. When Server is up, it sends a message ( a topic) to all clients to check that they are alive.  If clients are alive, they can read message and send a response to server (queue) that it is alive.

If user close client normally, client send a message to server that I will unregister. Then server unregisters it. This is done in database side.

If user close client abnormally(kill) , then client can not send a message to server for unregistration. Then server does not know this client is not alive anymore.  This causes inconsistency in my application. So I need a way to understand that client subscribed a topic is not subscribed anymore.

Server sends a message to topic to check that clients are alive.

```<code>@Schedule(hour = "*", minute = "*", second = "30", persistent = false)
public void sendNodeStatusRequest() {
    Message msg = MessageFactory.createStatusRequestMessage();
    publishNodeMessage(msg);

}
</code>```

After a time, Server show following logs. Could I catch this warning from Java?

```<code>07:17:00,698 WARN  [org.hornetq.core.protocol.core.impl.RemotingConnectionImpl] Connection failure
 has been detected: Did not receive ping from /127.0.0.1:61888. It is likely
 the client has exited or crashed without closing its connection, or the
 network between the server and client has failed. The connection will now be  closed. [code=3]
 07:17:00,698 WARN  [org.hornetq.core.server.impl.ServerSessionImpl] Client
connection failed, clearing up resources for session 4e4e9dc6-153e-11e7-
 80fa-742b62812c29
</code>```

答: If you still want to stick with JMS way of doing, then you can try to send the message synchronously, meaning the producer will wait until it hears from the consumer. More information here : http://docs.oracle.com/javaee/6/tutorial/doc/bncfa.html</p>

Body:
I have a distributed system application that uses JBoss as an application server. I have a client application that serves as a simulation engine. When client is up, it sends an registration message(JMS message)  to Server, then some field is set in the database. When Server is up, it sends a message ( a topic) to all clients to check that they are alive.  If clients are alive, they can read message and send a response to server (queue) that it is alive.

If user close client normally, client send a message to server that I will unregister. Then server unregisters it. This is done in database side.

If user close client abnormally(kill) , then client can not send a message to server for unregistration. Then server does not know this client is not alive anymore.  This causes inconsistency in my application. So I need a way to understand that client subscribed a topic is not subscribed anymore.

Server sends a message to topic to check that clients are alive.

@Schedule(hour = "*", minute = "*", second = "30", persistent = false)
public void sendNodeStatusRequest() {
    Message msg = MessageFactory.createStatusRequestMessage();
    publishNodeMessage(msg);

}

After a time, Server show following logs. Could I catch this warning from Java?

07:17:00,698 WARN  [org.hornetq.core.protocol.core.impl.RemotingConnectionImpl] Connection failure
 has been detected: Did not receive ping from /127.0.0.1:61888. It is likely
 the client has exited or crashed without closing its connection, or the
 network between the server and client has failed. The connection will now be  closed. [code=3]
 07:17:00,698 WARN  [org.hornetq.core.server.impl.ServerSessionImpl] Client
connection failed, clearing up resources for session 4e4e9dc6-153e-11e7-
 80fa-742b62812c29


问:
Assign value to readonly property works with fixed value but not with variable
Using Entity Framework to create an index and have the following code:

```<code>var op = new CreateIndexOperation
    {
        Columns = { "COL_A", "COL_B", "COL_C" },
        IsUnique = true,
        Name = "INDEX_NAME",
        Table = "TABLE_NAME"
    });
</code>```

This compiles and works as expected.  Trying to refactor this into the following method (simplified for this example):

```<code>private void AddIndex(params string[] columns)
{
    var op = new CreateIndexOperation
    {
        Columns = columns.ToList(),
        IsUnique = true,
        Name = "INDEX_NAME",
        Table = "TABLE_NAME"
    });
}
</code>```

This method throws the following compiler error:

```<code>Property or Indexer 'IndexOperation.Columns' cannot be assigned to -- it is read only
</code>```

Looking at the MSDN documentation, this appears to be correct and the Columns property doesn't have a setter.  However, if this is the case, why does the first block of code not throw a compiler-error, but the second does where I am trying to set this value from a variable instead?

答:
This is because when using the first code you´re using the collection-initializer, whereby the second example uses a classic setter-approach (which of course doesn´t exist). This means in the first example you´re actually calling something like this:

```<code>var op = new CreateIndexOperation();
op.Columns.Add(...);
op.IsUnique = true;
op.Name = "INDEX_NAME";
op.Table = "TABLE_NAME";
</code>```

As you can see you´re not setting the property, but instead you call a method on the object returned by the getter.

This of course assumes that Columns is initialized within the class´ constructor. Otherwise you´ll get a NullReferenceException.

The second code however compiles to this:

```<code>var op = new CreateIndexOperation();
op.Columns = columns.ToList();
op.IsUnique = true;
op.Name = "INDEX_NAME";
op.Table = "TABLE_NAME";
</code>```

Body:
Using Entity Framework to create an index and have the following code:

var op = new CreateIndexOperation
    {
        Columns = { "COL_A", "COL_B", "COL_C" },
        IsUnique = true,
        Name = "INDEX_NAME",
        Table = "TABLE_NAME"
    });

This compiles and works as expected.  Trying to refactor this into the following method (simplified for this example):

private void AddIndex(params string[] columns)
{
    var op = new CreateIndexOperation
    {
        Columns = columns.ToList(),
        IsUnique = true,
        Name = "INDEX_NAME",
        Table = "TABLE_NAME"
    });
}

This method throws the following compiler error:

Property or Indexer 'IndexOperation.Columns' cannot be assigned to -- it is read only

Looking at the MSDN documentation, this appears to be correct and the Columns property doesn't have a setter.  However, if this is the case, why does the first block of code not throw a compiler-error, but the second does where I am trying to set this value from a variable instead?

Body:
This is because when using the first code you´re using the collection-initializer, whereby the second example uses a classic setter-approach (which of course doesn´t exist). This means in the first example you´re actually calling something like this:

var op = new CreateIndexOperation();
op.Columns.Add(...);
op.IsUnique = true;
op.Name = "INDEX_NAME";
op.Table = "TABLE_NAME";

As you can see you´re not setting the property, but instead you call a method on the object returned by the getter.

This of course assumes that Columns is initialized within the class´ constructor. Otherwise you´ll get a NullReferenceException.

The second code however compiles to this:

var op = new CreateIndexOperation();
op.Columns = columns.ToList();
op.IsUnique = true;
op.Name = "INDEX_NAME";
op.Table = "TABLE_NAME";


问:
How to consume a simple Restful service with Scala and Akka-Http 10.0.5
I spent a whole day figuring out how to

Consume a remote restful json service

Unmarshall (deserialize) the payload into a case class model

The guys over at the google plus Akka mailing list were very helpful, so I thought it would be nice to have a working example on SO as well, for future reference.

答:
Akka-Http 10.0.5

```<code>package xxx

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.{ActorMaterializer, Materializer}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfter, FlatSpec, MustMatchers}
import org.scalatest.mock.MockitoSugar
import spray.json.DefaultJsonProtocol
import scala.concurrent.{Await, ExecutionContextExecutor, Future}
import akka.http.scaladsl.server.Directives

case class ColorBlob(url: String, averageColor: String, classificationColor: String)
case class ColorBlobsResponse(colorBlobs: Map[String, Option[ColorBlob]])

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
   implicit val format1 = jsonFormat3(ColorBlob)
   implicit val format2 = jsonFormat1(ColorBlobsResponse)
}

class ColorBlobRestTest
   extends FlatSpec
   with MockitoSugar
   with BeforeAndAfter
   with MustMatchers
   with ScalaFutures
   with JsonSupport
   with Directives {

   implicit val system: ActorSystem = ActorSystem()
   implicit val executor: ExecutionContextExecutor = system.dispatcher
   implicit val materializer: Materializer = ActorMaterializer()

   "this" should "work" in {
       val request = HttpRequest(method = HttpMethods.GET, uri = s"https://colorservice/colorblobs/en?productCodes=904655")
       val futureResponse: Future[HttpResponse] = Http().singleRequest(request)

       val futureColorBlobResponse: Future[ColorBlobsResponse] = futureResponse.flatMap { response: HttpResponse =>
           val entity: ResponseEntity = response.entity
           Unmarshal(entity).to[ColorBlobsResponse]
       }

       import scala.concurrent.duration._
       val colorBlobsResponse: ColorBlobsResponse = Await.result(futureColorBlobResponse, 1000.millis)

       assert(1==1)

    }
}
</code>```

Body:
Akka-Http 10.0.5

package xxx

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.{ActorMaterializer, Materializer}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfter, FlatSpec, MustMatchers}
import org.scalatest.mock.MockitoSugar
import spray.json.DefaultJsonProtocol
import scala.concurrent.{Await, ExecutionContextExecutor, Future}
import akka.http.scaladsl.server.Directives

case class ColorBlob(url: String, averageColor: String, classificationColor: String)
case class ColorBlobsResponse(colorBlobs: Map[String, Option[ColorBlob]])

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
   implicit val format1 = jsonFormat3(ColorBlob)
   implicit val format2 = jsonFormat1(ColorBlobsResponse)
}

class ColorBlobRestTest
   extends FlatSpec
   with MockitoSugar
   with BeforeAndAfter
   with MustMatchers
   with ScalaFutures
   with JsonSupport
   with Directives {

   implicit val system: ActorSystem = ActorSystem()
   implicit val executor: ExecutionContextExecutor = system.dispatcher
   implicit val materializer: Materializer = ActorMaterializer()

   "this" should "work" in {
       val request = HttpRequest(method = HttpMethods.GET, uri = s"https://colorservice/colorblobs/en?productCodes=904655")
       val futureResponse: Future[HttpResponse] = Http().singleRequest(request)

       val futureColorBlobResponse: Future[ColorBlobsResponse] = futureResponse.flatMap { response: HttpResponse =>
           val entity: ResponseEntity = response.entity
           Unmarshal(entity).to[ColorBlobsResponse]
       }

       import scala.concurrent.duration._
       val colorBlobsResponse: ColorBlobsResponse = Await.result(futureColorBlobResponse, 1000.millis)

       assert(1==1)

    }
}


问:
Does column store index affect the amount of memory needed for inner join?
I have a table with over 700M rows. I have tried 2 different indexing options: 1) 1 clustered and 1 non clustered index 2) one clustered column store index.

I am using SQL Server 2016.

When using the first option, I was able to join this table with another table in about 30 minutes.

With the second option I received an Out of Memory error after about 35 minutes.

Is it possible that this out of memory error was connected to the use of Column Store index? Or is it more likely that the server was just busy? If it is some feature of the column store index, is there a way to avoid this error?

Additionally, are there some instances (when you have more than 100,000,000 rows) when the usual index is preferred to the column store?

EDIT:

The table looks like this:

```<code>CREATE TABLE tab1 (
    column1 (bigint, not null),
    column2 (int, not null),
    column3 (bigint, not null),
    column4 (int, not null),
    column5 (datetime, not null),
    column6 (date, not null),
    column7 (datetime, not null),
    column8 (tinyint, not null),
    column9 (int, not null),
    column10 (datetime, not null),
    column11 (date, null)
)
</code>```

There are no keys defined.

Indexing option 1:

```<code>create clustered index index1 on table1
    (column8, column1)

CREATE NONCLUSTERED INDEX index2 on table1(column4,column11)
    INCLUDE(
     column2
      ,column6
      ,column7
      )
</code>```

Indexing option 2:

```<code>create clustered columnstore index colindex1 on table1
</code>```

The Join:

```<code>SELECT table1.column1
      ,table1.column2
      ,table1.column3
      ,table1.column4
      ,table1.column5
      ,table1.column6
      ,table1.column7
      ,table1.column8
      ,table1.column10
      ,table1.column11
      ,table2.column4
      ,table2.column5
      ,table2.column6
      ,table2.column7
      ,table2.column8
      ,table2.column9
      INTO newTable
      FROM table1
INNER JOIN table2
    ON (table1.column1 = table2.column1 and
        table1.column11 = table2.column2 and
        table1.column8 = table2.column3);
</code>```

答: First, try and come up with a primary key. If you can define a unique set of columns, there is nothing that beats that indexing. If you cannot do that, create a clustered index on column1, column8 and column11 (all the columns used in the join clause). Then if you have other select statements, see what columns are used in joins and where clauses and you can add additional non-clustered indices for them as well.

Body:
I have a table with over 700M rows. I have tried 2 different indexing options: 1) 1 clustered and 1 non clustered index 2) one clustered column store index.

I am using SQL Server 2016.

When using the first option, I was able to join this table with another table in about 30 minutes.

With the second option I received an Out of Memory error after about 35 minutes.

Is it possible that this out of memory error was connected to the use of Column Store index? Or is it more likely that the server was just busy? If it is some feature of the column store index, is there a way to avoid this error?

Additionally, are there some instances (when you have more than 100,000,000 rows) when the usual index is preferred to the column store?

EDIT:

The table looks like this:

CREATE TABLE tab1 (
    column1 (bigint, not null),
    column2 (int, not null),
    column3 (bigint, not null),
    column4 (int, not null),
    column5 (datetime, not null),
    column6 (date, not null),
    column7 (datetime, not null),
    column8 (tinyint, not null),
    column9 (int, not null),
    column10 (datetime, not null),
    column11 (date, null)
)

There are no keys defined.

Indexing option 1:

create clustered index index1 on table1
    (column8, column1)

CREATE NONCLUSTERED INDEX index2 on table1(column4,column11)
    INCLUDE(
     column2
      ,column6
      ,column7
      )

Indexing option 2:

create clustered columnstore index colindex1 on table1

The Join:

SELECT table1.column1
      ,table1.column2
      ,table1.column3
      ,table1.column4
      ,table1.column5
      ,table1.column6
      ,table1.column7
      ,table1.column8
      ,table1.column10
      ,table1.column11
      ,table2.column4
      ,table2.column5
      ,table2.column6
      ,table2.column7
      ,table2.column8
      ,table2.column9
      INTO newTable
      FROM table1
INNER JOIN table2
    ON (table1.column1 = table2.column1 and
        table1.column11 = table2.column2 and
        table1.column8 = table2.column3);


问:
ProcessBuilder failing when calling a system command where Runtime exec works
I'm having trouble with ProcessBuilder not running a command on the server.

Early in my project I use Runtime.exec() just to retrieve output from a program which works fine:

```<code>private List<SatelliteCode> getSatelliteCodes() {
    List<SatelliteCode> codes = new ArrayList<>();

    Runtime runtime = Runtime.getRuntime();
    String[] commands = { "w_scan", "-s?" };
    Process process;

    try {
        process = runtime.exec(commands);

        BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        String s = error.readLine(); // discard first line

        while ((s = error.readLine()) != null) {
            s = s.trim();
            int i = s.indexOf('\t'); // separated by a tab!?!?
            codes.add(new SatelliteCode(s.substring(0, i), s.substring(i)));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return codes;
}
</code>```

Running this in the terminal works fine and I get all the output I need:

```<code>w_scan -fs -cGB -sS19E2 > channels.conf
</code>```

However, the server needs to grab the ongoing output from the 'process.getErrorStream()' to display in the web interface. What is actually happening is the ProcessBuilder is failing and returning an exit code of 1.

The function that initialises the ProcessBuilder and to start the scan running is [EDIT 1]:

```<code>private static StringBuilder scan_error_output = null;

@Override
public boolean startSatelliteScan(String user, String country_code, String satellite_code) {
    UserAccountPermissions perm = validateUserEdit(user);
    if (perm == null) return false;

    Shared.writeUserLog(user, Shared.getTimeStamp() +
            ": DVB satellite scan started " +
            country_code + " - " + satellite_code +
            System.lineSeparator() + System.lineSeparator());

    scan_error_output = new StringBuilder();
    new ScanThread(country_code, satellite_code).start();

    // write out country code and satellite code to prefs file

    BufferedWriter bw = null;
    try {
        bw = new BufferedWriter(new FileWriter(satellite_last_scan_codes));

        bw.write(country_code); bw.newLine();
        bw.write(satellite_code); bw.newLine();

        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return true;
}
</code>```

That will then run two other threads on the server, one that will run the scan itself and wait for it to finish so that it can get the final scan data. And the other which constantly updates the output from the std error stream which is then polled at intervals from the clients browser. This is much like showing the ongoing output from the terminal.

The scan thread (which fails to start the process) [EDIT 1]:

```<code>private static class ScanThread extends Thread {
    private String cc, sc;

    public ScanThread(String country_code, String satellite_code) {
        cc = country_code;
        sc = satellite_code;
    }

    public void run() {
        ProcessBuilder pb = new ProcessBuilder("/usr/bin/w_scan",
                "-fs", "-c" + cc, "-s" + sc);
        pb.redirectOutput(new File(satellite_scan_file));

        Process process;
        try {
            System.out.println("Scan thread started");

            process = pb.start();

            IOScanErrorOutputHandler error_output_handler = new IOScanErrorOutputHandler(process.getErrorStream());
            error_output_handler.start();

            int result = process.waitFor();
            System.out.println(cc + " - " + sc + " - " +
                    "Process.waitFor() result " + result);

        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        System.out.println("Scan thread finished");
    }
}
</code>```

The error output stream thread which captures the output which obviously doesn't start due to the scan thread failing:

```<code>private static class IOScanErrorOutputHandler extends Thread {
    private InputStream inputStream;

    IOScanErrorOutputHandler(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public void run() {
        Scanner br = null;
        try {
            System.out.println("Scan thread Error IO capture running");
            br = new Scanner(new InputStreamReader(inputStream));
            String line = null;
            while (br.hasNextLine()) {
                line = br.nextLine();
                scan_error_output.append(line + System.getProperty("line.separator"));
            }
        } finally {
            br.close();
        }
        System.out.println("Scan thread Error IO capture finished");

        scan_error_output = null;
    }
}
</code>```

And the server function which returns the std error output progress:

```<code>@Override
public String pollScanResult(String user) {
    if (validateUserEdit(user) == null) return null;
    StringBuilder sb = scan_error_output; // grab instance
    if (sb == null) return null;
    return sb.toString();
}
</code>```

As mentioned above, Runtime.exec() works fine, but the ProcessBuilder is failing.

NB: I'm on Linux Mint 18.1, using Apache Tomcat 8 as the server, linux default JDK 8 and GWT 2.7 [Correction from 2.8] in Eclipse Neon.

Can anyone see what I am doing wrong?

Many thanks in advance...

[EDIT 1]

Whilst developing this on another machine, Linux Mint 17.2, JDK 8 and Apache Tomcat 7, for DVB-T, this method worked fine and polling for the scan output showed up in the client's browser.

The ProcessBuilder.start still returns 1 and an empty file is created for the output scan file.

[EDIT 2]

It appears that the reason the ProcessBuilder is failing is because the user 'tomcat8' doesn't have permissions to run 'w_scan'. 'w_scan' works from the terminal, but not from the tomcat server. Somehow I've got to fix that now.

[SOLUTIONS]

After being put in the right direction by VGR for getting the error stream from the ProcessBuilder, I started digging further and found I was getting:

```<code>main:3909: FATAL: failed to open '/dev/dvb/adapter0/frontend0': 13 Permission denied
</code>```

Apache tomcat 8 didn't have permission to access the DVB-S frontend to run a scan. This was fixed in two ways:

1 - 03catalina.policy I added the extra permissions (whether they made a difference I do not know).

```<code>grant codeBase "file:/dev/dvb/-" {
    permission java.io.FilePermission "file:/dev/dvb/-", "read, write";
    permission java.security.AllPermission;
};
</code>```

2 - The dvb frontends belong to the 'video' group. So I needed to add the user tomcat8 to that group.

```<code>usermod -a -G video tomcat8
</code>```

All works for now...

答:
You are not doing the same thing with ProcessBuilder that you’re doing with Runtime.exec, so I don't know why you think ProcessBuilder is the problem.

You have a few problems with how you’re writing the command’s output to a file.

First, the presence of ">", satellite_scan_temp_file in your ProcessBuilder command is incorrect.  Output redirection is not part of any command;  it is handled by a shell.  But when you run with Runtime.exec or ProcessBuilder, you are not running in a shell, you are executing the process directly.  Neither w_scan nor any other command considers > a special character.

The correct way to redirect to a file is with the redirectOutput method:

```<code>ProcessBuilder pb = new ProcessBuilder(
    "/usr/bin/w_scan", "-fs", "-s" + satellite_code, "-c" + country_code);

pb.redirectOutput(new File(satellite_scan_temp_file));
</code>```

Second, your ScanThread code is ignoring the (currently incorrect) redirect, and is attempting to read the command’s output.  But there is no output, because you are redirecting it all to a file.

Once you are properly redirecting output to a file, you can remove your BufferedReader and BufferedWriter loops completely.

Finally, it is worth noting that the error output you captured probably told you that > is not a valid argument to the w_scan process.

Body:
I'm having trouble with ProcessBuilder not running a command on the server.

Early in my project I use Runtime.exec() just to retrieve output from a program which works fine:

private List<SatelliteCode> getSatelliteCodes() {
    List<SatelliteCode> codes = new ArrayList<>();

    Runtime runtime = Runtime.getRuntime();
    String[] commands = { "w_scan", "-s?" };
    Process process;

    try {
        process = runtime.exec(commands);

        BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        String s = error.readLine(); // discard first line

        while ((s = error.readLine()) != null) {
            s = s.trim();
            int i = s.indexOf('\t'); // separated by a tab!?!?
            codes.add(new SatelliteCode(s.substring(0, i), s.substring(i)));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return codes;
}

Running this in the terminal works fine and I get all the output I need:

w_scan -fs -cGB -sS19E2 > channels.conf

However, the server needs to grab the ongoing output from the 'process.getErrorStream()' to display in the web interface. What is actually happening is the ProcessBuilder is failing and returning an exit code of 1.

The function that initialises the ProcessBuilder and to start the scan running is [EDIT 1]:

private static StringBuilder scan_error_output = null;

@Override
public boolean startSatelliteScan(String user, String country_code, String satellite_code) {
    UserAccountPermissions perm = validateUserEdit(user);
    if (perm == null) return false;

    Shared.writeUserLog(user, Shared.getTimeStamp() +
            ": DVB satellite scan started " +
            country_code + " - " + satellite_code +
            System.lineSeparator() + System.lineSeparator());

    scan_error_output = new StringBuilder();
    new ScanThread(country_code, satellite_code).start();

    // write out country code and satellite code to prefs file

    BufferedWriter bw = null;
    try {
        bw = new BufferedWriter(new FileWriter(satellite_last_scan_codes));

        bw.write(country_code); bw.newLine();
        bw.write(satellite_code); bw.newLine();

        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return true;
}

That will then run two other threads on the server, one that will run the scan itself and wait for it to finish so that it can get the final scan data. And the other which constantly updates the output from the std error stream which is then polled at intervals from the clients browser. This is much like showing the ongoing output from the terminal.

The scan thread (which fails to start the process) [EDIT 1]:

private static class ScanThread extends Thread {
    private String cc, sc;

    public ScanThread(String country_code, String satellite_code) {
        cc = country_code;
        sc = satellite_code;
    }

    public void run() {
        ProcessBuilder pb = new ProcessBuilder("/usr/bin/w_scan",
                "-fs", "-c" + cc, "-s" + sc);
        pb.redirectOutput(new File(satellite_scan_file));

        Process process;
        try {
            System.out.println("Scan thread started");

            process = pb.start();

            IOScanErrorOutputHandler error_output_handler = new IOScanErrorOutputHandler(process.getErrorStream());
            error_output_handler.start();

            int result = process.waitFor();
            System.out.println(cc + " - " + sc + " - " +
                    "Process.waitFor() result " + result);

        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        System.out.println("Scan thread finished");
    }
}

The error output stream thread which captures the output which obviously doesn't start due to the scan thread failing:

private static class IOScanErrorOutputHandler extends Thread {
    private InputStream inputStream;

    IOScanErrorOutputHandler(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public void run() {
        Scanner br = null;
        try {
            System.out.println("Scan thread Error IO capture running");
            br = new Scanner(new InputStreamReader(inputStream));
            String line = null;
            while (br.hasNextLine()) {
                line = br.nextLine();
                scan_error_output.append(line + System.getProperty("line.separator"));
            }
        } finally {
            br.close();
        }
        System.out.println("Scan thread Error IO capture finished");

        scan_error_output = null;
    }
}

And the server function which returns the std error output progress:

@Override
public String pollScanResult(String user) {
    if (validateUserEdit(user) == null) return null;
    StringBuilder sb = scan_error_output; // grab instance
    if (sb == null) return null;
    return sb.toString();
}

As mentioned above, Runtime.exec() works fine, but the ProcessBuilder is failing.

NB: I'm on Linux Mint 18.1, using Apache Tomcat 8 as the server, linux default JDK 8 and GWT 2.7 [Correction from 2.8] in Eclipse Neon.

Can anyone see what I am doing wrong?

Many thanks in advance...

[EDIT 1]

Whilst developing this on another machine, Linux Mint 17.2, JDK 8 and Apache Tomcat 7, for DVB-T, this method worked fine and polling for the scan output showed up in the client's browser.

The ProcessBuilder.start still returns 1 and an empty file is created for the output scan file.

[EDIT 2]

It appears that the reason the ProcessBuilder is failing is because the user 'tomcat8' doesn't have permissions to run 'w_scan'. 'w_scan' works from the terminal, but not from the tomcat server. Somehow I've got to fix that now.

[SOLUTIONS]

After being put in the right direction by VGR for getting the error stream from the ProcessBuilder, I started digging further and found I was getting:

main:3909: FATAL: failed to open '/dev/dvb/adapter0/frontend0': 13 Permission denied

Apache tomcat 8 didn't have permission to access the DVB-S frontend to run a scan. This was fixed in two ways:

1 - 03catalina.policy I added the extra permissions (whether they made a difference I do not know).

grant codeBase "file:/dev/dvb/-" {
    permission java.io.FilePermission "file:/dev/dvb/-", "read, write";
    permission java.security.AllPermission;
};

2 - The dvb frontends belong to the 'video' group. So I needed to add the user tomcat8 to that group.

usermod -a -G video tomcat8

All works for now...

Body:
You are not doing the same thing with ProcessBuilder that you’re doing with Runtime.exec, so I don't know why you think ProcessBuilder is the problem.

You have a few problems with how you’re writing the command’s output to a file.

First, the presence of ">", satellite_scan_temp_file in your ProcessBuilder command is incorrect.  Output redirection is not part of any command;  it is handled by a shell.  But when you run with Runtime.exec or ProcessBuilder, you are not running in a shell, you are executing the process directly.  Neither w_scan nor any other command considers > a special character.

The correct way to redirect to a file is with the redirectOutput method:

ProcessBuilder pb = new ProcessBuilder(
    "/usr/bin/w_scan", "-fs", "-s" + satellite_code, "-c" + country_code);

pb.redirectOutput(new File(satellite_scan_temp_file));

Second, your ScanThread code is ignoring the (currently incorrect) redirect, and is attempting to read the command’s output.  But there is no output, because you are redirecting it all to a file.

Once you are properly redirecting output to a file, you can remove your BufferedReader and BufferedWriter loops completely.

Finally, it is worth noting that the error output you captured probably told you that > is not a valid argument to the w_scan process.


问:
Jquery each and visible - Unknown Pseudoclass or Pseudoelement 'visible'

i have a problem with jquery/visible. Hope somebody can help me.

This code works, but i get an error in firebug

```<code>$('.fse:visible').each(function (i)
</code>```

-> Unknown Pseudoclass or Pseudoelement 'visible'.

second try

```<code>$('.fse').is(':visible').each(function (i)
</code>```

->  $(".fse").is(":visible").each is not a function

Whats wrong?

Thanks in advance!

Peter

答:
Since class can commonly defined u cant use as $(".classname : visible").each(function(i))

try this:

if($('.fse').is(':visible'))
{
//Do something here

$(this).css({'color':'red'});
}

Body:
i have a problem with jquery/visible. Hope somebody can help me.

This code works, but i get an error in firebug

$('.fse:visible').each(function (i)

-> Unknown Pseudoclass or Pseudoelement 'visible'.

second try

$('.fse').is(':visible').each(function (i)

->  $(".fse").is(":visible").each is not a function

Whats wrong?

Thanks in advance!

Peter


问:
How to prevent file from finishing in Node.js to run tests sequentially?
I've got tape.js tests in different files that alter my database.

They work fine when run individually, but when running all the files like this tape tests/**/*.js the tests fail - because tests in the second file start running before the first file has finished and the database state is incorrect.

How do I prevent Node from exiting a file while waiting for an async call to finish?

Neither of these ideas I had will work:

```<code>function wait()  //blocks forever so the test can never finish
{
   while (!testsFinished) {;}
}

function wait()  //returns immediately because it uses a timeout
{
   if (!testsFinished)
      setTimeout(wait, 1000);
}
</code>```

The only other option I can think of is to write my own test file manager that uses async.series([....]) to call each file individually. But that would be reinventing the wheel - writing my own test runner framework.

答:
This is probably not advised, but theoretically you could add properties onto nodes global object.

test1.js

```<code>var test = require( 'tape' ) ;
var util = require('util');

test( 'My first test file', function( assert ) {
  assert.equal( 1, 1, 'Numbers 1 and 1 are the same' ) ;
  assert.equal( 2, 2, 'Numbers 2 and 2 are the same' ) ;
  assert.equal( 3, 3, 'Numbers 3 and 3 are the same' ) ;

  myglobalvariableWithoutVarKeyword = 'shared var';
  console.log('test1 shared var= ' + util.inspect(myglobalvariableWithoutVarKeyword));

  assert.end() ;
} ) ;
</code>```

test2.js

```<code>var test = require( 'tape' ) ;
var util = require('util');

test( 'My second test file', function( assert ) {
  assert.equal( 4, 4, 'Numbers 4 and 4 are the same' ) ;
  assert.equal( 5, 5, 'Numbers 5 and 5 are the same' ) ;
  assert.equal( 6, 6, 'Numbers 6 and 6 are the same' ) ;

  console.log('test2 shared var= ' + util.inspect(myglobalvariableWithoutVarKeyword));
  assert.end() ;
} ) ;
</code>```

Outputs:

```<code> My first test file

    √ Numbers 1 and 1 are the same
    √ Numbers 2 and 2 are the same
    √ Numbers 3 and 3 are the same
    test1 shared var = 'shared var';

  My second test file

    √ Numbers 1 and 1 are the same
    √ Numbers 2 and 2 are the same
    √ Numbers 3 and 3 are the same
    test2 shared var = 'shared var';
</code>```

With this approach you could test if the shared variable has loaded all the tests, and then run assert.end() using promises.

Body:
I've got tape.js tests in different files that alter my database.

They work fine when run individually, but when running all the files like this tape tests/**/*.js the tests fail - because tests in the second file start running before the first file has finished and the database state is incorrect.

How do I prevent Node from exiting a file while waiting for an async call to finish?

Neither of these ideas I had will work:

function wait()  //blocks forever so the test can never finish
{
   while (!testsFinished) {;}
}

function wait()  //returns immediately because it uses a timeout
{
   if (!testsFinished)
      setTimeout(wait, 1000);
}

The only other option I can think of is to write my own test file manager that uses async.series([....]) to call each file individually. But that would be reinventing the wheel - writing my own test runner framework.

Body:
This is probably not advised, but theoretically you could add properties onto nodes global object.

test1.js

var test = require( 'tape' ) ;
var util = require('util');

test( 'My first test file', function( assert ) {
  assert.equal( 1, 1, 'Numbers 1 and 1 are the same' ) ;
  assert.equal( 2, 2, 'Numbers 2 and 2 are the same' ) ;
  assert.equal( 3, 3, 'Numbers 3 and 3 are the same' ) ;

  myglobalvariableWithoutVarKeyword = 'shared var';
  console.log('test1 shared var= ' + util.inspect(myglobalvariableWithoutVarKeyword));

  assert.end() ;
} ) ;

test2.js

var test = require( 'tape' ) ;
var util = require('util');

test( 'My second test file', function( assert ) {
  assert.equal( 4, 4, 'Numbers 4 and 4 are the same' ) ;
  assert.equal( 5, 5, 'Numbers 5 and 5 are the same' ) ;
  assert.equal( 6, 6, 'Numbers 6 and 6 are the same' ) ;

  console.log('test2 shared var= ' + util.inspect(myglobalvariableWithoutVarKeyword));
  assert.end() ;
} ) ;

Outputs:

 My first test file

    √ Numbers 1 and 1 are the same
    √ Numbers 2 and 2 are the same
    √ Numbers 3 and 3 are the same
    test1 shared var = 'shared var';

  My second test file

    √ Numbers 1 and 1 are the same
    √ Numbers 2 and 2 are the same
    √ Numbers 3 and 3 are the same
    test2 shared var = 'shared var';

With this approach you could test if the shared variable has loaded all the tests, and then run assert.end() using promises.


问:
Efficiently count the number of bits in an integer in JavaScript
Let's say I have an integer I and want to get the count of 1s in its binary form.

I am currently using the following code.

```<code>Number(i.toString(2).split("").sort().join("")).toString().length;
</code>```

Is there a faster way to do this? I am thinking about using bitwise operators.  Any thoughts?

NOTE: i is within the 32-bit limitation.

答:
You can use a strategy from this collection of Bit Twiddling Hacks:

function bitCount (n) {
  n = n - ((n >> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
  return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
}

console.log(bitCount(0xFF)) //=> 8```
</div>
</div>
</p>

<p>Note that the above strategy only works for 32-bit integers (a limitation of bitwise operators in JavaScript).</p>

<p>A more general approach for larger integers would involve counting 32-bit chunks individually (thanks to harold for the inspiration):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function bitCount (n) {
  var bits = 0
  while (n !== 0) {
    bits += bitCount32(n | 0)
    n /= 0x100000000
  }
  return bits
}

function bitCount32 (n) {
  n = n - ((n >> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
  return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
}

console.log(bitCount(Math.pow(2, 53) - 1)) //=> 53</code>```

You could also use a regular expression:

function bitCount (n) {
  return n.toString(2).match(/1/g).length
}

console.log(bitCount(0xFF)) //=> 8```

Body:
Let's say I have an integer I and want to get the count of 1s in its binary form.

I am currently using the following code.

Number(i.toString(2).split("").sort().join("")).toString().length;

Is there a faster way to do this? I am thinking about using bitwise operators.  Any thoughts?

NOTE: i is within the 32-bit limitation.

Body:
You can use a strategy from this collection of Bit Twiddling Hacks:

function bitCount (n) {
  n = n - ((n >> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
  return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
}

console.log(bitCount(0xFF)) //=> 8

Note that the above strategy only works for 32-bit integers (a limitation of bitwise operators in JavaScript).

A more general approach for larger integers would involve counting 32-bit chunks individually (thanks to harold for the inspiration):

function bitCount (n) {
  var bits = 0
  while (n !== 0) {
    bits += bitCount32(n | 0)
    n /= 0x100000000
  }
  return bits
}

function bitCount32 (n) {
  n = n - ((n >> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
  return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
}

console.log(bitCount(Math.pow(2, 53) - 1)) //=> 53

You could also use a regular expression:

function bitCount (n) {
  return n.toString(2).match(/1/g).length
}

console.log(bitCount(0xFF)) //=> 8


问:
TXSDateTime error "local time situated within the missing period prior to DST'
We convert our local dates (no time parts) to a external system expecting UTC datetime strings, by adding TTimeZone.Local.UTCOffset (now 2 hours) to a TDateTime.

This fails for the night we switch to DST (at 02:00).

Error from System.RTLConst:

```<code>SLocalTimeInvalid = 'The given "%s" local time is invalid (situated within the missing period prior to DST).';
</code>```

occurring in System.DateUtils:

```<code>function TTimeZone.GetUtcOffsetInSeconds(const ADateTime: TDateTime; const ForceDaylight: Boolean): Int64;
var
  LOffset, LDSTSave: Int64;
  LType: TLocalTimeType;
begin
  { Obtain the information we require }
  DoGetOffsetsAndType(ADateTime, LOffset, LDSTSave, LType);

  { Select the proper offset }
  if (LType = lttInvalid) then
    raise ELocalTimeInvalid.CreateResFmt(@SLocalTimeInvalid, [DateTimeToStr(ADateTime)])
  else if (LType = lttDaylight) or ((LType = lttAmbiguous) and ForceDaylight) then
    Result := LOffset + LDSTSave
  else
    Result := LOffset;
end;
</code>```

Code to reproduce:

```<code>function DateTime2UTCString(ADateTime: TDateTime): String;
var XSD: TXSDateTime;
begin
  XSD := TXSDateTime.Create;
  try
    try
      XSD.AsDateTime := ADateTime;
      Result := XSD.NativeToXS;
    except
      on E:Exception do
        Result := E.Message;
    end;
  finally
     XSD.Free;
  end;
end;

function Date2UTCString(ADateTime: TDateTime): String;
// Input is guaranteed to have no time fraction
begin
  ADateTime := ADateTime + TTimeZone.Local.UTCOffset;
  Result := DateTime2UTCString(ADateTime);
end;

procedure TFrmUTCandDST.Button1Click(Sender: TObject);
var
  lDT: TDateTime;
  l  : integer;
begin
  lDT := EncodeDate(2016,3,25);
  for l := 0 to 2 do
  begin
    lDT := lDT +1;
    Memo1.Lines.Add(DateToStr(lDT) + ' -> ' + Date2UTCString(lDT));
  end;
end;
</code>```

(Don't forget to use SOAP.XSBuiltIns, System.DateUtils, System.TimeSpan).

Output:

```<code>26-3-2016 -> 2016-03-26T02:00:00.000+01:00
27-3-2016 -> The given "27-3-2016 2:00:00" local time is invalid (situated within the missing period prior to DST).
28-3-2016 -> 2016-03-28T02:00:00.000+02:00
</code>```

How can I graciously circumvent this? I can use TTimeZone.Local.IsInvalidTime(ADateTime) to detect invalid dates, but
26-3-2016 2:00:00 would be wrong (that's exactly the time we moved to DST), not 27-3-2016 2:00:00 - so I don't know how to adjust in case of the 'invalid' date.

答:
There is bug in unit System.DateUtils.pas (afaik still present in 10.1).

Function AdjustDateTime first takes date and time handling it as local time, and THEN tries to put offset into it. Since during daylight saving time there is a "missing hour" (in case of central Europe it was 26.03.2017), therefore after 1:59:59 A.M you've got 3:00:00 A.M.

If you accidentally use this period (like 2:17:35), you'll get an exception.

This is also present in other functions.

Simple code to reproduce the exception (C++):

```<code>ShowMessage(ISO8601ToDate("2017-03-26T02:22:50.000Z",false));
</code>```

but this one runs ok:

```<code>ShowMessage(ISO8601ToDate("2017-03-26T02:22:50.000Z",true));`
</code>```

For now to avoid the exception use XSD.AsUTCDateTime, then apply the local offset.
Example in c++ :

```<code> TTimeZone * localTz = TTimeZone::Local;
 TDateTime TimeSomething = localTz->ToLocalTime(XSD->AsUTCDateTime);
</code>```

In your case either local time is indeed invalid (there was no "2:00"),
or somewhere you're trying to treat UTC Time as local time, which of course is invalid. Solve this and you will solve your problem.

How can I graciously circumvent this? I can use TTimeZone.Local.IsInvalidTime(ADateTime) to detect invalid dates, but 26-3-2016 2:00:00 would be wrong (that's exactly the time we moved to DST), not 27-3-2016 2:00:00 - so I don't know how to adjust in case of the 'invalid' date.

Additionally i think you missing that in year 2016 we moved to DST at 27.03 at 2:00 but THIS year at 26-03, so 27-3-2016 2:00:00 is perfectly invalid date :)

Body:
We convert our local dates (no time parts) to a external system expecting UTC datetime strings, by adding TTimeZone.Local.UTCOffset (now 2 hours) to a TDateTime.

This fails for the night we switch to DST (at 02:00).

Error from System.RTLConst:

SLocalTimeInvalid = 'The given "%s" local time is invalid (situated within the missing period prior to DST).';

occurring in System.DateUtils:

function TTimeZone.GetUtcOffsetInSeconds(const ADateTime: TDateTime; const ForceDaylight: Boolean): Int64;
var
  LOffset, LDSTSave: Int64;
  LType: TLocalTimeType;
begin
  { Obtain the information we require }
  DoGetOffsetsAndType(ADateTime, LOffset, LDSTSave, LType);

  { Select the proper offset }
  if (LType = lttInvalid) then
    raise ELocalTimeInvalid.CreateResFmt(@SLocalTimeInvalid, [DateTimeToStr(ADateTime)])
  else if (LType = lttDaylight) or ((LType = lttAmbiguous) and ForceDaylight) then
    Result := LOffset + LDSTSave
  else
    Result := LOffset;
end;

Code to reproduce:

function DateTime2UTCString(ADateTime: TDateTime): String;
var XSD: TXSDateTime;
begin
  XSD := TXSDateTime.Create;
  try
    try
      XSD.AsDateTime := ADateTime;
      Result := XSD.NativeToXS;
    except
      on E:Exception do
        Result := E.Message;
    end;
  finally
     XSD.Free;
  end;
end;

function Date2UTCString(ADateTime: TDateTime): String;
// Input is guaranteed to have no time fraction
begin
  ADateTime := ADateTime + TTimeZone.Local.UTCOffset;
  Result := DateTime2UTCString(ADateTime);
end;

procedure TFrmUTCandDST.Button1Click(Sender: TObject);
var
  lDT: TDateTime;
  l  : integer;
begin
  lDT := EncodeDate(2016,3,25);
  for l := 0 to 2 do
  begin
    lDT := lDT +1;
    Memo1.Lines.Add(DateToStr(lDT) + ' -> ' + Date2UTCString(lDT));
  end;
end;

(Don't forget to use SOAP.XSBuiltIns, System.DateUtils, System.TimeSpan).

Output:

26-3-2016 -> 2016-03-26T02:00:00.000+01:00
27-3-2016 -> The given "27-3-2016 2:00:00" local time is invalid (situated within the missing period prior to DST).
28-3-2016 -> 2016-03-28T02:00:00.000+02:00

How can I graciously circumvent this? I can use TTimeZone.Local.IsInvalidTime(ADateTime) to detect invalid dates, but
26-3-2016 2:00:00 would be wrong (that's exactly the time we moved to DST), not 27-3-2016 2:00:00 - so I don't know how to adjust in case of the 'invalid' date.

Body:
There is bug in unit System.DateUtils.pas (afaik still present in 10.1).

Function AdjustDateTime first takes date and time handling it as local time, and THEN tries to put offset into it. Since during daylight saving time there is a "missing hour" (in case of central Europe it was 26.03.2017), therefore after 1:59:59 A.M you've got 3:00:00 A.M.

If you accidentally use this period (like 2:17:35), you'll get an exception.

This is also present in other functions.

Simple code to reproduce the exception (C++):

ShowMessage(ISO8601ToDate("2017-03-26T02:22:50.000Z",false));

but this one runs ok:

ShowMessage(ISO8601ToDate("2017-03-26T02:22:50.000Z",true));`

For now to avoid the exception use XSD.AsUTCDateTime, then apply the local offset.
Example in c++ :

 TTimeZone * localTz = TTimeZone::Local;
 TDateTime TimeSomething = localTz->ToLocalTime(XSD->AsUTCDateTime);

In your case either local time is indeed invalid (there was no "2:00"),
or somewhere you're trying to treat UTC Time as local time, which of course is invalid. Solve this and you will solve your problem.

How can I graciously circumvent this? I can use TTimeZone.Local.IsInvalidTime(ADateTime) to detect invalid dates, but 26-3-2016 2:00:00 would be wrong (that's exactly the time we moved to DST), not 27-3-2016 2:00:00 - so I don't know how to adjust in case of the 'invalid' date.

Additionally i think you missing that in year 2016 we moved to DST at 27.03 at 2:00 but THIS year at 26-03, so 27-3-2016 2:00:00 is perfectly invalid date :)


问:
Capture SMS events in nativescript
I am working on an application which need to get updated when an SMS received (with the content from SMS) and also do the cleanup when SMS is deleted from the mobile.

How to listen for these SMS events with nativescript ?

答:
You want to look into https://www.npmjs.com/package/nativescript-sms-inbox.  Seems to provide all features you require.

About the application updating itself - do not think this is possible with the above plugin, as it would constantly need to run in background, listening for SMS events.

How about at the same time the SMS is sent, a push notification is sent to the app?

Title: Capture SMS events in nativescript


问:
Unnecessary else statements: Is there any disadvantage to using ELSE IF when just IF can be used?
Consider the speed of the following examples (please ignore that this example is completely ridiculous):

```<code>int multiply(int a, int b) {
  if (a == 0 || b == 0) {
    return 0;
  }
  if (a == b) {
    return pow(a, 2);
  }
  return a*b;
}
</code>```

versus

```<code>int multiply(int a, int b) {
  if (a == 0 || b == 0) {
    return 0;
  } else if (a == b) {
    return pow(a, 2);
  } else {
    return a*b;
  }
}
</code>```

Obviously, it's not really necessary here, but when I'm working with complex operations, I find it a lot easier to read when formatted as the latter.  Does it take any longer to run in the second configuration?  Will I be sacrificing anything?

答:
EDIT: Answering's OP question first, then talking about the general case.

Sepcific-to-your-problem Answer: In your case, since you have the return, under each condition, it will break out of the flow-control. In a general case, chaining them, when necessary, is better.

General Answer: Yes, essentially when you're only using if, your program is checking all the conditions, even if one of them was met.

When doing a chain of if,else-if,else, once one of the conditions is met, all the others, in that chain, will be ignored.

Body:
Consider the speed of the following examples (please ignore that this example is completely ridiculous):

int multiply(int a, int b) {
  if (a == 0 || b == 0) {
    return 0;
  }
  if (a == b) {
    return pow(a, 2);
  }
  return a*b;
}

versus

int multiply(int a, int b) {
  if (a == 0 || b == 0) {
    return 0;
  } else if (a == b) {
    return pow(a, 2);
  } else {
    return a*b;
  }
}

Obviously, it's not really necessary here, but when I'm working with complex operations, I find it a lot easier to read when formatted as the latter.  Does it take any longer to run in the second configuration?  Will I be sacrificing anything?


问:
BxAndroidBle cannot read device, status=22
I am having troubles with reading a Ble device and using the RxAndroidBle library.

I keep getting this error:

```<code>BleGattException{status=22, bleGattOperation=BleGattOperation{description='CONNECTION_STATE'}}
</code>```

Can anyone look at my code and see what I might be doing wrong:

```<code>subscription = rxBleDevice.establishConnection(context, true)
            .subscribe(rxBleConnection -> {
                rxBleConnection.readCharacteristic(UUID.fromString(UUID_LOG_COUNT)).doOnNext(Action1 -> Logger.d(Helper_Utils.reverseHex(HexString.bytesToHex(Action1))));
            }, throwable -> {
                Logger.d("Error", throwable.getMessage());
            });
</code>```

If you need more info, I will try to provide it.

EDIT

I have used 2 different phones:
OnePlus Two Android 6.0.1
Moto G Play Android 6.0.1

I have tried multiple times switching wifi and bluetooth on and off.
I have never been able to get a reading with this example.

答:
Thank you s_noopy for finding my problem.

This was the solution for my problem:

```<code>subscription = rxBleDevice.establishConnection(context, true)
        .subscribe(rxBleConnection -> {
           rxBleConnection.readCharacteristic(UUID.fromString(UUID_LOG_COUNT))
.subscribe(characteristicValue -> {
                            Logger.d(Helper_Utils.reverseHex(HexString.bytesToHex(characteristicValue)));
                        });
        }, throwable -> {
            Logger.d("Error", throwable.getMessage());
        });
</code>```

I changed the .doOnNext with .subscribe

Body:
I am having troubles with reading a Ble device and using the RxAndroidBle library.

I keep getting this error:

BleGattException{status=22, bleGattOperation=BleGattOperation{description='CONNECTION_STATE'}}

Can anyone look at my code and see what I might be doing wrong:

subscription = rxBleDevice.establishConnection(context, true)
            .subscribe(rxBleConnection -> {
                rxBleConnection.readCharacteristic(UUID.fromString(UUID_LOG_COUNT)).doOnNext(Action1 -> Logger.d(Helper_Utils.reverseHex(HexString.bytesToHex(Action1))));
            }, throwable -> {
                Logger.d("Error", throwable.getMessage());
            });

If you need more info, I will try to provide it.

EDIT

I have used 2 different phones:
OnePlus Two Android 6.0.1
Moto G Play Android 6.0.1

I have tried multiple times switching wifi and bluetooth on and off.
I have never been able to get a reading with this example.

Body:
Thank you s_noopy for finding my problem.

This was the solution for my problem:

subscription = rxBleDevice.establishConnection(context, true)
        .subscribe(rxBleConnection -> {
           rxBleConnection.readCharacteristic(UUID.fromString(UUID_LOG_COUNT))
.subscribe(characteristicValue -> {
                            Logger.d(Helper_Utils.reverseHex(HexString.bytesToHex(characteristicValue)));
                        });
        }, throwable -> {
            Logger.d("Error", throwable.getMessage());
        });

I changed the .doOnNext with .subscribe


问:
Why to use JPA with Hibernate?
I work to a project that it has installed Spring, Hibernate and JPA.

I have read tutorials about Hibernate and JPA and the big picture is that JPA is an interface, and Hibernate is the implementation of JPA.

But why to use JPA, with what it helps me? What are the differences between JPA and Hibernate. First, i thought that annotations in POJO classes are from JPA, but no, they are from Hibernate Annotations.

So, the big question is, for what is good JPA?
Thanks!

答:
The root reason for JPA to exist lies within the larger Java Enterprise specification. There was a growing need for a standardised ORM API to be part of the JavaEE 5 specification for standardisation across Java enterprise containers. That's it - that is why JPA exists and why existing ORM packages such as Hibernate do their best to implement it to the letter.

The net gain is quite simple; any Java Enterprise container (JBoss Wildfly, Weblogic, etc.) will support the JPA specification and will have an implementation for it built-in. Thus if you build an application or library and use only the JPA API in your code, you don't even have to package Hibernate or any other ORM with your application - it will during runtime just use whatever ORM the container provides.

Historically this wasn't usually possible because you'd still end up needing to add ORM specific configuration properties, so you at least needed to be aware of what ORM would be available on deployment to cater towards it. But since JPA 2.0 and 2.1 most of the common and uncommon configuration options have been standardised.

Long story short: if you're deploying to a JavaEE (or Spring Boot) container then using JPA is simply a good idea because it is readily available and is the standard (for object relational mapping).

If you're not going to be deploying to a JavaEE container and are going to be packaging an ORM with your application - well then you're even more free to do what you want. Just be aware that you wouldn't be the first to kick themselves when they're at a later point in time porting over code or maintaining a code base with mixed API usage.

Title: Why to use JPA with Hibernate?


问:
UIScrollView inside another view not scrolling
So I've seen other SO questions but I can't really figure out mine

I know my UIScrollView code works because I tested it in a regular UIViewController so I don't think contentSize is the problem, but when I place the same code inside a UICollectionReusableView it doesn't scroll anymore

```<code>-Working in UIViewController
    override func viewDidLoad() {
      super.viewDidLoad()
      let scrollingView = colorButtonsView(buttonSize: CGSize(width:100.0,height:50.0), buttonCount: 10)

      let scrollView = UIScrollView(frame: UIScreen.main.bounds)
      scrollView.backgroundColor = UIColor.black
      scrollView.contentSize = scrollingView.frame.size
      scrollView.showsHorizontalScrollIndicator = true

      self.view.addSubview(scrollView)
      scrollView.addSubview(scrollingView)

   }

-Not working in UICollectionReusableView

 override init(frame: CGRect) {
    super.init(frame: frame)

    //Add category scroll view
    let scrollingView = colorButtonsView(buttonSize: CGSize(width:100.0,height:50.0), buttonCount: 10)

    let scrollView = UIScrollView(frame: UIScreen.main.bounds)
    scrollView.backgroundColor = UIColor.black
    scrollView.contentSize = scrollingView.frame.size

    scrollView.showsHorizontalScrollIndicator = true

    self.addSubview(scrollView) //Only changes self.view to self
    scrollView.addSubview(scrollingView)

 }
</code>```

答:
Better late than never...I had the same problem, so maybe this is why;

I wanted to put a UIScrollView inside a UICollectionReusableView but by accident I had created my custom class as;

```<code>class CustomCellHeader: UICollectionViewCell {

}
</code>```

instead of;

```<code>class CustomCellHeader: UICollectionReusableView {

}
</code>```

Once I changed that, the UIScrollView within my header cell came to life!

Body:
So I've seen other SO questions but I can't really figure out mine

I know my UIScrollView code works because I tested it in a regular UIViewController so I don't think contentSize is the problem, but when I place the same code inside a UICollectionReusableView it doesn't scroll anymore

-Working in UIViewController
    override func viewDidLoad() {
      super.viewDidLoad()
      let scrollingView = colorButtonsView(buttonSize: CGSize(width:100.0,height:50.0), buttonCount: 10)

      let scrollView = UIScrollView(frame: UIScreen.main.bounds)
      scrollView.backgroundColor = UIColor.black
      scrollView.contentSize = scrollingView.frame.size
      scrollView.showsHorizontalScrollIndicator = true

      self.view.addSubview(scrollView)
      scrollView.addSubview(scrollingView)

   }

-Not working in UICollectionReusableView

 override init(frame: CGRect) {
    super.init(frame: frame)

    //Add category scroll view
    let scrollingView = colorButtonsView(buttonSize: CGSize(width:100.0,height:50.0), buttonCount: 10)

    let scrollView = UIScrollView(frame: UIScreen.main.bounds)
    scrollView.backgroundColor = UIColor.black
    scrollView.contentSize = scrollingView.frame.size

    scrollView.showsHorizontalScrollIndicator = true

    self.addSubview(scrollView) //Only changes self.view to self
    scrollView.addSubview(scrollingView)

 }

Body:
Better late than never...I had the same problem, so maybe this is why;

I wanted to put a UIScrollView inside a UICollectionReusableView but by accident I had created my custom class as;

class CustomCellHeader: UICollectionViewCell {

}

instead of;

class CustomCellHeader: UICollectionReusableView {

}

Once I changed that, the UIScrollView within my header cell came to life!


问:
Eager loading relationship returns empty using SELECT in WITH clause
Using Laravel 5.4, I have a query that correctly returns a relationship. Using the "with" clause in the query, I am attempting to return only selected columns from the relationship in my controller.

When I add the select to the with clause, relationship returns an empty array. Oddly enough, if I add a different parameter, such as a groupBy or join the query DOES return results. So something about my setup dislikes the select on the query.

Thus far I have tried:

using selectRaw

using select(DB::raw)

tried defining this as a separate relationship on my model.

Nothing has worked this far. Sql log looks good when I dump it.

Here is my model:

```<code>// MODEL
namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class ClassBlocks extends Model
{
    public $timestamps = false;

    public function schedule(){
        return $this->hasMany('App\ClassSchedules', 'class_block_id', 'id');
    }
}
</code>```

And here is my controller:

```<code>//CONTROLLER
use App;
use DateTime;
use Illuminate\Http\Request;

class ProgramsController extends Controller
{
    public function filterClass(Request $request, App\ClassBlocks $block)
    {

        $block = $block->newQuery();

        // Attempt to eager load relationship
        // Returns results when "select" disabled
        $block->with([
            'schedule' => function($query){
                $query->select('time_start');
                $query->groupBy('day');
            },
        ]);

        return $block->get();

    }
}
</code>```

Here is a sample result with select enabled (schedule returns empty):

```<code>[
  {
    "id": 13,
    "program_id": "1",
    "class_group_id": "1",
    "schedule": [

    ]
  }
]
</code>```

And here is a result with select disabled (returns relationship when select disabled):

```<code>[
  {
    "id": 13,
    "program_id": "1",
    "class_group_id": "1",
    "schedule": [
      {
        "id": 338,
        "class_group_id": "1",
        "program_id": "1",
        "class_block_id": "13",
        "date": "06/13/2017",
        "day": "Tuesday",
        "instructor_id": "1",
        "time_start": "6:30am",
        "time_end": "6:30am"
      },
      {
        "id": 339,
        "class_group_id": "1",
        "program_id": "1",
        "class_block_id": "13",
        "date": "06/14/2017",
        "day": "Wednesday",
        "instructor_id": "2",
        "time_start": "6:30am",
        "time_end": "6:30am"
      }
    ]
  },
]
</code>```

Any insight would be greatly appreciated.

答:
The problem here is:

```<code>$query->select('time_start');
</code>```

Laravel need to have column that is connection between 2 records. In this case you should probably use:

```<code>$query->select('time_start', 'class_block_id');
</code>```

to make it work.

Obviously you will have class_block_id in response this way. If you really don't want it, probably you should create some transformer that will return exactly you want in response.

Body:
Using Laravel 5.4, I have a query that correctly returns a relationship. Using the "with" clause in the query, I am attempting to return only selected columns from the relationship in my controller.

When I add the select to the with clause, relationship returns an empty array. Oddly enough, if I add a different parameter, such as a groupBy or join the query DOES return results. So something about my setup dislikes the select on the query.

Thus far I have tried:

using selectRaw

using select(DB::raw)

tried defining this as a separate relationship on my model.

Nothing has worked this far. Sql log looks good when I dump it.

Here is my model:

// MODEL
namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class ClassBlocks extends Model
{
    public $timestamps = false;

    public function schedule(){
        return $this->hasMany('App\ClassSchedules', 'class_block_id', 'id');
    }
}

And here is my controller:

//CONTROLLER
use App;
use DateTime;
use Illuminate\Http\Request;

class ProgramsController extends Controller
{
    public function filterClass(Request $request, App\ClassBlocks $block)
    {

        $block = $block->newQuery();

        // Attempt to eager load relationship
        // Returns results when "select" disabled
        $block->with([
            'schedule' => function($query){
                $query->select('time_start');
                $query->groupBy('day');
            },
        ]);

        return $block->get();

    }
}

Here is a sample result with select enabled (schedule returns empty):

[
  {
    "id": 13,
    "program_id": "1",
    "class_group_id": "1",
    "schedule": [

    ]
  }
]

And here is a result with select disabled (returns relationship when select disabled):

[
  {
    "id": 13,
    "program_id": "1",
    "class_group_id": "1",
    "schedule": [
      {
        "id": 338,
        "class_group_id": "1",
        "program_id": "1",
        "class_block_id": "13",
        "date": "06/13/2017",
        "day": "Tuesday",
        "instructor_id": "1",
        "time_start": "6:30am",
        "time_end": "6:30am"
      },
      {
        "id": 339,
        "class_group_id": "1",
        "program_id": "1",
        "class_block_id": "13",
        "date": "06/14/2017",
        "day": "Wednesday",
        "instructor_id": "2",
        "time_start": "6:30am",
        "time_end": "6:30am"
      }
    ]
  },
]

Any insight would be greatly appreciated.

Body:
The problem here is:

$query->select('time_start');

Laravel need to have column that is connection between 2 records. In this case you should probably use:

$query->select('time_start', 'class_block_id');

to make it work.

Obviously you will have class_block_id in response this way. If you really don't want it, probably you should create some transformer that will return exactly you want in response.


问:
Python unescape URL
I have got a url in this form - http:\\/\\/en.wikipedia.org\\/wiki\\/The_Truman_Show. How can I make it normal url. I have tried using urllib.unquote without much success.

I can always use regular expressions or some simple string replace stuff. But I believe that there is a better way to handle this...

答:
urllib.unquote is for replacing %xx escape codes in URLs with the characters they represent. It won't be useful for this.

Your "simple string replace stuff" is probably the best solution.

Title: Python unescape URL