问:
Receiving "validators.map is not a function" error on my custom form control
I created a family of components to use as form controls with the ControlValueAccessor.  When applying formControlName, formGroupName or formGroupArray to my components to pass in the form controls I get the error telling me

validators.map is not a function

This is how my component is set up

```<code>@Component({
  selector: 'view-box-form-component',
  templateUrl: './view-box-form.component.html',
  styleUrls: ['./view-box-form.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(()=>ViewBoxFormComponent),
      multi: true
    },
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(()=>ViewBoxFormComponent)
    }
  ]
})

export class ViewBoxFormComponent implements OnInit, ControlValueAccessor {

  ViewBoxFormData: FormGroup;

  constructor() { }

  ngOnInit() {}

  public onTouched : ()=> void =()=>{};

  writeValue(val: any):void{ val && this.ViewBoxFormData.setValue(val, {emitEvent: false}); console.log(val); }

  registerOnChange(fn: any): void{ this.ViewBoxFormData.valueChanges.subscribe(fn); console.log(fn); }

  registerOnTouched(fn: any): void{ this.onTouched = fn; }

  setDisabledState?(isDisabled: boolean): void{ isDisabled ? this.ViewBoxFormData.disable() : this.ViewBoxFormData.enable(); }

  validate(c: AbstractControl): ValidationErrors | null{
    return this.ViewBoxFormData.valid ? null : {invalidForm:{valid: false, message: 'field invalid'}};
  }

}
</code>```

and this is the template for that component

```<code><section [formGroup]="ViewBoxFormData" class="text-control-section">

    <label class="control-label">

        <p class="smallText"> x: </p>
        <input type="text" class="text-control smallText" formControlName="x" />

    </label>

    <label class="control-label">

        <p class="smallText"> y: </p>
        <input type="y" class="text-control smallText" formControlName="y" />

    </label>

    <label class="control-label">

        <p class="smallText"> width: </p>
        <input type="text" class="text-control smallText" formControlName="width" />

    </label>

    <label class="control-label">

        <p class="smallText"> height: </p>
        <input type="text" class="text-control smallText" formControlName="height" />

    </label>

</section>

</code>```

Inside the template to the parent component I implement the component like this

```<code><form [formGroup]="SvgFormData" (ngSubmit)="onSubmit()">

    <view-box-form-component formGroupName="viewBox"></view-box-form-component>

</form>
</code>```

I also have a couple other components I need to pass FormArrays into which I'm attempting to do with formArrayName="someControl".  Instead of creating the form inside the components I generate it with functions based on JSON objects.  The function for creating the form group for the view box data looks like this.

```<code>export function CreateViewBoxForm(data?: ViewBoxParameters): FormGroup{
    return new FormGroup({
      x      :  new FormControl((data ? data.x      : ''), Validators.required),
      y      :  new FormControl((data ? data.y      : ''), Validators.required),
      width  :  new FormControl((data ? data.width  : ''), Validators.required),
      height :  new FormControl((data ? data.height : ''), Validators.required)
    }) as FormGroup;
  }
</code>```

When I console.log() the completed form data everything is properly defined with all the proper values, I just can't figure out how to get them to pass into my components properly.  Dos anybody see what I'm doing wrong or if there's something more that I need to do to get this to work properly?

UPDATE

I decided to add a stackblitz of the entire mechanism so far so you guys can get a better idea for what I need to accomplish with my component structure.

stackblitz demo

答:
I think you'll have to add multi: true to your NG_VALIDATORS token.

Also, it looks like your ViewBoxFormComponent is not a simple FormControl, because inside your component you have another FormGroup instance. IMO, this is not idiomatically correct.

FormControlDirective, FormControlName, FormGroupName, FormArrayName, FormGroupDirective are form-control based directives and they, when combined, form an AbstractControlDirective tree(because each one inherits from AbstractControlDirective). These directives are the bridge between the the view layer(handled by ControlValueAccessor) and the model layer(handle by AbstractControl - the base class for FormControl, FormGroup, FormArray).

The root of such tree is FormGroupDirective(usually bound to a form element: <form [formGroup]="formGroupInstance">). With that in mind, your AbstractControl tree would look like this:

```<code>   FG <- [formGroup]="SvgFormData"
    |
    FC <- formGroupName="viewBox"
  / | \
 /  |  \
FC  FC  FC (height, width, x etc...)

</code>```

The FormControl should have no descendants. In this case, because your custom component(ViewBoxFormComponent) creates another tree. This is not wrong, but with this approach, you'll have to properly handle the both trees in order to not get unexpected results.

The FormGroup instance bound to the
 will not be registered as a descendant of SvgFormData because the FormGroupDirective does not behave like like FormGroupName:

FormGroupDirective

```<code>constructor(
      @Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
      @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) {
    super();
  }
</code>```

FormGroupName

```<code>  constructor(
      @Optional() @Host() @SkipSelf() parent: ControlContainer, // `ControlContainer` - token for `FormGroupDirective`/`FormGroupName`/`FormArrayName`
      @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],
      @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) {
    super();
    this._parent = parent;
    this._validators = validators;
    this._asyncValidators = asyncValidators;
  }
</code>```

If your custom component is not meant to contain a simple FormControl instance(it handles only a standalone FormControl instance with the help of formControl or ngModel directives), you should register it as descendant form group.

This can be achieved with this approach:

parent.component.ts

// The shape of the form is defined in one place!
// The children must only comply with the shape defined here

this.SvgFormData = this.fb.group({
  ViewBoxFormData: this.fb.group({
   height: this.fb.control(''),
   width: this.fb.control(''),
  /* ... */
  })
})
```

<h3>parent.component.html</h3>

<pre class="lang-html prettyprint-override"><code><form [formGroup]="SvgFormData" (ngSubmit)="onSubmit()">

    <!-- this will be a child form group -->
    <view-box-form-component></view-box-form-component>

</form>
</code>```

view-box-form-component.component.ts

```<code>@Component({
  selector: 'view-box-form-component',
  templateUrl: './view-box-form.component.html',
  styleUrls: ['./view-box-form.component.css'],
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(()=>ViewBoxFormComponent),
      multi: true,
    }
  ],
 viewProviders: [
   { provide: ControlContainer, useExisting: FormGroupDirective }
 ]
})

export class ViewBoxFormComponent implements OnInit {

  constructor() { }

  ngOnInit() {}

  validate(c: AbstractControl): ValidationErrors | null{
    /* ... */
  }
}
</code>```

As you can see, there is no need to provide CONTROL_VALUE_ACCESSOR anymore, because the form's shape will be defined in only one place(i.e: the parent form container). All you have to do in your child form container is to provide the right paths that correlate to the shape defined in the parent:

view-box-form-component.component.html

 x:

        <input type="text" class="text-control smallText" formControlName="x" />

 y:

        <input type="y" class="text-control smallText" formControlName="y" />

 width:

        <input type="text" class="text-control smallText" formControlName="width" />

 height:

        <input type="text" class="text-control smallText" formControlName="height" />

```

<p>What <code>viewProviders</code> does is to let you use a token(in this case <code>ControlContainer</code>) that is declared for the host element:</p>

```// FormGroupName

constructor (@Optional() @Host() @SkipSelf() parent: ControlContainer,) {}
```

Note: the same approach can be applied to FormArrayName.

You can find more about AbstractControl tree and how things work together in A thorough exploration of Angular Forms.

Body:
I created a family of components to use as form controls with the ControlValueAccessor.  When applying formControlName, formGroupName or formGroupArray to my components to pass in the form controls I get the error telling me

validators.map is not a function

This is how my component is set up

@Component({
  selector: 'view-box-form-component',
  templateUrl: './view-box-form.component.html',
  styleUrls: ['./view-box-form.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(()=>ViewBoxFormComponent),
      multi: true
    },
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(()=>ViewBoxFormComponent)
    }
  ]
})

export class ViewBoxFormComponent implements OnInit, ControlValueAccessor {

  ViewBoxFormData: FormGroup;

  constructor() { }

  ngOnInit() {}

  public onTouched : ()=> void =()=>{};

  writeValue(val: any):void{ val && this.ViewBoxFormData.setValue(val, {emitEvent: false}); console.log(val); }

  registerOnChange(fn: any): void{ this.ViewBoxFormData.valueChanges.subscribe(fn); console.log(fn); }

  registerOnTouched(fn: any): void{ this.onTouched = fn; }

  setDisabledState?(isDisabled: boolean): void{ isDisabled ? this.ViewBoxFormData.disable() : this.ViewBoxFormData.enable(); }

  validate(c: AbstractControl): ValidationErrors | null{
    return this.ViewBoxFormData.valid ? null : {invalidForm:{valid: false, message: 'field invalid'}};
  }

}

and this is the template for that component

 x:

        <input type="text" class="text-control smallText" formControlName="x" />

 y:

        <input type="y" class="text-control smallText" formControlName="y" />

 width:

        <input type="text" class="text-control smallText" formControlName="width" />

 height:

        <input type="text" class="text-control smallText" formControlName="height" />

Inside the template to the parent component I implement the component like this

<form [formGroup]="SvgFormData" (ngSubmit)="onSubmit()">

    <view-box-form-component formGroupName="viewBox"></view-box-form-component>

</form>

I also have a couple other components I need to pass FormArrays into which I'm attempting to do with formArrayName="someControl".  Instead of creating the form inside the components I generate it with functions based on JSON objects.  The function for creating the form group for the view box data looks like this.

export function CreateViewBoxForm(data?: ViewBoxParameters): FormGroup{
    return new FormGroup({
      x      :  new FormControl((data ? data.x      : ''), Validators.required),
      y      :  new FormControl((data ? data.y      : ''), Validators.required),
      width  :  new FormControl((data ? data.width  : ''), Validators.required),
      height :  new FormControl((data ? data.height : ''), Validators.required)
    }) as FormGroup;
  }

When I console.log() the completed form data everything is properly defined with all the proper values, I just can't figure out how to get them to pass into my components properly.  Dos anybody see what I'm doing wrong or if there's something more that I need to do to get this to work properly?

UPDATE

I decided to add a stackblitz of the entire mechanism so far so you guys can get a better idea for what I need to accomplish with my component structure.

stackblitz demo

Body:
I think you'll have to add multi: true to your NG_VALIDATORS token.

Also, it looks like your ViewBoxFormComponent is not a simple FormControl, because inside your component you have another FormGroup instance. IMO, this is not idiomatically correct.

FormControlDirective, FormControlName, FormGroupName, FormArrayName, FormGroupDirective are form-control based directives and they, when combined, form an AbstractControlDirective tree(because each one inherits from AbstractControlDirective). These directives are the bridge between the the view layer(handled by ControlValueAccessor) and the model layer(handle by AbstractControl - the base class for FormControl, FormGroup, FormArray).

The root of such tree is FormGroupDirective(usually bound to a form element: <form [formGroup]="formGroupInstance">). With that in mind, your AbstractControl tree would look like this:

   FG <- [formGroup]="SvgFormData"
    |
    FC <- formGroupName="viewBox"
  / | \
 /  |  \
FC  FC  FC (height, width, x etc...)

The FormControl should have no descendants. In this case, because your custom component(ViewBoxFormComponent) creates another tree. This is not wrong, but with this approach, you'll have to properly handle the both trees in order to not get unexpected results.

The FormGroup instance bound to the <section [formGroup]="ViewBoxFormData" class="text-control-section"> will not be registered as a descendant of SvgFormData because the FormGroupDirective does not behave like like FormGroupName:

FormGroupDirective

constructor(
      @Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
      @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) {
    super();
  }

FormGroupName

  constructor(
      @Optional() @Host() @SkipSelf() parent: ControlContainer, // `ControlContainer` - token for `FormGroupDirective`/`FormGroupName`/`FormArrayName`
      @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],
      @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) {
    super();
    this._parent = parent;
    this._validators = validators;
    this._asyncValidators = asyncValidators;
  }

If your custom component is not meant to contain a simple FormControl instance(it handles only a standalone FormControl instance with the help of formControl or ngModel directives), you should register it as descendant form group.

This can be achieved with this approach:

parent.component.ts

// The shape of the form is defined in one place!
// The children must only comply with the shape defined here

this.SvgFormData = this.fb.group({
  ViewBoxFormData: this.fb.group({
   height: this.fb.control(''),
   width: this.fb.control(''),
  /* ... */
  })
})

parent.component.html

<form [formGroup]="SvgFormData" (ngSubmit)="onSubmit()">

    <!-- this will be a child form group -->
    <view-box-form-component></view-box-form-component>

</form>

view-box-form-component.component.ts

@Component({
  selector: 'view-box-form-component',
  templateUrl: './view-box-form.component.html',
  styleUrls: ['./view-box-form.component.css'],
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(()=>ViewBoxFormComponent),
      multi: true,
    }
  ],
 viewProviders: [
   { provide: ControlContainer, useExisting: FormGroupDirective }
 ]
})

export class ViewBoxFormComponent implements OnInit {

  constructor() { }

  ngOnInit() {}

  validate(c: AbstractControl): ValidationErrors | null{
    /* ... */
  }
}

As you can see, there is no need to provide CONTROL_VALUE_ACCESSOR anymore, because the form's shape will be defined in only one place(i.e: the parent form container). All you have to do in your child form container is to provide the right paths that correlate to the shape defined in the parent:

view-box-form-component.component.html

<section formGroupName="ViewBoxFormData" class="text-control-section">

    <label class="control-label">

        <p class="smallText"> x: </p>
        <input type="text" class="text-control smallText" formControlName="x" />

    </label>

    <label class="control-label">

        <p class="smallText"> y: </p>
        <input type="y" class="text-control smallText" formControlName="y" />

    </label>

    <label class="control-label">

        <p class="smallText"> width: </p>
        <input type="text" class="text-control smallText" formControlName="width" />

    </label>

    <label class="control-label">

        <p class="smallText"> height: </p>
        <input type="text" class="text-control smallText" formControlName="height" />

    </label>

</section>

What viewProviders does is to let you use a token(in this case ControlContainer) that is declared for the host element:

// FormGroupName

constructor (@Optional() @Host() @SkipSelf() parent: ControlContainer,) {}

Note: the same approach can be applied to FormArrayName.

You can find more about AbstractControl tree and how things work together in A thorough exploration of Angular Forms.


来源: stackexchange

问:
Change speed and position stepper motor in ARDUINO
I am trying to move a certain distance from the motor step by step with a specific speed when i press a button. I am moving the distance without problem, but I cannot change the speed.
I tried with the following instructions

```<code>MOTOR.setseped (speed)
MOTOR.move(DRIVER_PASOS);
</code>```

and

```<code> speed()
 MOTOR.move(DRIVER_PASOS);
</code>```

The motor always move the distance correctly but with a default speed

some suggestions of how I can do it?

答:
I am not totally an expert on this subject.( Stepper motor ) But As far as I know motor speed can control with two basic way one of them voltage the other is current.
You should look your motors current consumption values from datasheet. Also you should check voltage current consumption. And you should ensure that  give motor exactly what it needs.
if you use driver circuit , you should check the switching time and drivers components works properly.
Generally people try to use MCU pins to control motor. But every time it is not right way. You should use driver shield (like these Adafruit Motor/Stepper/Servo Shield for Arduino kit - v1.2) . MCU pins can provide limitted current.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to move a certain distance from the motor step by step with a specific speed when i press a button. I am moving the distance without problem, but I cannot change the speed.
I tried with the following instructions

MOTOR.setseped (speed)
MOTOR.move(DRIVER_PASOS);

and

 speed()
 MOTOR.move(DRIVER_PASOS);

The motor always move the distance correctly but with a default speed

some suggestions of how I can do it?


问:
Exception while implementing LazyModel for primefaces datalist
I am trying to implement the lazy loading model for the primefaces datalist similar to datatable as shown here.

My initial code with the normal AJAX pagination feature works absolutely fine. However, when I try using the lazy loading model, I get the exception below when the page loads :

```<code>com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
SEVERE: Error Rendering View[/pages/index.xhtml]
java.io.NotSerializableException: java.util.ArrayList$SubList
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
    at java.util.HashMap.writeObject(HashMap.java:1100)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:975)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1362)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1170)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
    at java.util.HashMap.writeObject(HashMap.java:1100)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:975)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
    at com.sun.faces.renderkit.ClientSideStateHelper.doWriteState(ClientSideStateHelper.java:325)
    at com.sun.faces.renderkit.ClientSideStateHelper.writeState(ClientSideStateHelper.java:173)
    at com.sun.faces.renderkit.ResponseStateManagerImpl.writeState(ResponseStateManagerImpl.java:122)
    at com.sun.faces.application.StateManagerImpl.writeState(StateManagerImpl.java:166)
    at com.sun.faces.application.view.WriteBehindStateWriter.flushToWriter(WriteBehindStateWriter.java:225)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:418)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
</code>```

Here's the code of index.html

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
   xmlns:ui="http://java.sun.com/jsf/facelets"
   xmlns:h="http://java.sun.com/jsf/html"
   xmlns:f="http://java.sun.com/jsf/core"
   xmlns:p="http://primefaces.org/ui">

<ui:composition template="/pages/templates/template.xhtml">
   <ui:define name="content">

      <h:form prependId="false" id="form">
         <p:dataList value="#{movies.lazyMovieModel}" var="movie" id="movies" paginator="true" rows="10"
            paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
            type="none" paginatorAlwaysVisible="false" lazy="true">

            <h:outputText value="#{movie.movieName}, #{movie.releaseYear}" style="margin-left:10px">
            </h:outputText>
            <br/>
         </p:dataList>
      </h:form>

   </ui:define>
</ui:composition>
</html>
</code>```

MovieListBean.java

```<code>import org.primefaces.model.LazyDataModel;

import com.clixflix.enitities.Movie;
import com.clixflix.jsf.extensions.LazyMovieDataModel;

@ManagedBean(name = "movies")
@ViewScoped
public class MovieListBean extends BaseBean implements Serializable
{
   private static final long serialVersionUID = -5719443344065177588L;

   private LazyDataModel<Movie> lazyMovieModel;

   @PostConstruct
   public void initialize() {
      lazyMovieModel = new LazyMovieDataModel();
   }

   public LazyDataModel<Movie> getLazyMovieModel()
   {
      List<Movie> movieList = getServiceLocator().getMovieService().getMovieList();
      ((LazyMovieDataModel) lazyMovieModel).setMovieList(movieList);
      return lazyMovieModel;
   }
}
</code>```

LazyMovieDataModel.java (LazyModel implementation)

```<code>public class LazyMovieDataModel extends LazyDataModel<Movie>
{
   private static final long serialVersionUID = 8745562148994455749L;

   private List<Movie> movieList;

   public LazyMovieDataModel() {
      this.movieList = Collections.emptyList();
   }

   @Override
   public List<Movie> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
      // Sorting
      if (null != sortField) {
         LazySorter sorter = new LazySorter(sortField, sortOrder);
         Collections.sort(movieList, sorter);
         sorter = null;
      }

      // RowCount
      int rowCount = movieList.size();
      this.setRowCount(rowCount);

      // Pagination
      if (rowCount > pageSize) {
         return movieList.subList(first, (first + pageSize));
      }
      else {
         return movieList;
      }
   }

   private class LazySorter implements Comparator<Movie>
   {
      private String sortField;

      private SortOrder sortOrder;

      LazySorter(String sortField, SortOrder sortOrder) {
         this.sortField = sortField;
         this.sortOrder = sortOrder;
      }

      @SuppressWarnings("unchecked")
      @Override
      public int compare(Movie movie1, Movie movie2) {
         Object value1 = null, value2 = null;

         try {
            value1 = Movie.class.getField(this.sortField).get(movie1);
            value2 = Movie.class.getField(this.sortField).get(movie2);

            int value = ((Comparable<Object>) value1).compareTo(value2);
            return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
         }
         catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
            e.printStackTrace();
            return 0;
         }
      }
   }

   public void setMovieList(List<Movie> movieList) {
      this.movieList = movieList;
   }
}
</code>```

I am assuming the exception is at this line:

```<code>return movieList.subList(first, (first + pageSize));
</code>```

Could anyone please guide me as to what am I missing?

Also, I observe in the logs, that when I use the lazymodel, the DB gets queried three times but when I use the normal AJAX pagination, the DB is queried only once :|

UPDATE: I figured out the reason for the DB being queried 3 times. It was because I was calling my service in the getter of the LazyModel instead of only in the load method.

I made the following changes in the classes:

LazyMovieDataModel.java

```<code>public class LazyMovieDataModel extends LazyDataModel<Movie>
{
   private static final long serialVersionUID = 8745562148994455749L;

   public LazyMovieDataModel() {}

   @Override
   public List<Movie> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {

      List<Movie> movieList = getServiceLocator().getMovieService().getMovieList(first, (first + pageSize));

      // RowCount
      int rowCount = ((Number)getServiceLocator().getMovieService().getMovieCount()).intValue();
      this.setRowCount(rowCount);
   }
}
</code>```

LazyModel getter in MovieListBean.java

```<code>/* Removed PostConstruct init method */

public LazyDataModel<Movie> getLazyMovieModel()
{
   return lazyMovieModel;
}
</code>```

The above changes work fine on the initial page load. However, when I hit the next page button (or any pagination button) I get an NPE for getServiceLocator() in the load method.

The serviceLocator is a protected access modified managed property inherited from BaseBean and injected using Spring.

Any reason why the getter returns null on subsequent invokes ???

答:
Same problem in this link.There are 2 load methods in LazyDataModel:

```<code>public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
    throw new UnsupportedOperationException("Lazy loading is not implemented.");
}

public List<T> load(int first, int pageSize, List<SortMeta> multiSortMeta,Map<String,String> filters) {
    throw new UnsupportedOperationException("Lazy loading is not implemented.");
}
</code>```

This is where the error is thrown. You are using multisort, so you should override the second.Default method is the first one.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to implement the lazy loading model for the primefaces datalist similar to datatable as shown here.

My initial code with the normal AJAX pagination feature works absolutely fine. However, when I try using the lazy loading model, I get the exception below when the page loads :

com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
SEVERE: Error Rendering View[/pages/index.xhtml]
java.io.NotSerializableException: java.util.ArrayList$SubList
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
    at java.util.HashMap.writeObject(HashMap.java:1100)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:975)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1362)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1170)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
    at java.util.HashMap.writeObject(HashMap.java:1100)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:975)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
    at com.sun.faces.renderkit.ClientSideStateHelper.doWriteState(ClientSideStateHelper.java:325)
    at com.sun.faces.renderkit.ClientSideStateHelper.writeState(ClientSideStateHelper.java:173)
    at com.sun.faces.renderkit.ResponseStateManagerImpl.writeState(ResponseStateManagerImpl.java:122)
    at com.sun.faces.application.StateManagerImpl.writeState(StateManagerImpl.java:166)
    at com.sun.faces.application.view.WriteBehindStateWriter.flushToWriter(WriteBehindStateWriter.java:225)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:418)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

Here's the code of index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<ui:composition template="/pages/templates/template.xhtml">
   <ui:define name="content">

      <h:form prependId="false" id="form">

            <h:outputText value="#{movie.movieName}, #{movie.releaseYear}" style="margin-left:10px">
            </h:outputText>

      </h:form>

   </ui:define>
</ui:composition>

MovieListBean.java

import org.primefaces.model.LazyDataModel;

import com.clixflix.enitities.Movie;
import com.clixflix.jsf.extensions.LazyMovieDataModel;

@ManagedBean(name = "movies")
@ViewScoped
public class MovieListBean extends BaseBean implements Serializable
{
   private static final long serialVersionUID = -5719443344065177588L;

   private LazyDataModel<Movie> lazyMovieModel;

   @PostConstruct
   public void initialize() {
      lazyMovieModel = new LazyMovieDataModel();
   }

   public LazyDataModel<Movie> getLazyMovieModel()
   {
      List<Movie> movieList = getServiceLocator().getMovieService().getMovieList();
      ((LazyMovieDataModel) lazyMovieModel).setMovieList(movieList);
      return lazyMovieModel;
   }
}

LazyMovieDataModel.java (LazyModel implementation)

public class LazyMovieDataModel extends LazyDataModel<Movie>
{
   private static final long serialVersionUID = 8745562148994455749L;

   private List<Movie> movieList;

   public LazyMovieDataModel() {
      this.movieList = Collections.emptyList();
   }

   @Override
   public List<Movie> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
      // Sorting
      if (null != sortField) {
         LazySorter sorter = new LazySorter(sortField, sortOrder);
         Collections.sort(movieList, sorter);
         sorter = null;
      }

      // RowCount
      int rowCount = movieList.size();
      this.setRowCount(rowCount);

      // Pagination
      if (rowCount > pageSize) {
         return movieList.subList(first, (first + pageSize));
      }
      else {
         return movieList;
      }
   }

   private class LazySorter implements Comparator<Movie>
   {
      private String sortField;

      private SortOrder sortOrder;

      LazySorter(String sortField, SortOrder sortOrder) {
         this.sortField = sortField;
         this.sortOrder = sortOrder;
      }

      @SuppressWarnings("unchecked")
      @Override
      public int compare(Movie movie1, Movie movie2) {
         Object value1 = null, value2 = null;

         try {
            value1 = Movie.class.getField(this.sortField).get(movie1);
            value2 = Movie.class.getField(this.sortField).get(movie2);

            int value = ((Comparable<Object>) value1).compareTo(value2);
            return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
         }
         catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
            e.printStackTrace();
            return 0;
         }
      }
   }

   public void setMovieList(List<Movie> movieList) {
      this.movieList = movieList;
   }
}

I am assuming the exception is at this line:

return movieList.subList(first, (first + pageSize));

Could anyone please guide me as to what am I missing?

Also, I observe in the logs, that when I use the lazymodel, the DB gets queried three times but when I use the normal AJAX pagination, the DB is queried only once :|

UPDATE: I figured out the reason for the DB being queried 3 times. It was because I was calling my service in the getter of the LazyModel instead of only in the load method.

I made the following changes in the classes:

LazyMovieDataModel.java

public class LazyMovieDataModel extends LazyDataModel<Movie>
{
   private static final long serialVersionUID = 8745562148994455749L;

   public LazyMovieDataModel() {}

   @Override
   public List<Movie> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {

      List<Movie> movieList = getServiceLocator().getMovieService().getMovieList(first, (first + pageSize));

      // RowCount
      int rowCount = ((Number)getServiceLocator().getMovieService().getMovieCount()).intValue();
      this.setRowCount(rowCount);
   }
}

LazyModel getter in MovieListBean.java

/* Removed PostConstruct init method */

public LazyDataModel<Movie> getLazyMovieModel()
{
   return lazyMovieModel;
}

The above changes work fine on the initial page load. However, when I hit the next page button (or any pagination button) I get an NPE for getServiceLocator() in the load method.

The serviceLocator is a protected access modified managed property inherited from BaseBean and injected using Spring.

Any reason why the getter returns null on subsequent invokes ???

Body:
Same problem in this link.There are 2 load methods in LazyDataModel:

public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
    throw new UnsupportedOperationException("Lazy loading is not implemented.");
}

public List<T> load(int first, int pageSize, List<SortMeta> multiSortMeta,Map<String,String> filters) {
    throw new UnsupportedOperationException("Lazy loading is not implemented.");
}

This is where the error is thrown. You are using multisort, so you should override the second.Default method is the first one.


问:
Laravel use condition in query in result
I using laravel as Rest API, I get data from controller:

```<code>$user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address']);
</code>```

result:

```<code>{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null
  }
}
</code>```

Now I want get a secret data, it's national ID, I don't want to include this in json data, just want to detect, if it set, return another data. I want if national id is set,

```<code>$user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address', 'national_id']);
</code>```

result:

```<code>{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null,
    "national_id": 2115 // I don't want this
  }
}
</code>```

Instead want if national id is set, return data like this:

```<code>{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null,
    "verified": true // return this if national id is set
  }
}
</code>```

What I tried:

```<code>  $verified = false;
    $national = User::where('id', $id)
        ->whereNotNull('national_id')
        ->first();
    if($national){
        $verified = true;
    }
    $user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address']);
    $user['verified'] = $verified;
</code>```

But I think it's kinda not clean and don't want to use two query for a simple JSON data, is there a way to do this with one query not two?

答:
Instead you should use resources for the response. You can controll the exact json data you return for a model.
Read more about the resources:

https://laravel.com/docs/6.x/eloquent-resources#writing-resources

Body:
I using laravel as Rest API, I get data from controller:

$user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address']);

result:

{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null
  }
}

Now I want get a secret data, it's national ID, I don't want to include this in json data, just want to detect, if it set, return another data. I want if national id is set,

$user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address', 'national_id']);

result:

{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null,
    "national_id": 2115 // I don't want this
  }
}

Instead want if national id is set, return data like this:

{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null,
    "verified": true // return this if national id is set
  }
}

What I tried:

  $verified = false;
    $national = User::where('id', $id)
        ->whereNotNull('national_id')
        ->first();
    if($national){
        $verified = true;
    }
    $user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address']);
    $user['verified'] = $verified;

But I think it's kinda not clean and don't want to use two query for a simple JSON data, is there a way to do this with one query not two?


问:
How to click OK in alert box using protractor
I am using AngularJS and I want to delete a link, in such cases, an alert box appears to confirm the delete.

I am trying to do e2e test using protractor, how do I confirm in an alert box?

I tried:

```<code>browser.switchTo().alert().accept()
</code>```

but it doesn't seem to work.

Is there a provision in protractor for handling alert boxes?

答:
This thing is wroking fine i have tried it

```<code> await browser.switchTo().alert().accept();
</code>```

Body:
I am using AngularJS and I want to delete a link, in such cases, an alert box appears to confirm the delete.

I am trying to do e2e test using protractor, how do I confirm in an alert box?

I tried:

browser.switchTo().alert().accept()

but it doesn't seem to work.

Is there a provision in protractor for handling alert boxes?

Body:
This thing is wroking fine i have tried it

 await browser.switchTo().alert().accept();


问:
ag-grid hide rows with select all checkbox only works on filtered items
I'm using ag-grid in my angular project. One of my columns uses checkboxes for filtering and has a search bar and a select all checkbox. When the select all box is unchecked when you searched for something, only the items that match the search term are deselected instead of everything.

This question was already asked on github : https://github.com/ag-grid/ag-grid/issues/1559.
Here, the answer was given to set the selectAllOnminiFilter to false. However, in the changelog of ag-grid, it says the selectAllOnMiniFilter property is removed : https://www.ag-grid.com/ag-grid-changelog/ (key: AG-3383)

Is there a way to get this behavior without the selectAllOnminiFilter property?

答:
You should be able to get all nodes using

```<code>forEachNode((node, index))
</code>```

and then uncheck the node.

You could do it using the following

```<code>gridApi.forEachNode(node => node.setSelected(false));
</code>```

According to documentation, this will not ignore any sorted or filtered nodes.

Iterates through each node (row) in the grid and calls the callback
  for each node. This works similar to the 'forEach' method on a
  Javascript array. This is called for every node, ignoring any
  filtering or sorting applied within the grid. If using infinite row
  model, then gets called for each page loaded in the page cache.

Body:
You should be able to get all nodes using

forEachNode((node, index))

and then uncheck the node.

You could do it using the following

gridApi.forEachNode(node => node.setSelected(false));

According to documentation, this will not ignore any sorted or filtered nodes.

Iterates through each node (row) in the grid and calls the callback
  for each node. This works similar to the 'forEach' method on a
  Javascript array. This is called for every node, ignoring any
  filtering or sorting applied within the grid. If using infinite row
  model, then gets called for each page loaded in the page cache.


问:
How to store jQuery datatable show entries value store in variable

How to store Jquery datatable show entries value store in variable

答:
```<code>var table =  $('#example').DataTable();
var pagelenth = table.page.len();
</code>```

you can find the page length by table.page.len();

Body:
var table =  $('#example').DataTable();
var pagelenth = table.page.len();

you can find the page length by table.page.len();


问:
PHP foreach array and compare with GET
I'm trying to resolve my problem.

I store array in json file

I try to foreach array and compare it with my GET arguments

Problem was that only last of array filed works but other not.

auth.json

```<code>[{"License":"21X2-214X-SSDF-3215-SFFA","IP":"111111111","Note":"x1"},{"License":"S31S-SAF3-XF22-SLLT-341D","IP":"1111111","Note":"x2"}]
</code>```

PHP Code

```<code>$license = json_decode(file_get_contents('auth.json'), true);
foreach ($license as $cec) {

        if ($_GET["license"] == $cec["License"] AND $_GET["IP"] == $cec["IP"]){

            $user_auth = array(
            "user_info" => array(

                "auth" => 1
                ),
            );

        }else{
            $user_auth = array(
            "user_info" => array(

                "auth" => 0

                ),
            );
        }

    }
</code>```

答:
Having the if/else within your loop, can lead to clobbering of $user_auth.
Given your example, loop through for your 'needle', and if found set a flag.  Then later use that flag to construt your $user_auth array.

```<code><?php
$json =<<<JSON
[{"License":"21X2-214X-SSDF-3215-SFFA","IP":"111111111","Note":"x1"},{"License":"S31S-SAF3-XF22-SLLT-341D","IP":"1111111","Note":"x2"}]
JSON;

$data    = json_decode($json, true);
$ip      = $_GET['IP']      ?? null;
$license = $_GET['license'] ?? null;
$found   = false;

foreach($data as $item)
    if($item['License'] == $license && $item['IP'] == $ip)
        $found = true;

$user_auth =
    array(
        "user_info" =>
            array(
                "auth" => $found ? 1 : 0
            )
    );

var_dump($user_auth);
</code>```

Output (empty $_GET):

```<code>array(1) {
  ["user_info"]=>
  array(1) {
    ["auth"]=>
    int(0)
  }
}
</code>```

Title: PHP foreach array and compare with GET

Body:
I'm trying to resolve my problem.

I store array in json file

I try to foreach array and compare it with my GET arguments

Problem was that only last of array filed works but other not.

auth.json

[{"License":"21X2-214X-SSDF-3215-SFFA","IP":"111111111","Note":"x1"},{"License":"S31S-SAF3-XF22-SLLT-341D","IP":"1111111","Note":"x2"}]

PHP Code

$license = json_decode(file_get_contents('auth.json'), true);
foreach ($license as $cec) {

        if ($_GET["license"] == $cec["License"] AND $_GET["IP"] == $cec["IP"]){

            $user_auth = array(
            "user_info" => array(

                "auth" => 1
                ),
            );

        }else{
            $user_auth = array(
            "user_info" => array(

                "auth" => 0

                ),
            );
        }

    }

Body:
Having the if/else within your loop, can lead to clobbering of $user_auth.
Given your example, loop through for your 'needle', and if found set a flag.  Then later use that flag to construt your $user_auth array.

<?php
$json =<<<JSON
[{"License":"21X2-214X-SSDF-3215-SFFA","IP":"111111111","Note":"x1"},{"License":"S31S-SAF3-XF22-SLLT-341D","IP":"1111111","Note":"x2"}]
JSON;

$data    = json_decode($json, true);
$ip      = $_GET['IP']      ?? null;
$license = $_GET['license'] ?? null;
$found   = false;

foreach($data as $item)
    if($item['License'] == $license && $item['IP'] == $ip)
        $found = true;

$user_auth =
    array(
        "user_info" =>
            array(
                "auth" => $found ? 1 : 0
            )
    );

var_dump($user_auth);

Output (empty $_GET):

array(1) {
  ["user_info"]=>
  array(1) {
    ["auth"]=>
    int(0)
  }
}


问:
Using Hadoop to update MySQL
I'm using my reducers to input data into MySQL.
My concern is that in some cases, multiple reducers are launched for the same key simultaneously. In that case, there is a chance that the DB could be updated twice by the same data.
Is there a way to protect against that?

Would it make sense to turn off autocommit mode in the SQL connection in this case?

答: I think this situation has nothing to done with autocommits. If they are not too much and do not cost a considerable amount of overhead, then ignore them because they won't break up the consistency. All your reducers are doing to execute SQL queries, how can you prevent them to execute queries for the same keys? I think you should solve this issue in your mapreduce function, because this is not a case that DBMS can handle since all it does is to execute given query in the database.</p>

Title: Using Hadoop to update MySQL


问:
Switch case in order to check if string contains a substring
I have a string and want to check if there is a substring with switch/case. The fnstringCheck returns true for example if the fnstring is dies_ist_ein_test_diagnosen_erfassen.

What's going wrong? Thanks for your hints

```<code> var fnstring = (interim_transcript).toLowerCase().replace(/ /gi, "_");

 console.log('fnstring:', fnstring)
 var fnstringCheck = fnstring.indexOf("diagnosen_erfassen") !== -1;
 console.log(fnstringCheck)

 switch (fnstring) {
    case (fnstring.indexOf("_arztbrief_analysieren") !== -1):
        $('.analyzesBtn').trigger('click');
        break;

    case (fnstring.indexOf("_einleitung_erfassen") !== -1):
        changeSection('einleitung', mergedSource);
        break;

    case (fnstring.indexOf("diagnosen_erfassen") !== -1):
         changeSection('einleitung', mergedSource);
         break;

        ...
</code>```

答:
When you use switch statement, the expression in the switch is evaluated and compared to the values in the cases in order to decide which is the case statement that should be executed. See the documentation here.

In your case, the switch statement has a string expression, but your cases are evaluating to true or false, so none of them matches.

In my opinion, it would look more natural to express your logic with if-else checks:

```<code>if (fnstring.indexOf("_arztbrief_analysieren") !== -1) {
    $('.analyzesBtn').trigger('click');
} else if (fnstring.indexOf("_einleitung_erfassen") !== -1) {
    changeSection('einleitung', mergedSource);
} else if (fnstring.indexOf("diagnosen_erfassen") !== -1) {
    changeSection('einleitung', mergedSource);
}
</code>```

Body:
I have a string and want to check if there is a substring with switch/case. The fnstringCheck returns true for example if the fnstring is dies_ist_ein_test_diagnosen_erfassen.

What's going wrong? Thanks for your hints

 var fnstring = (interim_transcript).toLowerCase().replace(/ /gi, "_");

 console.log('fnstring:', fnstring)
 var fnstringCheck = fnstring.indexOf("diagnosen_erfassen") !== -1;
 console.log(fnstringCheck)

 switch (fnstring) {
    case (fnstring.indexOf("_arztbrief_analysieren") !== -1):
        $('.analyzesBtn').trigger('click');
        break;

    case (fnstring.indexOf("_einleitung_erfassen") !== -1):
        changeSection('einleitung', mergedSource);
        break;

    case (fnstring.indexOf("diagnosen_erfassen") !== -1):
         changeSection('einleitung', mergedSource);
         break;

        ...

Body:
When you use switch statement, the expression in the switch is evaluated and compared to the values in the cases in order to decide which is the case statement that should be executed. See the documentation here.

In your case, the switch statement has a string expression, but your cases are evaluating to true or false, so none of them matches.

In my opinion, it would look more natural to express your logic with if-else checks:

if (fnstring.indexOf("_arztbrief_analysieren") !== -1) {
    $('.analyzesBtn').trigger('click');
} else if (fnstring.indexOf("_einleitung_erfassen") !== -1) {
    changeSection('einleitung', mergedSource);
} else if (fnstring.indexOf("diagnosen_erfassen") !== -1) {
    changeSection('einleitung', mergedSource);
}


问:
Woocommerce Shipping Calculation Logic

The plot:

I am working with a Dropshipping company that has an API for providing products, the shipping is calculated this way:

Every product comes with a shipping size ( S,M,L ... ) and for each country this sizes have different fixed prices. I am saving this shipping size in a custom meta.

Example:

France

Size M: 10$

Size L: 15$

Spain

Size M: 15$

Size L: 20$

The problem:

I cannot seem to figure out a way of implementing this into woocommerce. I see that I can setup a flat rate for each country but I cannot implement these different sizes.

If this is not possible with plain Woocommerce, I want to implement something myself with php or I am also open to any official/verified Add-ons.

答: I figured out this on my own - so apparently I can make a shipping class for each of those sizes ( S, M, L ) and then I can setup Flat Rates by country and shipping class. This was very easy after all, no custom code required.</p>

Title: Woocommerce Shipping Calculation Logic


问:
How to generate a list with only two 1s and other 0s of the given length?
I have to generate lists that consist of 2 '1's and other elements are '0's. I tried the following code but it does not work:

```<code>count([], _, 0).
count([X|T], X, Y) :- count(T, X, Z), Y is 1+Z.
count([X1|T],X,Z):- X1\=X,count(T,X,Z).

two(X) :- count(X, 1, Counter), Counter =:= 2.
</code>```

Querying length(Vs, 4), Vs ins 0..1, two(Vs). gives nothing.

How to generate such lists properly?
I expect to get something like [1, 1, 0, 0], [1, 0, 1, 0] ... [0, 0, 1, 1].

答:
I think you are making it too complicated here. Instead of using clpfd here, you can just make a predicate that generates such lists.

We can first make a predicate that unifies with all lists that contain only 0s:

```<code>all0([]).
all0([0|T]) :-
    all0(T).
</code>```

next we can make a predicate with1s(N, l) that will "inject" N ones in a list it generates:

```<code>with1s(0, L) :-
    all0(L).
with1s(N, [H|T]) :-
    N > 0,
    ((H=1, N1 is N-1);
     (H=0, N1 = N)),
    with1s(N1, T).
</code>```

So for example for a list of three elements, we get:

```<code>?- L = [_,_,_], with1s(2, L).
L = [1, 1, 0] ;
L = [1, 0, 1] ;
L = [0, 1, 1] ;
false.
</code>```

This of course does not work bidirectional, I leave it as an exercise to further improve the predicate.

Body:
I have to generate lists that consist of 2 '1's and other elements are '0's. I tried the following code but it does not work:

count([], _, 0).
count([X|T], X, Y) :- count(T, X, Z), Y is 1+Z.
count([X1|T],X,Z):- X1\=X,count(T,X,Z).

two(X) :- count(X, 1, Counter), Counter =:= 2.

Querying length(Vs, 4), Vs ins 0..1, two(Vs). gives nothing.

How to generate such lists properly?
I expect to get something like [1, 1, 0, 0], [1, 0, 1, 0] ... [0, 0, 1, 1].

Body:
I think you are making it too complicated here. Instead of using clpfd here, you can just make a predicate that generates such lists.

We can first make a predicate that unifies with all lists that contain only 0s:

all0([]).
all0([0|T]) :-
    all0(T).

next we can make a predicate with1s(N, l) that will "inject" N ones in a list it generates:

with1s(0, L) :-
    all0(L).
with1s(N, [H|T]) :-
    N > 0,
    ((H=1, N1 is N-1);
     (H=0, N1 = N)),
    with1s(N1, T).

So for example for a list of three elements, we get:

?- L = [_,_,_], with1s(2, L).
L = [1, 1, 0] ;
L = [1, 0, 1] ;
L = [0, 1, 1] ;
false.

This of course does not work bidirectional, I leave it as an exercise to further improve the predicate.


问:
if statement, boolean value
This method is taken from Murach's C# 2010 book and is given as an example of an method that checks if a string contains a decimal value:

```<code>        // the new IsDecimal method
    public bool IsDecimal(TextBox textBox, string name)
    {
        //make sure the string only contains numbers and numeric formatting
        string s = textBox.Text;
        int decimalCount = 0;
        bool validDecimal = true;
        foreach (char c in s)
        {
            if (!(
                c == '0' || c == '1' || c == '2' ||   // numeric chars
                c == '3' || c == '4' || c == '5' ||
                c == '6' || c == '7' || c == '8' ||
                c == '9' || c == '.' ||
                c == '$' || c == '%' || c == ',' ||  // formatting chars
                c == ' '
                ))
            {
                validDecimal = false;
                break;
            }
            if (c == '.')
            {
                decimalCount++;
            }
        } // end loop

        if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
        else
        {
            MessageBox.Show(name + " must be a decimal number.",
                "Entry Error");
            textBox.Focus();
            return false;
        }
    }
</code>```

My question is about this if statement and boolean value:

```<code>            if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
</code>```

I understand that it should be checking if both validDecimal returns true from above loop and that there is only one decimal point present. I'm quite confused by this, my understanding of bool is that it can hold two values: 1 = true and 0 = false; in both of those cases that if statement would be satisfied (0 is smaller than 1 and 1 is equal). I'm thinking that correct if statement would look something like that: if (validDecimal == true && decimalCount <= 1) but since I'm beginner I'm not sure and this isn't in the errata for this book.

答:
I don't really know in c#, but in Java, you can even do this:

```<code>boolean b = 1<2;
</code>```

1<2 is true (remember, it's a boolean equation), so the value assigned to b is true. Everything you put in the if, is interpreted as

```<code>if(whateverLogicEquationHereIsTrue){do this}
else{means that the boolean input to the if, has come to be false}
</code>```

now, what is the output of this?

```<code>if(!(1>2)){print "a"}
else{print "b"}
</code>```

hint: ! is the logical operator NOT

Title: if statement, boolean value

Body:
This method is taken from Murach's C# 2010 book and is given as an example of an method that checks if a string contains a decimal value:

        // the new IsDecimal method
    public bool IsDecimal(TextBox textBox, string name)
    {
        //make sure the string only contains numbers and numeric formatting
        string s = textBox.Text;
        int decimalCount = 0;
        bool validDecimal = true;
        foreach (char c in s)
        {
            if (!(
                c == '0' || c == '1' || c == '2' ||   // numeric chars
                c == '3' || c == '4' || c == '5' ||
                c == '6' || c == '7' || c == '8' ||
                c == '9' || c == '.' ||
                c == '$' || c == '%' || c == ',' ||  // formatting chars
                c == ' '
                ))
            {
                validDecimal = false;
                break;
            }
            if (c == '.')
            {
                decimalCount++;
            }
        } // end loop

        if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
        else
        {
            MessageBox.Show(name + " must be a decimal number.",
                "Entry Error");
            textBox.Focus();
            return false;
        }
    }

My question is about this if statement and boolean value:

            if (validDecimal && decimalCount <= 1)
        {
            return true;
        }

I understand that it should be checking if both validDecimal returns true from above loop and that there is only one decimal point present. I'm quite confused by this, my understanding of bool is that it can hold two values: 1 = true and 0 = false; in both of those cases that if statement would be satisfied (0 is smaller than 1 and 1 is equal). I'm thinking that correct if statement would look something like that: if (validDecimal == true && decimalCount <= 1) but since I'm beginner I'm not sure and this isn't in the errata for this book.

Body:
I don't really know in c#, but in Java, you can even do this:

boolean b = 1<2;

1<2 is true (remember, it's a boolean equation), so the value assigned to b is true. Everything you put in the if, is interpreted as

if(whateverLogicEquationHereIsTrue){do this}
else{means that the boolean input to the if, has come to be false}

now, what is the output of this?

if(!(1>2)){print "a"}
else{print "b"}

hint: ! is the logical operator NOT


问:
Background color stays transparent, though devtools says it's white
Background color of the first paragraph on the main-content of my Drupal website stays transparent, though it is defined as white in the CSS, and even Devtools says it's white... it sounds noobish and so simple, yet I can't figure out what I'm doing wrong.

HTML:

...

```

<p>CSS:</p>

<pre class="lang-css prettyprint-override"><code>.region--white-background {
    background-color: #ffffff;
}
</code>```

答:
I found it at random!

It was a bug created by Drupal's appear on scroll animations. Javascript was disabling my background color after CSS created it. I had to to to appearance -> setings -> animations -> select "none" for the region called "main-content"

Body:
Background color of the first paragraph on the main-content of my Drupal website stays transparent, though it is defined as white in the CSS, and even Devtools says it's white... it sounds noobish and so simple, yet I can't figure out what I'm doing wrong.

HTML:

...

CSS:

.region--white-background {
    background-color: #ffffff;
}


问:
How can I execute a function when Flask app ends?
I am building a Flask app and was wondering how can I tell it to do a function when the user clicks "Ctrl + C or X" basically when they end the application. For this example, let's say I just want it to open a file and write "done" to it. Is this possible?</p>

答:
The way the program is terminated is through signals sent by your system. Two examples of signals are SIGKILL which corresponds to kill -9 and SIGINT which corresponds to pressing ctrl + c.

You have a built-in library in Python called signals though which you could play around with signals in Unix/Linux.

Simply import the library using import signals and then write a simple callback function that runs whenever the registered signal is received.

Example of signal handler function:

```<code>def receiveSignal(signalNumber, frame):
print('Received:', signalNumber)
return
</code>```

Example of registering signals

```<code>signal.signal(signal. SIGKILL, receiveSignal)
signal.signal(signal.SIGINT, receiveSignal)
</code>```

Now, whenever your program received the registered signals, the receiveSignal function is called and you could handle the task of writing to the file and then exiting over there.

The example above is taken from StackAbuse and you could find the complete example here

Body:
The way the program is terminated is through signals sent by your system. Two examples of signals are SIGKILL which corresponds to kill -9 and SIGINT which corresponds to pressing ctrl + c.

You have a built-in library in Python called signals though which you could play around with signals in Unix/Linux.

Simply import the library using import signals and then write a simple callback function that runs whenever the registered signal is received.

Example of signal handler function:

def receiveSignal(signalNumber, frame):
print('Received:', signalNumber)
return

Example of registering signals

signal.signal(signal. SIGKILL, receiveSignal)
signal.signal(signal.SIGINT, receiveSignal)

Now, whenever your program received the registered signals, the receiveSignal function is called and you could handle the task of writing to the file and then exiting over there.

The example above is taken from StackAbuse and you could find the complete example here


问:
How to add interval to subscribed date in join table
I have 2 tables transaction,plan so I am getting subscribed users data by joining these two table and at the same time I want to add plan_validity column as interval with subscription date to check whether validity is completed or  not ,but  while adding interval  it is showing error unexpected date_interval near '))' so how to add interval to subscription date of user.

```<code>transaction table

id    user id  plan_id   subscription_date

1        1       1       2019-06-08

2        2       3       2019-07-05

plan table

id    plan_validity

1      3 month

2      6  month

3      9 month
</code>```

mysql query:

```<code>select tr.*,t.subscription_date,DATE_ADD(t.subscription_date, INTERVAL  p.plan_validity)
from transaction t inner join plan p on t.plan_id=plan.id  where t.user_id=1
</code>```

答:
Try with a CASE expression that checks the type of interval that you want to add:

```<code>select t.*,
  case
    when p.plan_validity like '%month'
      then date_add(t.subscription_date, interval p.plan_validity month)
    when p.plan_validity like '%year'
      then date_add(t.subscription_date, interval p.plan_validity year)
  end result
from transaction t inner join plan p
on t.plan_id = p.id
where t.user_id = 1
</code>```

See the demo.

Results:

```<code>| id  | user_id | plan_id | subscription_date   | result     |
| --- | ------- | ------- | ------------------- | -----------|
| 1   | 1       | 1       | 2019-06-08          | 2019-09-08 |
</code>```

Body:
I have 2 tables transaction,plan so I am getting subscribed users data by joining these two table and at the same time I want to add plan_validity column as interval with subscription date to check whether validity is completed or  not ,but  while adding interval  it is showing error unexpected date_interval near '))' so how to add interval to subscription date of user.

transaction table

id    user id  plan_id   subscription_date

1        1       1       2019-06-08

2        2       3       2019-07-05

plan table

id    plan_validity

1      3 month

2      6  month

3      9 month

mysql query:

select tr.*,t.subscription_date,DATE_ADD(t.subscription_date, INTERVAL  p.plan_validity)
from transaction t inner join plan p on t.plan_id=plan.id  where t.user_id=1

Body:
Try with a CASE expression that checks the type of interval that you want to add:

select t.*,
  case
    when p.plan_validity like '%month'
      then date_add(t.subscription_date, interval p.plan_validity month)
    when p.plan_validity like '%year'
      then date_add(t.subscription_date, interval p.plan_validity year)
  end result
from transaction t inner join plan p
on t.plan_id = p.id
where t.user_id = 1

See the demo.

Results:

| id  | user_id | plan_id | subscription_date   | result     |
| --- | ------- | ------- | ------------------- | -----------|
| 1   | 1       | 1       | 2019-06-08          | 2019-09-08 |


答: put the div with "region region-content" class white background and it works!</p>

Title: Background color stays transparent, though devtools says it's white


问:
How to Customise default Alert in xamarin forms
I am trying to change the colour of Alert Buttons.

my alert like below.

```<code>await DisplayAlert("Question?", "Would you like to play a game", "Yes", "No");
</code>```

I need to make Yes button Red both Android and iOS.

I need to get default alert view for both platform rather than creating a custom pop up.

is there any way to write a renderer for this?

答:
Hello man hope to get nice day

in iOS you need to use MessageCenter wherever you need to display Dailog and subscribe it in ApprDelegate as following:

```<code>        UIAlertController vc = UIAlertController.Create("", titleWeSendFromMessageCenterArgs, UIAlertControllerStyle.Alert);
        UIAlertAction action = UIAlertAction.Create("OK", UIAlertActionStyle.Default, null);
        vc.AddAction(action);

        vc.View.TintColor = UIColor.Red;//or whatever you want

        Window.RootViewController.PresentViewController(vc, true, null);
</code>```

in Android you just change colorAccent in you style file in resource
hope to be useful.

Body:
I am trying to change the colour of Alert Buttons.

my alert like below.

await DisplayAlert("Question?", "Would you like to play a game", "Yes", "No");

I need to make Yes button Red both Android and iOS.

I need to get default alert view for both platform rather than creating a custom pop up.

is there any way to write a renderer for this?

Body:
Hello man hope to get nice day

in iOS you need to use MessageCenter wherever you need to display Dailog and subscribe it in ApprDelegate as following:

        UIAlertController vc = UIAlertController.Create("", titleWeSendFromMessageCenterArgs, UIAlertControllerStyle.Alert);
        UIAlertAction action = UIAlertAction.Create("OK", UIAlertActionStyle.Default, null);
        vc.AddAction(action);

        vc.View.TintColor = UIColor.Red;//or whatever you want

        Window.RootViewController.PresentViewController(vc, true, null);

in Android you just change colorAccent in you style file in resource
hope to be useful.


问:
How to run PHP code inside Advanced Text Widget WordPress
I have this code which should return a list of posts in wordpress. I added this code inside the Advanced Text Widget which supports PHP but I can't get it to work.

```<code><?php
// the query
$the_query = new WP_Query( array(
'post_type' => 'posts',
'posts_per_page' => 5,
));
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<div class="col-md-12">
    <div class="pgsgrid">
   <div class="col-md-3 col-xs-12 col-lg-3 col-sm-6 animated wow fadeInUp animated" data-wow-
delay=".5s" data-wow-offset="5" style="visibility: visible; animation-delay: 0.5s; animation-name:
fadeInUp;">
      <div class="hupjik">
      <img src="<?php echo get_the_post_thumbnail_url(); ?>" alt="pgs" class="img-responsive">
        <div class="medianews">
          <p><?php echo get_the_date(); ?></p>
                             <p><?php the_excerpt(); ?></p>

           <p> <a href="<?php echo the_permalink(); ?>" style="color:#ea6224">Read More ></a></p>
        </div>

        </div>
    </div>

    </div>
</code>```

答:
Text widget doesn't support PHP code but you can able to run your PHP Codes using Shortcode.

Use this code to function.php for creating a shortcode:

```<code>function custom_post_widget(){
    // the query
    $the_query = new WP_Query( array(
        'post_type' => 'post',
        'posts_per_page' => 5,
    ));
    ob_start();
    ?>
    <?php if ( $the_query->have_posts() ) : ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

    <div class="col-md-12">
        <div class="pgsgrid">
            <div class="col-md-3 col-xs-12 col-lg-3 col-sm-6 animated wow fadeInUp animated" data-wow- delay=".5s" data-wow-offset="5" style="visibility: visible; animation-delay: 0.5s; animation-name: fadeInUp;">
                <div class="hupjik">
                    <img src="<?php echo get_the_post_thumbnail_url(); ?>" alt="pgs" class="img-responsive">
                    <div class="medianews">
                        <p>
                            <?php echo get_the_date(); ?>
                        </p>
                        <p>
                            <?php the_excerpt(); ?>
                        </p>

                        <p> <a href="<?php echo the_permalink(); ?>" style="color:#ea6224">Read More ></a></p>
                    </div>

                </div>
            </div>

        </div>
    </div>
    <?php
    endwhile;
    endif;

    return ob_get_clean();
}
add_shortcode( 'custom_post_widget', 'custom_post_widget' );
</code>```

Then use this code to your text widget: [custom_post_widget]

I tested and works.

Body:
I have this code which should return a list of posts in wordpress. I added this code inside the Advanced Text Widget which supports PHP but I can't get it to work.

<?php
// the query
$the_query = new WP_Query( array(
'post_type' => 'posts',
'posts_per_page' => 5,
));
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

      <img src="<?php echo get_the_post_thumbnail_url(); ?>" alt="pgs" class="img-responsive">

<?php echo get_the_date(); ?>

<?php the_excerpt(); ?>

 <a href="<?php echo the_permalink(); ?>" style="color:#ea6224">Read More >

Body:
Text widget doesn't support PHP code but you can able to run your PHP Codes using Shortcode.

Use this code to function.php for creating a shortcode:

function custom_post_widget(){
    // the query
    $the_query = new WP_Query( array(
        'post_type' => 'post',
        'posts_per_page' => 5,
    ));
    ob_start();
    ?>
    <?php if ( $the_query->have_posts() ) : ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

    <div class="col-md-12">
        <div class="pgsgrid">
            <div class="col-md-3 col-xs-12 col-lg-3 col-sm-6 animated wow fadeInUp animated" data-wow- delay=".5s" data-wow-offset="5" style="visibility: visible; animation-delay: 0.5s; animation-name: fadeInUp;">
                <div class="hupjik">
                    <img src="<?php echo get_the_post_thumbnail_url(); ?>" alt="pgs" class="img-responsive">
                    <div class="medianews">
                        <p>
                            <?php echo get_the_date(); ?>
                        </p>
                        <p>
                            <?php the_excerpt(); ?>
                        </p>

                        <p> <a href="<?php echo the_permalink(); ?>" style="color:#ea6224">Read More &gt;</a></p>
                    </div>

                </div>
            </div>

        </div>
    </div>
    <?php
    endwhile;
    endif;

    return ob_get_clean();
}
add_shortcode( 'custom_post_widget', 'custom_post_widget' );

Then use this code to your text widget: [custom_post_widget]

I tested and works.


问:
Check textfield text while editing
I have a textField which looks like this:

I would like to keep track of what the user is typing in. If the text inputs matches one of the criteria below the textfield the "x" should change to a "checkImage".

I already have a TextFieldDidChange method for this:

```<code>@objc func passwordTextFieldDidChange(_ textField: UITextField) {
        if textField.text == "" {
            self.eyeButton.isHidden = true
        }else {
            self.eyeButton.isHidden = false
        }

}
</code>```

Problem:

How do I check a text for:
1. at least 1 uppercase letter + 1 lowercase letter
2. at least 1 digit
3. at least length 8

I also check the password strength afterwards with this method:

```<code>static func isPasswordValid(_ password : String) -> Bool {

    /*
    ^                         Start anchor
    (?=.*[A-Z].*[A-Z])        Ensure string has two uppercase letters.
    (?=.*[!@#$&*])            Ensure string has one special case letter.
    (?=.*[0-9].*[0-9])        Ensure string has two digits.
    (?=.*[a-z].*[a-z].*[a-z]) Ensure string has three lowercase letters.
    .{8}                      Ensure string is of length 8.
    $                         End anchor.
    */

    let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[A-Z]).(?=.*[0-9]).(?=.*[a-z]).{8,}$")
    return passwordTest.evaluate(with: password)
}
</code>```

But the user should also get "realtime" feedback wether or not is password is matching the 3 criteria.

Let me know if my question if unclear or if you need some more info. Grateful for every help :)

答:
That's a tricky one, but you're on the right track.

I also check the password strength afterwards with this method

It's not clear when you are calling isPasswordValid(:) but this needs to be done after the text field changes, ideally in the passwordTextFieldDidChange(:) function.

Bonus: You can move the updating of the eye button into a separate function to aid in readability.

```<code>@objc func passwordTextFieldDidChange(_ textField: UITextField) {
    self.updateEyeButton(show: !textField.isEmpty)
    self.validate(password: textField.text)
}
</code>```

There are a lot of different ways you can accomplish this task but this one should be pretty self explanatory, feel free to ask if you need further clarification.

You will need to separate the validation of each of your requirements.  In your current isPasswordValid(:) function, you check all the requirements together, which makes it impossible to determine which one passed/failed.

What you can do is create a separate struct to validate the requirements, in this case we named it PasswordValidator. This struct validates whether a given password matches your requirements and if not, returns the missing requirements to you.  Once you have an array of the missing requirements, you can act on each one (in your case changing the icon for each one).

Something like this (untested):

```<code>private struct PasswordValidator {

     private enum Result {
        case valid
        case invalid([Validator.Requirement])
     }

     private enum Requirement: String {
         case minimumOneUppercaseOneLowercase = "(?=.*[A-Z]).(?=.*[a-z])"
         case minimumOneDigit = "(?=.*[0-9])"
     }

      static func validate(password: String) -> PasswordValidator.Result {

          let missingRequirements = [Requirement]()

          if !evaluate(password: password, requirement: .minimumOneUppercaseOneLowercase) {
              missingRequirements.append(.minimumOneUppercaseOneLowercase)
          }

          if !evaluate(password: password, requirement: .minimumOneDigit) {
              missingRequirements.append(.minimumOneDigit)
          }

          if missingRequirements.isEmpty == false {
              return .invalid(missingRequirements)
          }

          return .valid
      }

      private static func evaluate(password: String, requirement: PasswordValidator.Requirement) -> Bool {
          let predicateString = "^\(requirement.rawValue)$"
          let passwordTest = NSPredicate(format: "SELF MATCHES %@", predicateString)
          return passwordTest.evaluate(with: password)
      }
  }
</code>```

As you can see each of the PasswordValidator.Requirement enum cases have an associated value containing the predicate (very untested!)

Now in your view controller, you can have a simple function to handle the validation result (called from your passwordTextFieldDidChange(:) function:

```<code>private func validate(password: String) {

        let validationResult = PasswordValidator.validate(password: password)

        switch validationResult {
        case .valid:
            // All should be checkmarks
            // self.updateIcons(missingRequirements: nil)
        case .invalid(let missingRequirements):
            // Change the icons
            // self.updateIcons(missingRequirements: missingRequirements)
        }
    }
</code>```

Title: Check textfield text while editing

Body:
I have a textField which looks like this:

I would like to keep track of what the user is typing in. If the text inputs matches one of the criteria below the textfield the "x" should change to a "checkImage".

I already have a TextFieldDidChange method for this:

@objc func passwordTextFieldDidChange(_ textField: UITextField) {
        if textField.text == "" {
            self.eyeButton.isHidden = true
        }else {
            self.eyeButton.isHidden = false
        }

}

Problem:

How do I check a text for:
1. at least 1 uppercase letter + 1 lowercase letter
2. at least 1 digit
3. at least length 8

I also check the password strength afterwards with this method:

static func isPasswordValid(_ password : String) -> Bool {

    /*
    ^                         Start anchor
    (?=.*[A-Z].*[A-Z])        Ensure string has two uppercase letters.
    (?=.*[!@#$&*])            Ensure string has one special case letter.
    (?=.*[0-9].*[0-9])        Ensure string has two digits.
    (?=.*[a-z].*[a-z].*[a-z]) Ensure string has three lowercase letters.
    .{8}                      Ensure string is of length 8.
    $                         End anchor.
    */

    let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[A-Z]).(?=.*[0-9]).(?=.*[a-z]).{8,}$")
    return passwordTest.evaluate(with: password)
}

But the user should also get "realtime" feedback wether or not is password is matching the 3 criteria.

Let me know if my question if unclear or if you need some more info. Grateful for every help :)

Body:
That's a tricky one, but you're on the right track.

I also check the password strength afterwards with this method

It's not clear when you are calling isPasswordValid(:) but this needs to be done after the text field changes, ideally in the passwordTextFieldDidChange(:) function.

Bonus: You can move the updating of the eye button into a separate function to aid in readability.

@objc func passwordTextFieldDidChange(_ textField: UITextField) {
    self.updateEyeButton(show: !textField.isEmpty)
    self.validate(password: textField.text)
}

There are a lot of different ways you can accomplish this task but this one should be pretty self explanatory, feel free to ask if you need further clarification.

You will need to separate the validation of each of your requirements.  In your current isPasswordValid(:) function, you check all the requirements together, which makes it impossible to determine which one passed/failed.

What you can do is create a separate struct to validate the requirements, in this case we named it PasswordValidator. This struct validates whether a given password matches your requirements and if not, returns the missing requirements to you.  Once you have an array of the missing requirements, you can act on each one (in your case changing the icon for each one).

Something like this (untested):

private struct PasswordValidator {

     private enum Result {
        case valid
        case invalid([Validator.Requirement])
     }

     private enum Requirement: String {
         case minimumOneUppercaseOneLowercase = "(?=.*[A-Z]).(?=.*[a-z])"
         case minimumOneDigit = "(?=.*[0-9])"
     }

      static func validate(password: String) -> PasswordValidator.Result {

          let missingRequirements = [Requirement]()

          if !evaluate(password: password, requirement: .minimumOneUppercaseOneLowercase) {
              missingRequirements.append(.minimumOneUppercaseOneLowercase)
          }

          if !evaluate(password: password, requirement: .minimumOneDigit) {
              missingRequirements.append(.minimumOneDigit)
          }

          if missingRequirements.isEmpty == false {
              return .invalid(missingRequirements)
          }

          return .valid
      }

      private static func evaluate(password: String, requirement: PasswordValidator.Requirement) -> Bool {
          let predicateString = "^\(requirement.rawValue)$"
          let passwordTest = NSPredicate(format: "SELF MATCHES %@", predicateString)
          return passwordTest.evaluate(with: password)
      }
  }

As you can see each of the PasswordValidator.Requirement enum cases have an associated value containing the predicate (very untested!)

Now in your view controller, you can have a simple function to handle the validation result (called from your passwordTextFieldDidChange(:) function:

private func validate(password: String) {

        let validationResult = PasswordValidator.validate(password: password)

        switch validationResult {
        case .valid:
            // All should be checkmarks
            // self.updateIcons(missingRequirements: nil)
        case .invalid(let missingRequirements):
            // Change the icons
            // self.updateIcons(missingRequirements: missingRequirements)
        }
    }


问:
How to find values that aren't 100% duplicated?
I have a list of people getting aid from my organization.

Some register their names with different spelling or different order.

Here is an example

```<code>**Names**                       **ID**
Ahmed mohammed Saleh            3576158946          Personal ID
Waleed Khalid Ali               5478698645          Personal ID
Fatima Nader Aljalal            4684325986          Personal ID
Hussan Huessien Ahmed           778569              Family ID
*Ahmed Mohamed Salah*           698745              Family ID
*Waleed Ali Khalid*             No ID
</code>```

The last two in the list have registered twice.

My data has 4000 rows and I have to find the partial duplicates.

答:
One way to reduce the difficulty of the task is to hash the names to a sorted string of lowercase characters with duplicate characters, spaces and vowels removed.  You could then compare the hashed names to determine similarity.  In the example below we are fortunate that we get exact matches but it would not be impossible to write a further function that checked if the hashed names differed by one, two or more characters, and in fact that the original names were a reasonable match.

```<code>Option Explicit

Private Type State

    CharArray As Variant

End Type

Private s As State

Public Sub test()

    Initialise
    Debug.Print "Ahmed mohammed Saleh", ConvertNameToHash("Ahmed mohammed Saleh")
    Debug.Print "Ahmed Mohamed Salah", ConvertNameToHash("Ahmed Mohamed Salah")
    Debug.Print "Waleed Khalid Ali", ConvertNameToHash("Waleed Khalid Ali")
    Debug.Print "Waleed Ali Khalid", ConvertNameToHash("Waleed Ali Khalid")
End Sub

Public Sub Initialise()

    s.CharArray = Split("b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z", ",")

End Sub

Public Function ConvertNameToHash(ByVal ipName As String) As String

    Dim myChars As String
    Dim myName As String

    myName = LCase$(ipName)
    Dim myChar As Variant
    For Each myChar In s.CharArray

        If InStr(myName, myChar) > 0 Then

            myChars = myChars & myChar

        End If

    Next

    ConvertNameToHash = myChars

End Function
</code>```

The output from the above code was

```<code>Ahmed mohammed Saleh        dhlms
Ahmed Mohamed Salah         dhlms
Waleed Khalid Ali           dhklw
Waleed Ali Khalid           dhklw
</code>```

Body:
I have a list of people getting aid from my organization.

Some register their names with different spelling or different order.

Here is an example

**Names**                       **ID**
Ahmed mohammed Saleh            3576158946          Personal ID
Waleed Khalid Ali               5478698645          Personal ID
Fatima Nader Aljalal            4684325986          Personal ID
Hussan Huessien Ahmed           778569              Family ID
*Ahmed Mohamed Salah*           698745              Family ID
*Waleed Ali Khalid*             No ID

The last two in the list have registered twice.

My data has 4000 rows and I have to find the partial duplicates.

Body:
One way to reduce the difficulty of the task is to hash the names to a sorted string of lowercase characters with duplicate characters, spaces and vowels removed.  You could then compare the hashed names to determine similarity.  In the example below we are fortunate that we get exact matches but it would not be impossible to write a further function that checked if the hashed names differed by one, two or more characters, and in fact that the original names were a reasonable match.

Option Explicit

Private Type State

    CharArray As Variant

End Type

Private s As State

Public Sub test()

    Initialise
    Debug.Print "Ahmed mohammed Saleh", ConvertNameToHash("Ahmed mohammed Saleh")
    Debug.Print "Ahmed Mohamed Salah", ConvertNameToHash("Ahmed Mohamed Salah")
    Debug.Print "Waleed Khalid Ali", ConvertNameToHash("Waleed Khalid Ali")
    Debug.Print "Waleed Ali Khalid", ConvertNameToHash("Waleed Ali Khalid")
End Sub

Public Sub Initialise()

    s.CharArray = Split("b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z", ",")

End Sub

Public Function ConvertNameToHash(ByVal ipName As String) As String

    Dim myChars As String
    Dim myName As String

    myName = LCase$(ipName)
    Dim myChar As Variant
    For Each myChar In s.CharArray

        If InStr(myName, myChar) > 0 Then

            myChars = myChars & myChar

        End If

    Next

    ConvertNameToHash = myChars

End Function

The output from the above code was

Ahmed mohammed Saleh        dhlms
Ahmed Mohamed Salah         dhlms
Waleed Khalid Ali           dhklw
Waleed Ali Khalid           dhklw


问:
Loopback 4 - Mongo and Elastic data synchronization
Is there an easy way to sync MongoDB data with Elastic if we are using a Loopback 4 application? (In a NodeJS Express application we can easily do this using mongoosastic plugin.)

Currently in loopback a model is bound to one data source which is either a mongo or elastic. My ultimate goal is to write POST, PUT, DELETE methods in mongo (and replicate in elastic) and GET methods to use Elastic as datasource.

答:
I would highly recommend to decouple the syncoronization part from the core routes of your application. You could leverage the MongoDB Change streams to listen for change and update your elasticsearch. This could be a simple app running on a totally different server which does the syncronization while you carry on serving your requests. This will make the overall process and architecture more durable and fault tolerant. You can read more about this on following link

Mongodb to elasticsearch


问:
Types of parameters 'saga' and 'saga' are incompatible
I have next code:

```<code>const sagaMiddleware = createSagaMiddleware(options);
.
.
.
const createdStore = createStore(
    create(),
    state,
    someMiddleware,
  ) as someStore;

createdStore.runSaga = sagaMiddleware.run; // error here
</code>```

which works fine until upgrade to latest redux-saga 1.1.3 varsion. Now I am getting next error:

```<code>Type '<S extends Saga<any[]>>(saga: S, ...args: Parameters<S>) => Task' is not assignable to type '(saga: (() => IterableIterator<any>) | undefined, args: any) => any'.
  Types of parameters 'saga' and 'saga' are incompatible.
    Type '(() => IterableIterator<any>) | undefined' is not assignable to type 'Saga<any[]>'.
      Type 'undefined' is not assignable to type 'Saga<any[]>'.
</code>```

how it can be fixed?

答:
I had the same issue using redux-boilerplate-typescript. I ended up doing the following in types/index.d.ts:

```<code>import { Saga } from '@redux-saga/types';
</code>```

then I changed

```<code>export interface InjectedStore extends Store {
  injectedReducers: any;
  injectedSagas: any;
  runSaga(
    saga: (() => IterableIterator<any>) | undefined,
    args: any | undefined,
  ): any;
}
</code>```

to

```<code>export interface InjectedStore extends Store {
  injectedReducers: any;
  injectedSagas: any;
  runSaga(
    saga: Saga | (() => IterableIterator<any>) | undefined,
    args: any | undefined,
  ): any;
}
</code>```

Body:
I have next code:

const sagaMiddleware = createSagaMiddleware(options);
.
.
.
const createdStore = createStore(
    create(),
    state,
    someMiddleware,
  ) as someStore;

createdStore.runSaga = sagaMiddleware.run; // error here

which works fine until upgrade to latest redux-saga 1.1.3 varsion. Now I am getting next error:

Type '<S extends Saga<any[]>>(saga: S, ...args: Parameters<S>) => Task' is not assignable to type '(saga: (() => IterableIterator<any>) | undefined, args: any) => any'.
  Types of parameters 'saga' and 'saga' are incompatible.
    Type '(() => IterableIterator<any>) | undefined' is not assignable to type 'Saga<any[]>'.
      Type 'undefined' is not assignable to type 'Saga<any[]>'.

how it can be fixed?

Body:
I had the same issue using redux-boilerplate-typescript. I ended up doing the following in types/index.d.ts:

import { Saga } from '@redux-saga/types';

then I changed

export interface InjectedStore extends Store {
  injectedReducers: any;
  injectedSagas: any;
  runSaga(
    saga: (() => IterableIterator<any>) | undefined,
    args: any | undefined,
  ): any;
}

to

export interface InjectedStore extends Store {
  injectedReducers: any;
  injectedSagas: any;
  runSaga(
    saga: Saga | (() => IterableIterator<any>) | undefined,
    args: any | undefined,
  ): any;
}


问:
How to save a video using OpenCV VideoWriter to a specific directory -- python
I am trying to save a video in a specific folder.
but after running the code no output is saved.
Could anyone help? Thanks.

```<code>cap = cv2.VideoCapture(file_paths[0])
fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()
fourcc = cv2.VideoWriter_fourcc(*'XVID')
name = "C:\jupyter_projects\Test Folder\Intention dataset\background_subtracted\out.mp4"
out = cv2.VideoWriter(name,fourcc, 20,(320,180),False)

while(1):
    ret, frame = cap.read()
    if (ret == True):
        resized_frame = cv2.resize(frame,(320,180),fx=0,fy=0, interpolation = cv2.INTER_CUBIC)
        fgmask = fgbg.apply(resized_frame)
        cv2.imshow('Frame',fgmask)
        out.write(fgmask)
        if cv2.waitKey(30) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
out.release()
cv2.waitKey(5)
cv2.destroyAllWindows()
</code>```

PS: when I use default directory for saving videos output will be saved.

```<code>out = cv2.VideoWriter("out.mp4",fourcc, 20,(320,180),False)
</code>```

答: Try using single quote and using double slash for your file directory.</p>

Body:
I am trying to save a video in a specific folder.
but after running the code no output is saved.
Could anyone help? Thanks.

cap = cv2.VideoCapture(file_paths[0])
fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()
fourcc = cv2.VideoWriter_fourcc(*'XVID')
name = "C:\jupyter_projects\Test Folder\Intention dataset\background_subtracted\out.mp4"
out = cv2.VideoWriter(name,fourcc, 20,(320,180),False)

while(1):
    ret, frame = cap.read()
    if (ret == True):
        resized_frame = cv2.resize(frame,(320,180),fx=0,fy=0, interpolation = cv2.INTER_CUBIC)
        fgmask = fgbg.apply(resized_frame)
        cv2.imshow('Frame',fgmask)
        out.write(fgmask)
        if cv2.waitKey(30) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
out.release()
cv2.waitKey(5)
cv2.destroyAllWindows()

PS: when I use default directory for saving videos output will be saved.

out = cv2.VideoWriter("out.mp4",fourcc, 20,(320,180),False)


问:
SSIS Project Deployment with excel
I created an SSIS project with multiple packages. One of my package has a data flow task using Excel as data source. After deploying the project to SQL SSISDB, I can see the .dtsx files in SSMS. But where should the excel file reside? Should it still be in my local machine. The SQL resides on another server and not my local machine. Where is the deployed packages stored?

Can someone explain these?

答:
Excel file

If the excel connection manager are pointing to a fixed path on your local machine. It will throw an error when executed from different server since the excel file path is not found.

You have to use dynamic excel connections to fix this issue, or to use an excel file on a shared network location (UNC path).

Package deployment

After deployment, the packages are stored within SSISDB database:

Deploying Packages to SQL Server Integration Services Catalog (SSISDB)

Ways to use and execute SQL Server Integration Services packages

SSISDB for SQL Server Integration Services

Title: SSIS Project Deployment with excel