问:
Annotation(stamp) missed after flattened
Annotation(PdfName.STAMP) missed after flattened by itextsharp5.5.13.1.
I have two pdfs. One does work, the other does not work.
Any ideas will be appreciated.

The code is following

```<code>string outFile = inputFile + "_f.pdf";
using (PdfReader pdfReader = new PdfReader(inputFileName))
{
    PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outFile, FileMode.Create, FileAccess.Write, FileShare.None))

    //pdfStamper.FormFlattening = true;
    //pdfStamper.FreeTextFlattening = true;
    pdfStamper.AnnotationFlattening = true;
    //pdfStamper.AcroFields.GenerateAppearances = true;

}
</code>```

答:
The cause is a bug in iTextSharp, annotation flattening does not correctly calculate the position for the flattened annotation if its bounding box does not use the origin as lower left corner.

If you look at the code of PdfStamperImp.FlattenAnnotations(bool), you'll quickly realize that the calculations in the if (app != null) block only make sense if the bounding box is located at the origin or no scaling is necessary for fitting the appearance bounding box into the annotation rectangle.

(As often the lower left corner of the bounding box is the origin, this does not pop up often.)

Thus, for flattening such annotations you have to use a different method for flattening, e.g. like this:

using (PdfReader pdfReader = new PdfReader(inputFileName))
{
    PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outFile, FileMode.Create, FileAccess.Write, FileShare.None));
    ImprovedAnnotationFlattening(pdfStamper);
    pdfStamper.Close();
}
```

<p>with these helper methods:</p>

<pre class="lang-cs prettyprint-override"><code>void ImprovedAnnotationFlattening(PdfStamper pdfStamper)
{
    double[] DEFAULT_MATRIX = { 1, 0, 0, 1, 0, 0 };

    PdfReader reader = pdfStamper.Reader;

    for (int page = 1; page <= reader.NumberOfPages; ++page)
    {
        PdfDictionary pageDic = reader.GetPageN(page);
        PdfArray annots = pageDic.GetAsArray(PdfName.ANNOTS);

        if (annots == null)
            continue;

        for (int idx = 0; idx < annots.Size; ++idx)
        {
            PdfObject annoto = annots.GetDirectObject(idx);
            if (!(annoto is PdfDictionary))
                continue;

            PdfDictionary annDic = (PdfDictionary)annoto;

            PdfNumber ff = annDic.GetAsNumber(PdfName.F);
            int flags = ff != null ? ff.IntValue : 0;
            if ((flags & PdfFormField.FLAGS_PRINT) == 0 || (flags & PdfFormField.FLAGS_HIDDEN) != 0)
                continue;

            PdfObject obj1 = annDic.Get(PdfName.AP);
            if (obj1 == null)
                continue;
            PdfDictionary appDic = obj1 is PdfIndirectReference
                ? (PdfDictionary)PdfReader.GetPdfObject(obj1)
                : (PdfDictionary)obj1;
            PdfObject obj = appDic.Get(PdfName.N);
            PdfStream objDict = appDic.GetAsStream(PdfName.N);

            if (objDict != null)
            {
                Rectangle rect = PdfReader.GetNormalizedRectangle(annDic.GetAsArray(PdfName.RECT));
                Rectangle bbox = PdfReader.GetNormalizedRectangle(objDict.GetAsArray(PdfName.BBOX));

                PdfContentByte cb = pdfStamper.GetOverContent(page);
                cb.SetLiteral("Q ");

                PdfArray matrixArray = objDict.GetAsArray(PdfName.MATRIX);
                double[] matrix = matrixArray != null ? matrixArray.AsDoubleArray() : DEFAULT_MATRIX;
                AffineTransform transform = new AffineTransform(matrix);

                double[] bboxCorners = { bbox.Left, bbox.Bottom, bbox.Right, bbox.Bottom, bbox.Right, bbox.Top, bbox.Left, bbox.Top };
                transform.Transform(bboxCorners, 0, bboxCorners, 0, 4);
                double minX = Min(bboxCorners, 0, 2);
                double maxX = Max(bboxCorners, 0, 2);
                double minY = Min(bboxCorners, 1, 2);
                double maxY = Max(bboxCorners, 1, 2);

                transform.preConcatenate(AffineTransform.GetTranslateInstance(-minX, -minY));
                transform.preConcatenate(AffineTransform.GetScaleInstance(rect.Width/(maxX-minX), rect.Height/(maxY-minY)));
                transform.preConcatenate(AffineTransform.GetTranslateInstance(rect.Left, rect.Bottom));

                transform.GetMatrix(matrix);

                cb.AddFormXObj(objDict, GenerateName(), matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);

                cb.SetLiteral("q ");

                annots.Remove(idx);
                --idx;
            }
        }
    }
}

double Min(double[] array, int start, int step)
{
    double result = array[start];

    for (int i = start + step; i < array.Length; i+=step)
    {
        result = Math.Min(result, array[i]);
    }

    return result;
}

double Max(double[] array, int start, int step)
{
    double result = array[start];

    for (int i = start + step; i < array.Length; i += step)
    {
        result = Math.Max(result, array[i]);
    }

    return result;
}

PdfName GenerateName()
{
    PdfName name = new PdfName("XXX" + formXObjectsCounter);
    ++formXObjectsCounter;
    return name;
}

int formXObjectsCounter = 4711;
</code>```

Beware: I just wrote these methods (copying as much as possible from the original flattening code) and only tested with your example files. Some border conditions might still have to be considered for general use. In particular I did not do all relevant null or 0 tests. Also I did not attempt to support proper tagging.

Body:
Annotation(PdfName.STAMP) missed after flattened by itextsharp5.5.13.1.
I have two pdfs. One does work, the other does not work.
Any ideas will be appreciated.

The code is following

string outFile = inputFile + "_f.pdf";
using (PdfReader pdfReader = new PdfReader(inputFileName))
{
    PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outFile, FileMode.Create, FileAccess.Write, FileShare.None))

    //pdfStamper.FormFlattening = true;
    //pdfStamper.FreeTextFlattening = true;
    pdfStamper.AnnotationFlattening = true;
    //pdfStamper.AcroFields.GenerateAppearances = true;

}

Body:
The cause is a bug in iTextSharp, annotation flattening does not correctly calculate the position for the flattened annotation if its bounding box does not use the origin as lower left corner.

If you look at the code of PdfStamperImp.FlattenAnnotations(bool), you'll quickly realize that the calculations in the if (app != null) block only make sense if the bounding box is located at the origin or no scaling is necessary for fitting the appearance bounding box into the annotation rectangle.

(As often the lower left corner of the bounding box is the origin, this does not pop up often.)

Thus, for flattening such annotations you have to use a different method for flattening, e.g. like this:

using (PdfReader pdfReader = new PdfReader(inputFileName))
{
    PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outFile, FileMode.Create, FileAccess.Write, FileShare.None));
    ImprovedAnnotationFlattening(pdfStamper);
    pdfStamper.Close();
}

with these helper methods:

void ImprovedAnnotationFlattening(PdfStamper pdfStamper)
{
    double[] DEFAULT_MATRIX = { 1, 0, 0, 1, 0, 0 };

    PdfReader reader = pdfStamper.Reader;

    for (int page = 1; page <= reader.NumberOfPages; ++page)
    {
        PdfDictionary pageDic = reader.GetPageN(page);
        PdfArray annots = pageDic.GetAsArray(PdfName.ANNOTS);

        if (annots == null)
            continue;

        for (int idx = 0; idx < annots.Size; ++idx)
        {
            PdfObject annoto = annots.GetDirectObject(idx);
            if (!(annoto is PdfDictionary))
                continue;

            PdfDictionary annDic = (PdfDictionary)annoto;

            PdfNumber ff = annDic.GetAsNumber(PdfName.F);
            int flags = ff != null ? ff.IntValue : 0;
            if ((flags & PdfFormField.FLAGS_PRINT) == 0 || (flags & PdfFormField.FLAGS_HIDDEN) != 0)
                continue;

            PdfObject obj1 = annDic.Get(PdfName.AP);
            if (obj1 == null)
                continue;
            PdfDictionary appDic = obj1 is PdfIndirectReference
                ? (PdfDictionary)PdfReader.GetPdfObject(obj1)
                : (PdfDictionary)obj1;
            PdfObject obj = appDic.Get(PdfName.N);
            PdfStream objDict = appDic.GetAsStream(PdfName.N);

            if (objDict != null)
            {
                Rectangle rect = PdfReader.GetNormalizedRectangle(annDic.GetAsArray(PdfName.RECT));
                Rectangle bbox = PdfReader.GetNormalizedRectangle(objDict.GetAsArray(PdfName.BBOX));

                PdfContentByte cb = pdfStamper.GetOverContent(page);
                cb.SetLiteral("Q ");

                PdfArray matrixArray = objDict.GetAsArray(PdfName.MATRIX);
                double[] matrix = matrixArray != null ? matrixArray.AsDoubleArray() : DEFAULT_MATRIX;
                AffineTransform transform = new AffineTransform(matrix);

                double[] bboxCorners = { bbox.Left, bbox.Bottom, bbox.Right, bbox.Bottom, bbox.Right, bbox.Top, bbox.Left, bbox.Top };
                transform.Transform(bboxCorners, 0, bboxCorners, 0, 4);
                double minX = Min(bboxCorners, 0, 2);
                double maxX = Max(bboxCorners, 0, 2);
                double minY = Min(bboxCorners, 1, 2);
                double maxY = Max(bboxCorners, 1, 2);

                transform.preConcatenate(AffineTransform.GetTranslateInstance(-minX, -minY));
                transform.preConcatenate(AffineTransform.GetScaleInstance(rect.Width/(maxX-minX), rect.Height/(maxY-minY)));
                transform.preConcatenate(AffineTransform.GetTranslateInstance(rect.Left, rect.Bottom));

                transform.GetMatrix(matrix);

                cb.AddFormXObj(objDict, GenerateName(), matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);

                cb.SetLiteral("q ");

                annots.Remove(idx);
                --idx;
            }
        }
    }
}

double Min(double[] array, int start, int step)
{
    double result = array[start];

    for (int i = start + step; i < array.Length; i+=step)
    {
        result = Math.Min(result, array[i]);
    }

    return result;
}

double Max(double[] array, int start, int step)
{
    double result = array[start];

    for (int i = start + step; i < array.Length; i += step)
    {
        result = Math.Max(result, array[i]);
    }

    return result;
}

PdfName GenerateName()
{
    PdfName name = new PdfName("XXX" + formXObjectsCounter);
    ++formXObjectsCounter;
    return name;
}

int formXObjectsCounter = 4711;

Beware: I just wrote these methods (copying as much as possible from the original flattening code) and only tested with your example files. Some border conditions might still have to be considered for general use. In particular I did not do all relevant null or 0 tests. Also I did not attempt to support proper tagging.


来源: stackexchange

问:
ASP.NET Core Template 3.1.5 - serviceDependencies.json
I've just updated Visual Studio 2019 and noted that in new Template (3.1.5) of ASP.NET Core (MVC), there's serviceDependencies.json
Currently in ASP.NET Core docs there no point about this, and I wasn't able to find any in google as well.

I understand, that somehow will be possible to register dependencies in json, but didn't get whole picture. How to use it, and when?

with content:

```<code>{
  "dependencies": {
    "mssql1": {
      "type": "mssql",
      "connectionId": "DefaultConnection"
    }
  }
}
</code>```

答:
After spending a bit more time, I've found that this future is related to Configuring Azure Services and emulators using Visual Studio, and it's not yet documented Undocumented files related to UserSecrets appears on 16.6 Preview4

The goal is to describe services which will be used in Azure App Services, with possibilities of local emulations, for simplifying Development/Deployment routine.

Note from devblog:

Starting with Visual Studio 16.6 Preview 2 the Connected Services tab offers a new experience called Service Dependencies. You can use it to connect your app to Azure services such as Azure SQL, Storage, Key Vault and many others. Wherever possible local emulation options are also available and more are planned for the future.

ContentLicense: CC BY-SA 4.0

Body:
I've just updated Visual Studio 2019 and noted that in new Template (3.1.5) of ASP.NET Core (MVC), there's serviceDependencies.json
Currently in ASP.NET Core docs there no point about this, and I wasn't able to find any in google as well.

I understand, that somehow will be possible to register dependencies in json, but didn't get whole picture. How to use it, and when?

with content:

{
  "dependencies": {
    "mssql1": {
      "type": "mssql",
      "connectionId": "DefaultConnection"
    }
  }
}


问:
Angular JWT with few Roles acess
I want to use several roles for accessing views in the application, if I use one role everything works correctly, however when I use several roles, the views do not give access

My model User have this:

```<code>export class User {
    role: Role[];                // I change - role: Role[] for few roles
    expiresIn: string;
    aud: string;
    iss: string;
    token?: string;
}

export const enum Role {
    Admin = 'admin',
    User = 'user',
    Engineer = 'engineer'
}
</code>```

my backend give my token with with roles:

```<code>//....
role: (2) ["admin", "engineer"]
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ
//....
</code>```

If I use this in login metod

```<code>tokenInfo['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'][0]   - first element in array
</code>```

i have only 1 role, and code work fine, but I can have many users who belong to different roles, and I need the application to give them access if there are at least 1 role

I handle token decoding and getting roles in authorization service

```<code>signin(username:string, password:string ) {
    return this.http.post<User>(`${environment.apiUrl}${environment.apiVersion}Profile/Login`, {username, password})
    .pipe(map(user => {
    if (user && user.token) {
      let tokenInfo = this.getDecodedAccessToken(user.token); // decode token
      this.session = {
        token: user.token,
        role: tokenInfo['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'],     - add this [0]
        expiresIn: tokenInfo.exp,
        aud: tokenInfo.aud,
        iss: tokenInfo.iss,
      }
      localStorage.setItem('currentUser', JSON.stringify(this.session));
      this.currentUserSubject.next(this.session);
    }
    return this.session;
    }))
}
</code>```

sigin metod for example

```<code>Login() {
    this.auth.signin(this.signinForm.value.email, this.signinForm.value.password)
        .pipe(first())
        .subscribe(
            data => {
                console.log("User is logged in");
                this.router.navigate(['/dashboard']);
                this.loading = false;
            });
  }
</code>```

Not sure if I correctly specify multiple access roles

```<code>//......
const adminRoutes: Routes = [
{
    path: 'dashboard',
    loadChildren: () => import('./views/dashboard/dashboard.module').then(m => m.DashboardModule),
    canActivate: [AuthGaurd],

},
{
    path: 'books',
    loadChildren: () => import('./views/books/books.module').then(m => m.BooksModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Admin] }  <- work fine if 1 role
},
{
    path: 'person',
    loadChildren: () => import('./views/person/person.module').then(m => m.PersonModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Admin, Role.Engineer] }  <- if have 1 role - admin - open
 },
 {
    path: 'eqip',
    loadChildren: () => import('./views/eqip/eqip.module').then(m => m.PersonModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Engineer] }  <- not open becouse only admin role
 }];

const routes: Routes = [
{
    path: '',
    redirectTo: 'applayout-sidebar-compact/dashboard/v1',
    pathMatch: 'full',
},
...
{
    path: '**',
    redirectTo: 'others/404'
}];

@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true })],
exports: [RouterModule]
})
export class AppRoutingModule { }
//......
</code>```

and guard sevice

```<code>  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const url: string = state.url;
const currentUser = this.auth.currentUserValue;
// in auth.service.ts
// constructor(private http: HttpClient) {
//   this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
//   this.currentUser = this.currentUserSubject.asObservable();

// }
// public get currentUserValue(): User {
//   return this.currentUserSubject.value;
// }
if (this.auth.isUserLoggedIn()) {

  // test code
  const ter = route.data.roles.includes(currentUser.role) <- Error now here
  console.log(ter)

  // main check role code
  // if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
  //   this.router.navigate(["/"]);
  //   return false;
  // }

  return true;

}
this.auth.setRedirectUrl(url);
this.router.navigate([this.auth.getLoginUrl()]);
return false;
</code>```

}

token in localStorage:

```<code>aud: "Service"
expiresIn: 1591967261
iss: "USs"
role: ["admin", "engineer"]
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHR....
</code>```

change app-routing.module.ts

```<code>@NgModule({
imports: [RouterModule.forRoot(routes, {
    useHash: true,
    initialNavigation: 'enabled',
    paramsInheritanceStrategy: 'always',
    relativeLinkResolution: 'corrected',
    scrollPositionRestoration: 'enabled',
})],
exports: [RouterModule]
</code>```

Error

```<code>Uncaught (in promise): TypeError: Cannot read property 'includes' of undefined
</code>```

TypeError: Cannot read property 'includes' of undefined

答:
This really depends on how you are handling your AuthGuard code. There is a comprehensive tutorial on how to set up your Authentication and Authorization in this guide: https://jasonwatmore.com/post/2018/11/22/angular-7-role-based-authorization-tutorial-with-example

Big area where you could be experiencing the issue is on your AuthGuard. You can have this example from the link I shared above:

```<code>import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { AuthenticationService } from '@/_services';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private authenticationService: AuthenticationService
    ) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const currentUser = this.authenticationService.currentUserValue;
        if (currentUser) {
            // check if route is restricted by role
            if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
                // role not authorised so redirect to home page
                this.router.navigate(['/']);
                return false;
            }

            // authorised so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}
</code>```

You also need to make sure you are passing the right roles into your AuthGuard.

If you want deeper restrictions in the future, there's also this guide:
How to prevent actions by user role in Angular

Hope this helps!

Title: Angular JWT with few Roles acess

Body:
I want to use several roles for accessing views in the application, if I use one role everything works correctly, however when I use several roles, the views do not give access

My model User have this:

export class User {
    role: Role[];                // I change - role: Role[] for few roles
    expiresIn: string;
    aud: string;
    iss: string;
    token?: string;
}

export const enum Role {
    Admin = 'admin',
    User = 'user',
    Engineer = 'engineer'
}

my backend give my token with with roles:

//....
role: (2) ["admin", "engineer"]
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ
//....

If I use this in login metod

tokenInfo['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'][0]   - first element in array

i have only 1 role, and code work fine, but I can have many users who belong to different roles, and I need the application to give them access if there are at least 1 role

I handle token decoding and getting roles in authorization service

signin(username:string, password:string ) {
    return this.http.post<User>(`${environment.apiUrl}${environment.apiVersion}Profile/Login`, {username, password})
    .pipe(map(user => {
    if (user && user.token) {
      let tokenInfo = this.getDecodedAccessToken(user.token); // decode token
      this.session = {
        token: user.token,
        role: tokenInfo['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'],     - add this [0]
        expiresIn: tokenInfo.exp,
        aud: tokenInfo.aud,
        iss: tokenInfo.iss,
      }
      localStorage.setItem('currentUser', JSON.stringify(this.session));
      this.currentUserSubject.next(this.session);
    }
    return this.session;
    }))
}

sigin metod for example

Login() {
    this.auth.signin(this.signinForm.value.email, this.signinForm.value.password)
        .pipe(first())
        .subscribe(
            data => {
                console.log("User is logged in");
                this.router.navigate(['/dashboard']);
                this.loading = false;
            });
  }

Not sure if I correctly specify multiple access roles

//......
const adminRoutes: Routes = [
{
    path: 'dashboard',
    loadChildren: () => import('./views/dashboard/dashboard.module').then(m => m.DashboardModule),
    canActivate: [AuthGaurd],

},
{
    path: 'books',
    loadChildren: () => import('./views/books/books.module').then(m => m.BooksModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Admin] }  <- work fine if 1 role
},
{
    path: 'person',
    loadChildren: () => import('./views/person/person.module').then(m => m.PersonModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Admin, Role.Engineer] }  <- if have 1 role - admin - open
 },
 {
    path: 'eqip',
    loadChildren: () => import('./views/eqip/eqip.module').then(m => m.PersonModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Engineer] }  <- not open becouse only admin role
 }];

const routes: Routes = [
{
    path: '',
    redirectTo: 'applayout-sidebar-compact/dashboard/v1',
    pathMatch: 'full',
},
...
{
    path: '**',
    redirectTo: 'others/404'
}];

@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true })],
exports: [RouterModule]
})
export class AppRoutingModule { }
//......

and guard sevice

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const url: string = state.url;
const currentUser = this.auth.currentUserValue;
// in auth.service.ts
// constructor(private http: HttpClient) {
//   this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
//   this.currentUser = this.currentUserSubject.asObservable();

// }
// public get currentUserValue(): User {
//   return this.currentUserSubject.value;
// }
if (this.auth.isUserLoggedIn()) {

  // test code
  const ter = route.data.roles.includes(currentUser.role) <- Error now here
  console.log(ter)

  // main check role code
  // if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
  //   this.router.navigate(["/"]);
  //   return false;
  // }

  return true;

}
this.auth.setRedirectUrl(url);
this.router.navigate([this.auth.getLoginUrl()]);
return false;

}

token in localStorage:

aud: "Service"
expiresIn: 1591967261
iss: "USs"
role: ["admin", "engineer"]
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHR....

change app-routing.module.ts

@NgModule({
imports: [RouterModule.forRoot(routes, {
    useHash: true,
    initialNavigation: 'enabled',
    paramsInheritanceStrategy: 'always',
    relativeLinkResolution: 'corrected',
    scrollPositionRestoration: 'enabled',
})],
exports: [RouterModule]

Error

Uncaught (in promise): TypeError: Cannot read property 'includes' of undefined

TypeError: Cannot read property 'includes' of undefined

Body:
This really depends on how you are handling your AuthGuard code. There is a comprehensive tutorial on how to set up your Authentication and Authorization in this guide: https://jasonwatmore.com/post/2018/11/22/angular-7-role-based-authorization-tutorial-with-example

Big area where you could be experiencing the issue is on your AuthGuard. You can have this example from the link I shared above:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { AuthenticationService } from '@/_services';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private authenticationService: AuthenticationService
    ) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const currentUser = this.authenticationService.currentUserValue;
        if (currentUser) {
            // check if route is restricted by role
            if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
                // role not authorised so redirect to home page
                this.router.navigate(['/']);
                return false;
            }

            // authorised so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

You also need to make sure you are passing the right roles into your AuthGuard.

If you want deeper restrictions in the future, there's also this guide:
How to prevent actions by user role in Angular

Hope this helps!


问:
Getting subscript out of range error for one variable specifically in an array
I am trying to set up a subroutine that protects and hides worksheets labeled as "restricted" and only protect worksheets labeled as "read only", as specified by the user in certain cells (see the image attached where the user would specify the status for each sheet). The code seems to work without a problem, only for the restricted portion of the sheets. However, as soon as I add the condition to check for the read only sheets, I get the subscript out of range error for the line marked by **, but the weird part is that its for the fourth element of the array always, so not sure why the first 3 work fine, or why adding the second condition stops it from working. If the "Case Read Only" and condition lines are taken out, it works fine. Maybe I am missing something obvious, I am fairly new to VBA as you can see by what is likely my inefficient code. Any help is very appreciated!

User table for selecting restricted and read only sheets

```<code>Private Sub Test()

Dim NumberOfSheets As Integer     'Variable for counting the sheets in model
NumberOfSheets = Application.Sheets.Count - 2 'Number of Sheets ignores Master Cmd sheet, and array starts at 0 so 2 is subtracted
Dim iCounter As Integer           'Counter for looping through the array
ReDim CheckWorksheets(NumberOfSheets) As String 'Restricted worksheet name variable declaration

Worksheets("Master Cmd").Activate 'Activate Master Cmd
Range("C7").Activate 'Activate first cell with sheet name

For iCounter = 0 To NumberOfSheets 'Loop to cycle through worksheet names

    CheckWorksheets(iCounter) = ActiveCell.Offset(iCounter, 0) 'Setting array variable equal to worksheet name

Next iCounter

For iCounter = 0 To NumberOfSheets 'Loop to change restricted worksheets status to very hidden

    Select Case ActiveCell.Offset(iCounter, 2)

        Case "Restricted"
            Worksheets(CheckWorksheets(iCounter)).Protect password:=AdminPassword 'Protecting sheets

            Worksheets(CheckWorksheets(iCounter)).Visible = xlSheetVeryHidden 'Condition to see if status is restricted in Master Cmd sheet

        Case "Read Only"
            **Worksheets(CheckWorksheets(iCounter)).Protect password:=AdminPassword**

    End Select

Next iCounter

End Sub
</code>```

答:
I would ditch the array.  Untested:

```<code>Private Sub Test()
    Const VAL_RESTRICTED = "Restricted"
    Dim wb As Workbook, c As Range

    Set wb = ThisWorkbook '? or ActiveWorkbook ?

    For Each c In wb.Worksheets("Master Cmd").Range("C7").Resize(wb.Worksheets.Count - 1, 1).Cells
        With wb.Worksheets(c.Value)
            .Protect Password:=AdminPassword 'Protecting sheets
            If c.Offset(0, 2).Value = VAL_RESTRICTED Then .Visible = xlSheetVeryHidden
        End With
    Next c
End Sub
</code>```

Edit: to debug the original problem you could modify your code slightly.

```<code>Dim shtName

'...
'...

For iCounter = 0 To NumberOfSheets

    shtName = CheckWorksheets(iCounter)
    Debug.Print iCounter, shtName

    Select Case ActiveCell.Offset(iCounter, 2)

        Case "Restricted"
            Worksheets(shtName).Protect password:=AdminPassword
            Worksheets(shtName).Visible = xlSheetVeryHidden

        Case "Read Only"
            Worksheets(shtName).Protect password:=AdminPassword

    End Select

Next iCounter
</code>```

Note also it's good practice to explcitly qualify your Worksheets with a specific workbook.  In this case it should be ThisWorkbook.Worksheets()

Body:
I am trying to set up a subroutine that protects and hides worksheets labeled as "restricted" and only protect worksheets labeled as "read only", as specified by the user in certain cells (see the image attached where the user would specify the status for each sheet). The code seems to work without a problem, only for the restricted portion of the sheets. However, as soon as I add the condition to check for the read only sheets, I get the subscript out of range error for the line marked by **, but the weird part is that its for the fourth element of the array always, so not sure why the first 3 work fine, or why adding the second condition stops it from working. If the "Case Read Only" and condition lines are taken out, it works fine. Maybe I am missing something obvious, I am fairly new to VBA as you can see by what is likely my inefficient code. Any help is very appreciated!

User table for selecting restricted and read only sheets

Private Sub Test()

Dim NumberOfSheets As Integer     'Variable for counting the sheets in model
NumberOfSheets = Application.Sheets.Count - 2 'Number of Sheets ignores Master Cmd sheet, and array starts at 0 so 2 is subtracted
Dim iCounter As Integer           'Counter for looping through the array
ReDim CheckWorksheets(NumberOfSheets) As String 'Restricted worksheet name variable declaration

Worksheets("Master Cmd").Activate 'Activate Master Cmd
Range("C7").Activate 'Activate first cell with sheet name

For iCounter = 0 To NumberOfSheets 'Loop to cycle through worksheet names

    CheckWorksheets(iCounter) = ActiveCell.Offset(iCounter, 0) 'Setting array variable equal to worksheet name

Next iCounter

For iCounter = 0 To NumberOfSheets 'Loop to change restricted worksheets status to very hidden

    Select Case ActiveCell.Offset(iCounter, 2)

        Case "Restricted"
            Worksheets(CheckWorksheets(iCounter)).Protect password:=AdminPassword 'Protecting sheets

            Worksheets(CheckWorksheets(iCounter)).Visible = xlSheetVeryHidden 'Condition to see if status is restricted in Master Cmd sheet

        Case "Read Only"
            **Worksheets(CheckWorksheets(iCounter)).Protect password:=AdminPassword**

    End Select

Next iCounter

End Sub

Body:
I would ditch the array.  Untested:

Private Sub Test()
    Const VAL_RESTRICTED = "Restricted"
    Dim wb As Workbook, c As Range

    Set wb = ThisWorkbook '? or ActiveWorkbook ?

    For Each c In wb.Worksheets("Master Cmd").Range("C7").Resize(wb.Worksheets.Count - 1, 1).Cells
        With wb.Worksheets(c.Value)
            .Protect Password:=AdminPassword 'Protecting sheets
            If c.Offset(0, 2).Value = VAL_RESTRICTED Then .Visible = xlSheetVeryHidden
        End With
    Next c
End Sub

Edit: to debug the original problem you could modify your code slightly.

Dim shtName

'...
'...

For iCounter = 0 To NumberOfSheets

    shtName = CheckWorksheets(iCounter)
    Debug.Print iCounter, shtName

    Select Case ActiveCell.Offset(iCounter, 2)

        Case "Restricted"
            Worksheets(shtName).Protect password:=AdminPassword
            Worksheets(shtName).Visible = xlSheetVeryHidden

        Case "Read Only"
            Worksheets(shtName).Protect password:=AdminPassword

    End Select

Next iCounter

Note also it's good practice to explcitly qualify your Worksheets with a specific workbook.  In this case it should be ThisWorkbook.Worksheets()


问:
Access-Control-Allow-Headers what does it do exactly and why is it included in a response?
I am following a tutorial for express with the following routes:

```<code>module.exports = function(app) {
    app.use(function(req, res, next) {
        res.header(
            "Access-Control-Allow-Headers",
            "x-access-token, Origin, Content-Type, Accept"
        );
        next();
    });

    app.post(
        '/api/auth/signup',
        [
            verifySignUp.checkDuplicateUsernameOrEmail,
            verifySignUp.checkRolesExist
        ],
        controller.signup
    );

    app.post('/api/auth/signin', controller.signin);
};
</code>```

In layman's terms what do these headers do and why are they included in the response? I thought headers were set as part of a request.

I have also tried the app with the headers removed and it functions fine, so not sure what the use is.

答:
Whenever a request to a server is made from cross origin (say you're requesting an API hosted at Domain A from Domain B), generally the browser blocks them for security reasons. To navigate (this might not be the 'right' word; it's, in fact, the only way of doing) this, there's a mechanism called CORS (cross origin resource sharing) in which the server has to explicitly say that it wants to allow resource sharing with other domains(origins) too. Now, to 'tell' this, the response has to contain right CORS headers which is Access-Control-Allow-Origin header.

So in layman terms, it's just a mechanism to inform the browser, "Hey! Look, I deliberately want to send this response to another origin. Don't block it."

So let's say. if the server responds with a wildcard:

```<code> Access-Control-Allow-Origin: *,
</code>```

This means, the resource can be accessed by any domain.

Similarly, if the server sends

```<code>Access-Control-Allow-Origin: "https://example.com"
</code>```

Then, this means the resource can be accessed only on this particular domain which is "https://example.com"

This is my understanding.

For more technical details, you may read:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

Body:
I am following a tutorial for express with the following routes:

module.exports = function(app) {
    app.use(function(req, res, next) {
        res.header(
            "Access-Control-Allow-Headers",
            "x-access-token, Origin, Content-Type, Accept"
        );
        next();
    });

    app.post(
        '/api/auth/signup',
        [
            verifySignUp.checkDuplicateUsernameOrEmail,
            verifySignUp.checkRolesExist
        ],
        controller.signup
    );

    app.post('/api/auth/signin', controller.signin);
};

In layman's terms what do these headers do and why are they included in the response? I thought headers were set as part of a request.

I have also tried the app with the headers removed and it functions fine, so not sure what the use is.

Body:
Whenever a request to a server is made from cross origin (say you're requesting an API hosted at Domain A from Domain B), generally the browser blocks them for security reasons. To navigate (this might not be the 'right' word; it's, in fact, the only way of doing) this, there's a mechanism called CORS (cross origin resource sharing) in which the server has to explicitly say that it wants to allow resource sharing with other domains(origins) too. Now, to 'tell' this, the response has to contain right CORS headers which is Access-Control-Allow-Origin header.

So in layman terms, it's just a mechanism to inform the browser, "Hey! Look, I deliberately want to send this response to another origin. Don't block it."

So let's say. if the server responds with a wildcard:

 Access-Control-Allow-Origin: *,

This means, the resource can be accessed by any domain.

Similarly, if the server sends

Access-Control-Allow-Origin: "https://example.com"

Then, this means the resource can be accessed only on this particular domain which is "https://example.com"

This is my understanding.

For more technical details, you may read:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers


问:
Plotting highest high of previous 5min on 1min timeframe
I'm attempting to plot the highest high of the previous 5min bar on a 1min timeframe.

This is my script

```<code>//@version=4
study("HTFB B/S 2", overlay=true)

start_y = input(2020, "Year")
start_m = input(5, "Month")
start_d = input(22, "Day")

t5 = time("5")

var float hi1 = na
var float hi5 = na

is_newbar_t5 = not na(t5) and (na(t5[1]) or t5 > t5[1])
canrun = time > timestamp(start_y,start_m,start_d,09,30,0)-1 and time < timestamp(start_y,start_m,start_d,10,0,0)+1

if canrun
    hi1 := high
    if is_newbar_t5
        label.new(bar_index, high, "newbar_t5", yloc=yloc.abovebar)
        hi5 := highest(high,5)
else
    hi1 := na
    hi5 := na

plot(hi1, title="hi1")
plot(hi5, title="hi5", color = is_newbar_t5 ? na : color.lime)
</code>```

Which results in this plot (on ticker SPX)

As you can see, this is not the expected outcome, because it does not plot the highest high of the previous 5 minutes.

I don't see why this doesn't work.

The statement hi5 := highest(high,5) is supposed to get the highest high of the previous 5 1min bars.

But it doesn't seem to do that.

Is this a bug in Pine Script?

Or more likely, an error in my logic?

答:
The problem is caused by the fact that highest() is among the functions that require evaluation on every bar to return the correct value, so we need to force this by taking it outside the if block.

This will produce the expected behavior:

```<code>h = highest(high,5)
if canrun
    hi1 := high
    if is_newbar_t5
        label.new(bar_index, high, "newbar_t5", yloc=yloc.abovebar, color=color.orange)
        hi5 := h
else
    hi1 := na
    hi5 := na
</code>```

With the date set to the 28th:

Body:
I'm attempting to plot the highest high of the previous 5min bar on a 1min timeframe.

This is my script

//@version=4
study("HTFB B/S 2", overlay=true)

start_y = input(2020, "Year")
start_m = input(5, "Month")
start_d = input(22, "Day")

t5 = time("5")

var float hi1 = na
var float hi5 = na

is_newbar_t5 = not na(t5) and (na(t5[1]) or t5 > t5[1])
canrun = time > timestamp(start_y,start_m,start_d,09,30,0)-1 and time < timestamp(start_y,start_m,start_d,10,0,0)+1

if canrun
    hi1 := high
    if is_newbar_t5
        label.new(bar_index, high, "newbar_t5", yloc=yloc.abovebar)
        hi5 := highest(high,5)
else
    hi1 := na
    hi5 := na

plot(hi1, title="hi1")
plot(hi5, title="hi5", color = is_newbar_t5 ? na : color.lime)

Which results in this plot (on ticker SPX)

As you can see, this is not the expected outcome, because it does not plot the highest high of the previous 5 minutes.

I don't see why this doesn't work.

The statement hi5 := highest(high,5) is supposed to get the highest high of the previous 5 1min bars.

But it doesn't seem to do that.

Is this a bug in Pine Script?

Or more likely, an error in my logic?

Body:
The problem is caused by the fact that highest() is among the functions that require evaluation on every bar to return the correct value, so we need to force this by taking it outside the if block.

This will produce the expected behavior:

h = highest(high,5)
if canrun
    hi1 := high
    if is_newbar_t5
        label.new(bar_index, high, "newbar_t5", yloc=yloc.abovebar, color=color.orange)
        hi5 := h
else
    hi1 := na
    hi5 := na

With the date set to the 28th:


问:
Why is accuracy lower 0.01, but prediction very good (99,99%)
I did my first own neural network with TensorFlow 2 in Python.
My idea was to build a neural network which is able to find the solution to translate binary numbers (8-bit) in decimal numbers.
After a few tries: Yeah it works very precise!

But what I don't understand: The accuracy is very low.

Second thing is: The model has to train over 200.000 values!
For 256 possible answers. Where are the failure in my code/model?

```<code>#dataset
def dataset(length, num):
 global testdata, solution
 testdata = np.random.randint(2, size=(num, length))

 solution = testdata.copy()
 solution = np.zeros((num, 1))

 for i in range(num):
  for n in range(length):
   x = testdata [i,length - n -1] * (2 ** n)
   solution [i] += x

length = 8
num = 220000
dataset (length, num)

#Modell
model = tf.keras.models.Sequential([
  tf.keras.layers.Dense(8, activation='relu'),
  tf.keras.layers.Dense(1, activation='relu')
])

model.compile(optimizer='adam',
              loss='mean_squared_error',
              metrics=['accuracy'])

#Training und Evaluate
model.fit(testdata, solution, epochs=4)
model.evaluate(t_testdata,  t_solution, verbose=2)
model.summary()
</code>```

loss: 6.6441e-05 - accuracy: 0.0077

Shouldn't it be like 0.77 or higher?

答:
You should not consider accuracy as metrics for the regression problem, since you are trying to output a single value, even if the small changes in the precision it will result as zero, you can consider below example.

Consider you are trying to predict value 15, and the model returns value 14.99, the resulting accuracy will still be zero.

```<code>m = tf.keras.metrics.Accuracy()
_ = m.update_state([[15]], [[14.99]])
m.result().numpy()
</code>```

Result:

```<code>0.0
</code>```

You can consider the below list of metrics for regression.

Regression metrics

MeanSquaredError class

RootMeanSquaredError class

MeanAbsoluteError class

MeanAbsolutePercentageError class

MeanSquaredLogarithmicError class

CosineSimilarity class

LogCoshError class

I have tried the same problem with one of the above listed metrics and below is the result.

```<code>def bin2int(bin_list):
    #bin_list = [0, 0, 0, 1]
    int_val = ""
    for k in bin_list:
        int_val += str(int(k))
    #int_val = 11011011
    return int(int_val, 2)

def dataset(num):
    # num - no of samples
    bin_len = 8
    X = np.zeros((num, bin_len))
    Y = np.zeros((num))

    for i in range(num):
        X[i] = np.around(np.random.rand(bin_len)).astype(int)
        Y[i] = bin2int(X[i])
    return X, Y

no_of_smaples = 220000
trainX, trainY = dataset(no_of_smaples)
testX, testY = dataset(5)

model = tf.keras.models.Sequential([
  tf.keras.layers.Dense(8, activation='relu'),
  tf.keras.layers.Dense(1, activation='relu')
])

model.compile(optimizer='adam',
              loss='mean_absolute_error',
              metrics=['mse'])

model.fit(trainX, trainY,validation_data = (testX,testY),epochs=4)
model.summary()
</code>```

Output:

```<code>Epoch 1/4
6875/6875 [==============================] - 15s 2ms/step - loss: 27.6938 - mse: 2819.9429 - val_loss: 0.0066 - val_mse: 5.2560e-05
Epoch 2/4
6875/6875 [==============================] - 15s 2ms/step - loss: 0.0580 - mse: 0.1919 - val_loss: 0.0066 - val_mse: 6.0013e-05
Epoch 3/4
6875/6875 [==============================] - 16s 2ms/step - loss: 0.0376 - mse: 0.0868 - val_loss: 0.0106 - val_mse: 1.2932e-04
Epoch 4/4
6875/6875 [==============================] - 15s 2ms/step - loss: 0.0317 - mse: 0.0466 - val_loss: 0.0177 - val_mse: 3.2429e-04
Model: "sequential_11"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_24 (Dense)             multiple                  72
_________________________________________________________________
dense_25 (Dense)             multiple                  9
_________________________________________________________________
round_4 (Round)              multiple                  0
=================================================================
Total params: 81
Trainable params: 81
Non-trainable params: 0
</code>```

Predict:

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

array([[5.993815]], dtype=float32)

Body:
I did my first own neural network with TensorFlow 2 in Python.
My idea was to build a neural network which is able to find the solution to translate binary numbers (8-bit) in decimal numbers.
After a few tries: Yeah it works very precise!

But what I don't understand: The accuracy is very low.

Second thing is: The model has to train over 200.000 values!
For 256 possible answers. Where are the failure in my code/model?

#dataset
def dataset(length, num):
 global testdata, solution
 testdata = np.random.randint(2, size=(num, length))

 solution = testdata.copy()
 solution = np.zeros((num, 1))

 for i in range(num):
  for n in range(length):
   x = testdata [i,length - n -1] * (2 ** n)
   solution [i] += x

length = 8
num = 220000
dataset (length, num)

#Modell
model = tf.keras.models.Sequential([
  tf.keras.layers.Dense(8, activation='relu'),
  tf.keras.layers.Dense(1, activation='relu')
])

model.compile(optimizer='adam',
              loss='mean_squared_error',
              metrics=['accuracy'])

#Training und Evaluate
model.fit(testdata, solution, epochs=4)
model.evaluate(t_testdata,  t_solution, verbose=2)
model.summary()

loss: 6.6441e-05 - accuracy: 0.0077

Shouldn't it be like 0.77 or higher?

Body:
You should not consider accuracy as metrics for the regression problem, since you are trying to output a single value, even if the small changes in the precision it will result as zero, you can consider below example.

Consider you are trying to predict value 15, and the model returns value 14.99, the resulting accuracy will still be zero.

m = tf.keras.metrics.Accuracy()
_ = m.update_state([[15]], [[14.99]])
m.result().numpy()

Result:

0.0

You can consider the below list of metrics for regression.

Regression metrics

MeanSquaredError class

RootMeanSquaredError class

MeanAbsoluteError class

MeanAbsolutePercentageError class

MeanSquaredLogarithmicError class

CosineSimilarity class

LogCoshError class

I have tried the same problem with one of the above listed metrics and below is the result.

def bin2int(bin_list):
    #bin_list = [0, 0, 0, 1]
    int_val = ""
    for k in bin_list:
        int_val += str(int(k))
    #int_val = 11011011
    return int(int_val, 2)

def dataset(num):
    # num - no of samples
    bin_len = 8
    X = np.zeros((num, bin_len))
    Y = np.zeros((num))

    for i in range(num):
        X[i] = np.around(np.random.rand(bin_len)).astype(int)
        Y[i] = bin2int(X[i])
    return X, Y

no_of_smaples = 220000
trainX, trainY = dataset(no_of_smaples)
testX, testY = dataset(5)

model = tf.keras.models.Sequential([
  tf.keras.layers.Dense(8, activation='relu'),
  tf.keras.layers.Dense(1, activation='relu')
])

model.compile(optimizer='adam',
              loss='mean_absolute_error',
              metrics=['mse'])

model.fit(trainX, trainY,validation_data = (testX,testY),epochs=4)
model.summary()

Output:

Epoch 1/4
6875/6875 [==============================] - 15s 2ms/step - loss: 27.6938 - mse: 2819.9429 - val_loss: 0.0066 - val_mse: 5.2560e-05
Epoch 2/4
6875/6875 [==============================] - 15s 2ms/step - loss: 0.0580 - mse: 0.1919 - val_loss: 0.0066 - val_mse: 6.0013e-05
Epoch 3/4
6875/6875 [==============================] - 16s 2ms/step - loss: 0.0376 - mse: 0.0868 - val_loss: 0.0106 - val_mse: 1.2932e-04
Epoch 4/4
6875/6875 [==============================] - 15s 2ms/step - loss: 0.0317 - mse: 0.0466 - val_loss: 0.0177 - val_mse: 3.2429e-04
Model: "sequential_11"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_24 (Dense)             multiple                  72
_________________________________________________________________
dense_25 (Dense)             multiple                  9
_________________________________________________________________
round_4 (Round)              multiple                  0
=================================================================
Total params: 81
Trainable params: 81
Non-trainable params: 0

Predict:

model.predict([[0., 0., 0., 0., 0., 1., 1., 0.]])

array([[5.993815]], dtype=float32)


问:
Windows MessageBox Display Issue with Cross Thread
I am trying to display error message notification using MessageBox.Show() method. But I am getting Cross thread operation issue. I used the below code. How can I resolve the cross thread issue? I tried with MethodInvoker but it is not solving my issue. Kindly suggest me the guidelines to resolve this issue.

```<code> public static class Notification()
 {

   public static void ShowErrorMessage(IWin32Window owner, String msg)
   {
       MessageBox.Show(owner, msg, Caption+ " - " + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }

}
</code>```

Issue :

Cross-thread operation not valid:Control 'MainPage' accessed from a thread other than the thread it was created on.

答:
Here is a full example of calling a MessageBox from another thread.  The trick here is to stash the dispatcher somewhere (like a static variable in some other static class -- in this example, I put the static variable in the same class, but you could put it anywhere)  And then you ask the Dispatcher to Invoke some call on the main thread.  You can do this synchronously (Invoke) or asynchronously (BeginInvoke) to suit your needs.</p>

```<code>static System.Windows.Threading.Dispatcher d; // Save the dispatcher in this global

private void Form1_Load(object sender, EventArgs e)
{
    d = System.Windows.Threading.Dispatcher.CurrentDispatcher;
    System.Threading.Timer t = new System.Threading.Timer((obj) => {
        d.Invoke(() => {
            MessageBox.Show("hi!");
        });
    }, null, 1000, System.Threading.Timeout.Infinite);

}
</code>```

Body:
I am trying to display error message notification using MessageBox.Show() method. But I am getting Cross thread operation issue. I used the below code. How can I resolve the cross thread issue? I tried with MethodInvoker but it is not solving my issue. Kindly suggest me the guidelines to resolve this issue.

 public static class Notification()
 {

   public static void ShowErrorMessage(IWin32Window owner, String msg)
   {
       MessageBox.Show(owner, msg, Caption+ " - " + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }

}

Issue :

Cross-thread operation not valid:Control 'MainPage' accessed from a thread other than the thread it was created on.

Body:
Here is a full example of calling a MessageBox from another thread.  The trick here is to stash the dispatcher somewhere (like a static variable in some other static class -- in this example, I put the static variable in the same class, but you could put it anywhere)  And then you ask the Dispatcher to Invoke some call on the main thread.  You can do this synchronously (Invoke) or asynchronously (BeginInvoke) to suit your needs.

static System.Windows.Threading.Dispatcher d; // Save the dispatcher in this global

private void Form1_Load(object sender, EventArgs e)
{
    d = System.Windows.Threading.Dispatcher.CurrentDispatcher;
    System.Threading.Timer t = new System.Threading.Timer((obj) => {
        d.Invoke(() => {
            MessageBox.Show("hi!");
        });
    }, null, 1000, System.Threading.Timeout.Infinite);

}


问:
Tomcat Java Servlet - Initialize Class on Application Startup
I have a class that takes a bit of time to start up (makes some JNI calls and what not), so it is not feasable to initialize this class everytime a page loads. Is it possible to initialize this class on application startup, then access its methods as pages are being served up?

For Example:

I have MyClass. When the application (tomcat) starts up I would like it to initialze my calss as follows:

```<code>MyClass myClassInstance = new MyClass("arg1", "arg2");
</code>```

Then when a page is called, say /testpage, I would like to make calls to myClassInstance:

```<code>import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import MyClass;

public class TestPage extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        String myResult = myClassInstance.getResult("whatever");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Test</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>" +myResult +"</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}
</code>```

Is this possible?

答:
You can do the initialize of the class inside the servlet's init method.

init() method is invoked when the servlet instance is loaded so it is a good place for expensive operations.

ContentLicense: CC BY-SA 3.0

Body:
I have a class that takes a bit of time to start up (makes some JNI calls and what not), so it is not feasable to initialize this class everytime a page loads. Is it possible to initialize this class on application startup, then access its methods as pages are being served up?

For Example:

I have MyClass. When the application (tomcat) starts up I would like it to initialze my calss as follows:

MyClass myClassInstance = new MyClass("arg1", "arg2");

Then when a page is called, say /testpage, I would like to make calls to myClassInstance:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import MyClass;

public class TestPage extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        String myResult = myClassInstance.getResult("whatever");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("");
        out.println("");
        out.println("<title>Test</title>");
        out.println("");
        out.println("");
        out.println("
" +myResult +"
");
        out.println("");
        out.println("");
    }
}

Is this possible?


问:
Compiling error when trying to run code from github Failed to execute / Compilation failure
```<code>Error:    https://pastebin.com/uaGPJz6N
</code>```

When in my own IDE, I set the project level to 8, which works fine. Once i run the code from my repo to a hosting service called Heroku, it runs the project on 1.5. Any idea how i change this?

```<code>pom.xml:    https://pastebin.com/LS9EicPt
</code>```

Any help is appreciated as most likely something ive missed. thanks :)

答:
According to Heroku documentation they use Java 8 by default.

You can specify a Java version by adding a file called system.properties to your application.

Set a property java.runtime.version in the file:

java.runtime.version=11

Accepted major version values are 1.7, 1.8, 11, 12, 13 and 14. Because the default is 1.8, you don’t need this file if you would like to use Java 8.

Also, in your pom.xml file you seem to incorrectly setup the Java version, it should be (not maven.compiler.testTarget):

```<code><properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>
</code>```

Body:
Error:    https://pastebin.com/uaGPJz6N

When in my own IDE, I set the project level to 8, which works fine. Once i run the code from my repo to a hosting service called Heroku, it runs the project on 1.5. Any idea how i change this?

pom.xml:    https://pastebin.com/LS9EicPt

Any help is appreciated as most likely something ive missed. thanks :)

Body:
According to Heroku documentation they use Java 8 by default.

You can specify a Java version by adding a file called system.properties to your application.

Set a property java.runtime.version in the file:

java.runtime.version=11

Accepted major version values are 1.7, 1.8, 11, 12, 13 and 14. Because the default is 1.8, you don’t need this file if you would like to use Java 8.

Also, in your pom.xml file you seem to incorrectly setup the Java version, it should be (not maven.compiler.testTarget):

<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>


问:
typescript type error cannot assign string or undefined to string[]
Can't fix a typescript error, I check the console log and the regions that Set returns is an array of strings which is exactly what I have for region type in my state. Why would this not work?

Code:

```<code>const [regions, setRegions] = useState<string[]>([])

useEffect(() => {
    if (areasOptions) {
      const regions = [[...new Set(areasOptions.areas.map((item: ListObject) => item.region))]]
      setRegions(regions) // Error
    }
  }, [areasOptions])
</code>```

Error:

Argument of type '(string | undefined)[][]' is not assignable to
  parameter of type 'SetStateAction'. [0]   Type '(string |
  undefined)[][]' is not assignable to type 'string[]'. [0]     Type
  '(string | undefined)[]' is not assignable to type 'string'.

答:
This non-react example should work for you:

function setRegions(abc: string[]) {

}
type ListObject = {
    region: string
}

const areasOptions: {areas: ListObject[]} = {
    areas: [
        {region: "a"},
        {region: "b"}
    ]
}

const regions = [...new Set(areasOptions.areas.map((item) => item.region))]
setRegions(regions)
```

Body:
Can't fix a typescript error, I check the console log and the regions that Set returns is an array of strings which is exactly what I have for region type in my state. Why would this not work?

Code:

const [regions, setRegions] = useState<string[]>([])

useEffect(() => {
    if (areasOptions) {
      const regions = [[...new Set(areasOptions.areas.map((item: ListObject) => item.region))]]
      setRegions(regions) // Error
    }
  }, [areasOptions])

Error:

Argument of type '(string | undefined)[][]' is not assignable to
  parameter of type 'SetStateAction'. [0]   Type '(string |
  undefined)[][]' is not assignable to type 'string[]'. [0]     Type
  '(string | undefined)[]' is not assignable to type 'string'.


问:
Could not create credential for cloudant db on bluemix
We created a Cloudant DB on Bluemix, but failed to create its credential. It shows an error as below:

```<code>Code: BXNIM0424E, Message: Identity has too many policies, Details: Policy cannot be granted because identity 'IBMid-XXXX’ reached the policy limit. PAP error response is: '{"trace":"bss-xxxxxxxxxx”,”errors":[{"code":"request_not_processed","message":"Exceeded maximum policies quota (10500) for account xxxxxxx.”}],”status_code":422}'
</code>```

How can we fix this error?

答:
The policy limits are defined here: https://cloud.ibm.com/docs/iam?topic=iam-iam_limits as well as how to request increasing them if that is needed.

Here is some documentation for the API to remove policies, as well:  https://cloud.ibm.com/apidocs/iam-policy-management#delete-a-policy-by-id

Body:
We created a Cloudant DB on Bluemix, but failed to create its credential. It shows an error as below:

Code: BXNIM0424E, Message: Identity has too many policies, Details: Policy cannot be granted because identity 'IBMid-XXXX’ reached the policy limit. PAP error response is: '{"trace":"bss-xxxxxxxxxx”,”errors":[{"code":"request_not_processed","message":"Exceeded maximum policies quota (10500) for account xxxxxxx.”}],”status_code":422}'

How can we fix this error?


问:
need help understanding this code
this code in book jQuery in action page 131

i don't understand

.trigger('adjustName');

what is adjustName

and Simple explanation for trigger()

thanks :)

```<code>$('#addFilterButton').click( function() {
    var filterItem = $('<div>')
    .addClass('filterItem')
    .appendTo('#filterPane')
    .data('suffix','.' + (filterCount++));
    $('div.template.filterChooser')
    .children().clone().appendTo(filterItem)
    .trigger('adjustName');
});
</code>```

答:
It is a string, the name of a custom event you defined.

E.g. it would trigger the event handler bound by:

```<code>el.bind('adjustName', function(){...});
</code>```

For more information I suggest to have a look at the documentation:

Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user.

Without knowing the context of the code, I would say that calling .trigger() here has no effect, as it is called on the cloneed elements and the event handlers are only cloned if true is passed to clone.

Title: need help understanding this code

Body:
this code in book jQuery in action page 131

i don't understand

.trigger('adjustName');

what is adjustName

and Simple explanation for trigger()

thanks :)

$('#addFilterButton').click( function() {
    var filterItem = $('
')
    .addClass('filterItem')
    .appendTo('#filterPane')
    .data('suffix','.' + (filterCount++));
    $('div.template.filterChooser')
    .children().clone().appendTo(filterItem)
    .trigger('adjustName');
});

Body:
It is a string, the name of a custom event you defined.

E.g. it would trigger the event handler bound by:

el.bind('adjustName', function(){...});

For more information I suggest to have a look at the documentation:

Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user.

Without knowing the context of the code, I would say that calling .trigger() here has no effect, as it is called on the cloneed elements and the event handlers are only cloned if true is passed to clone.


问:
Python create dataframe from multiple dataframes with one having multiple columns
I have 3 NumPy dataframes, which I want to merge with Pandas to a DataFrame in order to some actions.

My dataframes are:

dataframe1, size (38 x 9)

```<code>at1 at2 at3 at4 at5 at6 at7 at8 at9
43  -0.333333   91.3333 -4  31.3333 -1.33333    48.6667 59.6667 11.3333
54.5    4   79  0   12  5.5 24  67  43
40.4    0.4 85.6    0.2 31.6    1.6 45  53.4    8.8
</code>```

dataframe2, size (38 x 1)

```<code>at10
43
25
2
</code>```

dataframe3, size (38 x 1)

```<code>at1
-3
5
20
</code>```

My code so far is the following:

```<code>df = DataFrame (
            {"reps": array1,
            "labels": array2,
            "weight": array3}
            )
</code>```

When I execute this, I receive the following error message:

```<code>Exception: Data must be 1-dimensional
</code>```

I've spent a lot of time trying things, with no luck.
Any idea?

答:
You can covert each np(Numpy) array to pd (Pandas) Dataframe and then concat using pd.concat

```<code>at1=[43,54.5,40.4]
at2=[-0.33333,4,0.4]
at3=[91.3333,79,85.6]
at4=[-4,0,0.2]
at5=[31.3333,12,31.6]
at6=[1.33333,5.5,1.6]
at7=[48.6667,24,45]
at8=[59.6667,67,53.4]
at9=[11.3333,43,8.8]

base_at=np.array([at1,at2,at3,at4,at5,at6,at7,at8,at9])
</code>```

This is your array1

```<code>at10=np.array([43,25,2])
at11=np.array([-3,5,20])
</code>```

These are your array2 and array3 respectively.

```<code>at10_df=pd.DataFrame(at10).T
base_at_df=pd.DataFrame(base_at)
at11_df=pd.DataFrame(at11).T
</code>```

You converted all three arrays into respective DataFrames

```<code>pd.concat([base_at_df,at10_df,at11_df])
</code>```

And this is your DataFrame comprising of all three arrays

Here's the solution, I haven't changed the name of column, I think you can handle from here.

Body:
I have 3 NumPy dataframes, which I want to merge with Pandas to a DataFrame in order to some actions.

My dataframes are:

dataframe1, size (38 x 9)

at1 at2 at3 at4 at5 at6 at7 at8 at9
43  -0.333333   91.3333 -4  31.3333 -1.33333    48.6667 59.6667 11.3333
54.5    4   79  0   12  5.5 24  67  43
40.4    0.4 85.6    0.2 31.6    1.6 45  53.4    8.8

dataframe2, size (38 x 1)

at10
43
25
2

dataframe3, size (38 x 1)

at1
-3
5
20

My code so far is the following:

df = DataFrame (
            {"reps": array1,
            "labels": array2,
            "weight": array3}
            )

When I execute this, I receive the following error message:

Exception: Data must be 1-dimensional

I've spent a lot of time trying things, with no luck.
Any idea?

Body:
You can covert each np(Numpy) array to pd (Pandas) Dataframe and then concat using pd.concat

at1=[43,54.5,40.4]
at2=[-0.33333,4,0.4]
at3=[91.3333,79,85.6]
at4=[-4,0,0.2]
at5=[31.3333,12,31.6]
at6=[1.33333,5.5,1.6]
at7=[48.6667,24,45]
at8=[59.6667,67,53.4]
at9=[11.3333,43,8.8]

base_at=np.array([at1,at2,at3,at4,at5,at6,at7,at8,at9])

This is your array1

at10=np.array([43,25,2])
at11=np.array([-3,5,20])

These are your array2 and array3 respectively.

at10_df=pd.DataFrame(at10).T
base_at_df=pd.DataFrame(base_at)
at11_df=pd.DataFrame(at11).T

You converted all three arrays into respective DataFrames

pd.concat([base_at_df,at10_df,at11_df])

And this is your DataFrame comprising of all three arrays

Here's the solution, I haven't changed the name of column, I think you can handle from here.


问:
Cloud Storage Set CORS to allow download Firebase function
I have a firebase function which serves a website as per below:

```<code>const app = express();
app.use(express.static("my-website"));
exports.app = functions.https.onRequest(app);
</code>```

Where my-website has my-website/subfolder/index.html and my-website/subfolder/index.js. I have deployed the function and it successfully serves up index.html and index.js. However, index.js is attempting to download a file from Cloud Storage but is getting the following error:

```<code>Access to XMLHttpRequest at 'https://storage.cloud.google.com/my-project.appspot.com/my-project-files/data.csv' from origin 'https://us-central1-my-project.cloudfunctions.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

I am not using the firebase cloud storage web library, because the code is already written using the d3.js library as per below, and I can't change it:

```<code>d3.queue()
    .defer(
      d3.csv,
      "https://storage.cloud.google.com/my-project.appspot.com/my-project-files/data.csv"
    )
    .defer(d3.json, "data/config.json")
    .defer(d3.json, "data/geog.json")
    .await(ready);
</code>```

This code generates the following request:

```<code>:authority: storage.cloud.google.com
:method: GET
:path: /my-project.appspot.com/my-project-files/data.csv
:scheme: https
accept: text/csv,*/*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
origin: https://us-central1-my-project.cloudfunctions.net
pragma: no-cache
referer: https://us-central1-my-project.cloudfunctions.net/app/my-website/subfolder/index.html
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36
</code>```

I have set a CORS policy on my bucket to allow requests from my cloud functions, gsutil cors get gs://my-project.appspot.com returns:

```<code>[{"maxAgeSeconds": 3600,
"method": ["GET"],
"origin": ["https://us-central1-my-project.cloudfunctions.net"],
"responseHeader": ["Content-Type"]}]
</code>```

I am not sure where to go from here. What am I doing wrong?

答: I worked out that the problem is the Cloud Storage doesn't actually let you allow CORS for the storage.cloud.google.com, instead you have to use storage.googleapis.com.

Body:
I have a firebase function which serves a website as per below:

const app = express();
app.use(express.static("my-website"));
exports.app = functions.https.onRequest(app);

Where my-website has my-website/subfolder/index.html and my-website/subfolder/index.js. I have deployed the function and it successfully serves up index.html and index.js. However, index.js is attempting to download a file from Cloud Storage but is getting the following error:

Access to XMLHttpRequest at 'https://storage.cloud.google.com/my-project.appspot.com/my-project-files/data.csv' from origin 'https://us-central1-my-project.cloudfunctions.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am not using the firebase cloud storage web library, because the code is already written using the d3.js library as per below, and I can't change it:

d3.queue()
    .defer(
      d3.csv,
      "https://storage.cloud.google.com/my-project.appspot.com/my-project-files/data.csv"
    )
    .defer(d3.json, "data/config.json")
    .defer(d3.json, "data/geog.json")
    .await(ready);

This code generates the following request:

:authority: storage.cloud.google.com
:method: GET
:path: /my-project.appspot.com/my-project-files/data.csv
:scheme: https
accept: text/csv,*/*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
origin: https://us-central1-my-project.cloudfunctions.net
pragma: no-cache
referer: https://us-central1-my-project.cloudfunctions.net/app/my-website/subfolder/index.html
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36

I have set a CORS policy on my bucket to allow requests from my cloud functions, gsutil cors get gs://my-project.appspot.com returns:

[{"maxAgeSeconds": 3600,
"method": ["GET"],
"origin": ["https://us-central1-my-project.cloudfunctions.net"],
"responseHeader": ["Content-Type"]}]

I am not sure where to go from here. What am I doing wrong?


问:
Unable To Get The Property Value Of An Object That Comes From An API Call In REACTJS
Why I'm unable to access the property value of the Object That comes from an API Call ?

I Have Two Components In The React App, Both Are Given Below.

Here Is First Component Named 'Weather'

```<code>import React, { useState, useEffect } from "react";
import Styles from "./Weather.module.css";
import WeatherCard from "../Weather Card/WeatherCard.component";

const Weather = () => {
  // Initializing State
  //For Location
  const [location, setLocation] = useState("karachi");
  //For Location
  //For Query
  const [query, setQuery] = useState(location);
  //For Query
  //For Weather Data
  const [weatherData, setWeatherData] = useState({});

  //For Weather Data

  // Initializing State

  // Calling data through api

  useEffect(() => {
    const fetchingData = async () => {
      let url = `https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=6a571911f99d7d02c4974a178ff1d933`;

      let responseFromFetch = await fetch(url); // getting obj of promise.

      let data = await responseFromFetch.json(); // getting api/weather data.

      setWeatherData(data); // setting state that comes from api.
    };

    fetchingData(); // calling func that brings the data
  }, [query]);

  const handleSubmit = (e) => {
    e.preventDefault();
    setQuery(location);
    setLocation("");
  };

  return (
    <>
      <div className={Styles.formContainer}>
        <form onSubmit={handleSubmit}>
          <input
            className={Styles.inputField}
            type="text"
            placeholder="Know Your City Weather!"
            value={location}
            onChange={(e) => setLocation(e.target.value)}
          />
          <button type="submit" className={Styles.button}>
            Search
          </button>
        </form>
      </div>

      <WeatherCard weatherData={weatherData} />
    </>
  );
};

export default Weather;
</code>```

Okay, Now Here is the second Component Named 'WeatherCard'

```<code>import React, { Component } from "react";
import Styles from "../Whether/Weather.module.css";

export default class WeatherCard extends Component {
  render() {
    const accessObj = this.props.weatherData;

    console.log(accessObj); // getting whole obj - No error,
    console.log(accessObj.name); // getting the value of the key "name" - No error,       accessObj.name isn't an object
    console.log(accessObj.sys); // getting obj - No error,          accessObj.sys is an object
    console.log(accessObj.sys.country); // Not getting the value of key "country" - Error

    if (accessObj !== "undefined") {
      return (
        <>
          <div className={Styles.wrapper}>
            <div className={Styles.weatherContainer}>
              <div className={Styles.cityContainer}>
                <p className={Styles.city}>{accessObj.name}</p>
              </div>

              <div className={Styles.countryContainer}>
                {/* I want here to use the value of the property... But country is not available here.  */}

                <p className={Styles.country}>{accessObj.sys.country}</p>
              </div>

              <div className={Styles.tempContainer}>
                <p className={Styles.temp}>30 C</p>
              </div>

              <div className={Styles.humidityContainer}>
                <p className={Styles.humidity}>100</p>
              </div>
            </div>
          </div>
        </>
      );
    }
  }
}
</code>```

You Can Also see the error that occur's in the browser. screenshot link is HERE . Unable to attach the screenshot of the error here, because I'm new in this platform!

Advance Thanks For The Help !

答:
getting too fancy sometimes can lead you to some issues like the one here basically the problem is that your useEffect hook has a void type as it does not returns anything.

...

const fetchingData = () => {
      let url = `https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=6a571911f99d7d02c4974a178ff1d933`;

     return fetch(url)
        .then(res => res.json())
        .then(data => myFunctionThatSetsTheState(data)).catch(console.error)
};

useEffect(() => fetchingData(), [query]);

....
```

Body:
Why I'm unable to access the property value of the Object That comes from an API Call ?

I Have Two Components In The React App, Both Are Given Below.

Here Is First Component Named 'Weather'

import React, { useState, useEffect } from "react";
import Styles from "./Weather.module.css";
import WeatherCard from "../Weather Card/WeatherCard.component";

const Weather = () => {
  // Initializing State
  //For Location
  const [location, setLocation] = useState("karachi");
  //For Location
  //For Query
  const [query, setQuery] = useState(location);
  //For Query
  //For Weather Data
  const [weatherData, setWeatherData] = useState({});

  //For Weather Data

  // Initializing State

  // Calling data through api

  useEffect(() => {
    const fetchingData = async () => {
      let url = `https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=6a571911f99d7d02c4974a178ff1d933`;

      let responseFromFetch = await fetch(url); // getting obj of promise.

      let data = await responseFromFetch.json(); // getting api/weather data.

      setWeatherData(data); // setting state that comes from api.
    };

    fetchingData(); // calling func that brings the data
  }, [query]);

  const handleSubmit = (e) => {
    e.preventDefault();
    setQuery(location);
    setLocation("");
  };

  return (
    <>

        <form onSubmit={handleSubmit}>
          <input
            className={Styles.inputField}
            type="text"
            placeholder="Know Your City Weather!"
            value={location}
            onChange={(e) => setLocation(e.target.value)}
          />
          <button type="submit" className={Styles.button}>
            Search
          </button>
        </form>

      <WeatherCard weatherData={weatherData} />
    </>
  );
};

export default Weather;

Okay, Now Here is the second Component Named 'WeatherCard'

import React, { Component } from "react";
import Styles from "../Whether/Weather.module.css";

export default class WeatherCard extends Component {
  render() {
    const accessObj = this.props.weatherData;

    console.log(accessObj); // getting whole obj - No error,
    console.log(accessObj.name); // getting the value of the key "name" - No error,       accessObj.name isn't an object
    console.log(accessObj.sys); // getting obj - No error,          accessObj.sys is an object
    console.log(accessObj.sys.country); // Not getting the value of key "country" - Error

    if (accessObj !== "undefined") {
      return (
        <>

{accessObj.name}

                {/* I want here to use the value of the property... But country is not available here.  */}

{accessObj.sys.country}

30 C

100

        </>
      );
    }
  }
}

You Can Also see the error that occur's in the browser. screenshot link is HERE . Unable to attach the screenshot of the error here, because I'm new in this platform!

Advance Thanks For The Help !


问:
Should I use jquery or jquery mobile or iPad web pages?
I am making a web page "app" for the iPad or ios devices.  Should I use jquery mobile or just regular jquery?  After all they're only web pages aren't they?  Is jquery proper no good for me?  Do I need mobile jquery?

Thanks.

答:
I would look into two frameworks. Both are open source unless you are incorporated them into your own framework and offering this up as a service or an API.

These frameworks are Sencha Touch and JQuery Mobile.

Sencha Touch is great. It looks fantastic, is an official release (out of beta unlike JQMobile), and pretty easy to use. Everything is created through Javascript, which is then rendered behind the scenes into the proper HTML/CSS. It's got great documentation, a good forum of users.

Downsides - it's only completely customizable after learning SASS/Compass.

JQuery Mobile is awesome as well. Everything is created using HTML5 attributes, and then the library runs over the HTML you create and renders everything properly. Very easy to use as well, and easy to customize.

Downsides - Doesn't look as nice (yet), and is still in beta (or might even be alpha?)


问:
Degrees, Minutes and seconds regex
I need validate with RegEx an sexagecimal value, for example: 24° 12' 55,4" or 32° 24' 15,4".

For now, I have the next RegEx, that matches successful with degrees and minutes:

```<code>^([0-8][0-9]|[9][0])°\s([0-4][0-9]|[5][9])'$
</code>```

But, when add the seconds validator have problems:

```<code>^([0-8][0-9]|[9][0])°\s([0-4][0-9]|[5][9])'\s([0-4][0-9]|[5][9],[0-9])''$
</code>```

I'm new with RegEx, any ideas?

答:
I've recently had a similar use case but had to match variations such as

```<code>14° 58' 40.068" E
36°57'9" N
</code>```

so I came up with

```<code>(\d+)\s?\°\s?(\d+)\s?\'\s?(\d{1,}\.?\,?\d{0,}?)\"\s?(N|W|S|E)
</code>```

Testable here.

Title: Degrees, Minutes and seconds regex

Body:
I need validate with RegEx an sexagecimal value, for example: 24° 12' 55,4" or 32° 24' 15,4".

For now, I have the next RegEx, that matches successful with degrees and minutes:

^([0-8][0-9]|[9][0])°\s([0-4][0-9]|[5][9])'$

But, when add the seconds validator have problems:

^([0-8][0-9]|[9][0])°\s([0-4][0-9]|[5][9])'\s([0-4][0-9]|[5][9],[0-9])''$

I'm new with RegEx, any ideas?

Body:
I've recently had a similar use case but had to match variations such as

14° 58' 40.068" E
36°57'9" N

so I came up with

(\d+)\s?\°\s?(\d+)\s?\'\s?(\d{1,}\.?\,?\d{0,}?)\"\s?(N|W|S|E)

Testable here.


问:
Table id no longer being returned - failure on update in Flask app (psycopg2-sqlalchemy-postgresql)
I am working on a Flask app using PostgreSQL and SQLAlchemy with psycopg2. I develop on Debian bullseye/sid and have a test website running on Ubuntu 18.04.4 LTS. Recently (and I regret that I cannot pin down the update), I have been unable to commit anything to the database in the flask shell on my local machine; every attempt fails with a NotNullViolation on the primary key table id. This has always previously been handled. The following is an example of the error:

```<code>>>> db.session.commit()
Traceback (most recent call last):
  File "[...]DandyLion/.venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1283, in _execute_context [...]
sqlalchemy.exc.IntegrityError: (psycopg2.errors.NotNullViolation) null value in column "id" violates not-null constraint
DETAIL:  Failing row contains (null, 1, Resolve database id problem, null_id_problem, null, null, 2020-05-28 08:01:00.184953, null, 2020-05-30 17:00:00, [...]).
[SQL: INSERT INTO tasks (user_id, title, slug, [...]) RETURNING tasks.id]
</code>```

The database is setup with the following:

```<code>app.config.from_object(Config)
db = SQLAlchemy(app)
</code>```

I will confess ignorance as to the implementation details but notice that the SQL statement in the traceback indicates that tasks.id ought to be returned. This has always previously been the case.

The following are the versions on the (working) server and the local setup:

```
python:      3.8.3,  3.6.8
psycopg2:    2.8.4,  2.8.4
sqlalchemy:  1.3.12, 1.3.17
PostgresSQL: 10.12,  12.3
```

I initially investigated psycopg2, changing the version in my Pipfile on the local machine. To investigate further, I would appreciate any insights into the most likely point of failure. Can anybody help with this?

答:
As explained in this SO post you are trying to post a NULL value as your id.

You can solve it either by providing a value for the id or change the id column type to serial.

Body:
I am working on a Flask app using PostgreSQL and SQLAlchemy with psycopg2. I develop on Debian bullseye/sid and have a test website running on Ubuntu 18.04.4 LTS. Recently (and I regret that I cannot pin down the update), I have been unable to commit anything to the database in the flask shell on my local machine; every attempt fails with a NotNullViolation on the primary key table id. This has always previously been handled. The following is an example of the error:

>>> db.session.commit()
Traceback (most recent call last):
  File "[...]DandyLion/.venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1283, in _execute_context [...]
sqlalchemy.exc.IntegrityError: (psycopg2.errors.NotNullViolation) null value in column "id" violates not-null constraint
DETAIL:  Failing row contains (null, 1, Resolve database id problem, null_id_problem, null, null, 2020-05-28 08:01:00.184953, null, 2020-05-30 17:00:00, [...]).
[SQL: INSERT INTO tasks (user_id, title, slug, [...]) RETURNING tasks.id]

The database is setup with the following:

app.config.from_object(Config)
db = SQLAlchemy(app)

I will confess ignorance as to the implementation details but notice that the SQL statement in the traceback indicates that tasks.id ought to be returned. This has always previously been the case.

The following are the versions on the (working) server and the local setup:

python:      3.8.3,  3.6.8
psycopg2:    2.8.4,  2.8.4
sqlalchemy:  1.3.12, 1.3.17
PostgresSQL: 10.12,  12.3

I initially investigated psycopg2, changing the version in my Pipfile on the local machine. To investigate further, I would appreciate any insights into the most likely point of failure. Can anybody help with this?


问:
Kafka consumer is taking time to recognize new partition
I was running a test where kafka consumer was reading data from multiple partitions of a topic. While the process was running I added more partitions. It took around 5 minutes for consumer thread to read data from the new partition. I have found this configuration "topic.metadata.refresh.interval.ms", but this is for producer only. Is there a similar config for consumer too?</p>

答: I changed "metadata.max.age.ms" parameter value to refresh matadata https://kafka.apache.org/documentation/#consumerconfigs_metadata.max.age.ms</p>


问:
new code disables ability to use escape to quit
I added the following code to move a stimulus on the screen, and I just noticed that this seems to disable the ability to escape the code with the 'escape' key anywhere in the script. I am still very new to Javascript, any pointers would be appreciated. </p>

```<code>//the following appears a few time throughout the script
// check for quit (typically the Esc key)
if (psychoJS.experiment.experimentEnded ||
  psychoJS.eventManager.getKeys({ keyList: ['escape'] }).length > 0) {
  return quitPsychoJS('The [Escape] key was pressed. Goodbye!', false);
}

// and then later in the script

// FRR ----- manual entry BEGIN; copy this before "function TestRoutineBegin(trials) {"
// code to move stimulus
var xforce;
spacepressed = 0; // reset each trial
xforce = 0; // initially set speed ('force') to 0. It increases in steps of 1 as long as key is down

function resetXforce (event) {
  xforce = 0; // if finger has been lifted, go back to speed 0
}

function getKeyResponse (event) { // check for responses
  //psychoJS.eventManager.clearEvents({eventType:'keyboard'});
  var thisResp = psychoJS.eventManager.getKeys();
  console.log(thisResp);

  if (spacepressed == 0) {
    if ('left' == thisResp[0]) {
      xforce--;  // decrease angle with increasing acceleration the longer key pressed
      angle = (angle + xforce); //plus not minus here since xforce may become negative
      myx = (0.25 * Math.sin((((Math.PI * 2) * angle) / 360)));
      myy = (0.25 * Math.cos((((Math.PI * 2) * angle) / 360)));
      //smallcircle2.setPos([myx, myy]);
      image_on_circ_test.setPos([myx, myy]);

    }
    if ('right' == thisResp[0]) {
      xforce++; //increase angle with increasing acceleration the longer key pressed
      angle = (angle + xforce);
      myx = (0.25 * Math.sin((((Math.PI * 2) * angle) / 360)));
      myy = (0.25 * Math.cos((((Math.PI * 2) * angle) / 360)));
      //smallcircle2.setPos([myx, myy]);
      image_on_circ_test.setPos([myx, myy]);
    }

    if ('space' == thisResp[0]) {
      LocCol2 = 'white';  // if response locked with spacebar
      //document.removeEventListener("keydown", getKeyResponse); //once spacebar is pressed, dont except any more input
      spacepressed = 1;//new 28.05 15:55
    }

    /* if (psychoJS.eventManager.getKeys({keyList:['space']}).length > 0) {
      LocCol2 = 'white'  // if response locked with spacebar
      spacepressed = 1;
      }*/

    psychoJS.eventManager.clearEvents({ eventType: 'keyboard' });
  }
}

window.addEventListener('keydown', getKeyResponse); //tried keydown as well, with the same problem
window.addEventListener('keyup', resetXforce);

//  FRR------------------------------------------------------------------------------
</code>```

答:
It appears that the getKeyResponse() function is always clearing all keyboard events:

function getKeyResponse (event) {
  ...
  if (spacepressed == 0) {
    ...
    psychoJS.eventManager.clearEvents({ eventType: 'keyboard' });
  }
}
```

<p>I would add a check for escape key at the beginning of that function:</p>

<pre class="lang-js prettyprint-override"><code>function getKeyResponse (event) {
  ...

  // new addition
  if (psychoJS.eventManager.getKeys({ keyList: ['escape'] }).length > 0) {
    return;
  }

  if (spacepressed == 0) {
    ...
    psychoJS.eventManager.clearEvents({ eventType: 'keyboard' });
  }
}
</code>```

Body:
I added the following code to move a stimulus on the screen, and I just noticed that this seems to disable the ability to escape the code with the 'escape' key anywhere in the script. I am still very new to Javascript, any pointers would be appreciated.

//the following appears a few time throughout the script
// check for quit (typically the Esc key)
if (psychoJS.experiment.experimentEnded ||
  psychoJS.eventManager.getKeys({ keyList: ['escape'] }).length > 0) {
  return quitPsychoJS('The [Escape] key was pressed. Goodbye!', false);
}

// and then later in the script

// FRR ----- manual entry BEGIN; copy this before "function TestRoutineBegin(trials) {"
// code to move stimulus
var xforce;
spacepressed = 0; // reset each trial
xforce = 0; // initially set speed ('force') to 0. It increases in steps of 1 as long as key is down

function resetXforce (event) {
  xforce = 0; // if finger has been lifted, go back to speed 0
}

function getKeyResponse (event) { // check for responses
  //psychoJS.eventManager.clearEvents({eventType:'keyboard'});
  var thisResp = psychoJS.eventManager.getKeys();
  console.log(thisResp);

  if (spacepressed == 0) {
    if ('left' == thisResp[0]) {
      xforce--;  // decrease angle with increasing acceleration the longer key pressed
      angle = (angle + xforce); //plus not minus here since xforce may become negative
      myx = (0.25 * Math.sin((((Math.PI * 2) * angle) / 360)));
      myy = (0.25 * Math.cos((((Math.PI * 2) * angle) / 360)));
      //smallcircle2.setPos([myx, myy]);
      image_on_circ_test.setPos([myx, myy]);

    }
    if ('right' == thisResp[0]) {
      xforce++; //increase angle with increasing acceleration the longer key pressed
      angle = (angle + xforce);
      myx = (0.25 * Math.sin((((Math.PI * 2) * angle) / 360)));
      myy = (0.25 * Math.cos((((Math.PI * 2) * angle) / 360)));
      //smallcircle2.setPos([myx, myy]);
      image_on_circ_test.setPos([myx, myy]);
    }

    if ('space' == thisResp[0]) {
      LocCol2 = 'white';  // if response locked with spacebar
      //document.removeEventListener("keydown", getKeyResponse); //once spacebar is pressed, dont except any more input
      spacepressed = 1;//new 28.05 15:55
    }

    /* if (psychoJS.eventManager.getKeys({keyList:['space']}).length > 0) {
      LocCol2 = 'white'  // if response locked with spacebar
      spacepressed = 1;
      }*/

    psychoJS.eventManager.clearEvents({ eventType: 'keyboard' });
  }
}

window.addEventListener('keydown', getKeyResponse); //tried keydown as well, with the same problem
window.addEventListener('keyup', resetXforce);

//  FRR------------------------------------------------------------------------------

Body:
It appears that the getKeyResponse() function is always clearing all keyboard events:

function getKeyResponse (event) {
  ...
  if (spacepressed == 0) {
    ...
    psychoJS.eventManager.clearEvents({ eventType: 'keyboard' });
  }
}

I would add a check for escape key at the beginning of that function:

function getKeyResponse (event) {
  ...

  // new addition
  if (psychoJS.eventManager.getKeys({ keyList: ['escape'] }).length > 0) {
    return;
  }

  if (spacepressed == 0) {
    ...
    psychoJS.eventManager.clearEvents({ eventType: 'keyboard' });
  }
}


问:
Node JS spawn result: python3: can't open file './test': [Errno 2] No such file or directory
So I'm trying to run a simple python file called test.py through the Node JS child process, however it keeps saying that python3: can't open file './test': [Errno 2] No such file or directory. I tried everything to fix this error. For example, the python script ran successfully from the same directory the typescript file is present, I even tried the full path, the relative path for the python file and it still didn't work. I kindly request someone too look into this, thank you!

test.py

    import sys
    print("hello world")
    sys.stdout.flush()
```

<pre class="lang-js prettyprint-override"><code>var spawn = require("child_process").spawn;
var child = await spawn("python3", ['./test.py']);
let dataMain = "";
child.stdout.on("data", (data: Buffer) => {
    // Do something with the data returned from python script
    console.log(data); // buffer data
    dataMain += data.toString();
});

child.stdout.on("end", () => {
     console.log("end");
     console.log(dataMain);
});
child.stderr.pipe(process.stderr); // prints out the error

</code>```

答: Worked with ${process.cwd()}/test.py

Body:
So I'm trying to run a simple python file called test.py through the Node JS child process, however it keeps saying that python3: can't open file './test': [Errno 2] No such file or directory. I tried everything to fix this error. For example, the python script ran successfully from the same directory the typescript file is present, I even tried the full path, the relative path for the python file and it still didn't work. I kindly request someone too look into this, thank you!

test.py

    import sys
    print("hello world")
    sys.stdout.flush()

var spawn = require("child_process").spawn;
var child = await spawn("python3", ['./test.py']);
let dataMain = "";
child.stdout.on("data", (data: Buffer) => {
    // Do something with the data returned from python script
    console.log(data); // buffer data
    dataMain += data.toString();
});

child.stdout.on("end", () => {
     console.log("end");
     console.log(dataMain);
});
child.stderr.pipe(process.stderr); // prints out the error

Body: Worked with ${process.cwd()}/test.py


问:
Cakephp 3.x how do i extend the cake schema class?
I would like to add a few additional options to the schema $_fieldDefaults array for some documenting purposes.
I tried copying the class and including it in the model in place of the cake schema class but somewhere down the line  the constructor is looking for an instance of the cake schema class and not accepting my class.

Does anyone know if it is possable to simply swap out the schema class or would I need to start from the ground up and create a while new db driver to achieve my goals?

If i need to create a driver does anyone have an example or list of requirements needed to do so?

As a side thought,
I am also tossing around the idea of declaring a new public var in the table which holds the schema fields  and its options and then just looping through it in the build schema function so that I can always refer to the new variable instead of the schema object however that sounds wrong-ish but simpler than re inventing the wheel.

答:
You might just need to extend the original class in your new class.</p>

```<code><?php
namespace \your\new\class\namespace

use original\schema\class\schemaClassName

class YourNewClass extends schemaClassName {

//new code here

}
</code>```

Body:
You might just need to extend the original class in your new class.

<?php
namespace \your\new\class\namespace

use original\schema\class\schemaClassName

class YourNewClass extends schemaClassName {

//new code here

}


问:
Is there a way that a Party can be notified that a Flow has been completed?
Taking as an example the flow described in the Corda documentation (see here), how can Bob receive the notification that the transaction he just signed has been completed, without polling his own vault?
Does a specific callback exist?

I need that the CorDapp running on Bob node communicates to another system the status of the transaction in real-time

Thanks a lot

答:
In addition to Ashutosh's answer,

Inside a SpringBoot webserver that identifies an API to start your flow, you can use proxy.startTrackedFlowDynamic() (where proxy is your node's RPC connection); it returns a FlowProgressHandle which you can use to subscribe to flow events.


问:
PHP session cookies not saving
COOKIES that i get back from the server
it's as if my browser does not save this PHPSESID cookie

This is my index.php :

```<code><?php
  session_start();
  require_once 'bootstrap.php';

 if(session_id()==''){

     $_SESSION["var"] = 12;
 }
 else echo $_SESSION['var'];

</code>```

it does not return anything, how can this be ?

答:
You need to call session_start(); on every page you want use $_SESSION</p>

```<code><?php
  require_once 'bootstrap.php';
  session_start();

  if(!isset($_SESSION["var"])){
     $_SESSION["var"] = 12;
  }
  else {
     echo $_SESSION['var'];
  }

</code>```

Title: PHP session cookies not saving

Body:
COOKIES that i get back from the server
it's as if my browser does not save this PHPSESID cookie

This is my index.php :

<?php
  session_start();
  require_once 'bootstrap.php';

 if(session_id()==''){

     $_SESSION["var"] = 12;
 }
 else echo $_SESSION['var'];

it does not return anything, how can this be ?

Body:
You need to call session_start(); on every page you want use $_SESSION

<?php
  require_once 'bootstrap.php';
  session_start();

  if(!isset($_SESSION["var"])){
     $_SESSION["var"] = 12;
  }
  else {
     echo $_SESSION['var'];
  }


问:
Why do undefined constants evaluate to true?
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

```<code><?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>
</code>```

The above example prints 'Huh?'

Thanks so much for your help! :)

答:
Try defined('WHATEVER_THIS_ISNT_DEFINED')

When PHP encounters a constant that is not defined, it throws an E_NOTICE, and uses the constant name you've tried to use as a string. That's why your snippet prints Huh!, because a non-empty string (which is not "0") will evaluate to true.

From the manual:

If you use an undefined constant, PHP
  assumes that you mean the name of the
  constant itself, just as if you called
  it as a string (CONSTANT vs
  "CONSTANT"). An error of level
  E_NOTICE will be issued when this
  happens.

If you set your error reporting level to report E_NOTICEs, which is a good practice during development, you will also see the notice thrown.

PHP Constant Syntax

defined()

Casting to Boolean

error_reporting

error_reporting() function

Body:
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

<?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>

The above example prints 'Huh?'

Thanks so much for your help! :)