问:
update() firestore CRUD modal
maybe someone can help me with a CRUD that I am creating with modal dialogues. I have already managed to add, delete, but I need to edit. Having said that, I have already managed to capture the data of each record in its respective modality but I can not save the changes, I get the following error: Error: Function DocumentReference.update() called with invalid data. Unsupported field value: undefined (found in field titulo). I'm working with Firestore.

que-hacemos-admin.component.ts

import { Component, OnInit, Inject } from '@angular/core';

//Firestore
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

//Modal Material Design
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

import { AgregarComponent } from '../agregar/agregar.component';
import { EditarComponent } from '../editar/editar.component';
import { EliminarComponent } from '../eliminar/eliminar.component';
import { Title } from '@angular/platform-browser/src/browser/title';

export interface Servicios { titulo?: string; descripcion?: string };
export interface ServiciosId extends Servicios { id: string; };

@Component({
 selector: 'app-que-hacemos-admin',
 templateUrl: './que-hacemos-admin.component.html',
 styleUrls: ['./que-hacemos-admin.component.scss']
})
export class QueHacemosAdminComponent implements OnInit {

 titulo: string;
 descripcion: string;

 servicio: Servicios;
 serviciosCollection: AngularFirestoreCollection<Servicios>;
 serviciosObservable: Observable<Servicios[]>;
 // dialogRef: MatDialogRef<EditarComponent>;

 DocPredicate: any;

 constructor(private afs: AngularFirestore, public dialog: MatDialog) { }

 ngOnInit() {
  this.getQueHacemos();
 }

 getQueHacemos() {
  this.serviciosCollection = this.afs.collection('servicios', ref => ref.orderBy('titulo'));

  this.serviciosObservable = this.serviciosCollection.snapshotChanges().map(arr => {
   return arr.map(snap => {
    const data = snap.payload.doc.data() as Servicios;
    const id = snap.payload.doc.id;
    return { id, ...data };
   });
  });
 };

 agregarModal() {
  let dialogRef = this.dialog.open(AgregarComponent, {
   width: '550px'
  } );

 };

 editarModal(servicio) {
  let dialogRef = this.dialog.open(EditarComponent, {
   width: '550px',
   data: {
    titulo: servicio ? servicio.titulo :'',
    descripcion: servicio ? servicio.descripcion : '',
   }
  } );

  dialogRef.afterClosed().subscribe(result => {
   if (result) {
    this.serviciosCollection.doc(servicio.id).update({
     titulo: this.titulo,
     descripcion: this.descripcion,
    });
   }
  })
 };

 eliminarModal(servicio) {
  let dialogRef = this.dialog.open(EliminarComponent, {
  } );

  dialogRef.afterClosed().subscribe(estado => {
   if (estado) {
    this.serviciosCollection.doc(servicio.id).delete();
   }
  })
 };

}```
</div>
</div>
</p>

<p><strong>que-hacemos-admin.component.html</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="my-5 d-flex justify-content-between">
 <div><h2>¿Qué hacemos? - Admin</h2></div>
 <div><button class="btn btn-primary" (click)="agregarModal()">Agregar servicio</button></div>
</div>

<table class="table mb-5">
 <thead>
  <tr>
   <th scope="col">Servicio</th>
   <th scope="col">Descripción</th>
   <th scope="col"></th>
   <th scope="col"></th>
   <th scope="col"></th>
  </tr>
 </thead>
 <tbody>
  <tr *ngFor="let servicio of serviciosObservable | async">
   <td class="text-primary">{{ servicio.titulo }}</td>
   <td>{{ servicio.descripcion }}</td>
   <td><button class="btn btn-outline-secondary btn-sm" (click)="editarModal(servicio)">Editar</button></td>
   <td><button class="btn btn-outline-danger btn-sm" (click)="eliminarModal(servicio)">Eliminar</button></td>
  </tr>
 </tbody>
</table></code>```

editar.component.ts

import { Component, OnInit, Inject } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

//Firestore
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

//Modal Material Design
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

export interface Servicios { titulo: string; descripcion: string }
export interface ServiciosId extends Servicios { id: string; }

@Component({
 selector: 'app-editar',
 templateUrl: './editar.component.html',
 styleUrls: ['./editar.component.scss']
})
export class EditarComponent implements OnInit {

 titulo: string;
 descripcion: string;

 form: FormGroup;

 servicio: string;
 serviciosCollection: AngularFirestoreCollection<Servicios>;
 serviciosObservable: Observable<Servicios[]>;

 constructor(
  private afs: AngularFirestore,
  public dialog: MatDialog,
  public dialogRef: MatDialogRef<EditarComponent>,
  @Inject(MAT_DIALOG_DATA) public data,
  private formBuilder: FormBuilder
 ) { }

 ngOnInit() {
  this.getQueHacemos();

  this.form = this.formBuilder.group({
   titulo: this.data ? this.data.titulo : '',
   descripcion: this.data ? this.data.descripcion : ''
  })
 }

 getQueHacemos() {
  this.serviciosCollection = this.afs.collection('servicios', ref => ref.orderBy('titulo'));
  this.serviciosObservable = this.serviciosCollection.snapshotChanges().map(arr => {
   return arr.map(snap => {
    const data = snap.payload.doc.data() as Servicios;
    const id = snap.payload.doc.id;
    return { id, ...data };
   });
  });
 }

 editar() {
  this.dialogRef.close(true)
 }

 cancelar(){
  this.dialogRef.close(false)
 }

}```
</div>
</div>
</p>

<p><strong>editar.component.html</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="" [formGroup]="form">
 <div class="m-2">
   <div class="text-center">
    <h4 class="mb-4">Editar Servicio</h4>
   </div>
   <div class="form-group">
    <label>Título del servicio</label>
    <input type="text" class="form-control" placeholder="Título servicio" formControlName="titulo">
   </div>
   <div class="form-group">
    <label>Descripción del servicio</label>
    <textarea class="form-control" rows="8" placeholder="Descripción" formControlName="descripcion"></textarea>
   </div>
   <div class="text-right mt-3">
    <button class="btn btn-light" (click)="cancelar()">Cancelar</button>
    <button type="submit" class="btn btn-primary" (click)="editar()">Guardar cambios</button>
   </div>
  </div>
</form></code>```

答:
The value of this.titulo in que-hacemos-admin.component.ts when calling the service is undefined as you never set the value of this variable. Firestore doesn't accept undefined values. Null will be ok.

First your should return the dialog values in editar.component.ts and not just true.

```<code>editar() {
  this.dialogRef.close(this.form.value)
}
</code>```

Than you have to use these values in que-hacemos-admin.component.ts when handling the dialog result. The variable result contains the values returned above in the dialog.

```<code>dialogRef.afterClosed().subscribe(result => {
  if (result) {
    this.serviciosCollection.doc(servicio.id).update({
      titulo: result.titulo,
      descripcion: result.descripcion,
    });
  }
})
</code>```

Title: update() firestore CRUD modal

Body:
maybe someone can help me with a CRUD that I am creating with modal dialogues. I have already managed to add, delete, but I need to edit. Having said that, I have already managed to capture the data of each record in its respective modality but I can not save the changes, I get the following error: Error: Function DocumentReference.update() called with invalid data. Unsupported field value: undefined (found in field titulo). I'm working with Firestore.

que-hacemos-admin.component.ts

import { Component, OnInit, Inject } from '@angular/core';

//Firestore
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

//Modal Material Design
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

import { AgregarComponent } from '../agregar/agregar.component';
import { EditarComponent } from '../editar/editar.component';
import { EliminarComponent } from '../eliminar/eliminar.component';
import { Title } from '@angular/platform-browser/src/browser/title';

export interface Servicios { titulo?: string; descripcion?: string };
export interface ServiciosId extends Servicios { id: string; };

@Component({
 selector: 'app-que-hacemos-admin',
 templateUrl: './que-hacemos-admin.component.html',
 styleUrls: ['./que-hacemos-admin.component.scss']
})
export class QueHacemosAdminComponent implements OnInit {

 titulo: string;
 descripcion: string;

 servicio: Servicios;
 serviciosCollection: AngularFirestoreCollection<Servicios>;
 serviciosObservable: Observable<Servicios[]>;
 // dialogRef: MatDialogRef<EditarComponent>;

 DocPredicate: any;

 constructor(private afs: AngularFirestore, public dialog: MatDialog) { }

 ngOnInit() {
  this.getQueHacemos();
 }

 getQueHacemos() {
  this.serviciosCollection = this.afs.collection('servicios', ref => ref.orderBy('titulo'));

  this.serviciosObservable = this.serviciosCollection.snapshotChanges().map(arr => {
   return arr.map(snap => {
    const data = snap.payload.doc.data() as Servicios;
    const id = snap.payload.doc.id;
    return { id, ...data };
   });
  });
 };

 agregarModal() {
  let dialogRef = this.dialog.open(AgregarComponent, {
   width: '550px'
  } );

 };

 editarModal(servicio) {
  let dialogRef = this.dialog.open(EditarComponent, {
   width: '550px',
   data: {
    titulo: servicio ? servicio.titulo :'',
    descripcion: servicio ? servicio.descripcion : '',
   }
  } );

  dialogRef.afterClosed().subscribe(result => {
   if (result) {
    this.serviciosCollection.doc(servicio.id).update({
     titulo: this.titulo,
     descripcion: this.descripcion,
    });
   }
  })
 };

 eliminarModal(servicio) {
  let dialogRef = this.dialog.open(EliminarComponent, {
  } );

  dialogRef.afterClosed().subscribe(estado => {
   if (estado) {
    this.serviciosCollection.doc(servicio.id).delete();
   }
  })
 };

}

que-hacemos-admin.component.html

¿Qué hacemos? - Admin

<button class="btn btn-primary" (click)="agregarModal()">Agregar servicio</button>

   Servicio
   Descripción

   {{ servicio.titulo }}
   {{ servicio.descripcion }}
   <button class="btn btn-outline-secondary btn-sm" (click)="editarModal(servicio)">Editar</button>
   <button class="btn btn-outline-danger btn-sm" (click)="eliminarModal(servicio)">Eliminar</button>

editar.component.ts

import { Component, OnInit, Inject } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

//Firestore
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

//Modal Material Design
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

export interface Servicios { titulo: string; descripcion: string }
export interface ServiciosId extends Servicios { id: string; }

@Component({
 selector: 'app-editar',
 templateUrl: './editar.component.html',
 styleUrls: ['./editar.component.scss']
})
export class EditarComponent implements OnInit {

 titulo: string;
 descripcion: string;

 form: FormGroup;

 servicio: string;
 serviciosCollection: AngularFirestoreCollection<Servicios>;
 serviciosObservable: Observable<Servicios[]>;

 constructor(
  private afs: AngularFirestore,
  public dialog: MatDialog,
  public dialogRef: MatDialogRef<EditarComponent>,
  @Inject(MAT_DIALOG_DATA) public data,
  private formBuilder: FormBuilder
 ) { }

 ngOnInit() {
  this.getQueHacemos();

  this.form = this.formBuilder.group({
   titulo: this.data ? this.data.titulo : '',
   descripcion: this.data ? this.data.descripcion : ''
  })
 }

 getQueHacemos() {
  this.serviciosCollection = this.afs.collection('servicios', ref => ref.orderBy('titulo'));
  this.serviciosObservable = this.serviciosCollection.snapshotChanges().map(arr => {
   return arr.map(snap => {
    const data = snap.payload.doc.data() as Servicios;
    const id = snap.payload.doc.id;
    return { id, ...data };
   });
  });
 }

 editar() {
  this.dialogRef.close(true)
 }

 cancelar(){
  this.dialogRef.close(false)
 }

}

editar.component.html

<form action="" [formGroup]="form">

Editar Servicio

    Título del servicio
    <input type="text" class="form-control" placeholder="Título servicio" formControlName="titulo">

    Descripción del servicio
    <textarea class="form-control" rows="8" placeholder="Descripción" formControlName="descripcion"></textarea>

    <button class="btn btn-light" (click)="cancelar()">Cancelar</button>
    <button type="submit" class="btn btn-primary" (click)="editar()">Guardar cambios</button>

</form>

Body:
The value of this.titulo in que-hacemos-admin.component.ts when calling the service is undefined as you never set the value of this variable. Firestore doesn't accept undefined values. Null will be ok.

First your should return the dialog values in editar.component.ts and not just true.

editar() {
  this.dialogRef.close(this.form.value)
}

Than you have to use these values in que-hacemos-admin.component.ts when handling the dialog result. The variable result contains the values returned above in the dialog.

dialogRef.afterClosed().subscribe(result => {
  if (result) {
    this.serviciosCollection.doc(servicio.id).update({
      titulo: result.titulo,
      descripcion: result.descripcion,
    });
  }
})


来源: stackexchange

问:
Adb install failure: INSTALL_CANCELED_BY_USER
I try to install app via adb and get a error:

```<code>$ ./adb -d install /Users/dimon/Projects/one-place/myprogram/platforms/android/build/outputs/apk/android-debug.apk -r -g
3704 KB/s (4595985 bytes in 1.211s)
    pkg: /data/local/tmp/android-debug.apk
Failure [INSTALL_CANCELED_BY_USER]
</code>```

In device I do nothing in this moment.
Device is Xiaomi MI5, MIUI 7.2.13, Android 6.0. Developer mode enabled.
How to fix this?

The same error I get when try to run "ionic run android" command.

UPD

Here is logs from 'adb logcat' command getting in moment of installation program:

```<code>06-06 10:04:20.051   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.063   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.078 13397 13397 E ANDR-PERF-MPCTL: Unable to create control service (stage=2, rc=-1)
06-06 10:04:20.082   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.079 13396 13396 W iop     : type=1400 audit(0.0:527): avc: denied { write } for name="socket" dev="tmpfs" ino=14686 scontext=u:r:dumpstate:s0 tcontext=u:object_r:socket_device:s0 tclass=dir permissive=0
06-06 10:04:20.088   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.926 13400 13400 D AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 2000 <<<<<<
06-06 10:04:20.930 13400 13400 D AndroidRuntime: CheckJNI is OFF
06-06 10:04:20.966 13400 13400 D ICU     : No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
06-06 10:04:20.995 13400 13400 I Radio-JNI: register_android_hardware_Radio DONE
06-06 10:04:21.004 13400 13400 E         : WFDWhiteListing : library initialized successfully
06-06 10:04:21.020 13400 13400 D AndroidRuntime: Calling main entry com.android.commands.pm.Pm
06-06 10:04:21.027 13400 13400 I Timeline: Timeline: Activity_launch_request time:973226
06-06 10:04:21.028  1497  2996 I ActivityManager: START u0 {act=android.intent.action.VIEW dat=file:///data/local/tmp/android-debug.apk typ=application/vnd.android.package-archive flg=0x18000000 cmp=com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity (has extras)} from uid 2000 on display 0
06-06 10:04:21.033  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.033  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.033  1497  2996 E         : Service not available yet
06-06 10:04:21.034  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.037  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.037  1497  2996 E         : Service not available yet
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.050  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity}
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: notify state normal_state enter...
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: foreground_change:
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_cpu_powermode(middle)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_cpu_powermode
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_lcd_mode(ui)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_lcd_mode
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:528): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:529): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  3247  4440 I octvm_power: power mode [normal] start 1465200261
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_cpu_powermode(middle) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_power_profile -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2113 have been add to group sys_standby.
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_lcd_mode(ui) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_lcd_mode -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2900 have been add to group sys_standby.
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:530): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  2533  2887 I octvm   : task pid 4553 have been add to group sys_standby.
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.051  3247  4440 I octvm_power: onPowerModeChanged[normal] called
06-06 10:04:21.052  2875  3093 I FirstNotificationController: handleUnlockState: stoped
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_ready time:973254
06-06 10:04:21.055  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_stopped time:973255
06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:531): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:532): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.072  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.072  1497  2230 E         : Service not available yet
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.073  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.073  1497  2230 E         : Service not available yet
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.075  1497  2230 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.076  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.android.settings/com.android.settings.Settings$WifiSettingsActivity}
06-06 10:04:21.069  2887  2887 W EventReader: type=1400 audit(0.0:533): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_ready time:973275
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_stopped time:973275
06-06 10:04:21.076  2533  2887 I octvm   : task pid 2060 have been add to group sys_standby.
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.077  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.090 13400 13400 I art     : System.exit called, status: 1
06-06 10:04:21.090 13400 13400 I AndroidRuntime: VM exiting with result code 1.
06-06 10:04:21.100  2060  2130 V MI_STAT : disabled local event upload
</code>```

I see when android-debug.apk creates, but I don't understand why it's not installs. Maybe the key strings is:

```<code>06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk
</code>```

but this is not error strings, just warning and debug.
Also strange line:

```<code>06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0
</code>```

but I don't know if it is a problem.

Also I tried to install via adb some other apps, not only self-written. But no results.

答: If your switch Install by USB on and you are getting "the device is temporarily restricted" error, then apply any of the default mobile themes. If any other developer theme is applied then it will not Allow you to switch Install by USB on. This works for me.</p>

ContentLicense: CC BY-SA 3.0

Body:
I try to install app via adb and get a error:

$ ./adb -d install /Users/dimon/Projects/one-place/myprogram/platforms/android/build/outputs/apk/android-debug.apk -r -g
3704 KB/s (4595985 bytes in 1.211s)
    pkg: /data/local/tmp/android-debug.apk
Failure [INSTALL_CANCELED_BY_USER]

In device I do nothing in this moment.
Device is Xiaomi MI5, MIUI 7.2.13, Android 6.0. Developer mode enabled.
How to fix this?

The same error I get when try to run "ionic run android" command.

UPD

Here is logs from 'adb logcat' command getting in moment of installation program:

06-06 10:04:20.051   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.063   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.078 13397 13397 E ANDR-PERF-MPCTL: Unable to create control service (stage=2, rc=-1)
06-06 10:04:20.082   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.079 13396 13396 W iop     : type=1400 audit(0.0:527): avc: denied { write } for name="socket" dev="tmpfs" ino=14686 scontext=u:r:dumpstate:s0 tcontext=u:object_r:socket_device:s0 tclass=dir permissive=0
06-06 10:04:20.088   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.926 13400 13400 D AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 2000 <<<<<<
06-06 10:04:20.930 13400 13400 D AndroidRuntime: CheckJNI is OFF
06-06 10:04:20.966 13400 13400 D ICU     : No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
06-06 10:04:20.995 13400 13400 I Radio-JNI: register_android_hardware_Radio DONE
06-06 10:04:21.004 13400 13400 E         : WFDWhiteListing : library initialized successfully
06-06 10:04:21.020 13400 13400 D AndroidRuntime: Calling main entry com.android.commands.pm.Pm
06-06 10:04:21.027 13400 13400 I Timeline: Timeline: Activity_launch_request time:973226
06-06 10:04:21.028  1497  2996 I ActivityManager: START u0 {act=android.intent.action.VIEW dat=file:///data/local/tmp/android-debug.apk typ=application/vnd.android.package-archive flg=0x18000000 cmp=com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity (has extras)} from uid 2000 on display 0
06-06 10:04:21.033  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.033  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.033  1497  2996 E         : Service not available yet
06-06 10:04:21.034  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.037  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.037  1497  2996 E         : Service not available yet
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.050  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity}
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: notify state normal_state enter...
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: foreground_change:
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_cpu_powermode(middle)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_cpu_powermode
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_lcd_mode(ui)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_lcd_mode
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:528): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:529): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  3247  4440 I octvm_power: power mode [normal] start 1465200261
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_cpu_powermode(middle) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_power_profile -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2113 have been add to group sys_standby.
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_lcd_mode(ui) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_lcd_mode -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2900 have been add to group sys_standby.
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:530): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  2533  2887 I octvm   : task pid 4553 have been add to group sys_standby.
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.051  3247  4440 I octvm_power: onPowerModeChanged[normal] called
06-06 10:04:21.052  2875  3093 I FirstNotificationController: handleUnlockState: stoped
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_ready time:973254
06-06 10:04:21.055  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_stopped time:973255
06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:531): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:532): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.072  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.072  1497  2230 E         : Service not available yet
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.073  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.073  1497  2230 E         : Service not available yet
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.075  1497  2230 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.076  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.android.settings/com.android.settings.Settings$WifiSettingsActivity}
06-06 10:04:21.069  2887  2887 W EventReader: type=1400 audit(0.0:533): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_ready time:973275
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_stopped time:973275
06-06 10:04:21.076  2533  2887 I octvm   : task pid 2060 have been add to group sys_standby.
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.077  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.090 13400 13400 I art     : System.exit called, status: 1
06-06 10:04:21.090 13400 13400 I AndroidRuntime: VM exiting with result code 1.
06-06 10:04:21.100  2060  2130 V MI_STAT : disabled local event upload

I see when android-debug.apk creates, but I don't understand why it's not installs. Maybe the key strings is:

06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk

but this is not error strings, just warning and debug.
Also strange line:

06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0

but I don't know if it is a problem.

Also I tried to install via adb some other apps, not only self-written. But no results.


问:
Missing notification styles in Android 8.0
After I migrated my project to Android 8.0 (API 26), I receive this error:

```<code>error: resource style/TextAppearance.AppCompat.Notification (aka com.xxx.yyy:style/TextAppearance.AppCompat.Notification) not found.
</code>```

XML code:

```<code><TextView
    android:id="@+id/notification_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/notification_gap_text"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="@string/placeholder_text"
    android:textAppearance="@style/TextAppearance.AppCompat.Notification" />
</code>```

What should I do? Are there any new/substitute resources? My app's minSdkVersion is set to 15. I can't use material resources which need minimum API 21.

答:
Seems like the style was removed, but I extracted it from the appcompat:25.1.1 and is defined as follow:

```<code><style name="TextAppearance.AppCompat.Notification">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?android:attr/textColorSecondary</item>
</style>
</code>```

You can define this style in your styles.xml

Body:
After I migrated my project to Android 8.0 (API 26), I receive this error:

error: resource style/TextAppearance.AppCompat.Notification (aka com.xxx.yyy:style/TextAppearance.AppCompat.Notification) not found.

XML code:

<TextView
    android:id="@+id/notification_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/notification_gap_text"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="@string/placeholder_text"
    android:textAppearance="@style/TextAppearance.AppCompat.Notification" />

What should I do? Are there any new/substitute resources? My app's minSdkVersion is set to 15. I can't use material resources which need minimum API 21.

Body:
Seems like the style was removed, but I extracted it from the appcompat:25.1.1 and is defined as follow:

<style name="TextAppearance.AppCompat.Notification">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?android:attr/textColorSecondary</item>
</style>

You can define this style in your styles.xml


问:
How can i join two tables after filtering
How can i join two tables after filtering each table with some condition and on getting the result of filter, join both the results.

Tried code but showing syntax error

```<code>SELECT *
FROM Table1
WHERE flag1 = 0
JOIN SELECT *
     FROM TABLE2
     where flag2 = 0 on Table1.email = TABLE2.email
</code>```

答:
Unless I'm missing something, this ought to be pretty straightforward. Pseudo-code, but you can solve this a few ways...

```<code>SELECT
   *
FROM
   Table1
   JOIN TABLE2 ON Table1.orderlist_email = TABLE2.email
   Table1.flag1 = 0
   AND TABLE2.flag2 = 0
</code>```

Alternatively, you can add the WHERE conditions to the JOIN like so:

```<code>SELECT
   *
FROM
   Table1
   JOIN TABLE2 ON Table1.orderlist_email = TABLE2.email
   AND Table1.flag1 = 0
   AND TABLE2.flag2 = 0
</code>```

I think your concern is whether or not this means the engine will still perform a full scan of both tables, rather than sticking with a "pre-filtered" set it will attempt to join. Modern engines should be clever enough to figure this stuff out, but based on the complexity of your query, your mileage might vary.

Body:
How can i join two tables after filtering each table with some condition and on getting the result of filter, join both the results.

Tried code but showing syntax error

SELECT *
FROM Table1
WHERE flag1 = 0
JOIN SELECT *
     FROM TABLE2
     where flag2 = 0 on Table1.email = TABLE2.email

Body:
Unless I'm missing something, this ought to be pretty straightforward. Pseudo-code, but you can solve this a few ways...

SELECT
   *
FROM
   Table1
   JOIN TABLE2 ON Table1.orderlist_email = TABLE2.email
   Table1.flag1 = 0
   AND TABLE2.flag2 = 0

Alternatively, you can add the WHERE conditions to the JOIN like so:

SELECT
   *
FROM
   Table1
   JOIN TABLE2 ON Table1.orderlist_email = TABLE2.email
   AND Table1.flag1 = 0
   AND TABLE2.flag2 = 0

I think your concern is whether or not this means the engine will still perform a full scan of both tables, rather than sticking with a "pre-filtered" set it will attempt to join. Modern engines should be clever enough to figure this stuff out, but based on the complexity of your query, your mileage might vary.


问:
preg match everything except a letter
Is there a shorthand for the opposite of this? \p{L}

I want to match everything except a letter.. a-zA-ZæøåÆØÅ ...

You could of course do this [^\p{L}] but is there a shorter way of doing it?

答:
You can use property \P{L} to may any unicode non-letter.

\P{L} matches any characters that \pL does not

RegEx Demo

Title: preg match everything except a letter


问:
Handling File Upload Exception - Laravel
This is how i upload a file into my database but i am not able to handle my exception when the file uploaded is an invalid format or type.

I am able to handle exception when no file is uploaded but not when the file type is invalid or does not meet the standard.

How do i get this done please?

Controller

```<code> public function import($id, Request $request)
    {

       $country= Country::all()->where('id',$id)->first();

           if($request->file('imported-file'))
           {
                     $path = $request->file('imported-file')->getRealPath();
                     $data = Excel::load($path, function($reader)
               {
                     })->get();

               if(!empty($data) && $data->count())
               {
                 foreach ($data->toArray() as $row)
                 {
                   if(!empty($row))
                   {
                     $dataArray[] =
                     [
                       'name' => $row['name'],

                     ];
                   }
    else {
            return redirect('admin')->with('error','File format Error');

         }
               }

               if(!empty($dataArray))
               {
                $country->teams()->createMany($dataArray);
                 return redirect('admin')->with('status','Countries successfully added');

                }
              }
            }
else {
            return redirect('admin')->with('error','No file was uploaded');

         }

        }
</code>```

答:
Okay i solved this in a very simple way by checking out the laravel documentation. So here is what i just added </p>

```<code>if(($request->file('imported-file')->getClientOriginalExtension() != 'xls, xlm, xla ,xlc, xlt, xlw'))
        {

        }
else {

   //process the file

}
</code>```

Body:
This is how i upload a file into my database but i am not able to handle my exception when the file uploaded is an invalid format or type.

I am able to handle exception when no file is uploaded but not when the file type is invalid or does not meet the standard.

How do i get this done please?

Controller

 public function import($id, Request $request)
    {

       $country= Country::all()->where('id',$id)->first();

           if($request->file('imported-file'))
           {
                     $path = $request->file('imported-file')->getRealPath();
                     $data = Excel::load($path, function($reader)
               {
                     })->get();

               if(!empty($data) && $data->count())
               {
                 foreach ($data->toArray() as $row)
                 {
                   if(!empty($row))
                   {
                     $dataArray[] =
                     [
                       'name' => $row['name'],

                     ];
                   }
    else {
            return redirect('admin')->with('error','File format Error');

         }
               }

               if(!empty($dataArray))
               {
                $country->teams()->createMany($dataArray);
                 return redirect('admin')->with('status','Countries successfully added');

                }
              }
            }
else {
            return redirect('admin')->with('error','No file was uploaded');

         }

        }

Body:
Okay i solved this in a very simple way by checking out the laravel documentation. So here is what i just added

if(($request->file('imported-file')->getClientOriginalExtension() != 'xls, xlm, xla ,xlc, xlt, xlw'))
        {

        }
else {

   //process the file

}


问:
Fill a drawed circle with the midpoint algorithm in c-> infinite-loop?

I am trying to draw a filled circle with the midpoint algorithm. I already managed to draw an unfilled circle with y0 = 320; x0 = 240; radius = 180 -with the following code (reference: https://en.wikipedia.org/wiki/Midpoint_circle_algorithm):

```<code>int x0, int y0, int radius;

x0 = 320;     //assign values
y0 = 240;
radius = 180;

int x = radius-1;
int y = 0;
int dx = 1;
int dy = 1;
int err = dx - (radius << 1);

while (x >= y)
{
    putpixel(x0 + x, y0 + y);
    putpixel(x0 + y, y0 + x);
    putpixel(x0 - y, y0 + x);
    putpixel(x0 - x, y0 + y);
    putpixel(x0 - x, y0 - y);
    putpixel(x0 - y, y0 - x);
    putpixel(x0 + y, y0 - x);
    putpixel(x0 + x, y0 - y);

    if (err <= 0)
    {
        y++;
        err += dy;
        dy += 2;
    }
    if (err > 0)
    {
        x--;
        dx += 2;
        err += dx - (radius << 1);
    }
}
</code>```

This delivers the following output (saved in a bitmap):

Now I want, that this unfilled yellow circle will be filled, so it looks like this:

I thought I can accommplish this with setting the radius everytime to radius-- so it draws the same circle with a -1 radius - and that until radius=0. So basically it draws everytime a new circle filled up with the old circle until there is now circle to draw anymore (radius=0). My code for this is:

int x0, int y0, int radius;

```<code>x0 = 320;     //assign values
y0 = 240;
radius = 180;

int x = radius-1;
int y = 0;
int dx = 1;
int dy = 1;
int err = dx - (radius << 1);

while(radius!=0) {
    while (x >= y)
    {
        putpixel(x0 + x, y0 + y);
        putpixel(x0 + y, y0 + x);
        putpixel(x0 - y, y0 + x);
        putpixel(x0 - x, y0 + y);
        putpixel(x0 - x, y0 - y);
        putpixel(x0 - y, y0 - x);
        putpixel(x0 + y, y0 - x);
        putpixel(x0 + x, y0 - y);

        if (err <= 0)
        {
            y++;
            err += dy;
            dy += 2;
        }
        if (err > 0)
        {
            x--;
            dx += 2;
            err += dx - (radius << 1);
        }
    }

    x0 = x0 - 1;     //getting the next circle until radius = 0
    y0 = y0 -1;
    radius = radius - 1;

    x = radius-1;
    y = 0;
    dx = 1;
    dy = 1;
    err = dx - (radius << 1);

}
</code>```

This should be the code to my idea how I could fill up, but all i get is an infinite-loop.. Has anyone an idea why? Or has anyone another way to fill up the circle using the midpoint algorithm?

Greetings

答:
I'm pretty sure doing it your way won't generate a very nice circle; rounding errors and such might very well end up giving you "holes" in the circle, i.e. un-filled pixels.

A much better approach is to realize that the circle can be viewed as a bunch of horizontal lines of varying lengths. Thus, all you need to do is to iterate the y component from -r to r, and for each such y compute the corresponding x using your existing code. Then draw a horizontal line from (-x, y) to (x, y).

Body:
I am trying to draw a filled circle with the midpoint algorithm. I already managed to draw an unfilled circle with y0 = 320; x0 = 240; radius = 180 -with the following code (reference: https://en.wikipedia.org/wiki/Midpoint_circle_algorithm):

int x0, int y0, int radius;

x0 = 320;     //assign values
y0 = 240;
radius = 180;

int x = radius-1;
int y = 0;
int dx = 1;
int dy = 1;
int err = dx - (radius << 1);

while (x >= y)
{
    putpixel(x0 + x, y0 + y);
    putpixel(x0 + y, y0 + x);
    putpixel(x0 - y, y0 + x);
    putpixel(x0 - x, y0 + y);
    putpixel(x0 - x, y0 - y);
    putpixel(x0 - y, y0 - x);
    putpixel(x0 + y, y0 - x);
    putpixel(x0 + x, y0 - y);

    if (err <= 0)
    {
        y++;
        err += dy;
        dy += 2;
    }
    if (err > 0)
    {
        x--;
        dx += 2;
        err += dx - (radius << 1);
    }
}

This delivers the following output (saved in a bitmap):

Now I want, that this unfilled yellow circle will be filled, so it looks like this:

I thought I can accommplish this with setting the radius everytime to radius-- so it draws the same circle with a -1 radius - and that until radius=0. So basically it draws everytime a new circle filled up with the old circle until there is now circle to draw anymore (radius=0). My code for this is:

int x0, int y0, int radius;

x0 = 320;     //assign values
y0 = 240;
radius = 180;

int x = radius-1;
int y = 0;
int dx = 1;
int dy = 1;
int err = dx - (radius << 1);

while(radius!=0) {
    while (x >= y)
    {
        putpixel(x0 + x, y0 + y);
        putpixel(x0 + y, y0 + x);
        putpixel(x0 - y, y0 + x);
        putpixel(x0 - x, y0 + y);
        putpixel(x0 - x, y0 - y);
        putpixel(x0 - y, y0 - x);
        putpixel(x0 + y, y0 - x);
        putpixel(x0 + x, y0 - y);

        if (err <= 0)
        {
            y++;
            err += dy;
            dy += 2;
        }
        if (err > 0)
        {
            x--;
            dx += 2;
            err += dx - (radius << 1);
        }
    }

    x0 = x0 - 1;     //getting the next circle until radius = 0
    y0 = y0 -1;
    radius = radius - 1;

    x = radius-1;
    y = 0;
    dx = 1;
    dy = 1;
    err = dx - (radius << 1);

}

This should be the code to my idea how I could fill up, but all i get is an infinite-loop.. Has anyone an idea why? Or has anyone another way to fill up the circle using the midpoint algorithm?

Greetings


问:
Is there way to GC object in Flex even if there are objects binded to it?
I'm wondering how to garbage collect a variable in Flex even if there are other objects binded to it.</p>

答:
If you use a "weak reference" when binding, the object will be eligible for garbage collection.

Read more:
http://ted.onflash.org/2008/09/useweakreferencesboolean-false.php

ContentLicense: CC BY-SA 2.5


问:
Update cell background in Xamarin Form iOS
Does anyone encounter annoyed issue when update background color of cell in xamarin form?
I have notification list, when user clicks on item, it's marked as read then background color will be updated.
It works perfectly on android but iOS.
Most of the time the color is changed back to origin.
In the example, cell background is blue if notification is read.
When user clicks on cell, cell background should be red, but it's not changed most of time.

Notification Model

```<code> public class Notification : ObservableObject
{
    private string _message;
    private bool _isRead;

    public string Message
    {
        get => _message;
        set => SetProperty(ref _message, value);
    }

    public bool IsRead
    {
        get => _isRead;
        set => SetProperty(ref _isRead, value);
    }
}
</code>```

ViewModel

```<code>public class MainPageViewModel : BaseViewModel
{
    private ObservableCollection<Notification> _notifications;

    public ObservableCollection<Notification> Notifications
    {
        get => _notifications;
        set => SetProperty(ref _notifications, value);
    }

    public ICommand TappedCommand => new Command((o => OnTapped(o)));

    public MainPageViewModel()
    {
        _notifications = new ObservableCollection<Notification>()
        {
            new Notification()
            {
                IsRead = false,
                Message = "First notification"
            },
            new Notification()
            {
                IsRead = false,
                Message = "Second notification"
            },
            new Notification()
            {
                IsRead = false,
                Message = "Third notification"
            },
            new Notification()
            {
                IsRead = false,
                Message = "Fourth notification"
            }
        };
    }

    private void OnTapped(object o)
    {
        if(!(o is Notification noti)) return;

        noti.IsRead = true;
    }
}
</code>```

Page:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:NotificationTest"
         x:Class="NotificationTest.MainPage">
<ContentPage.Content>
    <ListView x:Name="NotiList"  ItemsSource="{Binding Notifications}" ItemTapped="OnTapped" ItemSelected="OnSelected" CachingStrategy="RecycleElement">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                <Grid BackgroundColor="{Binding IsRead,Converter={StaticResource ReadToColorConverter}}">
                    <Label Text="{Binding Message}"/>
                </Grid>
               </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>
</code>```

Page code behind ( just work around to hide selected line color in listview

```<code> public partial class MainPage : ContentPage
{
    private MainPageViewModel _vm;
    public MainPage()
    {
        InitializeComponent();
        _vm = new MainPageViewModel();
        BindingContext = _vm;
    }

    private void OnTapped(object sender, ItemTappedEventArgs e)
    {
        _vm.TappedCommand.Execute(e.Item);
    }

    private void OnSelected(object sender, SelectedItemChangedEventArgs e)
    {
        NotiList.SelectedItem = null;
    }
}
</code>```

答:
The problem was caused by the default behavior when selecting cell in iOS.

The default selected color will cover the red color , so it didn't get working.

Refer to my recent answer Here

Test

Body:
Does anyone encounter annoyed issue when update background color of cell in xamarin form?
I have notification list, when user clicks on item, it's marked as read then background color will be updated.
It works perfectly on android but iOS.
Most of the time the color is changed back to origin.
In the example, cell background is blue if notification is read.
When user clicks on cell, cell background should be red, but it's not changed most of time.

Notification Model

 public class Notification : ObservableObject
{
    private string _message;
    private bool _isRead;

    public string Message
    {
        get => _message;
        set => SetProperty(ref _message, value);
    }

    public bool IsRead
    {
        get => _isRead;
        set => SetProperty(ref _isRead, value);
    }
}

ViewModel

public class MainPageViewModel : BaseViewModel
{
    private ObservableCollection<Notification> _notifications;

    public ObservableCollection<Notification> Notifications
    {
        get => _notifications;
        set => SetProperty(ref _notifications, value);
    }

    public ICommand TappedCommand => new Command((o => OnTapped(o)));

    public MainPageViewModel()
    {
        _notifications = new ObservableCollection<Notification>()
        {
            new Notification()
            {
                IsRead = false,
                Message = "First notification"
            },
            new Notification()
            {
                IsRead = false,
                Message = "Second notification"
            },
            new Notification()
            {
                IsRead = false,
                Message = "Third notification"
            },
            new Notification()
            {
                IsRead = false,
                Message = "Fourth notification"
            }
        };
    }

    private void OnTapped(object o)
    {
        if(!(o is Notification noti)) return;

        noti.IsRead = true;
    }
}

Page:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:NotificationTest"
         x:Class="NotificationTest.MainPage">
<ContentPage.Content>
    <ListView x:Name="NotiList"  ItemsSource="{Binding Notifications}" ItemTapped="OnTapped" ItemSelected="OnSelected" CachingStrategy="RecycleElement">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                <Grid BackgroundColor="{Binding IsRead,Converter={StaticResource ReadToColorConverter}}">

                </Grid>
               </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>

Page code behind ( just work around to hide selected line color in listview

 public partial class MainPage : ContentPage
{
    private MainPageViewModel _vm;
    public MainPage()
    {
        InitializeComponent();
        _vm = new MainPageViewModel();
        BindingContext = _vm;
    }

    private void OnTapped(object sender, ItemTappedEventArgs e)
    {
        _vm.TappedCommand.Execute(e.Item);
    }

    private void OnSelected(object sender, SelectedItemChangedEventArgs e)
    {
        NotiList.SelectedItem = null;
    }
}


问:
CSplitterWnd flip between horizontal and vertical splitter?
Suppose I have a splitter with 2 rows.

--------

|        |

--------

|        |

--------

How do I make it to this

---------

|    |    |

|    |    |

|    |    |

---------

switch from horizontal split to vertical split

without having to re-create the whole splitter?

Code is:

```<code>if (!m_wndSplitter.CreateStatic(this, 1, 2, WS_CHILD|WS_VISIBLE))
{
    TRACE0("Failed to create splitter window\n");
    return FALSE;
}
if (!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CWnd), CSize(200, 100), NULL))
{
    TRACE0("Failed to create CView1\n");
    return FALSE;
}
if (!m_wndSplitter.CreateView(0, 2, RUNTIME_CLASS(CWnd), CSize(500, 100), NULL))
{
    TRACE0("Failed to create CView2\n");
    return FALSE;
}
</code>```

答:
-----------|----------|
|            |            |
|            |            |
|            |----------|
|            |            |
|            |            |
-----------|----------|

2 column splitter with right side having 2 rows, one Up and one Down and another one with left side to the Up and Down ?

ContentLicense: CC BY-SA 4.0

Body:
Suppose I have a splitter with 2 rows.

--------

|        |

--------

|        |

--------

How do I make it to this

---------

|    |    |

|    |    |

|    |    |

---------

switch from horizontal split to vertical split

without having to re-create the whole splitter?

Code is:

if (!m_wndSplitter.CreateStatic(this, 1, 2, WS_CHILD|WS_VISIBLE))
{
    TRACE0("Failed to create splitter window\n");
    return FALSE;
}
if (!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CWnd), CSize(200, 100), NULL))
{
    TRACE0("Failed to create CView1\n");
    return FALSE;
}
if (!m_wndSplitter.CreateView(0, 2, RUNTIME_CLASS(CWnd), CSize(500, 100), NULL))
{
    TRACE0("Failed to create CView2\n");
    return FALSE;
}


问:
Visual Studio 2017 Enterprise + TFS 2018 + Git Clone = Unable to get local issuer certificate
I'm new to interact with Git and I'm trying to combine it with TFS infrastructure, but experiencing SSL authentication problems. No Github, no VSTS. TFS is on-premises, therefore local installation.

Server part:

I've installed TFS 2018 on Windows Server 2016 and create a corporate self signed certificate and bind the TFS web service (IIS manager) on that certificate.

TFS is configured to run only through HTTPS. HTTP is redirected to HTTPS.
I've setup a new Project with Git as versioning system.

Client part:

I have two kind of Windows clients. Windows 7 SP1 and 10 Anniversary Update, both of them with Visual Studio 2017 Enterprise.

I installed the certificate (as Trusted Root Certification Authorities) and connecting through browser I have no whatsoever to see the project informations.
No browser raise any kind of alerts regarding authenticity of certicate.
Then, I installed Git-2.15.1.2-64-bit.exe, using Windows Secure Channel Library.

I followed this guide to configure Git clients, because I was getting title fatal error.
So basically I extracted content of self-signed and appended to ca-bundle.crt file.
All of them:

C:/Program Files/Git/mingw64/ssl/certs/

C:\users\myname (created as a global one just like guide says)

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\mingw32\ssl\certs (this is created by Visual Studio 2017 installation)

When I use through Powershell "git config --list --show-origin" command, I see listed:
file:"C:\Program Files\Git\mingw64/etc/gifconfig"  http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
file:"C:/users/myname/.gifconfig"  http.sslcainfo=C:/users/myname/ca-bundle.crt

If I try to clone repository from VS2017 Team Explorer panel it keeps saying:
"Git failed with a fatal error.
fatal: unable to access 'https://tfs.blahblah/': SSL certificate problem: unable to get local issuer certificate"

But when I use Git GUI it answers with a different error:
fatal: Couldn't find remote ref HEAD
As far as I know it looks reasonable because there is no commit attached.

But I can't commit anything if I can't "pair" with Visual Studio 2017.

I read through several links, but I couldn't get it through. So before mark it as duplicated, I ask you to PLEASE pay attention to my specific system/environment requirements.

Note: and please don't suggest me to switch off SSL because as already talked it is NOT a solution in corporate/enterprise environments

答:
After two day with system admin support, I got the solution.
I post it here in case it may help somebody else.
Visual Studio 2017 looks not accepting a self signed certificate, as error states ("local issuer blah blah"). It has to be a local CA to approve it.
Steps were:

Server:

Install Company/Trusted CA on TFS machine as Trusted Authority root

Preparing certificate for TFS and make it derive from company/trusted CA.

Install it as Trusted Authority root in TFS machine

Configure TFS-IIS binding in order to make TFS certificate to be compulsory for HTTPS connections

Client:

Install CA certificate as Trusted Authority root on client machine (tried with Windows 7 and 10)

Install TFS certificate as Trusted Authority root on client machine (you should see the lock in browser and connecting through it has to be recognized as secure)

Install Git client (I have Git-2.15.1.2-64-bit).

Run a shell (cmd, Powershell, Git-bash as you prefer) and digit this command: git config --global http.sslCAInfo C:/Users//ca-bundle.crt   (because Git and Visual Studio have multiple folders where they store certificates, you are basically creating a global path for both of them)

Now you should be able to see a new .gitconfig file with this content: [http]
sslCAInfo = C:/Users//ca-bundle.crt

if you digit command "git config --list --show-origin" you should see the new path/config added

Copy ca-bundle.crt from C:\Program Files\Git\mingw64\ssl\certs path to C:/Users// path

Export CA certificate as Base 64 X.509 (.CER) to up to you path (you can view certificates from IE Internet Options/Content/Certificates).

Open it with editor like Notepad++ or whatever the CA certificate that you just exported. Content should be: -----BEGIN CERTIFICATE-----publickey-----END CERTIFICATE-----

Copy this content

Open the C:/Users//ca-bundle.crt and paste appending that content

Export TFS certificate as Base 64 X.509 (.CER) to up to you path.

Open it with the editor you prefer and copy the content

Open the C:/Users//ca-bundle.crt and paste appending that content

Save the file

Now you should be able to clone repository.

So basically the point is that certificate has to have the all chain authority in it and there has to be one.


答:
There may not be enough (RAM/cache) space to save your filtered results and then join them together. It can be slower than you expect.

*technically you can, but not that efficient.

```<code>SELECT *
FROM (
    SELECT * FROM Table1 where flag1 = 0
) A
JOIN (
    SELECT * FROM TABLE2 where flag2 = 0
) B
ON A.orderlist_email = B.email;
</code>```

however, I'd recommend just join them first, and where everything later. MySQL (or whatever sql engine) will (usually) do a fine job optimizing it for you.

```<code>SELECT *
FROM Table1
JOIN TABLE2
ON A.orderlist_email = B.email
WHERE Table1.flag1 = 0
AND TABLE2.flag2 = 0;
</code>```

Title: How can i join two tables after filtering

Body:
There may not be enough (RAM/cache) space to save your filtered results and then join them together. It can be slower than you expect.

*technically you can, but not that efficient.

SELECT *
FROM (
    SELECT * FROM Table1 where flag1 = 0
) A
JOIN (
    SELECT * FROM TABLE2 where flag2 = 0
) B
ON A.orderlist_email = B.email;

however, I'd recommend just join them first, and where everything later. MySQL (or whatever sql engine) will (usually) do a fine job optimizing it for you.

SELECT *
FROM Table1
JOIN TABLE2
ON A.orderlist_email = B.email
WHERE Table1.flag1 = 0
AND TABLE2.flag2 = 0;


问:
Hook to change page title
I want to programmatically alter a page title in Drupal 8 so that it will be hard-coded in the theme file.

I'm attempting to use a hook function to preprocess_page_title, but it seems to not understand what page to change the title on.

Here's what I have so far:

```<code>function test_preprocess_page_title(&$variables) {
  if (arg(0) == 'node/12') {
    $variables['title'] = 'New Title';
  }
}
</code>```

I figured the only way to make this change on one specific page is to set the node argument. Has any one figured out a way to override page title on Drupal?

答:
In your template.theme file add the preprocessor and then override page-title.html.twig in your template folder by printing the variable, like below:

```<code>function theme_preprocess_page_title(&$variables) {
  $node = \Drupal::request()->attributes->get('node');
  $nid = $node->id();
  if($nid == '14') {
    $variables['subtitle'] = 'Subheading';
  }
}
</code>```

then {{ subtitle }}

Title: Hook to change page title

Body:
I want to programmatically alter a page title in Drupal 8 so that it will be hard-coded in the theme file.

I'm attempting to use a hook function to preprocess_page_title, but it seems to not understand what page to change the title on.

Here's what I have so far:

function test_preprocess_page_title(&$variables) {
  if (arg(0) == 'node/12') {
    $variables['title'] = 'New Title';
  }
}

I figured the only way to make this change on one specific page is to set the node argument. Has any one figured out a way to override page title on Drupal?

Body:
In your template.theme file add the preprocessor and then override page-title.html.twig in your template folder by printing the variable, like below:

function theme_preprocess_page_title(&$variables) {
  $node = \Drupal::request()->attributes->get('node');
  $nid = $node->id();
  if($nid == '14') {
    $variables['subtitle'] = 'Subheading';
  }
}

then {{ subtitle }}


问:
VBA, Import CSV split by ";" to sheet
I am trying to import a CSV file split by semicolon ";" into an excel object so I can use it later on.

Ideally i would like to use ADO, DAO or ADODB so I can also run SQL queries on the object, and get sum of specific fields, or total number of fields and so on.

So far i've gotten the code below, but it does not split the data by ";", so it all comes back as 1 field instead of multiple fields that can be handled.

```<code>Sub Import()
   Dim conn As New ADODB.Connection
   Dim rs As New ADODB.Recordset
   Dim f As ADODB.Field

   Dim csvName, csvPath

    csvPath = ActiveWorkbook.path
    csvName = "fileName.csv"

   conn.Open "DRIVER={Microsoft Text Driver (*.txt; *.csv)};DBQ=" & csvPath & ";"
   rs.Open "SELECT * FROM " & csvName, conn, adOpenStatic, adLockReadOnly, adCmdText

   Debug.Print rs.Fields

   While Not rs.EOF
      For Each f In rs.Fields
         Debug.Print f.Name & "=" & f.Value
      Next
   Wend
End Sub
</code>```

Can anyone give me an idea how I can also split the data by ";" and query it using SQL query? Or a different object that I could load a CSV into and query certain columns.

答:
Here's example:</p>

```<code>Public Sub QueryTextFile()

    Dim rsData As ADODB.Recordset
    Dim sConnect As String
    Dim sSQL As String

    ' Create the connection string.
    sConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=C:\Files\;" & _
               "Extended Properties=Text;"

    ' Create the SQL statement.
    sSQL = "SELECT * FROM Sales.csv;"
    Set rsData = New ADODB.Recordset
    rsData.Open sSQL, sConnect, adOpenForwardOnly, _
                adLockReadOnly, adCmdText

    ' Check to make sure we received data.
    If Not rsData.EOF Then
        ' Dump the returned data onto Sheet1.
        Sheet1.Range("A1").CopyFromRecordset rsData
    Else
        MsgBox "No records returned.", vbCritical
    End If

    ' Clean up our Recordset object.
    rsData.Close
    Set rsData = Nothing

End Sub
</code>```

Title: VBA, Import CSV split by ";" to sheet

Body:
I am trying to import a CSV file split by semicolon ";" into an excel object so I can use it later on.

Ideally i would like to use ADO, DAO or ADODB so I can also run SQL queries on the object, and get sum of specific fields, or total number of fields and so on.

So far i've gotten the code below, but it does not split the data by ";", so it all comes back as 1 field instead of multiple fields that can be handled.

Sub Import()
   Dim conn As New ADODB.Connection
   Dim rs As New ADODB.Recordset
   Dim f As ADODB.Field

   Dim csvName, csvPath

    csvPath = ActiveWorkbook.path
    csvName = "fileName.csv"

   conn.Open "DRIVER={Microsoft Text Driver (*.txt; *.csv)};DBQ=" & csvPath & ";"
   rs.Open "SELECT * FROM " & csvName, conn, adOpenStatic, adLockReadOnly, adCmdText

   Debug.Print rs.Fields

   While Not rs.EOF
      For Each f In rs.Fields
         Debug.Print f.Name & "=" & f.Value
      Next
   Wend
End Sub

Can anyone give me an idea how I can also split the data by ";" and query it using SQL query? Or a different object that I could load a CSV into and query certain columns.

Body:
Here's example:

Public Sub QueryTextFile()

    Dim rsData As ADODB.Recordset
    Dim sConnect As String
    Dim sSQL As String

    ' Create the connection string.
    sConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=C:\Files\;" & _
               "Extended Properties=Text;"

    ' Create the SQL statement.
    sSQL = "SELECT * FROM Sales.csv;"
    Set rsData = New ADODB.Recordset
    rsData.Open sSQL, sConnect, adOpenForwardOnly, _
                adLockReadOnly, adCmdText

    ' Check to make sure we received data.
    If Not rsData.EOF Then
        ' Dump the returned data onto Sheet1.
        Sheet1.Range("A1").CopyFromRecordset rsData
    Else
        MsgBox "No records returned.", vbCritical
    End If

    ' Clean up our Recordset object.
    rsData.Close
    Set rsData = Nothing

End Sub


问:
subscribing to location service of angular/common
My goal is to disable the back button of browser window. So, In my component, I am trying to listen for the path, for that I have imported location from angular/common and trying to subscribe it, but it does not seems to working for me. here is my code snippet of that perticular component where i want to disable back button. </p>

```<code>    import { DataService } from './../../../shared/services/data.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from "@angular/common";
@Component({
  selector: 'app-confirmation',
  templateUrl: './confirmation.component.html',
  styleUrls: ['./confirmation.component.scss']
})
export class ConfirmationComponent implements OnInit {
  userInput;
  customWindow;
  time;
  message: string;
  constructor(private location: Location, private dataService: DataService, private router: Router) {
     this.dataService.currentMessage
 .subscribe(message => (this.message = message));
 console.log(this.message);

this.dataService.timeSource.subscribe(time => (this.time = time));
console.log(this.time);

}

  ngOnInit(): void {
    this.customWindow = window.open("", "_blank", "");
    console.log('here');
    console.log(this.location);
 this.location.subscribe(x => console.log(x));
  }

  close () {

    console.log(this.customWindow);
   // this.customWindow.close();
 console.log('666');
 // this.router.navigate(['login']);
  }

}
</code>```

答:
There is a Solution with pure Javascript, no need for an Angular approach.

As seen here: Disable browser back button for one page application

Your solution would look like this:

```<code>window.onpopstate = function (e) { window.history.forward(1); }
</code>```

But be careful when executing this code in Angular Universal.

Body:
My goal is to disable the back button of browser window. So, In my component, I am trying to listen for the path, for that I have imported location from angular/common and trying to subscribe it, but it does not seems to working for me. here is my code snippet of that perticular component where i want to disable back button.

    import { DataService } from './../../../shared/services/data.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from "@angular/common";
@Component({
  selector: 'app-confirmation',
  templateUrl: './confirmation.component.html',
  styleUrls: ['./confirmation.component.scss']
})
export class ConfirmationComponent implements OnInit {
  userInput;
  customWindow;
  time;
  message: string;
  constructor(private location: Location, private dataService: DataService, private router: Router) {
     this.dataService.currentMessage
 .subscribe(message => (this.message = message));
 console.log(this.message);

this.dataService.timeSource.subscribe(time => (this.time = time));
console.log(this.time);

}

  ngOnInit(): void {
    this.customWindow = window.open("", "_blank", "");
    console.log('here');
    console.log(this.location);
 this.location.subscribe(x => console.log(x));
  }

  close () {

    console.log(this.customWindow);
   // this.customWindow.close();
 console.log('666');
 // this.router.navigate(['login']);
  }

}

Body:
There is a Solution with pure Javascript, no need for an Angular approach.

As seen here: Disable browser back button for one page application

Your solution would look like this:

window.onpopstate = function (e) { window.history.forward(1); }

But be careful when executing this code in Angular Universal.


问:
Django redirect from inside a view
I'm using django 1.11.8.

I need to perform some check on the requested view and inside it redirect the user to another Http page, but this code fail, as the redirect is ignored.

What am I missing?

```<code>class ThisCreateView(CreateView):

    def get_form_kwargs(self):
         if self.kwargs['x'] == 1:
              return redirect(reverse('this_app:this_list'))
         return kwargs
</code>```

答:
You can't return a redirect from the get_form_kwargs method. Its job is to return a dictionary of kwargs for the form.

You could move this check to the dispatch method.

```<code>def dispatch(self, request, *args, **kwargs):
     if kwargs['x'] == 1:
          # note you don't need to call reverse when you use redirect
          return redirect('this_app:this_list')
     return super(ThisCreateView, self).dispatch(*args, **kwargs)
</code>```

Title: Django redirect from inside a view

Body:
I'm using django 1.11.8.

I need to perform some check on the requested view and inside it redirect the user to another Http page, but this code fail, as the redirect is ignored.

What am I missing?

class ThisCreateView(CreateView):

    def get_form_kwargs(self):
         if self.kwargs['x'] == 1:
              return redirect(reverse('this_app:this_list'))
         return kwargs

Body:
You can't return a redirect from the get_form_kwargs method. Its job is to return a dictionary of kwargs for the form.

You could move this check to the dispatch method.

def dispatch(self, request, *args, **kwargs):
     if kwargs['x'] == 1:
          # note you don't need to call reverse when you use redirect
          return redirect('this_app:this_list')
     return super(ThisCreateView, self).dispatch(*args, **kwargs)


问:
SQL Server Unable to convert a string to a date in a where clause (Code 241)
I have a query which cut a substring out of a char field and returns it a a date.
And it works:

```<code>select
    ujp_jobid, ujp_lfdnr,
    isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date, getDate())) para_date,
    datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate())), convert(date,getDate())) datedif
from
    uno_jobpara
where
    ujp_jobid between 0 and 30000
    and ujp_paraname = 'P_PGENDE'
</code>```

The result is:

```<code>1   6   2017-11-28  8
2   372 2017-05-06  214
3   84  2017-05-01  219
</code>```

...

I first tried the to use the datedif part as where clause:

```<code>...
and ujp_paraname = 'P_PGENDE'
    and datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate()) ), convert(date,getDate())) > 0
</code>```

Suddenly the server raised an Error:

[Code: 241, SQL State: S0001]  Fehler beim Konvertieren einer Zeichenfolge in ein Datum und/oder eine Uhrzeit.

  (rough translation: Error converting a string to a date and/or a time)

Not quite sure why this is, but I guessed, that there the server tries to check the where conditional first and thinks that it might run into an an error.

However I tried to put in all in another select:

```<code>select
    ujp_jobid, ujp_lfdnr, para_date, datedif
from
    (select
         ujp_jobid, ujp_lfdnr,
         isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate()) ) para_date,
         datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date, getDate()) ), convert(date, getDate())) datedif
     from
         uno_jobpara
     where
         ujp_jobid between 0 and 30000
         and ujp_paraname = 'P_PGENDE') as tt
where
    tt.datedif > 0;
</code>```

The same error?! Why, and how can I tell SQL Server to run a subquery first? Do I really need a temp table?

TIA

Jo

答:
First check if all parsed strings can be converted to DATE.
Since you are using SQL Server 2016, you can use TRY_CONVERT to test if you can convert them or not.

```<code>SET DATEFORMAT dd.mm.yyyy; -- This format is equivalent to format 104

SELECT
    ujp_jobid, ujp_lfdnr,
  , substring(ujp_parawert, charindex(' ', ujp_parawert) + 1, 10)
WHERE
  TRY_CONVERT(DATE, SUBSTRING(ujp_parawert, CHARINDEX(' ', ujp_parawert) + 1,10)) IS NULL
</code>```

Check the records you get, those records cannot be converted.

If you get any, you have to decide if NULLs are acceptable or not.

If they are, use TRY_CONVERT() instead of CONVERT/CAST

If NULL are not acceptable, you'll have to modify your expression to handle all possible variations.

DATEFROMPARTS(year, month, day) can be useful too if you have to modify the expression.

Body:
I have a query which cut a substring out of a char field and returns it a a date.
And it works:

select
    ujp_jobid, ujp_lfdnr,
    isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date, getDate())) para_date,
    datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate())), convert(date,getDate())) datedif
from
    uno_jobpara
where
    ujp_jobid between 0 and 30000
    and ujp_paraname = 'P_PGENDE'

The result is:

1   6   2017-11-28  8
2   372 2017-05-06  214
3   84  2017-05-01  219

...

I first tried the to use the datedif part as where clause:

...
and ujp_paraname = 'P_PGENDE'
    and datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate()) ), convert(date,getDate())) > 0

Suddenly the server raised an Error:

[Code: 241, SQL State: S0001]  Fehler beim Konvertieren einer Zeichenfolge in ein Datum und/oder eine Uhrzeit.

  (rough translation: Error converting a string to a date and/or a time)

Not quite sure why this is, but I guessed, that there the server tries to check the where conditional first and thinks that it might run into an an error.

However I tried to put in all in another select:

select
    ujp_jobid, ujp_lfdnr, para_date, datedif
from
    (select
         ujp_jobid, ujp_lfdnr,
         isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date,getDate()) ) para_date,
         datediff(day, isnull(convert(date, substring(ujp_parawert, charindex(' ', ujp_parawert) + 1,10), 104), convert(date, getDate()) ), convert(date, getDate())) datedif
     from
         uno_jobpara
     where
         ujp_jobid between 0 and 30000
         and ujp_paraname = 'P_PGENDE') as tt
where
    tt.datedif > 0;

The same error?! Why, and how can I tell SQL Server to run a subquery first? Do I really need a temp table?

TIA

Jo

Body:
First check if all parsed strings can be converted to DATE.
Since you are using SQL Server 2016, you can use TRY_CONVERT to test if you can convert them or not.

SET DATEFORMAT dd.mm.yyyy; -- This format is equivalent to format 104

SELECT
    ujp_jobid, ujp_lfdnr,
  , substring(ujp_parawert, charindex(' ', ujp_parawert) + 1, 10)
WHERE
  TRY_CONVERT(DATE, SUBSTRING(ujp_parawert, CHARINDEX(' ', ujp_parawert) + 1,10)) IS NULL

Check the records you get, those records cannot be converted.

If you get any, you have to decide if NULLs are acceptable or not.

If they are, use TRY_CONVERT() instead of CONVERT/CAST

If NULL are not acceptable, you'll have to modify your expression to handle all possible variations.

DATEFROMPARTS(year, month, day) can be useful too if you have to modify the expression.


答:
Consider the two Select Statements as SUBQUERIES, and the results of these two subqueries as two different tables and then try joining.</p>

```<code>SELECT * FROM
(SELECT * FROM Table1 where flag1 = 0) Table1
JOIN
(SELECT * FROM TABLE2 where flag2 = 0) Table2
on Table1.orderlist_email = TABLE2.email
</code>```

Body:
How can i join two tables after filtering each table with some condition and on getting the result of filter, join both the results.

Tried code but showing syntax error

SELECT *
FROM Table1
WHERE flag1 = 0
JOIN SELECT *
     FROM TABLE2
     where flag2 = 0 on Table1.email = TABLE2.email

Body:
Consider the two Select Statements as SUBQUERIES, and the results of these two subqueries as two different tables and then try joining.

SELECT * FROM
(SELECT * FROM Table1 where flag1 = 0) Table1
JOIN
(SELECT * FROM TABLE2 where flag2 = 0) Table2
on Table1.orderlist_email = TABLE2.email


问:
Swift extract regex matches
I want to extract substrings from a string that match a regex pattern.

So I'm looking for something like this:

```<code>func matchesForRegexInText(regex: String!, text: String!) -> [String] {
   ???
}
</code>```

So this is what I have:

```<code>func matchesForRegexInText(regex: String!, text: String!) -> [String] {

    var regex = NSRegularExpression(pattern: regex,
        options: nil, error: nil)

    var results = regex.matchesInString(text,
        options: nil, range: NSMakeRange(0, countElements(text)))
            as Array<NSTextCheckingResult>

    /// ???

    return ...
}
</code>```

The problem is, that matchesInString delivers me an array of NSTextCheckingResult, where NSTextCheckingResult.range is of type NSRange.

NSRange is incompatible with Range<String.Index>, so it prevents me of using text.substringWithRange(...)

Any idea how to achieve this simple thing in swift without too many lines of code?

答:
Most of the solutions above only give the full match as a result ignoring the capture groups e.g.: ^\d+\s+(\d+)

To get the capture group matches as expected you need something like (Swift4) :

```<code>public extension String {
    public func capturedGroups(withRegex pattern: String) -> [String] {
        var results = [String]()

        var regex: NSRegularExpression
        do {
            regex = try NSRegularExpression(pattern: pattern, options: [])
        } catch {
            return results
        }
        let matches = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.count))

        guard let match = matches.first else { return results }

        let lastRangeIndex = match.numberOfRanges - 1
        guard lastRangeIndex >= 1 else { return results }

        for i in 1...lastRangeIndex {
            let capturedGroupIndex = match.range(at: i)
            let matchedString = (self as NSString).substring(with: capturedGroupIndex)
            results.append(matchedString)
        }

        return results
    }
}
</code>```

Title: Swift extract regex matches

Body:
I want to extract substrings from a string that match a regex pattern.

So I'm looking for something like this:

func matchesForRegexInText(regex: String!, text: String!) -> [String] {
   ???
}

So this is what I have:

func matchesForRegexInText(regex: String!, text: String!) -> [String] {

    var regex = NSRegularExpression(pattern: regex,
        options: nil, error: nil)

    var results = regex.matchesInString(text,
        options: nil, range: NSMakeRange(0, countElements(text)))
            as Array<NSTextCheckingResult>

    /// ???

    return ...
}

The problem is, that matchesInString delivers me an array of NSTextCheckingResult, where NSTextCheckingResult.range is of type NSRange.

NSRange is incompatible with Range<String.Index>, so it prevents me of using text.substringWithRange(...)

Any idea how to achieve this simple thing in swift without too many lines of code?

Body:
Most of the solutions above only give the full match as a result ignoring the capture groups e.g.: ^\d+\s+(\d+)

To get the capture group matches as expected you need something like (Swift4) :

public extension String {
    public func capturedGroups(withRegex pattern: String) -> [String] {
        var results = [String]()

        var regex: NSRegularExpression
        do {
            regex = try NSRegularExpression(pattern: pattern, options: [])
        } catch {
            return results
        }
        let matches = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.count))

        guard let match = matches.first else { return results }

        let lastRangeIndex = match.numberOfRanges - 1
        guard lastRangeIndex >= 1 else { return results }

        for i in 1...lastRangeIndex {
            let capturedGroupIndex = match.range(at: i)
            let matchedString = (self as NSString).substring(with: capturedGroupIndex)
            results.append(matchedString)
        }

        return results
    }
}


问:
if (view == null) issues in fragment
I have updated my Sdk Oreo 8.0 When i come my current fragment to my previous fragment its crash because i am using if (view == null)
if i removed this condition it 'll work fine but have to load again view. </p>

```<code>@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.home_fragement_layout, container, false);
            ButterKnife.bind(this, view);
            bundle=getArguments();
            registrationResponse=(RegistrationResponse)bundle.getSerializable("registerresponse");
            setadapter();
            hitUserFavouriteOutfitsapi();
           swipeRefreshLayout.setOnRefreshListener(this);
        }
        toolBarTopChangeState =((ToolBarTopChangeState)context);
        toolBarTopChangeState.stateChangeToolBarIcon(0);
        toolBarTopChangeState.stateChangeToolBarText(getString(R.string.app_name));
        return view;
    }
</code>```

答: On the lists is a good practice to check if the view is already created and if it's to use it further, but on the activities and fragments you should left the OS to decide when should inflate again the view. You can have a look over android lifecycle to understand better how it's works</p>

Title: if (view == null) issues in fragment

Body:
I have updated my Sdk Oreo 8.0 When i come my current fragment to my previous fragment its crash because i am using if (view == null)
if i removed this condition it 'll work fine but have to load again view.

@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.home_fragement_layout, container, false);
            ButterKnife.bind(this, view);
            bundle=getArguments();
            registrationResponse=(RegistrationResponse)bundle.getSerializable("registerresponse");
            setadapter();
            hitUserFavouriteOutfitsapi();
           swipeRefreshLayout.setOnRefreshListener(this);
        }
        toolBarTopChangeState =((ToolBarTopChangeState)context);
        toolBarTopChangeState.stateChangeToolBarIcon(0);
        toolBarTopChangeState.stateChangeToolBarText(getString(R.string.app_name));
        return view;
    }


问:
Save user language in a model through default() with Django
I would like to save the language of the user each time a new model instance is created:

models.py:

```<code>def getlanguage(request):
    lang = request.LANGUAGE_CODE
    return lang

class Comment(models.Model):
    language = models.CharField(max_length=100, blank=True, default=getlanguage)
</code>```

Django generates the following error:
TypeError: getlanguage() takes exactly 1 argument (0 given)

How to pass the request to the function?

Thank you!

答:
Your save method needs to be overridden like this.

```<code>class Comment(models.Model):
    language = models.CharField(max_length=100, blank=True, default='')

    def save(self, *args, **kwargs):
        default_language = kwargs.pop('default_language', None)
        if not self.language and default_language is not None:
            self.language = default_language
        super(Comment, self).save(*args, **kwargs)
</code>```

And you can pass the parameter when save() is called on an object in the views

```<code>comment = Comment()
comment.save(default_language=request.LANGUAGE_CODE)
</code>```

Body:
I would like to save the language of the user each time a new model instance is created:

models.py:

def getlanguage(request):
    lang = request.LANGUAGE_CODE
    return lang

class Comment(models.Model):
    language = models.CharField(max_length=100, blank=True, default=getlanguage)

Django generates the following error:
TypeError: getlanguage() takes exactly 1 argument (0 given)

How to pass the request to the function?

Thank you!

Body:
Your save method needs to be overridden like this.

class Comment(models.Model):
    language = models.CharField(max_length=100, blank=True, default='')

    def save(self, *args, **kwargs):
        default_language = kwargs.pop('default_language', None)
        if not self.language and default_language is not None:
            self.language = default_language
        super(Comment, self).save(*args, **kwargs)

And you can pass the parameter when save() is called on an object in the views

comment = Comment()
comment.save(default_language=request.LANGUAGE_CODE)


问:
Are all the classes containing business logic, domain objects?
So I have few doubts regarding calling something as domain object (and eventually placing the class under domain package) or not.

I have a micro-service whose responsibility is to do some calculations (without getting into actual business requirements, all it does is calculate some return of intereset based on given request). Now to achieve the calculations there are certain sub-calculations which need to take place and hence are composed in different classes respectively. But yes, these calculation do not need to be persisted in DB , and neither they have an ID (so definitely not an Entity or Aggregate). However these individual calculator classes (for the lack of terminology) do contain some complex business logic. Now, my question is, do these individual classes still qualify/classify as domain objects or should they be referred to as services ?

Feel free to ask for more clarifications around use case if need be.

Cheers !

答:
Now, my question is, do these individual classes still qualify/classify as domain objects or should they be referred to as services

From the DDD point of view, in the Domain layer, there are the following terms that could be implemented using classes: Domain entities, Aggregate roots (a type of Domain entity), Value objects and Domain services.

Because your things don't have an Identity they cannot be Domain entities or Aggregate roots. Calculations could be done inside Value objects or Domain services. Value objects contain specific behavior related to values so most probable your calculations are implemented using Domain services.

From my experience, not every domain class must be a DDD building block, they could be just classes extracted for better maintainability, Single responsibility principle (SOLID in general) etc.


问:
Elements form array.map don't render
I am trying to render elements from my state (array) but they don't want render on the screen. If I perform console.log(b.name) it logs my names in console.

```<code>renderAllElements() {
    this.state.myData.map(b => {
        return(
            <div>
                <h4>{b.name}</h4>
            </div>
        )
    })
}

render() {
    return (
        <div>
            {this.renderAllElements()}
        </div>
    )
}
</code>```

答:
You need to return back your map :</p>

```<code>renderAllElements() {
  return this.state.myData.map(b => {
      return(
        <div>
            <h4>{b.name}</h4>
        </div>
     )
  })
}
</code>```

Title: Elements form array.map don't render

Body:
I am trying to render elements from my state (array) but they don't want render on the screen. If I perform console.log(b.name) it logs my names in console.

renderAllElements() {
    this.state.myData.map(b => {
        return(

{b.name}

        )
    })
}

render() {
    return (

            {this.renderAllElements()}

    )
}

Body:
You need to return back your map :

renderAllElements() {
  return this.state.myData.map(b => {
      return(
        <div>
            <h4>{b.name}</h4>
        </div>
     )
  })
}