问:
Angular4 - ZoneAwareError
I'm suddenly seeing an error when I try to run an Angular4 that looks like this...

```<code>ERROR ZoneAwareError {__zone_symbol__error: Error: Uncaught (in promise): Error
Error
at Error.ZoneAwareError (http://localhost:4200/vendor.……}message: (...)name: (...)originalStack: (...)promise: ZoneAwarePromiserejection: Errorstack: (...)task: ZoneTasktoSource: function ()toString: function ()zone: ZonezoneAwareStack: (...)__zone_symbol__error: Error: Uncaught (in promise):
Error
Error
at Error.ZoneAwareError (http://localhost:4200/vendor.bundle.js:97291:33)
at ZoneAwareError (http://localhost:4200/vendor.bundle.js:97288:35)
at injectionError (http://localhost:4200/vendor.bundle.js:2061:86)
at noProviderError (http://localhost:4200/vendor.bundle.js:2099:12)
at ReflectiveInjector_._throwOrNull (http://localhost:4200/vendor.bundle.js:3601:19)
at ReflectiveInjector_._getByKeyDefault (http://localhost:4200/vendor.bundle.js:3640:25)
at ReflectiveInjector_._getByKey (http://localhost:4200/vendor.bundle.js:3572:25)
at ReflectiveInjector_.get (http://localhost:4200/vendor.bundle.js:3441:21)
at AppModuleInjector.NgModuleInjector.get (http://localhost:4200/vendor.bundle.js:4406:52)
at resolveDep (http://localhost:4200/vendor.bundle.js:11810:45)
at createClass (http://localhost:4200/vendor.bundle.js:11673:147)
at createDirectiveInstance (http://localhost:4200/vendor.bundle.js:11504:37)
at createViewNodes (http://localhost:4200/vendor.bundle.js:12853:49)
at createRootView (http://localhost:4200/vendor.bundle.js:12758:5)
at callWithDebugContext (http://localhost:4200/vendor.bundle.js:13889:42)
at Error.ZoneAwareError (http://localhost:4200/vendor.bundle.js:97291:33)
at ZoneAwareError (http://localhost:4200/vendor.bundle.js:97288:35)
at injectionError (http://localhost:4200/vendor.bundle.js:2061:86)
at noProviderError (http://localhost:4200/vendor.bundle.js:2099:12)
at ReflectiveInjector_._throwOrNull (http://localhost:4200/vendor.bundle.js:3601:19)
at ReflectiveInjector_._getByKeyDefault (http://localhost:4200/vendor.bundle.js:3640:25)
at ReflectiveInjector_._getByKey (http://localhost:4200/vendor.bundle.js:3572:25)
at ReflectiveInjector_.get (http://localhost:4200/vendor.bundle.js:3441:21)
at AppModuleInjector.NgModuleInjector.get (http://localhost:4200/vendor.bundle.js:4406:52)
at resolveDep (http://localhost:4200/vendor.bundle.js:11810:45)
at createClass (http://localhost:4200/vendor.bundle.js:11673:147)
at createDirectiveInstance (http://localhost:4200/vendor.bundle.js:11504:37)
at createViewNodes (http://localhost:4200/vendor.bundle.js:12853:49)
at createRootView (http://localhost:4200/vendor.bundle.js:12758:5)
at callWithDebugContext (http://localhost:4200/vendor.bundle.js:13889:42)
at resolvePromise (http://localhost:4200/vendor.bundle.js:96964:31) [angular]
at resolvePromise (http://localhost:4200/vendor.bundle.js:96935:17) [angular]
at http://localhost:4200/vendor.bundle.js:97012:17 [angular]
at Object.onInvokeTask (http://localhost:4200/vendor.bundle.js:4965:37) [angular]
at ZoneDelegate.invokeTask (http://localhost:4200/vendor.bundle.js:96665:36) [angular]
at Zone.runTask (http://localhost:4200/vendor.bundle.js:96465:47) [<root> => angular]
at drainMicroTaskQueue (http://localhost:4200/vendor.bundle.js:96845:35)
[<root>]
at HTMLAnchorElement.ZoneTask.invoke
(http://localhost:4200/vendor.bundle.js:96723:25) [<root>]get message: function ()set message: function (value)get name: function ()set name: function (value)get originalStack: function ()set originalStack: function (value)get stack: function ()set stack: function (value)get zoneAwareStack: function ()set
zoneAwareStack: function (value)__proto__: Object
defaultErrorLogger @ core.es5.js:1085
ErrorHandler.handleError @ core.es5.js:1145
next @ core.es5.js:4774
schedulerFn @ core.es5.js:3848
SafeSubscriber.__tryOrUnsub @ Subscriber.js:234
SafeSubscriber.next @ Subscriber.js:183
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3834
NgZone.triggerError @ core.es5.js:4205
onHandleError @ core.es5.js:4166
ZoneDelegate.handleError @ zone.js:338
Zone.runGuarded @ zone.js:142
_loop_1 @ zone.js:557
drainMicroTaskQueue @ zone.js:566
ZoneTask.invoke @ zone.js:424
</code>```

I can't figure out what part of my code is creating this as other parts of the app continue to work fine. When I try to roll back my code to a pre-error version, I'm still getting the error. The error is so vague, I have no idea what file or part of the file is causing the error.

Anyone have any ideas on how to start looking for this ?

UPDATE: The error appears to be when I import a service into a component. Here is the code for a dashboard component that imports and uses a service. if I remove this from the dashboard component constructor...

```<code>private CaseService: CaseService
</code>```

The error dissapears. Here is the dashboard component...

```<code>import {Component} from '@angular/core'
import {Router,ActivatedRoute} from '@angular/router'

import {Globals} from '../../models/globals.model'
import {CaseService} from '../../services/case.service'

@Component({
    templateUrl: 'dashboard.html'
})

export class DatabaseDashboard{

    constructor(private Globals: Globals, private Router: Router, private CaseService: CaseService){

   if(this.Globals.CurrentUser.IsLoggedIn !== true){
        this.Router.navigateByUrl('/login')
   }

   let PackageAuthorised = false
   Globals.CurrentUser.Packages.forEach(Package => {
       if(Package.PackageID == 1){ // 1 = Database Package in packages table
           PackageAuthorised = true
       }
   });

   if(PackageAuthorised === false){
        this.Router.navigateByUrl('/login')
   }

   this.CaseService.getAllCasesByUserid().subscribe(
    data => {
        console.log(data)
        if(data != null){
            this.Globals.Cases = data
        } else {
            alert("Failed to fetch Cases from Database")
        }
    })

    }

}
</code>```

...and here is the service...

```<code>import {Component} from '@angular/core'
import {Http,Headers, RequestOptions,URLSearchParams  } from '@angular/http'

import 'rxjs/Rx'
import { Observable } from 'rxjs/Observable'

import {Settings} from '../models/settings.model'
import {Globals} from '../models/globals.model'
import {Case} from '../models/case.model'

@Component({

})

export class CaseService {

constructor(private _http: Http, private Settings: Settings, private Globals: Globals) {

}

getAllCases(){
    console.log(this.Settings.ApiURL + 'cases.php?Method=getAllCases&AdminEmail=' + this.Globals.CurrentUser.UserEmail + '&AdminPassword=' + this.Globals.CurrentUser.UserPassword)
    return this._http.get(this.Settings.ApiURL + 'cases.php?Method=getAllCases&AdminEmail=' + this.Globals.CurrentUser.UserEmail + '&AdminPassword=' + this.Globals.CurrentUser.UserPassword).map(
        result => {
            let data = result.json()
            console.log(data)
            return data
        }
    )
}

getAllCasesByUserid(){
    console.log(this.Settings.ApiURL + 'cases.php?Method=getAllCasesByUserid&UserID=1&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword)
    return this._http.get(this.Settings.ApiURL + 'cases.php?Method=getAllCasesByUserid&UserID=1&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword).map(
        result => {
            console.log(result)
            let data = result.json()
            return data
        }
    )
}

deleteCase(CaseID: number){
     console.log(this.Settings.ApiURL + 'cases.php?Method=deleteCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseID=' + CaseID )

    return this._http.get(this.Settings.ApiURL + 'cases.php?Method=deleteCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseID=' + CaseID ).map(
        result => {
            let data = result.json()
            return data
        }
    )
}

saveNewCase(Case: Case){
    console.log(this.Settings.ApiURL + 'cases.php?Method=saveNewCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseUniqueCode=' + Case.CaseUniqueCode + '&CaseTitle=' + Case.CaseTitle  + '&CreatorUserid=' + Case.CreatorUserid + '&CaseBriefDesc=' + Case.CaseBriefDesc)

    return this._http.get(this.Settings.ApiURL + 'cases.php?Method=saveNewCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseUniqueCode=' + Case.CaseUniqueCode + '&CaseTitle=' + Case.CaseTitle  + '&CreatorUserid=' + Case.CreatorUserid + '&CaseBriefDesc=' + Case.CaseBriefDesc).map(
        result => {
            let data = result.json()
            return data
        }
    )
}

updateCase(Case: Case){
    console.log(this.Settings.ApiURL + 'cases.php?Method=updateCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseID=' + Case.CaseID + '&CaseUniqueCode=' + Case.CaseUniqueCode + '&CaseTitle=' + Case.CaseTitle  + '&CreatorUserid=' + Case.CreatorUserid + '&CaseBriefDesc=' + Case.CaseBriefDesc)

    return this._http.get(this.Settings.ApiURL + 'cases.php?Method=updateCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseID=' + Case.CaseID + '&CaseUniqueCode=' + Case.CaseUniqueCode + '&CaseTitle=' + Case.CaseTitle  + '&CreatorUserid=' + Case.CreatorUserid + '&CaseBriefDesc=' + Case.CaseBriefDesc).map(
        result => {
            let data = result.json()
            return data
        }
    )
}

}
</code>```

Expanded error...

```<code>defaultErrorLogger  @   core.es5.js:1085
ErrorHandler.handleError    @   core.es5.js:1145
next    @   core.es5.js:4774
schedulerFn @   core.es5.js:3848
SafeSubscriber.__tryOrUnsub @   Subscriber.js:234
SafeSubscriber.next @   Subscriber.js:183
Subscriber._next    @   Subscriber.js:125
Subscriber.next @   Subscriber.js:89
Subject.next    @   Subject.js:55
EventEmitter.emit   @   core.es5.js:3834
NgZone.triggerError @   core.es5.js:4205
onHandleError   @   core.es5.js:4166
ZoneDelegate.handleError    @   zone.js:338
Zone.runGuarded @   zone.js:142
_loop_1 @   zone.js:557
drainMicroTaskQueue @   zone.js:566
ZoneTask.invoke @   zone.js:424
</code>```

答:
Sure i wouldn't mind getting some points :).
Please include the service CaseService in the providers section of app.module.ts</p>

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [CaseService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Title: Angular4 - ZoneAwareError

Body:
I'm suddenly seeing an error when I try to run an Angular4 that looks like this...

ERROR ZoneAwareError {__zone_symbol__error: Error: Uncaught (in promise): Error
Error
at Error.ZoneAwareError (http://localhost:4200/vendor.……}message: (...)name: (...)originalStack: (...)promise: ZoneAwarePromiserejection: Errorstack: (...)task: ZoneTasktoSource: function ()toString: function ()zone: ZonezoneAwareStack: (...)__zone_symbol__error: Error: Uncaught (in promise):
Error
Error
at Error.ZoneAwareError (http://localhost:4200/vendor.bundle.js:97291:33)
at ZoneAwareError (http://localhost:4200/vendor.bundle.js:97288:35)
at injectionError (http://localhost:4200/vendor.bundle.js:2061:86)
at noProviderError (http://localhost:4200/vendor.bundle.js:2099:12)
at ReflectiveInjector_._throwOrNull (http://localhost:4200/vendor.bundle.js:3601:19)
at ReflectiveInjector_._getByKeyDefault (http://localhost:4200/vendor.bundle.js:3640:25)
at ReflectiveInjector_._getByKey (http://localhost:4200/vendor.bundle.js:3572:25)
at ReflectiveInjector_.get (http://localhost:4200/vendor.bundle.js:3441:21)
at AppModuleInjector.NgModuleInjector.get (http://localhost:4200/vendor.bundle.js:4406:52)
at resolveDep (http://localhost:4200/vendor.bundle.js:11810:45)
at createClass (http://localhost:4200/vendor.bundle.js:11673:147)
at createDirectiveInstance (http://localhost:4200/vendor.bundle.js:11504:37)
at createViewNodes (http://localhost:4200/vendor.bundle.js:12853:49)
at createRootView (http://localhost:4200/vendor.bundle.js:12758:5)
at callWithDebugContext (http://localhost:4200/vendor.bundle.js:13889:42)
at Error.ZoneAwareError (http://localhost:4200/vendor.bundle.js:97291:33)
at ZoneAwareError (http://localhost:4200/vendor.bundle.js:97288:35)
at injectionError (http://localhost:4200/vendor.bundle.js:2061:86)
at noProviderError (http://localhost:4200/vendor.bundle.js:2099:12)
at ReflectiveInjector_._throwOrNull (http://localhost:4200/vendor.bundle.js:3601:19)
at ReflectiveInjector_._getByKeyDefault (http://localhost:4200/vendor.bundle.js:3640:25)
at ReflectiveInjector_._getByKey (http://localhost:4200/vendor.bundle.js:3572:25)
at ReflectiveInjector_.get (http://localhost:4200/vendor.bundle.js:3441:21)
at AppModuleInjector.NgModuleInjector.get (http://localhost:4200/vendor.bundle.js:4406:52)
at resolveDep (http://localhost:4200/vendor.bundle.js:11810:45)
at createClass (http://localhost:4200/vendor.bundle.js:11673:147)
at createDirectiveInstance (http://localhost:4200/vendor.bundle.js:11504:37)
at createViewNodes (http://localhost:4200/vendor.bundle.js:12853:49)
at createRootView (http://localhost:4200/vendor.bundle.js:12758:5)
at callWithDebugContext (http://localhost:4200/vendor.bundle.js:13889:42)
at resolvePromise (http://localhost:4200/vendor.bundle.js:96964:31) [angular]
at resolvePromise (http://localhost:4200/vendor.bundle.js:96935:17) [angular]
at http://localhost:4200/vendor.bundle.js:97012:17 [angular]
at Object.onInvokeTask (http://localhost:4200/vendor.bundle.js:4965:37) [angular]
at ZoneDelegate.invokeTask (http://localhost:4200/vendor.bundle.js:96665:36) [angular]
at Zone.runTask (http://localhost:4200/vendor.bundle.js:96465:47) [<root> => angular]
at drainMicroTaskQueue (http://localhost:4200/vendor.bundle.js:96845:35)
[<root>]
at HTMLAnchorElement.ZoneTask.invoke
(http://localhost:4200/vendor.bundle.js:96723:25) [<root>]get message: function ()set message: function (value)get name: function ()set name: function (value)get originalStack: function ()set originalStack: function (value)get stack: function ()set stack: function (value)get zoneAwareStack: function ()set
zoneAwareStack: function (value)__proto__: Object
defaultErrorLogger @ core.es5.js:1085
ErrorHandler.handleError @ core.es5.js:1145
next @ core.es5.js:4774
schedulerFn @ core.es5.js:3848
SafeSubscriber.__tryOrUnsub @ Subscriber.js:234
SafeSubscriber.next @ Subscriber.js:183
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3834
NgZone.triggerError @ core.es5.js:4205
onHandleError @ core.es5.js:4166
ZoneDelegate.handleError @ zone.js:338
Zone.runGuarded @ zone.js:142
_loop_1 @ zone.js:557
drainMicroTaskQueue @ zone.js:566
ZoneTask.invoke @ zone.js:424

I can't figure out what part of my code is creating this as other parts of the app continue to work fine. When I try to roll back my code to a pre-error version, I'm still getting the error. The error is so vague, I have no idea what file or part of the file is causing the error.

Anyone have any ideas on how to start looking for this ?

UPDATE: The error appears to be when I import a service into a component. Here is the code for a dashboard component that imports and uses a service. if I remove this from the dashboard component constructor...

private CaseService: CaseService

The error dissapears. Here is the dashboard component...

import {Component} from '@angular/core'
import {Router,ActivatedRoute} from '@angular/router'

import {Globals} from '../../models/globals.model'
import {CaseService} from '../../services/case.service'

@Component({
    templateUrl: 'dashboard.html'
})

export class DatabaseDashboard{

    constructor(private Globals: Globals, private Router: Router, private CaseService: CaseService){

   if(this.Globals.CurrentUser.IsLoggedIn !== true){
        this.Router.navigateByUrl('/login')
   }

   let PackageAuthorised = false
   Globals.CurrentUser.Packages.forEach(Package => {
       if(Package.PackageID == 1){ // 1 = Database Package in packages table
           PackageAuthorised = true
       }
   });

   if(PackageAuthorised === false){
        this.Router.navigateByUrl('/login')
   }

   this.CaseService.getAllCasesByUserid().subscribe(
    data => {
        console.log(data)
        if(data != null){
            this.Globals.Cases = data
        } else {
            alert("Failed to fetch Cases from Database")
        }
    })

    }

}

...and here is the service...

import {Component} from '@angular/core'
import {Http,Headers, RequestOptions,URLSearchParams  } from '@angular/http'

import 'rxjs/Rx'
import { Observable } from 'rxjs/Observable'

import {Settings} from '../models/settings.model'
import {Globals} from '../models/globals.model'
import {Case} from '../models/case.model'

@Component({

})

export class CaseService {

constructor(private _http: Http, private Settings: Settings, private Globals: Globals) {

}

getAllCases(){
    console.log(this.Settings.ApiURL + 'cases.php?Method=getAllCases&AdminEmail=' + this.Globals.CurrentUser.UserEmail + '&AdminPassword=' + this.Globals.CurrentUser.UserPassword)
    return this._http.get(this.Settings.ApiURL + 'cases.php?Method=getAllCases&AdminEmail=' + this.Globals.CurrentUser.UserEmail + '&AdminPassword=' + this.Globals.CurrentUser.UserPassword).map(
        result => {
            let data = result.json()
            console.log(data)
            return data
        }
    )
}

getAllCasesByUserid(){
    console.log(this.Settings.ApiURL + 'cases.php?Method=getAllCasesByUserid&UserID=1&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword)
    return this._http.get(this.Settings.ApiURL + 'cases.php?Method=getAllCasesByUserid&UserID=1&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword).map(
        result => {
            console.log(result)
            let data = result.json()
            return data
        }
    )
}

deleteCase(CaseID: number){
     console.log(this.Settings.ApiURL + 'cases.php?Method=deleteCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseID=' + CaseID )

    return this._http.get(this.Settings.ApiURL + 'cases.php?Method=deleteCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseID=' + CaseID ).map(
        result => {
            let data = result.json()
            return data
        }
    )
}

saveNewCase(Case: Case){
    console.log(this.Settings.ApiURL + 'cases.php?Method=saveNewCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseUniqueCode=' + Case.CaseUniqueCode + '&CaseTitle=' + Case.CaseTitle  + '&CreatorUserid=' + Case.CreatorUserid + '&CaseBriefDesc=' + Case.CaseBriefDesc)

    return this._http.get(this.Settings.ApiURL + 'cases.php?Method=saveNewCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseUniqueCode=' + Case.CaseUniqueCode + '&CaseTitle=' + Case.CaseTitle  + '&CreatorUserid=' + Case.CreatorUserid + '&CaseBriefDesc=' + Case.CaseBriefDesc).map(
        result => {
            let data = result.json()
            return data
        }
    )
}

updateCase(Case: Case){
    console.log(this.Settings.ApiURL + 'cases.php?Method=updateCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseID=' + Case.CaseID + '&CaseUniqueCode=' + Case.CaseUniqueCode + '&CaseTitle=' + Case.CaseTitle  + '&CreatorUserid=' + Case.CreatorUserid + '&CaseBriefDesc=' + Case.CaseBriefDesc)

    return this._http.get(this.Settings.ApiURL + 'cases.php?Method=updateCase&UserEmail=' + this.Globals.CurrentUser.UserEmail + '&UserPassword=' + this.Globals.CurrentUser.UserPassword + '&CaseID=' + Case.CaseID + '&CaseUniqueCode=' + Case.CaseUniqueCode + '&CaseTitle=' + Case.CaseTitle  + '&CreatorUserid=' + Case.CreatorUserid + '&CaseBriefDesc=' + Case.CaseBriefDesc).map(
        result => {
            let data = result.json()
            return data
        }
    )
}

}

Expanded error...

defaultErrorLogger  @   core.es5.js:1085
ErrorHandler.handleError    @   core.es5.js:1145
next    @   core.es5.js:4774
schedulerFn @   core.es5.js:3848
SafeSubscriber.__tryOrUnsub @   Subscriber.js:234
SafeSubscriber.next @   Subscriber.js:183
Subscriber._next    @   Subscriber.js:125
Subscriber.next @   Subscriber.js:89
Subject.next    @   Subject.js:55
EventEmitter.emit   @   core.es5.js:3834
NgZone.triggerError @   core.es5.js:4205
onHandleError   @   core.es5.js:4166
ZoneDelegate.handleError    @   zone.js:338
Zone.runGuarded @   zone.js:142
_loop_1 @   zone.js:557
drainMicroTaskQueue @   zone.js:566
ZoneTask.invoke @   zone.js:424

Body:
Sure i wouldn't mind getting some points :).
Please include the service CaseService in the providers section of app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [CaseService],
  bootstrap: [AppComponent]
})
export class AppModule { }


来源: stackexchange

问:
SQL single table with two columns
I have a single table: Checking, with two columns: ID, Memo

ID is the primary key.

I would like a query that returns both columns: ID, Memo BUT only where Memo is DISTINCT

I can do the following to get the distinct values from Memo:

```<code>SELECT DISTINCT(memo)
FROM checking
</code>```

How do I return those Memo values and their values from the ID column?

I've run in circles trying inner and outer joins but I'm failing.

Thanks for your help

Sample data:

```<code>ID        Memo
1         a
2         c
3         e
4         g
5         a
6         c
</code>```

The desired return:

```<code>1,a
2,c
3,e
4,g
</code>```

5 and 6 would not be included because they have duplicate memo values.

Thanks again for your help.

答:
SELECT ID,MEMO from CHECKING WHERE ID IN (SELECT MIN(ID) FROM CHECKING WHERE MEMO IN (SELECT DISTINCT MEMO FROM CHECKING))

Though nested, this query would server the purpose!

ContentLicense: CC BY-SA 2.5

Title: SQL single table with two columns

Body:
I have a single table: Checking, with two columns: ID, Memo

ID is the primary key.

I would like a query that returns both columns: ID, Memo BUT only where Memo is DISTINCT

I can do the following to get the distinct values from Memo:

SELECT DISTINCT(memo)
FROM checking

How do I return those Memo values and their values from the ID column?

I've run in circles trying inner and outer joins but I'm failing.

Thanks for your help

Sample data:

ID        Memo
1         a
2         c
3         e
4         g
5         a
6         c

The desired return:

1,a
2,c
3,e
4,g

5 and 6 would not be included because they have duplicate memo values.

Thanks again for your help.


问:
ESLint error Unexpected block statement surrounding arrow body
I am using ESlint in my project. I am getting the error ** Unexpected block statement surrounding arrow body** from this function

```<code>const toggleDrawer = (state) => {
 return {
 ...state,
 drawerExpanded: !state.drawerExpanded,
 };
};
</code>```

Can anyone suggest me how to handle this ESlint error?

答:
Wrap the object in parenthesis ()

```<code>const toggleDrawer = (state) => ({
 ...state,
 drawerExpanded: !state.drawerExpanded,
});
</code>```

Also check if you have : arrow-body-style: ["error", "as-needed"] in es-lint

ContentLicense: CC BY-SA 3.0

Body:
I am using ESlint in my project. I am getting the error ** Unexpected block statement surrounding arrow body** from this function

const toggleDrawer = (state) => {
 return {
 ...state,
 drawerExpanded: !state.drawerExpanded,
 };
};

Can anyone suggest me how to handle this ESlint error?

Body:
Wrap the object in parenthesis ()

const toggleDrawer = (state) => ({
 ...state,
 drawerExpanded: !state.drawerExpanded,
});

Also check if you have : arrow-body-style: ["error", "as-needed"] in es-lint


问:
How to start asp.net core server on linux and keep it running
I have created basic ASP.Net Core server on Azure Ubuntu VM. I have exposed the server to a port 80 using nginx.
I am conecting to the VM via ssh.
And starting the server with "dotnet run" command.
That works fine.

However, every time I close the ssh connection, the server is stopping as well.
Is there a way to start and keep running the asp.net core server on Linux without having an active ssh connection?

答:
Basically what happens is:

You login with ssh

you startup an application under your user (dotnet run)

Close your ssh => logging out user, which means application is closed.

You need to start a service outside of your user. Here is some information:

https://askubuntu.com/questions/8653/how-to-keep-processes-running-after-ending-ssh-session

Otherwise i'd advice you to ask on https://askubuntu.com/


问:
is it possible to unload an Assembly loaded dynamically in dotnet core?
in .net framework was possible to load an assembly in separate AppDomain then unload it.
in .net core AppDomain not available and replaced by AssemblyLoadContext.
i can load assembly to AssemblyLoadContext as below:

```<code> var assembly = AssemblyLoadContext.Default.LoadFromStream(stream);
</code>```

there is any way to unload it?

答:
Check out this link here

The unload api is not yet completed.

```<code>namespace System.Runtime.Loader
{
    public class AssemblyLoadContext
    {
        // Allow to create an unloadable ALC. The default constructor
        // will call this method with false
        protected AssemblyLoadContext(bool unloadable);

        // Returns true if this ALC is collectible
        public bool Unloadable {get; }

        // Allows to explicitly unload an ALC. Once this method is called,
        // any call to LoadFromXXX method will throw an exception
        public void Unload();
    }
}
</code>```

there's an open issue for the unload api and the api has been approved probably released in the future version as the milestone is under Future tag.

Body:
in .net framework was possible to load an assembly in separate AppDomain then unload it.
in .net core AppDomain not available and replaced by AssemblyLoadContext.
i can load assembly to AssemblyLoadContext as below:

 var assembly = AssemblyLoadContext.Default.LoadFromStream(stream);

there is any way to unload it?

Body:
Check out this link here

The unload api is not yet completed.

namespace System.Runtime.Loader
{
    public class AssemblyLoadContext
    {
        // Allow to create an unloadable ALC. The default constructor
        // will call this method with false
        protected AssemblyLoadContext(bool unloadable);

        // Returns true if this ALC is collectible
        public bool Unloadable {get; }

        // Allows to explicitly unload an ALC. Once this method is called,
        // any call to LoadFromXXX method will throw an exception
        public void Unload();
    }
}

there's an open issue for the unload api and the api has been approved probably released in the future version as the milestone is under Future tag.


问:
Working on a Git feature branch and use(?) branch at the same time
I'm new to Git, and sometimes I find myself working on a feature branch(say adding library A) while also working on program B that uses it(which I call the use branch, maybe there is a better word). So what I've done in the past is have two separate branches, work on the feature branch 'til it seems like it might work, then start using the API in the use branch, merge the feature branch in and see if it works. If it doesn't work, I go back to the feature branch, fix the issue, merge and repeat. Is this the best way to do this?

My goal is to keep the feature branch separate from any implementation that uses it(though I suppose even that is up for debate). What I also thought of later is presuming I'm editing a limited number of files I could just do the 'fixing' changes in the use branch and use 'git checkout' in the feature branch to bring just the library changes back in.

What I guess I really want is to be working in a single workspace, but specify that these files belong to branch A and these files belong to branch B and be able to commit them separately. (I can imagine an implementation where you specify 2(or n) branches to combine into a pseudo branch, presuming that you don't alter the same files. Then when you change files that are in one branch you can commit just those files to that branch(and if you modify new files, you have to specify which branch this file 'belongs' to)). For all I know this may be in opposition to how Git works, but I don't know it enough to tell. :)

Thoughts?

Clarifications/Addendums:

This is a single program in one repository(though two repositories may be the solution)

There are two branches I'm currently working with

Example(not actually what I'm doing :)):
I'm writing a program to generate a random number and then write it to a file. So my main program is in its own branch(what I refer to as my 'use' branch). My main program is simply:

MyFileApi::Write("myfile", random());

where random() is some system API that already exists, but MyFileApi::Write is a new feature I'm developing(so my program is using this new feature). In my 'feature branch' I have say a header file and implementation for MyFileApi::Write. So I've written some implementation of MyFileApi::Write, but I want to test it using my new random-number-file-writer program(it would probably be best to write tests specifically for this API, but I'm being lazy and testing it in my program that uses the code). So what I've been doing is merging in my MyFileApi::Write changes into my 'use' branch, testing it, seeing it fail, going back to my feature branch, fixing the issue, merging again, repeat etc...

答:
There is nothing preventing you from cloning the repository twice, so you have two local workspaces, one for each branch.  If the build output from the feature branch needs to be in the use branch, you can always use symlinks (assuming you are on a Unixy OS) and .gitignore them from the use branch.

However, if these are two different programs (and it sounds like they are) then they should not be on separate branches at all -- they should either be in the same directory tree in both branches, or they should be in separate repositories altogether.  It's not considered good style to have one branch exclusively for one program and one branch exclusively for another (unless they are release branches or something special like that).


问:
Qmail - Local Queue stacking up
I have a big problem!
My customer contacted me, and told me that he isn't recieving emails from his websites contactform. I checked the mail-queue in Plesk, and I can see that they're stuck in "local"(!)

I tried to force send by running this in SSH kill -ALRM ps ax | grep [q]mail-send | awk '{print $1}'

It's not working - returns a empty line in my SSH.
I have tried similar solutions - but no luck.
Is there anything I can do, to get some more information about this issue?
I'm not an expert in Plesk at all - and all the help I can get is GREATLY appreciated.

Maillog:

```<code>Mar 29 08:14:12 opening qmail-local-handlers[28962]: from=lyg@lyg.dk
Mar 29 08:14:12 opening qmail-local-handlers[28962]: to=opening.dk-ak@opening.dk
Mar 29 08:14:12 opening qmail-local-handlers[28962]: mailbox: /var/qmail/mailnam                                                 es/opening.dk
Mar 29 08:14:12 opening qmail: 1490775252.408838 delivery 55: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.408855 status: local 5/10 remote 0/20
Mar 29 08:14:12 opening qmail: 1490775252.411033 delivery 57: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.411060 status: local 4/10 remote 0/20
Mar 29 08:14:12 opening qmail: 1490775252.412893 delivery 54: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.412910 status: local 3/10 remote 0/20
Mar 29 08:14:12 opening qmail: 1490775252.414351 delivery 53: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.414369 status: local 2/10 remote 0/20
Mar 29 08:14:12 opening qmail: 1490775252.414377 delivery 58: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.414384 status: local 1/10 remote 0/20
Mar 29 08:14:12 opening qmail: 1490775252.414554 delivery 56: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.414570 status: local 0/10 remote 0/20
Mar 29 08:14:41 opening qmail-queue-handlers[29038]: Unable to change group ID:                                                  Operation not permitted
Mar 29 08:14:41 opening qmail: 1490775281.517412 warning: trouble injecting boun                                                 ce message, will try later
Mar 29 08:14:41 opening qmail-queue-handlers[29039]: Unable to change group ID:                                                  Operation not permitted
Mar 29 08:14:41 opening qmail: 1490775281.518755 warning: trouble injecting boun                                                 ce message, will try later
</code>```

And if I run ps -ef|grep mail I get the following output:

```<code>[opening@opening log]$ ps -ef|grep mail
qmails   28182     1  0 08:10 ?        00:00:00 qmail-send
qmaill   28184 28182  0 08:10 ?        00:00:00 splogger qmail
root     28185 28182  0 08:10 ?        00:00:00 qmail-lspawn | /deliverquota ./Maildir
qmailr   28186 28182  0 08:10 ?        00:00:00 qmail-rspawn
qmailq   28187 28182  0 08:10 ?        00:00:00 qmail-clean
opening  29554 28582  0 08:20 pts/0    00:00:00 grep mail
root     64808     1  0 Mar23 ?        00:01:10 /usr/bin/spamd --nouser-config --username=popuser --daemonize --helper-home-dir=/var/qmail --virtual-config-dir=/var/qmail/mailnames/%d/%l/.spamassassin --create-prefs --max-children=5 -r /var/run/spamd.pid
</code>```

When I run plesk repair mail -y -v I get the following output:

```<code>[opening@opening log]$ sudo plesk repair mail -y -v Repairing the mail server configuration Reconfiguring all domains and mailboxes ......................... [OK] Error messages: 0; Warnings: 0; Errors resolved: 0
</code>```

Btw. Plesk is installed on an Azure server - if that is to any help at all.

Please let me know if I can provide any other info - and how.

Best regards

Aris Kuckovic

答:
The line:

```<code>Mar 29 08:14:41 opening qmail-queue-handlers[29038]: Unable to change group ID:Operation not permitted
</code>```

suggests that it maybe because of a permissions issue. You should open a ticket with Plesk support or check on their forums.

You can also switch to postfix as it is more widely used

Title: Qmail - Local Queue stacking up

Body:
I have a big problem!
My customer contacted me, and told me that he isn't recieving emails from his websites contactform. I checked the mail-queue in Plesk, and I can see that they're stuck in "local"(!)

I tried to force send by running this in SSH kill -ALRM ps ax | grep [q]mail-send | awk '{print $1}'

It's not working - returns a empty line in my SSH.
I have tried similar solutions - but no luck.
Is there anything I can do, to get some more information about this issue?
I'm not an expert in Plesk at all - and all the help I can get is GREATLY appreciated.

Maillog:

Mar 29 08:14:12 opening qmail-local-handlers[28962]: from=lyg@lyg.dk
Mar 29 08:14:12 opening qmail-local-handlers[28962]: to=opening.dk-ak@opening.dk
Mar 29 08:14:12 opening qmail-local-handlers[28962]: mailbox: /var/qmail/mailnam                                                 es/opening.dk
Mar 29 08:14:12 opening qmail: 1490775252.408838 delivery 55: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.408855 status: local 5/10 remote 0/20
Mar 29 08:14:12 opening qmail: 1490775252.411033 delivery 57: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.411060 status: local 4/10 remote 0/20
Mar 29 08:14:12 opening qmail: 1490775252.412893 delivery 54: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.412910 status: local 3/10 remote 0/20
Mar 29 08:14:12 opening qmail: 1490775252.414351 delivery 53: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.414369 status: local 2/10 remote 0/20
Mar 29 08:14:12 opening qmail: 1490775252.414377 delivery 58: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.414384 status: local 1/10 remote 0/20
Mar 29 08:14:12 opening qmail: 1490775252.414554 delivery 56: deferral: /bin/sh:                                                 _/deliverquota:_No_such_file_or_directory/
Mar 29 08:14:12 opening qmail: 1490775252.414570 status: local 0/10 remote 0/20
Mar 29 08:14:41 opening qmail-queue-handlers[29038]: Unable to change group ID:                                                  Operation not permitted
Mar 29 08:14:41 opening qmail: 1490775281.517412 warning: trouble injecting boun                                                 ce message, will try later
Mar 29 08:14:41 opening qmail-queue-handlers[29039]: Unable to change group ID:                                                  Operation not permitted
Mar 29 08:14:41 opening qmail: 1490775281.518755 warning: trouble injecting boun                                                 ce message, will try later

And if I run ps -ef|grep mail I get the following output:

[opening@opening log]$ ps -ef|grep mail
qmails   28182     1  0 08:10 ?        00:00:00 qmail-send
qmaill   28184 28182  0 08:10 ?        00:00:00 splogger qmail
root     28185 28182  0 08:10 ?        00:00:00 qmail-lspawn | /deliverquota ./Maildir
qmailr   28186 28182  0 08:10 ?        00:00:00 qmail-rspawn
qmailq   28187 28182  0 08:10 ?        00:00:00 qmail-clean
opening  29554 28582  0 08:20 pts/0    00:00:00 grep mail
root     64808     1  0 Mar23 ?        00:01:10 /usr/bin/spamd --nouser-config --username=popuser --daemonize --helper-home-dir=/var/qmail --virtual-config-dir=/var/qmail/mailnames/%d/%l/.spamassassin --create-prefs --max-children=5 -r /var/run/spamd.pid

When I run plesk repair mail -y -v I get the following output:

[opening@opening log]$ sudo plesk repair mail -y -v Repairing the mail server configuration Reconfiguring all domains and mailboxes ......................... [OK] Error messages: 0; Warnings: 0; Errors resolved: 0

Btw. Plesk is installed on an Azure server - if that is to any help at all.

Please let me know if I can provide any other info - and how.

Best regards

Aris Kuckovic

Body:
The line:

Mar 29 08:14:41 opening qmail-queue-handlers[29038]: Unable to change group ID:Operation not permitted

suggests that it maybe because of a permissions issue. You should open a ticket with Plesk support or check on their forums.

You can also switch to postfix as it is more widely used


问:
How to convert a html table obtained as a parameter on success of a Jquery $.get method
I have a Jquery $.get function which calls a controller which in turn returns a View containing a html table.

```<code> $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
 }
</code>```

This works fine and displays the table as intended. But i cant get this returned table to convert to a datatable using Jquery datatable() method as shown below.

```<code> $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
        $('#mytable').datatable();
 }
</code>```

I get an error Uncaught TypeError: $(...).datatable is not a function
Any way to get this working ? Also, i tried converting the table in the view itself and that didnt work either.

答:
Addition to Gen Answer, Please make sure you have added relevant script files to your page, </p>

<p>//cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js
For Style
//cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css </p>

Body:
I have a Jquery $.get function which calls a controller which in turn returns a View containing a html table.

 $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
 }

This works fine and displays the table as intended. But i cant get this returned table to convert to a datatable using Jquery datatable() method as shown below.

 $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
        $('#mytable').datatable();
 }

I get an error Uncaught TypeError: $(...).datatable is not a function
Any way to get this working ? Also, i tried converting the table in the view itself and that didnt work either.

Body:
Addition to Gen Answer, Please make sure you have added relevant script files to your page,

//cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js
For Style
//cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css


问:
the miracle of 'this' keyword JavaScript
```<code>var obj = {};
obj.fn = function() {
    return this;
    }
</code>```

output: Window object

is the 'this' not pertaning to 'obj' which is the objectof property 'fn'?

but if I make declare like this below...

```<code>var obj = {
    fn: function() {
        console.log(this);
       }
    }
</code>```

output is... Object object

are they not the same?

答:
Both your examples shall return the object itself with the console log of this, the window object is logged when reading this in the global scope:

```<code>    var obj = {};
    obj.fn = function() {
      console.log(this);
    }

    // logs window
    console.log(this);

    // logs object
    obj.fn();

    var obj1 = {
      fn: function() {
        console.log(this);
      }
    }

    // logs object
    obj1.fn();
</code>```

this will always take the value of the containing scope

Body:
var obj = {};
obj.fn = function() {
    return this;
    }

output: Window object

is the 'this' not pertaning to 'obj' which is the objectof property 'fn'?

but if I make declare like this below...

var obj = {
    fn: function() {
        console.log(this);
       }
    }

output is... Object object

are they not the same?

Body:
Both your examples shall return the object itself with the console log of this, the window object is logged when reading this in the global scope:

    var obj = {};
    obj.fn = function() {
      console.log(this);
    }

    // logs window
    console.log(this);

    // logs object
    obj.fn();

    var obj1 = {
      fn: function() {
        console.log(this);
      }
    }

    // logs object
    obj1.fn();

this will always take the value of the containing scope


问:
Create PushButtons in QTableView with QStyledItemDelegate subclass
I have the exact same problem, but I will use the QTableView widget. I read this and was wondering if I can override the createEditor function to use for instance QFileDialog to get the new data.

If this is possible, can anyone provide me with an example to implement such a subclass to QItemDelegate.

And if not, can anyone provide me with an example to implement a subclass to QItemDelegate, witch can draw a button next to a QLineEdit to get the functionality here.

Edit: Maybe this question is really stupid and i dont realize, because I left the project for around half a year.

Second: Is it safe to update from Qt 5.7 to 5.8?

答:
I have done my best and here is my solution.
The code for the QStyledItemDelegate subclass is mostly from here.

Solution Picture

However, there is one things I am curious to fix: (maybe someone can help me and left a comment)

QPixmap::grabWidget is deprecated, use QWidget::grab() instead but it looks like QWidget::grab() is not the right solution for this purpose.

foo.h:

```<code>#ifndef LIBRARYITEMDELEGATE_H
#define LIBRARYITEMDELEGATE_H

#include <QStyledItemDelegate>
#include <QWidget>
#include <QPushButton>
#include <QTableView>

class LibraryItemDelegate : public QStyledItemDelegate
{
    Q_OBJECT

public:
    explicit LibraryItemDelegate(QObject *parent = 0);
    ~LibraryItemDelegate();

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
//    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void setModelData(QWidget *editor, QAbstractItemModel *modal, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;

public slots:
    void cellEntered(const QModelIndex &index);

private:
    QTableView *myView;
    QPushButton *btn;
    bool isOneCellInEditMode;
    QPersistentModelIndex currentEditedCellIndex;
};

#endif // LIBRARYITEMDELEGATE_H
</code>```

foo.cpp:

```<code>#include "libraryitemdelegate.h"

#include <QPainter>
#include <QStylePainter>

LibraryItemDelegate::LibraryItemDelegate(QObject *parent) : QStyledItemDelegate(parent)
{
    if(QTableView *tableView = qobject_cast<QTableView*>(parent))
    {
        myView = tableView;
        btn = new QPushButton("...", myView);
        btn->hide();
        myView->setMouseTracking(true);
        connect(myView, SIGNAL(entered(QModelIndex)), this, SLOT(cellEntered(QModelIndex)));
        isOneCellInEditMode = false;
    }
}

LibraryItemDelegate::~LibraryItemDelegate(){}

void LibraryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if(index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1)
    {
        btn->setGeometry(option.rect);
        btn->setText("...");
        if(option.state == QStyle::State_Selected)
        {
            painter->fillRect(option.rect, option.palette.highlight());
        }
        QPixmap map = QPixmap::grabWidget(btn);
        painter->drawPixmap(option.rect.x(), option.rect.y(), map);
    }
    else
    {
        QStyledItemDelegate::paint(painter, option, index);
    }
}

//QSize LibraryItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
//{
//    // return the QSize of the item in Your view
//}

QWidget *LibraryItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if(index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1)
    {
        QPushButton *btn = new QPushButton(parent);
//        btn->setText(index.data().toString());
        btn->setText("...");
        return btn;
    }
    else
    {
        return QStyledItemDelegate::createEditor(parent, option, index);
    }
}

void LibraryItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    if(index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1)
    {
        QPushButton *btn = qobject_cast<QPushButton*>(editor);
//        btn->setProperty("data_value", index.data());
        btn->setProperty("data_value", "...");
        btn->setText("...");
    }
    else
    {
        QStyledItemDelegate::setEditorData(editor, index);
    }
}

void LibraryItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    if(index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1)
    {
        QPushButton *btn = qobject_cast<QPushButton*>(editor);
        model->setData(index, btn->property("data_value"));
    }
    else
    {
        QStyledItemDelegate::setModelData(editor, model, index);
    }
}

void LibraryItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

void LibraryItemDelegate::cellEntered(const QModelIndex &index)
{
    if(index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1)
    {
        if(isOneCellInEditMode)
        {
            myView->closePersistentEditor(currentEditedCellIndex);
        }
        myView->openPersistentEditor(index);
        isOneCellInEditMode = true;
        currentEditedCellIndex = index;
    }
    else
    {
        if(isOneCellInEditMode)
        {
            isOneCellInEditMode = false;
            myView->closePersistentEditor(currentEditedCellIndex);
        }
    }
}
</code>```

Implementation:

```<code>QStandardItemModel *myModel; // This is in the Header file

myModel = new QStandardItemModel(0,2,this);
myModel->setHeaderData(1, Qt::Horizontal, 1, Qt::UserRole);
myModel->setHorizontalHeaderLabels(QStringList(tr("Pfad zu den bibliotheks Ordnern")));

// Set Model and delegate to the View
ui->tableView_pathes->setModel(myModel);
LibraryItemDelegate *delegate = new LibraryItemDelegate(ui->tableView_pathes);
ui->tableView_pathes->setItemDelegate(delegate);

// Stretch only the first column
ui->tableView_pathes->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Stretch);
ui->tableView_pathes->horizontalHeader()->setSectionResizeMode(1,QHeaderView::Fixed);
</code>```

Edit: Here is the code for the buttons in the tableView. Connect the signals in createEditor with connect(btn, SIGNAL(pressed()), this, SLOT(buttonPressed())); and set give the delegate a reference to the QStandardItemModel.

```<code>void LibraryItemDelegate::buttonPressed()
{
    QString dir = QFileDialog::getExistingDirectory(new QWidget(), tr("Wähle die bibliotheks Ordner"), "/home", QFileDialog::ShowDirsOnly);

    qDebug() << "Test: " << dir;

    if(!dir.isEmpty())
    {
        QModelIndex ind = currentEditedCellIndex.model()->index(currentEditedCellIndex.row(), 0);
        myModel->setData(ind, dir, Qt::DisplayRole);
    }
}
</code>```

Body:
I have done my best and here is my solution.
The code for the QStyledItemDelegate subclass is mostly from here.

Solution Picture

However, there is one things I am curious to fix: (maybe someone can help me and left a comment)

QPixmap::grabWidget is deprecated, use QWidget::grab() instead but it looks like QWidget::grab() is not the right solution for this purpose.

foo.h:

#ifndef LIBRARYITEMDELEGATE_H
#define LIBRARYITEMDELEGATE_H

#include <QStyledItemDelegate>
#include <QWidget>
#include <QPushButton>
#include <QTableView>

class LibraryItemDelegate : public QStyledItemDelegate
{
    Q_OBJECT

public:
    explicit LibraryItemDelegate(QObject *parent = 0);
    ~LibraryItemDelegate();

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
//    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void setModelData(QWidget *editor, QAbstractItemModel *modal, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;

public slots:
    void cellEntered(const QModelIndex &index);

private:
    QTableView *myView;
    QPushButton *btn;
    bool isOneCellInEditMode;
    QPersistentModelIndex currentEditedCellIndex;
};

#endif // LIBRARYITEMDELEGATE_H

foo.cpp:

#include "libraryitemdelegate.h"

#include <QPainter>
#include <QStylePainter>

LibraryItemDelegate::LibraryItemDelegate(QObject *parent) : QStyledItemDelegate(parent)
{
    if(QTableView *tableView = qobject_cast<QTableView*>(parent))
    {
        myView = tableView;
        btn = new QPushButton("...", myView);
        btn->hide();
        myView->setMouseTracking(true);
        connect(myView, SIGNAL(entered(QModelIndex)), this, SLOT(cellEntered(QModelIndex)));
        isOneCellInEditMode = false;
    }
}

LibraryItemDelegate::~LibraryItemDelegate(){}

void LibraryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if(index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1)
    {
        btn->setGeometry(option.rect);
        btn->setText("...");
        if(option.state == QStyle::State_Selected)
        {
            painter->fillRect(option.rect, option.palette.highlight());
        }
        QPixmap map = QPixmap::grabWidget(btn);
        painter->drawPixmap(option.rect.x(), option.rect.y(), map);
    }
    else
    {
        QStyledItemDelegate::paint(painter, option, index);
    }
}

//QSize LibraryItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
//{
//    // return the QSize of the item in Your view
//}

QWidget *LibraryItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if(index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1)
    {
        QPushButton *btn = new QPushButton(parent);
//        btn->setText(index.data().toString());
        btn->setText("...");
        return btn;
    }
    else
    {
        return QStyledItemDelegate::createEditor(parent, option, index);
    }
}

void LibraryItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    if(index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1)
    {
        QPushButton *btn = qobject_cast<QPushButton*>(editor);
//        btn->setProperty("data_value", index.data());
        btn->setProperty("data_value", "...");
        btn->setText("...");
    }
    else
    {
        QStyledItemDelegate::setEditorData(editor, index);
    }
}

void LibraryItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    if(index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1)
    {
        QPushButton *btn = qobject_cast<QPushButton*>(editor);
        model->setData(index, btn->property("data_value"));
    }
    else
    {
        QStyledItemDelegate::setModelData(editor, model, index);
    }
}

void LibraryItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

void LibraryItemDelegate::cellEntered(const QModelIndex &index)
{
    if(index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1)
    {
        if(isOneCellInEditMode)
        {
            myView->closePersistentEditor(currentEditedCellIndex);
        }
        myView->openPersistentEditor(index);
        isOneCellInEditMode = true;
        currentEditedCellIndex = index;
    }
    else
    {
        if(isOneCellInEditMode)
        {
            isOneCellInEditMode = false;
            myView->closePersistentEditor(currentEditedCellIndex);
        }
    }
}

Implementation:

QStandardItemModel *myModel; // This is in the Header file

myModel = new QStandardItemModel(0,2,this);
myModel->setHeaderData(1, Qt::Horizontal, 1, Qt::UserRole);
myModel->setHorizontalHeaderLabels(QStringList(tr("Pfad zu den bibliotheks Ordnern")));

// Set Model and delegate to the View
ui->tableView_pathes->setModel(myModel);
LibraryItemDelegate *delegate = new LibraryItemDelegate(ui->tableView_pathes);
ui->tableView_pathes->setItemDelegate(delegate);

// Stretch only the first column
ui->tableView_pathes->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Stretch);
ui->tableView_pathes->horizontalHeader()->setSectionResizeMode(1,QHeaderView::Fixed);

Edit: Here is the code for the buttons in the tableView. Connect the signals in createEditor with connect(btn, SIGNAL(pressed()), this, SLOT(buttonPressed())); and set give the delegate a reference to the QStandardItemModel.

void LibraryItemDelegate::buttonPressed()
{
    QString dir = QFileDialog::getExistingDirectory(new QWidget(), tr("Wähle die bibliotheks Ordner"), "/home", QFileDialog::ShowDirsOnly);

    qDebug() << "Test: " << dir;

    if(!dir.isEmpty())
    {
        QModelIndex ind = currentEditedCellIndex.model()->index(currentEditedCellIndex.row(), 0);
        myModel->setData(ind, dir, Qt::DisplayRole);
    }
}


问:
the inherited class is not compatible with its parent when passing through an pointer agrument in C++
Consider the following code: collection technically is a vector with sort method in addition.

```<code>template<class T>
class collection
{
public:
  std::vector<T> vec;
  void sort(sortType<T>* U, bool compare(T, T))
  {
      U->doSort(vec, compare) ;
  }
}
</code>```

And this is class sortType

```<code>template<class T>
class sortType
{
 protected:
   virtual void doSort(std::vector<T>&,  bool compare(T, T)){};
}
</code>```

The following code is some different sorting methods that I want to use

```<code>template<class T>
class insertionsort : public sortType
{
 public:
   void doSort(std::vector<T>&, bool compare(T, T))
    {
      //code of insertion sort
    }
}
template<class T>
class quicksort : public sortType
{
 public:
   void doSort(std::vector<T>&, bool compare(T, T))
    {
      //code of quicksort
    }
}
</code>```

compare is a function look like this:

```<code>template <class T>
bool greater( T l, T r)
{
    if (l<r) return true;
    return false;
}
</code>```

I want to use the previous class like this:

```<code>insertionsort<int> U = insertionsort<int>();
collection<int> *Obj = new collection<int>();
Obj->sort(U, greater) ;    //error here!
</code>```

Unfortunately, visual studio announced that I cannot pass the insertionsort class to sortType class. How could I fix it and use something like those previous. Thank for helpings

I have written a small code to test with same proplem

```<code>template<class T>
T doSomeThing(int a, int b, pheptoan<T>* U)
{
    return U->dopheptoan<int>(a, b);
}

int _tmain(int argc, _TCHAR* argv[])
{
    int a = 6; int b = 7;
    phepcong<int>* U = new phepcong<int>();
    doSomeThing<int>(a, b, U);     //error here
    return 0;
}
</code>```

答:
I assume you declare sortType before collection.

Your derived class should be declared as

template<class T> class insertionsort : public sortType<T>

template<class T> class quicksort : public sortType<T>

And collection::sort takes a pointer to sortType, so the last line should be `Obj->sort(&U, greater);'

Body:
Consider the following code: collection technically is a vector with sort method in addition.

template<class T>
class collection
{
public:
  std::vector<T> vec;
  void sort(sortType<T>* U, bool compare(T, T))
  {
      U->doSort(vec, compare) ;
  }
}

And this is class sortType

template<class T>
class sortType
{
 protected:
   virtual void doSort(std::vector<T>&,  bool compare(T, T)){};
}

The following code is some different sorting methods that I want to use

template<class T>
class insertionsort : public sortType
{
 public:
   void doSort(std::vector<T>&, bool compare(T, T))
    {
      //code of insertion sort
    }
}
template<class T>
class quicksort : public sortType
{
 public:
   void doSort(std::vector<T>&, bool compare(T, T))
    {
      //code of quicksort
    }
}

compare is a function look like this:

template <class T>
bool greater( T l, T r)
{
    if (l<r) return true;
    return false;
}

I want to use the previous class like this:

insertionsort<int> U = insertionsort<int>();
collection<int> *Obj = new collection<int>();
Obj->sort(U, greater) ;    //error here!

Unfortunately, visual studio announced that I cannot pass the insertionsort class to sortType class. How could I fix it and use something like those previous. Thank for helpings

I have written a small code to test with same proplem

template<class T>
T doSomeThing(int a, int b, pheptoan<T>* U)
{
    return U->dopheptoan<int>(a, b);
}

int _tmain(int argc, _TCHAR* argv[])
{
    int a = 6; int b = 7;
    phepcong<int>* U = new phepcong<int>();
    doSomeThing<int>(a, b, U);     //error here
    return 0;
}


问:
TestNG Reporting, how to quickly identify Retry-d Tests?
Hello: When a @Test fails and a Retry happens, is there a direct way in TestNG to distinguish between a Test that has been Retried and a test that has not been retried - such as through a NG context method or variable?

Case 1: If a Test not been retried then the 1st test is a test that has not been retried.

Case 2: If a Test that has been retried 2 times then the 3rd test is a test that has not been retried.

Some options i have found such as http://www.seleniumeasy.com/testng-tutorials/retry-listener-failed-tests-count-update - but wanted to check if the community has other means and/or recommendations.

答:
You can try something like this. The idea is to basically retrieve the retry analyser instance associated with a particular test method and then query its retry count. If its retry count was greater than zero, then that method was retried.</p>

```<code>import org.testng.Assert;
import org.testng.IRetryAnalyzer;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

@Listeners(IdentifyRetriedTests.IdentifyingListener.class)
public class IdentifyRetriedTests {
    private static AtomicInteger counter = new AtomicInteger(0);
    private static AtomicInteger anotherCounter = new AtomicInteger(0);

    @Test(retryAnalyzer = Retry.class)
    public void hello() {
        if (counter.incrementAndGet() == 3) {
            Assert.assertTrue(true);
        } else {
            Assert.fail();
        }
    }

    @Test(retryAnalyzer = Retry.class)
    public void anotherHello() {
        if (anotherCounter.incrementAndGet() == 5) {
            Assert.assertTrue(true);
        } else {
            Assert.fail();
        }

    }

    public static class IdentifyingListener extends TestListenerAdapter {

        @Override
        public void onTestSuccess(ITestResult tr) {
            IRetryAnalyzer retry = tr.getMethod().getRetryAnalyzer();
            if (retry instanceof Retry) {
                //Check if the retry analyser's retry count was greater than zero. If yes, then its a retried method
                if (((Retry) retry).getRetryCount() > 0) {
                    tr.setAttribute("retried", true);
                }
            }
        }

        @Override
        public void onFinish(ITestContext testContext) {
            Set<ITestResult> results = new HashSet<>();
            results.addAll(testContext.getFailedTests().getAllResults());
            results.addAll(testContext.getPassedTests().getAllResults());
            for (ITestResult result : results) {
                if (result.getAttribute("retried") != null) {
                    System.err.println(result.getMethod().getMethodName() + "() was retried");
                }
            }
        }
    }

    public static class Retry implements IRetryAnalyzer {
        private AtomicInteger retryCount = new AtomicInteger(0);
        private static int maxRetryCount = 10;

        public boolean retry(ITestResult result) {
            return retryCount.getAndIncrement() < maxRetryCount;
        }

        int getRetryCount() {
            return retryCount.get();
        }
    }
}
</code>```

Body:
You can try something like this. The idea is to basically retrieve the retry analyser instance associated with a particular test method and then query its retry count. If its retry count was greater than zero, then that method was retried.

import org.testng.Assert;
import org.testng.IRetryAnalyzer;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

@Listeners(IdentifyRetriedTests.IdentifyingListener.class)
public class IdentifyRetriedTests {
    private static AtomicInteger counter = new AtomicInteger(0);
    private static AtomicInteger anotherCounter = new AtomicInteger(0);

    @Test(retryAnalyzer = Retry.class)
    public void hello() {
        if (counter.incrementAndGet() == 3) {
            Assert.assertTrue(true);
        } else {
            Assert.fail();
        }
    }

    @Test(retryAnalyzer = Retry.class)
    public void anotherHello() {
        if (anotherCounter.incrementAndGet() == 5) {
            Assert.assertTrue(true);
        } else {
            Assert.fail();
        }

    }

    public static class IdentifyingListener extends TestListenerAdapter {

        @Override
        public void onTestSuccess(ITestResult tr) {
            IRetryAnalyzer retry = tr.getMethod().getRetryAnalyzer();
            if (retry instanceof Retry) {
                //Check if the retry analyser's retry count was greater than zero. If yes, then its a retried method
                if (((Retry) retry).getRetryCount() > 0) {
                    tr.setAttribute("retried", true);
                }
            }
        }

        @Override
        public void onFinish(ITestContext testContext) {
            Set<ITestResult> results = new HashSet<>();
            results.addAll(testContext.getFailedTests().getAllResults());
            results.addAll(testContext.getPassedTests().getAllResults());
            for (ITestResult result : results) {
                if (result.getAttribute("retried") != null) {
                    System.err.println(result.getMethod().getMethodName() + "() was retried");
                }
            }
        }
    }

    public static class Retry implements IRetryAnalyzer {
        private AtomicInteger retryCount = new AtomicInteger(0);
        private static int maxRetryCount = 10;

        public boolean retry(ITestResult result) {
            return retryCount.getAndIncrement() < maxRetryCount;
        }

        int getRetryCount() {
            return retryCount.get();
        }
    }
}


问:
Android : IllegalArgumentException: "Component class X does not exist" in API 17 (no crash in API 8)
My emulators :

When I launch the tablet emulator I get :

```<code>FATAL EXCEPTION: main
java.lang.IllegalArgumentException: Component class TriggerMonitoringBootReceiver does not exist in di.k23b.hw3
    at android.os.Parcel.readException(Parcel.java:1429)
    at android.os.Parcel.readException(Parcel.java:1379)
    at android.content.pm.IPackageManager$Stub$Proxy.setComponentEnabledSetting(IPackageManager.java:2561)
    at android.app.ApplicationPackageManager.setComponentEnabledSetting(ApplicationPackageManager.java:1250)
    at di.k23b.hw3.receivers.TriggerMonitoringBootReceiver.enable(TriggerMonitoringBootReceiver.java:81)
    at di.k23b.hw3.receivers.TriggerMonitoringBootReceiver.enable(TriggerMonitoringBootReceiver.java:86)
    at di.k23b.hw3.activities.SettingsActivity.onSharedPreferenceChanged(SettingsActivity.java:192)
    at android.app.SharedPreferencesImpl$EditorImpl.notifyListeners(SharedPreferencesImpl.java:475)
    at android.app.SharedPreferencesImpl$EditorImpl.apply(SharedPreferencesImpl.java:385)
    at android.preference.Preference.tryCommit(Preference.java:1349)
    at android.preference.Preference.persistBoolean(Preference.java:1615)
    at android.preference.TwoStatePreference.setChecked(TwoStatePreference.java:83)
    at android.preference.TwoStatePreference.onClick(TwoStatePreference.java:69)
    at android.preference.Preference.performClick(Preference.java:949)
    at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:215)
    at android.widget.AdapterView.performItemClick(AdapterView.java:298)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
    at android.widget.AbsListView$1.run(AbsListView.java:3423)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

When I launch the froyo emulator all is fine (EDIT : no it is not - the receiver is not enabled BUT still there is no crash).

Is it a known issue or something ?

Manifest :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="di.k23b.hw3"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
    <application android:allowBackup="true" android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" android:theme="@style/AppTheme" >
        <activity
            android:name="di.k23b.hw3.activities.MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="di.k23b.hw3.activities.SettingsActivity"
            android:label="@string/title_activity_settings" >
        </activity>
        <receiver
            android:name="di.k23b.hw3.receivers.TriggerMonitoringBootReceiver"
            android:enabled="false" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <receiver
            android:name="di.k23b.hw3.receivers.BatteryMonitoringReceiver"
            android:enabled="false"/>
    </application>
</manifest>
</code>```

Relevant parts from the receiver (WIP !) :

```<code>private static void enable(Context context, boolean enable, String className) {
    PackageManager pacman = context.getPackageManager();
    final ComponentName componentName = new ComponentName(context, className);
    final int state = (enable) ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
            : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
    pacman.setComponentEnabledSetting(componentName, state,  // line 81
            PackageManager.DONT_KILL_APP);
}

public static void enable(Context baseContext, boolean enable) {
    enable(baseContext, enable,                 // line 86
            TriggerMonitoringBootReceiver.class.getSimpleName());
}
</code>```

And in SettingsActivity:

```<code>@Override
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
    if (MASTER_ENABLE.equals(key)) {
        TriggerMonitoringBootReceiver.enable(getBaseContext(),        // line 192
                sp.getBoolean(key, false));
        Toast.makeText(getApplicationContext(),
                "CB: " + sp.getBoolean(key, false), Toast.LENGTH_SHORT)
                .show();
    }
}
</code>```

EDIT : all clear now, using ComponentName(Context pkg, Class<?> cls)- as for the difference in the APIs:

Calls to PackageManager.setComponentEnabledSetting will now throw an IllegalArgumentException if the given component class name does not exist in the application's manifest. - from the Android documentation

答:
Just summarizing information already in this thread.

 Use the constructor
ComponentName(Context pkg, Class<?> cls).

Also, the component name needs to be specified in the manifest. See JELLYBEAN in this link.
 Calls to PackageManager.setComponentEnabledSetting will now throw an IllegalArgumentException if the given component class name does not exist in the application's manifest.

ContentLicense: CC BY-SA 4.0

Body:
My emulators :

When I launch the tablet emulator I get :

FATAL EXCEPTION: main
java.lang.IllegalArgumentException: Component class TriggerMonitoringBootReceiver does not exist in di.k23b.hw3
    at android.os.Parcel.readException(Parcel.java:1429)
    at android.os.Parcel.readException(Parcel.java:1379)
    at android.content.pm.IPackageManager$Stub$Proxy.setComponentEnabledSetting(IPackageManager.java:2561)
    at android.app.ApplicationPackageManager.setComponentEnabledSetting(ApplicationPackageManager.java:1250)
    at di.k23b.hw3.receivers.TriggerMonitoringBootReceiver.enable(TriggerMonitoringBootReceiver.java:81)
    at di.k23b.hw3.receivers.TriggerMonitoringBootReceiver.enable(TriggerMonitoringBootReceiver.java:86)
    at di.k23b.hw3.activities.SettingsActivity.onSharedPreferenceChanged(SettingsActivity.java:192)
    at android.app.SharedPreferencesImpl$EditorImpl.notifyListeners(SharedPreferencesImpl.java:475)
    at android.app.SharedPreferencesImpl$EditorImpl.apply(SharedPreferencesImpl.java:385)
    at android.preference.Preference.tryCommit(Preference.java:1349)
    at android.preference.Preference.persistBoolean(Preference.java:1615)
    at android.preference.TwoStatePreference.setChecked(TwoStatePreference.java:83)
    at android.preference.TwoStatePreference.onClick(TwoStatePreference.java:69)
    at android.preference.Preference.performClick(Preference.java:949)
    at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:215)
    at android.widget.AdapterView.performItemClick(AdapterView.java:298)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
    at android.widget.AbsListView$1.run(AbsListView.java:3423)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)

When I launch the froyo emulator all is fine (EDIT : no it is not - the receiver is not enabled BUT still there is no crash).

Is it a known issue or something ?

Manifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="di.k23b.hw3"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
    <application android:allowBackup="true" android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" android:theme="@style/AppTheme" >
        <activity
            android:name="di.k23b.hw3.activities.MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="di.k23b.hw3.activities.SettingsActivity"
            android:label="@string/title_activity_settings" >
        </activity>
        <receiver
            android:name="di.k23b.hw3.receivers.TriggerMonitoringBootReceiver"
            android:enabled="false" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <receiver
            android:name="di.k23b.hw3.receivers.BatteryMonitoringReceiver"
            android:enabled="false"/>
    </application>
</manifest>

Relevant parts from the receiver (WIP !) :

private static void enable(Context context, boolean enable, String className) {
    PackageManager pacman = context.getPackageManager();
    final ComponentName componentName = new ComponentName(context, className);
    final int state = (enable) ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
            : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
    pacman.setComponentEnabledSetting(componentName, state,  // line 81
            PackageManager.DONT_KILL_APP);
}

public static void enable(Context baseContext, boolean enable) {
    enable(baseContext, enable,                 // line 86
            TriggerMonitoringBootReceiver.class.getSimpleName());
}

And in SettingsActivity:

@Override
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
    if (MASTER_ENABLE.equals(key)) {
        TriggerMonitoringBootReceiver.enable(getBaseContext(),        // line 192
                sp.getBoolean(key, false));
        Toast.makeText(getApplicationContext(),
                "CB: " + sp.getBoolean(key, false), Toast.LENGTH_SHORT)
                .show();
    }
}

EDIT : all clear now, using ComponentName(Context pkg, Class<?> cls)- as for the difference in the APIs:

Calls to PackageManager.setComponentEnabledSetting will now throw an IllegalArgumentException if the given component class name does not exist in the application's manifest. - from the Android documentation


问:
How can I generate skeletal points of unfilled space?
Given an array of points coordinates, I would like to generate n new coordinates that best "define" the unfilled space.

The first part of my approach involves using K-Means clustering to generate k points that reasonably represent all of the points. I then thought to use these points to generate the skeletal points for the unfilled space.

An example is shown below. The initial points are shown as small dots, the K-Means cluster centers are shown as large dots (k = 5), and my human estimate of where the skeletal points should be placed are shown by yellow squares, where n = 4.

What would be the best approach for generating these skeletal points for the unfilled space? (It seems almost like I need an "inverse clustering" algorithm.) Feel free to provide a solution that does not use the K-Means clustering shown; that was just my attempt at simplifying the problem.

```<code># Dataset used:
X = np.array([
    [0.0, 0.0], [0.1, 0.0], [0.2, 0.0], [0.2, 0.1], [0.3, 0.1], [0.4, 0.1],
    [0.4, 0.2], [0.5, 0.2], [0.5, 0.3], [0.6, 0.3], [0.7, 0.3], [0.8, 0.3],
    [0.9, 0.3], [0.9, 0.4], [0.9, 0.5], [0.9, 0.5], [0.9, 0.6], [0.9, 0.7],
    [0.9, 0.7], [0.9, 0.8], [0.8, 0.8], [0.8, 0.9], [0.7, 0.9], [0.6, 0.9],
    [0.5, 0.9], [0.4, 0.9], [0.4, 0.8], [0.3, 0.8], [0.3, 0.7], [0.2, 0.7],
    [0.2, 0.6], [0.2, 0.5], [0.2, 0.4]
])
</code>```

答:
Here is one attempt at translating what you have asked for:

1) Fill the area in question with a grid of regularly spaced points.

2) Remove from this regular grid the points which are near your initial points.

3) Use k-means clustering to cluster the remaining grid points.

If you have P initial points and intend to create k clusters I would remove roughly P * 100 / (P + k) % of the grid points. There should be some clever way to get the accuracy of using a very fine grid without actually processing all the grid points one by one, e.g. by recursively splitting the space up into chunks, but a simple grid might allow you to test out this idea quickly and see what it looks like.

Body:
Given an array of points coordinates, I would like to generate n new coordinates that best "define" the unfilled space.

The first part of my approach involves using K-Means clustering to generate k points that reasonably represent all of the points. I then thought to use these points to generate the skeletal points for the unfilled space.

An example is shown below. The initial points are shown as small dots, the K-Means cluster centers are shown as large dots (k = 5), and my human estimate of where the skeletal points should be placed are shown by yellow squares, where n = 4.

What would be the best approach for generating these skeletal points for the unfilled space? (It seems almost like I need an "inverse clustering" algorithm.) Feel free to provide a solution that does not use the K-Means clustering shown; that was just my attempt at simplifying the problem.

# Dataset used:
X = np.array([
    [0.0, 0.0], [0.1, 0.0], [0.2, 0.0], [0.2, 0.1], [0.3, 0.1], [0.4, 0.1],
    [0.4, 0.2], [0.5, 0.2], [0.5, 0.3], [0.6, 0.3], [0.7, 0.3], [0.8, 0.3],
    [0.9, 0.3], [0.9, 0.4], [0.9, 0.5], [0.9, 0.5], [0.9, 0.6], [0.9, 0.7],
    [0.9, 0.7], [0.9, 0.8], [0.8, 0.8], [0.8, 0.9], [0.7, 0.9], [0.6, 0.9],
    [0.5, 0.9], [0.4, 0.9], [0.4, 0.8], [0.3, 0.8], [0.3, 0.7], [0.2, 0.7],
    [0.2, 0.6], [0.2, 0.5], [0.2, 0.4]
])


问:
Inconsistency between $ and ^ in regex when using start/end arguments to re.search?
From what I've read, ^ should match the start of a string, and $ the end. However, with re.search(), it looks like the behavior of ^ continues to work fine, while $ 'breaks'. Example:

```<code>>>> a = re.compile( "^a" )
>>> print a.search( "cat", 1, 3 )
None
</code>```

This seems correct to me -- 'a' is not at the start of the string, even if it is at the start of the search.

```<code>>>> a = re.compile( "a$" )
>>> print a.search( "cat", 0, 2 )
<_sre.SRE_Match object at 0x7f41df2334a8>
</code>```

This seems wrong to me, or inconsistent at least.

The documentation on the re module explicitly mentions that the behavior of ^ does not change due to start/end arguments to re.search, but no change in behavior is mentioned for $ (that I've seen).

Can anyone explain why things were designed this way, and/or suggest a convenient workaround?

By workaround, I would like to compose a regex which always matches the end of the string, even when someone uses the end argument to re.search.

And why was re.search designed such that:

```<code>s.search( string, endPos=len(string) - 1 )
</code>```

is the same as

```<code>s.search( string[:-1] )
</code>```

when

```<code>s.search( string, startPos=1 )
</code>```

is explicitly and intentionally not the same as

```<code>s.search( string[1:] )
</code>```

It seems to be less an issue of inconsistency between ^ and $, and more of an inconsistency within the re.search function.

答:
Short Answer

Use \A to and \Z to match the literal beginning or end of a string.
The relevant lines from the re module's docs:

6.2.1. Regular Expression Syntax

\A
  Matches only at the start of the string.

\Z
  Matches only at the end of the string.

Caveat about endpos

This won't work "even when someone uses the end argument to re.search".
Unlike the "start" parameter pos, which just marks a starting point, the endpos parameter means the search (or match) will be conducted on only a portion of the string (emphasis added):

6.2.3. Regular Expression Objects

regex.search(string[, pos[, endpos]])

The optional parameter endpos limits how far the string will be searched;
  it will be as if the string is endpos characters long,
  [...]
  rx.search(string, 0, 50) is equivalent to rx.search(string[:50], 0).

The \Z matches the end of the string being searched, which is exactly what endpos changes.

Background

The more-familiar ^ and $ don't do what you think they do:

^
  (Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.

$
  Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline.
  foo matches both 'foo' and 'foobar', while the regular expression foo$ matches only 'foo'.
  More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches 'foo2' normally, but 'foo1' in MULTILINE mode;
  searching for a single $ in 'foo\n' will find two (empty) matches:
  one just before the newline, and one at the end of the string.

Python's regular expressions are heavily influenced by Perl's, which extended the old grep abilities with a host of its own.
That included multi-line matching, which raised a question about metacharacters like ^:
Was it matching the beginning of the string, or the beginning of the line?
When grep was only matching one line at a time, those were equivalent concepts.

As you can see, ^ and $ ended up trying to match everything "start-like" and "end-ish".
Perl introduced the new escape sequences \A and \z (lower-case) to match only the start-of-string and end-of-string.

Those escape sequences were adopted by Python, but with one difference:
Python did not adopt Perl's \Z (upper-case), which matched both end-of-string and the special case newline-before-end-of-string...
making it not quite the partner to \A that one would expect.

(I assume Python upper-cased Perl's \z for consistency, avoiding the lopsided '\Apattern\z' regexes that were recommended in books like Perl Best Practices.)

History of pos and endpos

It appears that the strange "not actually the start-start position" meaning of pos is as old as the parameter itself:

The Python 1.4 match function docs (25 Oct 1996 --- probably pre-dating the regex object) don't show the pos or endpos parameters at all.

The Python 1.5 match method docs (17 Feb 1998) introduce both the regular expression object and the pos and endpos parameters.
It states that a ^ will match at pos, although later revisions suggest this was a typo.
(Speaking of typos:
The ^ character itself is missing.
It came and went, until finally reappearing for good(?) in Python 2.1.)

The Python 1.5.1 match method docs (14 Apr 1998) insert the missing "not", reversing the previous docs.

The Python 1.5.1p1 match method docs (06 Aug 1998) clarify the unexpected effects of pos.
They match Python 3.6.1's description of pos word-for-word...
give or take that pesky ^ typo.

I suspect the numerous changes to the docs over a couple months of bug-fix releases reflect the docs catching up with reality --- not changes to the design of match
(although I don't have Python 1 lying around to verify that).

The python-dev mailing list archives only go back to 1999, so unless the earlier messages were saved somewhere else, I think answering the "why" question would require guessing who wrote that code, and asking them.

Body:
From what I've read, ^ should match the start of a string, and $ the end. However, with re.search(), it looks like the behavior of ^ continues to work fine, while $ 'breaks'. Example:

>>> a = re.compile( "^a" )
>>> print a.search( "cat", 1, 3 )
None

This seems correct to me -- 'a' is not at the start of the string, even if it is at the start of the search.

>>> a = re.compile( "a$" )
>>> print a.search( "cat", 0, 2 )
<_sre.SRE_Match object at 0x7f41df2334a8>

This seems wrong to me, or inconsistent at least.

The documentation on the re module explicitly mentions that the behavior of ^ does not change due to start/end arguments to re.search, but no change in behavior is mentioned for $ (that I've seen).

Can anyone explain why things were designed this way, and/or suggest a convenient workaround?

By workaround, I would like to compose a regex which always matches the end of the string, even when someone uses the end argument to re.search.

And why was re.search designed such that:

s.search( string, endPos=len(string) - 1 )

is the same as

s.search( string[:-1] )

when

s.search( string, startPos=1 )

is explicitly and intentionally not the same as

s.search( string[1:] )

It seems to be less an issue of inconsistency between ^ and $, and more of an inconsistency within the re.search function.


问:
angularjs date format validation on input type date
I'm trying to create date using AngularJS and as per the documentation

Input with date validation and transformation. In browsers that do not
  yet support the HTML5 date input, a text element will be used. In that
  case, text must be entered in a valid ISO-8601 date format
  (yyyy-MM-dd), for example: 2009-01-06. Since many modern browsers do
  not yet support this input type, it is important to provide cues to
  users on the expected input format via a placeholder or label.

it only accepts valid ISO-8601 date format (yyyy-MM-dd).

I've tried to define the new date format in the pattern's attribute as shown in the following code:

```<code><div ng-app="">
  <form name="frmSPA" novalidate>
    <input type="date" placeholder="Enter SPA Date" pattern="dd/MM/yyyy" name="SPADate" ng-model="SPADate" ng-required="true" />
    <span ng-show="frmSPA.SPADate.$touched && frmSPA.SPADate.$error.required">SPA Date is required</span>
    <span ng-show="frmSPA.SPADate.$touched && frmSPA.SPADate.$error.date">Not a valid date</span>
  </form>
</div>
</code>```

but it doesn't work.

So how to change the default date format into dd/MM/yyyy. Here is the jsfiddle.

Body:
I'm trying to create date using AngularJS and as per the documentation

Input with date validation and transformation. In browsers that do not
  yet support the HTML5 date input, a text element will be used. In that
  case, text must be entered in a valid ISO-8601 date format
  (yyyy-MM-dd), for example: 2009-01-06. Since many modern browsers do
  not yet support this input type, it is important to provide cues to
  users on the expected input format via a placeholder or label.

it only accepts valid ISO-8601 date format (yyyy-MM-dd).

I've tried to define the new date format in the pattern's attribute as shown in the following code:

  <form name="frmSPA" novalidate>
    <input type="date" placeholder="Enter SPA Date" pattern="dd/MM/yyyy" name="SPADate" ng-model="SPADate" ng-required="true" />
    SPA Date is required
    Not a valid date
  </form>

but it doesn't work.

So how to change the default date format into dd/MM/yyyy. Here is the jsfiddle.

Body:
Use this ng-pattern also working for leap year. Work for 'MM-dd-YYYY' format.

ng-pattern='/^(((0[13578]|1[02])-(0[1-9]|[12]\d|3[01])-((19|[2-9]\d)\d{2}))|((0[13456789]|1[012])-(0[1-9]|[12]\d|30)-((19|[2-9]\d)\d{2}))|(02-(0[1-9]|1\d|2[0-8])-((19|[2-9]\d)\d{2}))|(02-29-((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/'