问:
Broad crawling - different xpaths - Scrapy
I'm new in Scrapy. I have thousands of url,xpath tuples and values in a database.
These urls are from different domains (not allways, there can be 100 urls from the same domain).

```<code>x.com/a //h1
y.com/a //div[@class='1']
z.com/a //div[@href='...']
x.com/b //h1
x.com/c //h1
...
</code>```

Now I want to get these values every 2 hours as fast as possible but to be sure that I don't overload any of these.

Can't figure out how to do that.

My thoughts:

I could create one Spider for every different domain, set it's parsing rules and run them at once.

Is it a good practice?

EDIT:
I'm not sure how it would work with outputting data into database according to concurrency.

EDIT2:

I can do something like this - for every domain there is a new spider. But this is impossible to do having thousands of different urls and it's xpaths.

```<code>class WikiScraper(scrapy.Spider):
    name = "wiki_headers"

    def start_requests(self):
        urls = [
            'https://en.wikipedia.org/wiki/Spider',
            'https://en.wikipedia.org/wiki/Data_scraping',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//h1/text()').extract()
        print header
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)

class CraigslistScraper(scrapy.Spider):
    name = "craigslist_headers"

    def start_requests(self):
        urls = [
            'https://columbusga.craigslist.org/act/6062657418.html',
            'https://columbusga.craigslist.org/acc/6060297390.html',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//span[@id="titletextonly"]/text()').extract()
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)
</code>```

答:
If I understand correctly you have map of domain to xpath values and you want to pull xpath depending on what domain you crawl?

Try something like:

```<code>DOMAIN_DATA = [('domain.com', '//div')]
def get_domain(url):
    for domain, xpath in DOMAIN_DATA:
        if domain in url:
            return xp

def parse(self, response):
    xpath = get_domain(response.url)
    if not xpath:
        logging.error('no xpath for url: {}; unknown domain'.format(response.url))
        return
    item = dict()
    item['some_field'] = repsonse.xpath(xpath).extract()
    yield item
</code>```

Body:
I'm new in Scrapy. I have thousands of url,xpath tuples and values in a database.
These urls are from different domains (not allways, there can be 100 urls from the same domain).

x.com/a //h1
y.com/a //div[@class='1']
z.com/a //div[@href='...']
x.com/b //h1
x.com/c //h1
...

Now I want to get these values every 2 hours as fast as possible but to be sure that I don't overload any of these.

Can't figure out how to do that.

My thoughts:

I could create one Spider for every different domain, set it's parsing rules and run them at once.

Is it a good practice?

EDIT:
I'm not sure how it would work with outputting data into database according to concurrency.

EDIT2:

I can do something like this - for every domain there is a new spider. But this is impossible to do having thousands of different urls and it's xpaths.

class WikiScraper(scrapy.Spider):
    name = "wiki_headers"

    def start_requests(self):
        urls = [
            'https://en.wikipedia.org/wiki/Spider',
            'https://en.wikipedia.org/wiki/Data_scraping',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//h1/text()').extract()
        print header
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)

class CraigslistScraper(scrapy.Spider):
    name = "craigslist_headers"

    def start_requests(self):
        urls = [
            'https://columbusga.craigslist.org/act/6062657418.html',
            'https://columbusga.craigslist.org/acc/6060297390.html',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//span[@id="titletextonly"]/text()').extract()
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)

Body:
If I understand correctly you have map of domain to xpath values and you want to pull xpath depending on what domain you crawl?

Try something like:

DOMAIN_DATA = [('domain.com', '//div')]
def get_domain(url):
    for domain, xpath in DOMAIN_DATA:
        if domain in url:
            return xp

def parse(self, response):
    xpath = get_domain(response.url)
    if not xpath:
        logging.error('no xpath for url: {}; unknown domain'.format(response.url))
        return
    item = dict()
    item['some_field'] = repsonse.xpath(xpath).extract()
    yield item


来源: stackexchange

问:
Cast Remote Display from Android Application to multiple chromecast
Is there are a possibility to stream Android Application to multiple chromecast devices? </p>

答: This is not a supported use case in the Google Cast SDK.</p>

ContentLicense: CC BY-SA 3.0


问:
Drivers for Classes in Java “Rectangle"
I’ve never used a separate file for a driver in Java.  I’m used to just using a main method.  I’ve used separate files in Python but Java is new.  Below is my code for each class (“Rectangle” and “Driver”), each from separate files.

Update with the methods changed to static:  Don’t pay attention to the change in class names or formatting…I’m just tweaking so it will work with MyProgrammingLab.  I still have to add in parameters for length and width being between 0.0 and 20.0 only (easy if-else statements).

```<code>import java.util.Scanner;
</code>```

public class Driver{

```<code>public static void main(String[] args) {

    Scanner input = new Scanner( System.in);

    System.out.print("Enter length of rectangle:");
    double length = input.nextDouble();
    System.out.print("Enter width of rectangle:");
    double width = input.nextDouble();

    Rectangle  Perimeter = new Rectangle(length, width);
    Perimeter.getPerimeter();
    Rectangle  Area = new Rectangle(length, width);
    Area.getArea();

    System.out.printf("Area: %.1f, Perimeter: %.1f",Rectangle.getArea(),Rectangle.getPerimeter());

}
</code>```

}

final class Rectangle {

```<code>private static double mLength;
private static double mWidth;

public Rectangle(double length, double width){
    mLength = length;
    mWidth = width;
}
public double getLength(){
    return mLength;
}

public double getWidth(){
    return mWidth;
}

public static double getArea(){
    double area = mWidth*mLength;
    return area;
}
public static double getPerimeter(){
    double perimeter = (mWidth*2)+(mLength*2);
    return perimeter;

}
</code>```

}

答:
It makes more sense to create a Rectangle object with it's length & width, so use your overloaded  Rectangle constructor by passing the length and width arguments (entered by user) as shown below:

```<code>Rectangle  Perimeter = new Rectangle(length, width);
</code>```

the constructor Rectangle() is undefined. Can anyone help?

The important point is that when you have an overloaded constructor like in your Rectangle class (where there are no default i.e., no argument constructors written), you can't create an object using new Rectangle();, this is because compiler doesn't add the default constrcutor automatically for you. I suggest look here for more details on this.

Also, if you wanted to print the Rectangle object with length & width details, you need to override toString() method from java.lang.Object method as shown below:

```<code>public class Rectangle {

    private double mLength;

    private double mWidth;

    //add your code here as is

    @Override
    public String toString() {
        return "Rectangle [mLength=" + mLength + ", mWidth=" + mWidth + "]";
    }
}
</code>```

Title: Drivers for Classes in Java “Rectangle"

Body:
I’ve never used a separate file for a driver in Java.  I’m used to just using a main method.  I’ve used separate files in Python but Java is new.  Below is my code for each class (“Rectangle” and “Driver”), each from separate files.

Update with the methods changed to static:  Don’t pay attention to the change in class names or formatting…I’m just tweaking so it will work with MyProgrammingLab.  I still have to add in parameters for length and width being between 0.0 and 20.0 only (easy if-else statements).

import java.util.Scanner;

public class Driver{

public static void main(String[] args) {

    Scanner input = new Scanner( System.in);

    System.out.print("Enter length of rectangle:");
    double length = input.nextDouble();
    System.out.print("Enter width of rectangle:");
    double width = input.nextDouble();

    Rectangle  Perimeter = new Rectangle(length, width);
    Perimeter.getPerimeter();
    Rectangle  Area = new Rectangle(length, width);
    Area.getArea();

    System.out.printf("Area: %.1f, Perimeter: %.1f",Rectangle.getArea(),Rectangle.getPerimeter());

}

}

final class Rectangle {

private static double mLength;
private static double mWidth;

public Rectangle(double length, double width){
    mLength = length;
    mWidth = width;
}
public double getLength(){
    return mLength;
}

public double getWidth(){
    return mWidth;
}

public static double getArea(){
    double area = mWidth*mLength;
    return area;
}
public static double getPerimeter(){
    double perimeter = (mWidth*2)+(mLength*2);
    return perimeter;

}

}

Body:
It makes more sense to create a Rectangle object with it's length & width, so use your overloaded  Rectangle constructor by passing the length and width arguments (entered by user) as shown below:

Rectangle  Perimeter = new Rectangle(length, width);

the constructor Rectangle() is undefined. Can anyone help?

The important point is that when you have an overloaded constructor like in your Rectangle class (where there are no default i.e., no argument constructors written), you can't create an object using new Rectangle();, this is because compiler doesn't add the default constrcutor automatically for you. I suggest look here for more details on this.

Also, if you wanted to print the Rectangle object with length & width details, you need to override toString() method from java.lang.Object method as shown below:

public class Rectangle {

    private double mLength;

    private double mWidth;

    //add your code here as is

    @Override
    public String toString() {
        return "Rectangle [mLength=" + mLength + ", mWidth=" + mWidth + "]";
    }
}


问:
Gnome Desktop Icons Alignment
It has been a long time since I started to compare the gnome desktop to the windows desktop.

But since I began to use linux, I realized that the "gnome way" to align the icons on Desktop is not that nice for me. And comparing to Windows's way, windows is better for me. (remember, for me).

I'd like to know if anyone has some tip to make "gnome desktop icon alignment" more like windows do. I tried to reduce the icon's size, did something, but was not that all.

So, could anyone tell another tip? I like when I put something on windows desktop, and wherever I put the file, Windows organize the file and put the icon right after the last icon (in a cascade style) (and automatically).

Any tips?

答:
Gnome 3.22

Open dconf editor.
1. Navigate to
-  org.gnome.nautilus.desktop > text-ellipsis-limit  1

- org.gnome.nautilus.icon-view > text-ellipsis-limit  ['0']
- org.gnome.SessionManager > auto-save-session  true

2.-Restart

On desktop right click and

check Keep aligned then Organise Desktop by name or

uncheck Keep aligNed and Organise Desktop by name.

This is the most you can get comparing to Windows's way (Gnome Desktop is really an unprofessional real mess!)

P.S. On org.gnome.nautilus.desktop > font xx --try different values to enlarge/shorten the icon label.

ContentLicense: CC BY-SA 2.5

Title: Gnome Desktop Icons Alignment


问:
Calculate distance between two locations in metre
I have two locations and I want to calculate distance in meter. I wrote some code but it's not working perfectly.

```<code>private void getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2)
{
    Location loc1 = new Location("");
    loc1.setLatitude(lat1);
    loc1.setLongitude(lon1);

    Location loc2 = new Location("");
    loc2.setLatitude(lat2);
    loc2.setLongitude(lon2);

    int R = 6371; // km

    double dLat = deg2rad(lat2-lat1);
    double dLon = deg2rad(lon2-lon1);
    double  a =
            Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
                            Math.sin(dLon/2) * Math.sin(dLon/2)
            ;
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double distanceInMeters = R * c;
    Log.e("distanceInMeters",distanceInMeters/10000+"mm");
}

public double  deg2rad(double deg) {
    return deg * (Math.PI/180);
}
</code>```

How can I calculate distance in meter? My goal is, if meter > 200 do something. How can i solve my problem?

答:
You can use below code for calculating distance between two Location in Metres:</p>

```<code>private double distanceBetween(double lat1, double lon1, double lat2, double lon2) {
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1))
            * Math.sin(deg2rad(lat2))
            + Math.cos(deg2rad(lat1))
            * Math.cos(deg2rad(lat2))
            * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = dist * 180.0 / Math.PI;
    dist = dist * 60 * 1.1515*1000;
    return (dist);
}

private double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two locations and I want to calculate distance in meter. I wrote some code but it's not working perfectly.

private void getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2)
{
    Location loc1 = new Location("");
    loc1.setLatitude(lat1);
    loc1.setLongitude(lon1);

    Location loc2 = new Location("");
    loc2.setLatitude(lat2);
    loc2.setLongitude(lon2);

    int R = 6371; // km

    double dLat = deg2rad(lat2-lat1);
    double dLon = deg2rad(lon2-lon1);
    double  a =
            Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
                            Math.sin(dLon/2) * Math.sin(dLon/2)
            ;
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double distanceInMeters = R * c;
    Log.e("distanceInMeters",distanceInMeters/10000+"mm");
}

public double  deg2rad(double deg) {
    return deg * (Math.PI/180);
}

How can I calculate distance in meter? My goal is, if meter > 200 do something. How can i solve my problem?

Body:
You can use below code for calculating distance between two Location in Metres:

private double distanceBetween(double lat1, double lon1, double lat2, double lon2) {
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1))
            * Math.sin(deg2rad(lat2))
            + Math.cos(deg2rad(lat1))
            * Math.cos(deg2rad(lat2))
            * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = dist * 180.0 / Math.PI;
    dist = dist * 60 * 1.1515*1000;
    return (dist);
}

private double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}


问:
AngularJS: SELECT Option not selected when ng-model is an array
How can I get the Broken example (below) to work without changing it from an array (as I have a lot of code that depends on it being an array in other parts of the application)?

I'd like to continue using an array but I'd like the correct select option to show when the model changes.  The model changes correctly when the button is clicked but the option isn't being found in the select (ng-model and ng-options just aren't matching up when it's an array).

angular.module('app', [])
  .controller('MainCtrl', ['$scope', function($scope) {

    $scope.valueWorking = 'value1';
    $scope.selectFilterWorking = [{name: 'name1', value: 'value1'},{name: 'name2', value: 'value2'}];

    $scope.valueBroken = ['value1'];
    $scope.selectFilterBroken = [{name: 'name1', value: ['value1']},{name: 'name2', value: ['value2', 'value3']}];

  }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">

  <strong>Working</strong> (SELECT <i>is</i> updated when ng-model is a string):<br>
  <select ng-model="valueWorking"
          ng-options="select.value as select.name for select in selectFilterWorking">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueWorking='value2'">Assign to String of 'value2'</button> {{valueWorking}}<br><br>

  <strong>Broken</strong> (SELECT <i>not</i> updated when ng-model is an array):<br>
  <select ng-model="valueBroken"
          ng-options="select.value as select.name for select in selectFilterBroken">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueBroken=['value2','value3']">Assign to Array of ["value2","value3"]</button> {{valueBroken}}

</div></code>```

Upon clicking 'Run code snippet' above, notice that the initial option is not selected (on the Broken select, when it's an array), but is initially selected on the Working select when it's a string. The correct option is also not shown when 'Assign to Array of ["value2"]' is clicked.

UPDATE:  I'm trying to get the OPTIONS ($scope.selectFilterBroken) to match the MODEL, rather than the other way around - hence my need to keep the model as an array.  The button click is merely to simulate the other parts of the application that manipulate the array.

Any help would be great.  Thanks and please.

答:
The reason its not binding is because the array value on $scope.valueBroken is different from the arrays in the $scope.selectFilterBroken. For them to match they have to be in the same array. For example, I have edited your code and assigned the value of an item in $scope.selectFilterBroken to $scope.valueBroken. And it is working fine now.

angular.module('app', [])
  .controller('MainCtrl', ['$scope', function($scope) {

    $scope.valueWorking = 'value1';
    $scope.selectFilterWorking = [{name: 'name1', value: 'value1'},{name: 'name2', value: 'value2'}];

    $scope.selectFilterBroken = [{name: 'name1', value: ['value1']},{name: 'name2', value: ['value2']}];
    $scope.valueBroken = $scope.selectFilterBroken[0].value;

  }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">

  <strong>Working</strong> (SELECT <i>is</i> updated when ng-model is a string):<br>
  <select ng-model="valueWorking"
          ng-options="select.value as select.name for select in selectFilterWorking">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueWorking='value2'">Assign to String of 'value2'</button> {{valueWorking}}<br><br>

  <strong>Broken</strong> (SELECT <i>not</i> updated when ng-model is an array):<br>
  <select ng-model="valueBroken"
          ng-options="select.value as select.name for select in selectFilterBroken">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueBroken=['value2']">Assign to Array of ["value2"]</button> {{valueBroken}}

</div></code>```

Body:
How can I get the Broken example (below) to work without changing it from an array (as I have a lot of code that depends on it being an array in other parts of the application)?

I'd like to continue using an array but I'd like the correct select option to show when the model changes.  The model changes correctly when the button is clicked but the option isn't being found in the select (ng-model and ng-options just aren't matching up when it's an array).

angular.module('app', [])
  .controller('MainCtrl', ['$scope', function($scope) {

    $scope.valueWorking = 'value1';
    $scope.selectFilterWorking = [{name: 'name1', value: 'value1'},{name: 'name2', value: 'value2'}];

    $scope.valueBroken = ['value1'];
    $scope.selectFilterBroken = [{name: 'name1', value: ['value1']},{name: 'name2', value: ['value2', 'value3']}];

  }]);

  Working (SELECT is updated when ng-model is a string):

  <select ng-model="valueWorking"
          ng-options="select.value as select.name for select in selectFilterWorking">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueWorking='value2'">Assign to String of 'value2'</button> {{valueWorking}}

  Broken (SELECT not updated when ng-model is an array):

  <select ng-model="valueBroken"
          ng-options="select.value as select.name for select in selectFilterBroken">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueBroken=['value2','value3']">Assign to Array of ["value2","value3"]</button> {{valueBroken}}

Upon clicking 'Run code snippet' above, notice that the initial option is not selected (on the Broken select, when it's an array), but is initially selected on the Working select when it's a string. The correct option is also not shown when 'Assign to Array of ["value2"]' is clicked.

UPDATE:  I'm trying to get the OPTIONS ($scope.selectFilterBroken) to match the MODEL, rather than the other way around - hence my need to keep the model as an array.  The button click is merely to simulate the other parts of the application that manipulate the array.

Any help would be great.  Thanks and please.

Body:
The reason its not binding is because the array value on $scope.valueBroken is different from the arrays in the $scope.selectFilterBroken. For them to match they have to be in the same array. For example, I have edited your code and assigned the value of an item in $scope.selectFilterBroken to $scope.valueBroken. And it is working fine now.

angular.module('app', [])
  .controller('MainCtrl', ['$scope', function($scope) {

    $scope.valueWorking = 'value1';
    $scope.selectFilterWorking = [{name: 'name1', value: 'value1'},{name: 'name2', value: 'value2'}];

    $scope.selectFilterBroken = [{name: 'name1', value: ['value1']},{name: 'name2', value: ['value2']}];
    $scope.valueBroken = $scope.selectFilterBroken[0].value;

  }]);

<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">

  <strong>Working</strong> (SELECT <i>is</i> updated when ng-model is a string):<br>
  <select ng-model="valueWorking"
          ng-options="select.value as select.name for select in selectFilterWorking">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueWorking='value2'">Assign to String of 'value2'</button> {{valueWorking}}<br><br>

  <strong>Broken</strong> (SELECT <i>not</i> updated when ng-model is an array):<br>
  <select ng-model="valueBroken"
          ng-options="select.value as select.name for select in selectFilterBroken">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueBroken=['value2']">Assign to Array of ["value2"]</button> {{valueBroken}}

</div>


问:
Wait on background thread for a random time
Currently I'm using this to wait for 5 seconds on the background thread before calling a function: DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 5, execute: {

This works great but I'd like to wait for a random duration each time.
Doing something like this:

```<code>let randomTime = Int(arc4random_uniform(10))
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + randomTime, execute: {
</code>```

gives me the error: Type of expression is ambiguous without more context

Cheers.

答:
Try below code:

```<code>    let randomTime = Int(arc4random_uniform(10))

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(randomTime)) {

    print("Delay is \(randomTime) sec")

        //Do something here
    }
</code>```

You can also use .microseconds(Int) and .nanoseconds(Int) depends on your requirement.

Body:
Currently I'm using this to wait for 5 seconds on the background thread before calling a function: DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 5, execute: {

This works great but I'd like to wait for a random duration each time.
Doing something like this:

let randomTime = Int(arc4random_uniform(10))
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + randomTime, execute: {

gives me the error: Type of expression is ambiguous without more context

Cheers.

Body:
Try below code:

    let randomTime = Int(arc4random_uniform(10))

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(randomTime)) {

    print("Delay is \(randomTime) sec")

        //Do something here
    }

You can also use .microseconds(Int) and .nanoseconds(Int) depends on your requirement.


答:
Looking at the docs for Dispatch, there appears to be two overloads for the + operator that would work for you:

```<code>public func +(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime

public func +(time: DispatchTime, seconds: Double) -> DispatchTime
</code>```

I suggest using the second function and initializing a Double instead of Int like you're trying to do now:

```<code>let randomTime = Double(arc4random_uniform(10))
</code>```

Title: Wait on background thread for a random time

Body:
Looking at the docs for Dispatch, there appears to be two overloads for the + operator that would work for you:

public func +(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime

public func +(time: DispatchTime, seconds: Double) -> DispatchTime

I suggest using the second function and initializing a Double instead of Int like you're trying to do now:

let randomTime = Double(arc4random_uniform(10))


问:
Running Calabash via SSH on Mac iOS Simulator Launch Fails
I'm trying to run Calabash test cases on another Mac vis SSH from another Mac. The user I ssh in with is not admin but I've given permission as described at https://superuser.com/questions/166179/how-to-enable-remote-access-for-another-account-on-mac-remotely-via-ssh

So after bundle exec cucumber the test cases start to run but the iOS Simulator doesn't launch and it fails with the error:

```<code>LSOpenURLsWithRole() failed for the application /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app with error -10810.
</code>```

Anyone know why this happens?

答:
After sshing in, try

```<code>chmod +x /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
</code>```

Body:
I'm trying to run Calabash test cases on another Mac vis SSH from another Mac. The user I ssh in with is not admin but I've given permission as described at https://superuser.com/questions/166179/how-to-enable-remote-access-for-another-account-on-mac-remotely-via-ssh

So after bundle exec cucumber the test cases start to run but the iOS Simulator doesn't launch and it fails with the error:

LSOpenURLsWithRole() failed for the application /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app with error -10810.

Anyone know why this happens?

Body:
After sshing in, try

chmod +x /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app


问:
JetBrains PyCharm is great, but I don't want to spend the $99
I'm sure this question is a great candidate for being closed as not being strictly a programming question but here goes.

I started developing a simple toy website using Django. The IDE I decided to use was JetBrains's PyCharm. My trial period has no expired. Can you recommend another IDE that's comparable to PyCharm but doesn't cost the $99?

Or do you think PyCharm is worth the $99?

I'd like to eventually incorporate myself so i can expense these types of expenditures, but as of right now, I can't wait until I'm incorporated to start developing .

Any suggestions will be appreciated.

Edit: I'm running Fedora 13.

答:
I purchased PyCharm as I do not find Eclipse with PyDev to really deliver what I need.

Of course, your mileage may vary, but I found the ease of which I could use TextMate syntax highlighting schemes with PyCharm a very large plus. I am rather infatuated with Monokai as my default colour scheme and setting it up with PyCharm was so much less painful than having to try and get Eclipse to play nicely.

Also, the download/update is more manageable with PyCharm than it is or ever will be with Eclipse.

The developers at JetBrains are also very responsive with regard to feature requests and bug fixing.

All in all the positive sides of PyCharm were for me the reason to bite the bullet and spend the money. As a disclaimer I have to mention that I had been able to buy it at the 50% price which was available during beta testing.


问:
Best way to execute multiple animations synchronously
This will be a 'best way to do' kind of a question.

I know there are multiple ways to do sequence animations, but which one is the better way to do it?

let's say I have 3 animations that I'm trying to execute, one after the other, so the next one only starts when the previous has finished.

I can do it with the UIView.animate(withCompletionBlock:) so in the completion section I call the second one and on the completionBlock of the second one I call the third one.

This one in particular makes me think: Is that a 'beautiful' way to do it? Is there any known issues using completionBlocks within another?

Just a thought. Calling animations within the previous animation completion block, may bring the code somehow like the pyramid of doom, if there's something like 10 synchronous animations, don't you think?

Another way to do is with the dispatch_after, the I call the next animation based on the NSTimeInterval of the previous one. In this case it may cause a app crash suspending the Main thread for the next one to execute, then suspend it again to execute the third one.

The last known way that I know is that I can use a NSTimeInterval to call the next animation, but this one is somewhat like the dispatch_after option.

In your opinion which would be the best way to do it?
Executing 3 or more visual animations, all synchronously (waiting for the previous one to finish to start the next one).

I might use this a lot in my app and I want to start it with the best way.

EXAMPLES

Animations within completionBlocks

```<code>DispatchQueue.main.async {
        UIView.animate(withDuration: 2.0, animations: {
            view1.alpha = 1
        }, completion: { (_) in
            UIView.animate(withDuration: 5.0, animations: {
                view2.alpha = 1
            }, completion: { (_) in
                UIView.animate(withDuration: 2.0, animations: {
                    view3.alpha = 0
                }, completion: { (_) in
                    UIView.animate(withDuration: 2.0, animations: {
                        view4.alpha = 0
                    }, completion: { (_) in
                            print("all completed")
                    })
                })
            })
        })
    }
</code>```

With dispatch_after:

```<code>    let anim1_duration = 2.0
    let anim2_duration = 3.0
    let anim3_duraiton = 5.0

    UIView.animate(withDuration: anim1_duration, animations: {
        view1.alpha = 1
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: UInt64(anim1_duration * Double(NSEC_PER_SEC)))) {
        UIView.animate(withDuration: anim2_duration, animations: {
            view2.alpha = 1
        }
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: UInt64((anim1_duration + anim2_duration) * Double(NSEC_PER_SEC)))) {
        UIView.animate(withDuration: anim3_duration, animations: {
            view3.alpha = 1
        }
    }
</code>```

答:
Check out UIView's animateKeyframes(withDuration:delay:options:animations:completion:):

```<code>class func animateKeyframes(withDuration duration: TimeInterval,
                      delay: TimeInterval,
                    options: UIViewKeyframeAnimationOptions = [],
                 animations: @escaping () -> Void,
                 completion: ((Bool) -> Void)? = nil)
</code>```

For your specific case, it would look like this:

```<code>UIView.animateKeyframes(withDuration: 20,
                        delay: 0,
                        options: [],
                        animations: {

                            UIView.addKeyframe(withRelativeStartTime: 0,
                                               relativeDuration: 0.2,
                                               animations: {
                                view1.alpha = 1
                            })

                            UIView.addKeyframe(withRelativeStartTime: 0.2,
                                               relativeDuration: 0.3,
                                               animations: {
                                view2.alpha = 1
                            })

                            UIView.addKeyframe(withRelativeStartTime: 0.5,
                                               relativeDuration: 0.1,
                                               animations: {
                                view3.alpha = 0
                            })

                            UIView.addKeyframe(withRelativeStartTime: 0.6,
                                               relativeDuration: 0.4,
                                               animations: {
                                view4.alpha = 0
                            })
},
                        completion: nil)
</code>```

Body:
This will be a 'best way to do' kind of a question.

I know there are multiple ways to do sequence animations, but which one is the better way to do it?

let's say I have 3 animations that I'm trying to execute, one after the other, so the next one only starts when the previous has finished.

I can do it with the UIView.animate(withCompletionBlock:) so in the completion section I call the second one and on the completionBlock of the second one I call the third one.

This one in particular makes me think: Is that a 'beautiful' way to do it? Is there any known issues using completionBlocks within another?

Just a thought. Calling animations within the previous animation completion block, may bring the code somehow like the pyramid of doom, if there's something like 10 synchronous animations, don't you think?

Another way to do is with the dispatch_after, the I call the next animation based on the NSTimeInterval of the previous one. In this case it may cause a app crash suspending the Main thread for the next one to execute, then suspend it again to execute the third one.

The last known way that I know is that I can use a NSTimeInterval to call the next animation, but this one is somewhat like the dispatch_after option.

In your opinion which would be the best way to do it?
Executing 3 or more visual animations, all synchronously (waiting for the previous one to finish to start the next one).

I might use this a lot in my app and I want to start it with the best way.

EXAMPLES

Animations within completionBlocks

DispatchQueue.main.async {
        UIView.animate(withDuration: 2.0, animations: {
            view1.alpha = 1
        }, completion: { (_) in
            UIView.animate(withDuration: 5.0, animations: {
                view2.alpha = 1
            }, completion: { (_) in
                UIView.animate(withDuration: 2.0, animations: {
                    view3.alpha = 0
                }, completion: { (_) in
                    UIView.animate(withDuration: 2.0, animations: {
                        view4.alpha = 0
                    }, completion: { (_) in
                            print("all completed")
                    })
                })
            })
        })
    }

With dispatch_after:

    let anim1_duration = 2.0
    let anim2_duration = 3.0
    let anim3_duraiton = 5.0

    UIView.animate(withDuration: anim1_duration, animations: {
        view1.alpha = 1
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: UInt64(anim1_duration * Double(NSEC_PER_SEC)))) {
        UIView.animate(withDuration: anim2_duration, animations: {
            view2.alpha = 1
        }
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: UInt64((anim1_duration + anim2_duration) * Double(NSEC_PER_SEC)))) {
        UIView.animate(withDuration: anim3_duration, animations: {
            view3.alpha = 1
        }
    }

Body:
Check out UIView's animateKeyframes(withDuration:delay:options:animations:completion:):

class func animateKeyframes(withDuration duration: TimeInterval,
                      delay: TimeInterval,
                    options: UIViewKeyframeAnimationOptions = [],
                 animations: @escaping () -> Void,
                 completion: ((Bool) -> Void)? = nil)

For your specific case, it would look like this:

UIView.animateKeyframes(withDuration: 20,
                        delay: 0,
                        options: [],
                        animations: {

                            UIView.addKeyframe(withRelativeStartTime: 0,
                                               relativeDuration: 0.2,
                                               animations: {
                                view1.alpha = 1
                            })

                            UIView.addKeyframe(withRelativeStartTime: 0.2,
                                               relativeDuration: 0.3,
                                               animations: {
                                view2.alpha = 1
                            })

                            UIView.addKeyframe(withRelativeStartTime: 0.5,
                                               relativeDuration: 0.1,
                                               animations: {
                                view3.alpha = 0
                            })

                            UIView.addKeyframe(withRelativeStartTime: 0.6,
                                               relativeDuration: 0.4,
                                               animations: {
                                view4.alpha = 0
                            })
},
                        completion: nil)


问:
Visual C++ debugger not showing return value
When I single-step with the Visual Studio debugger through the following program, no return value is shown in the "auto" window for any of the istringstream method calls.

It shows the return value for vector::size() though.

```<code>#include "stdafx.h"
#include <sstream>
#include <vector>

int main()
{
    std::vector<char>{}.size();      //<-- debugger shows return value
    std::istringstream{"x"}.get();   //<-- no return value shown
    std::istringstream{"x"}.good();  //<-- no return value shown
    std::istringstream{"x"}.tellg(); //<-- no return value shown
    return 0;
}
</code>```

Of course I run this in "debug" configuration, so the compiler shouldn't be able to optimize the calls away. I created the project using console application wizard without changing any project settings afterwards.

Should I file a bug?

Edit:

Another possibly related issue: I can't F11-step into any of the above istringstream methods. Debugger just steps over them as if I had pressed F10. Again, it works for vector::size().

答:
It turns out that this was an issue of missing debug symbols when dynamically linking to the VC++ runtime. After a default installation of Visual Studio 2017, for instance, debug symbols for the VC++ runtime are not available.

Possible solutions:

statically link to the VC++ Runtime (project properties > C/C++ > Code Generation > Runtime Library: Multithreaded-Debug)

enable Microsoft symbol server (Extras > Options > Debugging > Symbols > Check "Microsoft Symbol Server" and enter directory for storing symbols in the edit control below)

I think the issue did not occur for std::vector because it is header-only, so the code gets linked directly into the program executable. For the C++ stream library, much of the code actually is inside a VC runtime DLL.

Body:
When I single-step with the Visual Studio debugger through the following program, no return value is shown in the "auto" window for any of the istringstream method calls.

It shows the return value for vector::size() though.

#include "stdafx.h"
#include <sstream>
#include <vector>

int main()
{
    std::vector<char>{}.size();      //<-- debugger shows return value
    std::istringstream{"x"}.get();   //<-- no return value shown
    std::istringstream{"x"}.good();  //<-- no return value shown
    std::istringstream{"x"}.tellg(); //<-- no return value shown
    return 0;
}

Of course I run this in "debug" configuration, so the compiler shouldn't be able to optimize the calls away. I created the project using console application wizard without changing any project settings afterwards.

Should I file a bug?

Edit:

Another possibly related issue: I can't F11-step into any of the above istringstream methods. Debugger just steps over them as if I had pressed F10. Again, it works for vector::size().


问:
What's wrong with my code that prints structure information?
```<code>#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <ctype.h>

struct ALUMNO{
    int cod;
    char nombre[20], grupo[3], app[20], apm[20];
    float prom,cali[5];
} al[20]={'\0'};

void gotoxy(int x,int y){
    HANDLE hcon;
    hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD dwPos;
    dwPos.X = x;
    dwPos.Y= y;
    SetConsoleCursorPosition(hcon,dwPos);
}

int main()
{
    char gru[3];
    int x = 0, sw, ac;
    al[0].cod=12345;
    strcpy(al[0].grupo,"1A");
    strcpy(al[0].nombre,"Erick");
    strcpy(al[0].app,"Medina");
    strcpy(al[0].apm,"Ramirez");
    al[0].prom=0.0;

    al[1].cod=12346;
    strcpy(al[1].grupo,"1A");
    strcpy(al[1].nombre,"Emmanuel");
    strcpy(al[1].app,"Sauceda");
    strcpy(al[1].apm,"Perez");
    al[1].prom=0.0;

    al[2].cod=12347;
    strcpy(al[2].grupo,"1B");
    strcpy(al[2].nombre,"Vincio");
    strcpy(al[2].app,"Lopez");
    strcpy(al[2].apm,"Martinez");
    al[2].prom=0.0;
    //salon B
    al[3].cod=12348;
    strcpy(al[3].grupo,"1B");
    strcpy(al[3].nombre,"Bryan");
    strcpy(al[3].app,"Osuna");
    strcpy(al[3].apm,"Beltran");
    al[3].prom=0.0;

    al[4].cod=12349;
    strcpy(al[4].grupo,"1C");
    strcpy(al[4].nombre,"Fullano");
    strcpy(al[4].app,"Mangano");
    strcpy(al[4].apm,"Centenario");
    al[4].prom=0.0;

    al[5].cod=12350;
    strcpy(al[5].grupo,"1C");
    strcpy(al[5].nombre,"Chapo");
    strcpy(al[5].app,"Guzman");
    strcpy(al[5].apm,"Loera");
    al[5].prom=0.0;
    //done

    printf("Grupo: ");
    scanf("%s",&gru);
    gru[1]=toupper(gru[1]);
    system("cls");
    printf("Codigo\tAp.paterno\tap.materno\tnombre\tpromedio");
    for (x=0, sw=0; x<25 && al[x].cod!=0; x++){
        if (strcmp(gru,al[x].grupo)==0){
            sw=1;
            ac++;
        }
        if (sw==1){
            gotoxy(1,ac);
            printf("%i",al[x].cod);
            gotoxy(12,ac);
            printf("%s",al[x].app);
            gotoxy(30,ac);
            printf("%s",al[x].apm);
            gotoxy(50,ac);
            printf("%s",al[x].nombre);
            gotoxy(60,ac);
            printf("%.2f",al[x].prom);
        }
    }
    ac=0;
}
</code>```

For some reason, when you type in the correct group and hit enter, it will print maternal last names on top of others. Or some names maybe missing, or it's just my compiler. It works fine when you only have one name per group.

答:
Your gru variable is used wrong in scanf.  Should be gru, not &gru.

By the way, don't use scanf, use fgets

Body:
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <ctype.h>

struct ALUMNO{
    int cod;
    char nombre[20], grupo[3], app[20], apm[20];
    float prom,cali[5];
} al[20]={'\0'};

void gotoxy(int x,int y){
    HANDLE hcon;
    hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD dwPos;
    dwPos.X = x;
    dwPos.Y= y;
    SetConsoleCursorPosition(hcon,dwPos);
}

int main()
{
    char gru[3];
    int x = 0, sw, ac;
    al[0].cod=12345;
    strcpy(al[0].grupo,"1A");
    strcpy(al[0].nombre,"Erick");
    strcpy(al[0].app,"Medina");
    strcpy(al[0].apm,"Ramirez");
    al[0].prom=0.0;

    al[1].cod=12346;
    strcpy(al[1].grupo,"1A");
    strcpy(al[1].nombre,"Emmanuel");
    strcpy(al[1].app,"Sauceda");
    strcpy(al[1].apm,"Perez");
    al[1].prom=0.0;

    al[2].cod=12347;
    strcpy(al[2].grupo,"1B");
    strcpy(al[2].nombre,"Vincio");
    strcpy(al[2].app,"Lopez");
    strcpy(al[2].apm,"Martinez");
    al[2].prom=0.0;
    //salon B
    al[3].cod=12348;
    strcpy(al[3].grupo,"1B");
    strcpy(al[3].nombre,"Bryan");
    strcpy(al[3].app,"Osuna");
    strcpy(al[3].apm,"Beltran");
    al[3].prom=0.0;

    al[4].cod=12349;
    strcpy(al[4].grupo,"1C");
    strcpy(al[4].nombre,"Fullano");
    strcpy(al[4].app,"Mangano");
    strcpy(al[4].apm,"Centenario");
    al[4].prom=0.0;

    al[5].cod=12350;
    strcpy(al[5].grupo,"1C");
    strcpy(al[5].nombre,"Chapo");
    strcpy(al[5].app,"Guzman");
    strcpy(al[5].apm,"Loera");
    al[5].prom=0.0;
    //done

    printf("Grupo: ");
    scanf("%s",&gru);
    gru[1]=toupper(gru[1]);
    system("cls");
    printf("Codigo\tAp.paterno\tap.materno\tnombre\tpromedio");
    for (x=0, sw=0; x<25 && al[x].cod!=0; x++){
        if (strcmp(gru,al[x].grupo)==0){
            sw=1;
            ac++;
        }
        if (sw==1){
            gotoxy(1,ac);
            printf("%i",al[x].cod);
            gotoxy(12,ac);
            printf("%s",al[x].app);
            gotoxy(30,ac);
            printf("%s",al[x].apm);
            gotoxy(50,ac);
            printf("%s",al[x].nombre);
            gotoxy(60,ac);
            printf("%.2f",al[x].prom);
        }
    }
    ac=0;
}

For some reason, when you type in the correct group and hit enter, it will print maternal last names on top of others. Or some names maybe missing, or it's just my compiler. It works fine when you only have one name per group.


问:
Re-positioning captions in lightbox2
I'm a total noob and I've successfully downloaded lightbox2 and am wondering if there is a way to move the caption to the right of the image.

I have read some of the other tutorials describing how to find a line of code in the js file... but they are quite old and it looks like I may have a newer version.

I've been trying to play around with the css but to no avail.  I have no idea what to look for in the js. version of the file.  Any help would be very much appreciated.

答:
Using your web browser's document inspector can be very helpful when tinkering with css.

If you override the .lb-details class you can position the text to the right.

```<code>.lb-data .lb-details {
    text-align: right;
}
</code>```

Title: Re-positioning captions in lightbox2

Body:
Using your web browser's document inspector can be very helpful when tinkering with css.

If you override the .lb-details class you can position the text to the right.

.lb-data .lb-details {
    text-align: right;
}


问:
C - Why do I keep printing out the Memory Address instead of the value in the array
I am having trouble printing out the values stored in the array. It seems to be printing out the memory address instead. Here is my code:

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

void getMatrix(int x, int y);
void printMatrix(int arr[], int x, int y);
int product(int arr1[], int arr2[]);

int main(void){

 //Variables that will store matrix size
 int m, n, o, p;

 //Prompt user for size of Matrix A
 printf("Enter the rows and columns of Matrix A with space in between: ");

 //Read input
 scanf("%d %d", &m, &n);

 //Prompt user for the size of Matrix B
 printf("Enter the rows and columns of Matrix B with space in between: ");

 //Read input
 scanf("%d %d", &o, &p);

 //Seed RND Generator
 srand(time(NULL));

 //Check input
 if(n != o){
  while(n != o){
   printf("Matrix Sizes are not valid. Please enter valid sizes for the Matrices: ");
   scanf("%d %d %d %d", &m, &n, &o, &p);
  }
 }

 //Function Calls
 printf("Matrix 1:\n");
 getMatrix(m, n);
 printf("\nMatrix 2:\n");
 getMatrix(o, p);
}

void getMatrix(int x, int y){

 //Counter
 int c;

 //Size Declaration
 int size = x * y;

 //Array Declaration
 int arr[size];

 for(c = 0; c < size; c++){
  arr[c] = rand()%10;
 }

 printMatrix(arr[size], x, y);
}

void printMatrix(int arr[], int x, int y){

 //Counters
 int i, j;

 for(i = 0; i < y; i++){
  printf("\n");
  for(j = 0; j < x; j++){
   printf("%d ", arr[j]);
  }
 }
}
</code>```

So basically this code is supposed to take in input and create a variable length array and its supposed to store random numbers in a 1 dimensional array and then they have to be printed out in the form of a 2d array or a matrix. I feel there might be something wrong with the parameters of the printMatrix function or when passing the array obtained in the getMatrix function. Any help would be appreciated, thank you.

EDIT: Thank you all for the help. I didn't even think about using this as a solution. But it works now and prints out the numbers that it is supposed to. Thanks again

答:
I believe the problem lies with this line of code:

```<code>printMatrix(arr[size], x, y);
</code>```

It should be

```<code>printMatrix(arr, x, y);
</code>```

The printMatrix function expects an array, but in your code you pass an element from the array.

Body:
I am having trouble printing out the values stored in the array. It seems to be printing out the memory address instead. Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void getMatrix(int x, int y);
void printMatrix(int arr[], int x, int y);
int product(int arr1[], int arr2[]);

int main(void){

 //Variables that will store matrix size
 int m, n, o, p;

 //Prompt user for size of Matrix A
 printf("Enter the rows and columns of Matrix A with space in between: ");

 //Read input
 scanf("%d %d", &m, &n);

 //Prompt user for the size of Matrix B
 printf("Enter the rows and columns of Matrix B with space in between: ");

 //Read input
 scanf("%d %d", &o, &p);

 //Seed RND Generator
 srand(time(NULL));

 //Check input
 if(n != o){
  while(n != o){
   printf("Matrix Sizes are not valid. Please enter valid sizes for the Matrices: ");
   scanf("%d %d %d %d", &m, &n, &o, &p);
  }
 }

 //Function Calls
 printf("Matrix 1:\n");
 getMatrix(m, n);
 printf("\nMatrix 2:\n");
 getMatrix(o, p);
}

void getMatrix(int x, int y){

 //Counter
 int c;

 //Size Declaration
 int size = x * y;

 //Array Declaration
 int arr[size];

 for(c = 0; c < size; c++){
  arr[c] = rand()%10;
 }

 printMatrix(arr[size], x, y);
}

void printMatrix(int arr[], int x, int y){

 //Counters
 int i, j;

 for(i = 0; i < y; i++){
  printf("\n");
  for(j = 0; j < x; j++){
   printf("%d ", arr[j]);
  }
 }
}

So basically this code is supposed to take in input and create a variable length array and its supposed to store random numbers in a 1 dimensional array and then they have to be printed out in the form of a 2d array or a matrix. I feel there might be something wrong with the parameters of the printMatrix function or when passing the array obtained in the getMatrix function. Any help would be appreciated, thank you.

EDIT: Thank you all for the help. I didn't even think about using this as a solution. But it works now and prints out the numbers that it is supposed to. Thanks again

Body:
I believe the problem lies with this line of code:

printMatrix(arr[size], x, y);

It should be

printMatrix(arr, x, y);

The printMatrix function expects an array, but in your code you pass an element from the array.


答:
This declaration

```<code>int arr[size];
</code>```

says that arr is an array of size ints.  Thus,

```<code>printMatrix( arr[size], x, y );
</code>```

passes the value that happens to be where the first int just outside arr would be for the first argument, which the function interprets to be the address of the array to be printed.

Also, note that printMatrix keeps printing the first row again and again, as opposed to each successive row.

Title: C - Why do I keep printing out the Memory Address instead of the value in the array

Body:
This declaration

int arr[size];

says that arr is an array of size ints.  Thus,

printMatrix( arr[size], x, y );

passes the value that happens to be where the first int just outside arr would be for the first argument, which the function interprets to be the address of the array to be printed.

Also, note that printMatrix keeps printing the first row again and again, as opposed to each successive row.


问:
How do you manage SQL Queries
At the moment my code (PHP) has too many SQL queries in it. eg...

```<code>// not a real example, but you get the idea...
$results = $db->GetResults("SELECT * FROM sometable WHERE iUser=$userid");
if ($results) {
    // Do something
}
</code>```

I am looking into using stored procedures to reduce this and make things a little more robust, but I have some concerns..

I have hundreds of different queries in use around the web site, and many of them are quite similar. How should I manage all these queries when they are removed from their context (the code that uses the results) and placed in a stored procedure on the database?

答:
I'd move all the SQL to a separate Perl module (.pm)  Many queries could reuse the same functions, with slightly different parameters.

A common mistake for developers is to dive into ORM libraries, parametrized queries and stored procedures.   We then work for months in a row to make the code "better", but it's only "better" in a development kind of way.  You're not making any new features!

Use complexity in your code only to address customer needs.

OwnerDisplayName: rikh

Title: How do you manage SQL Queries

Body:
At the moment my code (PHP) has too many SQL queries in it. eg...

// not a real example, but you get the idea...
$results = $db->GetResults("SELECT * FROM sometable WHERE iUser=$userid");
if ($results) {
    // Do something
}

I am looking into using stored procedures to reduce this and make things a little more robust, but I have some concerns..

I have hundreds of different queries in use around the web site, and many of them are quite similar. How should I manage all these queries when they are removed from their context (the code that uses the results) and placed in a stored procedure on the database?

OwnerDisplayName: Andomar


问:
ASP.NET MVC: Custom parameters to login page after authorization
I would like to redirect visitors to a login page with added parameters (based on the action they are performing) after the authorization fails.

This is an example of what I would like to do:

ASP.NET MVC - CustomeAuthorize filter action using an external website for loggin in the user

However, since this is a custom filter, I do not know how or if I can specify the Roles like in the usual authorization filter. I would like something like:

```<code>[CustomAuthorization(Roles="Admins")]
</code>```

Thank you!

答: What about using just Request.Form in your custom Authorization class. It is just a POST call after all? Don't make it harder than it actually is. </p>

Body:
I would like to redirect visitors to a login page with added parameters (based on the action they are performing) after the authorization fails.

This is an example of what I would like to do:

ASP.NET MVC - CustomeAuthorize filter action using an external website for loggin in the user

However, since this is a custom filter, I do not know how or if I can specify the Roles like in the usual authorization filter. I would like something like:

[CustomAuthorization(Roles="Admins")]

Thank you!


问:
File.listFiles will only list files with dot extension
The typical file lists just fine.

myfile.txt

returns as expected.

myfile

without an extension does not return a file object.

Windows 7, Java JDK6 - Updating is not an option :(

Interestingly extensionless files do not show up as directories either.

```<code>File dir = new File("c:/somedirectory/");
File[] returnFiles = dir.listFiles();
</code>```

Added code as requested.  Expect 2 files in array and get one.

答:
I took the reference of the Java 6 documentation (https://docs.oracle.com/javase/6/docs/api/java/io/File.html). There aren't many changes for the class File from java 6 to java 8.

So I have executed a small sample of code with Java 7 and Java 8 on Unix.

```<code>    File dir = new File("/Users/somedirectory");
    File[] returnFiles = dir.listFiles();
    String[] files = dir.list();

    for(File f:returnFiles ){
        System.out.println(f.getName());
    }

    for(String f:files ){
        System.out.println(f);
    }
</code>```

My observation is that the first loop returned all the files including the hidden files along with both normal files and extensionless files. While the second one returned labels/names of all files and directories.

So I assume that the extensionless file may have been considered as directory instead of as file for some reason.

Body:
The typical file lists just fine.

myfile.txt

returns as expected.

myfile

without an extension does not return a file object.

Windows 7, Java JDK6 - Updating is not an option :(

Interestingly extensionless files do not show up as directories either.

File dir = new File("c:/somedirectory/");
File[] returnFiles = dir.listFiles();

Added code as requested.  Expect 2 files in array and get one.

Body:
I took the reference of the Java 6 documentation (https://docs.oracle.com/javase/6/docs/api/java/io/File.html). There aren't many changes for the class File from java 6 to java 8.

So I have executed a small sample of code with Java 7 and Java 8 on Unix.

    File dir = new File("/Users/somedirectory");
    File[] returnFiles = dir.listFiles();
    String[] files = dir.list();

    for(File f:returnFiles ){
        System.out.println(f.getName());
    }

    for(String f:files ){
        System.out.println(f);
    }

My observation is that the first loop returned all the files including the hidden files along with both normal files and extensionless files. While the second one returned labels/names of all files and directories.

So I assume that the extensionless file may have been considered as directory instead of as file for some reason.


问:
SimpleDateFormat converting UTC to timezone incorrectly
I have a problem when converting the following ISO string 2017-09-01T01:00:00.000Z into a date.

I'm using SimpleDateFormat as follows

```<code>SimpleDateFormat stringToDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = stringToDate.parse("2017-09-01T01:00:00.000Z");
</code>```

The date object output has a date that looks like this

```<code>Fri Sep 01 01:00:00 MDT 2017
</code>```

When I should get an output of

```<code>Fri Sep 01 01:00:00 UTC 2017
</code>```

OR

```<code>Fri Aug 31 19:00:00 MDT 2017
</code>```

It looks like it is not doing the timezone conversion correctly because the time is unchanged, but the timezone has been when neither or both should be changed.

答:
You could also try this function call to create Calendar instance, it should support yyyy-MM-dd'T'HH:mm:ss.SSSZ format.

Calendar cal = javax.xml.bind.DatatypeConverter.parseDateTime(ymd);

edit: hmm you said Android ok this class may not be available.

Body:
I have a problem when converting the following ISO string 2017-09-01T01:00:00.000Z into a date.

I'm using SimpleDateFormat as follows

SimpleDateFormat stringToDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = stringToDate.parse("2017-09-01T01:00:00.000Z");

The date object output has a date that looks like this

Fri Sep 01 01:00:00 MDT 2017

When I should get an output of

Fri Sep 01 01:00:00 UTC 2017

OR

Fri Aug 31 19:00:00 MDT 2017

It looks like it is not doing the timezone conversion correctly because the time is unchanged, but the timezone has been when neither or both should be changed.


问:
Pass arguments to PhantomJS script through PHP exec?
There was already a question similar to this, however it didn't quite answer the question.

So my question is, if I have a PhantomJS script which is executed via exec in PHP, could I also pass some arguments to it which the PhantomJS script could then somehow get and use? If so, how would I pass them from the PHP and how would I use them in the PhantomJS script? If not, is there any other way of doing this? Thanks.

答:
Run the following in PHP:

```<code>$response = exec('/path/to/phantomjs myscript.js arg1 arg2');
</code>```

Then read the arguments from system.args (as documented in http://phantomjs.org/api/system/property/args.html)

```<code>var system = require('system');
var args = system.args;

args.forEach(function(arg, i) {
  console.log(i + ': ' + arg);
});
</code>```

Body:
Run the following in PHP:

$response = exec('/path/to/phantomjs myscript.js arg1 arg2');

Then read the arguments from system.args (as documented in http://phantomjs.org/api/system/property/args.html)

var system = require('system');
var args = system.args;

args.forEach(function(arg, i) {
  console.log(i + ': ' + arg);
});


问:
bootstrapping for lmer with interaction term
I am running a mixed model using lme4 in R:

```<code>full_mod3=lmer(logcptplus1 ~ logdepth*logcobb + (1|fyear) + (1 |flocation),
data=cpt, REML=TRUE)
</code>```

summary:

```<code>Formula: logcptplus1 ~ logdepth * logcobb + (1 | fyear) + (1 | flocation)
   Data: cpt

REML criterion at convergence: 577.5

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.7797 -0.5431  0.0248  0.6562  2.1733

 Random effects:
 Groups    Name        Variance Std.Dev.
 fyear     (Intercept) 0.2254   0.4748
 flocation (Intercept) 0.1557   0.3946
 Residual              0.9663   0.9830
Number of obs: 193, groups:  fyear, 16; flocation, 16

Fixed effects:
                  Estimate Std. Error t value
(Intercept)        4.3949     1.2319   3.568
logdepth           0.2681     0.4293   0.625
logcobb           -0.7189     0.5955  -1.207
logdepth:logcobb   0.3791     0.2071   1.831
</code>```

I have used the effects package and function in R to calculate the 95% confidence intervals for the model output. I have calculated and extracted the 95% CI and standard error using the effects package so that I can examine the relationship between the predictor variable of importance and the response variable by holding the secondary predictor variable (logdepth) constant at the median (2.5) in the data set:

```<code>gm=4.3949 + 0.2681*depth_median + -0.7189*logcobb_range + 0.3791*
(depth_median*logcobb_range)

ef2=effect("logdepth*logcobb",full_mod3,
     xlevels=list(logcobb=seq(log(0.03268),log(0.37980),,200)))
</code>```

I have attempted to bootstrap the 95% CIs using code from here. However, I need to calculate the 95% CIs for only the median depth (2.5). Is there a way to specify in the confint() code so that I can calculate the CIs needed to visualize the bootstrapped results as in the plot above?

```<code>confint(full_mod3,method="boot",nsim=200,boot.type="perc")
</code>```

答:
You can do this by specifying a custom function:

```<code>library(lme4)
?confint.merMod
</code>```

FUN: bootstrap function; if ‘NULL’, an internal function that returns the fixed-effect parameters as well as the random-effect parameters on the standard deviation/correlation scale will be used. See ‘bootMer’ for details.

So FUN can be a prediction function (?predict.merMod) that uses a newdata argument that varies and fixes appropriate predictor variables.

An example with built-in data (not quite as interesting as yours since there's a single continuous predictor variable, but I think it should illustrate the approach clearly enough):

```<code>fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
pframe <- data.frame(Days=seq(0,20,by=0.5))
## predicted values at population level (re.form=NA)
pfun <- function(fit) {
    predict(fit,newdata=pframe,re.form=NA)
}
set.seed(101)
cc <- confint(fm1,method="boot",FUN=pfun)
</code>```

Picture:

```<code>par(las=1,bty="l")
matplot(pframe$Days,cc,lty=2,col=1,type="l",
     xlab="Days",ylab="Reaction")
</code>```

Body:
I am running a mixed model using lme4 in R:

full_mod3=lmer(logcptplus1 ~ logdepth*logcobb + (1|fyear) + (1 |flocation),
data=cpt, REML=TRUE)

summary:

Formula: logcptplus1 ~ logdepth * logcobb + (1 | fyear) + (1 | flocation)
   Data: cpt

REML criterion at convergence: 577.5

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.7797 -0.5431  0.0248  0.6562  2.1733

 Random effects:
 Groups    Name        Variance Std.Dev.
 fyear     (Intercept) 0.2254   0.4748
 flocation (Intercept) 0.1557   0.3946
 Residual              0.9663   0.9830
Number of obs: 193, groups:  fyear, 16; flocation, 16

Fixed effects:
                  Estimate Std. Error t value
(Intercept)        4.3949     1.2319   3.568
logdepth           0.2681     0.4293   0.625
logcobb           -0.7189     0.5955  -1.207
logdepth:logcobb   0.3791     0.2071   1.831

I have used the effects package and function in R to calculate the 95% confidence intervals for the model output. I have calculated and extracted the 95% CI and standard error using the effects package so that I can examine the relationship between the predictor variable of importance and the response variable by holding the secondary predictor variable (logdepth) constant at the median (2.5) in the data set:

gm=4.3949 + 0.2681*depth_median + -0.7189*logcobb_range + 0.3791*
(depth_median*logcobb_range)

ef2=effect("logdepth*logcobb",full_mod3,
     xlevels=list(logcobb=seq(log(0.03268),log(0.37980),,200)))

I have attempted to bootstrap the 95% CIs using code from here. However, I need to calculate the 95% CIs for only the median depth (2.5). Is there a way to specify in the confint() code so that I can calculate the CIs needed to visualize the bootstrapped results as in the plot above?

confint(full_mod3,method="boot",nsim=200,boot.type="perc")

Body:
You can do this by specifying a custom function:

library(lme4)
?confint.merMod

FUN: bootstrap function; if ‘NULL’, an internal function that returns the fixed-effect parameters as well as the random-effect parameters on the standard deviation/correlation scale will be used. See ‘bootMer’ for details.

So FUN can be a prediction function (?predict.merMod) that uses a newdata argument that varies and fixes appropriate predictor variables.

An example with built-in data (not quite as interesting as yours since there's a single continuous predictor variable, but I think it should illustrate the approach clearly enough):

fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
pframe <- data.frame(Days=seq(0,20,by=0.5))
## predicted values at population level (re.form=NA)
pfun <- function(fit) {
    predict(fit,newdata=pframe,re.form=NA)
}
set.seed(101)
cc <- confint(fm1,method="boot",FUN=pfun)

Picture:

par(las=1,bty="l")
matplot(pframe$Days,cc,lty=2,col=1,type="l",
     xlab="Days",ylab="Reaction")


问:
php dropdown show selected but one value by defaut
i'm using php for stored procedure on sql server. My problems is that i would like to show one value by defaut on the dropdown, but when someone select something else and the page refresh, it must show the what that person choose, not the default one. Here what i had done until now :

```<code><form method="post">
            <label for="from"><b>De:</b></label>
            <input  data-date-format='yy-mm-dd' type="text" id="from" name="from" size="6" value="<?php if(isset($_POST['from'])){ echo $_POST['from']; } ?>";/>
            <label for="to"><b>A:</b></label>
            <input data-date-format='yyyy-mm-dd' type="text" id="to" name="to" size="6" value="<?php if(isset($_POST['to'])){ echo $_POST['to']; } ?>";/>
            <label for="group"><b>Groupe:</b></label>
            <select type= "text" name="group" id="group" value="";>
            <option><?php if(isset($_POST['group'])){ echo $_POST['group']; } ?></option>
<?php
$sql = " Get_List_ReportStation";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
?>
<option selected value="RAL"><?php echo ($row['F1000'] . " " . $row['F1018']); ?></option>
<?php
}
?>
</select>
<input type="submit" value="Valider" name="submit">
</form>
<?php
if(isset($_POST["submit"])) {
$from = $_POST["from"];
$to = $_POST["to"];
$group = $_POST["group"];
}
?>
</code>```

Any ideas to help me? Thank you!

答:
```<code><select class="group">
    <option value="test1">test1</option>
    <option value="test2">test2</option>
    <option value="test3">test3</option>
    <option value="test4">test4</option>
</select>
</code>```

Add Javascript to store the users last value into localstorage.

```<code>var select = document.querySelector(".group");
var selectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');

if(lastSelected) {
    select.value = lastSelected;
}

// sets up a onselected
select.onchange = function () {
   lastSelected = select.options[select.selectedIndex].value;
   console.log(lastSelected);
   localStorage.setItem('select', lastSelected);
}
</code>```

Source: How to use LocalStorage on last HTML select value

For your given code try this

```<code><form method="post">
            <label for="from"><b>De:</b></label>
            <input  data-date-format='yy-mm-dd' type="text" id="from" name="from" size="6" value="<?php if(isset($_POST['from'])){ echo $_POST['from']; } ?>";/>
            <label for="to"><b>A:</b></label>
            <input data-date-format='yyyy-mm-dd' type="text" id="to" name="to" size="6" value="<?php if(isset($_POST['to'])){ echo $_POST['to']; } ?>";/>
            <label for="group"><b>Groupe:</b></label>
            <select type= "text" name="group" id="group">
            <option><?php if(isset($_POST['group'])){ echo $_POST['group']; } ?></option>
<?php
$sql = " Get_List_ReportStation";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
?>
<option value="<?php echo ($row['F1000']."_".$row['F1018']); ?>"><?php echo ($row['F1000'] . " " . $row['F1018']); ?></option>
<?php
}
?>
</select>
<input type="submit" value="Valider" name="submit">
</form>
<script>
var select = document.querySelector(".group");
var selectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');

if(lastSelected) {
    select.value = lastSelected;
} else {
    select.value = 'RAL'; // new code
}

// sets up a onselected
select.onchange = function () {
   lastSelected = select.options[select.selectedIndex].value;
   console.log(lastSelected);
   localStorage.setItem('select', lastSelected);
}
</script>
<?php
if(isset($_POST["submit"])) {
$from = $_POST["from"];
$to = $_POST["to"];
$group = $_POST["group"];
}
?>
</code>```

Body:
i'm using php for stored procedure on sql server. My problems is that i would like to show one value by defaut on the dropdown, but when someone select something else and the page refresh, it must show the what that person choose, not the default one. Here what i had done until now :

<form method="post">
            De:
            <input  data-date-format='yy-mm-dd' type="text" id="from" name="from" size="6" value="<?php if(isset($_POST['from'])){ echo $_POST['from']; } ?>";/>
            A:
            <input data-date-format='yyyy-mm-dd' type="text" id="to" name="to" size="6" value="<?php if(isset($_POST['to'])){ echo $_POST['to']; } ?>";/>
            Groupe:
            <select type= "text" name="group" id="group" value="";>
            <option><?php if(isset($_POST['group'])){ echo $_POST['group']; } ?></option>
<?php
$sql = " Get_List_ReportStation";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
?>
<option selected value="RAL"><?php echo ($row['F1000'] . " " . $row['F1018']); ?></option>
<?php
}
?>
</select>
<input type="submit" value="Valider" name="submit">
</form>
<?php
if(isset($_POST["submit"])) {
$from = $_POST["from"];
$to = $_POST["to"];
$group = $_POST["group"];
}
?>

Any ideas to help me? Thank you!

Body:
<select class="group">
    <option value="test1">test1</option>
    <option value="test2">test2</option>
    <option value="test3">test3</option>
    <option value="test4">test4</option>
</select>

Add Javascript to store the users last value into localstorage.

var select = document.querySelector(".group");
var selectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');

if(lastSelected) {
    select.value = lastSelected;
}

// sets up a onselected
select.onchange = function () {
   lastSelected = select.options[select.selectedIndex].value;
   console.log(lastSelected);
   localStorage.setItem('select', lastSelected);
}

Source: How to use LocalStorage on last HTML select value

For your given code try this

<form method="post">
            <label for="from"><b>De:</b></label>
            <input  data-date-format='yy-mm-dd' type="text" id="from" name="from" size="6" value="<?php if(isset($_POST['from'])){ echo $_POST['from']; } ?>";/>
            <label for="to"><b>A:</b></label>
            <input data-date-format='yyyy-mm-dd' type="text" id="to" name="to" size="6" value="<?php if(isset($_POST['to'])){ echo $_POST['to']; } ?>";/>
            <label for="group"><b>Groupe:</b></label>
            <select type= "text" name="group" id="group">
            <option><?php if(isset($_POST['group'])){ echo $_POST['group']; } ?></option>
<?php
$sql = " Get_List_ReportStation";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
?>
<option value="<?php echo ($row['F1000']."_".$row['F1018']); ?>"><?php echo ($row['F1000'] . " " . $row['F1018']); ?></option>
<?php
}
?>
</select>
<input type="submit" value="Valider" name="submit">
</form>
<script>
var select = document.querySelector(".group");
var selectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');

if(lastSelected) {
    select.value = lastSelected;
} else {
    select.value = 'RAL'; // new code
}

// sets up a onselected
select.onchange = function () {
   lastSelected = select.options[select.selectedIndex].value;
   console.log(lastSelected);
   localStorage.setItem('select', lastSelected);
}
</script>
<?php
if(isset($_POST["submit"])) {
$from = $_POST["from"];
$to = $_POST["to"];
$group = $_POST["group"];
}
?>


问:
Keeping Apple Watch Awake for more than 70 seconds (watchOS 3)
Is there any way to keep an Apple Watch awake for more than 70 seconds? I understand the purpose of turning off the face to save battery life but I'm trying to sample motion data continuously for about 3 minutes and the sampling is interrupted as soon as the face turns off. I've set the watch to stay awake for 70 seconds every time I tap it, but is there any way to prevent it from turning off for > 3 minutes? I found this post from Feb. of 2016 but haven't found any updates confirming or denying the possibility of preventing the watch face from sleeping in watchOS 3.</p>

答: If you're looking at sampling motion data like the accelerometer or gyroscope, you can create a HKWorkout Session that will keep your app running in the background. While your Watch face will still eventually turn off without tapping, you will still continue to be able to keep sampling your motion data. Note that only one HKWorkout Session can be run at a time. Hope this helps!</p>


问:
Very simple parallax code has performance issues
For a parallax-effect, I created a simple script in native Javascript, but it seems to fail somewhere I can't see. That's why I already added the requestAnimationFrame-functionality, but it doesn't seem to really help.

My relevant code is as follows:

```<code>var $parallax, vh;
$(document).ready(function() {
    $parallax = $('.parallax');
    vh = $(window).height();

    $parallax.parallaxInit();
});

$(window).resize(function() {
    vh = $(window).height();

    $parallax.parallaxInit();
});

$.fn.parallaxInit = function() {
    var _ = this;
    _.find('.parallax-bg')
        .css('height', vh + (vh * .8) );

}

//call function on scroll
$(window).scroll(function() {
    window.requestAnimationFrame(parallax);
});

var parallaxElements = document.getElementsByClassName('parallax'),
    parallaxLength = parallaxElements.length;

var el, scrollTop, elOffset, i;

function parallax(){

    for( i = 0; i < parallaxLength; i++ ) {

        el = parallaxElements[i];
        elOffset = el.getBoundingClientRect().top;

        // only change if the element is in viewport - save resources
        if( elOffset < vh && elOffset + el.offsetHeight > 0) {

            el.getElementsByClassName('parallax-bg')[0].style.top = -(elOffset * .8) + 'px';

        }

    }

}
</code>```

I think it's weird that this script by Hendry Sadrak runs better than my script (on my phone) while that is not really optimised, as far as I can tell.

Update: I checked if getBoundingClientRect might be slower in some freak of Javascript, but it's about 78% faster: https://jsperf.com/parallax-test

答:
I fixed it! I used transform: translate3d instead, which works with the GPU instead of the CPU. Which makes it much smoother, even on mobile.

http://codepen.io/AartdenBraber/pen/WpaxZg?editors=0010

Body:
For a parallax-effect, I created a simple script in native Javascript, but it seems to fail somewhere I can't see. That's why I already added the requestAnimationFrame-functionality, but it doesn't seem to really help.

My relevant code is as follows:

var $parallax, vh;
$(document).ready(function() {
    $parallax = $('.parallax');
    vh = $(window).height();

    $parallax.parallaxInit();
});

$(window).resize(function() {
    vh = $(window).height();

    $parallax.parallaxInit();
});

$.fn.parallaxInit = function() {
    var _ = this;
    _.find('.parallax-bg')
        .css('height', vh + (vh * .8) );

}

//call function on scroll
$(window).scroll(function() {
    window.requestAnimationFrame(parallax);
});

var parallaxElements = document.getElementsByClassName('parallax'),
    parallaxLength = parallaxElements.length;

var el, scrollTop, elOffset, i;

function parallax(){

    for( i = 0; i < parallaxLength; i++ ) {

        el = parallaxElements[i];
        elOffset = el.getBoundingClientRect().top;

        // only change if the element is in viewport - save resources
        if( elOffset < vh && elOffset + el.offsetHeight > 0) {

            el.getElementsByClassName('parallax-bg')[0].style.top = -(elOffset * .8) + 'px';

        }

    }

}

I think it's weird that this script by Hendry Sadrak runs better than my script (on my phone) while that is not really optimised, as far as I can tell.

Update: I checked if getBoundingClientRect might be slower in some freak of Javascript, but it's about 78% faster: https://jsperf.com/parallax-test


问:
How to update global variables inside class method in Python?
```<code>class Example(tk.Frame):
    def __init__(self, parent):
        global p
        p = 1.1
        ....

    def looper(self):
        if self.keys['Prior']:
            p = p -.01
            self.draw()
</code>```

This code comes back with UnboundLocalError: local variable 'p' referenced before assignment

I tried putting global p/p=1.1 down in the main routine outside of the Class and I got the same exact error.  Somewhere I must be misunderstanding things.  I thought global meant through the whole program...which is the way I want it...set it once and let it go throughout the program.  What am I doing wrong?

答:
You can define p before class definition (not advised), if you are pointing it from a method:

```<code>p = None

class Example(tk.Frame):
    def __init__(self, parent):
        global p
        p = 1.1

    def looper(self):
        global p
        if ...

# modifying the global
p = 5
</code>```

However, beware that every instance will modify it which doesn't make sense until you are having a singleton pattern or other purpose. Instead you should have p as instance variable:

```<code>class Example(tk.Frame):
    def __init__(self, parent):
        self.p = 1.1

    def looper(self):
        if self.keys['Prior']:
            self.p = self.p -.01
            self.draw()

# modifying the instance
my_instance = Example(..)
my_instance.p = 5
</code>```

Body:
class Example(tk.Frame):
    def __init__(self, parent):
        global p
        p = 1.1
        ....

    def looper(self):
        if self.keys['Prior']:
            p = p -.01
            self.draw()

This code comes back with UnboundLocalError: local variable 'p' referenced before assignment

I tried putting global p/p=1.1 down in the main routine outside of the Class and I got the same exact error.  Somewhere I must be misunderstanding things.  I thought global meant through the whole program...which is the way I want it...set it once and let it go throughout the program.  What am I doing wrong?

Body:
You can define p before class definition (not advised), if you are pointing it from a method:

p = None

class Example(tk.Frame):
    def __init__(self, parent):
        global p
        p = 1.1

    def looper(self):
        global p
        if ...

# modifying the global
p = 5

However, beware that every instance will modify it which doesn't make sense until you are having a singleton pattern or other purpose. Instead you should have p as instance variable:

class Example(tk.Frame):
    def __init__(self, parent):
        self.p = 1.1

    def looper(self):
        if self.keys['Prior']:
            self.p = self.p -.01
            self.draw()

# modifying the instance
my_instance = Example(..)
my_instance.p = 5


答:
What you're looking for is SUM rather than COUNT, that is,

```<code>SELECT
mdl_course.id,
mdl_course.shortname,
SUM(CASE WHEN usersbycourse.modulesfinished = 0 THEN 1 ELSE 0 END) AS studentcount
FROM mdl_course LEFT JOIN usersbycourse ON mdl_course.id = usersbycourse.instanceid
GROUP BY mdl_course.id;
</code>```

Title: COUNT counting something on LEFT JOIN that doesn't exist. Why?

Body:
I'm having a problem.

I have this table called usersbycourse which shows this information:

+------------+-----------------+--------+-----------+-------+-----------------+-----------------+
| instanceid | shortname       | userid | firstname | logid | lastaccessdelta | modulesfinished |
+------------+-----------------+--------+-----------+-------+-----------------+-----------------+
|          2 | PJU             |     74 | Robin     |   766 |         1662246 |               0 |
|          3 | Fundgest-GRHN1A |     75 | Batman    |   867 |         1576725 |               0 |
|          3 | Fundgest-GRHN1A |     77 | Abigobeu  |  1004 |          610480 |               0 |
+------------+-----------------+--------+-----------+-------+-----------------+-----------------+

and this SQL:

SELECT
mdl_course.id,
mdl_course.shortname,
COUNT(CASE WHEN usersbycourse.modulesfinished = 1 THEN NULL ELSE 1 END) AS studentcount
FROM mdl_course LEFT JOIN usersbycourse ON mdl_course.id = usersbycourse.instanceid
GROUP BY mdl_course.id;

The results from the SQL are:

+----+-----------------+--------------+
| id | shortname       | studentcount |
+----+-----------------+--------------+
|  1 | Unity I         |            1 |
|  2 | PJU             |            1 |
|  3 | Fundgest-GRHN1A |            2 |
|  4 | asdzxc2         |            1 |
+----+-----------------+--------------+

But why? In inside SQL has no Unity I, and no asdzxc2. How do I produce a result like this:

+----+-----------------+--------------+
| id | shortname       | studentcount |
+----+-----------------+--------------+
|  1 | Unity I         |            0 |
|  2 | PJU             |            1 |
|  3 | Fundgest-GRHN1A |            2 |
|  4 | asdzxc2         |            0 |
+----+-----------------+--------------+

?

EDIT:

I want to count only rows having modulesfinished = 0

Body:
What you're looking for is SUM rather than COUNT, that is,

SELECT
mdl_course.id,
mdl_course.shortname,
SUM(CASE WHEN usersbycourse.modulesfinished = 0 THEN 1 ELSE 0 END) AS studentcount
FROM mdl_course LEFT JOIN usersbycourse ON mdl_course.id = usersbycourse.instanceid
GROUP BY mdl_course.id;


问:
Swift for var list.enumerated()
I have an array of objects whose type is a struct with mutating functions. So I got this code:

```<code>for (index, object) in objects.enumerated() {
     otherArray[index] = object.someMutatingFunction(...)
}
</code>```

This leads me to this error Cannot use mutating member on immutable value of type 'Blabla' which I can fix by adding var:

```<code>for var (index, object) in objects.enumerated() {
     otherArray[index] = object.someMutatingFunction(...)
}
</code>```

But then I get another warning Variable 'index' was never mutated; consider changing to 'let' constant which I don't know how to fix elegantly. The only idea is too add a new var variable. Is there anything else I can do to prevent this warning?

答:
Prefix the object variable with the var keyword:

```<code>struct S {
    mutating func f() { }
}

let array = [S(), S()]

for (index, var object) in array.enumerated() {
    object.f()
}
</code>```

Note as Hamish points out in the comment to this answer that the elements of the array will not be modified.  Only the local copy of object inside the scope of the for loop can be modified.

If you want to modify array you have to declare it var outside the scope of the for loop, then assign to array indices.

Title: Swift for var list.enumerated()

Body:
I have an array of objects whose type is a struct with mutating functions. So I got this code:

for (index, object) in objects.enumerated() {
     otherArray[index] = object.someMutatingFunction(...)
}

This leads me to this error Cannot use mutating member on immutable value of type 'Blabla' which I can fix by adding var:

for var (index, object) in objects.enumerated() {
     otherArray[index] = object.someMutatingFunction(...)
}

But then I get another warning Variable 'index' was never mutated; consider changing to 'let' constant which I don't know how to fix elegantly. The only idea is too add a new var variable. Is there anything else I can do to prevent this warning?

Body:
Prefix the object variable with the var keyword:

struct S {
    mutating func f() { }
}

let array = [S(), S()]

for (index, var object) in array.enumerated() {
    object.f()
}

Note as Hamish points out in the comment to this answer that the elements of the array will not be modified.  Only the local copy of object inside the scope of the for loop can be modified.

If you want to modify array you have to declare it var outside the scope of the for loop, then assign to array indices.


问:
C++ non-blocking reading
All I need to do is just to read all available bytes from socket. But there is one condition: there is a method which reads n bytes from non-blocking socket which I have to use for implementation of another method which is going to read all available bytes.

Non-blocking reading of some data with defined size:

```<code>ssize_t read(void* buf, size_t len)
{
    ssize_t bytesRead = 0;
    ssize_t bytesTotallyRead = 0;
    size_t bytesLeftToRead = len;
    while (bytesTotallyRead < len)
    {
        bytesRead = ::recv(handle, (char*)buf+bytesTotallyRead, bytesLeftToRead, 0);
        if (bytesRead > 0)
        {
            bytesTotallyRead += bytesRead;
            bytesLeftToRead -= bytesRead;
        }
        else if (bytesRead == 0)
        {
            break;
        }
        else if (bytesRead < 0)
        {
            if (errno == EINTR)
            {
                continue;
            }
            else if (errno == EWOULDBLOCK)
            {
                int selectStatus(waitForIncomingData(500));
                if (selectStatus > 0)
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
    }
    return (bytesRead==-1)?-1:bytesTotallyRead;
}
</code>```

So I have to use this method to implement something like ssize_t readAllAvailable(std::vector<uint8_t> &data) which uses method above for it's implementation.

The problem here, as you see, that read() uses select() for waiting for incoming data so using of buffer of fixed size (in loop) might lead to 500 ms (in this concrete case) waiting after 1st iteration and this is definitely not the way it should be done.

Is it possible at all? I mean some efficient ways.

答:
there is a method which reads n bytes from socket asynchronously

No there isn't. There is a method which uses non-blocking mode and select() to reimplement blocking mode. There is nothing 'asynchronous' about it whatsoever. From the point of view of the caller it is blocking-mode. It is poorly, indeed incorrectly, conceived, and should be thrown away. The code you have posted is completely and utterly pointless. It's just a complicated way of implementing a blocking read loop. Use blocking mode. In effect, you already are, but with more system calls. And lose the select() call and EAGAIN/EWOUDLBLOCK stuff.

which I have to use for implementation of another method which is going to read all available bytes.
  ...
  The problem here, as you see, that read() uses select() for waiting for incoming data so using of buffer of fixed size (in loop) might lead to 500 ms (in this concrete case) waiting after 1st iteration

No it isn't. select() will return immediately data becomes available on the socket. No 500ms unless there is no data. And 'using a buffer of fixed size' has exactly nothing to do with it.

and this is definitely not the way it should be done.

It isn't the way it is done.

There is no problem here to solve.

Title: C++ non-blocking reading

Body:
All I need to do is just to read all available bytes from socket. But there is one condition: there is a method which reads n bytes from non-blocking socket which I have to use for implementation of another method which is going to read all available bytes.

Non-blocking reading of some data with defined size:

ssize_t read(void* buf, size_t len)
{
    ssize_t bytesRead = 0;
    ssize_t bytesTotallyRead = 0;
    size_t bytesLeftToRead = len;
    while (bytesTotallyRead < len)
    {
        bytesRead = ::recv(handle, (char*)buf+bytesTotallyRead, bytesLeftToRead, 0);
        if (bytesRead > 0)
        {
            bytesTotallyRead += bytesRead;
            bytesLeftToRead -= bytesRead;
        }
        else if (bytesRead == 0)
        {
            break;
        }
        else if (bytesRead < 0)
        {
            if (errno == EINTR)
            {
                continue;
            }
            else if (errno == EWOULDBLOCK)
            {
                int selectStatus(waitForIncomingData(500));
                if (selectStatus > 0)
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
    }
    return (bytesRead==-1)?-1:bytesTotallyRead;
}

So I have to use this method to implement something like ssize_t readAllAvailable(std::vector<uint8_t> &data) which uses method above for it's implementation.

The problem here, as you see, that read() uses select() for waiting for incoming data so using of buffer of fixed size (in loop) might lead to 500 ms (in this concrete case) waiting after 1st iteration and this is definitely not the way it should be done.

Is it possible at all? I mean some efficient ways.


问:
Leading zeros for Int in Swift
I'd like to convert an Int in Swift to a String with leading zeros. For example consider this code:

```<code>for myInt in 1 ... 3 {
    print("\(myInt)")
}
</code>```

Currently the result of it is:

```<code>1
2
3
</code>```

But I want it to be:

```<code>01
02
03
</code>```

Is there a clean way of doing this within the Swift standard libraries?

答:
Swift 3.0+

Left padding String extension similar to padding(toLength:withPad:startingAt:) in Foundation

```<code>extension String {
    func leftPadding(toLength: Int, withPad: String = " ") -> String {

        guard toLength > self.characters.count else { return self }

        let padding = String(repeating: withPad, count: toLength - self.characters.count)
        return padding + self
    }
}
</code>```

Usage:

```<code>let s = String(123)
s.leftPadding(toLength: 8, withPad: "0") // "00000123"
</code>```

Title: Leading zeros for Int in Swift

Body:
I'd like to convert an Int in Swift to a String with leading zeros. For example consider this code:

for myInt in 1 ... 3 {
    print("\(myInt)")
}

Currently the result of it is:

1
2
3

But I want it to be:

01
02
03

Is there a clean way of doing this within the Swift standard libraries?

Body:
Swift 3.0+

Left padding String extension similar to padding(toLength:withPad:startingAt:) in Foundation

extension String {
    func leftPadding(toLength: Int, withPad: String = " ") -> String {

        guard toLength > self.characters.count else { return self }

        let padding = String(repeating: withPad, count: toLength - self.characters.count)
        return padding + self
    }
}

Usage:

let s = String(123)
s.leftPadding(toLength: 8, withPad: "0") // "00000123"


问:
Vlookup in Macro Loop Within a Table
I am trying to calculate a VLookup "off sheet" (I do not want to place a formula into the cells then copy and paste as values - rather I want to do the calculation then have the result placed into the cells as a value)

I have a table which I add data to each month. I only want to calculate the VLookup for the new rows (blanks).  The VLookup result should go in Column A of the table titled "Regionals". The table array is a table called "Orgs" which is on a different worksheet called "PAS".  The below formula retrieve the result I am looking for if I put it directly onto the worksheet (in this example the "blank" was in cell A174560).

The main table where the VLookup occurs is titled "Table6"

Main table is on a worksheet titled "TAB"

Column B (value to lookup) is titled "County Codes" on the table

=VLOOKUP(B174560,Orgs[[#All],[County]:[Regional]],4,FALSE)

The code I have now:

```<code>Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For Each cell In Range("Table6[Regionals]").SpecialCells(xlCellTypeBlanks)
    cell.Value = [Application.WorksheetFunction.VLookup(cells(CELL.row,Worksheets("TAB").Range("Table6[County Codes]").column)),Worksheets("PAS").Range("Orgs[#All]),[County]:[Regional]"),4,false)]
Next
</code>```

The code runs without error, but places a #VALUE error in the blank cell.

I am guessing the issue lies in the syntax of using table names and columns names within the tables or from my attempt to use the cells format within the vlookup.

答:
Try:</p>

```<code>Dim addr, col As Long

With Worksheets("TAB")

   col = .Range("Table6[County Codes]").column

   For Each cell In  .Range("Table6[Regionals]").SpecialCells(xlCellTypeBlanks).Cells

        addr = .Cells(cell.Row, col).Address()

        cell.value = .Evaluate("VLOOKUP(" & addr & _
                         ",Orgs[[#All],[County]:[Regional]],4,FALSE)")
    Next
End With
</code>```

Title: Vlookup in Macro Loop Within a Table

Body:
I am trying to calculate a VLookup "off sheet" (I do not want to place a formula into the cells then copy and paste as values - rather I want to do the calculation then have the result placed into the cells as a value)

I have a table which I add data to each month. I only want to calculate the VLookup for the new rows (blanks).  The VLookup result should go in Column A of the table titled "Regionals". The table array is a table called "Orgs" which is on a different worksheet called "PAS".  The below formula retrieve the result I am looking for if I put it directly onto the worksheet (in this example the "blank" was in cell A174560).

The main table where the VLookup occurs is titled "Table6"

Main table is on a worksheet titled "TAB"

Column B (value to lookup) is titled "County Codes" on the table

=VLOOKUP(B174560,Orgs[[#All],[County]:[Regional]],4,FALSE)

The code I have now:

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For Each cell In Range("Table6[Regionals]").SpecialCells(xlCellTypeBlanks)
    cell.Value = [Application.WorksheetFunction.VLookup(cells(CELL.row,Worksheets("TAB").Range("Table6[County Codes]").column)),Worksheets("PAS").Range("Orgs[#All]),[County]:[Regional]"),4,false)]
Next

The code runs without error, but places a #VALUE error in the blank cell.

I am guessing the issue lies in the syntax of using table names and columns names within the tables or from my attempt to use the cells format within the vlookup.

Body:
Try:

Dim addr, col As Long

With Worksheets("TAB")

   col = .Range("Table6[County Codes]").column

   For Each cell In  .Range("Table6[Regionals]").SpecialCells(xlCellTypeBlanks).Cells

        addr = .Cells(cell.Row, col).Address()

        cell.value = .Evaluate("VLOOKUP(" & addr & _
                         ",Orgs[[#All],[County]:[Regional]],4,FALSE)")
    Next
End With