问:
Service data not getting bound to the kendoUI grid
I am developing and angular 4 component with kendoUI. I am using the kendoUI grid to display the json data. While debugging I can see that the service is pulling the records. To my knowledge I have bound that datagrid to the data returned by the service correctly. Not sure what the problem could be

movie.component.ts

```<code>import {Component, OnInit} from '@angular/core';
import {MovieService} from './movie.service';
import {IMovie} from './movie.interface';
import { GridDataResult, PageChangeEvent } from '@progress/kendo-angular-grid';
import { SortDescriptor, orderBy } from '@progress/kendo-data-query';
import { MRDBGlobalConstants } from '../shared/mrdb.global.constants';

@Component({
  moduleId: module.id,
  selector: 'app-movie',
  templateUrl: './movie.component.html',
  styleUrls: ['./movie.component.css'],
  providers:[MovieService]
})

export class MovieComponent implements OnInit {

public gridView : GridDataResult;
public pageSize : number;
public sort: SortDescriptor[] = [];
public skip: number = 0;
public movieResponses: IMovie[] = [];

public movieList : IMovie[];

  constructor(private movieService : MovieService) {

   }

  ngOnInit() {
    this.pageSize = MRDBGlobalConstants.GridPageSize;
    this.movieService.getMovies().subscribe((result : IMovie[]) => {
    this.movieList = result;
    this.getMovies();
    });

  }

public sortChange(sort: SortDescriptor[]) : void{
      this.sort  = sort;
      this.getMovies();
}

public pageChange(event: PageChangeEvent) : void{
      this.skip = event.skip;
      this.getMovies();
}

  private getMovies() : void
  {
      var sortedSR = this.movieList;
        if (this.sort && this.sort.length > 0) {
            if (this.sort[0].dir === undefined) this.sort[0].dir = "asc";
            sortedSR = orderBy(this.movieList, this.sort);
        }

    this.gridView = {
            data: sortedSR.slice(this.skip, this.skip + this.pageSize),
            total: this.movieList.length
        };
    }
}
</code>```

movie.service.ts

```<code>import {Injectable} from '@angular/core';
import {MRDBCommonService} from '../shared/services/mrdb.common.service';
import {IMovie} from './movie.interface';
const URL_MOVIE = '/api/movie';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

@Injectable()
export class MovieService
{

constructor(private _mrdbCommonService: MRDBCommonService){}

  getMovies(): Observable<IMovie[]> {

        return Observable.of([
        {
            movieId: 1,
            name: "Titanic",
            actor: "Test1",
            director: "Test2",
            movieLength: 2
        },
        {
            movieId: 2,
            name: "Titanic",
            actor: "Test1",
            director: "Test2",
            movieLength: 2
        },
        {
            movieId: 3,
            name: "Titanic",
            actor: "Test1",
            director: "Test2",
            movieLength: 2
        }
    ]);
    }
    createMovie(){

    }

    deleteMovie(){

    }

}
</code>```

movie.interface.ts

```<code>export interface IMovie{

    movieId:number;
    name:string;
    actor:string;
    director:string;
    movieLength:number;
}
</code>```

movie.component.html

```<code><!-- **************************
MAIN TITLE BAR
******************************* -->

<div class="section-title">
    <div class="title">
        <h1>Movie Results</h1>
    </div>
</div>

<!--  ################### -->
<!--  MAIN CONTENT START -->
<!--  ################### -->

<section id="main-content">
    <section class="wrapper">
        <div class="row mt">

            <div class="col-lg-12">
                <div class="content-panel">

                    <section id="no-more-tables">
                        <table id="holdingTable" class="table table-bordered table-striped table-condensed cf">
                            <tbody>
                                <tr>
                                    <td id="kendoGridHoldingColumn">
                                        <kendo-grid #grid [data]="gridView" class="table table-bordered table-striped table-condensed cf"
                                                    [scrollable]="'none'"
                                                    [sortable]="{ mode: 'single' }"
                                                    [sort]="sort"
                                                    (sortChange)="sortChange($event)"
                                                    [(pageSize)]="pageSize"
                                                    [skip]="skip"
                                                    [pageable]="true"
                                                    (pageChange)="pageChange($event)">
                                            <kendo-grid-column field="movieId" title="movieId" *ngIf="false">
                                            </kendo-grid-column>
                                            <kendo-grid-column field="name" title="Name" headerClass="kendoGridHeader" class="kendoGridCellSurveyResponsesList">
                                                <ng-template kendoGridHeaderTemplate let-column>
                                                    Name
                                                    <i class="fa fa-sort" aria-hidden="true"></i>
                                                </ng-template>
                                                <ng-template kendoGridCellTemplate let-dataItem>
                                                    <span data-title="Name">
                                                        {{dataItem.name}}
                                                    </span>
                                                </ng-template>
                                            </kendo-grid-column>
                                            <kendo-grid-column field="actor" title="Email" headerClass="kendoGridHeader" class="kendoGridCellSurveyResponsesList">
                                                <ng-template kendoGridHeaderTemplate let-column>
                                                    Actor
                                                    <i class="fa fa-sort" aria-hidden="true"></i>
                                                </ng-template>
                                                <ng-template kendoGridCellTemplate let-dataItem>
                                                    <span data-title="Actor">
                                                        {{dataItem.actor}}
                                                    </span>
                                                </ng-template>
                                            </kendo-grid-column>
                                            <kendo-grid-column field="director" title="Director" headerClass="kendoGridHeader" class="kendoGridCellSurveyResponsesList">
                                                <ng-template kendoGridHeaderTemplate let-column>
                                                    Director
                                                    <i class="fa fa-sort" aria-hidden="true"></i>
                                                </ng-template>
                                                <ng-template kendoGridCellTemplate let-dataItem>
                                                    <span data-title="Director">
                                                        {{dataItem.director}}
                                                    </span>
                                                </ng-template>
                                            </kendo-grid-column>
                                            <kendo-grid-column field="movieLength" title="Movie Length" data-title="Movie Length" headerClass="kendoGridHeader" class="kendoGridCellSurveyResponsesList">
                                                <ng-template kendoGridHeaderTemplate let-column>
                                                    Movie Length
                                                    <i class="fa fa-sort" aria-hidden="true"></i>
                                                </ng-template>
                                                <ng-template kendoGridCellTemplate let-dataItem>
                                                    <span data-title="Movie Length">
                                                        {{dataItem.movieLength}}
                                                    </span>
                                                </ng-template>
                                            </kendo-grid-column>

                                        </kendo-grid>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </section><!-- / #no-more-tables -->
                </div><!-- / content-panel -->
            </div><!-- / col-lg-12 -->
        </div><!-- / row -->
        <!-- / main content -->
    </section><!-- / wrapper -->
</section><!-- / #main-content -->
</code>```

答: This has been resolved. The reason is because the pageSize was 0. I set it to 10 and it works. </p>

Body:
I am developing and angular 4 component with kendoUI. I am using the kendoUI grid to display the json data. While debugging I can see that the service is pulling the records. To my knowledge I have bound that datagrid to the data returned by the service correctly. Not sure what the problem could be

movie.component.ts

import {Component, OnInit} from '@angular/core';
import {MovieService} from './movie.service';
import {IMovie} from './movie.interface';
import { GridDataResult, PageChangeEvent } from '@progress/kendo-angular-grid';
import { SortDescriptor, orderBy } from '@progress/kendo-data-query';
import { MRDBGlobalConstants } from '../shared/mrdb.global.constants';

@Component({
  moduleId: module.id,
  selector: 'app-movie',
  templateUrl: './movie.component.html',
  styleUrls: ['./movie.component.css'],
  providers:[MovieService]
})

export class MovieComponent implements OnInit {

public gridView : GridDataResult;
public pageSize : number;
public sort: SortDescriptor[] = [];
public skip: number = 0;
public movieResponses: IMovie[] = [];

public movieList : IMovie[];

  constructor(private movieService : MovieService) {

   }

  ngOnInit() {
    this.pageSize = MRDBGlobalConstants.GridPageSize;
    this.movieService.getMovies().subscribe((result : IMovie[]) => {
    this.movieList = result;
    this.getMovies();
    });

  }

public sortChange(sort: SortDescriptor[]) : void{
      this.sort  = sort;
      this.getMovies();
}

public pageChange(event: PageChangeEvent) : void{
      this.skip = event.skip;
      this.getMovies();
}

  private getMovies() : void
  {
      var sortedSR = this.movieList;
        if (this.sort && this.sort.length > 0) {
            if (this.sort[0].dir === undefined) this.sort[0].dir = "asc";
            sortedSR = orderBy(this.movieList, this.sort);
        }

    this.gridView = {
            data: sortedSR.slice(this.skip, this.skip + this.pageSize),
            total: this.movieList.length
        };
    }
}

movie.service.ts

import {Injectable} from '@angular/core';
import {MRDBCommonService} from '../shared/services/mrdb.common.service';
import {IMovie} from './movie.interface';
const URL_MOVIE = '/api/movie';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

@Injectable()
export class MovieService
{

constructor(private _mrdbCommonService: MRDBCommonService){}

  getMovies(): Observable<IMovie[]> {

        return Observable.of([
        {
            movieId: 1,
            name: "Titanic",
            actor: "Test1",
            director: "Test2",
            movieLength: 2
        },
        {
            movieId: 2,
            name: "Titanic",
            actor: "Test1",
            director: "Test2",
            movieLength: 2
        },
        {
            movieId: 3,
            name: "Titanic",
            actor: "Test1",
            director: "Test2",
            movieLength: 2
        }
    ]);
    }
    createMovie(){

    }

    deleteMovie(){

    }

}

movie.interface.ts

export interface IMovie{

    movieId:number;
    name:string;
    actor:string;
    director:string;
    movieLength:number;
}

movie.component.html

Movie Results

                                        <kendo-grid #grid [data]="gridView" class="table table-bordered table-striped table-condensed cf"
                                                    [scrollable]="'none'"
                                                    [sortable]="{ mode: 'single' }"
                                                    [sort]="sort"
                                                    (sortChange)="sortChange($event)"
                                                    [(pageSize)]="pageSize"
                                                    [skip]="skip"
                                                    [pageable]="true"
                                                    (pageChange)="pageChange($event)">
                                            <kendo-grid-column field="movieId" title="movieId" *ngIf="false">
                                            </kendo-grid-column>
                                            <kendo-grid-column field="name" title="Name" headerClass="kendoGridHeader" class="kendoGridCellSurveyResponsesList">
                                                <ng-template kendoGridHeaderTemplate let-column>
                                                    Name

                                                </ng-template>
                                                <ng-template kendoGridCellTemplate let-dataItem>

                                                        {{dataItem.name}}

                                                </ng-template>
                                            </kendo-grid-column>
                                            <kendo-grid-column field="actor" title="Email" headerClass="kendoGridHeader" class="kendoGridCellSurveyResponsesList">
                                                <ng-template kendoGridHeaderTemplate let-column>
                                                    Actor

                                                </ng-template>
                                                <ng-template kendoGridCellTemplate let-dataItem>

                                                        {{dataItem.actor}}

                                                </ng-template>
                                            </kendo-grid-column>
                                            <kendo-grid-column field="director" title="Director" headerClass="kendoGridHeader" class="kendoGridCellSurveyResponsesList">
                                                <ng-template kendoGridHeaderTemplate let-column>
                                                    Director

                                                </ng-template>
                                                <ng-template kendoGridCellTemplate let-dataItem>

                                                        {{dataItem.director}}

                                                </ng-template>
                                            </kendo-grid-column>
                                            <kendo-grid-column field="movieLength" title="Movie Length" data-title="Movie Length" headerClass="kendoGridHeader" class="kendoGridCellSurveyResponsesList">
                                                <ng-template kendoGridHeaderTemplate let-column>
                                                    Movie Length

                                                </ng-template>
                                                <ng-template kendoGridCellTemplate let-dataItem>

                                                        {{dataItem.movieLength}}

                                                </ng-template>
                                            </kendo-grid-column>

                                        </kendo-grid>


来源: stackexchange

问:
How to take a screenshot in Java?

Possible Duplicate:

  Is there a way to take a screenshot using Java and save it to some sort of image?

How to take a screenshot in Java?

答:
Use Robot#createScreenCapture().

```<code>BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "png", new File("/screenshot.png"));
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to take a screenshot in Java?

Body:
Use Robot#createScreenCapture().

BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "png", new File("/screenshot.png"));


问:
Getter returning '0' value; not passing object?
I've just started learning Java, and I encountered a bit of a problem while writing/experimenting with a simple program.

This is the method iM that calls the getter, getDateDifference() from the class VDC.

```<code> public static void iM() {

    VDC answer = new VDC();
    long theAnswer = answer.getDateDifference();
    System.out.println(theAnswer);

    }
</code>```

Which prints out a zero.

And this is class VDC.

```<code>public class VDC {

public static long dateDifference;

    public static void main(String[] args) {
        VDC.dateDifference();
        System.out.println(dateDifference);
    }

    public static void dateDifference() throws ParseException{

        String pattern = "dd/MM/yyyy/HH/mm";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date startDate = format.parse("22/06/2017/15/00");
        System.out.println("Start Date: " + startDate);

        Date dNow = new Date();
        System.out.println("Current date is: " + dNow);
        long diff = dNow.getTime() - startDate.getTime();
        dateDifference = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
    }

    public long getDateDifference() {
        return dateDifference;
    }

    public void setDateDifference(long dateDifference) {
        VDC.dateDifference = dateDifference;
    }
}
</code>```

I'm fairly certain that I wrote the setter and getter correctly, and running VDC.java in Eclipse gives me the correct value of dateDifference. However, if I attempt to run the class in which method iM is written in, dateDifference returns a value of 0.

After googling for far too long, I think my problem might be that the instance dateDifference isn't set to the passed dateDifference that originates from class VDC (Sorry if I'm confusing anyone).

I have tried to apply what I found in other SOF questions to my program, but I find myself unable to do so. How can I ensure that getDateDifference() returns the correct value (instead of 0) in another class?

(I am sorry if this is a bad question; I simply am unable to apply what I've found to solve my problem)

答:
You never invoke neither setDateDifference nor dateDifference.
So you need to change your iM to

```<code>public static void iM() {
    try {
        VDC.dateDifference();
        long theAnswer = answer.getDateDifference();
        System.out.println(theAnswer);
    catch (ParseException e) {
        ...
    }
}
</code>```

Since your methods are static you do not need to create an instance of VDC.

ContentLicense: CC BY-SA 3.0

Body:
I've just started learning Java, and I encountered a bit of a problem while writing/experimenting with a simple program.

This is the method iM that calls the getter, getDateDifference() from the class VDC.

 public static void iM() {

    VDC answer = new VDC();
    long theAnswer = answer.getDateDifference();
    System.out.println(theAnswer);

    }

Which prints out a zero.

And this is class VDC.

public class VDC {

public static long dateDifference;

    public static void main(String[] args) {
        VDC.dateDifference();
        System.out.println(dateDifference);
    }

    public static void dateDifference() throws ParseException{

        String pattern = "dd/MM/yyyy/HH/mm";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date startDate = format.parse("22/06/2017/15/00");
        System.out.println("Start Date: " + startDate);

        Date dNow = new Date();
        System.out.println("Current date is: " + dNow);
        long diff = dNow.getTime() - startDate.getTime();
        dateDifference = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
    }

    public long getDateDifference() {
        return dateDifference;
    }

    public void setDateDifference(long dateDifference) {
        VDC.dateDifference = dateDifference;
    }
}

I'm fairly certain that I wrote the setter and getter correctly, and running VDC.java in Eclipse gives me the correct value of dateDifference. However, if I attempt to run the class in which method iM is written in, dateDifference returns a value of 0.

After googling for far too long, I think my problem might be that the instance dateDifference isn't set to the passed dateDifference that originates from class VDC (Sorry if I'm confusing anyone).

I have tried to apply what I found in other SOF questions to my program, but I find myself unable to do so. How can I ensure that getDateDifference() returns the correct value (instead of 0) in another class?

(I am sorry if this is a bad question; I simply am unable to apply what I've found to solve my problem)

Body:
You never invoke neither setDateDifference nor dateDifference.
So you need to change your iM to

public static void iM() {
    try {
        VDC.dateDifference();
        long theAnswer = answer.getDateDifference();
        System.out.println(theAnswer);
    catch (ParseException e) {
        ...
    }
}

Since your methods are static you do not need to create an instance of VDC.


问:
how to trigger same name class only on current input text box in jquery plugin?
hello i am creating ajax search plugin.I have created some dynamically div. suppose I have two input box field and the div which is dynamically generated have same name . So I want to project only that div in which user enter the value on  text box  not other, but it fetch result on both div whether I type on first or second input box.
HTML

```<code><div class="row" style="padding:10px">
    <div class="col-md-6">
      <input type="text" class="form-control" name="" value="" id="searchText1">

    </div>
    <div class="col-md-6">
      <input type="text" class="form-control" name="" value="" id="searchText2">
    </div>
</div>
</code>```

js file

```<code>$(document).ready(function(){
  $('#searchText1').typefast({
    hint:true,
    autocomplete:true,

  });
  $('#searchText2').typefast({
    hint:true,
    autocomplete:true,

  });
</code>```

jquery plugin file

```<code>var timeOut = null;
var $current;
var $info;
var input;
var hint;
var comment;

(function( $ ) {

$.fn.typefast = function(a){
  $(this).one('keydown',function(){
  input=$(this);
    $('body').bodyAppend($(this));
    $(this).css({
        'position': 'relative',
        'top': '-34px',
        'background': 'transparent',
        'padding-left': '11px',
        'font-size': '16px'
    })
    $('<div>').attr({
        name: 'comment',
        class: 'comment'
      }).insertAfter($(this));
      comment=$(this);

  })
$(this).on('keydown',function (e) {
    var _this = $(this);

    clearTimeout(timeOut);
      timeOut = setTimeout(function() {
        var m = _this.val();
        api.searchResult(m,e);
        // console.log(ui.input);
        console.log(m);
    },500);

  })
  $.fn.bodyAppend=function(m) {
    $(window).ready(function() {
      $('<input>').attr({
          type: 'text',
          name: 'input1',
          class: 'form-control',
          id:'result',
          placeholder: 'working'
        }).insertBefore(m);
        hint=$('#result')
        single=$('.single')

    })
  }
};

}( jQuery ));
</code>```

My Question is that irrespective of number of input text field on page. My comment should point only the current input box in which I am on working. It should not update the other comment field
class single is the field in which ajax request result displayed.
What is the best way of doing this??

答:
For this case you can set one common class to all input field and apply typefast function on focus event to that class.

For Example,
HTML code

```<code><div class="col-md-6">
                <input type="text" class="form-control searchtext" name="" value="" >
            </div>
<div class="col-md-6">
                <input type="text" class="form-control searchtext" name="" value="" >
            </div>
</code>```

Javascript Code,

```<code>$(document).ready(function () {
                $(document).on("focus", ".searchtext", function () {
                    $($(this)).typefast({
                        hint: true,
                        autocomplete: true,
                    });
                });
            });
</code>```

Body:
hello i am creating ajax search plugin.I have created some dynamically div. suppose I have two input box field and the div which is dynamically generated have same name . So I want to project only that div in which user enter the value on  text box  not other, but it fetch result on both div whether I type on first or second input box.
HTML

      <input type="text" class="form-control" name="" value="" id="searchText1">

      <input type="text" class="form-control" name="" value="" id="searchText2">

js file

$(document).ready(function(){
  $('#searchText1').typefast({
    hint:true,
    autocomplete:true,

  });
  $('#searchText2').typefast({
    hint:true,
    autocomplete:true,

  });

jquery plugin file

var timeOut = null;
var $current;
var $info;
var input;
var hint;
var comment;

(function( $ ) {

$.fn.typefast = function(a){
  $(this).one('keydown',function(){
  input=$(this);
    $('body').bodyAppend($(this));
    $(this).css({
        'position': 'relative',
        'top': '-34px',
        'background': 'transparent',
        'padding-left': '11px',
        'font-size': '16px'
    })
    $('
').attr({
        name: 'comment',
        class: 'comment'
      }).insertAfter($(this));
      comment=$(this);

  })
$(this).on('keydown',function (e) {
    var _this = $(this);

    clearTimeout(timeOut);
      timeOut = setTimeout(function() {
        var m = _this.val();
        api.searchResult(m,e);
        // console.log(ui.input);
        console.log(m);
    },500);

  })
  $.fn.bodyAppend=function(m) {
    $(window).ready(function() {
      $('<input>').attr({
          type: 'text',
          name: 'input1',
          class: 'form-control',
          id:'result',
          placeholder: 'working'
        }).insertBefore(m);
        hint=$('#result')
        single=$('.single')

    })
  }
};

}( jQuery ));

My Question is that irrespective of number of input text field on page. My comment should point only the current input box in which I am on working. It should not update the other comment field
class single is the field in which ajax request result displayed.
What is the best way of doing this??

Body:
For this case you can set one common class to all input field and apply typefast function on focus event to that class.

For Example,
HTML code

<div class="col-md-6">
                <input type="text" class="form-control searchtext" name="" value="" >
            </div>
<div class="col-md-6">
                <input type="text" class="form-control searchtext" name="" value="" >
            </div>

Javascript Code,

$(document).ready(function () {
                $(document).on("focus", ".searchtext", function () {
                    $($(this)).typefast({
                        hint: true,
                        autocomplete: true,
                    });
                });
            });


问:
Batch file extract string
I know this has been asked numerous times, but I've been researching for like 2 hours and still can't do that.

I need a batch script to extract a string from a file.

The content of the file is this:

C:\Windows\system32\tasks{7D7A0547-0D79-0805-0A11-0B780D08110D}

I want to extract this part:

{7D7A0547-0D79-0805-0A11-0B780D08110D}

I tried it with for /f command and all kinds of options and searches, but I just can't do it.

TIA

Title: Batch file extract string

Body:
for /f "tokens=2 delims={}" %%# in ("C:\Windows\system32\tasks{7D7A0547-0D79-0805-0A11-0B780D08110D}") do echo {%%#}

?


问:
Access view inside view controller programmatically using a string tag
I'm retrieving a bunch of ViewControllers programmatically. The source of those ViewController is in my StoryBoard and I'm creating them using

```<code>let page = storyboard?.instantiateViewController(withIdentifier: "features_view_controller")
</code>```

What I want to do is, to access a UILabel I have inside that ViewController in my StoryBoard programmatically using preferably a string tag. Something like this maybe?

```<code>var label = page?.view("identifer")
</code>```

How can I do this?

答: you can give tag to your subview and access it like:-                       YourController.view.viewWithTag(yoursubviewtag)

ContentLicense: CC BY-SA 4.0

Body:
I'm retrieving a bunch of ViewControllers programmatically. The source of those ViewController is in my StoryBoard and I'm creating them using

let page = storyboard?.instantiateViewController(withIdentifier: "features_view_controller")

What I want to do is, to access a UILabel I have inside that ViewController in my StoryBoard programmatically using preferably a string tag. Something like this maybe?

var label = page?.view("identifer")

How can I do this?


问:
How to change default_controller URI Routing in Codeigniter?
I want to change default controller URI Routing Codeigniter to this here is my code :

from->

```<code>$route['default_controller'] = 'home';
</code>```

to->

```<code>$route['default_controller'] = 'Home_controller/home';
</code>```

with this I have store class Home_controller in folder controller/public

thank for your help !!!

答:
From docs:

You can NOT use a directory as a part of this setting!

Instead, if it can fit your requirements, you can set default controller in controllers directory like Home.php and put redirection in index method to your wanted route.

Body:
I want to change default controller URI Routing Codeigniter to this here is my code :

from->

$route['default_controller'] = 'home';

to->

$route['default_controller'] = 'Home_controller/home';

with this I have store class Home_controller in folder controller/public

thank for your help !!!


问:
Compare two string lists with each other Python
I would like to compare two string lists, locate the common strings and store the common strings in a new list.

For example:

```<code>my_list1=['      4,         -40.,         -12.\n',
 '      5,         -40.,         -15.\n',
 '      6,         -40.,         -18.\n',
 '      7,         -40.,         -21.\n',
 '      8,         -40.,         -24.\n',
 '      9,         -40.,         -27.\n',
 '     14,         -30.,         -30.\n',
 '     15,         -28.,         -30.\n']

my_list2=['49',
 '50',
 '51',
 '10',
 '53',
 '54',
 '55',
 '56',
 '57',
 '58',
 '59',
 '60',
 '6162',
 '15',
 '64',
 '65',
 '66']
</code>```

What I want to do is compare  each of the strings of my_list2 with the beginning of the strings in my_list1.

For example my_list1 contains '15' from my_list2 in [ '15, -28.,         -30.\n'] so i want a new list which is going to save all the common strings

答:
You can use str.startswith which can take a tuple of items as argument. Left strip each item in the first list and check if the item startswith any of the strings in the second list:

```<code>t = tuple(my_list2)
lst = [x for x in my_list1 if x.lstrip().startswith(t)]
print lst
# ['     15,         -28.,         -30.\n']
</code>```

Body:
I would like to compare two string lists, locate the common strings and store the common strings in a new list.

For example:

my_list1=['      4,         -40.,         -12.\n',
 '      5,         -40.,         -15.\n',
 '      6,         -40.,         -18.\n',
 '      7,         -40.,         -21.\n',
 '      8,         -40.,         -24.\n',
 '      9,         -40.,         -27.\n',
 '     14,         -30.,         -30.\n',
 '     15,         -28.,         -30.\n']

my_list2=['49',
 '50',
 '51',
 '10',
 '53',
 '54',
 '55',
 '56',
 '57',
 '58',
 '59',
 '60',
 '6162',
 '15',
 '64',
 '65',
 '66']

What I want to do is compare  each of the strings of my_list2 with the beginning of the strings in my_list1.

For example my_list1 contains '15' from my_list2 in [ '15, -28.,         -30.\n'] so i want a new list which is going to save all the common strings

Body:
You can use str.startswith which can take a tuple of items as argument. Left strip each item in the first list and check if the item startswith any of the strings in the second list:

t = tuple(my_list2)
lst = [x for x in my_list1 if x.lstrip().startswith(t)]
print lst
# ['     15,         -28.,         -30.\n']


问:
I want to get the list of opened application in taskbar using Java
I am making an application in Java, I want to get a list of all the opened application in the taskbar. I tried this code,

```<code>Process p = Runtime.getRuntime().exec(
        System.getenv("windir") + "\\system32\\" +
        "tasklist.exe /v /FI \"STATUS eq RUNNING\"");
</code>```

but I want only running application, not all the processes.

答:
One solution would be to use the tasklist command. Meaning: instead of running windir, you simply execute that other command and process its output.

Outlined here for an example that uses Java to call it; and there for documentation about the tool itself.

Body:
I am making an application in Java, I want to get a list of all the opened application in the taskbar. I tried this code,

Process p = Runtime.getRuntime().exec(
        System.getenv("windir") + "\\system32\\" +
        "tasklist.exe /v /FI \"STATUS eq RUNNING\"");

but I want only running application, not all the processes.


问:
Is a RESTful url valid without ids between objects?
I have two RESTful API design questions.  Let's say I have a fruitstand web app.  I want to return information about all the fruits I carry and the counts those fruits, and I do it with:

```<code>http://myfruitstand.com/fruits
</code>```

Question 1:
If I have 10 oranges, then I'm thinking that I can get information about a particular orange with:

```<code>http://myfruitstand.com/fruits/oranges/3
</code>```

But is the above url RESTful--don't I need an id between 'fruits' and 'oranges' to conform to REST standards?  Or is this url with 'fruits' being immediately followed with the subclass 'oranges' okay?

Question 2:
Similarly, if I want to have a discussion forum about my oranges (not a particular orange), can I put it here:

```<code>http://myfruitstand.com/fruits/oranges/comments
</code>```

Again, is the above url RESTful since there's no id between 'oranges' and 'comments' (an id here, of course, would imply a discussion about a particular orange and I don't want that)?  Here, there's no subclass rational of 'oranges' being immediately followed by 'comments.'

thanks in advance, Chuck

答:
I don't believe from your explanation of usage that you need an id for the fruit resource.

Similarly no id needed for the second one either.

As long as your urls model your object organization then I believe you're good to go.

Also, my personal feeling is that if you find a case where  you need to depart ever so slightly from any specification to meet your application needs, that's a reasonable thing to do. Do not allow adherence to this sort of 'model' interfere with getting the job done. For example in the RESTful context, sometimes you perform actions related to some objects that just don't fall clearly under the DELETE/PUT/POST/GET verbs. Do you smoosh those things into there in order to maintain perfect RESTfulness?

I am now hiding behind my desk so as not to be knocked unconscious by the RESTful gurus/religionists that will inevitably beat up on me now :)

Body:
I have two RESTful API design questions.  Let's say I have a fruitstand web app.  I want to return information about all the fruits I carry and the counts those fruits, and I do it with:

http://myfruitstand.com/fruits

Question 1:
If I have 10 oranges, then I'm thinking that I can get information about a particular orange with:

http://myfruitstand.com/fruits/oranges/3

But is the above url RESTful--don't I need an id between 'fruits' and 'oranges' to conform to REST standards?  Or is this url with 'fruits' being immediately followed with the subclass 'oranges' okay?

Question 2:
Similarly, if I want to have a discussion forum about my oranges (not a particular orange), can I put it here:

http://myfruitstand.com/fruits/oranges/comments

Again, is the above url RESTful since there's no id between 'oranges' and 'comments' (an id here, of course, would imply a discussion about a particular orange and I don't want that)?  Here, there's no subclass rational of 'oranges' being immediately followed by 'comments.'

thanks in advance, Chuck


问:
Treat WHERE IN parameters as AND and not OR
I have this table structure/data :

I want to select the row_id(s) that have the combination of (97,6,2) AND (99,1,4) on (attribute_id,store_id,value) respectively.

In this example, we want to get the row_id 8664 as it respects this condition.

What I did is to use the where in statement like following :

```<code>SELECT DISTINCT row_id from catalog_product_entity_int
where row_id in
   (select row_id from catalog_product_entity_int
    WHERE (attribute_id, store_id,value)
    IN ( (99,1,4),(97,6,1) ))
</code>```

This outputs the lines that have (99,1,4) OR (97,6,1).

I tried this query :

```<code>SELECT DISTINCT row_id from catalog_product_entity_int
where row_id in
    (select row_id from catalog_product_entity_int
    WHERE (attribute_id, store_id,value) IN (99,1,4)
    AND (attribute_id, store_id,value) IN(97,6,1) )
</code>```

But I have #1241 - Operand should contain 3 column(s)

How do I manage to select the lines that validates the two conditions together ?

答:
Write your where condition out like this</p>

```<code>WHERE (attribute_id = 99 AND store_id = 1 AND value = 4)
OR (attribute_id = 99 AND store_id = 6 AND value = 1)
</code>```

Body:
I have this table structure/data :

I want to select the row_id(s) that have the combination of (97,6,2) AND (99,1,4) on (attribute_id,store_id,value) respectively.

In this example, we want to get the row_id 8664 as it respects this condition.

What I did is to use the where in statement like following :

SELECT DISTINCT row_id from catalog_product_entity_int
where row_id in
   (select row_id from catalog_product_entity_int
    WHERE (attribute_id, store_id,value)
    IN ( (99,1,4),(97,6,1) ))

This outputs the lines that have (99,1,4) OR (97,6,1).

I tried this query :

SELECT DISTINCT row_id from catalog_product_entity_int
where row_id in
    (select row_id from catalog_product_entity_int
    WHERE (attribute_id, store_id,value) IN (99,1,4)
    AND (attribute_id, store_id,value) IN(97,6,1) )

But I have #1241 - Operand should contain 3 column(s)

How do I manage to select the lines that validates the two conditions together ?

Body:
Write your where condition out like this

WHERE (attribute_id = 99 AND store_id = 1 AND value = 4)
OR (attribute_id = 99 AND store_id = 6 AND value = 1)


问:
Get data between two dates mongo
I need to query the data between two dates.
I was pushing data into mongo where dates are in the format : 13-10-2015 15:08:22

Is there a way to do it?

Can't i tell mongo to compare these as dates with format explicilty mentioned

答:
You can use aggregate function in mongodb.

You can get dates using this :

```<code>let todayDate = new Date();
let beforeDate = new Date();
beforeDate.setDate(beforeDate.getDate() - 15);
</code>```

[Here 15 is days. It will subtract 15 days from current date].

```<code>TableName.aggregate([
        {
            "$match":
                {
                    "Date":
                        {
                            "$lte": todayDate,
                            "$gte": beforeDate
                        }
                }
        }
    ])
</code>```

Title: Get data between two dates mongo

Body:
You can use aggregate function in mongodb.

You can get dates using this :

let todayDate = new Date();
let beforeDate = new Date();
beforeDate.setDate(beforeDate.getDate() - 15);

[Here 15 is days. It will subtract 15 days from current date].

TableName.aggregate([
        {
            "$match":
                {
                    "Date":
                        {
                            "$lte": todayDate,
                            "$gte": beforeDate
                        }
                }
        }
    ])


问:
Style lower and upper fill in HTML5 range input
As explained here, IE allows styling of the lower and upper fill or track regions in CSS as follows:

/* The following only affects the range input in IE */

input[type="range"]::-ms-fill-lower {
  background-color: red;
}

input[type="range"]::-ms-fill-upper {
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="range"></code>```

Does anyone know of a way to apply different styles to the upper and lower tracks of a range input in Firefox, Chrome, etc. using CSS or any JS library?

UPDATE:

As pointed out by Wilson F, this is now supported in Firefox:

/* The following only affects the range input in FF */

input[type="range"]::-moz-range-progress {
  background-color: red;
}

input[type="range"]::-moz-range-track {
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="range">  </code>```

答:
At this stage there is still no option for native implementation of
-ms-fill-lower or -moz-fill-lower in Chrome. Manipulating the range input element with RangeSlider.js was not an option so I used the tweaking technique with CSS linear Gradients and little bit of javascript to fire css changes on input range thumb movement
Hope this helps someone check example on Codepen

Body:
As explained here, IE allows styling of the lower and upper fill or track regions in CSS as follows:

/* The following only affects the range input in IE */

input[type="range"]::-ms-fill-lower {
  background-color: red;
}

input[type="range"]::-ms-fill-upper {
  background-color: blue;
}

<input type="range">

Does anyone know of a way to apply different styles to the upper and lower tracks of a range input in Firefox, Chrome, etc. using CSS or any JS library?

UPDATE:

As pointed out by Wilson F, this is now supported in Firefox:

/* The following only affects the range input in FF */

input[type="range"]::-moz-range-progress {
  background-color: red;
}

input[type="range"]::-moz-range-track {
  background-color: blue;
}

<input type="range">


问:
SQL data retrieve - C#
how do i retrieve data from a table within a loop or something. That means I want to retrieve row by row at a time. but the sequence of rows may differ.
For example, 1st time i want 5rd row,then 2nd, then 9...so on.

I searched it through the internet. I got only two answers.

Use several SqlConnection objects.

reader= sqlCommand.ExecuteReader();
While(reader.Read()){
    reader["Column Name"].ToString();
}

If you got my problem, please help me
Thank you.

答:
The reader approach is usually the way to go, but your query (or SP) must already select the data in the order you want to retrieve it.

Alternatively you can load everything into a DataSet and do random access on the rows in it.

Title: SQL data retrieve - C#


问:
Convert excel to R, calculating from previous row, slow loop
I have some data that has been decoded and looks as follows:

```<code>datetime    date - day  date - month  date - year  gmt hrs  gmt minutes  gmt seconds  val1  val2  val3
37:00.9         NULL        NULL          15          0        30          54         1      1     0
37:01.9          29          9           NULL   0   30  55  1   1   0
37:02.9         NULL        NULL         NULL   0   30  56  1   1   0
37:03.9         NULL        NULL         NULL   0   30  57  1   1   0
37:04.9         NULL        NULL          15    0   30  58  1   1   0
37:05.9          29          9           NULL   0   30  59  1   1   0
37:06.9         NULL        NULL         NULL   0   31  0   1   1   0
37:07.9         NULL        NULL         NULL   0   31  1   1   1   0
37:08.9         NULL        NULL          15    0   31  2   1   1   0
37:09.9          29          9           NULL   0   31  3   1   1   0
37:10.9         NULL        NULL         NULL   0   31  4   1   1   0
37:11.9         NULL        NULL         NULL   0   31  5   1   1   0
37:12.9         NULL        NULL          15    6   7   40  1   1   0
37:13.9          30          9           NULL   6   7   41  1   1   0
37:14.9         NULL        NULL         NULL   6   7   42  1   1   0
37:15.9         NULL        NULL         NULL   6   7   43  1   1   0
37:16.9         NULL        NULL          15    6   7   44  1   1   0
</code>```

datetime is merely the time at decode so isn't relevant, and we see there are many NULL values in the date columns. You can also see that the time does have gaps as seen in the gmt change between the dates 29th and 30th. I would like to replace NULLs with the correct dates. For day, in excel I wrote the following (in K3):

=IF(AND(ISNUMBER(B3)=FALSE,OR(G3=G2+1,F3=F2+1,E3=E2+1,G3=G2,G3=G2+2)),K2,IF(ISNUMBER(B3)=FALSE,MAX(B4,B5,B6),B3))

Note sometimes seconds is equal to the row before and sometimes the diff is 2 seconds, which is why the OR covers those as well.

This works well, but the files are too large for excel to handle well. So I loaded these files into data tables in R and wrote the following equivalent code (doesnt cover the max part but added that after this failed):

```<code>test2$day =ifelse(is.na(test2$`DATE - DAY`)==T &
 (test2$`GMT SECONDS`==shift(test2$`GMT SECONDS`)+1 |test2$`GMT SECONDS`== shift(test2$`GMT SECONDS`) | test2$`GMT SECONDS`==shift(test2$`GMT SECONDS`)+2
  | test2$`GMT MINUTES`== shift(test2$`GMT MINUTES`) +1
   | test2$`GMT HRS`==shift(test2$`GMT HRS`) +1  ),
  shift(test2$day), ifelse(is.na(test2$`DATE - DAY`)==T, shift(test2$`DATE - DAY`, type = 'lead'),test2$`DATE - DAY`))
</code>```

Error in ans[test & ok] <- rep(yes, length.out = length(ans))[test & ok] :
    replacement has length zero
  In addition: Warning message:
  In rep(yes, length.out = length(ans)) :
    'x' is NULL so the result will be NULL

The above failed, so I created the following loop:

```<code> if(nrow(test3)>1) for(i in 2:nrow(test3)) test3$day[i]= ifelse(is.na(test3$`DATE - DAY`[i])==T &
          (test3$`GMT SECONDS`[i]==(test3$`GMT SECONDS`[i-1])+1 |test3$`GMT SECONDS`[i]== (test3$`GMT SECONDS`[i-1]) | test3$`GMT SECONDS`[i]==(test3$`GMT SECONDS`[i-1])+2
          | test3$`GMT MINUTES`[i]== (test3$`GMT MINUTES`[i-1]) +1
           | test3$`GMT HRS`[i]==(test3$`GMT HRS`[i-1]) +1 ),
          test3$day[i-1], ifelse(is.na(test3$`DATE - DAY`[i])==T, max(test3$`DATE - DAY`[i+1],test3$`DATE - DAY`[i+2],test3$`DATE - DAY`[i+3], na.rm=T),test3$`DATE - DAY`[i]))
</code>```

This loop works, but it is quite slow. My test data frame is 80K rows and the loop took about 10min, but I will be dealing with data frames with a few million rows. I am wondering if there is a faster way to do this in R.

Hopefully this makes sense, essentially the code is saying if the day is NULL (NA when in R), if the time follows from the row before then use the last date from the row above. If the time changes, choose the next date from one of the next 4 rows.

I cannot change the decoder, and I tried a few imputation methods including using averages, regression and kNN and none seemed to work well so a logical rule like the above is best. It is just slow in loops.

答:
Think I wrote some logic that handles all the problems I had:</p>

```<code>test2$time = strptime(sprintf("%s:%s:%s", test$`GMT HRS`, test$`GMT MINUTES`, test$`GMT SECONDS`), "%H:%M:%S")

test2$time = as.POSIXct(test2$time)

test2$day = ifelse(is.na(test2$`DATE - DAY`)==T & abs(test2$time - shift(test2$time)) < 3,
                       ifelse(is.na(shift(test2$`DATE - DAY`))==F,shift(test2$`DATE - DAY`), ifelse(is.na(shift(test2$`DATE - DAY`, n=2))==F, shift(test2$`DATE - DAY`, n=2), shift(test2$`DATE - DAY`, n=3))),
                       ifelse(is.na(test2$`DATE - DAY`) == T,
                      ifelse(is.na(shift(test2$`DATE - DAY`, type="lead"))==F,shift(test2$`DATE - DAY`, type="lead"), ifelse(is.na(shift(test2$`DATE - DAY`, n=2, type="lead"))==F,
                    shift(test2$`DATE - DAY`, n=2, type="lead"), shift(test2$`DATE - DAY`, n=3, type="lead"))),
                              test2$`DATE - DAY`))
</code>```

Body:
I have some data that has been decoded and looks as follows:

datetime    date - day  date - month  date - year  gmt hrs  gmt minutes  gmt seconds  val1  val2  val3
37:00.9         NULL        NULL          15          0        30          54         1      1     0
37:01.9          29          9           NULL   0   30  55  1   1   0
37:02.9         NULL        NULL         NULL   0   30  56  1   1   0
37:03.9         NULL        NULL         NULL   0   30  57  1   1   0
37:04.9         NULL        NULL          15    0   30  58  1   1   0
37:05.9          29          9           NULL   0   30  59  1   1   0
37:06.9         NULL        NULL         NULL   0   31  0   1   1   0
37:07.9         NULL        NULL         NULL   0   31  1   1   1   0
37:08.9         NULL        NULL          15    0   31  2   1   1   0
37:09.9          29          9           NULL   0   31  3   1   1   0
37:10.9         NULL        NULL         NULL   0   31  4   1   1   0
37:11.9         NULL        NULL         NULL   0   31  5   1   1   0
37:12.9         NULL        NULL          15    6   7   40  1   1   0
37:13.9          30          9           NULL   6   7   41  1   1   0
37:14.9         NULL        NULL         NULL   6   7   42  1   1   0
37:15.9         NULL        NULL         NULL   6   7   43  1   1   0
37:16.9         NULL        NULL          15    6   7   44  1   1   0

datetime is merely the time at decode so isn't relevant, and we see there are many NULL values in the date columns. You can also see that the time does have gaps as seen in the gmt change between the dates 29th and 30th. I would like to replace NULLs with the correct dates. For day, in excel I wrote the following (in K3):

=IF(AND(ISNUMBER(B3)=FALSE,OR(G3=G2+1,F3=F2+1,E3=E2+1,G3=G2,G3=G2+2)),K2,IF(ISNUMBER(B3)=FALSE,MAX(B4,B5,B6),B3))

Note sometimes seconds is equal to the row before and sometimes the diff is 2 seconds, which is why the OR covers those as well.

This works well, but the files are too large for excel to handle well. So I loaded these files into data tables in R and wrote the following equivalent code (doesnt cover the max part but added that after this failed):

test2$day =ifelse(is.na(test2$`DATE - DAY`)==T &
 (test2$`GMT SECONDS`==shift(test2$`GMT SECONDS`)+1 |test2$`GMT SECONDS`== shift(test2$`GMT SECONDS`) | test2$`GMT SECONDS`==shift(test2$`GMT SECONDS`)+2
  | test2$`GMT MINUTES`== shift(test2$`GMT MINUTES`) +1
   | test2$`GMT HRS`==shift(test2$`GMT HRS`) +1  ),
  shift(test2$day), ifelse(is.na(test2$`DATE - DAY`)==T, shift(test2$`DATE - DAY`, type = 'lead'),test2$`DATE - DAY`))

Error in ans[test & ok] <- rep(yes, length.out = length(ans))[test & ok] :
    replacement has length zero
  In addition: Warning message:
  In rep(yes, length.out = length(ans)) :
    'x' is NULL so the result will be NULL

The above failed, so I created the following loop:

 if(nrow(test3)>1) for(i in 2:nrow(test3)) test3$day[i]= ifelse(is.na(test3$`DATE - DAY`[i])==T &
          (test3$`GMT SECONDS`[i]==(test3$`GMT SECONDS`[i-1])+1 |test3$`GMT SECONDS`[i]== (test3$`GMT SECONDS`[i-1]) | test3$`GMT SECONDS`[i]==(test3$`GMT SECONDS`[i-1])+2
          | test3$`GMT MINUTES`[i]== (test3$`GMT MINUTES`[i-1]) +1
           | test3$`GMT HRS`[i]==(test3$`GMT HRS`[i-1]) +1 ),
          test3$day[i-1], ifelse(is.na(test3$`DATE - DAY`[i])==T, max(test3$`DATE - DAY`[i+1],test3$`DATE - DAY`[i+2],test3$`DATE - DAY`[i+3], na.rm=T),test3$`DATE - DAY`[i]))

This loop works, but it is quite slow. My test data frame is 80K rows and the loop took about 10min, but I will be dealing with data frames with a few million rows. I am wondering if there is a faster way to do this in R.

Hopefully this makes sense, essentially the code is saying if the day is NULL (NA when in R), if the time follows from the row before then use the last date from the row above. If the time changes, choose the next date from one of the next 4 rows.

I cannot change the decoder, and I tried a few imputation methods including using averages, regression and kNN and none seemed to work well so a logical rule like the above is best. It is just slow in loops.

Body:
Think I wrote some logic that handles all the problems I had:

test2$time = strptime(sprintf("%s:%s:%s", test$`GMT HRS`, test$`GMT MINUTES`, test$`GMT SECONDS`), "%H:%M:%S")

test2$time = as.POSIXct(test2$time)

test2$day = ifelse(is.na(test2$`DATE - DAY`)==T & abs(test2$time - shift(test2$time)) < 3,
                       ifelse(is.na(shift(test2$`DATE - DAY`))==F,shift(test2$`DATE - DAY`), ifelse(is.na(shift(test2$`DATE - DAY`, n=2))==F, shift(test2$`DATE - DAY`, n=2), shift(test2$`DATE - DAY`, n=3))),
                       ifelse(is.na(test2$`DATE - DAY`) == T,
                      ifelse(is.na(shift(test2$`DATE - DAY`, type="lead"))==F,shift(test2$`DATE - DAY`, type="lead"), ifelse(is.na(shift(test2$`DATE - DAY`, n=2, type="lead"))==F,
                    shift(test2$`DATE - DAY`, n=2, type="lead"), shift(test2$`DATE - DAY`, n=3, type="lead"))),
                              test2$`DATE - DAY`))


问:
SSDT projects and managing Integration tests with known data
I'm migrating over to SSDT for schema control of the DB structure for a large project with accompanying database. This project already has hundreds of integration tests inside of it that are in various states of brittleness. Many of these use what I would call "known data" to perform the integration tests with. The tests are relying on this data to be there for them to run successfully.

In the past, we've done a 1:1 copy of our integration test database for testing in feature branches, but i'm not wild about this process as it adds bloat to the server.

Using SSDT, is there a way to incorporate this "known data" into either a SSDT project, or a process that can be used to copy after the fact? I already have post-deploy scripts that load seed data into the system (types and the like), so I could put all known data there, but this could be dozens of extra sql files to potentially manage so i'm not wild about it.

Due to the complexities and the amount of known data, using the application sitting on top of the DB to insert it is not practical.

I was thinking about exploring a bacpac option, but before doing that wanted to see if there were any other ways people have managed integration testing of feature branches with known data in the past.

答:
BULK INSERT

The fastest way to get the static data for testing I've found so far is to use "BULK INSERT" from pre-populated data files in the post script. The main problem was that I needed to provide exact files path to the BULK INSERT. However you can use publish variables for that. This solution is the fastest way to get the data and it performs much much better than INSERT/MERGE statements.

INSERT/MERGE

If there is no so much data then INSERT/MERGE in the post scripts work well. There is already implemented stored procedure that can help to generate these statements. You can check it on github.

tSQLt

It is not really related to the actual question, but I strongly advice to use tSQLt framework for testing. It is not integration but unit testing, but with proper usage you will not need pre-populated data and it will be working on any database.


问:
Laravel migration - how to change the `id` field to be primary and auto-incrementing later
My table 'sales_order_details' has the id field  as integer 'int(10)' with a default value 0. I need to change it to be a primary auto-increment  key in migration.

I tried in the following way :

```<code> public function up()
    {
        Schema::table('sales_order_details', function (Blueprint $table){

         $table->integer('id')->default(NULL)->change();
         $table->increments('id')->change();

       });
    }

  public function down()
    {
        Schema::table('sales_order_details', function (Blueprint $table){
        $table->dropPrimary('id')->change();

       });
    }
</code>```

I get the following errors:

[Illuminate\Database\QueryException]
 SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table def
 inition; there can be only one auto column and it must be defined as a key
 (SQL: ALTER TABLE sales_order_details CHANGE id id INT UNSIGNED AUTO_INCREM
 ENT NOT NULL)

[Doctrine\DBAL\Driver\PDOException]
 SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table def
 inition; there can be only one auto column and it must be defined as a key

[PDOException]
 SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table def
 inition; there can be only one auto column and it must be defined as a key

How to make the migration properly ? I am using version 5.4

答:
You can try like this

```<code>  public function up()
    {
        DB::statement("ALTER TABLE sales_order_details MODIFY id INT NOT NULL PRIMARY KEY AUTO_INCREMENT");
    }

  public function down()
    {
        DB::statement("ALTER TABLE sales_order_details MODIFY id INT NOT NULL");
        DB::statement("ALTER TABLE sales_order_details DROP PRIMARY KEY");
        DB::statement("ALTER TABLE sales_order_details MODIFY id INT NULL");
    }
</code>```

This is the one of the way you can achieve your goal, i hope this is helpful for you

Body:
My table 'sales_order_details' has the id field  as integer 'int(10)' with a default value 0. I need to change it to be a primary auto-increment  key in migration.

I tried in the following way :

 public function up()
    {
        Schema::table('sales_order_details', function (Blueprint $table){

         $table->integer('id')->default(NULL)->change();
         $table->increments('id')->change();

       });
    }

  public function down()
    {
        Schema::table('sales_order_details', function (Blueprint $table){
        $table->dropPrimary('id')->change();

       });
    }

I get the following errors:

[Illuminate\Database\QueryException]
 SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table def
 inition; there can be only one auto column and it must be defined as a key
 (SQL: ALTER TABLE sales_order_details CHANGE id id INT UNSIGNED AUTO_INCREM
 ENT NOT NULL)

[Doctrine\DBAL\Driver\PDOException]
 SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table def
 inition; there can be only one auto column and it must be defined as a key

[PDOException]
 SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table def
 inition; there can be only one auto column and it must be defined as a key

How to make the migration properly ? I am using version 5.4

Body:
You can try like this

  public function up()
    {
        DB::statement("ALTER TABLE sales_order_details MODIFY id INT NOT NULL PRIMARY KEY AUTO_INCREMENT");
    }

  public function down()
    {
        DB::statement("ALTER TABLE sales_order_details MODIFY id INT NOT NULL");
        DB::statement("ALTER TABLE sales_order_details DROP PRIMARY KEY");
        DB::statement("ALTER TABLE sales_order_details MODIFY id INT NULL");
    }

This is the one of the way you can achieve your goal, i hope this is helpful for you


问:
Pre-commit SVN Hook + image optimization script
I was wondering if anyone had tried to make a pre-commit SVN hook to "smush" images before the commit using SmushIt, PunyPNG or any optimization script.

I tried looking on google but looks like nobody ever tried to do this.

I need advices and/or feedbacks.

Thanks !

答:
I'll admit, I'm not exactly answering the question, but I'm trying to steer you down a better path.  You really shouldn't mess with the content of commit in the start-commit or pre-commit hooks.  Besides, wouldn't you like to have the original unaltered graphic in the repository so in case the "smush" operation ruins the images or is not to your liking, you can always get the original back out of the repo and edit it again?

Now in your case, what I'd suggest is to setup a post-commit script that would detect that a graphics file has been committed and then call your "smush" tool if the image doesn't meet certain criteria (size, etc).  Once the image has had a "smush" applied to it, then commit it back to the repository.


问:
Paypal error We’re sorry Things don’t appear to be working at the moment
We’re sorry Things don’t appear to be working at the moment. This error comes each time while transacting through paypal.

Here is the url for live testing http://shreyasoft.in/paypal/ but not working from sandbox

Here is my paypal form

```<code>paypal_form.php
</code>```

here is the code for sandbox account

```<code><form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_blank">
   <input type="hidden" name="cmd" value="_xclick">
   <input type="hidden" name="business" value="sethiharshit92-facilitator@gmail.com">
   <input type="hidden" name="item_name" value="Widget">
   <input type="hidden" name="amount" value="10.00">
   <input type="hidden" name="currency_code" value="USD">
    <input type='hidden' name='cancel_return' value='http://localhost/paypal/paypal_cancel.php'>
    <input type='hidden' name='return' value='http://localhost/paypal/paypal_success.php'>
   <input type="submit" value="Old PayPal checkout">
</form>
</code>```

here is the error

答:
Paypal needs to be able to contact yourwebhost directly to validate the authentication.

it works like this:

you send request to paypal

paypal sends request to your site with key

your site needs to respond with proper answer

paypal continues transaction.

step 2 is failing at this point because paypal cannot contact your localhost.

Either use a webserver with a domain name/public ip, or set up your internet router to route traffic to port 80 to your development pc and use your public ip in communication with paypal

Body:
We’re sorry Things don’t appear to be working at the moment. This error comes each time while transacting through paypal.

Here is the url for live testing http://shreyasoft.in/paypal/ but not working from sandbox

Here is my paypal form

paypal_form.php

here is the code for sandbox account

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_blank">
   <input type="hidden" name="cmd" value="_xclick">
   <input type="hidden" name="business" value="sethiharshit92-facilitator@gmail.com">
   <input type="hidden" name="item_name" value="Widget">
   <input type="hidden" name="amount" value="10.00">
   <input type="hidden" name="currency_code" value="USD">
    <input type='hidden' name='cancel_return' value='http://localhost/paypal/paypal_cancel.php'>
    <input type='hidden' name='return' value='http://localhost/paypal/paypal_success.php'>
   <input type="submit" value="Old PayPal checkout">
</form>

here is the error


问:
How to set Default value for kendo-combobox in angular 2
I am using Kendo Combobox to bind certain values in UI.Is it possible to set the first value of the Array as the default value ?.</p>

答:
From Combobox Point of view you can add the first value as selection using following code. This is irrespective of the Angular code. Cause you've not mentioned any code snippet or feature you want to use to achieve that.

```<code>$("#targetComboId").kendoComboBox({
    dataTextField: "text",
    dataValueField: "value",
    dataSource: [{
            text: "Cotton",
            value: "1"
        },
        {
            text: "Polyester",
            value: "2"
        },
        {
            text: "Cotton/Polyester",
            value: "3"
        },
        {
            text: "Rib Knit",
            value: "4"
        }
    ],
    index: 0 // Your target value, set it to the index you want
});
</code>```

This will select and populate the first value in the Combobox. Hope it helps!

Body:
From Combobox Point of view you can add the first value as selection using following code. This is irrespective of the Angular code. Cause you've not mentioned any code snippet or feature you want to use to achieve that.

$("#targetComboId").kendoComboBox({
    dataTextField: "text",
    dataValueField: "value",
    dataSource: [{
            text: "Cotton",
            value: "1"
        },
        {
            text: "Polyester",
            value: "2"
        },
        {
            text: "Cotton/Polyester",
            value: "3"
        },
        {
            text: "Rib Knit",
            value: "4"
        }
    ],
    index: 0 // Your target value, set it to the index you want
});

This will select and populate the first value in the Combobox. Hope it helps!


问:
Go (golang) Package consisting of several folders
Is it possible in Go (golang) to have a package consisting of several .go files from different folders?

I am trying to make a subfolder inside of the main folder, and compiler says that it cannot find definitions ("undefined" error). When all the files are in the same folder, compilation does not give errors.

Thanks.

答:
No, this is not possible.

If you want to use folders inside your go project you have to use several packages.

NOT VALID

```<code>myproject
| -- main.go (package main)
| -- routes.go (package main)
+ -- models
     | -- db.go (package main)
     | -- mymodel.go (package main)
</code>```

VALID

```<code>myproject
| -- main.go (package main)
| -- routes.go (package main)
+ -- models
     | -- db.go (package models)
     | -- mymodel.go (package models)
</code>```

Body:
No, this is not possible.

If you want to use folders inside your go project you have to use several packages.

NOT VALID

myproject
| -- main.go (package main)
| -- routes.go (package main)
+ -- models
     | -- db.go (package main)
     | -- mymodel.go (package main)

VALID

myproject
| -- main.go (package main)
| -- routes.go (package main)
+ -- models
     | -- db.go (package models)
     | -- mymodel.go (package models)


答:
Try:</p>

```<code>SELECT DISTINCT row_id FROM catalog_product_entity_int WHERE row_id IN
(SELECT row_id FROM catalog_product_entity_int
WHERE (attribute_id = 99 AND store_id = 1 AND value = 4)
OR (attribute_id = 97 AND store_id = 6 AND value = 1))
</code>```

Title: Treat WHERE IN parameters as AND and not OR

Body:
Try:

SELECT DISTINCT row_id FROM catalog_product_entity_int WHERE row_id IN
(SELECT row_id FROM catalog_product_entity_int
WHERE (attribute_id = 99 AND store_id = 1 AND value = 4)
OR (attribute_id = 97 AND store_id = 6 AND value = 1))


问:
HTML & CSS progress bar does not stop at the end
I have created this progress bar and I just can't make it stop at the end. Currently its stopping at 70% and gets cleared. Any ideas? Is there any kind of animation setting to stop it at 100%?

.wrap {
  background-color: #f2f2f2;
  height: 10px;
  width: 400px;
  margin: 0 auto;
  position: relative;
  top: 20px;
  margin-bottom: 20px;
}

.bar {
  background: #ffcc00;
  height: 10px;
  width: 0%;
}

.animating {
  -webkit-animation: progress 3s ;
}

@-webkit-keyframes progress {
  0% {
    width: 0%;
  }
  100% {
    width: 70%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="bar animating"></div>
</div></code>```

答:
A Fancy version

  .wrap {
  background-color: #f2f2f2;
  height: 10px;
  width: 400px;
  margin: 0 auto;
  position: relative;
  top: 20px;
  margin-bottom: 20px;
}

.wrap div {
  background-color: #ffcc00;
  height: 10px;
  width: 0%;
  border-radius: 5px;
  animation: loadbar 3s;
  -webkit-animation: loadbar 3s;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

@-webkit-keyframes loadbar {
  0% {
    width: 0%;
  }
  100% {
    width: 100%;
  }
  @keyframes loadbar {
    0% {
      width: 0%;
    }
    100% {
      width: 100%;
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="bar animating"></div>
</div></code>```

Body:
A Fancy version

  .wrap {
  background-color: #f2f2f2;
  height: 10px;
  width: 400px;
  margin: 0 auto;
  position: relative;
  top: 20px;
  margin-bottom: 20px;
}

.wrap div {
  background-color: #ffcc00;
  height: 10px;
  width: 0%;
  border-radius: 5px;
  animation: loadbar 3s;
  -webkit-animation: loadbar 3s;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

@-webkit-keyframes loadbar {
  0% {
    width: 0%;
  }
  100% {
    width: 100%;
  }
  @keyframes loadbar {
    0% {
      width: 0%;
    }
    100% {
      width: 100%;
    }
  }

<div class="wrap">
  <div class="bar animating"></div>
</div>


问:
How to alter .htaccess for the following url rewriting?
When I go the url/[a 7 character alphanumeric string] for instance, localhost/delta/SW9NZ1p
or www.website.com/delta/SW9NZ1p, it should rewrite it as localhost/delta/product.php?url=SW9NZ1p or www.website.com/delta/product.php?url=SW9NZ1

Goal: While I'm viewing localhost/delta/SW9NZ1p I should see code executing from localhost/delta/product.php?url=SW9NZ1p but the url bar should show localhost/delta/SW9NZ1p

Can you tell me what's wrong with the following code?

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^delta/([a-zA-Z0-9]{7,})/?$  product.php?url=$1    [NC,L]
</IfModule>
</code>```

答:
You might be getting not found error because apache might literally searching for delta/as23221 if you are using the htaccess in root then use,

Try this in delta directory

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]{7,})/?$ product.php?url=$1 [NC,L]
</code>```

Try below in root,

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]{7,})/?$ delta/product.php?url=$1 [NC,L]
</code>```

Body:
When I go the url/[a 7 character alphanumeric string] for instance, localhost/delta/SW9NZ1p
or www.website.com/delta/SW9NZ1p, it should rewrite it as localhost/delta/product.php?url=SW9NZ1p or www.website.com/delta/product.php?url=SW9NZ1

Goal: While I'm viewing localhost/delta/SW9NZ1p I should see code executing from localhost/delta/product.php?url=SW9NZ1p but the url bar should show localhost/delta/SW9NZ1p

Can you tell me what's wrong with the following code?

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^delta/([a-zA-Z0-9]{7,})/?$  product.php?url=$1    [NC,L]
</IfModule>

Body:
You might be getting not found error because apache might literally searching for delta/as23221 if you are using the htaccess in root then use,

Try this in delta directory

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]{7,})/?$ product.php?url=$1 [NC,L]

Try below in root,

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]{7,})/?$ delta/product.php?url=$1 [NC,L]


问:
Nodejs loop through same API with different parameters
I trying to loop through same API result and if the API result is NULL then I want loop through it again few times (i.e 4-5 times) with different parameters and if it's reached the 5th time. I want to exit the loop. The code I'm trying is see below:

```<code>var roads = 1000;
var findResult = true;
var loop = 0;

while (findResult) {
  result = APIResult(rarray, roads);
  if (result !== null) {
    findResult = false; // stop the loop
  } else if (loop == 5) {
    findResult = false; // stop the loop
  } else {
    roads = roads * 10;
    loop++;
  }
}

function APIResult(rarray, roads) {
  request.post(
      env.TEST_URL + 'test/',
      {
        json: {
          //...
          roads: roads,
          //..
        },
      },
      function(error, response, body) {
        if (!error && response.statusCode == 200) {
          return JSON.parse(body.rows[0].result);
        }
      });
}
</code>```

I'm even tried adding Q promise but didn't worked, any idea how to do it?

答:
Your APIResult function doesn't return anything. This function is asynchronous, so it should return promise or use a callback.

Your code result = APIResult(rarray, roads); sets to result variable undefined value. I think, async/await style for implementing asynchronous JS features will work for you.

Current last Node.js version is 8.1. It has native support for async/await. There is an example, how you can implement your code:

```<code>async function main() {
  var roads = 1000;
  var findResult = true;
  var loop = 0;
  while (findResult) {
    try {
      result = await APIResult(rarray, roads);
    } catch (e) {
      //APIResult reject promise branch
    }

    if (result !== null) {
      findResult = false; // stop the loop
    } else if (loop == 5) {
      findResult = false; // stop the loop
    } else {
      roads = roads * 10;
      loop++;
    }
  }
}

async function APIResult(rarray, roads) {
  return new Promise((res, rej) => {
    request.post(
        env.TEST_URL + 'test/',
        {
          json: {
            //...
            roads: roads,
            //..
          },
        },
        function(error, response, body) {
          if (error) return rej(error);
          if (response.statusCode === 200) return res(JSON.parse(body.rows[0].result));
        });
  });
}

main();
</code>```

Body:
I trying to loop through same API result and if the API result is NULL then I want loop through it again few times (i.e 4-5 times) with different parameters and if it's reached the 5th time. I want to exit the loop. The code I'm trying is see below:

var roads = 1000;
var findResult = true;
var loop = 0;

while (findResult) {
  result = APIResult(rarray, roads);
  if (result !== null) {
    findResult = false; // stop the loop
  } else if (loop == 5) {
    findResult = false; // stop the loop
  } else {
    roads = roads * 10;
    loop++;
  }
}

function APIResult(rarray, roads) {
  request.post(
      env.TEST_URL + 'test/',
      {
        json: {
          //...
          roads: roads,
          //..
        },
      },
      function(error, response, body) {
        if (!error && response.statusCode == 200) {
          return JSON.parse(body.rows[0].result);
        }
      });
}

I'm even tried adding Q promise but didn't worked, any idea how to do it?

Body:
Your APIResult function doesn't return anything. This function is asynchronous, so it should return promise or use a callback.

Your code result = APIResult(rarray, roads); sets to result variable undefined value. I think, async/await style for implementing asynchronous JS features will work for you.

Current last Node.js version is 8.1. It has native support for async/await. There is an example, how you can implement your code:

async function main() {
  var roads = 1000;
  var findResult = true;
  var loop = 0;
  while (findResult) {
    try {
      result = await APIResult(rarray, roads);
    } catch (e) {
      //APIResult reject promise branch
    }

    if (result !== null) {
      findResult = false; // stop the loop
    } else if (loop == 5) {
      findResult = false; // stop the loop
    } else {
      roads = roads * 10;
      loop++;
    }
  }
}

async function APIResult(rarray, roads) {
  return new Promise((res, rej) => {
    request.post(
        env.TEST_URL + 'test/',
        {
          json: {
            //...
            roads: roads,
            //..
          },
        },
        function(error, response, body) {
          if (error) return rej(error);
          if (response.statusCode === 200) return res(JSON.parse(body.rows[0].result));
        });
  });
}

main();


问:
MS graph API sharepoint site. Create a folder in root
I try to use the MS graph API to work with sharepoint sites.
All works fine, except i can not find how to create a folder in root of a site (folders are documents library).

If i know the site id (SITEID) i can list folders in root of the site as drives

```<code>GET /v1.0/sites/SITEID/drives
</code>```

I have ID for each item (it is like a drive ID). The i can list folders on drives (which are subfolders of top level folders on a site)

```<code>GET /v1.0/sites/SITEID/drives/DRIVEID/root/children
</code>```

I can create folders in this place and subfolders

```<code>POST /v1.0/sites/SITEID/drives/DRIVEID/root/children
{
  "name": "New Folder 2",
  "folder": {}
}
</code>```

But how to create a top level folder on a site? In fact, how to create new drive on a site?

I try to guess something like

```<code>POST /v1.0/sites/SITEID/drives
{
  "name": "New Drive",
  "folder": {}
}
</code>```

But this doesn't work

Also, i tried to create a list https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/list_create

```<code>POST /v1.0/sites/SITEID/lists
{
  "name": "Books",
  "columns": [
    {
      "name": "Author",
      "text": { }
    },
    {
      "name": "PageCount",
      "number": { }
    }
  ],
  "list": {
    "template": "documentLibrary"
  }
}
</code>```

no success

答:
I think you are wrong. Folders are not document libraries.

Drive is a document library. Document library is a list with template: document library, so drive is also a list.

Endpoint

```<code>GET /v1.0/sites/SITEID/drives
</code>```

will return a list of lists with template: document library.

Endpoint

```<code>GET /v1.0/sites/SITEID/lists
</code>```

will return all lists of all types.

To create new drive (a document library) you should create a new list with document library as template. Then you will have a new drive in a root of the site.

What problem do you have with creation of a new list?

Body:
I try to use the MS graph API to work with sharepoint sites.
All works fine, except i can not find how to create a folder in root of a site (folders are documents library).

If i know the site id (SITEID) i can list folders in root of the site as drives

GET /v1.0/sites/SITEID/drives

I have ID for each item (it is like a drive ID). The i can list folders on drives (which are subfolders of top level folders on a site)

GET /v1.0/sites/SITEID/drives/DRIVEID/root/children

I can create folders in this place and subfolders

POST /v1.0/sites/SITEID/drives/DRIVEID/root/children
{
  "name": "New Folder 2",
  "folder": {}
}

But how to create a top level folder on a site? In fact, how to create new drive on a site?

I try to guess something like

POST /v1.0/sites/SITEID/drives
{
  "name": "New Drive",
  "folder": {}
}

But this doesn't work

Also, i tried to create a list https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/list_create

POST /v1.0/sites/SITEID/lists
{
  "name": "Books",
  "columns": [
    {
      "name": "Author",
      "text": { }
    },
    {
      "name": "PageCount",
      "number": { }
    }
  ],
  "list": {
    "template": "documentLibrary"
  }
}

no success

Body:
I think you are wrong. Folders are not document libraries.

Drive is a document library. Document library is a list with template: document library, so drive is also a list.

Endpoint

GET /v1.0/sites/SITEID/drives

will return a list of lists with template: document library.

Endpoint

GET /v1.0/sites/SITEID/lists

will return all lists of all types.

To create new drive (a document library) you should create a new list with document library as template. Then you will have a new drive in a root of the site.

What problem do you have with creation of a new list?


问:
Remote validation causes submit inputs (multiple-submit-buttons) to be null
I recently implemented remote validation in my form:

ViewModel:

```<code>[Remote("IsTagUnique", "myController", "myArea", ErrorMessage = "This tag already exists.")]
public string tag { get; set; }
</code>```

Controller:

```<code>        public ActionResult IsTagUnique(string tag)
        {
            using (db)
            {
                try
                {
                    var myTag = db.ASAuftraege.Single(m => m.tag == tag);
                        return Json(false, JsonRequestBehavior.AllowGet);
                    }
                }
                catch (Exception)
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult myView(string Send){
            // doSomething
        }
</code>```

View (called "myView")

```<code>@Html.TextBoxFor(m => m.tag) @Html.ValidationMessageFor(m => m.tag)

<button class="form-button-submit" type="submit" name="Send" value="Send">Send</button>
</code>```

The validation works perfectly fine.

Problem is: When I click the Send-button without manually triggering the validation on the tag-field once by clicking into the field and then clicking somewhere else the "IsTagUnique" function is executed before the myView()-function. This causes my submit-inputs (I actually have multiple send-buttons, just like the one shown in the view (different name/value of course) to be null. Any idea what I can do? I tried triggering the validation manually by giving focus and blurring the tag-field, and by triggering a change event. Doesn't trigger the validation, though.

答:
After searching for a while I found out this seems to be a known bug:

The issue happens when a form which uses the remote method to validate a field. If a submit button is pressed after the validator fires, everything is alright and the request will contain the clicked submit button name/value pair.
  However, when the remote method is not fired before the submit button is pressed, then the resulting request will NOT contain the submit button value/pair.

A solution that worked for me is this one:

```<code>$(function() {
$('button[type=submit]').click(function () {
    $('<input>').attr({
        type: 'hidden',
        name: this.name,
        value: this.value
    }).appendTo($(this).closest('form'));
});
});
</code>```

Credit to arturoribes

Body:
I recently implemented remote validation in my form:

ViewModel:

[Remote("IsTagUnique", "myController", "myArea", ErrorMessage = "This tag already exists.")]
public string tag { get; set; }

Controller:

        public ActionResult IsTagUnique(string tag)
        {
            using (db)
            {
                try
                {
                    var myTag = db.ASAuftraege.Single(m => m.tag == tag);
                        return Json(false, JsonRequestBehavior.AllowGet);
                    }
                }
                catch (Exception)
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult myView(string Send){
            // doSomething
        }

View (called "myView")

@Html.TextBoxFor(m => m.tag) @Html.ValidationMessageFor(m => m.tag)

<button class="form-button-submit" type="submit" name="Send" value="Send">Send</button>

The validation works perfectly fine.

Problem is: When I click the Send-button without manually triggering the validation on the tag-field once by clicking into the field and then clicking somewhere else the "IsTagUnique" function is executed before the myView()-function. This causes my submit-inputs (I actually have multiple send-buttons, just like the one shown in the view (different name/value of course) to be null. Any idea what I can do? I tried triggering the validation manually by giving focus and blurring the tag-field, and by triggering a change event. Doesn't trigger the validation, though.

Body:
After searching for a while I found out this seems to be a known bug:

The issue happens when a form which uses the remote method to validate a field. If a submit button is pressed after the validator fires, everything is alright and the request will contain the clicked submit button name/value pair.
  However, when the remote method is not fired before the submit button is pressed, then the resulting request will NOT contain the submit button value/pair.

A solution that worked for me is this one:

$(function() {
$('button[type=submit]').click(function () {
    $('<input>').attr({
        type: 'hidden',
        name: this.name,
        value: this.value
    }).appendTo($(this).closest('form'));
});
});

Credit to arturoribes


问:
Navigate to a cell in a DataFrame using a set of criteria
I have a csv table like so:

```<code>a, b, c, d
value, value, value, value
value, value, value, value
</code>```

which I'm loading into a DataFrame. I also have a dictionary that looks like this:

```<code>data = {'a': some_value, 'b' = some_value, 'c' = some_value}
</code>```

I want to navigate to the cell in column d where the row has values a, b and c as specified by this dictionary. I know that there exists exactly one cell that matches these criteria. How can I do this?

答:
You could convert the data into a dataframe, then use a merge:</p>

```<code>data = pd.DataFrame({'a':[1,2,3,4], 'b':[1,2,3,4],'c':[1,2,3,4],'d':[1,2,3,4]})

lookup = {'a':2,'b':2, 'c':2}

lookupdf = pd.DataFrame(lookup, index = [1]) #need the index, as they are all scalar

pd.merge(lookupdf, data)

    a   b   c   d
0   2   2   2   2
</code>```

Body:
I have a csv table like so:

a, b, c, d
value, value, value, value
value, value, value, value

which I'm loading into a DataFrame. I also have a dictionary that looks like this:

data = {'a': some_value, 'b' = some_value, 'c' = some_value}

I want to navigate to the cell in column d where the row has values a, b and c as specified by this dictionary. I know that there exists exactly one cell that matches these criteria. How can I do this?

Body:
You could convert the data into a dataframe, then use a merge:

data = pd.DataFrame({'a':[1,2,3,4], 'b':[1,2,3,4],'c':[1,2,3,4],'d':[1,2,3,4]})

lookup = {'a':2,'b':2, 'c':2}

lookupdf = pd.DataFrame(lookup, index = [1]) #need the index, as they are all scalar

pd.merge(lookupdf, data)

    a   b   c   d
0   2   2   2   2


问:
Tab bar is also moving when i scroll the table view
I have written the code programmatically  for my tab bar in my table view.The problem whenever i am scrolling the table view,the tab bar is also moving.The tab bar created in one cell,so it is also scrolling.How to keep that in static.Please help me in this.
Thanks in advance</p>

答: DOn't put the TabBar in the Scrollview. Rather, have the TabBar at the bottom of the main view, and have the ScrollView extend only to the top of the TabBar. That should fix it. If you put the TabBar on the ScrollView, it will scroll around (that's what the ScrollView does).</p>


问:
Return SVG object in filter
I am creating a filter that is intended to change weather id code with corresponding image.

HTML looks like this:

```<code><span ng-bind-html="weather.today.weather[0].id | weatherIcon"></span>
</code>```

When I use img tag it works just fine:

```<code>.filter('weatherIcon', function() {
    return function() {
        var template = `<img src="img/weather-icons-set/CLOUDS/CLOUDS/001lighticons-02.svg">`;
        return template;
    }
})
</code>```

But I would like to embed my svg to be able changing colors etc. Unfortunately with object tag it doesn't work at all:

```<code>.filter('weatherIcon', function() {
    return function() {
        var template = `<object type="image/svg+xml" data="img/weather-icons-set/CLOUDS/CLOUDS/001lighticons-02.svg" width="100" height="100"></object>`;
        return template;
    }
})
</code>```

I've also tried to put ng-include in filter return, but it also failed. Can you tell me, what is wrong with returning <object> in a filter, or give me a hint for another approach?

答:
Ultimately I used a web-font instead. My filter looks like this:</p>

```<code>.filter('weatherIcon', function($sce) {
    return function(weatherCode, isNight) {

        var template;
        var iconCode;

        ...

        template = `<span class="icon" data-icon="${iconCode}"></span>`
        return $sce.trustAsHtml(template);
    }
})
</code>```

Title: Return SVG object in filter

Body:
I am creating a filter that is intended to change weather id code with corresponding image.

HTML looks like this:

When I use img tag it works just fine:

.filter('weatherIcon', function() {
    return function() {
        var template = `<img src="img/weather-icons-set/CLOUDS/CLOUDS/001lighticons-02.svg">`;
        return template;
    }
})

But I would like to embed my svg to be able changing colors etc. Unfortunately with object tag it doesn't work at all:

.filter('weatherIcon', function() {
    return function() {
        var template = `<object type="image/svg+xml" data="img/weather-icons-set/CLOUDS/CLOUDS/001lighticons-02.svg" width="100" height="100"></object>`;
        return template;
    }
})

I've also tried to put ng-include in filter return, but it also failed. Can you tell me, what is wrong with returning <object> in a filter, or give me a hint for another approach?

Body:
Ultimately I used a web-font instead. My filter looks like this:

.filter('weatherIcon', function($sce) {
    return function(weatherCode, isNight) {

        var template;
        var iconCode;

        ...

        template = `<span class="icon" data-icon="${iconCode}"></span>`
        return $sce.trustAsHtml(template);
    }
})


问:
How to create CSR in Azure?
I have bought my domain from whois and my site (Asp.Net MVC) in deployed in Azure. I want to add SSL which I want to buy from GoDaddy.com. To do that I have to generate CSR (certificate signing request) in Azure so that I can use it to get my SSL certificate from GoDaddy.

So how can I generate CSR in Azure?

答:
Azure doesn't provide any mechanism to generate CSR. There are several ways to generate CSR:

Using certificate MMC

Using IIS Manager

using certreq.exe

using openssl

and many more

I would suggest you to use the Digicert's CSR generation tool. It can be used to generate a CSR and then you can use this to submit to GoDaddy. Here are the instructions on how to do this: CSR Creation in Azure App Service

Once you submit the CSR to the CA, they will provide you a .cer/.crt/.der file, which doesn't contain the private key.

You will first need to import this certificate to bind the private key with the cert. Once done, export the certificate with the private key so that you can generate a .PFX file, which the Azure App Services needs. You can again use Digicert's certificate utility to export the certifiate in pfx format. See this: How to Export Your SSL Certificate w/Private Key Using the DigiCert Certificate Utility

Or you can use the certificate console via MMC. See this:

Add the Certificates Snap-in to an MMC

Export a Certificate with the Private Key

Title: How to create CSR in Azure?


问:
Force GeoLocation to allow
I am currently trying to build an app for employees to clock on and off from work each day.

I have currently setup geolocation to automatically get the location of the user and store it in a database however for obvious reasons if a user presses deny it cannot get the location.

Is there a way I can force location to be on for my page or prevent the page from loading if location is disabled.

I have managed to set this up with a function but if the user presses a not now button or select later the page still renders correctly and does not prevent the employee using the system.

What I need to do are the following:

Force Location Services to be on or Prevent the page from rendering if they are off

Bring up the allow/deny location services box on page load if they have previously denied their use.

Any help would be greatly appreciated.

答:
The format for geolocation is </p>

```<code>navigator.geolocation.getCurrentPosition(success, error, options)
</code>```

<p>You can check if user prevented the location prompt by following way </p>

```<code>navigator.geolocation.getCurrentPosition(
    function(position) {
        // Success goes here
    }.bind(this),
    function(error) {
        toastr.error("Please turn on location for this feature")
        setTimeout(function() {
            window.location.href = '/'
        }, 2000)
    }, [your options]
)
</code>```

Title: Force GeoLocation to allow

Body:
The format for geolocation is

navigator.geolocation.getCurrentPosition(success, error, options)

You can check if user prevented the location prompt by following way

navigator.geolocation.getCurrentPosition(
    function(position) {
        // Success goes here
    }.bind(this),
    function(error) {
        toastr.error("Please turn on location for this feature")
        setTimeout(function() {
            window.location.href = '/'
        }, 2000)
    }, [your options]
)


问:
How to extend session timeout in PHPMyAdmin?
In PHPMyAdmin, the default LoginCookieValidity is 1440 seconds.  I changed it in Settings > Fetaurues to 360000.

Also to make sure that the change remains permanent, in config.inc.php I added

```<code>$cfg['LoginCookieValidity'] = 360000
</code>```

But the session still expires after few minutes, which is very annoying. I'm wondering how can I fix this?

答:
Create or edit your php.ini file and set this variable value in it:

session.gc_maxlifetime = 1440

The integer is in seconds. 500000 seconds is 5.7 days. Then restart apache.

Body:
In PHPMyAdmin, the default LoginCookieValidity is 1440 seconds.  I changed it in Settings > Fetaurues to 360000.

Also to make sure that the change remains permanent, in config.inc.php I added

$cfg['LoginCookieValidity'] = 360000

But the session still expires after few minutes, which is very annoying. I'm wondering how can I fix this?


问:
How to join two tables in Codeigniter
I try to join 2 tables and output the result:

In model:

```<code>$this->db->select('*');
$this->db->from('news');
$this->db->join('authors', 'authors.id = news.author_id');
</code>```

In view files:

```<code>foreach($item as $row):
    echo $row->id;
endforeach;
</code>```

When I run the code above, it will output id column from authors table.
My question is how do I echo id column from news table?

Both news and author tables have column named id.

答:
Try echo $row->author_id

It seems like the field you want in the news table is author_id instead of id.

EDIT Otherwise you can use the as sql keyword in your select statement to give a different name to your field.

```<code>$this->db->select('*, news.id as my_news_id');
</code>```

And then do, echo $row->my_news_id

Title: How to join two tables in Codeigniter

Body:
I try to join 2 tables and output the result:

In model:

$this->db->select('*');
$this->db->from('news');
$this->db->join('authors', 'authors.id = news.author_id');

In view files:

foreach($item as $row):
    echo $row->id;
endforeach;

When I run the code above, it will output id column from authors table.
My question is how do I echo id column from news table?

Both news and author tables have column named id.

Body:
Try echo $row->author_id

It seems like the field you want in the news table is author_id instead of id.

EDIT Otherwise you can use the as sql keyword in your select statement to give a different name to your field.

$this->db->select('*, news.id as my_news_id');

And then do, echo $row->my_news_id


问:
Get value from a column with regex
I have lines of text similar to this:

value1|value2|value3 etc.

The values itself are not interesting. The type of delimeter is also unimportant, just like the number of fields. There could be 100 column, there could be only 5.

I would like to know what is the usual way to write a regexp which will put any given column's value into a capture group.

For example if I would like to get the content of the third field:

[^\|]+?\|[^\|]+?\|(?<capture_group>[^\|]+?)\|

Maybe a little bit nicer version:

(?:[^\|]+?\|){2}(?<capture_group>[^\|]+?)\|

But this could be the 7th, the 100th, the 1000th, it doesn't matter.

My problem is, that after a while I run into catastrophic backtracking or simply extremely low running times.

What is the usual way to solve a problem like this?

Edit:

For further clarification: this is a use case where further string operations are simply not permitted. Workarounds are not possible. I would like to know if there's a way simply based on regex or not.

答:
For example if I would like to get the content of the third field:

```<code>[^\|]+?\|[^\|]+?\|(?<capture_group>[^\|]+?)\|
</code>```

Maybe a little bit nicer version:

```<code>(?:[^\|]+?\|){2}(?<capture_group>[^\|]+?)\|
</code>```

But this could be the 7th, the 100th, the 1000th, it doesn't matter.

As a matter of "steps", using capture groups will cost more step.

However, using capture groups will allow you to condense your pattern and use a curly bracketed quantifier.

In your first pattern above, you can get away with "greedy" negated character classes (remove the ?) because they will halt at the next |, and you don't need to escape the pipe inside the square brackets.

When you want to access a "much later" positioned substring in the input string,  not using a quantifier is going to require a horrifically long pattern and make it very, very difficult to comprehend the exact point that will be matched.  In these cases, it would be pretty silly not to use a capture group and a quantifier.

I agree with Toto's comment; accessing an array of split results is going to be a very sensible solution if possible.

Title: Get value from a column with regex

Body:
For example if I would like to get the content of the third field:

[^\|]+?\|[^\|]+?\|(?<capture_group>[^\|]+?)\|

Maybe a little bit nicer version:

(?:[^\|]+?\|){2}(?<capture_group>[^\|]+?)\|

But this could be the 7th, the 100th, the 1000th, it doesn't matter.

As a matter of "steps", using capture groups will cost more step.

However, using capture groups will allow you to condense your pattern and use a curly bracketed quantifier.

In your first pattern above, you can get away with "greedy" negated character classes (remove the ?) because they will halt at the next |, and you don't need to escape the pipe inside the square brackets.

When you want to access a "much later" positioned substring in the input string,  not using a quantifier is going to require a horrifically long pattern and make it very, very difficult to comprehend the exact point that will be matched.  In these cases, it would be pretty silly not to use a capture group and a quantifier.

I agree with Toto's comment; accessing an array of split results is going to be a very sensible solution if possible.