问:
UITableView And Diffable Data Source when supporting iOS 12 and 13
I have implemented UITableView Diffable Datasource in my project. It's working fine in IOS 13.
When I run this application below iOS 13 Version then it gives me warning that it available on ios 13 only. so I am trying to implement UITableView for below iOS 13 version.

UITableView code is done but I am facing this issue on iOS 13.

```<code>@available(iOS 13.0, *)
typealias UserDataSource = UITableViewDiffableDataSource<TblSection, YoutubeVideoModel>
@available(iOS 13.0, *)
typealias UserSnapshot = NSDiffableDataSourceSnapshot<TblSection, YoutubeVideoModel>
</code>```

here, I declare datasource variable

```<code>class SearchViewController: UIViewController {
    @available(iOS 13.0, *)
    var datasource: UserDataSource! //Stored properties cannot be marked potentially unavailable with '@available'
    }
</code>```

Initialize Datasource and snapshot

```<code> @available(iOS 13.0, *)
    func configureDatasource(){
         datasource = UITableViewDiffableDataSource<TblSection, YoutubeVideoModel>(tableView: searchTblView, cellProvider: { (tableView, indexPath, modelVideo) -> VideoTableViewCell? in
        self.configurationCell(indexPath: indexPath)
    })
    }

    @available(iOS 13.0, *)
    func createSnapshot(users: [YoutubeVideoModel]){
    var snapshot = UserSnapshot()
    snapshot.appendSections([.first])
    snapshot.appendItems(users)
    datasource.apply(snapshot, animatingDifferences: true)
      }
</code>```

I am facing this error when I declare Datasource please help thank you.

```<code>//Stored properties cannot be marked potentially unavailable with '@available'
</code>```

I am facing same issue on collectionview too.

答:
We can use @available on computed properties. However, lazy variables are considered computed properties and so you can use @available on them too. This has the nice benefit of removing the boilerplate of the extra stored property and the forced casts - in fact, it leaves no evidence of the property in your pre-iOS 10 code.

You can simply declare it like this:

```<code>@available(iOS 13.0, *)
lazy var datasource = UserDataSource()
</code>```

You can check this gist for more informations
https://gist.github.com/YogeshPateliOS/b2b13bfe5f7eef5cd7fa4a894cd35d5a

Body:
I have implemented UITableView Diffable Datasource in my project. It's working fine in IOS 13.
When I run this application below iOS 13 Version then it gives me warning that it available on ios 13 only. so I am trying to implement UITableView for below iOS 13 version.

UITableView code is done but I am facing this issue on iOS 13.

@available(iOS 13.0, *)
typealias UserDataSource = UITableViewDiffableDataSource<TblSection, YoutubeVideoModel>
@available(iOS 13.0, *)
typealias UserSnapshot = NSDiffableDataSourceSnapshot<TblSection, YoutubeVideoModel>

here, I declare datasource variable

class SearchViewController: UIViewController {
    @available(iOS 13.0, *)
    var datasource: UserDataSource! //Stored properties cannot be marked potentially unavailable with '@available'
    }

Initialize Datasource and snapshot

 @available(iOS 13.0, *)
    func configureDatasource(){
         datasource = UITableViewDiffableDataSource<TblSection, YoutubeVideoModel>(tableView: searchTblView, cellProvider: { (tableView, indexPath, modelVideo) -> VideoTableViewCell? in
        self.configurationCell(indexPath: indexPath)
    })
    }

    @available(iOS 13.0, *)
    func createSnapshot(users: [YoutubeVideoModel]){
    var snapshot = UserSnapshot()
    snapshot.appendSections([.first])
    snapshot.appendItems(users)
    datasource.apply(snapshot, animatingDifferences: true)
      }

I am facing this error when I declare Datasource please help thank you.

//Stored properties cannot be marked potentially unavailable with '@available'

I am facing same issue on collectionview too.

Body:
We can use @available on computed properties. However, lazy variables are considered computed properties and so you can use @available on them too. This has the nice benefit of removing the boilerplate of the extra stored property and the forced casts - in fact, it leaves no evidence of the property in your pre-iOS 10 code.

You can simply declare it like this:

@available(iOS 13.0, *)
lazy var datasource = UserDataSource()

You can check this gist for more informations
https://gist.github.com/YogeshPateliOS/b2b13bfe5f7eef5cd7fa4a894cd35d5a


来源: stackexchange

问:
Angular JS Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed
I am facing an issue of [ngRepeat:dupes].

systemService.getAllSystemSettings().then(
  function (obj) {
    $scope.project.meta.franchise = obj.find(item => item.keyword === "Program");
    console.log($scope.project.meta.franchise);
    $scope.project.meta.franchise = $scope.project.meta.franchise['keywordValue'].split(';');
    console.log($scope.project.meta.franchise);
    return $scope.project.meta.franchise);
  });
```

<p>in my HTML page :</p>

<pre class="lang-html prettyprint-override"><code><select class="form-control" ng-model="project.meta.franchise" ng-disabled="readOnlyUser">
  <option ng-repeat="option in project.meta.franchise" value="{{option}}">{{option}}</option>
</select>
</code>```

Output in console :

{ keyword: "Program", keywordValue: "test_abc;abc_&xyz;efg_&_hij"
}
[
  "test_abc",
  "abc_&xyz",
  "efg_&_hij"
]
```

error in console:

Please help me out in solving I tried putting track by $ index but no solution with that too. By using $track by it does not show the list in options. ThankYou in advance.

答: Try giving multiple = 'true' in your HTML select statement. Please refer to Davis Ford's post in GitHub regarding the same.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am facing an issue of [ngRepeat:dupes].

systemService.getAllSystemSettings().then(
  function (obj) {
    $scope.project.meta.franchise = obj.find(item => item.keyword === "Program");
    console.log($scope.project.meta.franchise);
    $scope.project.meta.franchise = $scope.project.meta.franchise['keywordValue'].split(';');
    console.log($scope.project.meta.franchise);
    return $scope.project.meta.franchise);
  });

in my HTML page :

<select class="form-control" ng-model="project.meta.franchise" ng-disabled="readOnlyUser">
  <option ng-repeat="option in project.meta.franchise" value="{{option}}">{{option}}</option>
</select>

Output in console :

{ keyword: "Program", keywordValue: "test_abc;abc_&xyz;efg_&_hij"
}
[
  "test_abc",
  "abc_&xyz",
  "efg_&_hij"
]

error in console:

Please help me out in solving I tried putting track by $ index but no solution with that too. By using $track by it does not show the list in options. ThankYou in advance.


问:
Is it possible to specify an arbitrary list of varags in a generic method?
I am trying to write an interface for REST controllers called GetOne right now this consists of a single method getOne

fun <T> getOne(vararg args : Any) : ResponseEntity<RestResponse<T>>
```

Ideally I would like to be able to implement this method in any REST controller that has a method for getting one item by id.

While my return type works fine, the method itself can have any number of arguments that are annotated in Spring to map / serialize the fields to the RequestBody / Path Variables / Query Parameters.

I thought I would be able to represent this in my interface as varargs , but this just results in the compiler expecting me to specifically have varargs in my method signature.

Is there a proper way to express this, or can you not do this in kotlin?

答:
Why do you need an interface for the controllers?
If you want some common functionality for the implementations (like logging the ID param), you could use Spring AOP.</p>

Body:
I am trying to write an interface for REST controllers called GetOne right now this consists of a single method getOne

fun <T> getOne(vararg args : Any) : ResponseEntity<RestResponse<T>>

Ideally I would like to be able to implement this method in any REST controller that has a method for getting one item by id.

While my return type works fine, the method itself can have any number of arguments that are annotated in Spring to map / serialize the fields to the RequestBody / Path Variables / Query Parameters.

I thought I would be able to represent this in my interface as varargs , but this just results in the compiler expecting me to specifically have varargs in my method signature.

Is there a proper way to express this, or can you not do this in kotlin?


问:
Compare Two values using Custom validator in dynamic formArray Angular 7
I have from group "additionalForm" in that i have formArray called "validations"
here the formArray is dynamic which is binding the values to validtionsField array. In the validtionsField array i have three objects in which i have two values which needs to be compared and they are Min-length and Max-Length.

ex. If i enter min length greater then the max length it should give error.

here is code for the above functionality

import {
  Component,
  OnInit,
  Inject
} from "@angular/core";
import {
  FormControl,
  FormArray,
  FormGroup,
  FormBuilder,
  Validators,
  AbstractControl,
  ValidationErrors,
  NgControlStatus,
  ValidatorFn
} from "@angular/forms";
import {
  MatDialogRef,
  MAT_DIALOG_DATA,
  MatSnackBar
} from "@angular/material";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
  validtionsField = [{
      validField: "Min Length",
      type: false,
      fieldType: "input",
      value: 1,
      keyval: "minLength"
    },
    {
      validField: "Max Length",
      type: false,
      fieldType: "input",
      value: 50,
      keyval: "maxLength"
    },
    {
      validField: "DataType",
      type: false,
      fieldType: "dropDown",
      dataTypeList: [],
      dataTypeId: "minLength",
      keyval: "dataTypeId",
      value: 874
    }
  ];

  dataType = [{
      id: 3701,
      localeId: 1,
      tenantId: 1,
      parentCategoryId: null,
      parentContentId: 873,
      name: "Alphabets",
      description: null
    },
    {
      id: 3702,
      localeId: 1,
      tenantId: 1,
      parentCategoryId: null,
      parentContentId: 874,
      name: "Alphanumeric",
      description: null
    }
  ];
  additionalForm: FormGroup = this.fb.group({
    fieldName: ["", [Validators.required]],
    validations: this.fb.array([])
  });

  constructor(public fb: FormBuilder) {}

  ngOnInit() {
    let frmArray = this.additionalForm.get("validations") as FormArray;

    for (let data of this.validtionsField) {
      frmArray.push(this.initSection(data));
    }
  }
  initSection(data) {
    return this.fb.group({
      validField: [data.validField, [Validators.required]],
      type: [data.type, [Validators.required]],
      value: [data.value, [Validators.required]],
      dataTypeList: [this.dataType, [Validators.required]],
      fieldType: [data.fieldType, [Validators.required]],
      validArray: []
    }, {
      validator: this.customValidator
    });
  }

  checkFieldType(data): any {
    return data === "dropDown";
  }

  // trying to access using below functioa to compare values min and max length
  public customValidator(control: AbstractControl): ValidationErrors | null {
    const newValue = control.get("value") ? control.get("value").value : null;
    const values = control.get("value") ? control.get("value").value : [];
    console.log("1 " + newValue);
    console.log(values);
    for (let i = 0, j = values.length; i < j; i++) {
      if (newValue === values[i]) {
        return {
          duplicate2: true
        };
      }
    }
    return null;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form [formGroup]="additionalForm">
  <mat-form-field>
    <input formControlName='fieldName' placeholder="Field Name" required matInput>
  </mat-form-field>
  <div class="row">
    <div class="col-md-12 col-sm-12">
      \
      <div formArrayName="validations">
        <ng-container *ngFor="let validationForm of  additionalForm.controls.validations.controls; let i = index">
          <div class="valid-data" [formGroupName]="i">
            <span>
                  <label>{{validationForm.value.validField }}</label>

                </span>
            <span>
                  <ng-container *ngIf="checkFieldType(validationForm.value.fieldType ); else input">
                    <mat-form-field class="select-dataType">
                      <mat-select required formControlName='value'  placeholder="Datatype">
                        <mat-option *ngFor="let fieldTypeData of validationForm.value.dataTypeList"
                          [value]='fieldTypeData.parentContentId'>
                          {{fieldTypeData.name}}</mat-option>
                      </mat-select>
                    </mat-form-field>
                  </ng-container>
                  <ng-template #input>
                    <mat-form-field>
                      <input required  formControlName='value' pattern= "[0-9]+" matInput>
                    </mat-form-field>
                  </ng-template>
                </span>
            <div *ngIf="validationForm.get('value')?.touched ">
              <div class="error" *ngIf="validationForm.get('value').hasError('required')">
                {{validationForm.value.validField}} is required
              </div>
            </div>
          </div>
        </ng-container>
      </div>
    </div>
  </div>
</form></code>```

above is the TS and HTML code and below is the function which i am trying to get old and new value from control but its failing, its giving me value from same input field from same min-length

/// trying this below functio to compare the min and max length.

public customValidator(control: AbstractControl): ValidationErrors | null {
  const newValue = control.get('value') ? control.get('value').value : null;
  const values = control.get('value') ? control.get('value').value : [];
  console.log("1 " + newValue);
  console.log(values);
  for (let i = 0, j = values.length; i < j; i++) {
    if (newValue === values[i]) {
      return {
        'duplicate2': true
      };
    }
  }
  return null;
}```

Please help me to compare values from dynamic form array, and here what ever values enters to from-array object are all bind to formcontrolName "value"

here is the link for code :

https://stackblitz.com/edit/angular6-material-components-demo-wgtafn

答:
You had to attach this validator to form array so that you can have access to all controls.

My Custom Validator :-

```<code>    export function customValidateArray(): ValidatorFn {
    return (formArray:FormArray):{[key: string]: any} | null=>{
      console.log('calling');
      let valid:boolean=true;
      setTimeout(()=>console.log(formArray),200);
      let minIndex = Object.keys(formArray.controls).findIndex((key) => formArray.controls[key].value.validField.toLowerCase()==="min length");
      let minLengthValue = formArray.controls[minIndex].value.value;
      let maxLengthValue = formArray.controls[Object.keys(formArray.controls).find((key) => formArray.controls[key].value.validField.toLowerCase()==="max length")].value.value;
      return minLengthValue < maxLengthValue ? null : {error: 'Min Length Should be less than max length', controlName : formArray.controls[minIndex].value.validField};
    }
  };
</code>```

I added it to form array ngOnInit of your code :-

```<code>ngOnInit() {
    let frmArray = this.additionalForm.get("validations") as FormArray;

    for (let data of this.validtionsField) {
      frmArray.push(this.initSection(data));
    }
    frmArray.setValidators(customValidateArray());
  }
</code>```

Use it in template like :-

```<code><div class="error" *ngIf="additionalForm.controls.validations.errors && validationForm.value.validField ===  additionalForm.controls.validations.errors.controlName">
                             {{additionalForm.controls.validations.errors.error}}
                      </div>
</code>```

Working stackblitz :-

https://stackblitz.com/edit/angular6-material-components-demo-p1tpql

Body:
I have from group "additionalForm" in that i have formArray called "validations"
here the formArray is dynamic which is binding the values to validtionsField array. In the validtionsField array i have three objects in which i have two values which needs to be compared and they are Min-length and Max-Length.

ex. If i enter min length greater then the max length it should give error.

here is code for the above functionality

import {
  Component,
  OnInit,
  Inject
} from "@angular/core";
import {
  FormControl,
  FormArray,
  FormGroup,
  FormBuilder,
  Validators,
  AbstractControl,
  ValidationErrors,
  NgControlStatus,
  ValidatorFn
} from "@angular/forms";
import {
  MatDialogRef,
  MAT_DIALOG_DATA,
  MatSnackBar
} from "@angular/material";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
  validtionsField = [{
      validField: "Min Length",
      type: false,
      fieldType: "input",
      value: 1,
      keyval: "minLength"
    },
    {
      validField: "Max Length",
      type: false,
      fieldType: "input",
      value: 50,
      keyval: "maxLength"
    },
    {
      validField: "DataType",
      type: false,
      fieldType: "dropDown",
      dataTypeList: [],
      dataTypeId: "minLength",
      keyval: "dataTypeId",
      value: 874
    }
  ];

  dataType = [{
      id: 3701,
      localeId: 1,
      tenantId: 1,
      parentCategoryId: null,
      parentContentId: 873,
      name: "Alphabets",
      description: null
    },
    {
      id: 3702,
      localeId: 1,
      tenantId: 1,
      parentCategoryId: null,
      parentContentId: 874,
      name: "Alphanumeric",
      description: null
    }
  ];
  additionalForm: FormGroup = this.fb.group({
    fieldName: ["", [Validators.required]],
    validations: this.fb.array([])
  });

  constructor(public fb: FormBuilder) {}

  ngOnInit() {
    let frmArray = this.additionalForm.get("validations") as FormArray;

    for (let data of this.validtionsField) {
      frmArray.push(this.initSection(data));
    }
  }
  initSection(data) {
    return this.fb.group({
      validField: [data.validField, [Validators.required]],
      type: [data.type, [Validators.required]],
      value: [data.value, [Validators.required]],
      dataTypeList: [this.dataType, [Validators.required]],
      fieldType: [data.fieldType, [Validators.required]],
      validArray: []
    }, {
      validator: this.customValidator
    });
  }

  checkFieldType(data): any {
    return data === "dropDown";
  }

  // trying to access using below functioa to compare values min and max length
  public customValidator(control: AbstractControl): ValidationErrors | null {
    const newValue = control.get("value") ? control.get("value").value : null;
    const values = control.get("value") ? control.get("value").value : [];
    console.log("1 " + newValue);
    console.log(values);
    for (let i = 0, j = values.length; i < j; i++) {
      if (newValue === values[i]) {
        return {
          duplicate2: true
        };
      }
    }
    return null;
  }
}

<form [formGroup]="additionalForm">
  <mat-form-field>
    <input formControlName='fieldName' placeholder="Field Name" required matInput>
  </mat-form-field>

      \

        <ng-container *ngFor="let validationForm of  additionalForm.controls.validations.controls; let i = index">

                  {{validationForm.value.validField }}

                  <ng-container *ngIf="checkFieldType(validationForm.value.fieldType ); else input">
                    <mat-form-field class="select-dataType">
                      <mat-select required formControlName='value'  placeholder="Datatype">
                        <mat-option *ngFor="let fieldTypeData of validationForm.value.dataTypeList"
                          [value]='fieldTypeData.parentContentId'>
                          {{fieldTypeData.name}}</mat-option>
                      </mat-select>
                    </mat-form-field>
                  </ng-container>
                  <ng-template #input>
                    <mat-form-field>
                      <input required  formControlName='value' pattern= "[0-9]+" matInput>
                    </mat-form-field>
                  </ng-template>

                {{validationForm.value.validField}} is required

        </ng-container>

</form>

above is the TS and HTML code and below is the function which i am trying to get old and new value from control but its failing, its giving me value from same input field from same min-length

/// trying this below functio to compare the min and max length.

public customValidator(control: AbstractControl): ValidationErrors | null {
  const newValue = control.get('value') ? control.get('value').value : null;
  const values = control.get('value') ? control.get('value').value : [];
  console.log("1 " + newValue);
  console.log(values);
  for (let i = 0, j = values.length; i < j; i++) {
    if (newValue === values[i]) {
      return {
        'duplicate2': true
      };
    }
  }
  return null;
}

Please help me to compare values from dynamic form array, and here what ever values enters to from-array object are all bind to formcontrolName "value"

here is the link for code :

https://stackblitz.com/edit/angular6-material-components-demo-wgtafn

Body:
You had to attach this validator to form array so that you can have access to all controls.

My Custom Validator :-

    export function customValidateArray(): ValidatorFn {
    return (formArray:FormArray):{[key: string]: any} | null=>{
      console.log('calling');
      let valid:boolean=true;
      setTimeout(()=>console.log(formArray),200);
      let minIndex = Object.keys(formArray.controls).findIndex((key) => formArray.controls[key].value.validField.toLowerCase()==="min length");
      let minLengthValue = formArray.controls[minIndex].value.value;
      let maxLengthValue = formArray.controls[Object.keys(formArray.controls).find((key) => formArray.controls[key].value.validField.toLowerCase()==="max length")].value.value;
      return minLengthValue < maxLengthValue ? null : {error: 'Min Length Should be less than max length', controlName : formArray.controls[minIndex].value.validField};
    }
  };

I added it to form array ngOnInit of your code :-

ngOnInit() {
    let frmArray = this.additionalForm.get("validations") as FormArray;

    for (let data of this.validtionsField) {
      frmArray.push(this.initSection(data));
    }
    frmArray.setValidators(customValidateArray());
  }

Use it in template like :-

<div class="error" *ngIf="additionalForm.controls.validations.errors && validationForm.value.validField ===  additionalForm.controls.validations.errors.controlName">
                             {{additionalForm.controls.validations.errors.error}}
                      </div>

Working stackblitz :-

https://stackblitz.com/edit/angular6-material-components-demo-p1tpql


问:
How to use C complex numbers in 'language=c++' mode?
Most of my library is written with Cython in the "normal" C mode. Up to now I rarely needed any C++ functionality, but always assumed (and sometimes did!) I could just switch to C++-mode for one module if I wanted to.

So I have like 10+ modules in C-mode and 1 module in C++-mode.

The problem is now how Cython seems to handle complex numbers definitions. In C-mode it assumes I think C complex numbers, and in C++-mode it assumes I think C++ complex numbers. I've read they might be even the same by now, but in any case Cython complains that they are not:

```<code>openChargeState/utility/cheb.cpp:2895:35: error: cannot convert ‘__pyx_t_double_complex {aka std::complex<double>}’ to ‘__complex__ double’ for argument ‘1’ to ‘double cabs(__complex__ double)’
 __pyx_t_5 = ((cabs(__pyx_v_num) == INFINITY) != 0);
</code>```

In that case I'm trying to use cabs defined in a C-mode module, and calling it from the C++-mode module.

I know there are some obvious workarounds (right now I'm just not using C++-mode; I'd like to use vectors and instead use the slower Python lists for now).

Is there maybe a way to tell my C++-mode module to use C complex numbers, or tell it that they are the same? If there is I couldn't find a working way to ctypedef C complex numbers in my C++-mode module... Or are there any other solutions?

EDIT: Comments of DavidW and ead suggested some reasonable things. First the minimum working example.

setup.py

```<code>from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize

extra_compile_args=['-O3']
compdir = {'language_level' : '3'}

extensions = cythonize([
                        Extension("cmod", ["cmod.pyx"]),
                        Extension("cppmod", ["cppmod.pyx"], language='c++')
                       ],
                       compiler_directives = compdir
                      )

setup(cmdclass = {'build_ext': build_ext},
      ext_modules = extensions
     )

import cppmod
</code>```

cmod.pyx

```<code>cdef double complex c_complex_fun(double complex xx):
    return xx**2
</code>```

cmod.pxd

```<code>cdef double complex c_complex_fun(double complex xx)

cdef extern from "complex.h":
    double cabs(double complex zz) nogil
</code>```

cppmod.pyx

```<code>cimport cmod

cdef double complex cpp_complex_fun(double complex xx):
    return cmod.c_complex_fun(xx)*abs(xx)   # cmod.cabs(xx) doesn't work here

print(cpp_complex_fun(5.5))
</code>```

Then just compile with python3 setup.py build_ext --inplace.

Now the interesting part is that (as written in the code) only "indirectly" imported c functions have a problem, in my case cabs. So the suggestion to just use abs actually does help, but I still don't understand the underlying logic. I hope I don't encounter this in another problem. I'm leaving the question up for now. Maybe somebody knows what's happening.

答:
Your problem has nothing to do with the fact, that one module is compiled as a C-extension and the other as a C++-extension - one can easily reproduce the issue in a C++-extension alone:

```<code>%%cython -+
cdef extern from "complex.h":
    double cabs(double complex zz) nogil

def cpp_complex_fun(double complex xx):
    return cabs(xx)
</code>```

results in your error-message:

error: cannot convert __pyx_t_double_complex {aka
  std::complex<double>} to __complex__ double for argument 1 to
  double cabs(__complex__ double)

The problem is that the complex numbers are ... well, complex. Cython's strategy (can be looked up here and here) to handle complex numbers is to use an available implementation from C/CPP and if none is found a hand-written fallback is used:

```<code>#if !defined(CYTHON_CCOMPLEX)
  #if defined(__cplusplus)
    #define CYTHON_CCOMPLEX 1
  #elif defined(_Complex_I)
    #define CYTHON_CCOMPLEX 1
  #else
    #define CYTHON_CCOMPLEX 0
  #endif
#endif
....
#if CYTHON_CCOMPLEX
  #ifdef __cplusplus
    typedef ::std::complex< double > __pyx_t_double_complex;
  #else
    typedef double _Complex __pyx_t_double_complex;
  #endif
#else
    typedef struct { double real, imag; } __pyx_t_double_complex;
#endif
</code>```

In case of a C++-extension, Cython's double complex is translated to std::complex<double> and thus cannot be called with cabs( double complex z ) because std::complex<double> isn't double complex.

So actually, it is your "fault": you lied to Cython and told him, that cabs has the signature double cabs(std::complex<double> z), but it was not enough to fool  the c++-compiler.

That means, in c++-module std::abs(std::complex<double>) could be used, or just Cython's/Python's abs, which is automatically translated to the right function (this is however not possible for all standard-function).

In case of the C-extension, because you have included complex.h as an so called "early include" with  cdef extern from "complex.h", thus for the above defines _Complex_I becomes defined and Cython's complex becomes an alias for double complex and thus cabs can be used.

Probably the right thing for Cython would be to always use the fallback per default and that the user should be able to choose the desired implementation (double complex or std::complex<double>) explicitly.

Body:
Most of my library is written with Cython in the "normal" C mode. Up to now I rarely needed any C++ functionality, but always assumed (and sometimes did!) I could just switch to C++-mode for one module if I wanted to.

So I have like 10+ modules in C-mode and 1 module in C++-mode.

The problem is now how Cython seems to handle complex numbers definitions. In C-mode it assumes I think C complex numbers, and in C++-mode it assumes I think C++ complex numbers. I've read they might be even the same by now, but in any case Cython complains that they are not:

openChargeState/utility/cheb.cpp:2895:35: error: cannot convert ‘__pyx_t_double_complex {aka std::complex<double>}’ to ‘__complex__ double’ for argument ‘1’ to ‘double cabs(__complex__ double)’
 __pyx_t_5 = ((cabs(__pyx_v_num) == INFINITY) != 0);

In that case I'm trying to use cabs defined in a C-mode module, and calling it from the C++-mode module.

I know there are some obvious workarounds (right now I'm just not using C++-mode; I'd like to use vectors and instead use the slower Python lists for now).

Is there maybe a way to tell my C++-mode module to use C complex numbers, or tell it that they are the same? If there is I couldn't find a working way to ctypedef C complex numbers in my C++-mode module... Or are there any other solutions?

EDIT: Comments of DavidW and ead suggested some reasonable things. First the minimum working example.

setup.py

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize

extra_compile_args=['-O3']
compdir = {'language_level' : '3'}

extensions = cythonize([
                        Extension("cmod", ["cmod.pyx"]),
                        Extension("cppmod", ["cppmod.pyx"], language='c++')
                       ],
                       compiler_directives = compdir
                      )

setup(cmdclass = {'build_ext': build_ext},
      ext_modules = extensions
     )

import cppmod

cmod.pyx

cdef double complex c_complex_fun(double complex xx):
    return xx**2

cmod.pxd

cdef double complex c_complex_fun(double complex xx)

cdef extern from "complex.h":
    double cabs(double complex zz) nogil

cppmod.pyx

cimport cmod

cdef double complex cpp_complex_fun(double complex xx):
    return cmod.c_complex_fun(xx)*abs(xx)   # cmod.cabs(xx) doesn't work here

print(cpp_complex_fun(5.5))

Then just compile with python3 setup.py build_ext --inplace.

Now the interesting part is that (as written in the code) only "indirectly" imported c functions have a problem, in my case cabs. So the suggestion to just use abs actually does help, but I still don't understand the underlying logic. I hope I don't encounter this in another problem. I'm leaving the question up for now. Maybe somebody knows what's happening.

Body:
Your problem has nothing to do with the fact, that one module is compiled as a C-extension and the other as a C++-extension - one can easily reproduce the issue in a C++-extension alone:

%%cython -+
cdef extern from "complex.h":
    double cabs(double complex zz) nogil

def cpp_complex_fun(double complex xx):
    return cabs(xx)

results in your error-message:

error: cannot convert __pyx_t_double_complex {aka
  std::complex<double>} to __complex__ double for argument 1 to
  double cabs(__complex__ double)

The problem is that the complex numbers are ... well, complex. Cython's strategy (can be looked up here and here) to handle complex numbers is to use an available implementation from C/CPP and if none is found a hand-written fallback is used:

#if !defined(CYTHON_CCOMPLEX)
  #if defined(__cplusplus)
    #define CYTHON_CCOMPLEX 1
  #elif defined(_Complex_I)
    #define CYTHON_CCOMPLEX 1
  #else
    #define CYTHON_CCOMPLEX 0
  #endif
#endif
....
#if CYTHON_CCOMPLEX
  #ifdef __cplusplus
    typedef ::std::complex< double > __pyx_t_double_complex;
  #else
    typedef double _Complex __pyx_t_double_complex;
  #endif
#else
    typedef struct { double real, imag; } __pyx_t_double_complex;
#endif

In case of a C++-extension, Cython's double complex is translated to std::complex<double> and thus cannot be called with cabs( double complex z ) because std::complex<double> isn't double complex.

So actually, it is your "fault": you lied to Cython and told him, that cabs has the signature double cabs(std::complex<double> z), but it was not enough to fool  the c++-compiler.

That means, in c++-module std::abs(std::complex<double>) could be used, or just Cython's/Python's abs, which is automatically translated to the right function (this is however not possible for all standard-function).

In case of the C-extension, because you have included complex.h as an so called "early include" with  cdef extern from "complex.h", thus for the above defines _Complex_I becomes defined and Cython's complex becomes an alias for double complex and thus cabs can be used.

Probably the right thing for Cython would be to always use the fallback per default and that the user should be able to choose the desired implementation (double complex or std::complex<double>) explicitly.


问:
Making a draft of tic-tac-toe
```<code>import numpy as np
player1 = True

def create_board():
    board = np.zeros((3,3), dtype=int)
    return board

def place(board , player1 , position ):
    if player1 == True:
        player1 = False
        if board[position] == 0:
            board = position
        elif board[position] != 0:
            print("False , place taken 1")
    else:
        if player1 == False:
            if board[position] == 0:
                board = position
            elif board[position] != [0, 0]:
                print("False , place taken 2 ")
    return board
</code>```

Function call:

```<code>place(board=create_board() , player1=1 , position=(0,0))
</code>```

Here is my code, in this code there is a lot going on however there is one part i could not get it right . In the bold section , i am trying to replace

```<code>([0,0,0],
 [0,0,0],
 [0,0,0])
</code>```

to

```<code>([1,0,0],
 [0,0,0],
 [0,0,0])
</code>```

May i know , how can I do this please ... Thank you !

答:
you're mistakenly changing the board variable to position inside the if statements

if board[position] == 0:
    board = position
```

<p>you should change the value inside <code>board</code> at index <code>position</code> </p>

<pre class="lang-py prettyprint-override"><code>board[position] = 1   # for player 1
board[position] = 2   # for player 2
</code>```

i've also cleaned the code a little bit

def place(board , player1 , position ):

    x = 1 if player1 else 2

    if board[position] != 0:
        print(f'False , place taken {x}')

    else:
        board[position] = x

    return board
```

Title: Making a draft of tic-tac-toe

Body:
import numpy as np
player1 = True

def create_board():
    board = np.zeros((3,3), dtype=int)
    return board

def place(board , player1 , position ):
    if player1 == True:
        player1 = False
        if board[position] == 0:
            board = position
        elif board[position] != 0:
            print("False , place taken 1")
    else:
        if player1 == False:
            if board[position] == 0:
                board = position
            elif board[position] != [0, 0]:
                print("False , place taken 2 ")
    return board

Function call:

place(board=create_board() , player1=1 , position=(0,0))

Here is my code, in this code there is a lot going on however there is one part i could not get it right . In the bold section , i am trying to replace

([0,0,0],
 [0,0,0],
 [0,0,0])

to

([1,0,0],
 [0,0,0],
 [0,0,0])

May i know , how can I do this please ... Thank you !

Body:
you're mistakenly changing the board variable to position inside the if statements

if board[position] == 0:
    board = position

you should change the value inside board at index position

board[position] = 1   # for player 1
board[position] = 2   # for player 2

i've also cleaned the code a little bit

def place(board , player1 , position ):

    x = 1 if player1 else 2

    if board[position] != 0:
        print(f'False , place taken {x}')

    else:
        board[position] = x

    return board


问:
Pass this to child Function
This function should get some data out of a MySQL database:

function getXXX() {
  this.output = []
  con.connect(function(err) {
    if (err) throw err
    con.query('SELECT * FROM `XXX`', function(err, result) {
      if (err) throw err
      this.output = result
    })
  })
  return this.output
}
console.log(getXXX())
```

how do i pass this to the child function because right now it returns []?

(I basically want a function that returns the values from the database)

答:
There are two ways to pass "this" to the inner function</p>

```<code>//Use arrow function that stores "this" automatically

function getXXX() {
    this.output = []
    con.connect((err) => {
        if (err) throw err
        con.query('SELECT * FROM `XXX`', function (err, result) {
            if (err) throw err
            this.output = result
        })
    })
    return this.output
}

//Bind "this" with .bind function

function getXXX() {
    this.output = []
    con.connect((function (err) {
        if (err) throw err
        con.query('SELECT * FROM `XXX`', function (err, result) {
            if (err) throw err
            this.output = result
        })
    }).bind(this))
    return this.output
}
</code>```

Title: Pass this to child Function

Body:
This function should get some data out of a MySQL database:

function getXXX() {
  this.output = []
  con.connect(function(err) {
    if (err) throw err
    con.query('SELECT * FROM `XXX`', function(err, result) {
      if (err) throw err
      this.output = result
    })
  })
  return this.output
}
console.log(getXXX())

how do i pass this to the child function because right now it returns []?

(I basically want a function that returns the values from the database)

Body:
There are two ways to pass "this" to the inner function

//Use arrow function that stores "this" automatically

function getXXX() {
    this.output = []
    con.connect((err) => {
        if (err) throw err
        con.query('SELECT * FROM `XXX`', function (err, result) {
            if (err) throw err
            this.output = result
        })
    })
    return this.output
}

//Bind "this" with .bind function

function getXXX() {
    this.output = []
    con.connect((function (err) {
        if (err) throw err
        con.query('SELECT * FROM `XXX`', function (err, result) {
            if (err) throw err
            this.output = result
        })
    }).bind(this))
    return this.output
}


问:
chat server in heroku
I have this chat server I normally run with ./manage.py run_chat_server. I recently deployed my app to Heroku and I can't figure out how to run the chat_server. can I get help
I have tried with the console in Heroku but I just realized that it does not run the manage.py command since it tells me command not found.

答:
I was able to get an application with django-private-chat running on Heroku. The key was to run the chat service as a separate Heroku web app. I deployed two versions of the application to separate Heroku apps, only changing the Procfile.

Here are what each Procfile looks like

```<code>#Chat Service Procfile
web: python manage.py run_chat_server
</code>```

```<code>#Django Application Procfile
web: gunicore <app_name>.wsgi
</code>```

The settings I used were:

```<code>#settings.py

CHAT_WS_SERVER_HOST =  '0.0.0.0'
CHAT_WS_SERVER_PROTOCOL = 'wss'
CHAT_WS_SERVER_PORT = int(os.environ.get('PORT', 5002))
</code>```

In addition, I modified the var base_ws_server_path = ‘wss://<chat-service-app-name>.herokuapp.com/' in templates>django_private_chat>dialogs.html.

Let me know if you have any questions.

Title: chat server in heroku

Body:
I was able to get an application with django-private-chat running on Heroku. The key was to run the chat service as a separate Heroku web app. I deployed two versions of the application to separate Heroku apps, only changing the Procfile.

Here are what each Procfile looks like

#Chat Service Procfile
web: python manage.py run_chat_server

#Django Application Procfile
web: gunicore <app_name>.wsgi

The settings I used were:

#settings.py

CHAT_WS_SERVER_HOST =  '0.0.0.0'
CHAT_WS_SERVER_PROTOCOL = 'wss'
CHAT_WS_SERVER_PORT = int(os.environ.get('PORT', 5002))

In addition, I modified the var base_ws_server_path = ‘wss://<chat-service-app-name>.herokuapp.com/' in templates>django_private_chat>dialogs.html.

Let me know if you have any questions.


问:
Making Boolean mask on date column in Pandas
Letsay I have a DataFrame with badly formatted dates:

```<code>df = pd.DataFrame(['01-01-1980','2001-03-01','05/22/2020'],columns=['DATE'])
</code>```

I want to compare them to some date '06/07/2003'. Doing Boolean mask on Timestamp-converted values is obvious way to go:

```<code>mask=pd.Timestamp(df['DATE']) < pd.Timestamp('06/07/2003')
</code>```

but that does not fly because Timestamp does not understand Series object. You can go pedestrian way but that is ugly:

```<code>mask=pd.Series([pd.Timestamp(df.loc[x,'DATE']) for x in df['DATE'].index]) < pd.Timestamp('06/07/2003')
</code>```

How to do it concisely?

答:
Use to_datetime for convert to datetimes, also for compare is possible use string:

```<code>mask = pd.to_datetime(df['DATE']) < '06/07/2003'
print (mask)
0     True
1     True
2    False
Name: DATE, dtype: bool
</code>```

Body:
Letsay I have a DataFrame with badly formatted dates:

df = pd.DataFrame(['01-01-1980','2001-03-01','05/22/2020'],columns=['DATE'])

I want to compare them to some date '06/07/2003'. Doing Boolean mask on Timestamp-converted values is obvious way to go:

mask=pd.Timestamp(df['DATE']) < pd.Timestamp('06/07/2003')

but that does not fly because Timestamp does not understand Series object. You can go pedestrian way but that is ugly:

mask=pd.Series([pd.Timestamp(df.loc[x,'DATE']) for x in df['DATE'].index]) < pd.Timestamp('06/07/2003')

How to do it concisely?

Body:
Use to_datetime for convert to datetimes, also for compare is possible use string:

mask = pd.to_datetime(df['DATE']) < '06/07/2003'
print (mask)
0     True
1     True
2    False
Name: DATE, dtype: bool


问:
Is Asynchronous file IO thread safe?
Is asynchronous file IO like FileStream.BeginWrite thread safe? If not, then it need to wrap with "SyncLock", that's mean it is still blocking thread.</p>

答: FileStream.BeginWrite already starts a new thread to access the files. You don't need to start the FileStream.BeginWrite on a separate thread (because that will be thread in a thread). On the other hand, multiple FileStream.BeginWrite functions should not be accessing the same file at the same time.

ContentLicense: CC BY-SA 3.0

Title: Is Asynchronous file IO thread safe?


问:
mongodb push values into array with $reduce
I have an document structure like this:

```<code>_id: 123,
posts: [
   {
      _id: 234,
      likesUser: [345, 456, 567, 678]
   }
]
</code>```

I want to use $reduce here so my expected output should look like this:

```<code>   output: {
      likes: [23, 31, 12, 32],  //each element is the size of the "likesUser" array
      ids: ["14312", "2342", "2312", "235234"]  //each element is the "_id" in the posts array
   }
</code>```

I have try it like this:

```<code>  let result = await Post.aggregate([
    {
      $match: {
        _id: USER
      }
    },
    {
      $project: {
        posts: {
          $reduce: {
            input: "$posts",
            initialValue: { likes: [], ids: [] },
            in: {
              likes: {
                $push: { $size: "$$this.likesUser" }
              },
              ids: {
                $push: "$$this._id"
              }
            }
          }
        }
      }
    }
  ]);
</code>```

In my frontend i use chart.js. The yAxsis are the likes and the xAxsis are the ID's. So for every element in my posts array i need the length of likesUser and _id
But it doenst work. Has anybody an idea how to achive this?

答:
You are on the right way. You need to use $mergeObjects operator to achieve this. Following query will be helpful:

db.collection.aggregate([
  {
    $match: {
      _id: USER
    }
  },
  {
    $project: {
      post: {
        $reduce: {
          input: "$posts",
          initialValue: {
            likes: [],
            ids: []
          },
          in: {
            $mergeObjects: [
              "$$value",
              {
                likes: {
                  $concatArrays: [
                    "$$value.likes",
                    [
                      {
                        $size: "$$this.likesUser"
                      }
                    ]
                  ]
                },
                ids: {
                  $concatArrays: [
                    "$$value.ids",
                    [
                      "$$this._id"
                    ]
                  ]
                }
              }
            ]
          }
        }
      }
    }
  }
])
```

MongoPlayGroundLink

I hope the above is helpful.

Body:
I have an document structure like this:

_id: 123,
posts: [
   {
      _id: 234,
      likesUser: [345, 456, 567, 678]
   }
]

I want to use $reduce here so my expected output should look like this:

   output: {
      likes: [23, 31, 12, 32],  //each element is the size of the "likesUser" array
      ids: ["14312", "2342", "2312", "235234"]  //each element is the "_id" in the posts array
   }

I have try it like this:

  let result = await Post.aggregate([
    {
      $match: {
        _id: USER
      }
    },
    {
      $project: {
        posts: {
          $reduce: {
            input: "$posts",
            initialValue: { likes: [], ids: [] },
            in: {
              likes: {
                $push: { $size: "$$this.likesUser" }
              },
              ids: {
                $push: "$$this._id"
              }
            }
          }
        }
      }
    }
  ]);

In my frontend i use chart.js. The yAxsis are the likes and the xAxsis are the ID's. So for every element in my posts array i need the length of likesUser and _id
But it doenst work. Has anybody an idea how to achive this?

Body:
You are on the right way. You need to use $mergeObjects operator to achieve this. Following query will be helpful:

db.collection.aggregate([
  {
    $match: {
      _id: USER
    }
  },
  {
    $project: {
      post: {
        $reduce: {
          input: "$posts",
          initialValue: {
            likes: [],
            ids: []
          },
          in: {
            $mergeObjects: [
              "$$value",
              {
                likes: {
                  $concatArrays: [
                    "$$value.likes",
                    [
                      {
                        $size: "$$this.likesUser"
                      }
                    ]
                  ]
                },
                ids: {
                  $concatArrays: [
                    "$$value.ids",
                    [
                      "$$this._id"
                    ]
                  ]
                }
              }
            ]
          }
        }
      }
    }
  }
])

MongoPlayGroundLink

I hope the above is helpful.


问:
Normalization introduce some NaN in my dataframe
I am trying to normalise my df column by column.
I have tried different methods but they always introduce NaN values.

df_data=df.set_index("Topic")
k=1
a= int (input('Number of class:'))
for i in range (a):
    df_data_class=df_data.loc[df_data['Class']==k].drop('Class',1)
    df_norm=df_data_class.sub(df_data_class.min()).div((df_data_class.max()-df_data_class.min()))
    fig,ax=plt.subplots(figsize=(9,5))
    ax=sns.heatmap(df_data_norm,cmap='summer_r',linewidth=1,ax=ax,cbar_kws={'label':'Percentage'})
    ax.set_ylabel('Student Name')
    ax.set_xlabel('Topics')
    ax.set_title('Heatmap')
    k+=1'
```

答: If you are dividing by zero, there is always a chance of getting NaN.  https://en.wikipedia.org/wiki/NaN.  If the max-min is zero in your set, you will get division by zero. </p>


问:
Android :cannot unit test android functions receiving NPE
I have just started unit testing in android. I cannot unit test android internal method to notify that data is changed (notifyDataSetChanged)and I am getting null pointer exception on this point. I am using mockito and power moockito to mock different objects.

```<code> public void RecyclerView(String value,Bitmap image) {
  RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainActivity.this);
    recyclerView.setAdapter(adapter);// set adapter on recyclerview
    adapter.notifyDataSetChanged();// Notify the adapter

    }
</code>```

My unit test is:

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest({MainActivity.class})
public class MainActivityTest {

    @Mock
    Bitmap bitmap;

    @Mock
    RecyclerView recycleview;
    @InjectMocks
    Activity activity;
    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mainactivity = new MainActivity();

    }

    @Test
    public void PopulateRecyleViewTest() {
        try {
            final RecyclerViewAdapter abc = PowerMockito.mock(RecyclerViewAdapter.class);

            PowerMockito.whenNew(RecyclerViewAdapter.class).withArguments(mainactivity).thenReturn(abc);
            doNothing().when(abc).notifyDataSetChanged(); //do nothing getting exception here
            mainactivity.recyclerView = recycleview;

            mainactivity.PopulateRecyleView("", bitmap);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
</code>```

Is there any way to unit test this method so that notifydatasetchanged() do not give NPE(Null Pointer Exception)? I have read that power mockito is used to unit test final method but it does not seem to be unit testing notifyDataSetChanged which is final method. Any help would be appreciated.

答:
With Mockito 2.0 and above you can mock final classes and methods by adding a file. Check out this document: Mock the unmockable: opt-in mocking of final classes/methods

Basically it states that you have to create the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker then add the single line:

mock-maker-inline

After that you should be able to mock a final class or method. I had the same issue you had and this worked for me.

Body:
I have just started unit testing in android. I cannot unit test android internal method to notify that data is changed (notifyDataSetChanged)and I am getting null pointer exception on this point. I am using mockito and power moockito to mock different objects.

 public void RecyclerView(String value,Bitmap image) {
  RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainActivity.this);
    recyclerView.setAdapter(adapter);// set adapter on recyclerview
    adapter.notifyDataSetChanged();// Notify the adapter

    }

My unit test is:

@RunWith(PowerMockRunner.class)
@PrepareForTest({MainActivity.class})
public class MainActivityTest {

    @Mock
    Bitmap bitmap;

    @Mock
    RecyclerView recycleview;
    @InjectMocks
    Activity activity;
    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mainactivity = new MainActivity();

    }

    @Test
    public void PopulateRecyleViewTest() {
        try {
            final RecyclerViewAdapter abc = PowerMockito.mock(RecyclerViewAdapter.class);

            PowerMockito.whenNew(RecyclerViewAdapter.class).withArguments(mainactivity).thenReturn(abc);
            doNothing().when(abc).notifyDataSetChanged(); //do nothing getting exception here
            mainactivity.recyclerView = recycleview;

            mainactivity.PopulateRecyleView("", bitmap);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

Is there any way to unit test this method so that notifydatasetchanged() do not give NPE(Null Pointer Exception)? I have read that power mockito is used to unit test final method but it does not seem to be unit testing notifyDataSetChanged which is final method. Any help would be appreciated.


问:
Set background color of a specific control
I have searched the net looking for a way to set background color a dialog control.

I have managed to do this with this code:

```<code>case WM_CTLCOLORSTATIC:
{
    HDC hdcStatic = (HDC) wParam;
    SetTextColor(hdcStatic, RGB(255,255,255));
    SetBkColor(hdcStatic, RGB(0,0,0));

    if (hbrBkgnd == NULL)
    {
        hbrBkgnd = CreateSolidBrush(RGB(0,0,0));
    }
    return (INT_PTR)hbrBkgnd;
}
</code>```

However, what I am actually looking for is to color only a specific static control, not all the static controls I have in my dialog. Is there anyway to do this? Perhaps set the hdc to something using GetDlgItem(hdlg,"IDC_MYCONTROL") ?

-- UPDATE

After the suggestions I ended up with this :

```<code>case WM_CTLCOLORSTATIC:
{
    HDC hdcStatic = (HDC) lParam;
    HWND hWnd =  (HWND)lParam;
    HWND dlg =GetDlgItem(hDlg, IDC_STATIC2);
    if (hWnd == dlg)
    {
        SetTextColor(hdcStatic, RGB(255,255,255));
        SetBkColor(hdcStatic, RGB(0,0,0));
    }
    if (hbrBkgnd == NULL)
    {
        hbrBkgnd = CreateSolidBrush(RGB(0,0,0));
    }
    return (INT_PTR)hbrBkgnd;
}
</code>```

And it seems that even if SetBkColor is run nothing changes on the dialog, leading on the wierd problem described below.

答: Check lParam matches the handle to the child that you want to change the colour of.</p>

Body:
I have searched the net looking for a way to set background color a dialog control.

I have managed to do this with this code:

case WM_CTLCOLORSTATIC:
{
    HDC hdcStatic = (HDC) wParam;
    SetTextColor(hdcStatic, RGB(255,255,255));
    SetBkColor(hdcStatic, RGB(0,0,0));

    if (hbrBkgnd == NULL)
    {
        hbrBkgnd = CreateSolidBrush(RGB(0,0,0));
    }
    return (INT_PTR)hbrBkgnd;
}

However, what I am actually looking for is to color only a specific static control, not all the static controls I have in my dialog. Is there anyway to do this? Perhaps set the hdc to something using GetDlgItem(hdlg,"IDC_MYCONTROL") ?

-- UPDATE

After the suggestions I ended up with this :

case WM_CTLCOLORSTATIC:
{
    HDC hdcStatic = (HDC) lParam;
    HWND hWnd =  (HWND)lParam;
    HWND dlg =GetDlgItem(hDlg, IDC_STATIC2);
    if (hWnd == dlg)
    {
        SetTextColor(hdcStatic, RGB(255,255,255));
        SetBkColor(hdcStatic, RGB(0,0,0));
    }
    if (hbrBkgnd == NULL)
    {
        hbrBkgnd = CreateSolidBrush(RGB(0,0,0));
    }
    return (INT_PTR)hbrBkgnd;
}

And it seems that even if SetBkColor is run nothing changes on the dialog, leading on the wierd problem described below.


问:
Docker-Compose Nginx (with static React) and Nginx
I am currently stuck on making nginx proxy to the node load balancer. It gives the following error when making a request on 185.146.87.32:5000/:

2020/06/01 13:23:09 [warn] 6#6: *1 upstream server temporarily disabled while connecting to upstream, client: 86.125.198.83, server: domain.ro, request: "GET / HTTP/1.1", upstream: "http://185.146.87.32:5002/", host: "185.146.87.32:5000"

I managed to make this work on a local system, but now I am trying to make it work on a remote server.
BACKEND_SERVER_PORT_1=5001
BACKEND_SERVER_PORT_2=5002
BACKEND_NODE_PORT=5000
BACKEND_NGINX_PORT=80
CLIENT_SERVER_PORT=3000
ADMIN_SERVER_PORT=3006
NGINX_SERVER_PORT=80
API_HOST="http://domain.ro"

This is the docker-compose:

```<code>version: '3'
services:

#####################################
#   Setup for NGINX container
#####################################
nginx:
  container_name: domain_back_nginx
  build:
    context: ./nginx
    dockerfile: Dockerfile
  image: domain/domain_back_nginx
  ports:
    - ${BACKEND_NODE_PORT}:${BACKEND_NGINX_PORT}
  volumes:
    - ./:/usr/src/domain
  restart: always
#####################################
#   Setup for backend container
#####################################
backend_1:
  container_name: domain_back_server_1
  build:
    context: ./
    dockerfile: Dockerfile
  image: domain/domain_back_server_1
  ports:
    - ${BACKEND_SERVER_PORT_1}:${BACKEND_NODE_PORT}
  volumes:
    - ./:/usr/src/domain
  restart: always
  command: npm start
#####################################
#   Setup for backend container
#####################################
backend_2:
  container_name: domain_back_server_2
  build:
    context: ./
    dockerfile: Dockerfile
  image: domain/domain_back_server_2
  ports:
    - ${BACKEND_SERVER_PORT_2}:${BACKEND_NODE_PORT}
  volumes:
    - ./:/usr/src/domain
  restart: always
  command: npm start
</code>```

The Dockerfile for node is:

```<code>FROM node:12.17.0-alpine3.9

RUN mkdir -p /usr/src/domain

ENV NODE_ENV=production

WORKDIR /usr/src/domain

COPY package*.json ./

RUN npm install --silent

COPY . .

EXPOSE 5000
</code>```

The config file for nginx is:

```<code>upstream domain {
  least_conn;
  server backend_1 weight=1;
  server backend_2 weight=1;
}

server {
   listen 80;
   listen [::]:80;

   root /var/www/domain_app;
   server_name domain.ro www.domain.ro;
   location / {
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_pass http://domain;
  }
  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   /usr/share/nginx/html;
  }
}
</code>```

The Dockerfile for nginx is:

```<code>FROM nginx:1.17-alpine as build

#!/bin/sh

RUN rm /etc/nginx/conf.d/default.conf

COPY default.conf /etc/nginx/conf.d

CMD ["nginx", "-g", "daemon off;"]
</code>```

答:
don't expose your backend to world,

create a docker network for your services, then expose nginx, it's the best practice,
but in your case you didnt specify backend ports in nginx.conf

```<code>upstream domain {
  least_conn;
  server backend_1:5000 weight=1;
  server backend_2:5000 weight=1;
}
</code>```

you should do below:

```<code>version: '3'
services:

#####################################
#   Setup for NGINX container
#####################################
nginx:
  container_name: domain_back_nginx
  build:
    context: ./nginx
    dockerfile: Dockerfile
  image: domain/domain_back_nginx
  networks:
    - proxy
  ports:
    - 5000:80
  volumes:
    - ./:/usr/src/domain
  restart: always
#####################################
#   Setup for backend container
#####################################
backend_1:
  container_name: domain_back_server_1
  build:
    context: ./
    dockerfile: Dockerfile
  image: domain/domain_back_server_1
  networks:
    - proxy

  ## always expose, just in case you missed it in Dockerfile, this will expose the port(s)
  ## just in defined networks
  expose:
    - 5000
  volumes:
    - ./:/usr/src/domain
  restart: always
  command: npm start
#####################################
#   Setup for backend container
#####################################
backend_2:
  container_name: domain_back_server_2
  build:
    context: ./
    dockerfile: Dockerfile
  image: domain/domain_back_server_2
  networks:
    - proxy

  ## always expose, just in case you missed it in Dockerfile, this will expose the port(s)
  ## just in defined networks
  expose:
    - 5000
  volumes:
    - ./:/usr/src/domain
  restart: always
  command: npm start

networks:
  proxy:
    external:
      name: proxy
</code>```

but after all, i recommend jwilder/nginx-proxy

Body:
I am currently stuck on making nginx proxy to the node load balancer. It gives the following error when making a request on 185.146.87.32:5000/:

2020/06/01 13:23:09 [warn] 6#6: *1 upstream server temporarily disabled while connecting to upstream, client: 86.125.198.83, server: domain.ro, request: "GET / HTTP/1.1", upstream: "http://185.146.87.32:5002/", host: "185.146.87.32:5000"

I managed to make this work on a local system, but now I am trying to make it work on a remote server.
BACKEND_SERVER_PORT_1=5001
BACKEND_SERVER_PORT_2=5002
BACKEND_NODE_PORT=5000
BACKEND_NGINX_PORT=80
CLIENT_SERVER_PORT=3000
ADMIN_SERVER_PORT=3006
NGINX_SERVER_PORT=80
API_HOST="http://domain.ro"

This is the docker-compose:

version: '3'
services:

#####################################
#   Setup for NGINX container
#####################################
nginx:
  container_name: domain_back_nginx
  build:
    context: ./nginx
    dockerfile: Dockerfile
  image: domain/domain_back_nginx
  ports:
    - ${BACKEND_NODE_PORT}:${BACKEND_NGINX_PORT}
  volumes:
    - ./:/usr/src/domain
  restart: always
#####################################
#   Setup for backend container
#####################################
backend_1:
  container_name: domain_back_server_1
  build:
    context: ./
    dockerfile: Dockerfile
  image: domain/domain_back_server_1
  ports:
    - ${BACKEND_SERVER_PORT_1}:${BACKEND_NODE_PORT}
  volumes:
    - ./:/usr/src/domain
  restart: always
  command: npm start
#####################################
#   Setup for backend container
#####################################
backend_2:
  container_name: domain_back_server_2
  build:
    context: ./
    dockerfile: Dockerfile
  image: domain/domain_back_server_2
  ports:
    - ${BACKEND_SERVER_PORT_2}:${BACKEND_NODE_PORT}
  volumes:
    - ./:/usr/src/domain
  restart: always
  command: npm start

The Dockerfile for node is:

FROM node:12.17.0-alpine3.9

RUN mkdir -p /usr/src/domain

ENV NODE_ENV=production

WORKDIR /usr/src/domain

COPY package*.json ./

RUN npm install --silent

COPY . .

EXPOSE 5000

The config file for nginx is:

upstream domain {
  least_conn;
  server backend_1 weight=1;
  server backend_2 weight=1;
}

server {
   listen 80;
   listen [::]:80;

   root /var/www/domain_app;
   server_name domain.ro www.domain.ro;
   location / {
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_pass http://domain;
  }
  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   /usr/share/nginx/html;
  }
}

The Dockerfile for nginx is:

FROM nginx:1.17-alpine as build

#!/bin/sh

RUN rm /etc/nginx/conf.d/default.conf

COPY default.conf /etc/nginx/conf.d

CMD ["nginx", "-g", "daemon off;"]

Body:
don't expose your backend to world,

create a docker network for your services, then expose nginx, it's the best practice,
but in your case you didnt specify backend ports in nginx.conf

upstream domain {
  least_conn;
  server backend_1:5000 weight=1;
  server backend_2:5000 weight=1;
}

you should do below:

version: '3'
services:

#####################################
#   Setup for NGINX container
#####################################
nginx:
  container_name: domain_back_nginx
  build:
    context: ./nginx
    dockerfile: Dockerfile
  image: domain/domain_back_nginx
  networks:
    - proxy
  ports:
    - 5000:80
  volumes:
    - ./:/usr/src/domain
  restart: always
#####################################
#   Setup for backend container
#####################################
backend_1:
  container_name: domain_back_server_1
  build:
    context: ./
    dockerfile: Dockerfile
  image: domain/domain_back_server_1
  networks:
    - proxy

  ## always expose, just in case you missed it in Dockerfile, this will expose the port(s)
  ## just in defined networks
  expose:
    - 5000
  volumes:
    - ./:/usr/src/domain
  restart: always
  command: npm start
#####################################
#   Setup for backend container
#####################################
backend_2:
  container_name: domain_back_server_2
  build:
    context: ./
    dockerfile: Dockerfile
  image: domain/domain_back_server_2
  networks:
    - proxy

  ## always expose, just in case you missed it in Dockerfile, this will expose the port(s)
  ## just in defined networks
  expose:
    - 5000
  volumes:
    - ./:/usr/src/domain
  restart: always
  command: npm start

networks:
  proxy:
    external:
      name: proxy

but after all, i recommend jwilder/nginx-proxy


答:
You are assigning your board to your position information with board = position and I think you mean board[position] == 1

```<code>def place(board , player, position ):
    if board[position] == 0: #if the position is unclaimed
        board[position] = player #claim it for the player
    else:
        print(f"place was already taken by player {board[position]}")
    return board

#call using the player number
place(board=create_board() , player=1 , position=(0,0))
</code>```

This function would give you what you are looking for.

Title: Making a draft of tic-tac-toe

Body:
You are assigning your board to your position information with board = position and I think you mean board[position] == 1

def place(board , player, position ):
    if board[position] == 0: #if the position is unclaimed
        board[position] = player #claim it for the player
    else:
        print(f"place was already taken by player {board[position]}")
    return board

#call using the player number
place(board=create_board() , player=1 , position=(0,0))

This function would give you what you are looking for.


问:
Displaying Unlimited Structure of Categories --> Subcategories --> etc?
I imagine this is a fairly common requirement for people when it comes to building any kind of application that relies on sorting and displaying data in categories - any CMS/Forums/Carts etc and I've been tearing my hair out trying to think of a way to show all categories and their children to no avail - the best I've managed is while loop within while loop (however many levels I think I may require) but this defeats the point of programming in my opinion, it needs to be effortlessly extensible.

So, given:

```<code>Category 1
-Sub cat
-Sub cat
--Sub sub cat
--- Sub sub cat
-- Sub sub cat
-Sub cat
Category 2
-Sub cat
-Sub cat
--Sub sub cat
---sub sub sub cat
----sub sub sub sub cat
-sub cat
Category 3
-Sub cat
</code>```

Database fields: ID Name ParentIDS

How would you go about echoing each of the categories in their hierarchy from a database?

I'd post my code, but obviously its massive, given the long-hand way of nesting loops.

I've thought about writing bits of code that find the 'depth' of the category tree but that still isn't cutting it.. ideas?

答: as a hint, you could use Recursion . General idea is available at http://en.wikipedia.org/wiki/Recursion . I.e. you write function that grabs and displays all files and folders in current folder. Then you repeatedly apply same function for each subfolder in same recursion loop. Etc etc etc.</p>

Body:
I imagine this is a fairly common requirement for people when it comes to building any kind of application that relies on sorting and displaying data in categories - any CMS/Forums/Carts etc and I've been tearing my hair out trying to think of a way to show all categories and their children to no avail - the best I've managed is while loop within while loop (however many levels I think I may require) but this defeats the point of programming in my opinion, it needs to be effortlessly extensible.

So, given:

Category 1
-Sub cat
-Sub cat
--Sub sub cat
--- Sub sub cat
-- Sub sub cat
-Sub cat
Category 2
-Sub cat
-Sub cat
--Sub sub cat
---sub sub sub cat
----sub sub sub sub cat
-sub cat
Category 3
-Sub cat

Database fields: ID Name ParentIDS

How would you go about echoing each of the categories in their hierarchy from a database?

I'd post my code, but obviously its massive, given the long-hand way of nesting loops.

I've thought about writing bits of code that find the 'depth' of the category tree but that still isn't cutting it.. ideas?


问:
react-scripts start error code-134, not starting application
I'm trying to create a simple electron application for windows with react.js. Everything was fine, suddenly, I'm encountering some error, which doesn't let me run the application :

Error : https://pastebin.com/awMi4UBM (react-scripts start)

Error : https://pastebin.com/xeH3A1Dx(rescripts start)

My package.json partially :

```<code>   ....
  "scripts": {
    "start": "rescripts start",
    "startb": "react-scripts start",
    "build": "rescripts build",
    "test": "rescripts test",
    "eject": "react-scripts eject",
    "postinstall": "electron-builder install-app-deps",
    "preelectron-pack": "yarn build",
    "electron-pack": "electron-builder build -mw",
    "electron-dev": "concurrently \"BROWSER=none yarn start\" \"wait-on http://localhost:3000 && electron .\""
  },
     ...
</code>```

Pasted here too :

error for react-scripts start:

```<code>yarn run v1.17.3
$ react-scripts start
i ｢wds｣: Project is running at http://0.0.0.0:3000/
i ｢wds｣: webpack output is served from /
i ｢wds｣: Content not from webpack is served from E:\gits\telapoka-dev\telapoka-react\public
i ｢wds｣: 404s will fallback to /index.html
Starting the development server...

<--- Last few GCs --->

[2260:0000019DDCF58EB0]   134175 ms: Scavenge 1375.7 (1424.0) -> 1375.4 (1424.5) MB, 11.0 / 0.0 ms  (average mu = 0.124, current mu = 0.023) allocation failure
[2260:0000019DDCF58EB0]   137527 ms: Mark-sweep 1376.1 (1424.5) -> 1375.8 (1424.5) MB, 3339.8 / 0.0 ms  (average mu = 0.070, current mu = 0.014) allocation failure scavenge might not su
cceed

<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0000001B64F5C5C1]
    1: StubFrame [pc: 0000001B64F4EC05]
Security context: 0x03045269e6e9 <JSObject>
    2: replace [00000304526905E9](this=0x03b789806cc9 <String[80]: E:\gits\telapoka-dev\telapoka-react\node_modules\react-file-viewer\dist\index.js>,0x014e3ebde1c1 <JSRegExp <String[2]:
 \\>>,0x014cc71b23e1 <String[1]: />)
    3: _append [000001ED43DEE861] [E:\gits\telapoka-dev\telapoka-react\node_modules\@babel\gener...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 00007FF761E3C6AA v8::internal::GCIdleTimeHandler::GCIdleTimeHandler+4506
 2: 00007FF761E17416 node::MakeCallback+4534
 3: 00007FF761E17D90 node_module_register+2032
 4: 00007FF76213189E v8::internal::FatalProcessOutOfMemory+846
 5: 00007FF7621317CF v8::internal::FatalProcessOutOfMemory+639
 6: 00007FF762317F94 v8::internal::Heap::MaxHeapGrowingFactor+9620
 7: 00007FF76230EF76 v8::internal::ScavengeJob::operator=+24550
 8: 00007FF76230D5CC v8::internal::ScavengeJob::operator=+17980
 9: 00007FF762316317 v8::internal::Heap::MaxHeapGrowingFactor+2327
10: 00007FF762316396 v8::internal::Heap::MaxHeapGrowingFactor+2454
11: 00007FF762440637 v8::internal::Factory::NewFillerObject+55
12: 00007FF7624BD826 v8::internal::operator<<+73494
13: 0000001B64F5C5C1
error Command failed with exit code 134.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Process finished with exit code 134
</code>```

error for rescripts start:

```<code>yarn electron-dev
yarn run v1.17.3
$ concurrently "BROWSER=none yarn start" "wait-on http://localhost:3000 && electron ."
[0] 'BROWSER' is not recognized as an internal or external command,
[0] operable program or batch file.
[0] BROWSER=none yarn start exited with code 1
</code>```

Dependencies :

```<code>  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "axios": "^0.19.2",
    "concurrently": "^5.1.0",
    "copy-clipboard-js": "^1.0.3",
    "dialog": "^0.3.1",
    "electron-is-dev": "^1.1.0",
    "fs": "^0.0.1-security",
    "react": "^16.12.0",
    "react-ace": "^8.0.0",
    "react-awesome-button": "^6.5.1",
    "react-collapsible": "^2.6.2",
    "react-dom": "^16.12.0",
    "react-file-viewer": "^1.2.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.3.0",
    "react-welcome-page": "^0.2.1",
    "remote": "^0.2.6",
    "wait-on": "^4.0.0"
  },
</code>```

DevDependencies:

```<code>  "devDependencies": {
    "@rescripts/cli": "^0.0.13",
    "@rescripts/rescript-env": "^0.0.11",
    "electron": "^8.0.0",
    "electron-builder": "^22.3.2",
    "typescript": "^3.7.5"
  },
</code>```

答:
delete node_modules

clear cache

delete temp folders

delete package_lock.json if exists(should exist if using npm) or yarn.lock(if using yarn)

as we are using react, it is unofficially official that using npm install may create some problem, use yarn install

Everything should work fine.

Body:
I'm trying to create a simple electron application for windows with react.js. Everything was fine, suddenly, I'm encountering some error, which doesn't let me run the application :

Error : https://pastebin.com/awMi4UBM (react-scripts start)

Error : https://pastebin.com/xeH3A1Dx(rescripts start)

My package.json partially :

   ....
  "scripts": {
    "start": "rescripts start",
    "startb": "react-scripts start",
    "build": "rescripts build",
    "test": "rescripts test",
    "eject": "react-scripts eject",
    "postinstall": "electron-builder install-app-deps",
    "preelectron-pack": "yarn build",
    "electron-pack": "electron-builder build -mw",
    "electron-dev": "concurrently \"BROWSER=none yarn start\" \"wait-on http://localhost:3000 && electron .\""
  },
     ...

Pasted here too :

error for react-scripts start:

yarn run v1.17.3
$ react-scripts start
i ｢wds｣: Project is running at http://0.0.0.0:3000/
i ｢wds｣: webpack output is served from /
i ｢wds｣: Content not from webpack is served from E:\gits\telapoka-dev\telapoka-react\public
i ｢wds｣: 404s will fallback to /index.html
Starting the development server...

<--- Last few GCs --->

[2260:0000019DDCF58EB0]   134175 ms: Scavenge 1375.7 (1424.0) -> 1375.4 (1424.5) MB, 11.0 / 0.0 ms  (average mu = 0.124, current mu = 0.023) allocation failure
[2260:0000019DDCF58EB0]   137527 ms: Mark-sweep 1376.1 (1424.5) -> 1375.8 (1424.5) MB, 3339.8 / 0.0 ms  (average mu = 0.070, current mu = 0.014) allocation failure scavenge might not su
cceed

<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0000001B64F5C5C1]
    1: StubFrame [pc: 0000001B64F4EC05]
Security context: 0x03045269e6e9 <JSObject>
    2: replace [00000304526905E9](this=0x03b789806cc9 <String[80]: E:\gits\telapoka-dev\telapoka-react\node_modules\react-file-viewer\dist\index.js>,0x014e3ebde1c1 <JSRegExp <String[2]:
 \\>>,0x014cc71b23e1 <String[1]: />)
    3: _append [000001ED43DEE861] [E:\gits\telapoka-dev\telapoka-react\node_modules\@babel\gener...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 00007FF761E3C6AA v8::internal::GCIdleTimeHandler::GCIdleTimeHandler+4506
 2: 00007FF761E17416 node::MakeCallback+4534
 3: 00007FF761E17D90 node_module_register+2032
 4: 00007FF76213189E v8::internal::FatalProcessOutOfMemory+846
 5: 00007FF7621317CF v8::internal::FatalProcessOutOfMemory+639
 6: 00007FF762317F94 v8::internal::Heap::MaxHeapGrowingFactor+9620
 7: 00007FF76230EF76 v8::internal::ScavengeJob::operator=+24550
 8: 00007FF76230D5CC v8::internal::ScavengeJob::operator=+17980
 9: 00007FF762316317 v8::internal::Heap::MaxHeapGrowingFactor+2327
10: 00007FF762316396 v8::internal::Heap::MaxHeapGrowingFactor+2454
11: 00007FF762440637 v8::internal::Factory::NewFillerObject+55
12: 00007FF7624BD826 v8::internal::operator<<+73494
13: 0000001B64F5C5C1
error Command failed with exit code 134.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Process finished with exit code 134

error for rescripts start:

yarn electron-dev
yarn run v1.17.3
$ concurrently "BROWSER=none yarn start" "wait-on http://localhost:3000 && electron ."
[0] 'BROWSER' is not recognized as an internal or external command,
[0] operable program or batch file.
[0] BROWSER=none yarn start exited with code 1

Dependencies :

  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "axios": "^0.19.2",
    "concurrently": "^5.1.0",
    "copy-clipboard-js": "^1.0.3",
    "dialog": "^0.3.1",
    "electron-is-dev": "^1.1.0",
    "fs": "^0.0.1-security",
    "react": "^16.12.0",
    "react-ace": "^8.0.0",
    "react-awesome-button": "^6.5.1",
    "react-collapsible": "^2.6.2",
    "react-dom": "^16.12.0",
    "react-file-viewer": "^1.2.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.3.0",
    "react-welcome-page": "^0.2.1",
    "remote": "^0.2.6",
    "wait-on": "^4.0.0"
  },

DevDependencies:

  "devDependencies": {
    "@rescripts/cli": "^0.0.13",
    "@rescripts/rescript-env": "^0.0.11",
    "electron": "^8.0.0",
    "electron-builder": "^22.3.2",
    "typescript": "^3.7.5"
  },


问:
Regroupe all data on firebase for each "getKey()" when using them on app
i have a probleme and i don't know how to solve this.

```<code>userRef.addValueEventListener(new ValueEventListener(){
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for(DataSnapshot priereSnapshot : dataSnapshot.getChildren()){
            //takeFromDataBase
            LocationUser locationUser = priereSnapshot.getValue(LocationUser.class);
            double longitudeD = Double.valueOf(locationUser.locationUserLongitude);
            double latitudeD = Double.valueOf(locationUser.locationUserLatitude);
            //createMarkerFromDataBase
            LatLng Test = new LatLng(latitudeD, longitudeD);
            String idNum = userRef.getKey();
            MarkerOptions optionsTest = new MarkerOptions().position(Test).title("Janaza le: " + locationUser.locationUserDate);
            map.addMarker(optionsTest).setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
            //createLayoutFromInfoUser
            String adresseD = locationUser.locationUserAdresse;
            String dateD = locationUser.locationUserDate;
            String heureD = locationUser.locationUserTime;
            adresse_txt.setText(adresseD);
            date_txt.setText(dateD);
            heure_txt.setText(heureD);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    }
});
</code>```

It's ok when the marker is getting the date and the hour, but when i want to show other information from the same getkey(), it's not working.
For exemple, when i'm clicking on the marker 3 for (12/07/2020), the app need to put the right information relate to this date on firebase from the same getKey, but it's not working.
the thing is that i don't know how to link all data from the same getkey()

Can you help me please?

答:
I'm not sure I understand correctly, but I think your problem may be here:

```<code>String idNum = userRef.getKey();
</code>```

This gets the key of the userRef, which is the location that you listen to.

More likely you want to get the key of the specific user snapshot, for the current iteration of the loop. To do that, you'll want to get the key of the snapshot:

```<code>String idNum = priereSnapshot.getKey();
</code>```

Body:
i have a probleme and i don't know how to solve this.

userRef.addValueEventListener(new ValueEventListener(){
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for(DataSnapshot priereSnapshot : dataSnapshot.getChildren()){
            //takeFromDataBase
            LocationUser locationUser = priereSnapshot.getValue(LocationUser.class);
            double longitudeD = Double.valueOf(locationUser.locationUserLongitude);
            double latitudeD = Double.valueOf(locationUser.locationUserLatitude);
            //createMarkerFromDataBase
            LatLng Test = new LatLng(latitudeD, longitudeD);
            String idNum = userRef.getKey();
            MarkerOptions optionsTest = new MarkerOptions().position(Test).title("Janaza le: " + locationUser.locationUserDate);
            map.addMarker(optionsTest).setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
            //createLayoutFromInfoUser
            String adresseD = locationUser.locationUserAdresse;
            String dateD = locationUser.locationUserDate;
            String heureD = locationUser.locationUserTime;
            adresse_txt.setText(adresseD);
            date_txt.setText(dateD);
            heure_txt.setText(heureD);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    }
});

It's ok when the marker is getting the date and the hour, but when i want to show other information from the same getkey(), it's not working.
For exemple, when i'm clicking on the marker 3 for (12/07/2020), the app need to put the right information relate to this date on firebase from the same getKey, but it's not working.
the thing is that i don't know how to link all data from the same getkey()

Can you help me please?

Body:
I'm not sure I understand correctly, but I think your problem may be here:

String idNum = userRef.getKey();

This gets the key of the userRef, which is the location that you listen to.

More likely you want to get the key of the specific user snapshot, for the current iteration of the loop. To do that, you'll want to get the key of the snapshot:

String idNum = priereSnapshot.getKey();


问:
Laravel returning object to javascript getting Uncaught SyntaxError: Unexpected token '&' error
I am making a call to my db, saving the results in an array.
When I try to use my results in the front end I get a Uncaught SyntaxError: Unexpected token '&' error
I have been trying different combinations of decode or encode on the backend and JSON.parse and stringify on the front end.  What am I doing wrong?

My backend code

```<code>        $data = [];
        $data['service'] = DB::table('servicingdata')->get();
        $data['loans'] = DB::table('loandata')->get();
        return view('welcome', $data);
</code>```

My front end code

```<code><script type="text/javascript">

            console.log({{$loans}})
        </script>
</code>```

答:
If need print html in blade lavarel, you need do this:

Displaying Unescaped Data

By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

```<code>Hello, {!! $name !!}.
</code>```

for more info, the docs.

Body:
I am making a call to my db, saving the results in an array.
When I try to use my results in the front end I get a Uncaught SyntaxError: Unexpected token '&' error
I have been trying different combinations of decode or encode on the backend and JSON.parse and stringify on the front end.  What am I doing wrong?

My backend code

        $data = [];
        $data['service'] = DB::table('servicingdata')->get();
        $data['loans'] = DB::table('loandata')->get();
        return view('welcome', $data);

My front end code

Body:
If need print html in blade lavarel, you need do this:

Displaying Unescaped Data

By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

Hello, {!! $name !!}.

for more info, the docs.


问:
iphone :client-server communication not occuring
i had made the following programming for client server programming but it is not working. the server is not able to receive the request for connection setup.plz help.</p>

```<code>#import "clientserverprogramViewController.h"
#import "secondview.h"
#import <CoreFoundation/CFSocket.h>
#include <sys/socket.h>
#include <netinet/in.h>

NSInputStream *iStream;
NSOutputStream *oStream;

@implementation clientserverprogramViewController

@synthesize  name,filepath,display;

-(IBAction) print {
    NSString *urlStr = serverIP;]
    [display setText : urlStr];

    if (![urlStr isEqualToString:@""]) {
        NSURL *website = [NSURL URLWithString:urlStr];

        if (!website) {
            NSLog(@"%@ is not a valid URL");
            return;
        }
        NSHost *host = [NSHost hostWithName:[website host]];

        [NSStream getStreamsToHost:host port:3000 inputStream:&iStream  outputStream:&oStream];

        [iStream retain];
        [oStream retain];

        [iStream setDelegate:self];
        [oStream setDelegate:self];
        [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                           forMode:NSDefaultRunLoopMode];

        [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                           forMode:NSDefaultRunLoopMode];

        [iStream open];
        [oStream open];
    }
}

-(IBAction) settings {
    [self presentModalViewController:nextview animated: YES];
}

-(IBAction) cancel {
    exit(0);
}

- (void)dealloc {
    [super dealloc];
}

@end
</code>```

答:
You only open streams and don't do anything with them. It's like picking up a phone and not dialing a number. Use NSStreamDelegate protocol to implement data transmission code.

Update:

You have these lines that set the delegate for streams:

```<code>[iStream setDelegate:self];
[oStream setDelegate:self];
</code>```

Now implement methods that are defined in NSStreamDelegate protocol in your own class (AFAIK - there's only one of them). See how to receive/send data from there.

Body:
i had made the following programming for client server programming but it is not working. the server is not able to receive the request for connection setup.plz help.

#import "clientserverprogramViewController.h"
#import "secondview.h"
#import <CoreFoundation/CFSocket.h>
#include <sys/socket.h>
#include <netinet/in.h>

NSInputStream *iStream;
NSOutputStream *oStream;

@implementation clientserverprogramViewController

@synthesize  name,filepath,display;

-(IBAction) print {
    NSString *urlStr = serverIP;]
    [display setText : urlStr];

    if (![urlStr isEqualToString:@""]) {
        NSURL *website = [NSURL URLWithString:urlStr];

        if (!website) {
            NSLog(@"%@ is not a valid URL");
            return;
        }
        NSHost *host = [NSHost hostWithName:[website host]];

        [NSStream getStreamsToHost:host port:3000 inputStream:&iStream  outputStream:&oStream];

        [iStream retain];
        [oStream retain];

        [iStream setDelegate:self];
        [oStream setDelegate:self];
        [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                           forMode:NSDefaultRunLoopMode];

        [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                           forMode:NSDefaultRunLoopMode];

        [iStream open];
        [oStream open];
    }
}

-(IBAction) settings {
    [self presentModalViewController:nextview animated: YES];
}

-(IBAction) cancel {
    exit(0);
}

- (void)dealloc {
    [super dealloc];
}

@end

Body:
You only open streams and don't do anything with them. It's like picking up a phone and not dialing a number. Use NSStreamDelegate protocol to implement data transmission code.

Update:

You have these lines that set the delegate for streams:

[iStream setDelegate:self];
[oStream setDelegate:self];

Now implement methods that are defined in NSStreamDelegate protocol in your own class (AFAIK - there's only one of them). See how to receive/send data from there.


问:
How to pass attachment reference as dataweave 2.0 field mapping value in Mule 4 to consume SOAP Service
How to pass xml attachment reference as dataweave 2.0 field mapping value in Mule 4 to consume SOAP Service.
We need to map xml attachment reference as one of the input parameter to consume SOAP Service with Web Service consumer connector.</p>

答:
The usage of attachments in the Web Service Consumer is explained in the documentation at https://docs.mulesoft.com/connectors/web-service/web-service-consumer-consume#attachments

Example:

```<code><wsc:consume config-ref="config" operation="addClients">
    <wsc:message>
        <wsc:body>#[payload]</wsc:body>
        <wsc:attachments>
          #[{ file1: vars.xmlFile } ]
        </wsc:attachments>
    </wsc:message>
</wsc:consume>
</code>```

Body:
The usage of attachments in the Web Service Consumer is explained in the documentation at https://docs.mulesoft.com/connectors/web-service/web-service-consumer-consume#attachments

Example:

<wsc:consume config-ref="config" operation="addClients">
    <wsc:message>
        <wsc:body>#[payload]</wsc:body>
        <wsc:attachments>
          #[{ file1: vars.xmlFile } ]
        </wsc:attachments>
    </wsc:message>
</wsc:consume>


问:
Is it possible to pre-populate the message in the LinkedIn Share plugin?
We would like to use LinkedIn Share widget; however, we want to pre-populate the message with some default text. Is this possible?

Here is an example of the code for the plugin

```<code><script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>
<script type="IN/Share" data-counter="top"></script>
</code>```

答:
Currently, you cannot pre-populate the message itself.  The Official LinkedIn Sharing Documentation states that the following URL share format is the only acceptable one...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

However!!!  You can still have a preview of your site display for the person about to post the message.  You would do this by means of og: tags...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Example results with og: tags...

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

And when you're all done, test out that you implemented everything correctly with the LinkedIn Post Inspector.

Body:
Currently, you cannot pre-populate the message itself.  The Official LinkedIn Sharing Documentation states that the following URL share format is the only acceptable one...

https://www.linkedin.com/sharing/share-offsite/?url={url}

However!!!  You can still have a preview of your site display for the person about to post the message.  You would do this by means of og: tags...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Example results with og: tags...

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

And when you're all done, test out that you implemented everything correctly with the LinkedIn Post Inspector.


问:
What does it mean to escape a string?
I was reading Does $_SESSION['username'] need to be escaped before getting into an SQL query? and it said "You need to escape every string you pass to the sql query, regardless of its origin". Now I know something like this is really basic. A Google search turned up over 20, 000 results. Stackoverflow alone had 20 pages of results but no one actually explains  what escaping a string is or how to do it. It is just assumed. Can you help me? I want to learn because as always I am making a web app in PHP.

I have looked at:
Inserting Escape Characters, What are all the escape characters in Java?,
Cant escape a string with addcslashes(),
Escape character,
what does mysql_real_escape_string() really do?,
How can i escape double quotes from a string in php?,
MySQL_real_escape_string not adding slashes?,
remove escape sequences from string in php I could go on but I am sure you get the point. This is not laziness.

答:
For simplicity, you could basically imagine the backslash "\" to be a command to the interpreter during runtime.

For e.g. while interpreting this statement:

```<code>$txt = "Hello world!";
</code>```

during the lexical analysis phase ( or when splitting up the statement into individual tokens) these would be the tokens identified
$, txt, =, ", Hello world!, ", and ;

However the backslash within the string will cause an extra set of tokens and is interpreted as a command to do something with the character that immediately follows it :
for e.g.

```<code>$txt = "this \" is escaped";
</code>```

results in the following tokens:
$, txt, =, ", this, \, ", is escaped, ", and ;

the interpreter already knows (or has preset routes it can take) what to do based on the character that succeeds the \ token. So in the case of " it proceeds to treat it as a character and not as the end-of-string command.

Title: What does it mean to escape a string?

Body:
For simplicity, you could basically imagine the backslash "\" to be a command to the interpreter during runtime.

For e.g. while interpreting this statement:

$txt = "Hello world!";

during the lexical analysis phase ( or when splitting up the statement into individual tokens) these would be the tokens identified
$, txt, =, ", Hello world!, ", and ;

However the backslash within the string will cause an extra set of tokens and is interpreted as a command to do something with the character that immediately follows it :
for e.g.

$txt = "this \" is escaped";

results in the following tokens:
$, txt, =, ", this, \, ", is escaped, ", and ;

the interpreter already knows (or has preset routes it can take) what to do based on the character that succeeds the \ token. So in the case of " it proceeds to treat it as a character and not as the end-of-string command.


问:
Make image in picture element fit its container
I have the following code:

#container {
  background: steelblue;
  width: 333px;
  height: 333px;
}

picture img {
  object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <picture>
    <img src="http://placekitten.com/g/300/300" alt="kitten">
  </picture>
</div></code>```

How can I get the picture to fill the container box?

Here's a codepen.

答: It took me a long time to figure out because I was trying to add the style of width: 100% to the picture tag, instead of adding it to the 'img' tag directly.

Body:
I have the following code:

#container {
  background: steelblue;
  width: 333px;
  height: 333px;
}

picture img {
  object-fit: cover;
}

  <picture>

  </picture>

How can I get the picture to fill the container box?

Here's a codepen.