问:
Generate excel from html

I am trying to generate excel file and my data is in the form of HTML string. I have an HTML table with few columns and rows. I am generating one huge HTML table with n rows and n column in java and saving that string into a flat file and naming that file as mydata.html or mydata.xls. When this file is opened using Microsoft Excel, it shows the table in the column-wise format. The document is rendered perfectly fine. This is the simplest way to generate the file in excel.

Please find attached the sample HTML file. Save this file as mydata.html or mydata.xls and open it using Microsoft excel. If saved as .xls, click yes in the excel dialog box at the time of opening.

<!DOCTYPE html>

    Column 1
    Column 2
    Column 3

    Row 1  Column 1

     Paragraph 1 . This is a large text which spills over multiple lines.Java is at the heart of our digital lifestyle. It's the platform for launching careers, exploring human-to-digital interfaces, architecting the world's best applications, and unlocking innovation everywhere from garages to global organizations. When it comes to building computer programming skills, learning Java will take you way beyond the games of your childhood. Knowing Java will be a clear advantage in your future career. Learning Java can be a skill for a career, or a skill for fun or both. Students of all ages have built amazing things, from hobby projects to world-changing initiatives. Oracle Academy Workshops are designed to make first experiences with computing fun and engaging, while still leveraging best academic curriculum practices like project-based learning and offering educators methods for assessment. Oracle Academy Workshops are best used by educators in one of three ways: to introduce students, including students as young as late primary school ages, to computer science in a fun and engaging way;
  to incorporate exposure to computer science into the teaching of other academic disciplines; and
  to offer a limited introduction to computer science to students via extra-curricular programs and/or workshop experiences.

Paragraph 2  --> Like our Getting Started with Java Using Alice Workshop, this freely available course is designed for teachers, students and individuals with little or no programming experience and teaches basic Java programming concepts through developing 3-D animations in Alice 3.1. Alice is a free, educational, introductory Java development environment created at Carnegie Mellon University. While it is suitable for all beginning learners, it can be especially engaging for girls. Learners will have fun creating animated stories and games using objects and characters from a rich gallery of 3-D models.

Paragraph 3   Oracle Academy Workshops are also available to Individual and Institutional members in Workshop in a Box formats to facilitate the delivery of introductory computer science workshops by parents, volunteers, computer club sponsors and educators who may not specialize in teaching computer science

     Paragraph 1 .
      When you learn Java, youre learning more than just a language. Because Java is a technology platform with many interconnected capabilities that can give cutting-edge, in-demand job skills. In fact, Java tops Inc.coms list of the ten most popular programming languages. Java can take you where you want to go. Learn how to create games, simulations and other graphical programs using basic Java programming via free educational Java development environments from Carnegie Mellon University (Alice) and the University of Kent (Greenfoot). No prior programming or computer science experience is required.

     Paragraph 2 .
     Oracle Academy self-study courses are designed to provide a self-paced learning experience for teachers, students and individuals.

Paragraph 3 Oracle Academy Workshop in a Box are designed to facilitate the delivery of introductory computer science workshops by parents, volunteers, computer club sponsors and educators who may not specialize in teaching computer science.

```

However, I am facing one major problem. Any paragraph (P tag) or the line break(using
 tag) causes the adjacent cells to jump to the next row. Please open the attached HTML file using excel. The column 2 and column 3 have 3 paragraph in them. Please observe the alignment of paragraph 2  of column 3. Paragraph 2 of column 3 doesn't start right after paragraph 1, it rather starts in same line as paragraph 2 of column 2. There is a lot of blank spaces above the paragraph 2 of column 3. I want the paragraph 2 should start right after the paragraph 1.  If the html file is opened in browser, the alignment of paragraph is perfect.

I want the paragraph 2 should start right after the paragraph 1. Please find attached the image file.

答:
you can use the line break tag
 instead of the paragraph tag
, just add the style .... style="mso-data-placement:same-cell;" .. here is your example

<!DOCTYPE html>

    Column 1
    Column 2
    Column 3

    Row 1  Column 1

     Paragraph 1 . This is a large text which spills over multiple lines.Java is at the heart of our digital lifestyle. It's the platform for launching careers, exploring human-to-digital interfaces, architecting the world's best applications, and unlocking innovation everywhere from garages to global organizations. When it comes to building computer programming skills, learning Java will take you way beyond the games of your childhood. Knowing Java will be a clear advantage in your future career. Learning Java can be a skill for a career, or a skill for fun or both. Students of all ages have built amazing things, from hobby projects to world-changing initiatives. Oracle Academy Workshops are designed to make first experiences with computing fun and engaging, while still leveraging best academic curriculum practices like project-based learning and offering educators methods for assessment. Oracle Academy Workshops are best used by educators in one of three ways: to introduce students, including students as young as late primary school ages, to computer science in a fun and engaging way;
  to incorporate exposure to computer science into the teaching of other academic disciplines; and
  to offer a limited introduction to computer science to students via extra-curricular programs and/or workshop experiences.

  Paragraph 2  --> Like our Getting Started with Java Using Alice Workshop, this freely available course is designed for teachers, students and individuals with little or no programming experience and teaches basic Java programming concepts through developing 3-D animations in Alice 3.1. Alice is a free, educational, introductory Java development environment created at Carnegie Mellon University. While it is suitable for all beginning learners, it can be especially engaging for girls. Learners will have fun creating animated stories and games using objects and characters from a rich gallery of 3-D models.

  Paragraph 3   Oracle Academy Workshops are also available to Individual and Institutional members in Workshop in a Box formats to facilitate the delivery of introductory computer science workshops by parents, volunteers, computer club sponsors and educators who may not specialize in teaching computer science

     Paragraph 1 .
      When you learn Java, youre learning more than just a language. Because Java is a technology platform with many interconnected capabilities that can give cutting-edge, in-demand job skills. In fact, Java tops Inc.coms list of the ten most popular programming languages. Java can take you where you want to go. Learn how to create games, simulations and other graphical programs using basic Java programming via free educational Java development environments from Carnegie Mellon University (Alice) and the University of Kent (Greenfoot). No prior programming or computer science experience is required.

     Paragraph 2 .
     Oracle Academy self-study courses are designed to provide a self-paced learning experience for teachers, students and individuals.

     Paragraph 3 Oracle Academy Workshop in a Box are designed to facilitate the delivery of introductory computer science workshops by parents, volunteers, computer club sponsors and educators who may not specialize in teaching computer science.

```

And here's the result  CLICK FOR THE RESULT IN EXCEL

Title: Generate excel from html

Body:
I am trying to generate excel file and my data is in the form of HTML string. I have an HTML table with few columns and rows. I am generating one huge HTML table with n rows and n column in java and saving that string into a flat file and naming that file as mydata.html or mydata.xls. When this file is opened using Microsoft Excel, it shows the table in the column-wise format. The document is rendered perfectly fine. This is the simplest way to generate the file in excel.

Please find attached the sample HTML file. Save this file as mydata.html or mydata.xls and open it using Microsoft excel. If saved as .xls, click yes in the excel dialog box at the time of opening.

<!DOCTYPE html>

    Column 1
    Column 2
    Column 3

    Row 1  Column 1

     Paragraph 1 . This is a large text which spills over multiple lines.Java is at the heart of our digital lifestyle. It's the platform for launching careers, exploring human-to-digital interfaces, architecting the world's best applications, and unlocking innovation everywhere from garages to global organizations. When it comes to building computer programming skills, learning Java will take you way beyond the games of your childhood. Knowing Java will be a clear advantage in your future career. Learning Java can be a skill for a career, or a skill for fun or both. Students of all ages have built amazing things, from hobby projects to world-changing initiatives. Oracle Academy Workshops are designed to make first experiences with computing fun and engaging, while still leveraging best academic curriculum practices like project-based learning and offering educators methods for assessment. Oracle Academy Workshops are best used by educators in one of three ways: to introduce students, including students as young as late primary school ages, to computer science in a fun and engaging way;
  to incorporate exposure to computer science into the teaching of other academic disciplines; and
  to offer a limited introduction to computer science to students via extra-curricular programs and/or workshop experiences.

Paragraph 2  --> Like our Getting Started with Java Using Alice Workshop, this freely available course is designed for teachers, students and individuals with little or no programming experience and teaches basic Java programming concepts through developing 3-D animations in Alice 3.1. Alice is a free, educational, introductory Java development environment created at Carnegie Mellon University. While it is suitable for all beginning learners, it can be especially engaging for girls. Learners will have fun creating animated stories and games using objects and characters from a rich gallery of 3-D models.

Paragraph 3   Oracle Academy Workshops are also available to Individual and Institutional members in Workshop in a Box formats to facilitate the delivery of introductory computer science workshops by parents, volunteers, computer club sponsors and educators who may not specialize in teaching computer science

     Paragraph 1 .
      When you learn Java, youre learning more than just a language. Because Java is a technology platform with many interconnected capabilities that can give cutting-edge, in-demand job skills. In fact, Java tops Inc.coms list of the ten most popular programming languages. Java can take you where you want to go. Learn how to create games, simulations and other graphical programs using basic Java programming via free educational Java development environments from Carnegie Mellon University (Alice) and the University of Kent (Greenfoot). No prior programming or computer science experience is required.

     Paragraph 2 .
     Oracle Academy self-study courses are designed to provide a self-paced learning experience for teachers, students and individuals.

Paragraph 3 Oracle Academy Workshop in a Box are designed to facilitate the delivery of introductory computer science workshops by parents, volunteers, computer club sponsors and educators who may not specialize in teaching computer science.

However, I am facing one major problem. Any paragraph (P tag) or the line break(using
 tag) causes the adjacent cells to jump to the next row. Please open the attached HTML file using excel. The column 2 and column 3 have 3 paragraph in them. Please observe the alignment of paragraph 2  of column 3. Paragraph 2 of column 3 doesn't start right after paragraph 1, it rather starts in same line as paragraph 2 of column 2. There is a lot of blank spaces above the paragraph 2 of column 3. I want the paragraph 2 should start right after the paragraph 1.  If the html file is opened in browser, the alignment of paragraph is perfect.

I want the paragraph 2 should start right after the paragraph 1. Please find attached the image file.

Body:
you can use the line break tag <br> instead of the paragraph tag <p>, just add the style .... style="mso-data-placement:same-cell;" .. here is your example

<!DOCTYPE html>
<html>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    border: 1px solid #dddddd;
    width: 75%;
    valign:top;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
    valign:top;
    width: 25%;
}

tr:nth-child(even) {
    background-color: #dddddd;
    border: 1px solid #dddddd;valign:top;
}
</style>
<body>

<table>
  <tr>
    <th valign="top">Column 1</th>
    <th valign="top">Column 2 </th>
    <th valign="top">Column 3 </th>
  </tr>
  <tr>
    <td valign="top">Row 1  Column 1</td>
    <td valign="top">

     <b>Paragraph 1 </b>. This is a large text which spills over multiple lines.Java is at the heart of our digital lifestyle. It's the platform for launching careers, exploring human-to-digital interfaces, architecting the world's best applications, and unlocking innovation everywhere from garages to global organizations. When it comes to building computer programming skills, learning Java will take you way beyond the games of your childhood. Knowing Java will be a clear advantage in your future career. Learning Java can be a skill for a career, or a skill for fun or both. Students of all ages have built amazing things, from hobby projects to world-changing initiatives. Oracle Academy Workshops are designed to make first experiences with computing fun and engaging, while still leveraging best academic curriculum practices like project-based learning and offering educators methods for assessment. Oracle Academy Workshops are best used by educators in one of three ways: to introduce students, including students as young as late primary school ages, to computer science in a fun and engaging way;
  to incorporate exposure to computer science into the teaching of other academic disciplines; and
  to offer a limited introduction to computer science to students via extra-curricular programs and/or workshop experiences.

  <br style="mso-data-placement:same-cell;" />

  <b>Paragraph 2 </b> --> Like our Getting Started with Java Using Alice Workshop, this freely available course is designed for teachers, students and individuals with little or no programming experience and teaches basic Java programming concepts through developing 3-D animations in Alice 3.1. Alice is a free, educational, introductory Java development environment created at Carnegie Mellon University. While it is suitable for all beginning learners, it can be especially engaging for girls. Learners will have fun creating animated stories and games using objects and characters from a rich gallery of 3-D models.

  <br style="mso-data-placement:same-cell;" />

  <b>Paragraph 3  </b> Oracle Academy Workshops are also available to Individual and Institutional members in Workshop in a Box formats to facilitate the delivery of introductory computer science workshops by parents, volunteers, computer club sponsors and educators who may not specialize in teaching computer science

  <br style="mso-data-placement:same-cell;" />

 </td>
    <td valign="top">

     <b>Paragraph 1 </b>.
      When you learn Java, youre learning more than just a language. Because Java is a technology platform with many interconnected capabilities that can give cutting-edge, in-demand job skills. In fact, Java tops Inc.coms list of the ten most popular programming languages. Java can take you where you want to go. Learn how to create games, simulations and other graphical programs using basic Java programming via free educational Java development environments from Carnegie Mellon University (Alice) and the University of Kent (Greenfoot). No prior programming or computer science experience is required.
     <br style="mso-data-placement:same-cell;" />

     <b>Paragraph 2 </b>.
     Oracle Academy self-study courses are designed to provide a self-paced learning experience for teachers, students and individuals.
     <br style="mso-data-placement:same-cell;" />

     <b>Paragraph 3 </b>Oracle Academy Workshop in a Box are designed to facilitate the delivery of introductory computer science workshops by parents, volunteers, computer club sponsors and educators who may not specialize in teaching computer science.
     <br style="mso-data-placement:same-cell;" />
    </td>
  </tr>

</table>

</body>
</html>

And here's the result  CLICK FOR THE RESULT IN EXCEL


来源: stackexchange

问:
selenium webdriver - waiting until outerHTML attribute of last class in list contains "X"
Using c# and selenium webdriver, how can I wait until the last class in a list contains a specific attribute?

In my AUT, I have three classes on a page (they are all called paragraph).  I need to get the last paragraph specifically (I'm using a list but feel free to suggest better method) then wait until the last class on the page contains an outerHTML attribute of "X".

This is what I have so far:

I create a list to store all classes, get the last class and finally, get the outerHTML attribute for the last class.

```<code>IList<IwebElement> Element = driver.FindElements(By.ClassName("Paragraph"));
var GetLastElement = Element.Last();
var LastElementAttribute = GetLastElement.GetAttribute("outerHTML");
</code>```

Based on my code above, how can I add a wait condition that will check the last class in the list contains an outerHTML attribute of "X"?

答:
As per the defination, outerHTML returns the html of the element and its child elements. In certain cases it can be set to completely replace an element with an html string. Hence in this case it would be worth looking into any of the following ExpectedConditions :

TextToBePresentInElement

TextToBePresentInElementLocated

TextToBePresentInElementValue(IWebElement, String)

ToString

Among the list of the ExpectedConditions mentioned, ToString looks more promising as per your case is concerned as it Returns a String that represents the current Object. Hence we can easily search the String for the intended character "X"

ContentLicense: CC BY-SA 3.0

Body:
Using c# and selenium webdriver, how can I wait until the last class in a list contains a specific attribute?

In my AUT, I have three classes on a page (they are all called paragraph).  I need to get the last paragraph specifically (I'm using a list but feel free to suggest better method) then wait until the last class on the page contains an outerHTML attribute of "X".

This is what I have so far:

I create a list to store all classes, get the last class and finally, get the outerHTML attribute for the last class.

IList<IwebElement> Element = driver.FindElements(By.ClassName("Paragraph"));
var GetLastElement = Element.Last();
var LastElementAttribute = GetLastElement.GetAttribute("outerHTML");

Based on my code above, how can I add a wait condition that will check the last class in the list contains an outerHTML attribute of "X"?


问:
HttpInterceptor change response body based on value from other observable
Some how i can't seem to change the response body based on the value from another observable which i can only get after i retrieved the response.

Changing the request is pretty simple, i don't know how to do it with the response.

```<code>@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor(private _injector: Injector) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).map((event: HttpEvent<any>) => {
      if (!(event instanceof HttpResponse)) return event;

      const translateService = this._injector.get(TranslateService);

      // retrieved the key from the reponse, now need to retrieve data from the translateservice
      translateService.get(`${event.body.key}`).subscribe((value: string) => {
        event.body.message = value;
      });

       // how to return new response ??
      return event.clone({ body: event.body });
    });
  }
}
</code>```

so basically i want to return a new reponse body with a new property 'message' on it.

答:
Since you cant directly alter the response body you have to return a cloned one. See below for the final answer.</p>

```<code>@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor(private _injector: Injector) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const translateService = this._injector.get(TranslateService);

    return next.handle(request)
        // filter out only events that HTTP event.
        .filter((event: HttpEvent<any>) =>(event instanceof HttpResponse))
        //then switch the observable to get the response of the translate service.
        .switchMap(event => translateService.get(`${event.body.key}`)
            .map(value => event.clone({ body: { message:value } }));
    });
  }
}
</code>```

Body:
Some how i can't seem to change the response body based on the value from another observable which i can only get after i retrieved the response.

Changing the request is pretty simple, i don't know how to do it with the response.

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor(private _injector: Injector) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).map((event: HttpEvent<any>) => {
      if (!(event instanceof HttpResponse)) return event;

      const translateService = this._injector.get(TranslateService);

      // retrieved the key from the reponse, now need to retrieve data from the translateservice
      translateService.get(`${event.body.key}`).subscribe((value: string) => {
        event.body.message = value;
      });

       // how to return new response ??
      return event.clone({ body: event.body });
    });
  }
}

so basically i want to return a new reponse body with a new property 'message' on it.

Body:
Since you cant directly alter the response body you have to return a cloned one. See below for the final answer.

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor(private _injector: Injector) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const translateService = this._injector.get(TranslateService);

    return next.handle(request)
        // filter out only events that HTTP event.
        .filter((event: HttpEvent<any>) =>(event instanceof HttpResponse))
        //then switch the observable to get the response of the translate service.
        .switchMap(event => translateService.get(`${event.body.key}`)
            .map(value => event.clone({ body: { message:value } }));
    });
  }
}


问:
Inserting a function into directive without isolate scope
I'm not sure if I'm going about this the right way.  I am using the ui-select directive which does not seem to support the HTML required directive.  So I built my own, ui-select-required.  It seems I am unable to use isolate scope because ui-select already instantiates an isolate scope.

I want to make ui-select-required take in a function as an attribute.  If the attribute is present, the it should validate with the return value of this function.  If the attribute is not present then it should validate on presence of a value. This is all a part of a component.

product_details.js

```<code>angular
  .module('ProductComponents')
  .component('productDetails', {
    bindings:{
      product: '=product',
    },
    templateUrl: "/template/admin/products/details",
    controllerAs: 'prodDetails',
    controller: [
      'v3Stitcher',
      'AjaxLoaderSvc',
      'ModelInformationSvc',
      '$filter',
      '$http',
      'current_site',
      function(
        v3Stitcher,
        AjaxLoaderSvc,
        ModelInformationSvc,
        $filter,
        $http,
        current_site
      ){
        var prodDetails = this;

        ...

    prodDetails.templateRequired = function(){
      // Product types requiring a template
      // 3 - customizable_downloadable
      // 6 - static_variable_downloadable
      var productTypes = [3, 6];

      // Specification types requiring a template
      var specificationTypes = ["print_on_demand"];

      if(productTypes.indexOf(prodDetails.product.product_type) > -1){
        return true;
      }
      if(specificationTypes.indexOf(prodDetails.specification.specification_type) > -1){
        console.log('here'); // this gets called
        return true;
      }

      return false;
    };

.directive('uiSelectRequired',function(){
  return {
    restrict:'A',
    require:'ngModel',
    link:function(scope, elem, attrs, ctrl){
      var form = angular.element(document).find('form');
      var input = angular.element(elem.find('input')[0]);
      var requiredFn = scope[attrs['requiredFn']];

      if(requiredFn){
        ctrl.$validators.uiSelectRequired = function(){
          return requiredFn();
        };
      } else {
        ctrl.$validators.uiSelectRequired = function(modelValue){
          return !ctrl.$isEmpty(modelValue)
        };
      }

      form.on('submit', function(){
        if(ctrl.$invalid){
          elem.find('span').removeClass('ng-valid').addClass('ng-invalid');
        }
      });

      elem.on('change', function(){
        if(ctrl.$invalid){
          elem.find('span').removeClass('ng-invalid').addClass('ng-valid');
        }
      });
    }
  };
});
</code>```

details.slim

```<code>label(ng-class="{'label label-danger': prodDetails.templateRequired()}")
  | Template
ui-select(ng-model="prodDetails.product.template_id" name="template" ng-model-options="{ debounce: { default:500, blur: 0 } }" ui-select-required required-fn="prodDetails.templateRequired")
  ui-select-match(placeholder="Search Templates...")
    | {{$select.selected.name}}
  ui-select-choices(position="down" repeat="template.id as template in prodDetails.templates" refresh="prodDetails.refreshTemplates($select.search)" minimum-input-length="1" refresh-delay="0")
    | {{ template.name }}
    br
    | id: {{template.id}}
    br
    | created: {{template.created_at | date : 'yyyy-MM-dd'}}
</code>```

The problem I'm having is that the variable requireFn is undefined.  However, if in the HTML I send in the controller variable prodDetails alone then requireFn has the correct value of the controller variable.

答:
I think your problem is that:

You are doing controllerAs: 'prodDetails' in your isolate scope and

You are looking to reference the function directly on the scope in your uiSelectRequired directive

I think if you switch this:

```<code>var requiredFn = scope[attrs['requiredFn']];
</code>```

to:

```<code>var requiredFn = scope.$eval(attrs.requiredFn);
</code>```

You should get what you are looking for. This is assuming that templateRequired property has been added to the productDetails component's controller instance.

To reiterate, your issue was that you were looking for the property directly on the isolate scope itself, where it has been added to the controller reference. By doing a scope.$eval, you will essentially be parsing the path prodDetails.templateRequired -- which will hopefully resolve to the function reference you were hoping to get in the first place.

Edit: So the second part of your question in the comments lead me to believe you never needed a function into a directive with isolate scope. I think what you are trying to do is make the template model required conditionally. Angular already gives you this functionality through required and ng-required directives. You state in your question these are not available on ui-select, but they are "helper" directives with ngModel. I believe this is a mostly working example of what you want to do where I switch to required/ng-required and eliminate the need for your custom directive.

Body:
I'm not sure if I'm going about this the right way.  I am using the ui-select directive which does not seem to support the HTML required directive.  So I built my own, ui-select-required.  It seems I am unable to use isolate scope because ui-select already instantiates an isolate scope.

I want to make ui-select-required take in a function as an attribute.  If the attribute is present, the it should validate with the return value of this function.  If the attribute is not present then it should validate on presence of a value. This is all a part of a component.

product_details.js

angular
  .module('ProductComponents')
  .component('productDetails', {
    bindings:{
      product: '=product',
    },
    templateUrl: "/template/admin/products/details",
    controllerAs: 'prodDetails',
    controller: [
      'v3Stitcher',
      'AjaxLoaderSvc',
      'ModelInformationSvc',
      '$filter',
      '$http',
      'current_site',
      function(
        v3Stitcher,
        AjaxLoaderSvc,
        ModelInformationSvc,
        $filter,
        $http,
        current_site
      ){
        var prodDetails = this;

        ...

    prodDetails.templateRequired = function(){
      // Product types requiring a template
      // 3 - customizable_downloadable
      // 6 - static_variable_downloadable
      var productTypes = [3, 6];

      // Specification types requiring a template
      var specificationTypes = ["print_on_demand"];

      if(productTypes.indexOf(prodDetails.product.product_type) > -1){
        return true;
      }
      if(specificationTypes.indexOf(prodDetails.specification.specification_type) > -1){
        console.log('here'); // this gets called
        return true;
      }

      return false;
    };

.directive('uiSelectRequired',function(){
  return {
    restrict:'A',
    require:'ngModel',
    link:function(scope, elem, attrs, ctrl){
      var form = angular.element(document).find('form');
      var input = angular.element(elem.find('input')[0]);
      var requiredFn = scope[attrs['requiredFn']];

      if(requiredFn){
        ctrl.$validators.uiSelectRequired = function(){
          return requiredFn();
        };
      } else {
        ctrl.$validators.uiSelectRequired = function(modelValue){
          return !ctrl.$isEmpty(modelValue)
        };
      }

      form.on('submit', function(){
        if(ctrl.$invalid){
          elem.find('span').removeClass('ng-valid').addClass('ng-invalid');
        }
      });

      elem.on('change', function(){
        if(ctrl.$invalid){
          elem.find('span').removeClass('ng-invalid').addClass('ng-valid');
        }
      });
    }
  };
});

details.slim

label(ng-class="{'label label-danger': prodDetails.templateRequired()}")
  | Template
ui-select(ng-model="prodDetails.product.template_id" name="template" ng-model-options="{ debounce: { default:500, blur: 0 } }" ui-select-required required-fn="prodDetails.templateRequired")
  ui-select-match(placeholder="Search Templates...")
    | {{$select.selected.name}}
  ui-select-choices(position="down" repeat="template.id as template in prodDetails.templates" refresh="prodDetails.refreshTemplates($select.search)" minimum-input-length="1" refresh-delay="0")
    | {{ template.name }}
    br
    | id: {{template.id}}
    br
    | created: {{template.created_at | date : 'yyyy-MM-dd'}}

The problem I'm having is that the variable requireFn is undefined.  However, if in the HTML I send in the controller variable prodDetails alone then requireFn has the correct value of the controller variable.

Body:
I think your problem is that:

You are doing controllerAs: 'prodDetails' in your isolate scope and

You are looking to reference the function directly on the scope in your uiSelectRequired directive

I think if you switch this:

var requiredFn = scope[attrs['requiredFn']];

to:

var requiredFn = scope.$eval(attrs.requiredFn);

You should get what you are looking for. This is assuming that templateRequired property has been added to the productDetails component's controller instance.

To reiterate, your issue was that you were looking for the property directly on the isolate scope itself, where it has been added to the controller reference. By doing a scope.$eval, you will essentially be parsing the path prodDetails.templateRequired -- which will hopefully resolve to the function reference you were hoping to get in the first place.

Edit: So the second part of your question in the comments lead me to believe you never needed a function into a directive with isolate scope. I think what you are trying to do is make the template model required conditionally. Angular already gives you this functionality through required and ng-required directives. You state in your question these are not available on ui-select, but they are "helper" directives with ngModel. I believe this is a mostly working example of what you want to do where I switch to required/ng-required and eliminate the need for your custom directive.


问:
OpenCV compiler error when using Stitcher under iOS
Whenever I try to use the OpenCV Stitcher class in iOS and I include the stitcher-header ( #include ) I end up with a compile error "Expected '{'" in exposure_compensate.hpp. Apparently the line
    enum { NO, GAIN, GAIN_BLOCKS };
is causing some sort of error.

I am very new to openCV but using other functions like filter2d() work as expected. How can I resolve this?

答:
In your project, create a Prefix Header, MyProject.pch, and set it in your project's build settings.

Then within that pch file, do something like this:

```<code>#ifdef __cplusplus
#   include <opencv2/opencv.hpp>
#   include <opencv2/stitching/detail/blenders.hpp>
#   include <opencv2/stitching/detail/exposure_compensate.hpp>
#else
#   import <Foundation/Foundation.h>
#   import <UIKit/UIKit.h>
#   import <Availability.h>
#endif
</code>```

Body:
In your project, create a Prefix Header, MyProject.pch, and set it in your project's build settings.

Then within that pch file, do something like this:

#ifdef __cplusplus
#   include <opencv2/opencv.hpp>
#   include <opencv2/stitching/detail/blenders.hpp>
#   include <opencv2/stitching/detail/exposure_compensate.hpp>
#else
#   import <Foundation/Foundation.h>
#   import <UIKit/UIKit.h>
#   import <Availability.h>
#endif


问:
Rails 4.2: Turn a reference field into foreign key
I'm maintaining an old system that uses Rails 4.2 and for an unknown reason the references are created this way:

```<code>  t.references :credit_card, null: false
  t.references :car, null: false
  t.references :profile, null: false
</code>```

This allows me to create registers for this model with invalid credit_card ids, for example.
Foreign key isn't validated.

Generating index migration didn't turn them into fk's and didn't validate them at all:

```<code>class AddIndexToRentals < ActiveRecord::Migration
  def change
    add_index :rentals, :credit_card_id
    add_index :rentals, :car_id
    add_index :rentals, :profile_id
  end
end
</code>```

How can I make those fields foreign keys and accept only existent ids?

答:
You can add a foreign key to your migration to validate existence of the referenced record, generate a migration and do the following.

```<code>class AddForeignKeyToRentals < ActiveRecord::Migration
  def change
    add_foreign_key :rentals, :credit_cards
    add_foreign_key :rentals, :cars
    add_foreign_key :rentals, :profiles
  end
end
</code>```

One thing to note that you won't be able to run this migration if you have records that do not exist in the foreign key column. Also you can add an extra existence validation in your model.

```<code>validates :credit_card, :car, :profile, presence: true
</code>```

Hope this helps! :)

Body:
I'm maintaining an old system that uses Rails 4.2 and for an unknown reason the references are created this way:

  t.references :credit_card, null: false
  t.references :car, null: false
  t.references :profile, null: false

This allows me to create registers for this model with invalid credit_card ids, for example.
Foreign key isn't validated.

Generating index migration didn't turn them into fk's and didn't validate them at all:

class AddIndexToRentals < ActiveRecord::Migration
  def change
    add_index :rentals, :credit_card_id
    add_index :rentals, :car_id
    add_index :rentals, :profile_id
  end
end

How can I make those fields foreign keys and accept only existent ids?

Body:
You can add a foreign key to your migration to validate existence of the referenced record, generate a migration and do the following.

class AddForeignKeyToRentals < ActiveRecord::Migration
  def change
    add_foreign_key :rentals, :credit_cards
    add_foreign_key :rentals, :cars
    add_foreign_key :rentals, :profiles
  end
end

One thing to note that you won't be able to run this migration if you have records that do not exist in the foreign key column. Also you can add an extra existence validation in your model.

validates :credit_card, :car, :profile, presence: true

Hope this helps! :)


问:
Local image in canvas in chrome
chrome's access to local files are restricted, but I would like to draw an image on a canvas: an image selected with a file input and without sending the image to the server and then requesting it back.

Some help would be great!

答:
Since your using Google Chrome, file:// URIs cannot read other file:// URIs. If you are using this for development, then you can add the following command line switch to chrome:

```<code>--allow-file-access-from-files
</code>```

HTML5 has (currently in development) FileSystem API you can read an example from it here:
http://www.html5rocks.com/tutorials/file/filesystem/

ContentLicense: CC BY-SA 2.5

Title: Local image in canvas in chrome

Body:
Since your using Google Chrome, file:// URIs cannot read other file:// URIs. If you are using this for development, then you can add the following command line switch to chrome:

--allow-file-access-from-files

HTML5 has (currently in development) FileSystem API you can read an example from it here:
http://www.html5rocks.com/tutorials/file/filesystem/


问:
Use While Loop With setTimeout
I have making a text-based space rpg game. In the battle system, the player and AI take turns firing at each other. I can't figure out how to make the system loop with a while loop without making the browser crash via infinite loop. Here is my code:

```<code>function battle(enemy) {
var battleOver = false;
console.log(enemy.name + " appears!");
//problem loop here.
while(battleOver === false){
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
    var ibumped = i + 1;
    console.log("Press " + ibumped + " to fire the " + userWeapons[i].name + ".");
}
var weaponChosen;
setTimeout(function() {
    var weaponChoice = prompt("Which weapon do you choose?");
    switch (weaponChoice) {
        case 1:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");
            break;
        case 2:
            weaponChosen = userWeapons[1];
            console.log(userWeapons[1].name + " chosen.");
            break;
        default:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");

    };
}, 1000);
setTimeout(function() {
    if (enemy.shields > 0 && weaponChosen.ignoreShield === false) {
        enemy.shields = enemy.shields - weaponChosen.damage;
        weaponChosen.fire(enemy);
        if (enemy.shields < 0) {
            enemy.health = enemy.health + enemy.shields;
            console.log("Enemy shields destroyed and enemy took " + -1 * enemy.shields + " damage!")
        } else {
            console.log("Enemy shields have been reduced to " + enemy.shields + ".");
        }
    } else {
        enemy.health = enemy.health - weaponChosen.damage;
        weaponChosen.fire(enemy);
        console.log("Enemy takes " + weaponChosen.damage + " damage!");
    }
    if (enemy.health <= 0 && battleOver === false) {
        console.log("Enemy destroyed!");
        battleOver = true;
    }
}, 3000);
setTimeout(function() {
    if (enemy.health > 0 && battleOver === false) {
        if (enemy.weapons != null) {
            console.log(enemy.weapons.name + " fired at you.");
            health = health - enemy.weapons.damage;
            console.log("You have " + health + " health left.");
            if (health <= 0) {
                console.log("Game over... You were destroyed");
                battleOver = true;
            }
        } else {
            console.log("The enemy did nothing...");
        }
    };
}, 5000);
}
}
</code>```

All help is appreciated!

答:
A while loop blocks the whole page until it ends, and as your loop never exits its infinite. You may replace it with a high speed interval:</p>

```<code>const loop = setInterval( function(){
   if( battleOver ) return clearInterval(loop);
   console.log("This enemy has " + enemy.health + " health.");
   for (var i = 0; i < userWeapons.length; i++) {
     console.log("Press " + (i + 1) + " to fire the " + userWeapons[i].name + ".");
   }
},10);
</code>```

Title: Use While Loop With setTimeout

Body:
I have making a text-based space rpg game. In the battle system, the player and AI take turns firing at each other. I can't figure out how to make the system loop with a while loop without making the browser crash via infinite loop. Here is my code:

function battle(enemy) {
var battleOver = false;
console.log(enemy.name + " appears!");
//problem loop here.
while(battleOver === false){
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
    var ibumped = i + 1;
    console.log("Press " + ibumped + " to fire the " + userWeapons[i].name + ".");
}
var weaponChosen;
setTimeout(function() {
    var weaponChoice = prompt("Which weapon do you choose?");
    switch (weaponChoice) {
        case 1:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");
            break;
        case 2:
            weaponChosen = userWeapons[1];
            console.log(userWeapons[1].name + " chosen.");
            break;
        default:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");

    };
}, 1000);
setTimeout(function() {
    if (enemy.shields > 0 && weaponChosen.ignoreShield === false) {
        enemy.shields = enemy.shields - weaponChosen.damage;
        weaponChosen.fire(enemy);
        if (enemy.shields < 0) {
            enemy.health = enemy.health + enemy.shields;
            console.log("Enemy shields destroyed and enemy took " + -1 * enemy.shields + " damage!")
        } else {
            console.log("Enemy shields have been reduced to " + enemy.shields + ".");
        }
    } else {
        enemy.health = enemy.health - weaponChosen.damage;
        weaponChosen.fire(enemy);
        console.log("Enemy takes " + weaponChosen.damage + " damage!");
    }
    if (enemy.health <= 0 && battleOver === false) {
        console.log("Enemy destroyed!");
        battleOver = true;
    }
}, 3000);
setTimeout(function() {
    if (enemy.health > 0 && battleOver === false) {
        if (enemy.weapons != null) {
            console.log(enemy.weapons.name + " fired at you.");
            health = health - enemy.weapons.damage;
            console.log("You have " + health + " health left.");
            if (health <= 0) {
                console.log("Game over... You were destroyed");
                battleOver = true;
            }
        } else {
            console.log("The enemy did nothing...");
        }
    };
}, 5000);
}
}

All help is appreciated!

Body:
A while loop blocks the whole page until it ends, and as your loop never exits its infinite. You may replace it with a high speed interval:

const loop = setInterval( function(){
   if( battleOver ) return clearInterval(loop);
   console.log("This enemy has " + enemy.health + " health.");
   for (var i = 0; i < userWeapons.length; i++) {
     console.log("Press " + (i + 1) + " to fire the " + userWeapons[i].name + ".");
   }
},10);


问:
Python: change global variable from within another file
In my main class I use a global variable ADDRESS that is defined in another file called config.py.
I want to change the value of ADDRESS from within my main class, by calling a function in config.py.

In my main class I have:

```<code>from config import ADDRESS, change_address
change_address("192.168.10.100")
print("new address " + ADDRESS)
</code>```

In my config file I have the following:

```<code>ADDRESS = "0.0.0.0"

def change_address(address):
    global ADDRESS
    ADDRESS = address
    print("changed address to: " + ADDRESS)
</code>```

The print statement in my config file correctly prints the new address of 192.168.10.100.
However, the print statement in my main class prints 0.0.0.0.
What am I missing here?

答:
All that from config import ADDRESS, change_address does is take ADDRESS and change_address from your config module's namespace and dumps it into your current module's name-space. Now, if you reassign the value of ADDRESS in config's namespace, it won't be seen by the current module - that's how name-spaces work. It is like doing the following:

```<code>>>> some_namespace = {'a':1}
>>> globals().update(some_namespace)
>>> a
1
>>> some_namespace
{'a': 1}
>>> some_namespace['a'] = 99
>>> a
1
>>> some_namespace
{'a': 99}
</code>```

The simplest solution? Don't clobber name-spaces:

```<code>import config
config.change_address("192.168.10.100")
print("new address " + config.ADDRESS)
</code>```

Body:
In my main class I use a global variable ADDRESS that is defined in another file called config.py.
I want to change the value of ADDRESS from within my main class, by calling a function in config.py.

In my main class I have:

from config import ADDRESS, change_address
change_address("192.168.10.100")
print("new address " + ADDRESS)

In my config file I have the following:

ADDRESS = "0.0.0.0"

def change_address(address):
    global ADDRESS
    ADDRESS = address
    print("changed address to: " + ADDRESS)

The print statement in my config file correctly prints the new address of 192.168.10.100.
However, the print statement in my main class prints 0.0.0.0.
What am I missing here?

Body:
All that from config import ADDRESS, change_address does is take ADDRESS and change_address from your config module's namespace and dumps it into your current module's name-space. Now, if you reassign the value of ADDRESS in config's namespace, it won't be seen by the current module - that's how name-spaces work. It is like doing the following:

>>> some_namespace = {'a':1}
>>> globals().update(some_namespace)
>>> a
1
>>> some_namespace
{'a': 1}
>>> some_namespace['a'] = 99
>>> a
1
>>> some_namespace
{'a': 99}

The simplest solution? Don't clobber name-spaces:

import config
config.change_address("192.168.10.100")
print("new address " + config.ADDRESS)


问:
How to stop url request to validate credit card number
I have a website (PHP Laravel site) that uses Brainstree to process credit card payments.  Today the site receives A LOT direct request to 1 url that passes in credit card information.  It seems the hacker figures out our parameters and is using my site trying to validate their stolen credit card numbers.

Here is an example of a request.

http://mysite/renew?card_nubmer=42693111111111&ccv=014&expiration_month=11&expiration_year=2019&first_name=beqnykit&last_name=fozwgfrpn&postal_code=44101&type=visa&price=12year=1&country_name=USA&currency=%24

It is causing the CPU usage to be 100%, slowing down my site.

Before our code was processing the request and display an error page. Now it validates the request and redirects invalid renew request to log in page.  The CPU load is still 100%.

What can I do to stop this or stop the CPU load, at the least?

答:
Enable the use of CSRF field, it's a must. You're saying you began handling the request as POST, so that's fine.

This route also has to be available for authenticated users only. Add a proper middleware if you haven't yet.

As for additional protection I would recommend to use some throttle middleware. Consider using this package or something similar. It will not allow to use the method more often than the number of times per minute you specify. https://github.com/GrahamCampbell/Laravel-Throttle


问:
Discrete Fourier Transform not working/very inefficient in python

I am trying to write a Discrete Fourier Transform function in python that will give the energy spectral density of a signal as an array (which I will then output graphically). I am doing this using matrix multiplications. My code seems to work for a small set of the data but takes a long time to process; for a large set of data e.g. a wav file it never completes the task. The function is currently:

```<code>from scipy.io import wavfile
import numpy as np
import matplotlib.pyplot as plt
</code>```

def esd(data, fs):

```<code>a=[]

for i in range(int(np.size(data)/100)):

    dt = 1/(fs)

    fvec = np.arange(100*i , 100+(100*i) , 1)
    nvec = np.arange(0 , np.size(data) , 1)

    Wconst = np.exp(-1j*2*np.pi/np.size(data))

    ematrix = Wconst**(np.outer(fvec,nvec))

    b = (dt**2)*(abs(np.inner(ematrix , data))**2)

    a = np.concatenate((a,b))

return a
</code>```

Where data is the data set and fs is the sampling frequency. Is there a reason why this function is so slow or inefficient? It is designed to process the signal in 100 blocks of frequencies as otherwise the matrix would be extremely large.

答:
This algorithm implements the "naive" discrete Fourier transform (DFT), by computing the Vandermonde frequency matrix. The problem is right here:

```<code>b = (dt ** 2) * abs(np.inner(ematrix, data)) ** 2
</code>```

This naive implementation uses a direct matrix-vector multiplication, and has a running time of O(N**2), where N == data.size. So it'll do much worse as you get larger data, and probably not complete in a reasonable time for your WAV-file.

This is the whole point of using the Fast Fourier Transform algorithm, which takes advantage of lots of structure in the problem. Most notably, the FFT breaks the problem down recursively into smaller problems of size N / 2. That recursive structure is what gives the FFT a running time of O(N log N).

Body:
I am trying to write a Discrete Fourier Transform function in python that will give the energy spectral density of a signal as an array (which I will then output graphically). I am doing this using matrix multiplications. My code seems to work for a small set of the data but takes a long time to process; for a large set of data e.g. a wav file it never completes the task. The function is currently:

from scipy.io import wavfile
import numpy as np
import matplotlib.pyplot as plt

def esd(data, fs):

a=[]

for i in range(int(np.size(data)/100)):

    dt = 1/(fs)

    fvec = np.arange(100*i , 100+(100*i) , 1)
    nvec = np.arange(0 , np.size(data) , 1)

    Wconst = np.exp(-1j*2*np.pi/np.size(data))

    ematrix = Wconst**(np.outer(fvec,nvec))

    b = (dt**2)*(abs(np.inner(ematrix , data))**2)

    a = np.concatenate((a,b))

return a

Where data is the data set and fs is the sampling frequency. Is there a reason why this function is so slow or inefficient? It is designed to process the signal in 100 blocks of frequencies as otherwise the matrix would be extremely large.

Body:
This algorithm implements the "naive" discrete Fourier transform (DFT), by computing the Vandermonde frequency matrix. The problem is right here:

b = (dt ** 2) * abs(np.inner(ematrix, data)) ** 2

This naive implementation uses a direct matrix-vector multiplication, and has a running time of O(N**2), where N == data.size. So it'll do much worse as you get larger data, and probably not complete in a reasonable time for your WAV-file.

This is the whole point of using the Fast Fourier Transform algorithm, which takes advantage of lots of structure in the problem. Most notably, the FFT breaks the problem down recursively into smaller problems of size N / 2. That recursive structure is what gives the FFT a running time of O(N log N).


问:
HTML5 Canvas animation uses 88-98% of CPU
i'm trying to animate a faux pixelated map of the world so that it transitions between different colors smoothly. i originially did this with jquery and tables but the cpu usage was very high so i thought i'd try html5 canvas instead. However, i still get very high cpu usage for this. i'm wondering if its the large array in the code (which i use to indicate where a square should be filled). any help would be deeply appreciated.</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title>canvas version</title>
    <script src="raphael.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<div id="canvasesdiv" style="position:relative; width:864px; height:456px">
    <canvas id="world-map" width="864" height="456" style="position:absolute; left:0px; top:0px; z-index:1;">
    </canvas>
    <canvas id="backdrop" width="864" height="456" style="position:absolute; left:0px; top:0px; z-index:0;"></canvas>
    <script type="text/javascript">
        //declare vars
        var ctx1
        var ctx2
        var layer1
        var layer2
        var red = 255;
        var dr = 1;
        //initialization
        function init() {
            layer1 = document.getElementById("backdrop");
            ctx1 = layer1.getContext("2d");
            //layer2 = document.getElementById("world-map");
            //ctx2 = layer2.getContext("2d");
            drawMap(red);
            setInterval(function(){red = drawMap(red);},1);
            }

            //LOOP THROUGH THE ARRAY IT SHOULD BE 38 ROWS EACH WITH 72 COLUMN ENTRIES make each one 12x12 and then fill according to array non zero entries
        var array = [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0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0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 0.0, 22.0, 23.0, 24.0, 25.0, 26.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 33.0, 34.0, 35.0, 36.0, 37.0, 0.0, 0.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 59.0, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 0.0, 0.0, 22.0, 23.0, 0.0, 0.0, 0.0, 27.0, 28.0, 0.0, 0.0, 0.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 59.0, 60.0, 61.0, 62.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 59.0, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0, 0.0, 0.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 30.0, 0.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 0.0, 0.0, 0.0, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 0.0, 0.0, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 59.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 29.0, 30.0, 0.0, 0.0, 0.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 59.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.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, 0.0, 0.0, 0.0, 0.0]]//

            //Draw the map and animate the background in red only for now
        function drawMap(){
            ctx1.clearRect(0,0, 864, 456);
            red -= dr
            if (red < 0 || red > 255){
                dr = -dr
            }
            ctx1.fillStyle = 'rgb('+red+',0,0)';
            ctx1.strokeStyle = '#000';
            for (var row = 0; row < 38; row+=1){
                for (var col = 0; col < 72; col+=1){
                    if (array[row][col] != 0.0){
                        ctx1.fillRect(col*12,row*12,12,12);
                        ctx1.strokeRect(col*12,row*12,12,12);
                    }
                }
            }
            return red;
        }
    init();
    </script>
    </div>
</body>
</html>
</code>```

Body:
i'm trying to animate a faux pixelated map of the world so that it transitions between different colors smoothly. i originially did this with jquery and tables but the cpu usage was very high so i thought i'd try html5 canvas instead. However, i still get very high cpu usage for this. i'm wondering if its the large array in the code (which i use to indicate where a square should be filled). any help would be deeply appreciated.

<!DOCTYPE html>

    <title>canvas version</title>

    <canvas id="world-map" width="864" height="456" style="position:absolute; left:0px; top:0px; z-index:1;">
    </canvas>
    <canvas id="backdrop" width="864" height="456" style="position:absolute; left:0px; top:0px; z-index:0;"></canvas>

Body:
Here's how I would modify your code. Major changes:

Do not call drawMap as fast as possible, instead maxing out at 30fps (and in practice slightly less).

Precalculate the xy offsets, skipping zeroes, once only. This significantly shortens the number of iterations you loop through in drawMap. (~970 vs. ~2700)

Use the fact that drawMap is a closure to modify red directly with no need to return/assign it.

Remove the hard-coding of 12, instead letting you set squareSize in one spot and have your code and canvas updated accordingly.

Change the offset per 'frame' to 5 instead of 1 to account for lower fps. In reality, the best choice would be to specify a redPerSecond variable and calculate the inter-frame delay between calls to drawMap so that the color pulsing happens at the same world speed regardless of framerate.

Remove all decimals from your map array for shorter code, and introduce reasonable linebreaks so that my text editor doesn't cry.

No need to set the strokeStyle to the same value each call to drawMap().

  var map = [
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,21,22,0,0,25,26,27,28,29,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,18,19,20,21,22,23,24,25,26,27,28,29,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,12,13,14,15,16,17,18,19,0,0,22,23,24,25,26,27,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,44,45,46,47,48,49,50,0,0,53,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,0,22,23,24,25,26,0,0,0,0,0,0,33,34,35,36,37,0,0,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,0,0,22,23,0,0,0,27,28,0,0,0,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,0,0,0,0,0,0,0,0,0],
    [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,0,0,0,0,0,0,0,0,0,0,0,0,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,0,0,0,0,0,0,0,0,0,0,0],
    [0,1,2,0,0,0,6,7,8,9,10,11,12,13,14,15,16,17,18,19,0,0,0,0,0,0,0,0,0,0,30,0,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,0,0,0,60,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,6,7,8,9,10,11,12,13,14,15,16,17,18,19,0,0,0,0,0,0,0,0,0,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,0,0,60,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,6,7,8,9,10,11,12,13,14,15,16,17,18,19,0,0,0,0,0,0,0,0,0,0,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,5,6,7,8,9,10,11,12,13,14,15,16,17,18,0,0,0,0,0,0,0,0,0,0,0,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,5,6,7,8,9,10,11,12,13,14,15,16,0,0,0,0,0,0,0,0,0,0,0,0,29,30,0,0,0,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,5,6,7,8,9,10,11,12,13,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,29,0,0,0,33,34,35,0,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,5,6,7,8,9,10,11,12,13,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,29,30,31,32,0,0,0,0,0,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,5,6,7,8,9,10,11,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,6,7,8,9,0,0,0,13,0,0,0,0,0,0,0,0,0,0,0,0,0,27,28,29,30,31,32,33,34,35,36,37,0,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,6,7,8,0,0,0,12,13,14,0,0,0,0,0,0,0,0,0,0,0,0,27,28,29,30,31,32,33,34,35,36,37,0,39,40,41,42,0,0,0,46,47,48,49,50,51,52,53,54,55,56,57,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,7,8,0,10,11,0,13,14,15,16,0,0,0,0,0,0,0,0,0,0,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,0,0,46,47,48,49,0,51,52,53,54,0,0,57,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,8,9,10,11,0,0,0,0,0,17,0,0,0,0,0,0,0,25,0,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,0,0,0,0,0,47,48,0,0,51,52,53,54,0,0,57,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,11,0,0,14,0,0,17,0,0,0,0,0,0,0,0,0,27,28,29,30,31,32,33,34,35,36,37,38,39,40,0,0,0,0,0,0,47,0,0,0,0,52,53,54,0,0,57,58,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,12,13,14,15,16,17,0,0,0,0,0,0,0,0,0,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,0,0,0,0,0,0,48,0,0,0,52,0,0,0,0,57,58,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,13,14,15,16,17,18,0,0,0,0,0,0,0,0,0,28,29,30,31,32,33,34,35,36,37,38,39,40,41,0,0,0,0,46,0,0,0,0,0,52,53,0,0,56,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,12,13,14,15,16,17,18,0,0,0,0,0,0,0,0,0,0,0,0,0,32,33,34,35,36,37,38,39,40,0,0,0,0,0,0,0,0,0,0,0,0,53,0,55,56,57,58,59,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,12,13,14,15,16,17,18,19,20,0,0,0,0,0,0,0,0,0,0,0,0,33,34,35,36,37,38,39,0,0,0,0,0,0,0,0,0,0,0,0,0,53,54,55,56,57,0,59,60,61,62,0,64,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,12,13,14,15,16,17,18,19,20,21,22,0,0,0,0,0,0,0,0,0,0,33,34,35,36,37,38,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,54,55,0,0,0,0,0,61,62,63,64,65,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,13,14,15,16,17,18,19,20,21,22,0,0,0,0,0,0,0,0,0,0,33,34,35,36,37,38,39,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,57,58,0,0,0,0,63,64,0,66,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,13,14,15,16,17,18,19,20,21,0,0,0,0,0,0,0,0,0,0,0,33,34,35,36,37,38,39,0,41,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,59,60,0,62,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,14,15,16,17,18,19,20,21,0,0,0,0,0,0,0,0,0,0,0,33,34,35,36,37,38,0,40,41,0,0,0,0,0,0,0,0,0,0,0,0,0,55,56,57,58,59,60,61,62,0,0,0,0,67,0,69,0,71],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,15,16,17,18,19,20,21,0,0,0,0,0,0,0,0,0,0,0,33,34,35,36,37,38,0,40,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,56,57,58,59,60,61,62,63,0,0,66,0,0,0,0,71],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,15,16,17,18,19,20,0,0,0,0,0,0,0,0,0,0,0,0,33,34,35,36,37,0,0,40,0,0,0,0,0,0,0,0,0,0,0,0,0,0,55,56,57,58,59,60,61,62,63,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,15,16,17,18,19,0,0,0,0,0,0,0,0,0,0,0,0,0,0,34,35,36,37,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,55,56,57,58,59,60,61,62,63,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,15,16,17,18,19,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,35,36,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,55,56,57,58,59,60,61,62,63,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,15,16,17,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,60,61,62,0,0,0,0,67,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,15,16,17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,60,61,0,0,0,0,66,67,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,60,0,0,0,0,65,66,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
  ];
  var squareSize = 12;
  var nonZeroIndices = [];
  var rows = map.length, cols=map[0].length;
  for (var row=0; row<rows; ++row){
    for (var col=0; col<cols; ++col){
      if (map[row][col]) nonZeroIndices.push( [col*squareSize,row*squareSize] );
    }
  }
  var nonZeroes = nonZeroIndices.length;

  window.onload = function(){
    var layer1 = document.getElementById("backdrop");
    var ctx1   = layer1.getContext('2d');
    var red=255, offset=5;
    var w = layer1.width  = map[0].length * squareSize;
    var h = layer1.height = map.length    * squareSize;
    ctx1.strokeStyle = '#000';
    var drawMap = function(){
      ctx1.clearRect(0,0,w,h);
      red -= offset;
      ctx1.fillStyle = 'rgb('+red+',0,0)';
      for (var i=0; i<nonZeroes; ++i){
        var xy = nonZeroIndices[i];
        ctx1.fillRect(xy[0],xy[1],squareSize,squareSize);
        ctx1.strokeRect(xy[0],xy[1],squareSize,squareSize);
      }
      if (red<0 || red>255) offset *= -1;
    };
    setInterval( drawMap, 1000/30 );
  };

<div id="canvasesdiv" style="position:relative; width:864px; height:456px">
  <canvas id="world-map" width="864" height="456" style="position:absolute; left:0px; top:0px; z-index:1;"></canvas>
  <canvas id="backdrop" width="864" height="456" style="position:absolute; left:0px; top:0px; z-index:0;"></canvas>
</div>


问:
Transform Pandas DataFrame to LIBFM format txt file
I want to transform a Pandas Data frame in python to a sparse matrix txt file in the LIBFM format.

Here the format needs to look like this:

```<code>4   0:1.5   3:-7.9
2   1:1e-5  3:2
-1  6:1
</code>```

This file contains three cases. The first column states the target of each of the three case: i.e. 4 for the first case, 2 for the second and -1 for the third. After the target, each line contains the non-zero elements of x, where an entry like 0:1.5 reads x0 = 1.5 and 3:-7.9 means x3 = −7.9, etc. That means the left side of INDEX:VALUE states the index within x whereas the right side states the value of x.

In total the data from the example describes the following design matrix X and target vector y:

```<code>   1.5  0.0   0.0  −7.9  0.0  0.0  0.0
X: 0.0  10−5  0.0  2.0   0.0  0.0  0.0
   0.0  0.0   0.0  0.0   0.0  0.0  1.0

   4
Y: 2
  −1
</code>```

This is also explained in the Manual file under chapter 2.

Now here is my problem: I have a pandas dataframe that looks like this:

```<code>  overall reviewerID        asin       brand         Positive Negative  \
0  5.0   A2XVJBSRI3SWDI  0000031887  Boutique Cutie     3.0       -1
1  4.0   A2G0LNLN79Q6HR  0000031887  Boutique Cutie     5.0       -2
2  2.0   A2R3K1KX09QBYP  0000031887  Boutique Cutie     3.0       -2
3  1.0   A19PBP93OF896   0000031887  Boutique Cutie     2.0       -3
4  4.0   A1P0IHU93EF9ZK  0000031887  Boutique Cutie     2.0       -2

  LDA_0     LDA_1      ...    LDA_98      LDA_99
0  0.000833  0.000833  ...    0.000833    0.000833
1  0.000769  0.000769  ...    0.000769    0.000769
2  0.000417  0.000417  ...    0.000417    0.000417
3  0.000137  0.014101  ...    0.013836    0.000137
4  0.000625  0.000625  ...    0.063125    0.000625
</code>```

Where "overall" is the target column and all other 105 columns are features.

The 'ReviewerId', 'Asin' and 'Brand' columns needs to be changed to dummy variables. So each unique 'ReviewerID', 'Asin' and brand gets his own column. This means if 'ReviewerID' has 100 unique values you get 100 columns where the value is 1 if that row represents the specific Reviewer and else zero.

All other columns don't need to get reformatted. So the index for those columns can just be the column number.

So the first 3 rows in the above pandas data frame need to be transformed to the following output:

```<code>5 0:1 5:1 6:1 7:3 8:-1 9:0.000833 10:0.000833 ... 107:0.000833 108:0.00833
4 1:1 5:1 6:1 7:5 8:-2 9:0.000769 10:0.000769 ... 107:0.000769 108:0.00769
2 2:1 5:1 6:1 7:3 8:-2 9:0.000417 10:0.000417 ... 107:0.000417 108:0.000417
</code>```

In the LIBFM] package there is a program that can transform the User - Item - Rating into the LIBFM output format. However this program can't get along with this many columns.

Is there an easy way to do this? I have 1 million rows in total.

答:
LibFM executable expects the input in libSVM format that you have explained here. If the file converter in the LibFM package do not work for your data, try the scikit learn sklearn.datasets.dump_svmlight_file method.

Ref: http://scikit-learn.org/stable/modules/generated/sklearn.datasets.dump_svmlight_file.html

Body:
I want to transform a Pandas Data frame in python to a sparse matrix txt file in the LIBFM format.

Here the format needs to look like this:

4   0:1.5   3:-7.9
2   1:1e-5  3:2
-1  6:1

This file contains three cases. The first column states the target of each of the three case: i.e. 4 for the first case, 2 for the second and -1 for the third. After the target, each line contains the non-zero elements of x, where an entry like 0:1.5 reads x0 = 1.5 and 3:-7.9 means x3 = −7.9, etc. That means the left side of INDEX:VALUE states the index within x whereas the right side states the value of x.

In total the data from the example describes the following design matrix X and target vector y:

   1.5  0.0   0.0  −7.9  0.0  0.0  0.0
X: 0.0  10−5  0.0  2.0   0.0  0.0  0.0
   0.0  0.0   0.0  0.0   0.0  0.0  1.0

   4
Y: 2
  −1

This is also explained in the Manual file under chapter 2.

Now here is my problem: I have a pandas dataframe that looks like this:

  overall reviewerID        asin       brand         Positive Negative  \
0  5.0   A2XVJBSRI3SWDI  0000031887  Boutique Cutie     3.0       -1
1  4.0   A2G0LNLN79Q6HR  0000031887  Boutique Cutie     5.0       -2
2  2.0   A2R3K1KX09QBYP  0000031887  Boutique Cutie     3.0       -2
3  1.0   A19PBP93OF896   0000031887  Boutique Cutie     2.0       -3
4  4.0   A1P0IHU93EF9ZK  0000031887  Boutique Cutie     2.0       -2

  LDA_0     LDA_1      ...    LDA_98      LDA_99
0  0.000833  0.000833  ...    0.000833    0.000833
1  0.000769  0.000769  ...    0.000769    0.000769
2  0.000417  0.000417  ...    0.000417    0.000417
3  0.000137  0.014101  ...    0.013836    0.000137
4  0.000625  0.000625  ...    0.063125    0.000625

Where "overall" is the target column and all other 105 columns are features.

The 'ReviewerId', 'Asin' and 'Brand' columns needs to be changed to dummy variables. So each unique 'ReviewerID', 'Asin' and brand gets his own column. This means if 'ReviewerID' has 100 unique values you get 100 columns where the value is 1 if that row represents the specific Reviewer and else zero.

All other columns don't need to get reformatted. So the index for those columns can just be the column number.

So the first 3 rows in the above pandas data frame need to be transformed to the following output:

5 0:1 5:1 6:1 7:3 8:-1 9:0.000833 10:0.000833 ... 107:0.000833 108:0.00833
4 1:1 5:1 6:1 7:5 8:-2 9:0.000769 10:0.000769 ... 107:0.000769 108:0.00769
2 2:1 5:1 6:1 7:3 8:-2 9:0.000417 10:0.000417 ... 107:0.000417 108:0.000417

In the LIBFM] package there is a program that can transform the User - Item - Rating into the LIBFM output format. However this program can't get along with this many columns.

Is there an easy way to do this? I have 1 million rows in total.


问:
How do we check if a browser's auto-update is enabled through javascript
I want to check form the javascript if a browser's auto-update is enabled.

The reason I want this is that our software supports only a set of Browser versions and we want to alert them if auto-update is on.

Is there any way we can do this?

Abhi

答:
No. Browsers are highly sand-boxed and will give you almost no information about the users system.

You'll instead have to just do something like check the version and alert them if it isn't up-to-date, with maybe some information on how to check if they have auto-updated turned on.


问:
PHP Constant References
I'm a intermediate C++ programmer and know that you can pass a constant reference as a parameter in order to prevent editing to the actual variable. I was wondering if I could do this in PHP?</p>

答: No, there is no equivalent to C++'s const qualifier in PHP.

Title: PHP Constant References


问:
How do i make my reusable react component saves when the user clicks button?
My component this.props.save(); when componentWillUnmount? however if i leave the page to an external link in a different tab it does not trigger componentWillUnmount

my component

export default class AutoSave extends React.Component {

  constructor(props) {
    super(props);
    this.setIntervalId = null;
  }

  componentDidMount() {
    if (!window.onbeforeunload) {
      window.onbeforeunload = () => {
        this.props.save();
      };
    }

    this.setIntervalId = setInterval(() => this.props.save(), this.props.intervalInMs);
  }

  componentWillUnmount() {
    this.props.save();
    clearInterval(this.setIntervalId);
  }

  render() {

    return Last saved at {now()};
  }
}```
</div>
</div>
</p>

<p>My link looks like this </p>

```<Link href="http://www.google.com"  target="_blank">
      Google Link
    </Link>
```

How can I make component save when user clicks link? It's a react/redux app.

答:
Why are you doing some kind of job in a class that extends from "React.Component". In ReactJS Component is not meant for to do jobs like that. From official documentation "Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.".There is no part in your component except the span that is related to ui. Anyway you should create AutoSave as Pure Component and use it in all React Components. : </p>

```<code>export default class AutoSave
{
  constructor(saveFn, intervalInMs) {
    this.saveFn = saveFn;
    this.setIntervalId = setInterval(
        () => {
            this.save();
        },
        intervalInMs
    );
  }

  unmount() {
    this.save();
    clearInterval(this.setIntervalId);
  }

  save() {
    this.saveFn();
    this.callOnSaveCallback();
  }

  onSave(callback) {
    this.onSaveCallback = callback;
  }

  // private method that calls onSaveCallback
  callOnSaveCallback() {
    if(this.onSaveCallback != null)
        this.onSaveCallback();
  }

}
</code>```

<p>And use it in my React Components like this : </p>

```<code>import AutoSave from './AutoSave';
export default class ReactComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // ... other properties
            "lastSave": new Date()
        }
        this.save = this.save.bind(this);
        this.autoSave = new AutoSave(this.save, 100);
        this.autoSave.onSave(
            () => {
                this.setState(
                    {
                        "lastSave": new Date()
                    }
                );
            }
        )
    }

    componentWillUnmount() {
        this.autoSave.unmount();
        this.autoSave = null;
    }

    onClick() {
        this.autoSave.save();
    }

    save() {
        // some saving job
    }

    render() {
        return (
            <div>
                // ... other components
                <Link href="http://www.google.com"  target="_blank" onClick={this.onClick.bind(this)}>
                  Google Link
                </Link>
                <span className="saving">Last saved at {this.state.lastSave}</span>
            </div>
        );
    }
}
</code>```

Body:
My component this.props.save(); when componentWillUnmount? however if i leave the page to an external link in a different tab it does not trigger componentWillUnmount

my component

export default class AutoSave extends React.Component {

  constructor(props) {
    super(props);
    this.setIntervalId = null;
  }

  componentDidMount() {
    if (!window.onbeforeunload) {
      window.onbeforeunload = () => {
        this.props.save();
      };
    }

    this.setIntervalId = setInterval(() => this.props.save(), this.props.intervalInMs);
  }

  componentWillUnmount() {
    this.props.save();
    clearInterval(this.setIntervalId);
  }

  render() {

    return Last saved at {now()};
  }
}

My link looks like this

<Link href="http://www.google.com"  target="_blank">
      Google Link
    </Link>

How can I make component save when user clicks link? It's a react/redux app.

Body:
Why are you doing some kind of job in a class that extends from "React.Component". In ReactJS Component is not meant for to do jobs like that. From official documentation "Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.".There is no part in your component except the span that is related to ui. Anyway you should create AutoSave as Pure Component and use it in all React Components. :

export default class AutoSave
{
  constructor(saveFn, intervalInMs) {
    this.saveFn = saveFn;
    this.setIntervalId = setInterval(
        () => {
            this.save();
        },
        intervalInMs
    );
  }

  unmount() {
    this.save();
    clearInterval(this.setIntervalId);
  }

  save() {
    this.saveFn();
    this.callOnSaveCallback();
  }

  onSave(callback) {
    this.onSaveCallback = callback;
  }

  // private method that calls onSaveCallback
  callOnSaveCallback() {
    if(this.onSaveCallback != null)
        this.onSaveCallback();
  }

}

And use it in my React Components like this :

import AutoSave from './AutoSave';
export default class ReactComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // ... other properties
            "lastSave": new Date()
        }
        this.save = this.save.bind(this);
        this.autoSave = new AutoSave(this.save, 100);
        this.autoSave.onSave(
            () => {
                this.setState(
                    {
                        "lastSave": new Date()
                    }
                );
            }
        )
    }

    componentWillUnmount() {
        this.autoSave.unmount();
        this.autoSave = null;
    }

    onClick() {
        this.autoSave.save();
    }

    save() {
        // some saving job
    }

    render() {
        return (
            <div>
                // ... other components
                <Link href="http://www.google.com"  target="_blank" onClick={this.onClick.bind(this)}>
                  Google Link
                </Link>
                <span className="saving">Last saved at {this.state.lastSave}</span>
            </div>
        );
    }
}


问:
How to reset a date in Firefox input[type=date]?
Firefox v57.0.1 supports the attribute "date" for the HTML input tag.
I would like in jQuery to reset the date value when the user click on a radio button like this:

In order to get this result:

My jQuery code:

```<code>$("input[name=f_foo_duration]").click(function() {

   if ($("#f_foo_duration_until").is(':checked')) {
       $("#f_foo_duration_date").attr("readonly", false);
   }else{
      $("#f_foo_duration_date").attr("readonly", true);
      $("#f_foo_duration_date").attr( "value", new Date() ); <-- here
   }
});
</code>```

I tested:

val("")

val(null)

val("0000-00-00")

val( new Date() )

without any success... is there a solution?

答:
We'll need to get it to the YYYY-MM-DD format.

```<code>  $("#f_foo_duration_date").val(new Date().toISOString().slice(0,10));
</code>```

See this question for more info on switching the format: Format JavaScript Date to yyyy-mm-dd

ContentLicense: CC BY-SA 4.0

Body:
Firefox v57.0.1 supports the attribute "date" for the HTML input tag.
I would like in jQuery to reset the date value when the user click on a radio button like this:

In order to get this result:

My jQuery code:

$("input[name=f_foo_duration]").click(function() {

   if ($("#f_foo_duration_until").is(':checked')) {
       $("#f_foo_duration_date").attr("readonly", false);
   }else{
      $("#f_foo_duration_date").attr("readonly", true);
      $("#f_foo_duration_date").attr( "value", new Date() ); <-- here
   }
});

I tested:

val("")

val(null)

val("0000-00-00")

val( new Date() )

without any success... is there a solution?

Body:
We'll need to get it to the YYYY-MM-DD format.

  $("#f_foo_duration_date").val(new Date().toISOString().slice(0,10));

See this question for more info on switching the format: Format JavaScript Date to yyyy-mm-dd