问:
Ionic3/Angular4: Two-way databinding stops working after click event on Google-Maps
I am using Ionic 3 and I am using the Google Maps plugin for it. I have two pages, a list and a map. I display the same objects on both views and when you click a list entry or a marker (info window), the object's detail page will be opened where you can rate the selected object.

Anyway, when I open the detail page via the list, everything works fine but when I open the detail page via the map-marker, the two-way data binding stops working. In the code below you can find the <rating-input> component in the rating dialog. That's the code that's not working.

I've tried using a simple input text to find out if it's really the two way data binding or if it's my component. The data binding did not work either using the simple textbox.

Here is the code:

```<code> //adding the markers to the map and adding the clicklisteners
 putMarkersForMarkets(markets: Christmasmarket[]) {

markets.forEach(market => {
  let isOpen = this.openinghoursService.isOpenAt(market, new Date());
  this.map.addMarker({
    title: market.name,
    icon: isOpen ? 'green' : 'red',
    animation: 'DROP',
    position: {
      lat: market.position.latitude,
      lng: market.position.longitude
    }
  }).then(marker => {
    marker.on(GoogleMapsEvent.INFO_CLICK)
      .subscribe(() => {
        this.onClickMarket(market);
      });
  });;

});

}

onClickMarket(market: Christmasmarket) {
       this.map.setVisible(false);
       this.map.setClickable(false);
     this.app.getRootNav().push(MarketDetailPage, { data: market });
   }
</code>```

Rating-Popup html:

```<code><ion-header>
  <ion-navbar color="primary">
    <ion-title>{{'RATINGDIALOG.TITLE' | translate}}</ion-title>
    <ion-buttons end>
      <button ion-button icon-only (click)="dismiss()">
      <ion-icon name="close"></ion-icon>
    </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <form #form="ngForm">
    <b>{{'RATINGDIALOG.HEADERMARKET' | translate}}</b><br>
    <rating-input [(rating)]="rating" [texts]="ratingTexts" name="rating"></rating-input>
    <b>{{'RATINGDIALOG.HEADERPRICE' | translate}}</b><br>
    <rating-input [(rating)]="ratingPrice" symbol="logo-euro" [texts]="ratingPriceTexts"></rating-input>

    <input type="text" [(value)]="meinval">

    {{meinval}}
  </form>
</ion-content>
<ion-footer>
  <ion-row>
    <ion-col>
      <button [disabled]="rating == 0 || ratingPrice == 0" ion-button full color="secondary" (click)="saveRating()">
        {{'RATINGDIALOG.SAVE' | translate}}
    </button>
    </ion-col>
    <ion-col>
      <button ion-button full color="secondary" (click)="dismiss()">{{'RATINGDIALOG.CANCEL' | translate}}
      </button>
    </ion-col>
  </ion-row>
</ion-footer>
</code>```

Rating popup typescript:

```<code>import { Component, OnInit } from '@angular/core';
import { ViewController, NavParams } from 'ionic-angular';
import { Christmasmarket } from "../../../model/christmasmarket";
import { ChristmasMarketService } from "../../../services/christmasmarketservice";
import { TranslateService } from "@ngx-translate/core";

@Component({
  selector: 'rating-dialog',
  templateUrl: 'ratingdialog.component.html'
})
export class RatingDialogComponent implements OnInit {

  rating: number;
  ratingPrice: number;

  ratingTexts: Array<string>;
  ratingPriceTexts: Array<string>;

  market: Christmasmarket;

  meinval: String;
  constructor(
    private viewCtrl: ViewController,
    private navParams: NavParams,
    private christmasMarketService: ChristmasMarketService,
    private translate: TranslateService
  ) {

  }

  ngOnInit(): void {

    this.translate.get('RATINGTEXTS').subscribe(res => {
      this.ratingTexts = [];
      this.ratingTexts.push(res['VALUE1']);
      this.ratingTexts.push(res['VALUE2']);
      this.ratingTexts.push(res['VALUE3']);
      this.ratingTexts.push(res['VALUE4']);
      this.ratingTexts.push(res['VALUE5']);
    });

    this.translate.get('RATINGPRICETEXTS').subscribe(res => {
      this.ratingPriceTexts = [];
      this.ratingPriceTexts.push(res['VALUE1']);
      this.ratingPriceTexts.push(res['VALUE2']);
      this.ratingPriceTexts.push(res['VALUE3']);
      this.ratingPriceTexts.push(res['VALUE4']);
      this.ratingPriceTexts.push(res['VALUE5']);
    });

    this.market = this.navParams.get('data');
    this.rating = 0;
    this.ratingPrice = 0;

    this.christmasMarketService.findRatingOfMarket(this.market.id).then(rating => {

      if (rating) {
        this.rating = rating.rating;
        this.ratingPrice = rating.ratingPrice;
      }
    }).catch(e => {

        console.log(e);
    });
  }

  dismiss() {
    this.viewCtrl.dismiss(this.market);
  }

  saveRating() {
    this.christmasMarketService.rateMarket(this.market.id, this.rating, this.ratingPrice).then(market => {
      this.market = market;
      this.dismiss();
      console.log(market);
  }).catch(e => {
      console.log(e);
  });

  }

}
</code>```

Rating-input component html

```<code><button ion-button icon-only clear="true" (click)="onClickRating(num)" *ngFor="let num of possibleRatings">
<ion-icon [name]="symbol"  [color]="rating >= num ? 'black' : 'grey'"></ion-icon>
</button>
<p *ngIf="texts">
    {{texts[rating-1]}}
</p>
<p *ngIf="!rating || rating == 0">
    -
</p>
</code>```

rating-input component typescript

import { Component, Input, Output, EventEmitter } from "@angular/core";

```<code>@Component({
  selector: 'rating-input',
  templateUrl: 'ratinginput.component.html'
})
export class RatingInputComponent{

  @Input() @Output() rating: number;
  @Input() symbol: string = 'star';
  @Input() texts : Array<string>;

  @Output() ratingChange = new EventEmitter();

  possibleRatings: Array<number> = [1, 2, 3, 4, 5];

  onClickRating(rating: number) {
    this.rating = rating;
    this.ratingChange.emit(this.rating);
  }
}
</code>```

答:
You Can Use Ng zone</p>

```<code> import { NgZone  } from '@angular/core';

    export class AppComponent {

    constructor(public zone: NgZone){
     window['AppComponent'] = {component: this, zone: zone};
    }
    onClickRating(){
    window['AppComponent'].zone.run(() => {window['AppComponent'].component.yourFunctionName();});
    }
    }
</code>```

Body:
I am using Ionic 3 and I am using the Google Maps plugin for it. I have two pages, a list and a map. I display the same objects on both views and when you click a list entry or a marker (info window), the object's detail page will be opened where you can rate the selected object.

Anyway, when I open the detail page via the list, everything works fine but when I open the detail page via the map-marker, the two-way data binding stops working. In the code below you can find the <rating-input> component in the rating dialog. That's the code that's not working.

I've tried using a simple input text to find out if it's really the two way data binding or if it's my component. The data binding did not work either using the simple textbox.

Here is the code:

 //adding the markers to the map and adding the clicklisteners
 putMarkersForMarkets(markets: Christmasmarket[]) {

markets.forEach(market => {
  let isOpen = this.openinghoursService.isOpenAt(market, new Date());
  this.map.addMarker({
    title: market.name,
    icon: isOpen ? 'green' : 'red',
    animation: 'DROP',
    position: {
      lat: market.position.latitude,
      lng: market.position.longitude
    }
  }).then(marker => {
    marker.on(GoogleMapsEvent.INFO_CLICK)
      .subscribe(() => {
        this.onClickMarket(market);
      });
  });;

});

}

onClickMarket(market: Christmasmarket) {
       this.map.setVisible(false);
       this.map.setClickable(false);
     this.app.getRootNav().push(MarketDetailPage, { data: market });
   }

Rating-Popup html:

<ion-header>
  <ion-navbar color="primary">
    <ion-title>{{'RATINGDIALOG.TITLE' | translate}}</ion-title>
    <ion-buttons end>
      <button ion-button icon-only (click)="dismiss()">
      <ion-icon name="close"></ion-icon>
    </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <form #form="ngForm">
    {{'RATINGDIALOG.HEADERMARKET' | translate}}

    <rating-input [(rating)]="rating" [texts]="ratingTexts" name="rating"></rating-input>
    {{'RATINGDIALOG.HEADERPRICE' | translate}}

    <rating-input [(rating)]="ratingPrice" symbol="logo-euro" [texts]="ratingPriceTexts"></rating-input>

    <input type="text" [(value)]="meinval">

    {{meinval}}
  </form>
</ion-content>
<ion-footer>
  <ion-row>
    <ion-col>
      <button [disabled]="rating == 0 || ratingPrice == 0" ion-button full color="secondary" (click)="saveRating()">
        {{'RATINGDIALOG.SAVE' | translate}}
    </button>
    </ion-col>
    <ion-col>
      <button ion-button full color="secondary" (click)="dismiss()">{{'RATINGDIALOG.CANCEL' | translate}}
      </button>
    </ion-col>
  </ion-row>
</ion-footer>

Rating popup typescript:

import { Component, OnInit } from '@angular/core';
import { ViewController, NavParams } from 'ionic-angular';
import { Christmasmarket } from "../../../model/christmasmarket";
import { ChristmasMarketService } from "../../../services/christmasmarketservice";
import { TranslateService } from "@ngx-translate/core";

@Component({
  selector: 'rating-dialog',
  templateUrl: 'ratingdialog.component.html'
})
export class RatingDialogComponent implements OnInit {

  rating: number;
  ratingPrice: number;

  ratingTexts: Array<string>;
  ratingPriceTexts: Array<string>;

  market: Christmasmarket;

  meinval: String;
  constructor(
    private viewCtrl: ViewController,
    private navParams: NavParams,
    private christmasMarketService: ChristmasMarketService,
    private translate: TranslateService
  ) {

  }

  ngOnInit(): void {

    this.translate.get('RATINGTEXTS').subscribe(res => {
      this.ratingTexts = [];
      this.ratingTexts.push(res['VALUE1']);
      this.ratingTexts.push(res['VALUE2']);
      this.ratingTexts.push(res['VALUE3']);
      this.ratingTexts.push(res['VALUE4']);
      this.ratingTexts.push(res['VALUE5']);
    });

    this.translate.get('RATINGPRICETEXTS').subscribe(res => {
      this.ratingPriceTexts = [];
      this.ratingPriceTexts.push(res['VALUE1']);
      this.ratingPriceTexts.push(res['VALUE2']);
      this.ratingPriceTexts.push(res['VALUE3']);
      this.ratingPriceTexts.push(res['VALUE4']);
      this.ratingPriceTexts.push(res['VALUE5']);
    });

    this.market = this.navParams.get('data');
    this.rating = 0;
    this.ratingPrice = 0;

    this.christmasMarketService.findRatingOfMarket(this.market.id).then(rating => {

      if (rating) {
        this.rating = rating.rating;
        this.ratingPrice = rating.ratingPrice;
      }
    }).catch(e => {

        console.log(e);
    });
  }

  dismiss() {
    this.viewCtrl.dismiss(this.market);
  }

  saveRating() {
    this.christmasMarketService.rateMarket(this.market.id, this.rating, this.ratingPrice).then(market => {
      this.market = market;
      this.dismiss();
      console.log(market);
  }).catch(e => {
      console.log(e);
  });

  }

}

Rating-input component html

<button ion-button icon-only clear="true" (click)="onClickRating(num)" *ngFor="let num of possibleRatings">
<ion-icon [name]="symbol"  [color]="rating >= num ? 'black' : 'grey'"></ion-icon>
</button>

    {{texts[rating-1]}}

    -

rating-input component typescript

import { Component, Input, Output, EventEmitter } from "@angular/core";

@Component({
  selector: 'rating-input',
  templateUrl: 'ratinginput.component.html'
})
export class RatingInputComponent{

  @Input() @Output() rating: number;
  @Input() symbol: string = 'star';
  @Input() texts : Array<string>;

  @Output() ratingChange = new EventEmitter();

  possibleRatings: Array<number> = [1, 2, 3, 4, 5];

  onClickRating(rating: number) {
    this.rating = rating;
    this.ratingChange.emit(this.rating);
  }
}

Body:
You Can Use Ng zone

 import { NgZone  } from '@angular/core';

    export class AppComponent {

    constructor(public zone: NgZone){
     window['AppComponent'] = {component: this, zone: zone};
    }
    onClickRating(){
    window['AppComponent'].zone.run(() => {window['AppComponent'].component.yourFunctionName();});
    }
    }


来源: stackexchange

问:
How to test functions for equality when unit testing
I have the following code:

```<code>DeviceEventEmitter.addListener(eventName, () => { return 'myHandler' })
</code>```

I am testing that DeviceEventEmitter is called with the following test:

```<code>DeviceEventEmitter.addListener = jest.fn();
expect(DeviceEventEmitter.addListener.mock.calls[0][1]).toEqual(() => { return 'myHandler' });
</code>```

However, the test fails with:

```<code>expect(received).toEqual(expected)

Expected value to equal:
  [Function anonymous]
Received:
  [Function anonymous]
</code>```

It looks like it doesn't understand that the functions are the same.

So how can I make it detect when the functions are the same?

答:
This will always return false because you're creating a new function as parameter for the toEqual function:

```<code>expect(DeviceEventEmitter.addListener.mock.calls[0][1]).toEqual(() => { return 'myHandler' });
</code>```

2 functions with the same body are still different. You have to keep the reference to the listener and then compare the reference:

```<code>var listener = () => { return 'myHandler' }
DeviceEventEmitter.addListener(eventName, listener)

DeviceEventEmitter.addListener = jest.fn();
expect(DeviceEventEmitter.addListener.mock.calls[0][1]).toEqual(listener);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following code:

DeviceEventEmitter.addListener(eventName, () => { return 'myHandler' })

I am testing that DeviceEventEmitter is called with the following test:

DeviceEventEmitter.addListener = jest.fn();
expect(DeviceEventEmitter.addListener.mock.calls[0][1]).toEqual(() => { return 'myHandler' });

However, the test fails with:

expect(received).toEqual(expected)

Expected value to equal:
  [Function anonymous]
Received:
  [Function anonymous]

It looks like it doesn't understand that the functions are the same.

So how can I make it detect when the functions are the same?

Body:
This will always return false because you're creating a new function as parameter for the toEqual function:

expect(DeviceEventEmitter.addListener.mock.calls[0][1]).toEqual(() => { return 'myHandler' });

2 functions with the same body are still different. You have to keep the reference to the listener and then compare the reference:

var listener = () => { return 'myHandler' }
DeviceEventEmitter.addListener(eventName, listener)

DeviceEventEmitter.addListener = jest.fn();
expect(DeviceEventEmitter.addListener.mock.calls[0][1]).toEqual(listener);


问:
Apply function over rows in pandas df
In a pandas df, I have a column ['name'] with various Operating System classifications such as 'Windows 7', 'Windows 10', 'Linux', 'Mobile iOS 9.1', 'OS X 10.12', etc. That are strings.

I am hoping to use this function to create a new column ['type'] that will be a more generalized version:

```<code>def name_group(row):
    if 'Windows' in row:
        name = 'Microsoft Windows'
    elif 'iOS' in row:
        name = 'Apple iOS'
    elif 'OS X' in row:
        name ='Apple Macintosh'
    elif 'Macintosh' in row:
        name = 'Apple Macintosh'
    elif 'Linux' in row:
        name = 'GNU/Linux'
    else:
        name = 'Other'
    return name
</code>```

It works correctly when I test the function by passing in a single string variable, but for some reason when I apply the function to the df like this, it only returns "other" for each row.

```<code>new_df['type'] = new_df.apply(name_group, axis=1)
</code>```

Any thoughts on what could be causing this?

答:
You need pass column name with Series.apply:

```<code>new_df['type'] = new_df['name'].apply(name_group)
</code>```

But if want use DataFrame.apply then need lambda function and pass name of column too:

```<code>new_df['type'] = new_df.apply(lambda x: name_group(x['name']), axis=1)
</code>```

Title: Apply function over rows in pandas df

Body:
In a pandas df, I have a column ['name'] with various Operating System classifications such as 'Windows 7', 'Windows 10', 'Linux', 'Mobile iOS 9.1', 'OS X 10.12', etc. That are strings.

I am hoping to use this function to create a new column ['type'] that will be a more generalized version:

def name_group(row):
    if 'Windows' in row:
        name = 'Microsoft Windows'
    elif 'iOS' in row:
        name = 'Apple iOS'
    elif 'OS X' in row:
        name ='Apple Macintosh'
    elif 'Macintosh' in row:
        name = 'Apple Macintosh'
    elif 'Linux' in row:
        name = 'GNU/Linux'
    else:
        name = 'Other'
    return name

It works correctly when I test the function by passing in a single string variable, but for some reason when I apply the function to the df like this, it only returns "other" for each row.

new_df['type'] = new_df.apply(name_group, axis=1)

Any thoughts on what could be causing this?

Body:
You need pass column name with Series.apply:

new_df['type'] = new_df['name'].apply(name_group)

But if want use DataFrame.apply then need lambda function and pass name of column too:

new_df['type'] = new_df.apply(lambda x: name_group(x['name']), axis=1)


问:
object oriented JavaScript
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

```<code>function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}
</code>```

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

```<code>function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

and

```<code>var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

答:
I think that you want to do this: var newpoint =  [new Point]. (The way you do is initialising element 0 with new object, but element 0 of newpoint doesn't exist, because you never said that newpoint is an array.) That way you initialised first element of an array newpoint to that new Point, so this: newpoint[0].x = 10 can execute.

But then this: newpoint[length].x = 10*i will fail because your array only has one element initialised and it is newpoint[0], all others are undefined. I think you want to initialise them first (all 10) like so for example:

```<code>for(var i=1; i<10; i++)
{
    newpoint.push(new Point());
}
</code>```

Also, change Point like below if you want to be able to see x and y in the object you created!

```<code>function Point()
{
    this.x;
    this.y;
}
</code>```

Then your code will run fine...

ContentLicense: CC BY-SA 2.5

Title: object oriented JavaScript

Body:
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

and

var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

Body:
I think that you want to do this: var newpoint =  [new Point]. (The way you do is initialising element 0 with new object, but element 0 of newpoint doesn't exist, because you never said that newpoint is an array.) That way you initialised first element of an array newpoint to that new Point, so this: newpoint[0].x = 10 can execute.

But then this: newpoint[length].x = 10*i will fail because your array only has one element initialised and it is newpoint[0], all others are undefined. I think you want to initialise them first (all 10) like so for example:

for(var i=1; i<10; i++)
{
    newpoint.push(new Point());
}

Also, change Point like below if you want to be able to see x and y in the object you created!

function Point()
{
    this.x;
    this.y;
}

Then your code will run fine...


问:
REST request argument Validation In Router Function
In Spring controller approach, We could do REST request argument validation using @Valid with Something like this

```<code>@PostMapping(REGISTER)
  public ResponseEntity<SomeData> registerSomeData(@RequestBody @Valid final SomeData someData) {
    ...................
  }

public class SomeData {

  @Size(min = 2, max = 20)
  private String firstname;

  @Digits(fraction = 0, integer = 10)
  private Integer customerID;

  @NotNull
  private Customer customer;
}
</code>```

If the request doesn't match these contraints, then Spring framework would throw Bad Request Exception(400).

With Spring5 router functions, I don't understand how we can do this, because we can't give @Valid in router functions.

答:
You can't use annotation-based validation with (functional) Spring Webflux. See this answer.

If you absolutely need annotation-based validation, you should know that you can keep using the traditional Spring MVC with Spring 5 (or non-functional Webflux).

Body:
In Spring controller approach, We could do REST request argument validation using @Valid with Something like this

@PostMapping(REGISTER)
  public ResponseEntity<SomeData> registerSomeData(@RequestBody @Valid final SomeData someData) {
    ...................
  }

public class SomeData {

  @Size(min = 2, max = 20)
  private String firstname;

  @Digits(fraction = 0, integer = 10)
  private Integer customerID;

  @NotNull
  private Customer customer;
}

If the request doesn't match these contraints, then Spring framework would throw Bad Request Exception(400).

With Spring5 router functions, I don't understand how we can do this, because we can't give @Valid in router functions.


问:
Python - If row more than, do something
I'm new to Python and i'm trying to create a block of code that prints a statement if a value is more than a value I've defined. The below code however isn't working, it's not printing anything despite the values of row[4] being greater than '10'. Even when I try == '55.9280': it still doesn't satisfy the criteria, and itsn't printing anything. Thanks in advance!

The list is an output of a MySQL statement string convetred into a list. With row[4] being QueryTime.

```<code>Forename: Surname: Email: Querytime:
</code>```

e.g.

```<code>for row in list:
    print row[4]
    if row[4] > '10':
        print("is greater than")
</code>```

row 4 =

```<code>55.9280
45.5300
40.2040
38.7850
32.8320
32.5820
31.6290
30.0630
29.4950
28.9780
</code>```

Title: Python - If row more than, do something

Body:
I'm new to Python and i'm trying to create a block of code that prints a statement if a value is more than a value I've defined. The below code however isn't working, it's not printing anything despite the values of row[4] being greater than '10'. Even when I try == '55.9280': it still doesn't satisfy the criteria, and itsn't printing anything. Thanks in advance!

The list is an output of a MySQL statement string convetred into a list. With row[4] being QueryTime.

Forename: Surname: Email: Querytime:

e.g.

for row in list:
    print row[4]
    if row[4] > '10':
        print("is greater than")

row 4 =

55.9280
45.5300
40.2040
38.7850
32.8320
32.5820
31.6290
30.0630
29.4950
28.9780

Body:
>>> print 55.9280 == '55.9280'
False
>>> print 55.9280 == 55.9280
True
>>> print 55.9280 > '10'
False
>>> print 55.9280 > 10
True

You need to pay attention to data types.


问:
What is better: WHERE n = 0 or WHERE n != 1
I'm making a lot of times a query which have almost always a condition for "hidden" status in Mysql DB.

A piece is this:

```<code>...
WHERE `price` >= '7500'
AND `ads`.`subcat_id` = '22'
AND `recycle_bin` != 1
AND `hidden` =0
...
</code>```

So, an idea came into my mind... what's most optimal?
This:

```<code>AND `recycle_bin` != 1
</code>```

or this:

```<code>AND `recycle_bin` = 0
</code>```

or both?

答:
By testing it, you can appreciate that the elapsed time is the same, but there are differences in CPU time. For a table with ~10k rows:

```<code>SELECT * FROM table where field = 0;
</code>```

returns CPU time = 15 ms,  elapsed time = 32 ms.
And if you do:

```<code>SELECT * FROM table where field != 1;
</code>```

returns CPU time = 31 ms,  elapsed time = 32 ms.

Body:
I'm making a lot of times a query which have almost always a condition for "hidden" status in Mysql DB.

A piece is this:

...
WHERE `price` >= '7500'
AND `ads`.`subcat_id` = '22'
AND `recycle_bin` != 1
AND `hidden` =0
...

So, an idea came into my mind... what's most optimal?
This:

AND `recycle_bin` != 1

or this:

AND `recycle_bin` = 0

or both?

Body:
By testing it, you can appreciate that the elapsed time is the same, but there are differences in CPU time. For a table with ~10k rows:

SELECT * FROM table where field = 0;

returns CPU time = 15 ms,  elapsed time = 32 ms.
And if you do:

SELECT * FROM table where field != 1;

returns CPU time = 31 ms,  elapsed time = 32 ms.


问:
SSMS Joins and COUNT function
I've got a database which records all the jobs that we complete for the various departments in the business.

Table 1 is Department – this stores the name of the department alongside it's ID

Table 2 is Section – this stores the name of section alongside it's ID (one department could have several sections)

Table 3 is User – name of the person who completed the task, alongside the department and section id that the task was for)

Table 4 is date of completion – this contains the name of the person who completed the task and the date it was submitted to the system

Big boss wants me to provide a report that will detail how many jobs each department and section have submitted within a certain time frame.

So far I have got this:

```<code>SELECT  Dept.DepartmenttId,
Name.SectionId,
count (Name.DepartmentId)
FROM    Name
LEFT join Job on Name.UserId = Job.UserId
WHERE Job.DateSubmitted > '2017-09-01 00:00:00.000' and Job.DateSubmitted <'2017-09-30 23:59:59.000'
Group by Name.DepartmentId, Name.SectionId
</code>```

That gives me results like:

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

where I am getting the name of person alongside the department ID and section ID.

What I want is:

```<code>Bob    IT    Development
</code>```

so I can see the name of the department and section rather than the IDs.

I've been playing around with joins, but everything I try breaks the count part. Is there a way to get the count and the names within one query? Have I gone wrong in the way I've structured what I have so far?

Current tables:

DEPARTMENT

```<code>DepartmentId :: DepartmentName
1 :: IT
2 :: Marketing
3 :: Finance
</code>```

SECTION

```<code>SectionId :: SectionName
1 :: Development
2 :: Helpdesk
3 :: Architecture
4 :: Procurement
</code>```

NAME

```<code>Name :: JobId :: DepartmentId :: SectionId
Bob :: J1234 :: 1 :: 2
Steve :: J1235 :: 3 :: 4
</code>```

JOB

```<code>JOBId :: DateSubmitted
J1234 :: 02/09/2017
J1235 :: 04/09/2017
</code>```

答:
Based on the query provided by Eralper, I think I've got it: </p>

```<code>SELECT DepartmentName, SectionName, Count(*) as JobCount
FROM Name
INNER JOIN Department on Name.DepartmentId = Department.DepartmentId
INNER JOIN Section on Name.SectionId = Section.SectionId
INNER JOIN Job on Name.JobId = Job.JobId
WHERE Job.DateSubmitted between '2017-09-01 00:00:00.000' and '2017-09-20 23:59:59.000'
GROUP BY DepartmentName, SectionName
</code>```

Title: SSMS Joins and COUNT function

Body:
I've got a database which records all the jobs that we complete for the various departments in the business.

Table 1 is Department – this stores the name of the department alongside it's ID

Table 2 is Section – this stores the name of section alongside it's ID (one department could have several sections)

Table 3 is User – name of the person who completed the task, alongside the department and section id that the task was for)

Table 4 is date of completion – this contains the name of the person who completed the task and the date it was submitted to the system

Big boss wants me to provide a report that will detail how many jobs each department and section have submitted within a certain time frame.

So far I have got this:

SELECT  Dept.DepartmenttId,
Name.SectionId,
count (Name.DepartmentId)
FROM    Name
LEFT join Job on Name.UserId = Job.UserId
WHERE Job.DateSubmitted > '2017-09-01 00:00:00.000' and Job.DateSubmitted <'2017-09-30 23:59:59.000'
Group by Name.DepartmentId, Name.SectionId

That gives me results like:

BOB      2    3
STEVE    1    2

where I am getting the name of person alongside the department ID and section ID.

What I want is:

Bob    IT    Development

so I can see the name of the department and section rather than the IDs.

I've been playing around with joins, but everything I try breaks the count part. Is there a way to get the count and the names within one query? Have I gone wrong in the way I've structured what I have so far?

Current tables:

DEPARTMENT

DepartmentId :: DepartmentName
1 :: IT
2 :: Marketing
3 :: Finance

SECTION

SectionId :: SectionName
1 :: Development
2 :: Helpdesk
3 :: Architecture
4 :: Procurement

NAME

Name :: JobId :: DepartmentId :: SectionId
Bob :: J1234 :: 1 :: 2
Steve :: J1235 :: 3 :: 4

JOB

JOBId :: DateSubmitted
J1234 :: 02/09/2017
J1235 :: 04/09/2017

Body:
Based on the query provided by Eralper, I think I've got it:

SELECT DepartmentName, SectionName, Count(*) as JobCount
FROM Name
INNER JOIN Department on Name.DepartmentId = Department.DepartmentId
INNER JOIN Section on Name.SectionId = Section.SectionId
INNER JOIN Job on Name.JobId = Job.JobId
WHERE Job.DateSubmitted between '2017-09-01 00:00:00.000' and '2017-09-20 23:59:59.000'
GROUP BY DepartmentName, SectionName

ContentLicense: CC BY-SA 4.0


问:
Octlet, quad word or what?
I am translating some documentation on libraw1394 to Russian. The documentation on libraw1394 says:

The basic data structures defined in
  the standard and used in this document
  are the quadlet (32 bit quantity) and
  the octlet (64 bit quantity)...

There is no such unit like "octlet" in Russian. I used to use "quad word" (russian "chetvertnoye slovo") for 64 bit quantity. Would it be correct to substitute "octlet" by "quad word"?

What are the alternative terms for "octlet"?

答:
Looking at http://en.wikipedia.org/wiki/Integer_(computer_science), one could use "doubleword" or "quadword" for 64bit integers, yet "quadword" can also be used for 128bit integers and "doubleword" for 32bit ones.

The problem is the term "word", which actually means a "fixed sized group of bits that are handled together by the system" ( http://en.wikipedia.org/wiki/Word_(computing) ).

In Intel's documentation on its own processors:

"word" means "16bit integers",

"double word" means "32bit integers",

"quad word" means "64bit integers",

"double quad word" means "128bit integers".

Title: Octlet, quad word or what?


答:
Not sure what you're trying to do (see xyproblem.info) but the following code is similar to yours and doesn't crash. You need to convert between strings and integers if that is what you want. </p>

```<code>[list = \[\[1,2,3,4,5\], \[5,10,15,20,25\], \[15,16,17,18,19\], \[20,21,22,23,24\], \[21,22,23,24,25\]\]

for row in list:
    print row\[4\]
    if row\[4\] > int('10'):
        print("is greater than")][1]
</code>```

Title: Python - If row more than, do something

Body:
Not sure what you're trying to do (see xyproblem.info) but the following code is similar to yours and doesn't crash. You need to convert between strings and integers if that is what you want.

[list = \[\[1,2,3,4,5\], \[5,10,15,20,25\], \[15,16,17,18,19\], \[20,21,22,23,24\], \[21,22,23,24,25\]\]

for row in list:
    print row\[4\]
    if row\[4\] > int('10'):
        print("is greater than")][1]


问:
Updating a value in a particular column and maintaining it throughout the database
i have a requirement to substitute a value with some another value and maintain that through out the tables present in the oracle database .

For example: i have a column called city in table tab_a. In city column i can have numerous values of cities and many of the will be repeating.

So if i change value "a-> b" in city column of table tab_a, wherever a comes in the city column it should be changed to b.

Now suppose i have another table by the name of "tab_c" which has city column.
so if city of column of tab_c table consist of value "a" it should also be changed to "b".

Can somebody help me to implement this .

答:
This would be a fine relational desing - you have a dedicated table with citiestab_citywith a PK andcity_name. Other tables use the PKID` to reference it.

```<code>create table tab_a
(id number,
city_id number);

create table tab_b
(id number,
city_id number);

create table tab_city
(id number,
city_name number);
</code>```

A change of city name a signle update of the city_tab because the ID remains the same.

```<code>update tab_city
set city_name = 'New York'
where id = 1;
-- 1 record updated, former name  of ID = 1 was "York"
</code>```

Contrary to this, your design identifies the city with the name. This is problematic as for each change you must update all the references.

```<code>create table tab_a
(city_name varchar2(100));

create table tab_b
(city_name varchar2(100));
</code>```

While performing the updates below, you see immediately the difference to the propper relational design.

```<code>update tab_a
set city_name = 'New York'
where city_name = 'York';
-- tons of records updated

update tab_b
set city_name = 'New York'
where city_name = 'York';
-- tons of records updated
</code>```

Body:
This would be a fine relational desing - you have a dedicated table with citiestab_citywith a PK andcity_name. Other tables use the PKID` to reference it.

create table tab_a
(id number,
city_id number);

create table tab_b
(id number,
city_id number);

create table tab_city
(id number,
city_name number);

A change of city name a signle update of the city_tab because the ID remains the same.

update tab_city
set city_name = 'New York'
where id = 1;
-- 1 record updated, former name  of ID = 1 was "York"

Contrary to this, your design identifies the city with the name. This is problematic as for each change you must update all the references.

create table tab_a
(city_name varchar2(100));

create table tab_b
(city_name varchar2(100));

While performing the updates below, you see immediately the difference to the propper relational design.

update tab_a
set city_name = 'New York'
where city_name = 'York';
-- tons of records updated

update tab_b
set city_name = 'New York'
where city_name = 'York';
-- tons of records updated


问:
How i can override Accessibility className for android.widget.TextView
I want to "talkback" anounces standart TextView as button.
i tried to use this way

```<code>public class AccessibilityDelegateButton extends AccessibilityDelegateCompat {
    private CharSequence  className;
    public AccessibilityDelegateButton(CharSequence className) {
        super();
        this.className =className;
    }

    @Override
    public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
        super.onPopulateAccessibilityEvent(host,event);
        event.setClassName(className);
    }

    @Override
    public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
        super.onInitializeAccessibilityNodeInfo(host,info);
        info.setClassName(className);
    }
}
</code>```

and activity:

```<code>    TextView finishButton= new TextView(this);
    ViewCompat.setAccessibilityDelegate(finishButton, new AccessibilityDelegateButton(Button.class.getName()));
</code>```

but it does not work...

答:
As stated in the official documentation

On platform versions prior to API 23, delegate methods on views in the android.widget.* package are called before host methods. This prevents certain properties such as class name from being modified

Starting in API 23, delegate methods are called after host methods, which all properties to be modified without being overwritten by the host class.

And that should be the same for AccessibilityDelegateCompat according to the note

Are you on API < 23 maybe?
In that case you have to set the class name in onInitializeAccessibilityNodeInfo method of View.AccessibilityDelegateCompat

Body:
I want to "talkback" anounces standart TextView as button.
i tried to use this way

public class AccessibilityDelegateButton extends AccessibilityDelegateCompat {
    private CharSequence  className;
    public AccessibilityDelegateButton(CharSequence className) {
        super();
        this.className =className;
    }

    @Override
    public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
        super.onPopulateAccessibilityEvent(host,event);
        event.setClassName(className);
    }

    @Override
    public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
        super.onInitializeAccessibilityNodeInfo(host,info);
        info.setClassName(className);
    }
}

and activity:

    TextView finishButton= new TextView(this);
    ViewCompat.setAccessibilityDelegate(finishButton, new AccessibilityDelegateButton(Button.class.getName()));

but it does not work...


问:
Is there a way to block or assert on accidental recursion in c#
I am working with a large and complex event driven body of code and there are piles of opportunity to accidentally create a recursive condition.

Sometimes the recursive condition is temporary and the application catches up with itself but even that usually creates unnecessary lag.  Other times it creates a stackoverflow which is often very difficult to debug when it happens at a client site.

I would like to have a way to either blacklist or whitelist sections of code that are permitted to recurse.   If the recursive condition happens during DEV then I want it to assert so that I can correct the code.

What I am considering is having the application examine its own stack to ensure that the method it just entered is not already on the stack.

Any pointers would be appreciated.

Note: This is for a Web Application but I have run into this challenge in multiple environments.

答:
You can inspect stack like this:

```<code>[MethodImpl(MethodImplOptions.NoInlining)]
// optionally decorate with Conditional to only be used in Debug configuration
[Conditional("DEBUG")]
public static void FailIfCallerIsRecursive() {
    var trace = new StackTrace();
    // previous frame is the caller
    var caller = trace.GetFrame(1).GetMethod();
    // inspect the rest
    for (int i = 2; i < trace.FrameCount; i++) {
        // if found caller somewhere up the stack - throw
        if (trace.GetFrame(i).GetMethod() == caller)
            throw new Exception("Recursion detected");
    }
}
</code>```

Then just call it a the beginning:

```<code>void MyPotentiallyRecursiveMethod() {
    FailIfCallerIsRecursive()
}
</code>```

But note that it's quite expensive. However since you are going to use that only in dev (debug) configuration - why not. You can also modify it a bit to throw only when certain level of recursion is detected (so caller appears X time up the stack).

Body:
You can inspect stack like this:

[MethodImpl(MethodImplOptions.NoInlining)]
// optionally decorate with Conditional to only be used in Debug configuration
[Conditional("DEBUG")]
public static void FailIfCallerIsRecursive() {
    var trace = new StackTrace();
    // previous frame is the caller
    var caller = trace.GetFrame(1).GetMethod();
    // inspect the rest
    for (int i = 2; i < trace.FrameCount; i++) {
        // if found caller somewhere up the stack - throw
        if (trace.GetFrame(i).GetMethod() == caller)
            throw new Exception("Recursion detected");
    }
}

Then just call it a the beginning:

void MyPotentiallyRecursiveMethod() {
    FailIfCallerIsRecursive()
}

But note that it's quite expensive. However since you are going to use that only in dev (debug) configuration - why not. You can also modify it a bit to throw only when certain level of recursion is detected (so caller appears X time up the stack).


问:
Reserved Keyword in Where clause
Consider the following setup

```<code>create table #test([user] varchar(10))
insert into #test([user]) values ('test')
</code>```

when user column is enclosed with square brackets then the query returns result else it does not return result even though there is a matching record

```<code>SELECT *
FROM   #test WHERE [user] = 'test' -- returns record

SELECT *
FROM   #test WHERE user = 'test' --did not return record
</code>```

This begs the following two questions

Why is the first query works and the second query does not ?

Why the reserved keyword is allowed to use in where clause without escaping it ?

答:
As per  MS Docs

user without brackets will work as function which returns database user name

if you check with following query it will return records

```<code>SELECT *
FROM   #test WHERE user = 'dbo'
</code>```

When we Use [] Square brackets it sql server will treat as non reserve keyword like user defined column name,table name,function name.etc

Title: Reserved Keyword in Where clause

Body:
Consider the following setup

create table #test([user] varchar(10))
insert into #test([user]) values ('test')

when user column is enclosed with square brackets then the query returns result else it does not return result even though there is a matching record

SELECT *
FROM   #test WHERE [user] = 'test' -- returns record

SELECT *
FROM   #test WHERE user = 'test' --did not return record

This begs the following two questions

Why is the first query works and the second query does not ?

Why the reserved keyword is allowed to use in where clause without escaping it ?

Body:
As per  MS Docs

user without brackets will work as function which returns database user name

if you check with following query it will return records

SELECT *
FROM   #test WHERE user = 'dbo'

When we Use [] Square brackets it sql server will treat as non reserve keyword like user defined column name,table name,function name.etc


问:
Calling javascript form php
I am having a form inside a php script. I am doing the validation using javascript.

```<code><?php

$con = mysql_connect("servername","login","passsword");
if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }

mysql_select_db("dbadminatms", $con);

if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['comments']))
{
    $sql="INSERT INTO feedback_comments (posted_by, email, comments_text, comment_date)
        VALUES
    ('$_POST[name]','$_POST[email]','$_POST[comments]',NOW())";
    $emailID = $_POST['email'];
    $postedBy = $_POST['name'];
    $message = $_POST['comments'];

    if (!mysql_query($sql,$con))
    {
        die('Error: ' . mysql_error());
    }
    else
    {
        mail( "aaa@bbb.coml.com", "Subject: Comments", $message, "From: $emailID\r\n $postedBy" );
    }
}
    else
{

echo '

<form action="contactus.php" method="POST" id="feedback" onsubmit="javascript:return validate("feedback","name","email","comments");">

                <p id="errorMsg">All fields are required</p>

                <label for="name" class="label" id="nameLabel">Your name: </label><input id="name" type="text" size="30"  name="name" class="field"/>
                <br /><br />
                <label for="email" class="label" id="emailLabel">Your Email id: </label><input id="email" type="text" size="30"  name="email" class="field"/>
                <br /><br />

                    <label for="comments" class="label" id="commentsLabel">Comments:</label>
                  <div id="commentsSection">
                    <textarea name="comments" id="comments" class="ui-corner-all" cols="9" rows="5" tabindex="140"></textarea>
                  </div>

            <p><input type="submit" value="Submit" id="submit"/> <input type="reset" /></p>

        </form>';
}

    mysql_close($con);
?>
</code>```

Everrything's is working fine but I can't validate the form using javascript.

答:
The relevant excerpt is:

```<code>onsubmit="javascript:return validate("feedback","name","email","comments");"
</code>```

Two things:

Your use of double quotes within the attribute will end it prematurely (the browser will only see onsubmit="javascript:return validate(", which is invalid and will be tossed by the JavaScript interpreter). Use single quotes instead within the attribute value:

```<code>onsubmit="javascript:return validate('feedback','name','email','comments');"
</code>```

Do you actually have a JavaScript function called validate that's included in the page somewhere, either directly or via an external JavaScript file?

Separately, note that if you use onsubmit, you don't use javascript: at the beginning, just:

```<code>onsubmit="return validate('feedback','name','email','comments');"
</code>```

The javascript: pseudo-protocol is only used where the HTML would normally contain a link, as with the href attribute of anchors. onsubmit and similar don't accept links, just JavaScript code, so you don't use it. (It's largely harmless if you do, because coincidentally it looks like a label in JavaScript, and so the code parses okay and runs. But it's wrong.)

Off-topic, but important: NEVER rely on client-side validation; client-side validation is purely a user experience improvement exercise (helping people send you things you'll accept), never a replacement for server-side validation. Your PHP code as quoted is wide open to SQL injection (or even innocent issues — what happens if there's a ' in one of the fields, for instance?). Search for "SQL Injection PHP" to find lots of way so correctly process submitted data.

Title: Calling javascript form php

Body:
I am having a form inside a php script. I am doing the validation using javascript.

<?php

$con = mysql_connect("servername","login","passsword");
if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }

mysql_select_db("dbadminatms", $con);

if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['comments']))
{
    $sql="INSERT INTO feedback_comments (posted_by, email, comments_text, comment_date)
        VALUES
    ('$_POST[name]','$_POST[email]','$_POST[comments]',NOW())";
    $emailID = $_POST['email'];
    $postedBy = $_POST['name'];
    $message = $_POST['comments'];

    if (!mysql_query($sql,$con))
    {
        die('Error: ' . mysql_error());
    }
    else
    {
        mail( "aaa@bbb.coml.com", "Subject: Comments", $message, "From: $emailID\r\n $postedBy" );
    }
}
    else
{

echo '

<form action="contactus.php" method="POST" id="feedback" onsubmit="javascript:return validate("feedback","name","email","comments");">

All fields are required

                Your name: <input id="name" type="text" size="30"  name="name" class="field"/>

                Your Email id: <input id="email" type="text" size="30"  name="email" class="field"/>

                    Comments:

                    <textarea name="comments" id="comments" class="ui-corner-all" cols="9" rows="5" tabindex="140"></textarea>

<input type="submit" value="Submit" id="submit"/> <input type="reset" />

        </form>';
}

    mysql_close($con);
?>

Everrything's is working fine but I can't validate the form using javascript.

Body:
The relevant excerpt is:

onsubmit="javascript:return validate("feedback","name","email","comments");"

Two things:

Your use of double quotes within the attribute will end it prematurely (the browser will only see onsubmit="javascript:return validate(", which is invalid and will be tossed by the JavaScript interpreter). Use single quotes instead within the attribute value:

onsubmit="javascript:return validate('feedback','name','email','comments');"

Do you actually have a JavaScript function called validate that's included in the page somewhere, either directly or via an external JavaScript file?

Separately, note that if you use onsubmit, you don't use javascript: at the beginning, just:

onsubmit="return validate('feedback','name','email','comments');"

The javascript: pseudo-protocol is only used where the HTML would normally contain a link, as with the href attribute of anchors. onsubmit and similar don't accept links, just JavaScript code, so you don't use it. (It's largely harmless if you do, because coincidentally it looks like a label in JavaScript, and so the code parses okay and runs. But it's wrong.)

Off-topic, but important: NEVER rely on client-side validation; client-side validation is purely a user experience improvement exercise (helping people send you things you'll accept), never a replacement for server-side validation. Your PHP code as quoted is wide open to SQL injection (or even innocent issues — what happens if there's a ' in one of the fields, for instance?). Search for "SQL Injection PHP" to find lots of way so correctly process submitted data.


问:
Angular UI Grid validation without edit
I created a UI Grid with validations. I append an empty row for the user to fill out. It looks like the validations only happen on edit. It seems valid that the empty row is not flagging validations from the start because the user has not had any interactions with the cell yet - however if a user starts to edit a cell - but then decides not to - the validations still do not take place.

There are two scenarios I would like to support:

An empty 'new' row

No visual validation failures

User starts an edit - but then clicks away without making any changes

Validation failures are visible

An existing row that is invalid

Load data with that doesn't pass validations

Validation failures are immediately visible without any user interaction

Plunker: http://plnkr.co/edit/cb9Vb9b4iTC8z4haahbL?p=preview

```<code>  $scope.gridOptions.columnDefs = [
    { name: 'id',
      enableCellEdit: false,
      width: '10%'
    },
    { name: 'name',
      displayName: 'Name',
      width: '20%',
      validators: {
        required: true,
        startWith: 'M'
      },
      cellTemplate: 'ui-grid/cellTitleValidator'
    },
    { name: 'gender',
      displayName: 'Gender',
      width: '20%',
      validators: {
        required: true
      },
      cellTemplate: 'ui-grid/cellTitleValidator'
    }
  ];
</code>```

答:
This is similar to Afifa's answer, but higher performance when many of your columns aren't validated:

Add the following to your onRegisterApi:

```<code> $scope.gridApi.core.on.rowsRendered($scope, function () {
                $interval(function () {
                    var rowsRendred =
    $scope.gridApi.grid.renderContainers.body.renderedRows;
                    var validatedColumns = [];
                    rowsRendred[0].grid.options.columnDefs.forEach(function (colDef) {
                        if (typeof (colDef.validators) != 'undefined') {
                            validatedColumns.push(colDef);
                        }
                    });
                    rowsRendred.forEach(function (row) {
                        validatedColumns.forEach(function (colDef) {

 $scope.gridApi.grid.validate.runValidators(row.entity, colDef, row.entity[colDef.field], NaN, $scope.gridApi.grid);
                        });
                    });
                }, 500, 1);
            });
</code>```

Title: Angular UI Grid validation without edit

Body:
I created a UI Grid with validations. I append an empty row for the user to fill out. It looks like the validations only happen on edit. It seems valid that the empty row is not flagging validations from the start because the user has not had any interactions with the cell yet - however if a user starts to edit a cell - but then decides not to - the validations still do not take place.

There are two scenarios I would like to support:

An empty 'new' row

No visual validation failures

User starts an edit - but then clicks away without making any changes

Validation failures are visible

An existing row that is invalid

Load data with that doesn't pass validations

Validation failures are immediately visible without any user interaction

Plunker: http://plnkr.co/edit/cb9Vb9b4iTC8z4haahbL?p=preview

  $scope.gridOptions.columnDefs = [
    { name: 'id',
      enableCellEdit: false,
      width: '10%'
    },
    { name: 'name',
      displayName: 'Name',
      width: '20%',
      validators: {
        required: true,
        startWith: 'M'
      },
      cellTemplate: 'ui-grid/cellTitleValidator'
    },
    { name: 'gender',
      displayName: 'Gender',
      width: '20%',
      validators: {
        required: true
      },
      cellTemplate: 'ui-grid/cellTitleValidator'
    }
  ];

Body:
This is similar to Afifa's answer, but higher performance when many of your columns aren't validated:

Add the following to your onRegisterApi:

 $scope.gridApi.core.on.rowsRendered($scope, function () {
                $interval(function () {
                    var rowsRendred =
    $scope.gridApi.grid.renderContainers.body.renderedRows;
                    var validatedColumns = [];
                    rowsRendred[0].grid.options.columnDefs.forEach(function (colDef) {
                        if (typeof (colDef.validators) != 'undefined') {
                            validatedColumns.push(colDef);
                        }
                    });
                    rowsRendred.forEach(function (row) {
                        validatedColumns.forEach(function (colDef) {

 $scope.gridApi.grid.validate.runValidators(row.entity, colDef, row.entity[colDef.field], NaN, $scope.gridApi.grid);
                        });
                    });
                }, 500, 1);
            });


问:
Make h1 decide the div width
I'm trying to set the div width to be decided by h1. So the header can be as wide as it wants to be, while the paragraph will only be as wide as the header.

```<code><div>
  <h1></h1>
  <p></p>
</div>
</code>```

I've heard that this is impossible in plain html/css. Is this true? If so, what would a solution look like?

答:
Set div-s display value to inline-block:

```<code>div {
    display: inline-block;
}
</code>```

But since h1 has width of 100%(is block element) then it's going to be as wide as some other parent is. If you want heading not to be 100% width then make it aswell inline-block:

```<code>h1 {
    display: inline-block;
}
</code>```

Example: https://jsfiddle.net/cr29y1tc/32/

Title: Make h1 decide the div width

Body:
I'm trying to set the div width to be decided by h1. So the header can be as wide as it wants to be, while the paragraph will only be as wide as the header.

I've heard that this is impossible in plain html/css. Is this true? If so, what would a solution look like?

Body:
Set div-s display value to inline-block:

div {
    display: inline-block;
}

But since h1 has width of 100%(is block element) then it's going to be as wide as some other parent is. If you want heading not to be 100% width then make it aswell inline-block:

h1 {
    display: inline-block;
}

Example: https://jsfiddle.net/cr29y1tc/32/


问:
Python list name causing syntax error
In the second function, I keep getting a syntax error on the listExpenseNames list. I've tried changing the name of the variable to ExpenseNamesList, but I got the same error. For both these variable names I also tested with 0 as the index, but that also made no difference. Any help would be appreciated. Also, please don't try to correct any other errors there may be in my code, I want to learn through making mistakes myself. (This may seem contradictory because I just posted asking for a fix, but that's only because I'm stumped and it's preventing me from moving on.)</p>

```<code>def inputExpenseNames():
    listExpenseNames =[]
    loopExpenseNames = y
    while loopExpenseNames == y:
        listExpenseNames.append = input('Please enter the expense name.')
        loopExpenseNames=input('Would you like to enter another expense? If so, please enter \'y\'')
    print(listExpenseNames)

def inputExpenseAmounts():
    listExpenseAmounts =[]
    loopExpenseAmounts = 0
    while loopExpenseAmounts <= len(inputExpenseNames) :
        listExpenseAmounts.append = input('How much was spent on' listExpenseNames[int(loopExpenseAmounts)]'?')
        loopExpenseAmounts += 1
    print(listExpenseAmounts)
</code>```

答:
I assume you want to print the string stored in listExpenseNames[int(loopExpenseAmounts)] for the input display text. You need to concatenate the strings with a + to one string and not only list them after each other:</p>

```<code>listExpenseAmounts.append = input('How much was spent on' + listExpenseNames[int(loopExpenseAmounts)] + '?')
</code>```

Title: Python list name causing syntax error

Body:
In the second function, I keep getting a syntax error on the listExpenseNames list. I've tried changing the name of the variable to ExpenseNamesList, but I got the same error. For both these variable names I also tested with 0 as the index, but that also made no difference. Any help would be appreciated. Also, please don't try to correct any other errors there may be in my code, I want to learn through making mistakes myself. (This may seem contradictory because I just posted asking for a fix, but that's only because I'm stumped and it's preventing me from moving on.)

def inputExpenseNames():
    listExpenseNames =[]
    loopExpenseNames = y
    while loopExpenseNames == y:
        listExpenseNames.append = input('Please enter the expense name.')
        loopExpenseNames=input('Would you like to enter another expense? If so, please enter \'y\'')
    print(listExpenseNames)

def inputExpenseAmounts():
    listExpenseAmounts =[]
    loopExpenseAmounts = 0
    while loopExpenseAmounts <= len(inputExpenseNames) :
        listExpenseAmounts.append = input('How much was spent on' listExpenseNames[int(loopExpenseAmounts)]'?')
        loopExpenseAmounts += 1
    print(listExpenseAmounts)

Body:
I assume you want to print the string stored in listExpenseNames[int(loopExpenseAmounts)] for the input display text. You need to concatenate the strings with a + to one string and not only list them after each other:

listExpenseAmounts.append = input('How much was spent on' + listExpenseNames[int(loopExpenseAmounts)] + '?')


问:
build gradle for hibernate usage in intellj
hey i d like to know how i manage to build build gradle in intellj.
i know how to do it in eclipse an it works fine.
i want to connect a sqlite db to intellj like i do it in eclipse so i can insert soemthing over hibernate.
this is how i do it in eclipse:
i make a new gradle project
then i write my buildgradle file

then i go rightclick on build.gradle and select "gradle" and then "refresh gradle"

now this works without eclipse telling me there was an error

i drag and drop my db here (name of db: spiel.db)

and then i write my hibernate.cfg.xml:

and now when i run my main everything is fine...

now i want to do the exact thing in intellj:

so i do new gradle project and then i write the same buildgradle file
then i press build

and now intellj is complaining about my code

did i forget something?

答: It looks like some import problem, do you have hibernate support on? https://www.jetbrains.com/help/idea/overview-of-hibernate-support.html</p>


问:
Change boolean var onClick based on parameter
I am creating a page that sets a variable to true or false based on a button click. This is doable if I create a function per variable/button, but since there will be quite a few variables in the end, I would like to do this in a single function, if possible:

```<code><div>
  <button type="button" id="colorbutton" class="button red" onClick="manualSelect('Color')">Colors</button>
  <button type="button" id="animalbutton" class="button red" onClick="manualSelect('Animal')">Animals</button>
</div>
</code>```

$manualColor = false;
$manualAnimal = false;

function manualSelect(item) {
  if ($('manual' + item) == false) {
    $('manual' + item) = true;
  } else {
    $('manual' + item) = false;
  }
}
```

I know this is stupid, it's just to set the example.

Here's the full script:
https://jsfiddle.net/8ers54s9/5/

答:
This is possible, of course:

var manual = {
  "Color": false,
  "Animal": false,
};

$("button").on("click", function() {
  var item = $(this).data("select");
  manual[item] = !manual[item];
  console.info(manual);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <button type="button" id="colorbutton" class="button red"  data-select="Color">Colors</button>
    <button type="button" id="animalbutton" class="button red" data-select="Animal">Animals</button>
</div></code>```

Body:
I am creating a page that sets a variable to true or false based on a button click. This is doable if I create a function per variable/button, but since there will be quite a few variables in the end, I would like to do this in a single function, if possible:

  <button type="button" id="colorbutton" class="button red" onClick="manualSelect('Color')">Colors</button>
  <button type="button" id="animalbutton" class="button red" onClick="manualSelect('Animal')">Animals</button>

$manualColor = false;
$manualAnimal = false;

function manualSelect(item) {
  if ($('manual' + item) == false) {
    $('manual' + item) = true;
  } else {
    $('manual' + item) = false;
  }
}

I know this is stupid, it's just to set the example.

Here's the full script:
https://jsfiddle.net/8ers54s9/5/

Body:
This is possible, of course:

var manual = {
  "Color": false,
  "Animal": false,
};

$("button").on("click", function() {
  var item = $(this).data("select");
  manual[item] = !manual[item];
  console.info(manual);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <button type="button" id="colorbutton" class="button red"  data-select="Color">Colors</button>
    <button type="button" id="animalbutton" class="button red" data-select="Animal">Animals</button>
</div>


答:
You are trying to concatenate strings on the following line but you are not. try the following code instead.</p>

```<code>listExpenseAmounts.append(input('How much was spent on'+ listExpenseNames[int(loopExpenseAmounts)]'?'))
</code>```

Title: Python list name causing syntax error

Body:
You are trying to concatenate strings on the following line but you are not. try the following code instead.

listExpenseAmounts.append(input('How much was spent on'+ listExpenseNames[int(loopExpenseAmounts)]'?'))


问:
Nested for loop not working in makefile
I am trying to use a nested for loop for searching and copying some files inside the recipe of one of the targets inside a makefile:

```<code>DIR = $(DIR_A) $(DIR_B)

install:
      for dirs in $(DIR); do \
        for file in $(shell find $(dirs) -type f -and -not -path "*/.svn*" | sed -e "s|$(dirs)||"); do \
        folder=$${file%/*}; \
          $(INSTALL) -d $(DEST_DIR)$$folder/log; \
          $(INSTALL) $(dirs)/$$file $(DEST_DIR)$$folder/log; \
        done \
      done
</code>```

However $(dirs) variable always evaluates to empty inside the second for loop and the current working directory gets passed to "find" instead of first directory path from $(DIR).

Can someone please suggest if I am missing something ?

Thanks.

答:
The $(dirs) in the find command is being expanded by make to the make variable dirs which is unset and thus the empty string.  To reference the shell variable, you need to escape the $:

```<code> for file in $$(find $${dirs} -type f -and \
      -not -path "*/.svn*" | sed -e "s|$${dirs}||"); do
</code>```

But don't do this.  It is much cleaner to explicitly list the files you intend to install.  If there are many, it is fine to write a script to generate the Makefile.  What you are doing is a fragile mess.

Title: Nested for loop not working in makefile

Body:
I am trying to use a nested for loop for searching and copying some files inside the recipe of one of the targets inside a makefile:

DIR = $(DIR_A) $(DIR_B)

install:
      for dirs in $(DIR); do \
        for file in $(shell find $(dirs) -type f -and -not -path "*/.svn*" | sed -e "s|$(dirs)||"); do \
        folder=$${file%/*}; \
          $(INSTALL) -d $(DEST_DIR)$$folder/log; \
          $(INSTALL) $(dirs)/$$file $(DEST_DIR)$$folder/log; \
        done \
      done

However $(dirs) variable always evaluates to empty inside the second for loop and the current working directory gets passed to "find" instead of first directory path from $(DIR).

Can someone please suggest if I am missing something ?

Thanks.

Body:
The $(dirs) in the find command is being expanded by make to the make variable dirs which is unset and thus the empty string.  To reference the shell variable, you need to escape the $:

 for file in $$(find $${dirs} -type f -and \
      -not -path "*/.svn*" | sed -e "s|$${dirs}||"); do

But don't do this.  It is much cleaner to explicitly list the files you intend to install.  If there are many, it is fine to write a script to generate the Makefile.  What you are doing is a fragile mess.


问:
HTML / CSS How to add image icon to input type="button"?
I'm using the below CSS, but it puts an image in the center of the button. Any way to left or right align an icon using <input type="button">, so that the text and the image fit and align nicely?

```<code>background: url('/common/assets/images/icons/16x16/add.png');
background-position:center;
background-repeat:no-repeat;
</code>```

答:
Simply add icon in button element here is the example</p>

```<code>   <button class="social-signup facebook">
     <i class="fa fa-facebook-official"></i>
      Sign up with Facebook</button>
</code>```

Body:
I'm using the below CSS, but it puts an image in the center of the button. Any way to left or right align an icon using <input type="button">, so that the text and the image fit and align nicely?

background: url('/common/assets/images/icons/16x16/add.png');
background-position:center;
background-repeat:no-repeat;

Body:
Simply add icon in button element here is the example

   <button class="social-signup facebook">
     <i class="fa fa-facebook-official"></i>
      Sign up with Facebook</button>


问:
Swift 3 - How to capture image and its subview?
I am working on a project that contains custom camera view.And i am unable to capture the subview over the main view.My main view consist of AVCaptureSession and i want to take photo of superview and subview both in single image.

What i am trying in code:

```<code>class ViewController: UIViewController {

@IBOutlet weak var cameraButton: UIButton!

var captureSession = AVCaptureSession()

var backCamera: AVCaptureDevice?
var frontCamera: AVCaptureDevice?
var currentDevice: AVCaptureDevice?

var photoOutput: AVCapturePhotoOutput?

var cameraPreviewLayer:AVCaptureVideoPreviewLayer?

var image: UIImage?

var toggleCameraGestureRecognizer = UISwipeGestureRecognizer()

var zoomInGestureRecognizer = UISwipeGestureRecognizer()
var zoomOutGestureRecognizer = UISwipeGestureRecognizer()

override func viewDidLoad() {
    super.viewDidLoad()
    setupCaptureSession()
    setupDevice()
    setupInputOutput()
    setupPreviewLayer()
    captureSession.startRunning()

    toggleCameraGestureRecognizer.direction = .up
    toggleCameraGestureRecognizer.addTarget(self, action: #selector(self.switchCamera))
    view.addGestureRecognizer(toggleCameraGestureRecognizer)

    // Zoom In recognizer
    zoomInGestureRecognizer.direction = .right
    zoomInGestureRecognizer.addTarget(self, action: #selector(zoomIn))
    view.addGestureRecognizer(zoomInGestureRecognizer)

    // Zoom Out recognizer
    zoomOutGestureRecognizer.direction = .left
    zoomOutGestureRecognizer.addTarget(self, action: #selector(zoomOut))
    view.addGestureRecognizer(zoomOutGestureRecognizer)
    styleCaptureButton()
}
  cameraButton.layer.borderColor = UIColor.white.cgColor
    cameraButton.layer.borderWidth = 5
    cameraButton.clipsToBounds = true
    cameraButton.layer.cornerRadius = min(cameraButton.frame.width, cameraButton.frame.height) / 2
}

func setupCaptureSession() {
    captureSession.sessionPreset = AVCaptureSession.Preset.photo
}

func setupDevice() {
    let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: AVCaptureDevice.Position.unspecified)
    let devices = deviceDiscoverySession.devices

    for device in devices {
        if device.position == AVCaptureDevice.Position.back {
            backCamera = device
        } else if device.position == AVCaptureDevice.Position.front {
            frontCamera = device
        }
    }
    currentDevice = backCamera
}

func setupInputOutput() {
    do {

        let captureDeviceInput = try AVCaptureDeviceInput(device: currentDevice!)
        captureSession.addInput(captureDeviceInput)
        photoOutput = AVCapturePhotoOutput()
        photoOutput!.setPreparedPhotoSettingsArray([AVCapturePhotoSettings(format: [AVVideoCodecKey : AVVideoCodecType.jpeg])], completionHandler: nil)
        captureSession.addOutput(photoOutput!)

    } catch {
        print(error)
    }
}

func setupPreviewLayer() {
    self.cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    self.cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    self.cameraPreviewLayer?.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
    self.cameraPreviewLayer?.frame = view.frame

    self.view.layer.insertSublayer(self.cameraPreviewLayer!, at: 0)
}
@IBAction func cameraButton_TouchUpInside(_ sender: Any) {
    let settings = AVCapturePhotoSettings()
    self.photoOutput?.capturePhoto(with: settings, delegate: self)
}
}
extension ViewController: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
    if let imageData = photo.fileDataRepresentation() {
        self.image = UIImage(data: imageData)
        performSegue(withIdentifier: "Preview_Segue", sender: nil)
    }
}
}
</code>```

Please help me

答:
If I understood you are trying to get the content (as an image) of what the camera is grabbing and some overlay views.

As far as I remember is not possible to grab what is inside the AVPreviewLayer, maybe they changed something in the latest version. When I tried (iOS6) it wasn't possible, the area with the AVPreviewLayer was always empty.

What you can do is take the current camera buffer and draw inside it. By setting a class as a session delegate you can receive this callback optional

```<code>func captureOutput(_ output: AVCaptureOutput,
                  didOutput sampleBuffer: CMSampleBuffer,
                       from connection: AVCaptureConnection)
</code>```

Here you will receive the image from the camera, this buffer can be converted into images using Accelerate framework or CoreImage.

Is not easy, but also not impossible.

Body:
I am working on a project that contains custom camera view.And i am unable to capture the subview over the main view.My main view consist of AVCaptureSession and i want to take photo of superview and subview both in single image.

What i am trying in code:

class ViewController: UIViewController {

@IBOutlet weak var cameraButton: UIButton!

var captureSession = AVCaptureSession()

var backCamera: AVCaptureDevice?
var frontCamera: AVCaptureDevice?
var currentDevice: AVCaptureDevice?

var photoOutput: AVCapturePhotoOutput?

var cameraPreviewLayer:AVCaptureVideoPreviewLayer?

var image: UIImage?

var toggleCameraGestureRecognizer = UISwipeGestureRecognizer()

var zoomInGestureRecognizer = UISwipeGestureRecognizer()
var zoomOutGestureRecognizer = UISwipeGestureRecognizer()

override func viewDidLoad() {
    super.viewDidLoad()
    setupCaptureSession()
    setupDevice()
    setupInputOutput()
    setupPreviewLayer()
    captureSession.startRunning()

    toggleCameraGestureRecognizer.direction = .up
    toggleCameraGestureRecognizer.addTarget(self, action: #selector(self.switchCamera))
    view.addGestureRecognizer(toggleCameraGestureRecognizer)

    // Zoom In recognizer
    zoomInGestureRecognizer.direction = .right
    zoomInGestureRecognizer.addTarget(self, action: #selector(zoomIn))
    view.addGestureRecognizer(zoomInGestureRecognizer)

    // Zoom Out recognizer
    zoomOutGestureRecognizer.direction = .left
    zoomOutGestureRecognizer.addTarget(self, action: #selector(zoomOut))
    view.addGestureRecognizer(zoomOutGestureRecognizer)
    styleCaptureButton()
}
  cameraButton.layer.borderColor = UIColor.white.cgColor
    cameraButton.layer.borderWidth = 5
    cameraButton.clipsToBounds = true
    cameraButton.layer.cornerRadius = min(cameraButton.frame.width, cameraButton.frame.height) / 2
}

func setupCaptureSession() {
    captureSession.sessionPreset = AVCaptureSession.Preset.photo
}

func setupDevice() {
    let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: AVCaptureDevice.Position.unspecified)
    let devices = deviceDiscoverySession.devices

    for device in devices {
        if device.position == AVCaptureDevice.Position.back {
            backCamera = device
        } else if device.position == AVCaptureDevice.Position.front {
            frontCamera = device
        }
    }
    currentDevice = backCamera
}

func setupInputOutput() {
    do {

        let captureDeviceInput = try AVCaptureDeviceInput(device: currentDevice!)
        captureSession.addInput(captureDeviceInput)
        photoOutput = AVCapturePhotoOutput()
        photoOutput!.setPreparedPhotoSettingsArray([AVCapturePhotoSettings(format: [AVVideoCodecKey : AVVideoCodecType.jpeg])], completionHandler: nil)
        captureSession.addOutput(photoOutput!)

    } catch {
        print(error)
    }
}

func setupPreviewLayer() {
    self.cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    self.cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    self.cameraPreviewLayer?.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
    self.cameraPreviewLayer?.frame = view.frame

    self.view.layer.insertSublayer(self.cameraPreviewLayer!, at: 0)
}
@IBAction func cameraButton_TouchUpInside(_ sender: Any) {
    let settings = AVCapturePhotoSettings()
    self.photoOutput?.capturePhoto(with: settings, delegate: self)
}
}
extension ViewController: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
    if let imageData = photo.fileDataRepresentation() {
        self.image = UIImage(data: imageData)
        performSegue(withIdentifier: "Preview_Segue", sender: nil)
    }
}
}

Please help me

Body:
If I understood you are trying to get the content (as an image) of what the camera is grabbing and some overlay views.

As far as I remember is not possible to grab what is inside the AVPreviewLayer, maybe they changed something in the latest version. When I tried (iOS6) it wasn't possible, the area with the AVPreviewLayer was always empty.

What you can do is take the current camera buffer and draw inside it. By setting a class as a session delegate you can receive this callback optional

func captureOutput(_ output: AVCaptureOutput,
                  didOutput sampleBuffer: CMSampleBuffer,
                       from connection: AVCaptureConnection)

Here you will receive the image from the camera, this buffer can be converted into images using Accelerate framework or CoreImage.

Is not easy, but also not impossible.


问:
Replace spaces with new line in makefile
Does anyone know how to replace all spaces in a string in to a new line in a Makefile(GNU make)</p>

答:
```<code>text := hello a b c

null :=
space := ${null} ${null}
${space} := ${space}# ${ } is a space. Neat huh?

define \n

endef

$(error [$(subst ${ },${\n},${text})])
</code>```


问:
How to use sed to replace the first space with an empty string
I am having trouble loading a space delimited text file into a table. The data in this text file is generated by teragen, and hence, is just dummy data, where there are only 2 columns, and the first column has values of random special character strings.

Example:

~~~{ZRGHS|

~~~{qahVN)

I run into a problem and get rejected rows because some of these values have a space in them as a random ASCII character, which causes it to think that there are 3 columns, when my table has 2, so they get rejected.

So, what I want to do is remove only the first space from these rejected rows, which will need to be repeated multiple times over each row, and then try to reload them. Would sed be the best way to go about this, or would something else like tr be more appropriate?

Thanks!

答:
To strip/remove 1st character from string:

function stringStripStart {
    echo ${1:1:${#1}}
}

Similar to remove traling character:

function stringStripEnd {
    FINAL_LEN=${#1}-1
    echo ${1:0:$FINAL_LEN}
}

Note: for empty string, some additional condition needs to be added.


问:
Spacy model types and available functionality mapping
Spacy models are associated with different 'types' including: vocabulary, syntax, entities and vectors. The way that entities and vectors map to features available in a document is obvious (entity recognition and word vectors) but how do vocabulary and syntax relate to features available in a document after parsing text? For example, the multi-lingual model 'xx_ent_wiki_sm' does not offer 'vocabulary' so does that mean that the is_oov of tokens will be unavailable using that model? I'm asking this because I want to provide a web service on top of Spacy that operates on different language models. </p>

答:
"syntax" refers to the dependency parse all all related linguistic features and properties. For example, token.dep_, token.head, doc.noun_chunks or doc.sents – essentially, everything that requires the dependency parse (see this page for a quick overview).

"vocabulary" means that the Vocab is pre-populated with a number of the most frequent words. If the model doesn't come with a vocab, all tokens will be out-of-vocabulary and return True for is_oov. Larger models typically also ship with larger vocabulary. The sm models should also ship with a basic vocabulary of the most frequent words – but there might be an issue with the way some of the data is currently set, which should be fixed in the next update to the models.


问:
Why is my Bootstrap column not centering its content?`
I have the following basic layout, in which to show a flash-card - the detail-card:

```<code><div class="col-md-4"></div>
<div id="cardContainer" class="col-md-4 text-center detail-card-container">
    @Html.Partial("_DetailCard", cardModel)
</div>
<div class="col-md-4"></div>
</code>```

I know I could just use col-offset but I have plans for the other two columns.

My vision here was to divide the page into three columns, give the middle one, detail-card-container, class text-center so that the content of that div should be horizontally centered inside it.

Yet when I start up the app, I get a display as follows:

The blue is the available space in the detail-card-container for the 'detail-card, outlined in red. The detail card is fixed width 200, and the available space is about 400+ .This is displaying at the left of its available space, not in the centre as intended. The empty spaces to the left and right of the green in the image are the emptycol-md-4` divs.

What am I doing wrong?

答:
Use</p>

```<code><div class="col-md-4" align="center">
</code>```

Body:
I have the following basic layout, in which to show a flash-card - the detail-card:

    @Html.Partial("_DetailCard", cardModel)

I know I could just use col-offset but I have plans for the other two columns.

My vision here was to divide the page into three columns, give the middle one, detail-card-container, class text-center so that the content of that div should be horizontally centered inside it.

Yet when I start up the app, I get a display as follows:

The blue is the available space in the detail-card-container for the 'detail-card, outlined in red. The detail card is fixed width 200, and the available space is about 400+ .This is displaying at the left of its available space, not in the centre as intended. The empty spaces to the left and right of the green in the image are the emptycol-md-4` divs.

What am I doing wrong?

Body:
Use

<div class="col-md-4" align="center">


答:
This code has a couple of problems:

listExpenseNames will not be defined inside inputExpenseAmounts. See Here for an explanation

l.append = ... will change the value of the append attribute, it won't actually append anything.  To append something do l.append(...)

As others have pointed out, use + to concatenate strings: 'spent on' +  listExpenseNames[int(loopExpenseAmounts)] + '?'

`

Title: Python list name causing syntax error


问:
CSV Playback with Node Red
Disclaimer - I am not a software guy so please bear with me while I learn.

I am looking to use node red as a parser/translator by taking data from a CSV file and sending out the rows of data at 1Hz.  Let's say 5-10 rows of data being read and published per second.

Eventually, I will publish that data to some Modbus registers but I'm not there yet.

I have scoured the web and tried several examples, however, as soon as I trigger the flow, Node.Red stops responding and I have to delete the source CSV,(so it can't run any more) and restart node.red in order to get it back up in running.

I have many of the Big Nodes from this guy installed and have tried a variety of different methods but I just can't seem to get it.

If I can get a single column of data from a CSV file being sent out one row at a time, I think that would keep me busy for a bit.

答:
There is a file node that will read a file a line at a time, you can then feed this through the csv node to parse out the fields in the CSV into an object so you can work with it.

The delay node has a rate limiting function that can be used to limit the flow to processing 1 message per second to achieve the rate you want.

All the nodes I've mentioned should be in the core set that ships with Node-RED

Title: CSV Playback with Node Red


问:
Bring activity front if it is running or create new one with backpress

Let me explain detailed; I have notification and this notification opens B activity with two cases.

Cases :

If app is closed. (not running on background)

If app is opened. (on background or front)

Case-1

I click to the notification and it opens the B activity with case-1. When i press back i want to go to the A activity and kill B activity. I dont need B activity anymore. Everything easy from here without using flags. When I'm on B activity and press back two times from here, it goes A activity and then closes the app. My trouble here is, if i open the app from navigation buttons of phone (can't remember the name of this button) app is opening from B activity. That's not what i expected. I want to open A activity. Don't want to see B activity anymore.

Case-2

I click to the notification and it opens the B activity with case-2.When i press back i want to bring A activity to the front, without creating anything new. If i press back on B activity, two times and close the app and then again re-open app from navigation button of phone, want to open app from A activity.

So how can i make this correctly, i tried to use flags (i already read docs) but couldn't get work.
What flags should i use when i open the B activity and onBackPress method of B activity to go A activity as i wanted

答:
You May try this isTaskRoot() Which will return B is root

if it is true then launch A

other wise you may finish B

B Activity

```<code>@Override
    public void onBackPressed() {
        if (isTaskRoot()) {
            //call A which is not exist
            Intent i =new Intent(B.this,A.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
        }else {
            //Finish B if A Already Exixt
            finish();
        }
    }
</code>```

You can call B Activity on Notification Click

if A is present then u can finish B else you can launch A

If set FLAG_ACTIVITY_CLEAR_TOP, the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

Body:
You May try this isTaskRoot() Which will return B is root

if it is true then launch A

other wise you may finish B

B Activity

@Override
    public void onBackPressed() {
        if (isTaskRoot()) {
            //call A which is not exist
            Intent i =new Intent(B.this,A.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
        }else {
            //Finish B if A Already Exixt
            finish();
        }
    }

You can call B Activity on Notification Click

if A is present then u can finish B else you can launch A

If set FLAG_ACTIVITY_CLEAR_TOP, the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.


问:
Octlet, quad word or what?
I am translating some documentation on libraw1394 to Russian. The documentation on libraw1394 says:

The basic data structures defined in
  the standard and used in this document
  are the quadlet (32 bit quantity) and
  the octlet (64 bit quantity)...

There is no such unit like "octlet" in Russian. I used to use "quad word" (russian "chetvertnoye slovo") for 64 bit quantity. Would it be correct to substitute "octlet" by "quad word"?

What are the alternative terms for "octlet"?

答:
If you don't want to use the english terms directly, perhaps quartet (квартет) and octet (Октет) will do...

However, to avoid confusion with 8-bit octets, it might be better to make up less ambiguous words, eg кварто байт and октябристов(???) байт; perhaps a native speaker could tell us if these terms make any sense, because I'm not really convinced that Google is right with its suggestion for the second term...

Title: Octlet, quad word or what?


答:
In AngularJS </p>

```<code><button ng-click="manual()">Click me!</button>
</code>```

<pre class="lang-js prettyprint-override"><code>$scope.manualColor = true;

$scope.manual = function () {
  $scope.manualColor = false;
}
</code>```

Title: Change boolean var onClick based on parameter

Body:
In AngularJS

<button ng-click="manual()">Click me!</button>

$scope.manualColor = true;

$scope.manual = function () {
  $scope.manualColor = false;
}


问:
query with columns of same an different tables
I have 2 tables with structure as shown below:

```<code>THINGS
COLUMNA            COLUMNB
Fruits             Apple
Fruits             Pear
Fruits             Grapes
Dairy products     Yoghurt
.......

QUANTITY
COLUMNC         COLUMND
Fruits           1
Apple            2
Pear             3
Yoghurt          1
Dairy products   1
</code>```

I need a query to get something like:

COLUMA AND COLUMN C of these way:

```<code>RESULTA         RESULTB
Fruits          1,2,3
Dairy Products  1
</code>```

The query SQL that I try is:

```<code>select COLUMNA, listagg(COLUMND,',') within group (order by COLUMND) from THINGS, QUANTITY  where COLUMNA=COLUMNC group by COLUMNC;
</code>```

Is this possible? I have tried to get this but to no avail. I am working on Oracle 12.

答:
It's not quite clear how do you join data, but for given examples this works:

```<code>select columna result, listagg(columnd, ', ') within group (order by columnd) resultb
  from (select distinct columna, columnd
          from things t
          join quantity q on q.columnc in (t.columna, t.columnb))
  group by columna
</code>```

Test:

```<code>with things(columna, columnb) as (
    select 'Fruits',         'Apple'   from dual union all
    select 'Fruits',         'Pear'    from dual union all
    select 'Fruits',         'Grapes'  from dual union all
    select 'Dairy products', 'Yoghurt' from dual ),
quantity(columnc, columnd) as (
    select 'Fruits',          1 from dual union all
    select 'Apple',           2 from dual union all
    select 'Pear',            3 from dual union all
    select 'Yoghurt',         1 from dual union all
    select 'Dairy products',  1 from dual )
select columna result, listagg(columnd, ', ') within group (order by columnd) resultb
  from (select distinct columna, columnd
          from things t join quantity q on q.columnc in (t.columna, t.columnb))
  group by columna
</code>```

Result:

```<code>RESULT         RESULTB
-------------- ----------
Dairy products 1
Fruits         1, 2, 3
</code>```

Body:
I have 2 tables with structure as shown below:

THINGS
COLUMNA            COLUMNB
Fruits             Apple
Fruits             Pear
Fruits             Grapes
Dairy products     Yoghurt
.......

QUANTITY
COLUMNC         COLUMND
Fruits           1
Apple            2
Pear             3
Yoghurt          1
Dairy products   1

I need a query to get something like:

COLUMA AND COLUMN C of these way:

RESULTA         RESULTB
Fruits          1,2,3
Dairy Products  1

The query SQL that I try is:

select COLUMNA, listagg(COLUMND,',') within group (order by COLUMND) from THINGS, QUANTITY  where COLUMNA=COLUMNC group by COLUMNC;

Is this possible? I have tried to get this but to no avail. I am working on Oracle 12.

Body:
It's not quite clear how do you join data, but for given examples this works:

select columna result, listagg(columnd, ', ') within group (order by columnd) resultb
  from (select distinct columna, columnd
          from things t
          join quantity q on q.columnc in (t.columna, t.columnb))
  group by columna

Test:

with things(columna, columnb) as (
    select 'Fruits',         'Apple'   from dual union all
    select 'Fruits',         'Pear'    from dual union all
    select 'Fruits',         'Grapes'  from dual union all
    select 'Dairy products', 'Yoghurt' from dual ),
quantity(columnc, columnd) as (
    select 'Fruits',          1 from dual union all
    select 'Apple',           2 from dual union all
    select 'Pear',            3 from dual union all
    select 'Yoghurt',         1 from dual union all
    select 'Dairy products',  1 from dual )
select columna result, listagg(columnd, ', ') within group (order by columnd) resultb
  from (select distinct columna, columnd
          from things t join quantity q on q.columnc in (t.columna, t.columnb))
  group by columna

Result:

RESULT         RESULTB
-------------- ----------
Dairy products 1
Fruits         1, 2, 3


问:
Silverlight TextBlock: Convert Text to InlineCollection
Consider the following markup declaration:

```<code><TextBlock>
 <Run>abcdefghijklmnopqrstuvwxyz</Run>
 <LineBreak/>
 <Run>0123456789</Run>
</TextBlock>
</code>```

I want to bind any data to a TextBlock and convert this data to an InlineCollection. It would be very elegant to do this with Data Binding. The other way is to observe my Data Source and use the Inlines-Property from the TextBlock class in Code Behind.

I tried the following but it didn't work:

```<code><TextBlock>
 <Binding Path="MyDataSource" Converter="{StaticResource MyTextConverter}"/>
</TextBlock>
</code>```

What I want to do is achieve auto font-scaling by encapsulating my TextBlock in a ViewBox, but also generating LineBreaks after an arbitrary letter count.

Thanks in advance for any help.
Best regards.

答:
I guess you just have to assign yout converter to the TextProperty of your TextBlock.
Then your converter add \r\n to get a linebreak when you need it.

Body:
Consider the following markup declaration:

<TextBlock>
 <Run>abcdefghijklmnopqrstuvwxyz</Run>
 <LineBreak/>
 <Run>0123456789</Run>
</TextBlock>

I want to bind any data to a TextBlock and convert this data to an InlineCollection. It would be very elegant to do this with Data Binding. The other way is to observe my Data Source and use the Inlines-Property from the TextBlock class in Code Behind.

I tried the following but it didn't work:

<TextBlock>
 <Binding Path="MyDataSource" Converter="{StaticResource MyTextConverter}"/>
</TextBlock>

What I want to do is achieve auto font-scaling by encapsulating my TextBlock in a ViewBox, but also generating LineBreaks after an arbitrary letter count.

Thanks in advance for any help.
Best regards.


问:
fread() blank.lines.skips leaves NA line
I have blank lines between monthly blocks of data in a csv file. I looked at using the blank.line.skips = TRUE parameter of fread or read.csv to drop those empty rows.

But what I am getting is a line with a NA at the end. Why is the row not completely dropped?

I did see some old data answers on SO about fread crashing when it has a blank row but that seems to have been fixed.

TEST CASE

```<code>temp <- data.table(a = c("a","","c","d"),
                   b = c(10,"",30,40))

fwrite (temp, "test.csv")

mydata <- fread("test.csv",
                blank.lines.skip = TRUE,
                stringsAsFactors = FALSE)
</code>```

RESULTS

I get the second row which is blank included with an NA added:

```<code>> mydata
a  b
1: a 10
2:   NA
3: c 30
4: d 40
</code>```

I wanted (and expected):

```<code>> mydata
a  b
1: a 10
2: c 30
3: d 40
</code>```

(I realise I can get this with a mydata[complete.cases(mydata), ] but I expected the blank.lines.skips to do this. From fread help "If TRUE blank lines in the input are ignored.")

Is this fread leaving the line a bug or feature?

答:
When you perform fwrite (temp, "test.csv") the second line (without considering headers) is not blank... It has a separator:

```<code>a,b
a,10
,
c,30
d,40
</code>```

The argument blank.lines.skips is for truly blanklines:

Ex: with test.csv as following

```<code>a,b
a,10

c,30
d,40
</code>```

To control :

```<code>> dim(fread("test.csv", blank.lines.skip = TRUE))
[1] 3 2
</code>```

Argument blank.lines.skip = TRUE avoid stopping at the first blank line. Without setting this argument you would have:

```<code>> dim(fread("test.csv"))
[1] 1 2
Warning message:
In fread("test.csv") :
  Stopped reading at empty line 3 but text exists afterwards (discarded): c,30
</code>```

Edit:

To solve your problem of blank lines, I would advise to:

Strip them from your file before reading your data if you have a lot of those lines.

Drop them after reading if you have just a few of them.

Body:
I have blank lines between monthly blocks of data in a csv file. I looked at using the blank.line.skips = TRUE parameter of fread or read.csv to drop those empty rows.

But what I am getting is a line with a NA at the end. Why is the row not completely dropped?

I did see some old data answers on SO about fread crashing when it has a blank row but that seems to have been fixed.

TEST CASE

temp <- data.table(a = c("a","","c","d"),
                   b = c(10,"",30,40))

fwrite (temp, "test.csv")

mydata <- fread("test.csv",
                blank.lines.skip = TRUE,
                stringsAsFactors = FALSE)

RESULTS

I get the second row which is blank included with an NA added:

> mydata
a  b
1: a 10
2:   NA
3: c 30
4: d 40

I wanted (and expected):

> mydata
a  b
1: a 10
2: c 30
3: d 40

(I realise I can get this with a mydata[complete.cases(mydata), ] but I expected the blank.lines.skips to do this. From fread help "If TRUE blank lines in the input are ignored.")

Is this fread leaving the line a bug or feature?

Body:
When you perform fwrite (temp, "test.csv") the second line (without considering headers) is not blank... It has a separator:

a,b
a,10
,
c,30
d,40

The argument blank.lines.skips is for truly blanklines:

Ex: with test.csv as following

a,b
a,10

c,30
d,40

To control :

> dim(fread("test.csv", blank.lines.skip = TRUE))
[1] 3 2

Argument blank.lines.skip = TRUE avoid stopping at the first blank line. Without setting this argument you would have:

> dim(fread("test.csv"))
[1] 1 2
Warning message:
In fread("test.csv") :
  Stopped reading at empty line 3 but text exists afterwards (discarded): c,30

Edit:

To solve your problem of blank lines, I would advise to:

Strip them from your file before reading your data if you have a lot of those lines.

Drop them after reading if you have just a few of them.