问:
Initialize Page Objects - Arquillian - Selenium
I am new to Selenium and Arquillian framework. I am trying to implement Page Object Model. Webdriver browser capabilities are saved in arquillian xml file.

I am using TestNG and created the following classes:

```<code>public class Test{
  @Drone
  Webdriver driver;
  @Page
  Login login;
  @Page
  Home home;
  public void createOrderTest(){
    login.navigateURL();
    login.setcredentials();
    home.createOrder();
  }
}

public class Login{
  // Webelements needed in methods below are declared here
  public void navigateURL(){
     driver.get("//url/login.aspx");
  }
  public void setCredentials(){
     // code to enter username, password and click login
     Graphene.waitAjax().until().element(signIn).is().not().visible();
  }
}

public class Home{
  // Webelements needed in methods below are declared here
  public void createOrder(){
     // code to create order
  }
}
</code>```

Problem Statement:
I am not sure how to navigate between Login and Home pages in code.  Once user logs in using Login page methods, how does Webdriver get to use Home page methods to continue the test ?

Error:

Test runs fine with navigateURL and setcredentials methods. However, test fails to access createOrder method as follows:

```<code>WARNING: Argument 1 for UpdateTestResultBeforeAfter.update is null. It won't be invoked.
FAILED CONFIGURATION: @BeforeMethod arquillianBeforeTest(public void Test.createOrder() throws javax.mail.MessagingException,java.io.IOException,java.security.GeneralSecurityException)
org.jboss.arquillian.graphene.enricher.exception.PageObjectInitializationException: Can not instantiate Page Object class Home
</code>```

Please guide me. Thank you.

答:
Is the home page a static page? I assume you should not redirect the login page to home page. This should be done by the application itself. That is, end user will access the login page with url. after the all the navigations should be done by the application itself.</p>

```<code>@RunAsClient
public class Test extends Arquillian{

  @Drone
  Webdriver driver;

  @Page
  Login login;

  @Page
  Home home;

  public void createOrderTest(){
    login.navigateURL();
    login.setcredentials();

    //you do not need this
    //home = Graphene.goTo(Home.class)

    //use graphene fluent wait API to wait for the page load
    home.createOrder();
  }
}
</code>```

Body:
I am new to Selenium and Arquillian framework. I am trying to implement Page Object Model. Webdriver browser capabilities are saved in arquillian xml file.

I am using TestNG and created the following classes:

public class Test{
  @Drone
  Webdriver driver;
  @Page
  Login login;
  @Page
  Home home;
  public void createOrderTest(){
    login.navigateURL();
    login.setcredentials();
    home.createOrder();
  }
}

public class Login{
  // Webelements needed in methods below are declared here
  public void navigateURL(){
     driver.get("//url/login.aspx");
  }
  public void setCredentials(){
     // code to enter username, password and click login
     Graphene.waitAjax().until().element(signIn).is().not().visible();
  }
}

public class Home{
  // Webelements needed in methods below are declared here
  public void createOrder(){
     // code to create order
  }
}

Problem Statement:
I am not sure how to navigate between Login and Home pages in code.  Once user logs in using Login page methods, how does Webdriver get to use Home page methods to continue the test ?

Error:

Test runs fine with navigateURL and setcredentials methods. However, test fails to access createOrder method as follows:

WARNING: Argument 1 for UpdateTestResultBeforeAfter.update is null. It won't be invoked.
FAILED CONFIGURATION: @BeforeMethod arquillianBeforeTest(public void Test.createOrder() throws javax.mail.MessagingException,java.io.IOException,java.security.GeneralSecurityException)
org.jboss.arquillian.graphene.enricher.exception.PageObjectInitializationException: Can not instantiate Page Object class Home

Please guide me. Thank you.

Body:
Is the home page a static page? I assume you should not redirect the login page to home page. This should be done by the application itself. That is, end user will access the login page with url. after the all the navigations should be done by the application itself.

@RunAsClient
public class Test extends Arquillian{

  @Drone
  Webdriver driver;

  @Page
  Login login;

  @Page
  Home home;

  public void createOrderTest(){
    login.navigateURL();
    login.setcredentials();

    //you do not need this
    //home = Graphene.goTo(Home.class)

    //use graphene fluent wait API to wait for the page load
    home.createOrder();
  }
}


来源: stackexchange

问:
Java: do while string issue
I have an issue when I run this program, If I use int it works, but for string it does not.</p>

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

public class userinput_swutch_do_while {

    public static void main(String[] args) {

        String password= null;
        Scanner value = new Scanner(System.in);
        do {
            System.out.println("Enter the password for ATM: ");
            password = value.nextLine();
            System.out.println("You put : "+password);

        } while  (password !="55");

        System.out.println("You got it!");

    }

}
</code>```

答:
In JAVA, String equality is tested correctly using equals()or equalsIgnoreCase();

That being said, you can try this :

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

public class userinput_swutch_do_while {

public static void main(String[] args) {

    String password= null;
    Scanner value = new Scanner(System.in);
    do {
        System.out.println("Enter the password for ATM: ");
        password = value.nextLine();
        System.out.println("You put : "+password);

    } while(!(password.equals("55")));// string equality

    System.out.println("You got it!");

  }

 }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Java: do while string issue

Body:
I have an issue when I run this program, If I use int it works, but for string it does not.

import java.util.Scanner;

public class userinput_swutch_do_while {

    public static void main(String[] args) {

        String password= null;
        Scanner value = new Scanner(System.in);
        do {
            System.out.println("Enter the password for ATM: ");
            password = value.nextLine();
            System.out.println("You put : "+password);

        } while  (password !="55");

        System.out.println("You got it!");

    }

}

Body:
In JAVA, String equality is tested correctly using equals()or equalsIgnoreCase();

That being said, you can try this :

import java.util.Scanner;

public class userinput_swutch_do_while {

public static void main(String[] args) {

    String password= null;
    Scanner value = new Scanner(System.in);
    do {
        System.out.println("Enter the password for ATM: ");
        password = value.nextLine();
        System.out.println("You put : "+password);

    } while(!(password.equals("55")));// string equality

    System.out.println("You got it!");

  }

 }


问:
D3 disable pan & zoom when scrolling
I've rendered a d3 map that has pan and zoom enabled, but when scrolling down the viewport either on desktop or mobile, the window gets stuck zooming in the map.

Is there a way to temporarily disable d3.zoom, while the window is scrolling?

I've seen ways of toggling the zoom/pan using a button as seen here: http://jsfiddle.net/0xncswrk/, but I wanted to know if it's possible without having to add a button.  Here's my current zoom logic.

Thanks!

```<code>this.zoom = d3.zoom()
  .scaleExtent([1, 8])
  .on('zoom', () => {
    this.svg.attr('transform', d3.event.transform);
  });

this.svg = d3.select(this.el).append('svg')
    .attr('width', '100%')
    .attr('height', this.height)
    .attr('class', 'bubble-map__svg-us')
    .call(this.zoom)
    .append('g');
</code>```

答:
EDIT: Wow old answer but never saw your comment. Sorry about that. Yeah sorry I forgot to consider mobile zooming.

In the documentation, perhaps this is new, but they recommend having more granular control of what zoom you allow by using zoom.filter. For touch related events, they also support zoom.touchable.

As specified in the d3-zoom documentation

To disable just wheel-driven zooming (say to not interfere with native scrolling), you can remove the zoom behavior’s wheel event listener after applying the zoom behavior to the selection:

selection
      .call(zoom)
      .on("wheel.zoom", null);

You can also consider just setting the scaleExtent to be [1,1] especially if it's just temporary so it locks the zoom to only one possible scale but preferably you opt for what the documentation says :P

Title: D3 disable pan & zoom when scrolling

Body:
I've rendered a d3 map that has pan and zoom enabled, but when scrolling down the viewport either on desktop or mobile, the window gets stuck zooming in the map.

Is there a way to temporarily disable d3.zoom, while the window is scrolling?

I've seen ways of toggling the zoom/pan using a button as seen here: http://jsfiddle.net/0xncswrk/, but I wanted to know if it's possible without having to add a button.  Here's my current zoom logic.

Thanks!

this.zoom = d3.zoom()
  .scaleExtent([1, 8])
  .on('zoom', () => {
    this.svg.attr('transform', d3.event.transform);
  });

this.svg = d3.select(this.el).append('svg')
    .attr('width', '100%')
    .attr('height', this.height)
    .attr('class', 'bubble-map__svg-us')
    .call(this.zoom)
    .append('g');


问:
Is "message" a reserved word in Django or Python?
I seem to get a TypeError ('message' is an invalid keyword argument for this function) every time I try adding something in the DB via the Django admin interface. The object is added but this exception is raised. Could be this linked to the fact that I have a model named "Message"?</p>

答:
This example shows what others have already pointed out.</p>

```<code>>>> def hello(msg):
...     print "Hello, ", msg
...
>>> hello("world")
Hello,  world
>>> hello(msg="world")
Hello,  world
>>> hello(message="world")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: hello() got an unexpected keyword argument 'message'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This example shows what others have already pointed out.

>>> def hello(msg):
...     print "Hello, ", msg
...
>>> hello("world")
Hello,  world
>>> hello(msg="world")
Hello,  world
>>> hello(message="world")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: hello() got an unexpected keyword argument 'message'


问:
Cannot start Go server on localhost
Today, i encountered a very strange problem concerning a local server in Go on MAC OS X 10.12.2. Suddenly, after a successful build, i cannot start my application. Every time i get a "Killed 9" message.

This problem could be caused by two dependencies:

github.com/xeodou/go-sqlcipher

github.com/shirou/gopsutil/host

Without them the application can start, but I need them.

I  have been using those two dependencies for two months and I haven't had any problems with them. The problem happened suddenly after a successful build. I cloned the whole repository into two environments with Mac OS X 10.12.2 and Windows 8 and I didn't get any problems. The applications started on both machines.

Probably due to constant application checks and dozens of local servers created, MAC OS blocks some processes, but I couldn't find out where the problem is.

答: There seems to be some issue with the Sierra command line tools that were released today as part of xcode 8.3. Totally hosed my go project with immediate Killed: 9 upon running it. I had to revert back to command line tools from 8.2</p>

Title: Cannot start Go server on localhost


问:
What is wrong with this link? when clicked on, browser says "null/"
https://smile.amazon.com/gp/f.html?C=1OR2JD8DH59TD&K=A2CTKC0L6X87GK&R=28ZTBZOJI3VVH&T=C&U=http%3A%2F%2Fnull&A=KQPRJ83ZWZ0RQMDCCLBSZSLUIACA&H=1OLUERCFQKYSOSL3QA4HUYMYKEKA

I am unsure why this link is only coming up as "null/" when entered into browser. Someone please help me fix this!

答:
The part

```<code>http%3A%2F%2Fnull
</code>```

in your link means (after URL decoding)

```<code>http://null
</code>```

as %3A is the hexadecimal presentation of the character :, and %2F of the character /.

This part is preceded with &U=; & is the parameter's delimiter, U= means that the string http://null is assigned to the variable U.

The code at the server side may do with the content of U whatever it wants - it indeed redirects you to its content , i. e. to http://null.

Body:
The part

http%3A%2F%2Fnull

in your link means (after URL decoding)

http://null

as %3A is the hexadecimal presentation of the character :, and %2F of the character /.

This part is preceded with &U=; & is the parameter's delimiter, U= means that the string http://null is assigned to the variable U.

The code at the server side may do with the content of U whatever it wants - it indeed redirects you to its content , i. e. to http://null.


问:
WordPress Find and Replace in the Database
A quick overview: We're trying to convert some very long standing (7+ year old) WordPress Multisite installations from Subdomain to Subdirectory. Changing the wp-config.php and .htaccess is all well and good. But some of these installations have well over 1000 sites, and littered throughout the database can have an immense number of instances of abc.multisite.com.

I'm trying to find the best way to automate the conversion of abc.multisite.com to multisite.com/abc, of course without it affecting 123abc.multisite.com leading to 123multisite.com/abc.

All of the find/replace plugins I've seen that could do this only do a single search at a time, and I've got thousands of records to replace.

What would the best way to go about this? Is there an SQL command that I could loop through in PHP to dig through the hundreds of DB tables?

I can get a list of the sites using the get_sites() function and loop through that.

Or is there a better tool to export the database and find/replace there (the size of some of these DBs would crash atom/sublime/brackets.

答:
If you have (SSH) access to WP CLI, you can run this in your site root:

```<code>wp search-replace abc.multisite.com multisite.com/abc
</code>```

For Multisites, if you want to search in all tables, you'll need the --network flag.

http://wp-cli.org/commands/search-replace/

By default, the command uses tables registered to the $wpdb object.
  On multisite, this will just be the tables for the current site unless
  --network is specified. Search/replace intelligently handles PHP serialized data, and does not change primary key values.

```<code>wp search-replace abc.multisite.com multisite.com/abc --network
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you have (SSH) access to WP CLI, you can run this in your site root:

wp search-replace abc.multisite.com multisite.com/abc

For Multisites, if you want to search in all tables, you'll need the --network flag.

http://wp-cli.org/commands/search-replace/

By default, the command uses tables registered to the $wpdb object.
  On multisite, this will just be the tables for the current site unless
  --network is specified. Search/replace intelligently handles PHP serialized data, and does not change primary key values.

wp search-replace abc.multisite.com multisite.com/abc --network


问:
IntelliJ: Viewing diff of all changed files between local and a git commit/branch
Using IntelliJ's diff viewer is a very nice way to review code because you can make changes in your local version with all the capabilities of the IntelliJ code editor (refactoring, completion, etc).

Unfortunately, I have not worked out how to do the most important thing when you're doing code reviews in IntelliJ, namely: Looking at the diff of all the changed files in the working tree (checked out to the branch you want to merge from) and another branch (the branch you plan to merge into, e.g. "master").

Does anyone know how to do this?

答: If you just want to compare your currently open file with another branch in a side-by-side fashion, just go to VCS -> Git -> Compare with Branch.</p>


问:
Eclipse Kura OSGi Dependency Management
Preface: I'm new to Eclipse, OSGi, and Kura

I'm trying to develop a Kura plug-in that depends on org.apache.httpcomponents.httpclient. I found an OSGi bundle for the package here.

Currently, the only way I'm able to use the plug-in (with the OSX Kura emulator) is to download httpclient-osgi-4.5.jar and add it to ~/Documents/workspace/target-definition/common/repository/plugins/. Otherwise I get a class not found error.

When I add the plugin to MANIFEST.MF either as with REQUIRE-PLUGIN or IMPORT-PACKAGE, Eclipse cannot find the package.

What's the correct way to require, fetch, and add to the classpath a remote dependency using Eclipse Kura/OSGi? Eclipse currently only looks in my local workspace for dependancies, is there an accepted way to fetch remote plugins?

Thanks for the help!

答:
What for me works is;

Simply copied the bundle in ${workspace_loc}/target-definition/common/repository/plugins

Clicked on reload

Clicked on Set as Target Platform

After these steps, Eclipse is aware of my bundle and could able to use it anywhere.

Title: Eclipse Kura OSGi Dependency Management


问:
Using Javascript to Build a Dynamic JSON array
I want the JSON structure to be something like this:

```<code>var data = [{ "label": "Category A", "value": 20 },
{ "label": "Category B", "value": 50 },
{ "label": "Category C", "value": 30 }];
</code>```

I have a bunch of label and values that can be more than the 3 pairs above (it's dynamic).  The data for each label and value will also be differnt (entered by the user).

How do I create a JSON object like data when a user can enter as many label and value pairs with different data? Thanks,

答:
create an array :

```<code>var ary = [];
</code>```

keep pushing pairs of ( label , value )  that you obtain from some source :

```<code>ary.push( { "label" :  "a label" , "value" : "a value" } );
</code>```

Once it is done, create the json string as follow:

```<code>var outputJson = JSON.stringify(ary);
</code>```

Body:
I want the JSON structure to be something like this:

var data = [{ "label": "Category A", "value": 20 },
{ "label": "Category B", "value": 50 },
{ "label": "Category C", "value": 30 }];

I have a bunch of label and values that can be more than the 3 pairs above (it's dynamic).  The data for each label and value will also be differnt (entered by the user).

How do I create a JSON object like data when a user can enter as many label and value pairs with different data? Thanks,

Body:
create an array :

var ary = [];

keep pushing pairs of ( label , value )  that you obtain from some source :

ary.push( { "label" :  "a label" , "value" : "a value" } );

Once it is done, create the json string as follow:

var outputJson = JSON.stringify(ary);


问:
Export object inside of function
I'm trying to write functional stateless components and in doing so have run into an issue. I wrap by Navigator in a function that takes props as an argument (these are arbitrary). The component that gets wrapped is currently defined as follows since it is used in the reducer for this component.

```<code>export const Navigator = StackNavigator(screens, navigatorConfig);

const NavigatorView = (props) => {
    return (<Navigator screenProps={{ ...props }}/>);
};
</code>```

This works, but I'd ideally like to be able to instantiate the Navigator as a local variable in the NavigatorView function, and export there so that I have flexibility towards what attributes I can set at instantiation time (like shown below).

```<code>const NavigatorView = (myArg, props) => {
    const Navigator = StackNavigator(screens, myArg);
    return (<Navigator screenProps={{ ...props }}/>);
};
</code>```

The problem here is as follows, how can I export Navigator (that's used in the reducer) while keeping it wrapped in a function? I've tried module.exports = Navigator;, export const Navigator... but they do not work. Thanks.

答:
How about making a function that returns a function?</p>

```<code>export const generateNavigator = (screens, navigatorConfig) =>
  StackNavigator(screens, navigatorConfig);

const NavigatorView = (myArg, props) => {
    const Navigator = generateNavigator(screens, myArg);
    return (<Navigator screenProps={{ ...props }}/>);
};
</code>```

Title: Export object inside of function

Body:
I'm trying to write functional stateless components and in doing so have run into an issue. I wrap by Navigator in a function that takes props as an argument (these are arbitrary). The component that gets wrapped is currently defined as follows since it is used in the reducer for this component.

export const Navigator = StackNavigator(screens, navigatorConfig);

const NavigatorView = (props) => {
    return (<Navigator screenProps={{ ...props }}/>);
};

This works, but I'd ideally like to be able to instantiate the Navigator as a local variable in the NavigatorView function, and export there so that I have flexibility towards what attributes I can set at instantiation time (like shown below).

const NavigatorView = (myArg, props) => {
    const Navigator = StackNavigator(screens, myArg);
    return (<Navigator screenProps={{ ...props }}/>);
};

The problem here is as follows, how can I export Navigator (that's used in the reducer) while keeping it wrapped in a function? I've tried module.exports = Navigator;, export const Navigator... but they do not work. Thanks.

Body:
How about making a function that returns a function?

export const generateNavigator = (screens, navigatorConfig) =>
  StackNavigator(screens, navigatorConfig);

const NavigatorView = (myArg, props) => {
    const Navigator = generateNavigator(screens, myArg);
    return (<Navigator screenProps={{ ...props }}/>);
};


问:
Angular: updating view with value passed from directive to controller
Budding web developer here struggling with updating the view from my controller.

I'm using highmaps and angular to build a neat selection tool for my web app. I've got a directive nested inside the scope of a controller. I would like this directive to update a value (selectedCountry) stored in the controller. Then, I'd like the controller to display the up to date selectedCountry value on the view.

I've checked that the directive is passing the correct selectedCountry value to the parent controller. However, the controller is not updating the view to match the updated value. I would greatly appreciate if someone could take a look at this.

Demo Here: http://jsfiddle.net/frauLLmr/5/

index.html

```<code><div ng-app="myApp">
  <div ng-controller="GraphController as graphCtrl">
    <div> {{graphCtrl.showSelectedCountry()}} </div>
    <div> {{graphCtrl.selectedCountry}} </div>
    <high-chart-directive update-selected-country='graphCtrl.updateSelectedCountry(newCountry)'></high-chart-directive>
  </div>
</div>
</code>```

app.js

```<code>var myApp = angular.module('myApp', []);
myApp.controller('GraphController', function() {
  var self = this;
  self.selectedCountry = 'unselected';
  var outsideScopeTest = function() {
    alert('selectedCountry (from controller scope): '
        + self.selectedCountry);
  };
  self.updateSelectedCountry = function(newCountry) {
    self.selectedCountry = newCountry;
    outsideScopeTest();
  };
  self.showSelectedCountry = function() {
    return self.selectedCountry;
  };
});

myApp.directive('highChartDirective', function () {
  return {
    restrict: 'E',
    scope: {
      updateSelectedCountry: '&'
    },
    link: function(scope, element) {
      Highcharts.mapChart(element[0], getMapOptions(mapClick));

      function mapClick(event) {
        scope.updateSelectedCountry({newCountry: event.point.name});
        alert('selectedCountry (from directive scope): '
        + event.point.name);
      }
    }
  };

  function getMapOptions(callback) {
    return {
      title: {
        text: ''
      },
      mapNavigation: {
        enabled: true,
        buttonOptions: {
          verticalAlign: 'bottom'
        }
      },
      series: [{
        data: getTestCountries(),
        mapData: Highcharts.maps['custom/world-highres'],
        // TODO-chantelle: figure out how geoJSON joinBy works
        joinBy: 'hc-key',
        name: 'Emission per capita',
        states: {
          hover: {
            color: '#9370DB'
          }
        },
        dataLabels: {
          enabled: false,
          format: '{point.name}'
        }
      }],
      plotOptions: {
        series: {
          events: {
            click: function(event) {
              callback(event);
            }
          }
        }
      }
    };
  }

  function getTestCountries() {
    return [{
      "hc-key": "ca",
      "value": 0
    }, {
      "hc-key": "br",
      "value": 1
    }, {
      "hc-key": "ru",
      "value": 2
    }];
  }
});
</code>```

答:
the issue is that  Highcharts.mapChart(element[0], getMapOptions(mapClick)); is not part of the angular scope. So any calls here will not trigger the angular app to refresh. You need to force angular to update using $scope.apply();</p>

```<code>var outsideScopeTest = function() {
    alert('selectedCountry (from controller scope): '
    + selfc.selectedCountry);

    // force angular update
    $scope.$apply();

};
</code>```

Body:
Budding web developer here struggling with updating the view from my controller.

I'm using highmaps and angular to build a neat selection tool for my web app. I've got a directive nested inside the scope of a controller. I would like this directive to update a value (selectedCountry) stored in the controller. Then, I'd like the controller to display the up to date selectedCountry value on the view.

I've checked that the directive is passing the correct selectedCountry value to the parent controller. However, the controller is not updating the view to match the updated value. I would greatly appreciate if someone could take a look at this.

Demo Here: http://jsfiddle.net/frauLLmr/5/

index.html

 {{graphCtrl.showSelectedCountry()}}

 {{graphCtrl.selectedCountry}}

    <high-chart-directive update-selected-country='graphCtrl.updateSelectedCountry(newCountry)'></high-chart-directive>

app.js

var myApp = angular.module('myApp', []);
myApp.controller('GraphController', function() {
  var self = this;
  self.selectedCountry = 'unselected';
  var outsideScopeTest = function() {
    alert('selectedCountry (from controller scope): '
        + self.selectedCountry);
  };
  self.updateSelectedCountry = function(newCountry) {
    self.selectedCountry = newCountry;
    outsideScopeTest();
  };
  self.showSelectedCountry = function() {
    return self.selectedCountry;
  };
});

myApp.directive('highChartDirective', function () {
  return {
    restrict: 'E',
    scope: {
      updateSelectedCountry: '&'
    },
    link: function(scope, element) {
      Highcharts.mapChart(element[0], getMapOptions(mapClick));

      function mapClick(event) {
        scope.updateSelectedCountry({newCountry: event.point.name});
        alert('selectedCountry (from directive scope): '
        + event.point.name);
      }
    }
  };

  function getMapOptions(callback) {
    return {
      title: {
        text: ''
      },
      mapNavigation: {
        enabled: true,
        buttonOptions: {
          verticalAlign: 'bottom'
        }
      },
      series: [{
        data: getTestCountries(),
        mapData: Highcharts.maps['custom/world-highres'],
        // TODO-chantelle: figure out how geoJSON joinBy works
        joinBy: 'hc-key',
        name: 'Emission per capita',
        states: {
          hover: {
            color: '#9370DB'
          }
        },
        dataLabels: {
          enabled: false,
          format: '{point.name}'
        }
      }],
      plotOptions: {
        series: {
          events: {
            click: function(event) {
              callback(event);
            }
          }
        }
      }
    };
  }

  function getTestCountries() {
    return [{
      "hc-key": "ca",
      "value": 0
    }, {
      "hc-key": "br",
      "value": 1
    }, {
      "hc-key": "ru",
      "value": 2
    }];
  }
});

Body:
the issue is that  Highcharts.mapChart(element[0], getMapOptions(mapClick)); is not part of the angular scope. So any calls here will not trigger the angular app to refresh. You need to force angular to update using $scope.apply();

var outsideScopeTest = function() {
    alert('selectedCountry (from controller scope): '
    + selfc.selectedCountry);

    // force angular update
    $scope.$apply();

};


答:
```<code>var data = [
  { "label": "Category A", "value": 20 },
  { "label": "Category B", "value": 50 },
  { "label": "Category C", "value": 30 }
];

data.push({ "label": "Category D", "value": 60 });

var jsonData = JSON.stringify(data);
</code>```

Title: Using Javascript to Build a Dynamic JSON array


问:
Where should I put data for automated tests with testthat?
I am using Hadley's testthat-based approach for automated testing of my package.

With this approach, what is the most suitable place to put test data files that is files only used by the test scripts in tests/testthat), but not by any other functions in R/?

My current approach is to put them in tests/testdata, and then read.table from there with a relative path rather than with system.file (in order to avoid the need to install the package to run tests).

Is there a standard way to do this?

答:
Lifting from Ben Bolker's comments:

I use inst/testdata and then
  system.file("testdata",...,package="my_package")

The advantage of this method:

You can keep your file structure neat, especially if you have many data files and/or tests.

The fact that files in inst are installed is long-standing canonical R practice; it seems safer that system.file("testdata", "some_file") will always work than that ../testdata/some_file will do. I've had bad experiences using relative file paths when doing R CMD check.

Unlike Sathish's answer, it doesn't depend on your data being "stored" as R code.


问:
Wordpress - Is it okay to add new column to the existing db table?
I need to store phone number on Comments. I know I can use meta field and be saved in wp_commentmeta table. But will reduce database size if it's in 1 table.

So, can I add like phone_no column to wp_comments table? Will it affect the way WordPress works?

Thanks

答: It will not break the Wordpress if you add a column, but you will not reduce size by doing so, and I think you should use wp_commentmeta.</p>


问:
Android - I can't refresh / redraw a ListView
I have a ListView that lists a set of books.

The user can add a new book and, after that, the set of books is shown again using the onActivityResult method.

I have been trying for hours to get the set of books to refresh after adding a new book but with no luck, at all.

This is the code I have tried:

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

    private ArrayList<Book> books = null;
    private BookItemAdapter bookItemAdapter;
    ListView booksSetView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        books = new ArrayList<Book>();
        booksSetView = (ListView)findViewById(R.id.booksSet);

        Cursor booksCursor = null;

        booksCursor = getBooksCursor();
        if (booksCursor.moveToFirst())
        {
            do
            {
                books.add(getBookFromCursor(booksCursor));
            } while(booksCursor.moveToNext());
        }

        bookItemAdapter = new BookItemAdapter(this, R.layout.book_item, books, 0); // BookItemAdapter is a ArrayAdapter
        booksSetView.setAdapter(bookItemAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
            Log.e("BOOKS MANAGER", "trying to refresh");

        bookItemAdapter.notifyDataSetChanged();
        booksSetView.invalidate();
        booksSetView.invalidateViews();
    }
}
</code>```

Please some help.

Thanks a lot!

答:
I've had wierd issues like this, while it really isnt pretty, you can just substitute notifyDataSetChanged for the adapter constructor.</p>

```<code>@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
            Log.e("BOOKS MANAGER", "trying to refresh");

        bookItemAdapter = new BookItemAdapter(this, R.layout.book_item, books, 0); // BookItemAdapter is a ArrayAdapter
        booksSetView.setAdapter(bookItemAdapter);
    }
</code>```

Body:
I have a ListView that lists a set of books.

The user can add a new book and, after that, the set of books is shown again using the onActivityResult method.

I have been trying for hours to get the set of books to refresh after adding a new book but with no luck, at all.

This is the code I have tried:

public class BookActivity extends Activity {

    private ArrayList<Book> books = null;
    private BookItemAdapter bookItemAdapter;
    ListView booksSetView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        books = new ArrayList<Book>();
        booksSetView = (ListView)findViewById(R.id.booksSet);

        Cursor booksCursor = null;

        booksCursor = getBooksCursor();
        if (booksCursor.moveToFirst())
        {
            do
            {
                books.add(getBookFromCursor(booksCursor));
            } while(booksCursor.moveToNext());
        }

        bookItemAdapter = new BookItemAdapter(this, R.layout.book_item, books, 0); // BookItemAdapter is a ArrayAdapter
        booksSetView.setAdapter(bookItemAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
            Log.e("BOOKS MANAGER", "trying to refresh");

        bookItemAdapter.notifyDataSetChanged();
        booksSetView.invalidate();
        booksSetView.invalidateViews();
    }
}

Please some help.

Thanks a lot!

Body:
I've had wierd issues like this, while it really isnt pretty, you can just substitute notifyDataSetChanged for the adapter constructor.

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
            Log.e("BOOKS MANAGER", "trying to refresh");

        bookItemAdapter = new BookItemAdapter(this, R.layout.book_item, books, 0); // BookItemAdapter is a ArrayAdapter
        booksSetView.setAdapter(bookItemAdapter);
    }


问:
Reactjs pass variables from one component to another
I have a component like this:

```<code>class LoginPage extends React.Component{
  constructor(props)  {
    super(props);
    this.state = {submit:''};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    alert('username and password were submitted: ' + this.props.userName + ' and ' + this.props.password);
    e.prevenDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <GetUsername/>
        <GetPassword/>
        <button type="submit">Login</button>
       </form>
    )
  }
}
</code>```

The GetUsername and GetPassword components get username and password from user input. My question is that is there anyway I can pass the username and password from these 2 components to the handleSubmit method of the LoginPage component above, so the alert pops up can show correctly?

答:
You need to make username and password part of the state of your LoginPage component, and update the state whenever the input changes.  You do this by having an inputChanged function defined on LoginPage which is passed as a prop to your GetUsername and GetPassword components.

```<code>class LoginPage extends React.Component {
  constructor() {
    super();
    this.state = {
      username: '',
      password: ''
    };
  }

  handleSubmit(e) {
    e.prevenDefault();
    alert('username and password were submitted: ' + this.state.userName + ' and ' + this.state.password);
  }

  handleInputChange(name, value) {
    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <GetUsername onChange={newValue => this.handleInputChange('username', newValue)} />
        <GetPassword  onChange={newValue => this.handleInputChange('password', newValue)} />
        <button type="submit">Login</button>
       </form>
    )
  }
</code>```

Then e.g.

```<code>const GetUsername = ({ onChange }) => (
    <input type="text" name="username" onChange={(e) => onChange(e.target.value)} />
);
</code>```

Body:
I have a component like this:

class LoginPage extends React.Component{
  constructor(props)  {
    super(props);
    this.state = {submit:''};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    alert('username and password were submitted: ' + this.props.userName + ' and ' + this.props.password);
    e.prevenDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <GetUsername/>
        <GetPassword/>
        <button type="submit">Login</button>
       </form>
    )
  }
}

The GetUsername and GetPassword components get username and password from user input. My question is that is there anyway I can pass the username and password from these 2 components to the handleSubmit method of the LoginPage component above, so the alert pops up can show correctly?

Body:
You need to make username and password part of the state of your LoginPage component, and update the state whenever the input changes.  You do this by having an inputChanged function defined on LoginPage which is passed as a prop to your GetUsername and GetPassword components.

class LoginPage extends React.Component {
  constructor() {
    super();
    this.state = {
      username: '',
      password: ''
    };
  }

  handleSubmit(e) {
    e.prevenDefault();
    alert('username and password were submitted: ' + this.state.userName + ' and ' + this.state.password);
  }

  handleInputChange(name, value) {
    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <GetUsername onChange={newValue => this.handleInputChange('username', newValue)} />
        <GetPassword  onChange={newValue => this.handleInputChange('password', newValue)} />
        <button type="submit">Login</button>
       </form>
    )
  }

Then e.g.

const GetUsername = ({ onChange }) => (
    <input type="text" name="username" onChange={(e) => onChange(e.target.value)} />
);


问:
How to add a dynamic formula to a cell reference using VBA?
I am trying to add a dynamic formula to a cell using VBA. I have seen a couple of post on it but I cannot figure out what I am doing wrong. I am getting a run-time error '1004' for "Method 'Range' of object'_Worksheet' failed". What am I doing wrong?

```<code>Sub AddFormulas()

Dim LastNumberRow As Integer

Set countBase = Sheet7.Range("CU2")
colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count

Dim startCount As Integer
startCount = 98

    For i = 1 To colCount

        If IsNumeric(Cells(2, startCount + i)) Then
            Sheet7.Range(3, i).Formula = "=Sheet6!" & Cells(3, startCount + i).Address & "*" & "Sheet7!" & Cells(3, colCount + startCount).Address
        Else
            'Do some stuff
        End If
    Next i
End Sub
</code>```

I have added the proposed changes from the comments below but not I get a file explorer popup window. I have altered my code with the following changes:

```<code>If IsNumeric(Sheet7.Cells(2, startCount + i)) Then
            Set bSum = Sheet7.Cells(3, colCount + startCount)
            Set bSpr = Sheet6.Cells(3, startCount + i)

            Sheet7.Cells(3, i).Formula = "=Sheet6!" & bSpr.Address() & "*" & "Sheet7!" & bSpr.Address()
</code>```

答:
Try replacing Sheet7.Range(3, i).Formula = ...
with: Sheet7.Cells(3, i).Formula = ...

Body:
I am trying to add a dynamic formula to a cell using VBA. I have seen a couple of post on it but I cannot figure out what I am doing wrong. I am getting a run-time error '1004' for "Method 'Range' of object'_Worksheet' failed". What am I doing wrong?

Sub AddFormulas()

Dim LastNumberRow As Integer

Set countBase = Sheet7.Range("CU2")
colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count

Dim startCount As Integer
startCount = 98

    For i = 1 To colCount

        If IsNumeric(Cells(2, startCount + i)) Then
            Sheet7.Range(3, i).Formula = "=Sheet6!" & Cells(3, startCount + i).Address & "*" & "Sheet7!" & Cells(3, colCount + startCount).Address
        Else
            'Do some stuff
        End If
    Next i
End Sub

I have added the proposed changes from the comments below but not I get a file explorer popup window. I have altered my code with the following changes:

If IsNumeric(Sheet7.Cells(2, startCount + i)) Then
            Set bSum = Sheet7.Cells(3, colCount + startCount)
            Set bSpr = Sheet6.Cells(3, startCount + i)

            Sheet7.Cells(3, i).Formula = "=Sheet6!" & bSpr.Address() & "*" & "Sheet7!" & bSpr.Address()


问:
Getting "bad username or password" error while attempting to connect to broker
I have followed the tutorial presented here, but I couldn't connect a client to the server. I always get the following error message (full stacktrace):

```<code>Error: Connection refused: Bad username or password
at MqttClient._handleConnack (${project_dir}/node_modules/mqtt/lib/client.js:760:24)
at MqttClient._handlePacket (${project_dir}/node_modules/mqtt/lib/client.js:300:12)
at process (${project_dir}/node_modules/mqtt/lib/client.js:242:12)
at Writable.writable._write (${project_dir}/node_modules/mqtt/lib/client.js:252:5)
at doWrite (${project_dir}/node_modules/mqtt/node_modules/readable-stream/lib/_stream_writable.js:345:64)
at writeOrBuffer (${project_dir}/node_modules/mqtt/node_modules/readable-stream/lib/_stream_writable.js:334:5)
at Writable.write (${project_dir}/node_modules/mqtt/node_modules/readable-stream/lib/_stream_writable.js:271:11)
at Socket.ondata (_stream_readable.js:528:20)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
</code>```

I have double-checked my environment variables, whose values came from my Auth0 account, (particularly CLIENT_ID, DOMAIN, CLIENT_SECRET and CONNECTION) but they seem fine.

I've changed the client's code a bit to match the current version of MQTT.js. Here is the code:

```<code>const mqtt = require('mqtt');
const settings = {
    port: 1883,
    keepalive: 1000,
    protocolId: 'MQIsdp', // already tried 'MQTT' with protocol version 4
    protocolVersion: 3,
    clientId: 'a random id',
    username: 'an account at Auth0',
    password: 'the password of the account'
}

var client = mqtt.connect('mqtt://localhost', settings);

client.on("connect", function () {
    client.subscribe("topic");
    console.log("connected");
});

client.on("message", function (topic, message) {
    // message is Buffer
    console.log(message.toString());
    client.end();
});
</code>```

The broker code is very similar to the presented in the tutorial. I want to solve this error before changing it.

```<code>const mosca = require('mosca')
const Auth0Mosca = require('auth0mosca');
require('dotenv').config();

const settings = {
    port: 1883
};

if (!process.env.AUTH0_DOMAIN || !process.env.AUTH0_CLIENT_ID ||
    !process.env.AUTH0_CLIENT_SECRET || !process.env.AUTH0_CONNECTION) {
    throw 'Make sure you have AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET and AUTH0_CONNECTION in your .env file';
}

const auth0 = new Auth0Mosca('https://' + process.env.AUTH0_DOMAIN, process.env.AUTH0_CLIENT_ID, process.env.AUTH0_CLIENT_SECRET, process.env.AUTH0_CONNECTION);

// mosca server
const server = new mosca.Server(settings);

server.authenticate = auth0.authenticateWithCredentials();
server.authorizePublish = auth0.authorizePublish();
server.authorizeSubscribe = auth0.authorizeSubscribe();

server.on('ready', setup);

// MQTT server is ready
function setup() {
    console.log('Mosca server is up and running');
}

server.on('clientConnected', function(client) {
    console.log('New connection: ', client.id);
});
</code>```

I know that it is probably a stupid mistake or a library update that is causing this. For the latter case, here are the versions:

```<code>"auth0mosca": "^0.1.0",
"mosca": "^2.3.0",
"mqtt": "^2.5.0"
</code>```

Finally, I have checked that the request reaches the broker.

答:
I have forked the repository with the code of the tutorial and updated its dependencies to the latest versions. Also, added the possibility to verify JWTs signed with, for example, RS256 algorithm. </p>

<p>This solved my problem and I hope it helps everyone facing the same issue. </p>

Body:
I have followed the tutorial presented here, but I couldn't connect a client to the server. I always get the following error message (full stacktrace):

Error: Connection refused: Bad username or password
at MqttClient._handleConnack (${project_dir}/node_modules/mqtt/lib/client.js:760:24)
at MqttClient._handlePacket (${project_dir}/node_modules/mqtt/lib/client.js:300:12)
at process (${project_dir}/node_modules/mqtt/lib/client.js:242:12)
at Writable.writable._write (${project_dir}/node_modules/mqtt/lib/client.js:252:5)
at doWrite (${project_dir}/node_modules/mqtt/node_modules/readable-stream/lib/_stream_writable.js:345:64)
at writeOrBuffer (${project_dir}/node_modules/mqtt/node_modules/readable-stream/lib/_stream_writable.js:334:5)
at Writable.write (${project_dir}/node_modules/mqtt/node_modules/readable-stream/lib/_stream_writable.js:271:11)
at Socket.ondata (_stream_readable.js:528:20)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)

I have double-checked my environment variables, whose values came from my Auth0 account, (particularly CLIENT_ID, DOMAIN, CLIENT_SECRET and CONNECTION) but they seem fine.

I've changed the client's code a bit to match the current version of MQTT.js. Here is the code:

const mqtt = require('mqtt');
const settings = {
    port: 1883,
    keepalive: 1000,
    protocolId: 'MQIsdp', // already tried 'MQTT' with protocol version 4
    protocolVersion: 3,
    clientId: 'a random id',
    username: 'an account at Auth0',
    password: 'the password of the account'
}

var client = mqtt.connect('mqtt://localhost', settings);

client.on("connect", function () {
    client.subscribe("topic");
    console.log("connected");
});

client.on("message", function (topic, message) {
    // message is Buffer
    console.log(message.toString());
    client.end();
});

The broker code is very similar to the presented in the tutorial. I want to solve this error before changing it.

const mosca = require('mosca')
const Auth0Mosca = require('auth0mosca');
require('dotenv').config();

const settings = {
    port: 1883
};

if (!process.env.AUTH0_DOMAIN || !process.env.AUTH0_CLIENT_ID ||
    !process.env.AUTH0_CLIENT_SECRET || !process.env.AUTH0_CONNECTION) {
    throw 'Make sure you have AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET and AUTH0_CONNECTION in your .env file';
}

const auth0 = new Auth0Mosca('https://' + process.env.AUTH0_DOMAIN, process.env.AUTH0_CLIENT_ID, process.env.AUTH0_CLIENT_SECRET, process.env.AUTH0_CONNECTION);

// mosca server
const server = new mosca.Server(settings);

server.authenticate = auth0.authenticateWithCredentials();
server.authorizePublish = auth0.authorizePublish();
server.authorizeSubscribe = auth0.authorizeSubscribe();

server.on('ready', setup);

// MQTT server is ready
function setup() {
    console.log('Mosca server is up and running');
}

server.on('clientConnected', function(client) {
    console.log('New connection: ', client.id);
});

I know that it is probably a stupid mistake or a library update that is causing this. For the latter case, here are the versions:

"auth0mosca": "^0.1.0",
"mosca": "^2.3.0",
"mqtt": "^2.5.0"

Finally, I have checked that the request reaches the broker.

Body:
I have forked the repository with the code of the tutorial and updated its dependencies to the latest versions. Also, added the possibility to verify JWTs signed with, for example, RS256 algorithm.

This solved my problem and I hope it helps everyone facing the same issue.


问:
How send post request from php to python?
I want send post request from php to python and get answer
I write this script which the send post

```<code>$url = 'http://localhost:8080/cgi-bin/file.py';
$body = 'hello world';
$options = array('method'=>'POST',
'content'=>$body,
'header'=>'Content-type:application/x-ww-form-urlencoded');
$context = stream_context_create(array('http' => $options));
print file_get_contents($url, false,$context);
</code>```

I'm use custom python server

```<code>from http.server import HTTPServer, CGIHTTPRequestHandler
server_address = ("", 8080)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()
</code>```

And python script which the takes post request

```<code>print('Content-type: text/html\n')
import cgi
form = cgi.FieldStorage()
text2 = form.getfirst("content", "empty")
print("<p>TEXT_2: {}</p>".format(text2))
</code>```

And then I get

```<code>write() argument must be str, not bytes\r\n'
</code>```

How can it be solved?
P.S Sorry for my bad english

答:
You can also use a library like guzzle that may have some other bells and whistles you may want to use.

Example usage can be found on this other answer here:

https://stackoverflow.com/a/29601842/6626810

Body:
I want send post request from php to python and get answer
I write this script which the send post

$url = 'http://localhost:8080/cgi-bin/file.py';
$body = 'hello world';
$options = array('method'=>'POST',
'content'=>$body,
'header'=>'Content-type:application/x-ww-form-urlencoded');
$context = stream_context_create(array('http' => $options));
print file_get_contents($url, false,$context);

I'm use custom python server

from http.server import HTTPServer, CGIHTTPRequestHandler
server_address = ("", 8080)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()

And python script which the takes post request

print('Content-type: text/html\n')
import cgi
form = cgi.FieldStorage()
text2 = form.getfirst("content", "empty")
print("
TEXT_2: {}
".format(text2))

And then I get

write() argument must be str, not bytes\r\n'

How can it be solved?
P.S Sorry for my bad english


问:
Alternative to subprocess mv to reduce memory footprint
How would I do the following in a more pythonic way that doesn't create a new thread (which takes up too much memory for me) --

```<code>subprocess.call(['mv', '/tmp/%s' % self.file_name, self.file_name])
</code>```

Also, I need to make sure it respects the sudo command when running the script, because I need that in order to move the file.

答:
The operation you're performing is best done using shutil.move, which will run with the same privileges as your Python process (because it is your Python process), so if the Python script is sudoed, so is the move operation:

```<code>import shutil

shutil.move('/tmp/%s' % self.file_name, self.file_name)
</code>```

Body:
How would I do the following in a more pythonic way that doesn't create a new thread (which takes up too much memory for me) --

subprocess.call(['mv', '/tmp/%s' % self.file_name, self.file_name])

Also, I need to make sure it respects the sudo command when running the script, because I need that in order to move the file.

Body:
The operation you're performing is best done using shutil.move, which will run with the same privileges as your Python process (because it is your Python process), so if the Python script is sudoed, so is the move operation:

import shutil

shutil.move('/tmp/%s' % self.file_name, self.file_name)


问:
Error : Cannot fetch a row from OLE DB provider "ADsDSOObject" for linked server "ADSI"
When I attempt to query AD for users I receive the following error:

Cannot fetch a row from OLE DB provider "ADsDSOObject" for linked server "ADSI".

I assume the issue due to the 1000 row limit (or 901 rows in SqlServer 2008). I can page the query but I am looking for workaround that would allow me to retrieve more than 1000 at a time.

In case it helps, I am using SqlServer 2008 R2.
and here is my query

```<code>SELECT  samaccountname AS Account, ISNULL(givenName, '''') AS givenName, ISNULL(SN, '''') AS SN, ISNULL(DisplayName, '''') as DisplayName, ISNULL(Title, '''') AS Title
                        FROM OpenQuery(ADSI,
                        'SELECT SamAccountName, givenName, SN, DisplayName, Title
                        FROM ''LDAP://corpdomain.corp''
                        WHERE objectClass = ''User'' and (SN = ''*'' or givenName = ''*'')')
</code>```

Any ideas?

EDIT -
Upon further inspection I realized I am not able to properly page this query either. Does anyone have any tips on a solution that will allow me to page the results or a workaround that will allow me to return more than 901?

答:
I hit this problem too, and didn't like the usual solution posted of paging by the first letter of the account name.  This would mean 26 separate calls to AD, and also could still potentially fail because with a large domain its very possible to have more than 901 accounts starting with the same first letter - particularly if you are looking at computer accounts, which likely follow some systematic naming convention using the same first letter...

I did some playing around and I found that if you order the openquery by uSNCreated and put a TOP 901 clause on the outer query it doesn't blow up.

So, here is my SQL which fetches ALL active directory objects (computers, domain controllers, users and contacts) into a temp table in chunks of 901 records and gives you some useful information on each object.

```<code>CREATE TABLE #ADData(
    Login           NVARCHAR(256)
    ,CommonName     NVARCHAR(256)
    ,GivenName      NVARCHAR(256)
    ,FamilyName     NVARCHAR(256)
    ,DisplayName    NVARCHAR(256)
    ,Title          NVARCHAR(256)
    ,Department     NVARCHAR(256)
    ,Location       NVARCHAR(256)
    ,Info           NVARCHAR(256)
    ,LastLogin      BIGINT
    ,flags          INT
    ,Email          NVARCHAR(256)
    ,Phone          NVARCHAR(256)
    ,Mobile         NVARCHAR(256)
    ,Quickdial      NVARCHAR(256)
    , usnCreated    INT
)

DECLARE @Query      VARCHAR (2000)
DECLARE @Filter     VARCHAR(200)
DECLARE @Rowcount   INT

select @Filter =''

WHILE ISNULL(@rowcount,901)  = 901 BEGIN

    SELECT @Query = '
    SELECT top 901
            Login           = SamAccountName
            , CommonName    = cn
            , GivenName
            , FamilyName    = sn
            , DisplayName
            , Title
            , Department
            , Location      = physicalDeliveryOfficeName
            , Info
            , LastLogin     = CAST(LastLogon AS bigint)
            , flags         = CAST (UserAccountControl as int)
            , Email         = mail
            , Phone         = telephoneNumber
            , Mobile        = mobile
            , QuickDial     = Pager
            , usnCreated
        FROM OPENROWSET(''ADSDSOObject'', '''', ''
                SELECT cn, givenName, sn, userAccountControl, lastLogon, displayName, samaccountname,
                title,  department, physicalDeliveryOfficeName, info, mail, telephoneNumber, mobile, pager, usncreated
            FROM ''''LDAP://[ldap-query-string]''''
            WHERE objectClass=''''Person''''
            AND objectClass = ''''User''''
            ' + @filter + '
            ORDER BY usnCreated'')'
    INSERT INTO #ADData EXEC (@Query)
    SELECT @Rowcount = @@ROWCOUNT
    SELECT @Filter = 'and usnCreated > '+ LTRIM(STR((SELECT MAX(usnCreated) FROM #ADData)))

END

SELECT LOGIN
        , CommonName
        , GivenName
        , FamilyName
        , DisplayName
        , Title
        , Department
        , Location
        , Email
        , Phone
        , QuickDial
        , Mobile
        , Info
        , Disabled      = CASE WHEN CAST (flags AS INT) & 2 > 0 THEN 'Y' ELSE NULL END
        , Locked        = CASE WHEN CAST (flags AS INT) & 16  > 0 THEN 'Y' ELSE NULL END
        , NoPwdExpiry   = CASE WHEN CAST (flags AS INT) & 65536  > 0 THEN 'Y' ELSE NULL END
        , LastLogin     = CASE WHEN ISNULL(CAST (LastLogin AS BIGINT),0) = 0 THEN NULL ELSE
                            DATEADD(ms, (CAST (LastLogin AS BIGINT) / CAST(10000 AS BIGINT)) % 86400000,
                            DATEADD(day, CAST (LastLogin AS BIGINT) / CAST(864000000000 AS BIGINT) - 109207, 0)) END
        , Type = CASE WHEN flags  & 512 = 512 THEN 'user'
                    WHEN flags IS NULL THEN 'contact'
                    WHEN flags & 4096 = 4096 THEN 'computer'
                    WHEN flags & 532480 = 532480 THEN 'computer (DC)' END
FROM #ADData
ORDER BY Login

DROP TABLE #ADData
</code>```

Body:
When I attempt to query AD for users I receive the following error:

Cannot fetch a row from OLE DB provider "ADsDSOObject" for linked server "ADSI".

I assume the issue due to the 1000 row limit (or 901 rows in SqlServer 2008). I can page the query but I am looking for workaround that would allow me to retrieve more than 1000 at a time.

In case it helps, I am using SqlServer 2008 R2.
and here is my query

SELECT  samaccountname AS Account, ISNULL(givenName, '''') AS givenName, ISNULL(SN, '''') AS SN, ISNULL(DisplayName, '''') as DisplayName, ISNULL(Title, '''') AS Title
                        FROM OpenQuery(ADSI,
                        'SELECT SamAccountName, givenName, SN, DisplayName, Title
                        FROM ''LDAP://corpdomain.corp''
                        WHERE objectClass = ''User'' and (SN = ''*'' or givenName = ''*'')')

Any ideas?

EDIT -
Upon further inspection I realized I am not able to properly page this query either. Does anyone have any tips on a solution that will allow me to page the results or a workaround that will allow me to return more than 901?

Body:
I hit this problem too, and didn't like the usual solution posted of paging by the first letter of the account name.  This would mean 26 separate calls to AD, and also could still potentially fail because with a large domain its very possible to have more than 901 accounts starting with the same first letter - particularly if you are looking at computer accounts, which likely follow some systematic naming convention using the same first letter...

I did some playing around and I found that if you order the openquery by uSNCreated and put a TOP 901 clause on the outer query it doesn't blow up.

So, here is my SQL which fetches ALL active directory objects (computers, domain controllers, users and contacts) into a temp table in chunks of 901 records and gives you some useful information on each object.

CREATE TABLE #ADData(
    Login           NVARCHAR(256)
    ,CommonName     NVARCHAR(256)
    ,GivenName      NVARCHAR(256)
    ,FamilyName     NVARCHAR(256)
    ,DisplayName    NVARCHAR(256)
    ,Title          NVARCHAR(256)
    ,Department     NVARCHAR(256)
    ,Location       NVARCHAR(256)
    ,Info           NVARCHAR(256)
    ,LastLogin      BIGINT
    ,flags          INT
    ,Email          NVARCHAR(256)
    ,Phone          NVARCHAR(256)
    ,Mobile         NVARCHAR(256)
    ,Quickdial      NVARCHAR(256)
    , usnCreated    INT
)

DECLARE @Query      VARCHAR (2000)
DECLARE @Filter     VARCHAR(200)
DECLARE @Rowcount   INT

select @Filter =''

WHILE ISNULL(@rowcount,901)  = 901 BEGIN

    SELECT @Query = '
    SELECT top 901
            Login           = SamAccountName
            , CommonName    = cn
            , GivenName
            , FamilyName    = sn
            , DisplayName
            , Title
            , Department
            , Location      = physicalDeliveryOfficeName
            , Info
            , LastLogin     = CAST(LastLogon AS bigint)
            , flags         = CAST (UserAccountControl as int)
            , Email         = mail
            , Phone         = telephoneNumber
            , Mobile        = mobile
            , QuickDial     = Pager
            , usnCreated
        FROM OPENROWSET(''ADSDSOObject'', '''', ''
                SELECT cn, givenName, sn, userAccountControl, lastLogon, displayName, samaccountname,
                title,  department, physicalDeliveryOfficeName, info, mail, telephoneNumber, mobile, pager, usncreated
            FROM ''''LDAP://[ldap-query-string]''''
            WHERE objectClass=''''Person''''
            AND objectClass = ''''User''''
            ' + @filter + '
            ORDER BY usnCreated'')'
    INSERT INTO #ADData EXEC (@Query)
    SELECT @Rowcount = @@ROWCOUNT
    SELECT @Filter = 'and usnCreated > '+ LTRIM(STR((SELECT MAX(usnCreated) FROM #ADData)))

END

SELECT LOGIN
        , CommonName
        , GivenName
        , FamilyName
        , DisplayName
        , Title
        , Department
        , Location
        , Email
        , Phone
        , QuickDial
        , Mobile
        , Info
        , Disabled      = CASE WHEN CAST (flags AS INT) & 2 > 0 THEN 'Y' ELSE NULL END
        , Locked        = CASE WHEN CAST (flags AS INT) & 16  > 0 THEN 'Y' ELSE NULL END
        , NoPwdExpiry   = CASE WHEN CAST (flags AS INT) & 65536  > 0 THEN 'Y' ELSE NULL END
        , LastLogin     = CASE WHEN ISNULL(CAST (LastLogin AS BIGINT),0) = 0 THEN NULL ELSE
                            DATEADD(ms, (CAST (LastLogin AS BIGINT) / CAST(10000 AS BIGINT)) % 86400000,
                            DATEADD(day, CAST (LastLogin AS BIGINT) / CAST(864000000000 AS BIGINT) - 109207, 0)) END
        , Type = CASE WHEN flags  & 512 = 512 THEN 'user'
                    WHEN flags IS NULL THEN 'contact'
                    WHEN flags & 4096 = 4096 THEN 'computer'
                    WHEN flags & 532480 = 532480 THEN 'computer (DC)' END
FROM #ADData
ORDER BY Login

DROP TABLE #ADData


问:
How do I do Entity Extraction in Lucene
I m trying to do Entity Extraction (more like matching) in Lucene. Here is a sample workflow:

Given some text (from a URL) AND a list people names, try to extract names of people from the text.

Note:

Names of people are not completely
  normalized. e.g. Some are Mr. X, Mrs.
  Y and some are just John Doe, X and Y.
  Other prefixes and suffixes to think
  about are Jr., Sr., Dr., I, II ...
  etc. (dont let me get started with non
  US names).

I am using Lucene MemoryIndex to create an in memory index of the text from each Url (stripping html tags) and am using StandardAnalyzer to query for the list of all names, one at a time (100k names, Is there any other way to do this? On an avg. this takes about 8 secs. on the average text I have).

A major problem is that to eliminate noise I m using a score of 0.01 as a base score and queries like "Mr. John Doe" have a significantly lower score as compared to "John Doe" if the text contains "John Doe" and in many cases miss the 0.01 threshold.

The other problem is that If I normalize all names and start removing all occurences of Dr. Mr. Mrs. etc. then I start missing good matches like "Dr. John Edward II" and end up with a lot of junk matches like "Mr. John Edward".

I understand that Lucene might not be the right tool for the job either, but so far it hasnt proved to be too bad. Any help appreciated.

答:
NEE is an NLP task that is not part of lucene. For open source, you can look at lingpipe and gate and opennlp. There are various for-money alternatives.

GATE is entirely rule-based, and will be hard to use for high precision. You'll need a statistical engine for that; lingpipe has one, but you have to supply the training data. I'm not up to date on the contents of opennlp in this area.

Title: How do I do Entity Extraction in Lucene


问:
SSIS Package only executes when windows account logged into server
This one is giving me a headache.

I have created some SSIS packages in Visual Studio 2015 with the following settings;

domain/user as
Project Protection Level: EncryptSensitiveWithPassword (password is same as domain/user)
Package Protection Level: EncryptSensitiveWithPassword (password is same as domain/user)

ODBC Connection is tested and working.

SSIS is from SQL Server 2014 => MySQL 5.6, both the 64 and 32 bit ODBC drivers are installed on the Windows Server 2012 box for MySQL.

Deployed package to Integration Service Catalogs.

When I run the package it works 100%, no errors.  But only when the AD account domain/user is logged into the Windows Server 2012 box that the SQL Server is implemented on.

When the domain/user is not logged in the package fails with the following error:

```<code>Package: Error: An ODBC error -1 has occurred.
Data Flow Task: Error. ODBC Destination failed validation and returned error code 0x80004005
Data Flow Task: Error: The AcquireConnection method call to the connection manager DATA_WH.root failed with error code 0xC0014009. There may be error messages posted before this with more information on why the AcquireConnection method call failed.
</code>```

On SQL Server:

Created Security..Logins..domain/user
Assigned serveradmin role
Mapped to SSISDB and msdb
Status is granted permission to connect to database
Login is enabled
Created credential called database_credential
identity: domain/user
password: same as domain/user
Mapped domain/user to a  database_credential

In SSIS job activity the job is set to run as database_credential as type SQL Server Integration Services Package.

As long as I am logged in as domain/user on the Windows Server, doesn't even need to be logged in to SQL Server the SSIS package runs perfectly.  When the user isn't logged in it falls over.

This is really confusing me.  I'm turning in circles and need some help.

Anyone any ideas?

答:
For anyone interested in this, or having the same issue, I implemented a workaround by creating a scheduled task in the windows task scheduler that ran the package using DTEXEC.exe from the command line.

It worked perfectly, the only issue is there is no history as you would normally get using the SSIS service in SQL Server, but on the upside it works regardless of the user being logged in or not.

Hope someone finds this useful.

Body:
This one is giving me a headache.

I have created some SSIS packages in Visual Studio 2015 with the following settings;

domain/user as
Project Protection Level: EncryptSensitiveWithPassword (password is same as domain/user)
Package Protection Level: EncryptSensitiveWithPassword (password is same as domain/user)

ODBC Connection is tested and working.

SSIS is from SQL Server 2014 => MySQL 5.6, both the 64 and 32 bit ODBC drivers are installed on the Windows Server 2012 box for MySQL.

Deployed package to Integration Service Catalogs.

When I run the package it works 100%, no errors.  But only when the AD account domain/user is logged into the Windows Server 2012 box that the SQL Server is implemented on.

When the domain/user is not logged in the package fails with the following error:

Package: Error: An ODBC error -1 has occurred.
Data Flow Task: Error. ODBC Destination failed validation and returned error code 0x80004005
Data Flow Task: Error: The AcquireConnection method call to the connection manager DATA_WH.root failed with error code 0xC0014009. There may be error messages posted before this with more information on why the AcquireConnection method call failed.

On SQL Server:

Created Security..Logins..domain/user
Assigned serveradmin role
Mapped to SSISDB and msdb
Status is granted permission to connect to database
Login is enabled
Created credential called database_credential
identity: domain/user
password: same as domain/user
Mapped domain/user to a  database_credential

In SSIS job activity the job is set to run as database_credential as type SQL Server Integration Services Package.

As long as I am logged in as domain/user on the Windows Server, doesn't even need to be logged in to SQL Server the SSIS package runs perfectly.  When the user isn't logged in it falls over.

This is really confusing me.  I'm turning in circles and need some help.

Anyone any ideas?


问:
How to download information?
Currently, I have the following that downloads all files under an AWS (Amazon Web Services) S3 bucket.</p>

答:
To do this in boto3, you could do something like this:

```<code>import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for object_summary in bucket.objects.all():
    print(object_summary.key)
    print(object_summary.last_modified)
</code>```

In this case boto3 will handle all pagination so you won't be limited to only the first page of results.

Is that what you are trying to do?

Title: How to download information?

Body:
To do this in boto3, you could do something like this:

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for object_summary in bucket.objects.all():
    print(object_summary.key)
    print(object_summary.last_modified)

In this case boto3 will handle all pagination so you won't be limited to only the first page of results.

Is that what you are trying to do?


问:
Pandas Apply with Idmax Incorrectly Converts Mixed Object Columns to Floats
So I have various columns in my dataset that are a mix of integers and strings. Trying to remove duplicates, I convert each column in the row to a string, get the length of it, and add that length as an extra column:

```<code>import pandas as pd
import datetime

r1 = [datetime.date(2016, 7, 10), 'M']
r2 = [datetime.date(2014, 11, 26), 0]
r3 = [datetime.date(2015, 8, 13), 'M']
r4 = [datetime.date(2015, 5, 11), 'OPSTC']
r5 = [datetime.date(2014, 1, 31), 'FMS']
df = pd.DataFrame([r1, r2, r3, r4, r5], columns=['date', 'mix'])
df['date'] = pd.to_datetime(df['date'])

def f(row):
    return(row.apply(lambda x: len(str(x))).sum())

df['width'] = df.apply(f, axis=1)
df

    date        mix     width
0   2016-07-10  M       20
1   2014-11-26  0       20
2   2015-08-13  M       20
3   2015-05-11  OPSTC   24
4   2014-01-31  FMS     22

for column in df.columns:
    print(column, df[column].dtype)

date  datetime64[ns]
mix   object
width int64
</code>```

This does not create any problems. The problem happens when I group the rows and eliminate those that don't have the highest row total:

```<code>def f(rows):
    rows.applymap(str) # Even putting this in here has no effect!

    return(rows.ix[rows['width'].idxmax()])

df = df.groupby(['date'], as_index=False).apply(f)
df = df.reset_index(drop=True)
df

    date        mix width
0   2014-01-31  NaN 22
1   2014-11-26  0.0 20
2   2015-05-11  NaN 24
3   2015-08-13  NaN 20
4   2016-07-10  NaN 20
</code>```

It is converting the mixed object columns to floats. You can group by either mix or date to reproduce the problem. Converting the columns to strings (either by using .apply(str) or .astype(str)) has no effect.

I am using Python 3.5.2.final.0 and Pandas 0.18.1.

答:
There are a few points of failure here

failed to assign to variable

```<code>def f(rows):
    rows.applymap(str)  # this doesn't get assigned
    return rows.ix[rows['width'].idxmax()]
</code>```

don't use ix.  Doesn't effect anything here.  But it will be deprecated.

Super subtle and dangerous point... row.ix[rows['width'].idxmax()] returns a pd.Series.  Why is this important?  At the moment I can't nail down the entire story (I'm working on it).  But, when you return a pd.Series pandas is conducting some inferrecne and determined that 'mix' ought to be numeric.  The apply method for a groupby object passes a pd.DataFrame object to the function being applied.  You can fix this by changign the scalar rows['width'].idxmax() to the array-like [rows['width'].idxmax()]

```<code>def f(rows):
    return rows.loc[[rows['width'].idxmax()]]

print(df.groupby(['date'], as_index=False).apply(f))

           date    mix  width
0 4 2014-01-31    FMS     22
1 1 2014-11-26      0     20
2 3 2015-05-11  OPSTC     24
3 2 2015-08-13      M     20
4 0 2016-07-10      M     20
</code>```

Ok, so the dtypes make sense again, but you haven't eliminated anything because you grouped by date which where all unique.  Not sure what you wanted here but this is a guess.

```<code>df.query('width == @df.width.max()')
# equivalently
# df[df.width == df.width.max()]

        date    mix  width
3 2015-05-11  OPSTC     24
</code>```

Body:
So I have various columns in my dataset that are a mix of integers and strings. Trying to remove duplicates, I convert each column in the row to a string, get the length of it, and add that length as an extra column:

import pandas as pd
import datetime

r1 = [datetime.date(2016, 7, 10), 'M']
r2 = [datetime.date(2014, 11, 26), 0]
r3 = [datetime.date(2015, 8, 13), 'M']
r4 = [datetime.date(2015, 5, 11), 'OPSTC']
r5 = [datetime.date(2014, 1, 31), 'FMS']
df = pd.DataFrame([r1, r2, r3, r4, r5], columns=['date', 'mix'])
df['date'] = pd.to_datetime(df['date'])

def f(row):
    return(row.apply(lambda x: len(str(x))).sum())

df['width'] = df.apply(f, axis=1)
df

    date        mix     width
0   2016-07-10  M       20
1   2014-11-26  0       20
2   2015-08-13  M       20
3   2015-05-11  OPSTC   24
4   2014-01-31  FMS     22

for column in df.columns:
    print(column, df[column].dtype)

date  datetime64[ns]
mix   object
width int64

This does not create any problems. The problem happens when I group the rows and eliminate those that don't have the highest row total:

def f(rows):
    rows.applymap(str) # Even putting this in here has no effect!

    return(rows.ix[rows['width'].idxmax()])

df = df.groupby(['date'], as_index=False).apply(f)
df = df.reset_index(drop=True)
df

    date        mix width
0   2014-01-31  NaN 22
1   2014-11-26  0.0 20
2   2015-05-11  NaN 24
3   2015-08-13  NaN 20
4   2016-07-10  NaN 20

It is converting the mixed object columns to floats. You can group by either mix or date to reproduce the problem. Converting the columns to strings (either by using .apply(str) or .astype(str)) has no effect.

I am using Python 3.5.2.final.0 and Pandas 0.18.1.

Body:
There are a few points of failure here

failed to assign to variable

def f(rows):
    rows.applymap(str)  # this doesn't get assigned
    return rows.ix[rows['width'].idxmax()]

don't use ix.  Doesn't effect anything here.  But it will be deprecated.

Super subtle and dangerous point... row.ix[rows['width'].idxmax()] returns a pd.Series.  Why is this important?  At the moment I can't nail down the entire story (I'm working on it).  But, when you return a pd.Series pandas is conducting some inferrecne and determined that 'mix' ought to be numeric.  The apply method for a groupby object passes a pd.DataFrame object to the function being applied.  You can fix this by changign the scalar rows['width'].idxmax() to the array-like [rows['width'].idxmax()]

def f(rows):
    return rows.loc[[rows['width'].idxmax()]]

print(df.groupby(['date'], as_index=False).apply(f))

           date    mix  width
0 4 2014-01-31    FMS     22
1 1 2014-11-26      0     20
2 3 2015-05-11  OPSTC     24
3 2 2015-08-13      M     20
4 0 2016-07-10      M     20

Ok, so the dtypes make sense again, but you haven't eliminated anything because you grouped by date which where all unique.  Not sure what you wanted here but this is a guess.

df.query('width == @df.width.max()')
# equivalently
# df[df.width == df.width.max()]

        date    mix  width
3 2015-05-11  OPSTC     24


问:
How to wait for async to finish
I would like to run some async workflow, then wait for it to finish before printing some results, example:

```<code>let dowork n =
    async {
        do printfn "work %d" n
    }

let creatework() =
    async {
        for x in [1..5] do
            Async.Start(dowork x)
    }

Async.RunSynchronously(creatework())
printfn "finished"
</code>```

when I run this, I want all the dowork calls to finish before printing "finished". However I get results like this:

work 2
work 3
work 4
work 5
finished
work 1

I have tried removing async from creatework() but "finished" is printed before the async workflows are run.

In the real dowork, the program performs some IO, so I want to wait for the slowest one to finish before continuing.

答: I found that it's convenient to use MailboxProcessor to make sure that all side-effects (e.g. printfn) happen on the same thread.  Use MailboxProcessor.PostAndReply(singleResult) to funnel work results (be it just the strings to print) into the same synchronization context, and provide for another message type that returns aggregate values.  One could use a union for types of these messages.</p>

Title: How to wait for async to finish

Body:
I would like to run some async workflow, then wait for it to finish before printing some results, example:

let dowork n =
    async {
        do printfn "work %d" n
    }

let creatework() =
    async {
        for x in [1..5] do
            Async.Start(dowork x)
    }

Async.RunSynchronously(creatework())
printfn "finished"

when I run this, I want all the dowork calls to finish before printing "finished". However I get results like this:

work 2
work 3
work 4
work 5
finished
work 1

I have tried removing async from creatework() but "finished" is printed before the async workflows are run.

In the real dowork, the program performs some IO, so I want to wait for the slowest one to finish before continuing.


问:
How can I implement std::fmt::Display for a custom IntoIterator::Item?
LimitedFifoQueue is a struct that wraps the functionality of a VecDeque to limit the number of items it will store at any time:

```<code>use std::collections::{vec_deque, VecDeque};
use std::fmt;
use std;

#[derive(Debug)]
pub struct LimitedFifoQueue<T> {
    size: usize,
    store: VecDeque<T>,
}

impl<T> LimitedFifoQueue<T> where T: fmt::Display {
    pub fn new(size: usize) -> LimitedFifoQueue<T> {
        LimitedFifoQueue {
            size: size,
            store: VecDeque::with_capacity(size),
        }
    }
    pub fn push(&mut self, elem: T) {
        self.store.push_front(elem);
        if self.store.len() > self.size {
            self.store.pop_back();
        }
    }
    pub fn clear(&mut self) {
        self.store.clear();
    }
}
</code>```

I've implemented the IntoIterator trait as follows:

```<code>impl<T> IntoIterator for LimitedFifoQueue<T> where T: fmt::Display {
    type Item = T;
    type IntoIter = vec_deque::IntoIter<T>;
    fn into_iter(self) -> Self::IntoIter {
        self.store.into_iter()
    }
}
</code>```

And a simplified function that loops through and prints each Item:

```<code>fn print_all<I>(lines: &I) where I: IntoIterator {
    for string in lines.into_iter() {
        println!("{}", string);
    }
}
</code>```

This gives me the following error:

println!("{}", string);
               ^^^^^^ the trait `std::fmt::Display` is not implemented for `<I as std::iter::IntoIterator>::Item`
```

I have created a playground of the code with a full stack trace here.

Also, I'm aware that there may be a better way to accomplish what I'm trying to do. I'd love to hear any additional suggestions.

答:
How can I implement std::fmt::Display for a custom IntoIterator::Item?

You cannot. Item might be a type you don't own, and Display is a trait you don't own. You cannot implement a trait you don't own for a type you don't own.

All you can do is require that Item implements Display:

```<code>fn print_all<I>(lines: I)
    where I: IntoIterator,
          I::Item: fmt::Display,
{
    for string in lines.into_iter() {
        println!("{}", string);
    }
}
</code>```

You don't need any of the other T: Display bounds on your data structure or its methods, as none of those implementations care to print out a value.

Incidentally, into_iter is automatically called on the for-loops argument, so you only need to say:

```<code>fn print_all<I>(lines: I)
    where I: IntoIterator,
          I::Item: fmt::Display,
{
    for string in lines {
        println!("{}", string);
    }
}
</code>```

You may also wish to review How to implement Iterator and IntoIterator for a simple struct?, as you are passing &lfq into print_all, but &LimitedFifoQueue doesn't implement IntoIterator, only LimitedFifoQueue does. These are different types. You'll need something like

```<code>impl<'a, T> IntoIterator for &'a LimitedFifoQueue<T> {
    type Item = &'a T;
    type IntoIter = vec_deque::Iter<'a, T>;
    fn into_iter(self) -> Self::IntoIter {
        self.store.iter()
    }
}
</code>```

Body:
LimitedFifoQueue is a struct that wraps the functionality of a VecDeque to limit the number of items it will store at any time:

use std::collections::{vec_deque, VecDeque};
use std::fmt;
use std;

#[derive(Debug)]
pub struct LimitedFifoQueue<T> {
    size: usize,
    store: VecDeque<T>,
}

impl<T> LimitedFifoQueue<T> where T: fmt::Display {
    pub fn new(size: usize) -> LimitedFifoQueue<T> {
        LimitedFifoQueue {
            size: size,
            store: VecDeque::with_capacity(size),
        }
    }
    pub fn push(&mut self, elem: T) {
        self.store.push_front(elem);
        if self.store.len() > self.size {
            self.store.pop_back();
        }
    }
    pub fn clear(&mut self) {
        self.store.clear();
    }
}

I've implemented the IntoIterator trait as follows:

impl<T> IntoIterator for LimitedFifoQueue<T> where T: fmt::Display {
    type Item = T;
    type IntoIter = vec_deque::IntoIter<T>;
    fn into_iter(self) -> Self::IntoIter {
        self.store.into_iter()
    }
}

And a simplified function that loops through and prints each Item:

fn print_all(lines: &I) where I: IntoIterator {
    for string in lines.into_iter() {
        println!("{}", string);
    }
}

This gives me the following error:

println!("{}", string);
               ^^^^^^ the trait `std::fmt::Display` is not implemented for `<I as std::iter::IntoIterator>::Item`

I have created a playground of the code with a full stack trace here.

Also, I'm aware that there may be a better way to accomplish what I'm trying to do. I'd love to hear any additional suggestions.

Body:
How can I implement std::fmt::Display for a custom IntoIterator::Item?

You cannot. Item might be a type you don't own, and Display is a trait you don't own. You cannot implement a trait you don't own for a type you don't own.

All you can do is require that Item implements Display:

fn print_all<I>(lines: I)
    where I: IntoIterator,
          I::Item: fmt::Display,
{
    for string in lines.into_iter() {
        println!("{}", string);
    }
}

You don't need any of the other T: Display bounds on your data structure or its methods, as none of those implementations care to print out a value.

Incidentally, into_iter is automatically called on the for-loops argument, so you only need to say:

fn print_all<I>(lines: I)
    where I: IntoIterator,
          I::Item: fmt::Display,
{
    for string in lines {
        println!("{}", string);
    }
}

You may also wish to review How to implement Iterator and IntoIterator for a simple struct?, as you are passing &lfq into print_all, but &LimitedFifoQueue doesn't implement IntoIterator, only LimitedFifoQueue does. These are different types. You'll need something like

impl<'a, T> IntoIterator for &'a LimitedFifoQueue<T> {
    type Item = &'a T;
    type IntoIter = vec_deque::Iter<'a, T>;
    fn into_iter(self) -> Self::IntoIter {
        self.store.iter()
    }
}


问:
How do you scroll a list in AppMaker?
I have a list widget with five rows per page.  When the user goes to the next page I reload the page (by doing an unload/load on the data source with the new page number) and that works fine.  However, the list stays scrolled to the bottom.  How can I scroll the list to the top so the user does not have to?

I tried the ways that work in standard HTML but they do not work in AppMaker, and I cannot find any documentation on how to do this.

Thanks for any tips or pointers.

答:
You can achieve the desired behavior by doing the following:

In the outline, locate the TablePanel widget and select the List:TableBody widget

2.In the property editor, scroll to the Events section and click on the onDataLoad event value. Then click on Custom Action.

Type in this code var elem = widget.getElement(); elem.scrollTop = 0; so that it looks like this

Make sure the change is saved and then preview your app and it should work. Let me know if you need something else or if it don't work.

Title: How do you scroll a list in AppMaker?


问:
Weird characters in MPI_File_write
I copied the following example from  Using MPI-2: Advanced Features of the Message-Passing Interface but the output file is just weired characters. I tried to change the data types from int to char but the output is still the same. I tried to open the open the outputfile with different programs like Notepadqq and gedit. I tried also to open the file with different file formats and adding null pointer to the end of the file through process zero but the results are still weired characters.</p>

```<code>/* example of parallel MPI write into a single file */
#include <stdio.h>
#include "mpi.h"
#define BUFSIZE 100

int main( int argc, char **argv )

{
    int i, MyRank, NumProcs, buf[BUFSIZE];
    MPI_File TheFile;
    MPI_Status status;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &MyRank);
    MPI_Comm_size(MPI_COMM_WORLD,&NumProcs);
    for (i=0; i<BUFSIZE; i++)
        buf[i]=MyRank*BUFSIZE+i;
    MPI_File_open(MPI_COMM_WORLD, "testfile",MPI_MODE_CREATE|MPI_MODE_WRONLY,MPI_INFO_NULL, &TheFile);
    MPI_File_set_view(TheFile,MyRank*BUFSIZE*sizeof(int),MPI_INT,MPI_INT,"native",MPI_INFO_NULL);
    MPI_File_write(TheFile,buf,BUFSIZE,MPI_INT,MPI_STATUS_IGNORE);
// THis is my trial
    if(MyRank == 0){
        char nullChar = '\0';
        MPI_File_write(TheFile, & nullChar , 1 , MPI_CHAR ,MPI_STATUS_IGNORE );
    }

    MPI_File_close(&TheFile);
    MPI_Finalize();
    return 0;
}
</code>```

答: Because you are opening a binary file and you expect to see meaningful characters (not gonna happen). Look here for the difference between binary and text files. You can always read the data with MPI_File_read().

Title: Weird characters in MPI_File_write

Body:
I copied the following example from  Using MPI-2: Advanced Features of the Message-Passing Interface but the output file is just weired characters. I tried to change the data types from int to char but the output is still the same. I tried to open the open the outputfile with different programs like Notepadqq and gedit. I tried also to open the file with different file formats and adding null pointer to the end of the file through process zero but the results are still weired characters.

/* example of parallel MPI write into a single file */
#include <stdio.h>
#include "mpi.h"
#define BUFSIZE 100

int main( int argc, char **argv )

{
    int i, MyRank, NumProcs, buf[BUFSIZE];
    MPI_File TheFile;
    MPI_Status status;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &MyRank);
    MPI_Comm_size(MPI_COMM_WORLD,&NumProcs);
    for (i=0; i<BUFSIZE; i++)
        buf[i]=MyRank*BUFSIZE+i;
    MPI_File_open(MPI_COMM_WORLD, "testfile",MPI_MODE_CREATE|MPI_MODE_WRONLY,MPI_INFO_NULL, &TheFile);
    MPI_File_set_view(TheFile,MyRank*BUFSIZE*sizeof(int),MPI_INT,MPI_INT,"native",MPI_INFO_NULL);
    MPI_File_write(TheFile,buf,BUFSIZE,MPI_INT,MPI_STATUS_IGNORE);
// THis is my trial
    if(MyRank == 0){
        char nullChar = '\0';
        MPI_File_write(TheFile, & nullChar , 1 , MPI_CHAR ,MPI_STATUS_IGNORE );
    }

    MPI_File_close(&TheFile);
    MPI_Finalize();
    return 0;
}


答:
This problem has nothing to do with your IntoIterator implementation or the rest of your type definition. Just take a look at this code:

```<code>fn print_all<I>(lines: &I) where I: IntoIterator {
    for string in lines.into_iter() {
        println!("{}", string);
    }
}
</code>```

This piece of code doesn't even know about your LimitedFifoQueue type! It takes a value of generic type I. What do we know about I? It implements IntoIterator. Great, what does that tell us about the values the iterator will spit out? Nothing!

So it could be anything, in particular also stuff that doesn't implement fmt::Display. So what we want to do is to annotate that the items of the iterator should at least implement fmt::Display. How is that done? By adding a bound to the associated type Item of the IntoIterator trait:

```<code>fn print_all<I>(lines: &I)
    where I: IntoIterator,
          I::Item: fmt::Display,
{ ... }
</code>```

Once you understand that you can also add bounds to associated items this makes intuitive sense.

After you fixed that error, another error will be reported, about "moving out of borrowed content". This is a fairly standard error, which I won't explain in detail here. But in summary: your print_all() function should receive a I instead of a &I.

Title: How can I implement std::fmt::Display for a custom IntoIterator::Item?

Body:
This problem has nothing to do with your IntoIterator implementation or the rest of your type definition. Just take a look at this code:

fn print_all<I>(lines: &I) where I: IntoIterator {
    for string in lines.into_iter() {
        println!("{}", string);
    }
}

This piece of code doesn't even know about your LimitedFifoQueue type! It takes a value of generic type I. What do we know about I? It implements IntoIterator. Great, what does that tell us about the values the iterator will spit out? Nothing!

So it could be anything, in particular also stuff that doesn't implement fmt::Display. So what we want to do is to annotate that the items of the iterator should at least implement fmt::Display. How is that done? By adding a bound to the associated type Item of the IntoIterator trait:

fn print_all<I>(lines: &I)
    where I: IntoIterator,
          I::Item: fmt::Display,
{ ... }

Once you understand that you can also add bounds to associated items this makes intuitive sense.

After you fixed that error, another error will be reported, about "moving out of borrowed content". This is a fairly standard error, which I won't explain in detail here. But in summary: your print_all() function should receive a I instead of a &I.


问:
Apache camel in desktop
Is it possible to use Apache camel in a desktop application?

And how can I store the result of a route (like weather) in a string so I can show it on a JLabel?

答:
Sure it is possible.

result of a route

is in Camel Exchange at last to component on the route

So per Camel documentation Pojo Consuming

Use the Bean endpoint:
  You can always use the bean endpoint
  from(uri).to("bean:myBean?method=methodName");

then if you have a bean with method which accepts appropriate Class (e.g. your weather) as parameter you have your route result.
Then you can do with it whatever you want to.

Or last component in route can be an implementation of Camel Processor interface (Camel process component) which will do the same, but extract Body from camel Exchange is up to you.

Title: Apache camel in desktop


问:
Searching for max value in an array of JSON objects
I have an array of JSON Objects that looks like the below sample:

```<code>    [ { _id: 58d98fc46cb2342d6848ae3,
    updateNumber: '1',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 17:06:00 GMT-0400 (EDT),
    update: 'update 1',
    subject: 'test1',
    impact: 'test1',
    incidentNumber: '12345',
    wasNew: true,
    __v: 0 },
  { _id: 58d880126fb5087d684c8de4,
    updateNumber: '2',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 18:06:00 GMT-0400 (EDT),
    update: 'update 2',
    subject: 'test1',
    impact: 'test1',
    incidentNumber: '12345',
    wasNew: true,
    __v: 0 },
  { _id: 58c23ae21bt2743d6328ae3,
    updateNumber: '1',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 17:06:00 GMT-0400 (EDT),
    update: 'update 1',
    subject: 'test2',
    impact: 'test2',
    incidentNumber: '23456',
    wasNew: true,
    __v: 0 } ]
</code>```

What I need to be able to do is for each incidentnumber, grab the latest update. Each incidentNumber will have multiple updates and I want to be able to retrieve the latest update (In the above example that is update 2 for incidentNumber 12345 and update 1 for incidentNumber 23456)

So far I have tried variations of _.max which will only work for one incidentNumber and not multiple.

I have searched extensively and so far have not found any questions that involved the same dataset I have.

Can anyone point me in the right direction on how to start solving this problem?

Thanks

答:
To get all incidents latest update, you can do the following where:

arr is your array of of incidents

id is your identifier

counter is what you are comparing the value of

function getLatestUpdate(arr, id, counter) {
  var _latest = [];
  var latest = [];

  while (arr.length) {
    var item = arr.shift();
    var currentUpdate = _latest[item[id]];

    _latest[item[id]] = (!currentUpdate) ? item : (currentUpdate[counter] > item[counter] ? currentUpdate : item);
  }

  for(key in _latest) {
    latest.push(_latest[key]);
  }

  return latest;
}

var latest = getLatestUpdate(arr, '_id', 'updateNumber');
```

If may not be the most efficient, but it takes advantage of arrays being objects and comparing the value of the object's counter while filtering through the array, then pushing the objects that exist to the array upon completion and destroying the key/value pairs that were being stored there.

Body:
I have an array of JSON Objects that looks like the below sample:

    [ { _id: 58d98fc46cb2342d6848ae3,
    updateNumber: '1',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 17:06:00 GMT-0400 (EDT),
    update: 'update 1',
    subject: 'test1',
    impact: 'test1',
    incidentNumber: '12345',
    wasNew: true,
    __v: 0 },
  { _id: 58d880126fb5087d684c8de4,
    updateNumber: '2',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 18:06:00 GMT-0400 (EDT),
    update: 'update 2',
    subject: 'test1',
    impact: 'test1',
    incidentNumber: '12345',
    wasNew: true,
    __v: 0 },
  { _id: 58c23ae21bt2743d6328ae3,
    updateNumber: '1',
    resolution: 'tbd',
    nextUpdate: Mon Mar 27 2017 17:06:00 GMT-0400 (EDT),
    update: 'update 1',
    subject: 'test2',
    impact: 'test2',
    incidentNumber: '23456',
    wasNew: true,
    __v: 0 } ]

What I need to be able to do is for each incidentnumber, grab the latest update. Each incidentNumber will have multiple updates and I want to be able to retrieve the latest update (In the above example that is update 2 for incidentNumber 12345 and update 1 for incidentNumber 23456)

So far I have tried variations of _.max which will only work for one incidentNumber and not multiple.

I have searched extensively and so far have not found any questions that involved the same dataset I have.

Can anyone point me in the right direction on how to start solving this problem?

Thanks

Body:
To get all incidents latest update, you can do the following where:

arr is your array of of incidents

id is your identifier

counter is what you are comparing the value of

function getLatestUpdate(arr, id, counter) {
  var _latest = [];
  var latest = [];

  while (arr.length) {
    var item = arr.shift();
    var currentUpdate = _latest[item[id]];

    _latest[item[id]] = (!currentUpdate) ? item : (currentUpdate[counter] > item[counter] ? currentUpdate : item);
  }

  for(key in _latest) {
    latest.push(_latest[key]);
  }

  return latest;
}

var latest = getLatestUpdate(arr, '_id', 'updateNumber');

If may not be the most efficient, but it takes advantage of arrays being objects and comparing the value of the object's counter while filtering through the array, then pushing the objects that exist to the array upon completion and destroying the key/value pairs that were being stored there.


问:
Where does gitosis store the working copies?
i wonder where gitosis stores the working copies of my repositories. I can see the filetree with the gitweb interface but cant find any working copy in /srv/gitosis/repositories/testrepo. Iam also able to push and clone to the repo.

But how can i manage to write my deploy-script without knowing the path of the working copy?

答: gitosis stores repositories bare, that is, without a working directory at all.  You will have to clone /srv/gitosis/repositories/testrepo somewhere else for deployment.