问:
why I have the error Unauthorized even if I put the crossorigin?
I am developing a rest service which recovers data from a database, on the backend side everything works well (I tested in postman it recovers the desired data as you can see in this photo):

but frontend level it does not work it gives me the following error:

yet I put the crossorigin in my controller, but it still does not work :(

here is the code for my controller:

```<code>package com.app.habilitation.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.app.habilitation.entity.EmploiEntity;
import com.app.habilitation.service.EmploiService;

@RestController
@SpringBootApplication
@CrossOrigin(origins = "*")
@RequestMapping("/emploi")
public class EmploiController {

    private EmploiService emploiService;

    @Autowired
    public EmploiController(EmploiService theemploiService) {
        emploiService=theemploiService;
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/getall")
    public List<EmploiEntity> getAll() {

        return emploiService.findAll();

    }
}
</code>```

and this is my dao  code :

```<code>package com.app.habilitation.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.app.habilitation.entity.EmploiEntity;

public interface EmploiDao extends JpaRepository<EmploiEntity, Integer> {

}
</code>```

and this is my entity code :

```<code>package com.app.habilitation.entity;

import java.sql.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="ORDO_DEP_P_EMPLOI")
public class EmploiEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="IDENTIFIANT")
    private Integer id;

    @Column(name="CODE")
    private String code;

    @Column(name="NOM")
    private String nom;

    @Column(name="DATEEFFET")
    private Date dateeffet;

    @Column(name="DATEFIN")
    private Date datefin;

    @Column(name="STATUT")
    private String statut;

    /*@OneToMany(mappedBy = "emploi", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    private List<UserEntity> users; */

    public Integer getId() {
        return id;
    }

    /* public List<UserEntity> getUsers() {
        return users;
    }

    public void setUsers(List<UserEntity> users) {
        this.users = users;
    } */

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public Date getDateeffet() {
        return dateeffet;
    }

    public void setDateeffet(Date dateeffet) {
        this.dateeffet = dateeffet;
    }

    public Date getDatefin() {
        return datefin;
    }

    public void setDatefin(Date datefin) {
        this.datefin = datefin;
    }

    public String getStatut() {
        return statut;
    }

    public void setStatut(String statut) {
        this.statut = statut;
    }

    public EmploiEntity(Integer id, String code, String nom, Date dateeffet, Date datefin, String statut
            ) {
        this.id = id;
        this.code = code;
        this.nom = nom;
        this.dateeffet = dateeffet;
        this.datefin = datefin;
        this.statut = statut;

    }

    public EmploiEntity() {
    }

    @Override
    public String toString() {
        return "EmploiEntity [id=" + id + ", code=" + code + ", nom=" + nom + ", dateeffet=" + dateeffet + ", datefin="
                + datefin + ", statut=" + statut + "]";
    }

}
</code>```

this is my emploiService code :

```<code>package com.app.habilitation.service;

import java.util.List;

import com.app.habilitation.entity.EmploiEntity;

public interface EmploiService {

    public List<EmploiEntity> findAll();
}
</code>```

and this is my emploiServiceImpl :

```<code>package com.app.habilitation.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.habilitation.dao.EmploiDao;
import com.app.habilitation.entity.EmploiEntity;

@Service
public class EmploiServiceImpl implements EmploiService {

    private EmploiDao emploiDao;

    public EmploiServiceImpl(EmploiDao theEmploiDao) {
        emploiDao=theEmploiDao;
    }

    @Override
    @Transactional
    public List<EmploiEntity> findAll() {

        return emploiDao.findAll();
    }

}
</code>```

this is my component.html :

```<code><div class="inscription">

    <!-- Default form register -->
    <form class="text-center border border-light p-5">

        <p class="h4 mb-4">Sign up</p>

        <div class="form-row mb-4">
            <div class="col">
                <!-- First name -->
                <input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" placeholder="Votre prenom">
            </div>
            <div class="col">
                <!-- Last name -->
                <input type="text" id="nom" class="form-control" [(ngModel)]="user.nom" placeholder="Votre nom">
            </div>
        </div>

        <!-- E-mail -->
        <input type="email" id="email" class="form-control mb-4" [(ngModel)]="user.email" placeholder="Votre email">

        <!-- Login -->
        <input type="text" id="login" class="form-control mb-4" [(ngModel)]="user.login" placeholder="Votre login">

        <!-- Password -->
        <input type="password" id="password" class="form-control" [(ngModel)]="user.motdepasse" placeholder="Votre mot de passe"
            aria-describedby="defaultRegisterFormPasswordHelpBlock">

        <!-- Confirmation mot de passe -->
        <input type="password" id="password-confirmation" class="form-control"
            placeholder="Confirmez votre mot de passe" [(ngModel)]="user.confirmationmotdepasse" aria-describedby="defaultRegisterFormPasswordHelpBlock">

        <!-- Entite -->

            <select class="form-control" id="entite" [(ngModel)]="user.entite">
                <option value="" selected disabled>Votre entité</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>

        <!-- Emploi -->

        <select class="form-control" id="emploi" [(ngModel)]="user.emploi">
            <option value="" selected disabled >Votre emploi</option>
            <ul class="list-unstyled navbar-list">

                <li *ngFor="let tempAllEmploi of allEmploi">

                    <option>{{ tempAllEmploi.NOM}}</option>
                </li>
            </ul>

        </select>

        <!-- Sign up button -->
        <button mdbBtn color="info" block="true" class="my-4" type="submit" id="btn-inscription" class="btn-primary btn-lg" (click)="inscriptionts()">Valider</button>

    </form>
    <!-- Default form register -->

</div>
</code>```

(focus more on this code ):

```<code><!-- Emploi -->

        <select class="form-control" id="emploi" [(ngModel)]="user.emploi">
            <option value="" selected disabled >Votre emploi</option>
            <ul class="list-unstyled navbar-list">

                <li *ngFor="let tempAllEmploi of allEmploi">

                    <option>{{ tempAllEmploi.NOM}}</option>
                </li>
            </ul>

        </select>
</code>```

this is my emploi class :

```<code>import { User } from './user';

export class Emploi {

    IDENTIFIANT: number;
    CODE: string;
    NOM: string;
    DATEEFFET: Date;
    DATEFIN: Date;
    STATUT: string;
    users: User;
}
</code>```

and this is my .ts component :

```<code>import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/model/user';
import { RestapiService } from 'src/app/restapi.service';
import { Emploi } from 'src/app/model/emploi';

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

  allEmploi: Emploi[];
  user: any;
  //user: Users= new Users(0,0,0,"","","","","",new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),"",0,new Date("dd-mm-yyyy"),"","");

  constructor(private Userservice: RestapiService) { }

  ngOnInit(): void {

    this.getAllEmploi();
  }

  public getAllEmploi(){

    this.Userservice.getEmploi().subscribe(

      data => {
        this.allEmploi=data;
      }
    );
  }

  public inscriptionts(){

    let resp=this.Userservice.inscription(this.user);
    resp.subscribe((data)=> this.user=data);
  }
}
</code>```

and this is my service :

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Emploi } from './model/emploi';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RestapiService {

  url_getAllEmploi="http://localhost:8484/emploi/getall";

  constructor(private http:HttpClient) { }

  public inscription(user) {

    return this.http.post("http://localhost:8484/addUser", user);
  }

  public getEmploi(): Observable<Emploi[]> {

    return this.http.get<Emploi[]>(this.url_getAllEmploi);
  }

  public login(username:string, password:string) {
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)})
    return this.http.get("http://localhost:8484/", {headers, responseType:'text' as 'json'});
  }

  public getUsers() {
    let username="hr";
    let password="hr";
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)});
    return this.http.get("http://localhost:8484/getUsers", {headers});
  }
}
</code>```

(focus more on this code in service) :

```<code>package com.app.habilitation.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.app.habilitation.entity.EmploiEntity;

public interface EmploiDao extends JpaRepository<EmploiEntity, Integer> {

}
</code>```0

can someone help me please ??

答:
Have you tried: </p>

```<code>  public getEmploi(): Observable<Emploi[]> {
    return this.http.get<Emploi[]>(this.url_getAllEmploi, {responseType:'text'});
  }
</code>```

Body:
I am developing a rest service which recovers data from a database, on the backend side everything works well (I tested in postman it recovers the desired data as you can see in this photo):

but frontend level it does not work it gives me the following error:

yet I put the crossorigin in my controller, but it still does not work :(

here is the code for my controller:

package com.app.habilitation.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.app.habilitation.entity.EmploiEntity;
import com.app.habilitation.service.EmploiService;

@RestController
@SpringBootApplication
@CrossOrigin(origins = "*")
@RequestMapping("/emploi")
public class EmploiController {

    private EmploiService emploiService;

    @Autowired
    public EmploiController(EmploiService theemploiService) {
        emploiService=theemploiService;
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/getall")
    public List<EmploiEntity> getAll() {

        return emploiService.findAll();

    }
}

and this is my dao  code :

package com.app.habilitation.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.app.habilitation.entity.EmploiEntity;

public interface EmploiDao extends JpaRepository<EmploiEntity, Integer> {

}

and this is my entity code :

package com.app.habilitation.entity;

import java.sql.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="ORDO_DEP_P_EMPLOI")
public class EmploiEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="IDENTIFIANT")
    private Integer id;

    @Column(name="CODE")
    private String code;

    @Column(name="NOM")
    private String nom;

    @Column(name="DATEEFFET")
    private Date dateeffet;

    @Column(name="DATEFIN")
    private Date datefin;

    @Column(name="STATUT")
    private String statut;

    /*@OneToMany(mappedBy = "emploi", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    private List<UserEntity> users; */

    public Integer getId() {
        return id;
    }

    /* public List<UserEntity> getUsers() {
        return users;
    }

    public void setUsers(List<UserEntity> users) {
        this.users = users;
    } */

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public Date getDateeffet() {
        return dateeffet;
    }

    public void setDateeffet(Date dateeffet) {
        this.dateeffet = dateeffet;
    }

    public Date getDatefin() {
        return datefin;
    }

    public void setDatefin(Date datefin) {
        this.datefin = datefin;
    }

    public String getStatut() {
        return statut;
    }

    public void setStatut(String statut) {
        this.statut = statut;
    }

    public EmploiEntity(Integer id, String code, String nom, Date dateeffet, Date datefin, String statut
            ) {
        this.id = id;
        this.code = code;
        this.nom = nom;
        this.dateeffet = dateeffet;
        this.datefin = datefin;
        this.statut = statut;

    }

    public EmploiEntity() {
    }

    @Override
    public String toString() {
        return "EmploiEntity [id=" + id + ", code=" + code + ", nom=" + nom + ", dateeffet=" + dateeffet + ", datefin="
                + datefin + ", statut=" + statut + "]";
    }

}

this is my emploiService code :

package com.app.habilitation.service;

import java.util.List;

import com.app.habilitation.entity.EmploiEntity;

public interface EmploiService {

    public List<EmploiEntity> findAll();
}

and this is my emploiServiceImpl :

package com.app.habilitation.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.habilitation.dao.EmploiDao;
import com.app.habilitation.entity.EmploiEntity;

@Service
public class EmploiServiceImpl implements EmploiService {

    private EmploiDao emploiDao;

    public EmploiServiceImpl(EmploiDao theEmploiDao) {
        emploiDao=theEmploiDao;
    }

    @Override
    @Transactional
    public List<EmploiEntity> findAll() {

        return emploiDao.findAll();
    }

}

this is my component.html :

    <form class="text-center border border-light p-5">

Sign up

                <input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" placeholder="Votre prenom">

                <input type="text" id="nom" class="form-control" [(ngModel)]="user.nom" placeholder="Votre nom">

        <input type="email" id="email" class="form-control mb-4" [(ngModel)]="user.email" placeholder="Votre email">

        <input type="text" id="login" class="form-control mb-4" [(ngModel)]="user.login" placeholder="Votre login">

        <input type="password" id="password" class="form-control" [(ngModel)]="user.motdepasse" placeholder="Votre mot de passe"
            aria-describedby="defaultRegisterFormPasswordHelpBlock">

        <input type="password" id="password-confirmation" class="form-control"
            placeholder="Confirmez votre mot de passe" [(ngModel)]="user.confirmationmotdepasse" aria-describedby="defaultRegisterFormPasswordHelpBlock">

            <select class="form-control" id="entite" [(ngModel)]="user.entite">
                <option value="" selected disabled>Votre entité</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>

        <select class="form-control" id="emploi" [(ngModel)]="user.emploi">
            <option value="" selected disabled >Votre emploi</option>

                    <option>{{ tempAllEmploi.NOM}}</option>

        </select>

        <button mdbBtn color="info" block="true" class="my-4" type="submit" id="btn-inscription" class="btn-primary btn-lg" (click)="inscriptionts()">Valider</button>

    </form>

(focus more on this code ):

        <select class="form-control" id="emploi" [(ngModel)]="user.emploi">
            <option value="" selected disabled >Votre emploi</option>

                    <option>{{ tempAllEmploi.NOM}}</option>

        </select>

this is my emploi class :

import { User } from './user';

export class Emploi {

    IDENTIFIANT: number;
    CODE: string;
    NOM: string;
    DATEEFFET: Date;
    DATEFIN: Date;
    STATUT: string;
    users: User;
}

and this is my .ts component :

import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/model/user';
import { RestapiService } from 'src/app/restapi.service';
import { Emploi } from 'src/app/model/emploi';

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

  allEmploi: Emploi[];
  user: any;
  //user: Users= new Users(0,0,0,"","","","","",new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),"",0,new Date("dd-mm-yyyy"),"","");

  constructor(private Userservice: RestapiService) { }

  ngOnInit(): void {

    this.getAllEmploi();
  }

  public getAllEmploi(){

    this.Userservice.getEmploi().subscribe(

      data => {
        this.allEmploi=data;
      }
    );
  }

  public inscriptionts(){

    let resp=this.Userservice.inscription(this.user);
    resp.subscribe((data)=> this.user=data);
  }
}

and this is my service :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Emploi } from './model/emploi';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RestapiService {

  url_getAllEmploi="http://localhost:8484/emploi/getall";

  constructor(private http:HttpClient) { }

  public inscription(user) {

    return this.http.post("http://localhost:8484/addUser", user);
  }

  public getEmploi(): Observable<Emploi[]> {

    return this.http.get<Emploi[]>(this.url_getAllEmploi);
  }

  public login(username:string, password:string) {
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)})
    return this.http.get("http://localhost:8484/", {headers, responseType:'text' as 'json'});
  }

  public getUsers() {
    let username="hr";
    let password="hr";
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)});
    return this.http.get("http://localhost:8484/getUsers", {headers});
  }
}

(focus more on this code in service) :

public getEmploi(): Observable<Emploi[]> {

    return this.http.get<Emploi[]>(this.url_getAllEmploi);
  }

can someone help me please ??

Body:
Have you tried:

  public getEmploi(): Observable<Emploi[]> {
    return this.http.get<Emploi[]>(this.url_getAllEmploi, {responseType:'text'});
  }


来源: stackexchange

问:
what is the type of a pointer to dynamically allocated memory of pointers of type char?
I am new to C. I need to allocate memory and store pointers in it. These pointers are of type char. So what is the type of the pointer to that memory? char? or long because addresses are just numbers?</p>

答:
Assuming I understand what you’re asking for, it sounds like this is what you want:

```<code>#define N 10 // or however many elements you want
...
char **arr = malloc( sizeof *arr * N ); // sizeof *arr == sizeof (char *)
</code>```

Each arr[i] will have type char *.

If you want an array of char, then it would be

```<code>char *arr = malloc( sizeof *arr * N );
</code>```

and each arr[i] will have type char.

So, general rule, if you want to allocate an array of type T, use

```<code>T *arr = malloc( sizeof *arr * N );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Assuming I understand what you’re asking for, it sounds like this is what you want:

#define N 10 // or however many elements you want
...
char **arr = malloc( sizeof *arr * N ); // sizeof *arr == sizeof (char *)

Each arr[i] will have type char *.

If you want an array of char, then it would be

char *arr = malloc( sizeof *arr * N );

and each arr[i] will have type char.

So, general rule, if you want to allocate an array of type T, use

T *arr = malloc( sizeof *arr * N );


问:
Find unused CSS rule and js script in a web project?
HI..
My project has many CSS roles and JavaScript scripts that are not used in my project. How can I find these unused files?</p>

答:
When I've needed to do this, I've used the search feature of the dev environment to search all files in the solution for the filename of the file I suspected wasn't used. If it didn't get found, or got found only within the file itself, I knew it wasn't used, since the files have to be referenced (via a script or link element, or in a script that combines and minifies them) to be used.

Of course, if you're building filenames up from component parts, that won't work. For instance, if you have code with a variable basename containing "foo" and then code outputting a script tag like:

```<code><script src="<%=basename%>-bar.js"></script>
</code>```

...then my search for "foo-bar.js" won't find it. If that's a real possibility in your code, you'll have to find all the script and link elements and check them yourself...

...or experiment: Deploy your solution, and on the server, delete each file you think might not be used, refresh on the browser, and look for 404s in the console.

...all of which relates to unused files. If you think the files are referenced, but their contents aren't used, you'll either need to selectively remove the references and see what breaks (blech, a manual and error-prone process) or you'll need a code coverage analysis tool. This question here on StackOverflow discusses code coverage analysis tools for JavaScript, and Spudley's answer here points to a "code coverage" (for lack of a better term) tool for CSS.

ContentLicense: CC BY-SA 3.0

Body:
When I've needed to do this, I've used the search feature of the dev environment to search all files in the solution for the filename of the file I suspected wasn't used. If it didn't get found, or got found only within the file itself, I knew it wasn't used, since the files have to be referenced (via a script or link element, or in a script that combines and minifies them) to be used.

Of course, if you're building filenames up from component parts, that won't work. For instance, if you have code with a variable basename containing "foo" and then code outputting a script tag like:

<script src="<%=basename%>-bar.js"></script>

...then my search for "foo-bar.js" won't find it. If that's a real possibility in your code, you'll have to find all the script and link elements and check them yourself...

...or experiment: Deploy your solution, and on the server, delete each file you think might not be used, refresh on the browser, and look for 404s in the console.

...all of which relates to unused files. If you think the files are referenced, but their contents aren't used, you'll either need to selectively remove the references and see what breaks (blech, a manual and error-prone process) or you'll need a code coverage analysis tool. This question here on StackOverflow discusses code coverage analysis tools for JavaScript, and Spudley's answer here points to a "code coverage" (for lack of a better term) tool for CSS.


问:
Query when data is not available in one of the table
I have 2 tables A & B. I used left join on table, but when left table(A) does not have I want query which return right table values with same columns as blank from left table.

I used below query and it is working fine for me. Is there any better way to built same query to improve performance?

```<code>IF EXISTS(SELECT 1 FROM TableA WHERE Project_ID = @Project_ID)
    SELECT
        A.ID, A.Project_ID, A.Column1, A.Column2,
        B.Column
    FROM
        TableA A
    LEFT JOIN
        TableB B ON A.Project_ID = B.Project_ID
    WHERE
        A.Project_ID = @Project_ID
ELSE
    SELECT
        B.ID, B.Project_ID, '' As Column1, '' As Column2, B.Column
    FROM
        TableB
    WHERE
        project_ID = @Project_ID
</code>```

答:
If I understand correctly, you want a full join:

```<code>select A.ID, A.Project_ID, A.Column1, A.Column2, B.Column
from (select a.*
      from TableA a
      where A.Project_ID = @Project_ID
     ) a full join
     (select b.*
      from TableB b
      where b.Project_ID = @Project_ID
     ) b
     on a.Project_ID = b.Project_ID;
</code>```

When filtering with full joins, I usually find it most sensible to use subqueries.

Body:
I have 2 tables A & B. I used left join on table, but when left table(A) does not have I want query which return right table values with same columns as blank from left table.

I used below query and it is working fine for me. Is there any better way to built same query to improve performance?

IF EXISTS(SELECT 1 FROM TableA WHERE Project_ID = @Project_ID)
    SELECT
        A.ID, A.Project_ID, A.Column1, A.Column2,
        B.Column
    FROM
        TableA A
    LEFT JOIN
        TableB B ON A.Project_ID = B.Project_ID
    WHERE
        A.Project_ID = @Project_ID
ELSE
    SELECT
        B.ID, B.Project_ID, '' As Column1, '' As Column2, B.Column
    FROM
        TableB
    WHERE
        project_ID = @Project_ID

Body:
If I understand correctly, you want a full join:

select A.ID, A.Project_ID, A.Column1, A.Column2, B.Column
from (select a.*
      from TableA a
      where A.Project_ID = @Project_ID
     ) a full join
     (select b.*
      from TableB b
      where b.Project_ID = @Project_ID
     ) b
     on a.Project_ID = b.Project_ID;

When filtering with full joins, I usually find it most sensible to use subqueries.


问:
Continuing a Project using Pycharm instead of Visual Studio
I am currently in the middle of a Django project and considering switching from Visual Studio Code to Pycharm but after activating the Virtual Env it is not showing any Project Interpreter.

Also when I type in the terminal python manage.py runserver it is saying bash: python: command not found

Is there a way to continue the project using pycharm or do I have to install everything from start?

答:
Sure you can proceed using any other IDE, in your case PyCharm.

Make sure that you define the Python variable in your PyCharm Settings so everything can be interpreted accordingly and to ensure that all required packages are accessible.

Go to File/Settings/project:Foo in your PyCharm IDE and then check for the Interpreter to be set up.

Additionally you might consider to scan/run your requirements.txt once again. Just to be sure.


问:
How to check if any application is running in docker container?
How to check if any application is running in docker container ? What is the command for it.</p>

答: You can also use docker top <name of your container> to check process running in your container.


问:
[[WinError 2]] The system cannot find the file specified: 'desktop.ini'
I'm trying to sort the files in a folder by the date they were created (with the most recently created first). The following commands:

```<code>import os

list1 = os.listdir(r'D:\Users\Pruthvi\Videos\Movies & TV Shows')
print(list1)
</code>```

display the current files in my movies folder in an arbitrary order:

```<code>['desktop.ini', 'Friends.S05.1080p.BluRay.x264-TENEIGHTY[rartv]', 'Narcos.Mexico.S02.COMPLETE.1080p.NF.WEBRip.DDP5.1.Atmos.x264-NTG[TGx]', 'Rick.and.Morty.S04E09.1080p.WEBRip.x264-BTX[TGx]', 'South.Park.S01.1080p.BluRay.x264-SHORTBREHD[rartv]', 'Temp', 'The.Wolf.of.Wall.Street.2013.1080p.BluRay.AVC.DTS-HD.MA.5.1-SharpHD']
</code>```

Having searched StackOverflow, the solution seems to be using the following on windows:

```<code>list1.sort(key=os.path.getctime)
</code>```

However, this results in the following error:

```<code>FileNotFoundError: [WinError 2] The system cannot find the file specified: 'desktop.ini'
</code>```

答:
As you have seen, the os.listdir function gives you file names without any folder paths.  If you pass one of these names to os.path.getctime, it won't know the folder where the file was found, so it will just look in the current folder.  Unless the current folder is the same as the one passed to os.listdir, getctime will not find the same files.

So to fix it, you could make the current folder the one that supplied the file names, or you could change the list construction so the list contains complete path names rather than just file names.

Body:
I'm trying to sort the files in a folder by the date they were created (with the most recently created first). The following commands:

import os

list1 = os.listdir(r'D:\Users\Pruthvi\Videos\Movies & TV Shows')
print(list1)

display the current files in my movies folder in an arbitrary order:

['desktop.ini', 'Friends.S05.1080p.BluRay.x264-TENEIGHTY[rartv]', 'Narcos.Mexico.S02.COMPLETE.1080p.NF.WEBRip.DDP5.1.Atmos.x264-NTG[TGx]', 'Rick.and.Morty.S04E09.1080p.WEBRip.x264-BTX[TGx]', 'South.Park.S01.1080p.BluRay.x264-SHORTBREHD[rartv]', 'Temp', 'The.Wolf.of.Wall.Street.2013.1080p.BluRay.AVC.DTS-HD.MA.5.1-SharpHD']

Having searched StackOverflow, the solution seems to be using the following on windows:

list1.sort(key=os.path.getctime)

However, this results in the following error:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'desktop.ini'


问:
difference between a pointer and reference parameter?
Are these the same:

```<code>int foo(bar* p) {
  return p->someInt();
}
</code>```

and

```<code>int foo(bar& r) {
  return r.someInt();
}
</code>```

Ignore the null pointer potential. Are these two functions functionally identical no matter if someInt() is virtual or if they are passed a bar or a subclass of bar?

Does this slice anything:

```<code>bar& ref = *ptr_to_bar;
</code>```

答:
Not sure if anyone answered your 2nd question hidden at the bottom about slicing... no that won't cause slicing.

Slicing is when a derived object is assigned (copied) to a base class object -- the derived class's specialization is "sliced" off.  Note that I said the object is copied, we're not talking about pointers being copied/assigned, but the objects themselves.

In your example, that's not happening.  You're just de-referencing a pointer to a Bar object (thereby resulting in a Bar object) being used as the rvalue in a reference initialization.  Not sure I got my terminology right...

Body:
Are these the same:

int foo(bar* p) {
  return p->someInt();
}

and

int foo(bar& r) {
  return r.someInt();
}

Ignore the null pointer potential. Are these two functions functionally identical no matter if someInt() is virtual or if they are passed a bar or a subclass of bar?

Does this slice anything:

bar& ref = *ptr_to_bar;

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 2.5


问:
Problem with restriction in xsd
```<code><xs:restriction base="xs:any">
</code>```

Why cant I put restriction on any type like this?

答:
Because its meaningless, semantically it would be like the statment "You can't do nothing"

More syntactically, after reading about xs:restriction, I think that xs:any is not a built in data type, simpleType element or a complexType element but rather a place holder for extending a document with any element.

Title: Problem with restriction in xsd

Body:
<xs:restriction base="xs:any">

Why cant I put restriction on any type like this?


问:
Unnecessary LEFT JOINs on all Child tables from main LEFT JOIN table required in query for correct result
I am LEFT JOIN-ing the table RECALLS_T with EVENTS_T. Some Recalls do not have any Events, and for those I want a blank row returned.

However, once an entry in EVENTS_T exists, all the following extra tables from EVENTS_T which I also need (ANSWERS_T, ACTIVITY_QUESTIONS_T, ACTIVITES_T) are guaranteed to have entries. For these subsequent tables there is no need to do a LEFT JOIN from their parent, it can be an INNER JOIN just as well.

But if I do the following, the query does not return blank EVENTS_T rows for a RECALLS_T.

```<code>SELECT ..
FROM
   recalls_t r
   LEFT JOIN events_t e  ON ( r.id = e.recall_id )     --Only LEFT JOIN this main table
   INNER JOIN answers_t ans ON (ans.event_id = e.id)
   INNER JOIN activity_questions_t aq ON (ans.activity_question_id = aq.id)
   INNER JOIN PUBLIC.activities_t act ON (aq.activity_id = act.id)
</code>```

Instead, I need to change every subsequent INNER JOIN to a LEFT JOIN as well, in order to get Recalls with blank Events.

```<code>SELECT ..
FROM
   recalls_t r
   LEFT JOIN events_t e  ON ( r.id = e.recall_id )
   LEFT JOIN answers_t ans ON (ans.event_id = e.id)
   LEFT JOIN activity_questions_t aq ON (ans.activity_question_id = aq.id)
   LEFT JOIN PUBLIC.activities_t act ON (aq.activity_id = act.id)
</code>```

I'm just not clear on why I have to do this. The top-level optional join is all I care about, but the downstream joins from EVENTS_T are guaranteed to have data provided the Event exists. Shouldn't the top-level single EVENTS_T join be enough? I'm using Postgres.

答:
The reason you need to do this is because rows preserved by the outer join will have NULL for all columns from events - so inner joining using an equality condition on e.id will remove them from the result again.

you can move the ON clause to the end of the query to give your desired semantics.

The left join is then on the virtual result of inner joining events_t, answers_t, activity_questions_t and activities_t

```<code>SELECT ...
FROM   recalls_t r
       LEFT JOIN events_t e
                 INNER JOIN answers_t ans
                         ON ( ans.event_id = e.id )
                 INNER JOIN activity_questions_t aq
                         ON ( ans.activity_question_id = aq.id )
                 INNER JOIN PUBLIC.activities_t act
                         ON ( aq.activity_id = act.id )
              ON ( r.id = e.recall_id )
</code>```

Or you could consider a RIGHT JOIN here instead

```<code>SELECT ...
FROM   events_t e
       INNER JOIN answers_t ans
               ON ( ans.event_id = e.id )
       INNER JOIN activity_questions_t aq
               ON ( ans.activity_question_id = aq.id )
       INNER JOIN PUBLIC.activities_t act
               ON ( aq.activity_id = act.id )
       RIGHT JOIN recalls_t r
               ON ( r.id = e.recall_id )
</code>```

Body:
I am LEFT JOIN-ing the table RECALLS_T with EVENTS_T. Some Recalls do not have any Events, and for those I want a blank row returned.

However, once an entry in EVENTS_T exists, all the following extra tables from EVENTS_T which I also need (ANSWERS_T, ACTIVITY_QUESTIONS_T, ACTIVITES_T) are guaranteed to have entries. For these subsequent tables there is no need to do a LEFT JOIN from their parent, it can be an INNER JOIN just as well.

But if I do the following, the query does not return blank EVENTS_T rows for a RECALLS_T.

SELECT ..
FROM
   recalls_t r
   LEFT JOIN events_t e  ON ( r.id = e.recall_id )     --Only LEFT JOIN this main table
   INNER JOIN answers_t ans ON (ans.event_id = e.id)
   INNER JOIN activity_questions_t aq ON (ans.activity_question_id = aq.id)
   INNER JOIN PUBLIC.activities_t act ON (aq.activity_id = act.id)

Instead, I need to change every subsequent INNER JOIN to a LEFT JOIN as well, in order to get Recalls with blank Events.

SELECT ..
FROM
   recalls_t r
   LEFT JOIN events_t e  ON ( r.id = e.recall_id )
   LEFT JOIN answers_t ans ON (ans.event_id = e.id)
   LEFT JOIN activity_questions_t aq ON (ans.activity_question_id = aq.id)
   LEFT JOIN PUBLIC.activities_t act ON (aq.activity_id = act.id)

I'm just not clear on why I have to do this. The top-level optional join is all I care about, but the downstream joins from EVENTS_T are guaranteed to have data provided the Event exists. Shouldn't the top-level single EVENTS_T join be enough? I'm using Postgres.

Body:
The reason you need to do this is because rows preserved by the outer join will have NULL for all columns from events - so inner joining using an equality condition on e.id will remove them from the result again.

you can move the ON clause to the end of the query to give your desired semantics.

The left join is then on the virtual result of inner joining events_t, answers_t, activity_questions_t and activities_t

SELECT ...
FROM   recalls_t r
       LEFT JOIN events_t e
                 INNER JOIN answers_t ans
                         ON ( ans.event_id = e.id )
                 INNER JOIN activity_questions_t aq
                         ON ( ans.activity_question_id = aq.id )
                 INNER JOIN PUBLIC.activities_t act
                         ON ( aq.activity_id = act.id )
              ON ( r.id = e.recall_id )

Or you could consider a RIGHT JOIN here instead

SELECT ...
FROM   events_t e
       INNER JOIN answers_t ans
               ON ( ans.event_id = e.id )
       INNER JOIN activity_questions_t aq
               ON ( ans.activity_question_id = aq.id )
       INNER JOIN PUBLIC.activities_t act
               ON ( aq.activity_id = act.id )
       RIGHT JOIN recalls_t r
               ON ( r.id = e.recall_id )


问:
Converting each row of a dataframe into a string and assigning it as a column to another dataset in pandas
I have a dataset:

```<code>id   name   address   phone   email
123  abc    123 abc   12345   info@abc.com
456  cbs    456 cbs   67890   info@cbs.com
758  nbc    789 nbc   11121   info@nbc.com
</code>```

I want to create a new dataset, where it retains the first two columns (id and name) and has the third column, which will have a string that is a combination of values of address, phone and email. In other words, I need it to look like this:

```<code>id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '456 cbs   67890   info@cbs.com'
758  nbc    '789 nbc   11121   info@nbc.com'
</code>```

This is the code I have:

```<code>df_transformed = df[['id','name']]
df_meta = df[['address','phone','email']]
df_meta_str = df_meta.iloc[:].to_string(header=False, index=False)
df_transformed['meta_str'] = df_meta_str
</code>```

But what I get is:

```<code>id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '123 abc   12345   info@abc.com'
758  nbc    '123 abc   12345   info@abc.com'
</code>```

I think the problem is that df_meta_str has the data in all rows combined as one big string.

What would be a way to achieve a separate string on a separate row?

答:
You can use pd.Series.cat here.

```<code>df['meta_str'] = df['address'].str.cat(df[['phone','email']].astype(str),sep=' ')
df.drop(columns='address')

   id   name   meta_str
0  123  abc    123 abc 12345 info@abc.com
1  456  cbs    456 cbs 67890 info@cbs.com
2  758  nbc    789 nbc 11121 info@nbc.com

</code>```

Body:
I have a dataset:

id   name   address   phone   email
123  abc    123 abc   12345   info@abc.com
456  cbs    456 cbs   67890   info@cbs.com
758  nbc    789 nbc   11121   info@nbc.com

I want to create a new dataset, where it retains the first two columns (id and name) and has the third column, which will have a string that is a combination of values of address, phone and email. In other words, I need it to look like this:

id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '456 cbs   67890   info@cbs.com'
758  nbc    '789 nbc   11121   info@nbc.com'

This is the code I have:

df_transformed = df[['id','name']]
df_meta = df[['address','phone','email']]
df_meta_str = df_meta.iloc[:].to_string(header=False, index=False)
df_transformed['meta_str'] = df_meta_str

But what I get is:

id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '123 abc   12345   info@abc.com'
758  nbc    '123 abc   12345   info@abc.com'

I think the problem is that df_meta_str has the data in all rows combined as one big string.

What would be a way to achieve a separate string on a separate row?

Body:
You can use pd.Series.cat here.

df['meta_str'] = df['address'].str.cat(df[['phone','email']].astype(str),sep=' ')
df.drop(columns='address')

   id   name   meta_str
0  123  abc    123 abc 12345 info@abc.com
1  456  cbs    456 cbs 67890 info@cbs.com
2  758  nbc    789 nbc 11121 info@nbc.com


问:
Simple_one_for_one can only be terminated if appointed SHUTDOWN strategy to brutal_kill?
The supervisor is an OTP behavior.

```<code>init([]) ->
    RoomSpec = {mod_zytm_room, {mod_zytm_room, start_link, []},
                transient, brutal_kill, worker, [mod_zytm_room]},
    {ok, {{simple_one_for_one, 10, 10000}, [RoomSpec]}}.
</code>```

Above code will invoke child's terminate method.

But if I change the brutal_kill to an integer timeout (e.g. 6000), the terminate method was never invoked.

I see an explanation in the Erlang document:

The dynamically created child processes of a simple-one-for-one
  supervisor are not explicitly killed, regardless of shutdown strategy,
  but are expected to terminate when the supervisor does (that is, when
  an exit signal from the parent process is received).

But I cannot fully understand. Is it said that exit(Pid, kill) can terminate a simple_one_for_one child spec while exit(Pid, shutdown) can't ?

===================================update====================================

mod_zytm_room_sup.erl

```<code>-module(mod_zytm_room_sup).

-behaviour(supervisor).

-export([start_link/0, init/1, open_room/1, close_room/1]).

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

init([]) ->
    RoomSpec = {mod_zytm_room, {mod_zytm_room, start_link, []},
                transient, brutal_kill, worker, [mod_zytm_room]},
    {ok, {{simple_one_for_one, 10, 10000}, [RoomSpec]}}.

open_room(RoomId) ->
    supervisor:start_child(?MODULE, [RoomId]).

close_room(RoomPid) ->
    supervisor:terminate_child(?MODULE, RoomPid).
</code>```

mod_zytm_room.erl

```<code>-module(mod_zytm_room).

-behaviour(gen_server).

-export([start_link/1]).

-export([init/1, handle_cast/2, handle_info/2, handle_call/3, code_change/3, terminate/2]).

start_link(RoomId) ->
    gen_server:start_link(?MODULE, [RoomId], []).

init([RoomId]) ->
    {ok, []}.

terminate(_, _) ->
    error_logger:info_msg("~p terminated:~p", [?MODULE, self()]),
    ok.

...other methods ommited.
</code>```

mod_zytm_sup.erl

```<code>-module(mod_zytm_sup).

-behaviour(gen_server).

-export([start_link/0]).

-export([init/1, handle_cast/2, handle_info/2, handle_call/3, code_change/3, terminate/2]).

start_link() ->
    gen_server:start_link(?MODULE, [], []).

init([]) ->
    {ok, []}.

%% invoked by an erlang:send_after event.
handle_info({'CLOSE_ROOM', RoomPid}, State) ->
    mod_zytm_room_sup:close_room(RoomPid),
    {noreply, State}.

...other methods ommited.
</code>```

Both mod_zytm_sup and mod_zytm_room_sup are a part of a system supervision tree, mod_zytm_sup invoke mod_zytm_room_sup to create or close mod_zytm_room process.

答:
The dynamically created child processes of a simple-one-for-one
  supervisor are not explicitly killed, regardless of shutdown strategy,
  but are expected to terminate when the supervisor does (that is, when
  an exit signal from the parent process is received).

Note that this is no longer true.  Since Erlang/OTP R15A, dynamic children are explicitly terminated as per the shutdown strategy.

Body:
The supervisor is an OTP behavior.

init([]) ->
    RoomSpec = {mod_zytm_room, {mod_zytm_room, start_link, []},
                transient, brutal_kill, worker, [mod_zytm_room]},
    {ok, {{simple_one_for_one, 10, 10000}, [RoomSpec]}}.

Above code will invoke child's terminate method.

But if I change the brutal_kill to an integer timeout (e.g. 6000), the terminate method was never invoked.

I see an explanation in the Erlang document:

The dynamically created child processes of a simple-one-for-one
  supervisor are not explicitly killed, regardless of shutdown strategy,
  but are expected to terminate when the supervisor does (that is, when
  an exit signal from the parent process is received).

But I cannot fully understand. Is it said that exit(Pid, kill) can terminate a simple_one_for_one child spec while exit(Pid, shutdown) can't ?

===================================update====================================

mod_zytm_room_sup.erl

-module(mod_zytm_room_sup).

-behaviour(supervisor).

-export([start_link/0, init/1, open_room/1, close_room/1]).

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

init([]) ->
    RoomSpec = {mod_zytm_room, {mod_zytm_room, start_link, []},
                transient, brutal_kill, worker, [mod_zytm_room]},
    {ok, {{simple_one_for_one, 10, 10000}, [RoomSpec]}}.

open_room(RoomId) ->
    supervisor:start_child(?MODULE, [RoomId]).

close_room(RoomPid) ->
    supervisor:terminate_child(?MODULE, RoomPid).

mod_zytm_room.erl

-module(mod_zytm_room).

-behaviour(gen_server).

-export([start_link/1]).

-export([init/1, handle_cast/2, handle_info/2, handle_call/3, code_change/3, terminate/2]).

start_link(RoomId) ->
    gen_server:start_link(?MODULE, [RoomId], []).

init([RoomId]) ->
    {ok, []}.

terminate(_, _) ->
    error_logger:info_msg("~p terminated:~p", [?MODULE, self()]),
    ok.

...other methods ommited.

mod_zytm_sup.erl

-module(mod_zytm_sup).

-behaviour(gen_server).

-export([start_link/0]).

-export([init/1, handle_cast/2, handle_info/2, handle_call/3, code_change/3, terminate/2]).

start_link() ->
    gen_server:start_link(?MODULE, [], []).

init([]) ->
    {ok, []}.

%% invoked by an erlang:send_after event.
handle_info({'CLOSE_ROOM', RoomPid}, State) ->
    mod_zytm_room_sup:close_room(RoomPid),
    {noreply, State}.

...other methods ommited.

Both mod_zytm_sup and mod_zytm_room_sup are a part of a system supervision tree, mod_zytm_sup invoke mod_zytm_room_sup to create or close mod_zytm_room process.


问:
How to achieve pagination/table layout with Angular.js?
Let's say I receive an object literal with 15+ objects and I need to display them in a nice layout (not all in a row), what is the most efficient method for controlling when the line should break/page should end?

Right now I'm using ng-repeat on table row's, and the result is a long thin table with one column.

Edit for clarification.  Could have objects within objects/more params.  Here is my object:

```<code>$scope.zones = [
        {"name": "Zone 1",
         "activity": "1"},
        {"name": "Zone 2",
         "activity": "1"},
        {"name": "Zone 3",
         "activity": "0"},
        {"name": "Zone 4",
         "activity": "0"},
        {"name": "Zone 5",
         "activity": "0"},
        {"name": "Zone 6",
         "activity": "0"},
        {"name": "Zone 7",
         "activity": "1"},
        {"name": "Zone 8",
         "activity": "0"},
        {"name": "Zone 9",
         "activity": "0"},
        {"name": "Zone 10",
         "activity": "0"},
        {"name": "Zone 11",
         "activity": "1"},
        {"name": "Zone 12",
         "activity": "1"},
        {"name": "Zone 13",
         "activity": "0"},
        {"name": "Zone 14",
         "activity": "0"},
        {"name": "Zone 15",
         "activity": "1"},
    ];
</code>```

答:
The simplest way is using slice. You pipe the slice and mention the start index and end index for the part of the data you wish to display. Here is the code:

HTML

```<code><table>
  <thead>
     ...
  </thead>
  <tbody>
     <tr *ngFor="let row of rowData | slice:startIndex:endIndex">
        ...
     </tr>
  </tbody>
</table>
<nav *ngIf="rowData" aria-label="Page navigation example">
    <ul class="pagination">
        <li class="page-item">
            <a class="page-link" (click)="updateIndex(0)" aria-label="Previous">
                <span aria-hidden="true">First</span>
            </a>
        </li>
        <li *ngFor="let i of getArrayFromNumber(rowData.length)" class="page-item">
            <a class="page-link" (click)="updateIndex(i)">{{i+1}}</a></li>

        <li class="page-item">
            <a class="page-link" (click)="updateIndex(pageNumberArray.length-1)" aria-label="Next">
                <span aria-hidden="true">Last</span>
            </a>
        </li>
    </ul>
</nav>
</code>```

TypeScript

```<code>...
public rowData = data // data you want to display in table
public paginationRowCount = 100 //number of records in a page
...
getArrayFromNumber(length) {
        if (length % this.paginationRowCount === 0) {
            this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount)).keys());
        } else {
            this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount) + 1).keys());
        }
        return this.pageNumberArray;
    }

    updateIndex(pageIndex) {
        this.startIndex = pageIndex * this.paginationRowCount;
        if (this.rowData.length > this.startIndex + this.paginationRowCount) {
            this.endIndex = this.startIndex + this.paginationRowCount;
        } else {
            this.endIndex = this.rowData.length;
        }
    }
</code>```

Refence for tutorial: https://www.youtube.com/watch?v=Q0jPfb9iyE0

Body:
Let's say I receive an object literal with 15+ objects and I need to display them in a nice layout (not all in a row), what is the most efficient method for controlling when the line should break/page should end?

Right now I'm using ng-repeat on table row's, and the result is a long thin table with one column.

Edit for clarification.  Could have objects within objects/more params.  Here is my object:

$scope.zones = [
        {"name": "Zone 1",
         "activity": "1"},
        {"name": "Zone 2",
         "activity": "1"},
        {"name": "Zone 3",
         "activity": "0"},
        {"name": "Zone 4",
         "activity": "0"},
        {"name": "Zone 5",
         "activity": "0"},
        {"name": "Zone 6",
         "activity": "0"},
        {"name": "Zone 7",
         "activity": "1"},
        {"name": "Zone 8",
         "activity": "0"},
        {"name": "Zone 9",
         "activity": "0"},
        {"name": "Zone 10",
         "activity": "0"},
        {"name": "Zone 11",
         "activity": "1"},
        {"name": "Zone 12",
         "activity": "1"},
        {"name": "Zone 13",
         "activity": "0"},
        {"name": "Zone 14",
         "activity": "0"},
        {"name": "Zone 15",
         "activity": "1"},
    ];

Body:
The simplest way is using slice. You pipe the slice and mention the start index and end index for the part of the data you wish to display. Here is the code:

HTML

<table>
  <thead>
     ...
  </thead>
  <tbody>
     <tr *ngFor="let row of rowData | slice:startIndex:endIndex">
        ...
     </tr>
  </tbody>
</table>
<nav *ngIf="rowData" aria-label="Page navigation example">
    <ul class="pagination">
        <li class="page-item">
            <a class="page-link" (click)="updateIndex(0)" aria-label="Previous">
                <span aria-hidden="true">First</span>
            </a>
        </li>
        <li *ngFor="let i of getArrayFromNumber(rowData.length)" class="page-item">
            <a class="page-link" (click)="updateIndex(i)">{{i+1}}</a></li>

        <li class="page-item">
            <a class="page-link" (click)="updateIndex(pageNumberArray.length-1)" aria-label="Next">
                <span aria-hidden="true">Last</span>
            </a>
        </li>
    </ul>
</nav>

TypeScript

...
public rowData = data // data you want to display in table
public paginationRowCount = 100 //number of records in a page
...
getArrayFromNumber(length) {
        if (length % this.paginationRowCount === 0) {
            this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount)).keys());
        } else {
            this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount) + 1).keys());
        }
        return this.pageNumberArray;
    }

    updateIndex(pageIndex) {
        this.startIndex = pageIndex * this.paginationRowCount;
        if (this.rowData.length > this.startIndex + this.paginationRowCount) {
            this.endIndex = this.startIndex + this.paginationRowCount;
        } else {
            this.endIndex = this.rowData.length;
        }
    }

Refence for tutorial: https://www.youtube.com/watch?v=Q0jPfb9iyE0


问:
Randomised Queue implementation - ideas for randomness
I am taking the Algorithms course in coursera. One of the assignments is the following:

Randomized queue. A randomized queue is similar to a stack or queue,
  except that the item removed is chosen uniformly at random among items
  in the data structure.

I am trying to find a way to implement dequeue (randomly removing an item) in a constant amount of time. I have thought of an idea to do this recquiring a deque (which supports removing and adding an item from the front and back in constant time). My idea is as follows:

Use a deque as an underlying data structure inside the randomized queue

Enqueue - use a library function to generate an integer between 0 and 1 inclusive. If the integer is 0, add the item to the front of the deque. Otherwise, add it to the back.

Dequeue - any direction would be fine.

The reason why the randomness happens in enqueue rather than in dequeue is because I find it to be not exactly random (E.G. n calls to enqueue will have dequeue only return either the first or nth item). So to be sure the items are being removed randomly, I decided to enqueue them randomly.

This idea seems good to me because I cannot find holes in it, but the problem is I cannot prove that my idea would really work. I don't know much about randomness. In fact, this is only the 5th time I am working with random data structures.

Is my idea correct? Will it generate a data structure that removes items at random?

答:
Enqueueing only at the ends does not produce a uniformly random sequence. The last item to be enqueued is necessarily at either ends, and the first item to be enqueued is more likely to be somewhere in the middle than at either ends after enqueueing other items.

To illustrate, take the set of three items {1, 2, 3}, the smallest set that does not result in a uniform distribution. Enqueueing them in that order gives the following possible results (in parenthesis is where to enqueue the next item).

```<code>[1] -> (front) -> [1, 2] -> (front) -> [1, 2, 3]
[1] -> (front) -> [1, 2] -> (back) -> [3, 1, 2]
[1] -> (back) -> [2, 1] -> (front) -> [2, 1, 3]
[1] -> (back) -> [2, 1] -> (back) -> [3, 2, 1]
</code>```

These four results are the only possibilities and are all equally likely. And as you can see, the last item is never in the middle while both the first and second items are in the middle twice.

What you want is to dequeue at a random place. But you don't need to preserve the order of other items, since they are uniformly distributed. That means you can just swap the last item with a random one, and then dequeue that one (which became the last item).

Body:
Enqueueing only at the ends does not produce a uniformly random sequence. The last item to be enqueued is necessarily at either ends, and the first item to be enqueued is more likely to be somewhere in the middle than at either ends after enqueueing other items.

To illustrate, take the set of three items {1, 2, 3}, the smallest set that does not result in a uniform distribution. Enqueueing them in that order gives the following possible results (in parenthesis is where to enqueue the next item).

[1] -> (front) -> [1, 2] -> (front) -> [1, 2, 3]
[1] -> (front) -> [1, 2] -> (back) -> [3, 1, 2]
[1] -> (back) -> [2, 1] -> (front) -> [2, 1, 3]
[1] -> (back) -> [2, 1] -> (back) -> [3, 2, 1]

These four results are the only possibilities and are all equally likely. And as you can see, the last item is never in the middle while both the first and second items are in the middle twice.

What you want is to dequeue at a random place. But you don't need to preserve the order of other items, since they are uniformly distributed. That means you can just swap the last item with a random one, and then dequeue that one (which became the last item).


问:
3.4.2 Argument-dependent name lookup from n3290 Draft
A point from ISO draft n3290 section 3.4.2 paragraph 1:

When the postfix-expression in a function call is an unqualified-id, other namespaces not considered during the usual unqualified lookup may be searched, and in those namespaces, namespace-scope friend function declarations not otherwise visible may be found. These modifications to the search depend on the types of the arguments (and for template template arguments, the namespace of the template argument).

Here  they said aboout  "these modifications to the search depend on the types of the arguments / template template  arguments / namespace of the template argument  " ...Can any one expalin with an example please? I tried with argumetn types..please expalin with template template argument types & namespace of the template argument type

答:
Consider a simple unqualified function call:

```<code>foo(x);
</code>```

ADL means that foo is looked up not just in the enclosing scope, and the namespace that the call is in, but also the namespace of the type of x. e.g. if x is a std::vector<int> then namespace std is also searched. Thus:

```<code>int main() {
    std::vector<int> x,y;
    swap(x,y);
}
</code>```

is OK, and will call std::swap().

The lookup also depends on the namespace of any template arguments too, so if x is std::vector<mynamespace::myclass> then mynamespace is also included in the lookup. Thus

```<code>namespace mynamespace {
    struct myclass {};
    void foo(std::vector<mynamespace::myclass> const&){}
}

int main() {
    std::vector<mynamespace::myclass> x;
    foo(x);
}
</code>```

will call mynamespace::foo().

Finally, the lookup also extends to the namespaces of any templates used as template template parameters. e.g.

```<code>namespace mynamespace {
    template<typename T>
    struct mytemplate
    {};

    template<typename T>
    void bar(T const&) {}
}

template<template<typename> class T>
struct wrapper {};

int main() {
    wrapper<mynamespace::mytemplate> x;
    bar(x);
}
</code>```

Even though wrapper is in the global namespace, mynamespace::bar will be found, because the template template parameter used for x is mynamespace::mytemplate.

Body:
Consider a simple unqualified function call:

foo(x);

ADL means that foo is looked up not just in the enclosing scope, and the namespace that the call is in, but also the namespace of the type of x. e.g. if x is a std::vector<int> then namespace std is also searched. Thus:

int main() {
    std::vector<int> x,y;
    swap(x,y);
}

is OK, and will call std::swap().

The lookup also depends on the namespace of any template arguments too, so if x is std::vector<mynamespace::myclass> then mynamespace is also included in the lookup. Thus

namespace mynamespace {
    struct myclass {};
    void foo(std::vector<mynamespace::myclass> const&){}
}

int main() {
    std::vector<mynamespace::myclass> x;
    foo(x);
}

will call mynamespace::foo().

Finally, the lookup also extends to the namespaces of any templates used as template template parameters. e.g.

namespace mynamespace {
    template<typename T>
    struct mytemplate
    {};

    template<typename T>
    void bar(T const&) {}
}

template<template<typename> class T>
struct wrapper {};

int main() {
    wrapper<mynamespace::mytemplate> x;
    bar(x);
}

Even though wrapper is in the global namespace, mynamespace::bar will be found, because the template template parameter used for x is mynamespace::mytemplate.


问:
Connection Spring Boot-MySql : Public Key Retrieval is not allowed
I ran one of my apps back in early June of this year with no problems.  After trying it again today, I get the following error in the console :

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Public Key Retrieval is not allowed

Any ideas on how to fix?

I've researched this but have found nothing specific to Spring Boot apps.

Settings in applications.properties :

```<code>spring.mvc.view.prefix=/WEB-INF/views/

spring.mvc.view.suffix=.jsp

spring.datasource.url = jdbc:mysql://localhost:3306/testdb?verifyServerCertificate=false&useSSL=false&requireSSL=false&useJDBCCompliantTimezoneShift=true&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password =

spring.jpa.show-sql = true

spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update

spring.jpa.hibernate.naming.implicit-strategy = org.hibernate.cfg.ImprovedNamingStrategy

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
</code>```

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Public Key Retrieval is not allowed

Body:
I ran one of my apps back in early June of this year with no problems.  After trying it again today, I get the following error in the console :

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Public Key Retrieval is not allowed

Any ideas on how to fix?

I've researched this but have found nothing specific to Spring Boot apps.

Settings in applications.properties :

spring.mvc.view.prefix=/WEB-INF/views/

spring.mvc.view.suffix=.jsp

spring.datasource.url = jdbc:mysql://localhost:3306/testdb?verifyServerCertificate=false&useSSL=false&requireSSL=false&useJDBCCompliantTimezoneShift=true&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password =

spring.jpa.show-sql = true

spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update

spring.jpa.hibernate.naming.implicit-strategy = org.hibernate.cfg.ImprovedNamingStrategy

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Public Key Retrieval is not allowed

Body:
use the following

jdbc:mysql://localhost:3306/payphone?useSSL=false&useJDBCComplaintTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&allowPublicKeyRetrieval=true


问:
how can i ckeditor in form that i created?
I create a form with input and text area fields. As models, I have:

```<code>title = models.CharField(max_length=200)

description = RichTextUploadingField(blank=True,null=True,config_name='default')
</code>```

but in the template that I used the form tag, the textarea isn't showing as an editor:

```<code><form>
    <input type="text" name="title" required
    <textarea name="text" cols="50" rows="15" required></textarea>

</form>
</code>```

答:
You can add CKEditor on any-kind of Html form you want all you want to that, call the hosted version or download JavaScript pack of CKEditor to your Html or PHP Page.

```<code><script src="//cdn.ckeditor.com/4.5.5/standard/ckeditor.js"></script>
</code>```

Now you need to convert the Text-area to CKEditor. For that you have to add the below JavaScript under the Text-area which you want to transform to CKEditor.

```<code><textarea name="text" id="text">This is a demo .</textarea><script> CKEDITOR.replace( 'text' );</script>
</code>```

Now you need to change the “text” from the JavaScript with the name of the Text-area.

Body:
I create a form with input and text area fields. As models, I have:

title = models.CharField(max_length=200)

description = RichTextUploadingField(blank=True,null=True,config_name='default')

but in the template that I used the form tag, the textarea isn't showing as an editor:

<form>
    <input type="text" name="title" required
    <textarea name="text" cols="50" rows="15" required></textarea>

</form>

Body:
You can add CKEditor on any-kind of Html form you want all you want to that, call the hosted version or download JavaScript pack of CKEditor to your Html or PHP Page.

<script src="//cdn.ckeditor.com/4.5.5/standard/ckeditor.js"></script>

Now you need to convert the Text-area to CKEditor. For that you have to add the below JavaScript under the Text-area which you want to transform to CKEditor.

<textarea name="text" id="text">This is a demo .</textarea><script> CKEDITOR.replace( 'text' );</script>

Now you need to change the “text” from the JavaScript with the name of the Text-area.


问:
Object column containing strings retain string type after converting to categorical data type(Pandas Categorical)
In Pandas, I am trying to convert data of data type object containing string values into categorical data type. Even after converting and system showing that the data type is categorical, I am still able to perform string functions on it and pd.api.types.is_string_dtype is returning True. Due to this, when I am trying to fit a machine learning model for the data, it errors out.

Input:

```<code>df_tmp["UsageBand"] = df_tmp["UsageBand"].astype("category")
df_tmp["UsageBand"].dtypes,pd.api.types.is_string_dtype(df_tmp["UsageBand"])
</code>```

Output: (CategoricalDtype(categories=['High', 'Low', 'Medium'], ordered=True), **True**)

Error seen when trying to fit model

```<code>ValueError                                Traceback (most recent call last)
<timed exec> in <module>

~\machinelearning\sample-project\bulldozer-project\env\lib\site-packages\sklearn\ensemble\_forest.py in fit(self, X, y, sample_weight)
    293         """
    294         # Validate or convert input data
--> 295         X = check_array(X, accept_sparse="csc", dtype=DTYPE)
    296         y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None)
    297         if sample_weight is not None:

~\machinelearning\sample-project\bulldozer-project\env\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    529                     array = array.astype(dtype, casting="unsafe", copy=False)
    530                 else:
--> 531                     array = np.asarray(array, order=order, dtype=dtype)
    532             except ComplexWarning:
    533                 raise ValueError("Complex data not supported\n"

~\machinelearning\sample-project\bulldozer-project\env\lib\site-packages\numpy\core\_asarray.py in asarray(a, dtype, order)
     83
     84     """
---> 85     return array(a, dtype, copy=False, order=order)
     86
     87

ValueError: could not convert string to float: 'Low'
</code>```

答:
Instead of converting all the categorical content into numbers, I had only done this conversion on the null data causing the problem.

Wrong code:

```<code>for cols in df_tmp.columns:
    if not pd.api.types.is_numeric_dtype(df_tmp[cols]) and df_tmp[cols].isnull().sum() >0:
        df_tmp[cols+"_is_missing"] = df_tmp[cols].isnull()
        df_tmp[cols] = pd.Categorical(df_tmp[cols]).codes + 1
</code>```

Correct Code:

```<code>for labels,content in df_tmp.items():
    if not pd.api.types.is_numeric_dtype(content):
        df_tmp[labels+"is_missing"] = pd.isnull(content)
        df_tmp[labels] = pd.Categorical(content).codes + 1
</code>```

Body:
In Pandas, I am trying to convert data of data type object containing string values into categorical data type. Even after converting and system showing that the data type is categorical, I am still able to perform string functions on it and pd.api.types.is_string_dtype is returning True. Due to this, when I am trying to fit a machine learning model for the data, it errors out.

Input:

df_tmp["UsageBand"] = df_tmp["UsageBand"].astype("category")
df_tmp["UsageBand"].dtypes,pd.api.types.is_string_dtype(df_tmp["UsageBand"])

Output: (CategoricalDtype(categories=['High', 'Low', 'Medium'], ordered=True), **True**)

Error seen when trying to fit model

ValueError                                Traceback (most recent call last)
<timed exec> in <module>

~\machinelearning\sample-project\bulldozer-project\env\lib\site-packages\sklearn\ensemble\_forest.py in fit(self, X, y, sample_weight)
    293         """
    294         # Validate or convert input data
--> 295         X = check_array(X, accept_sparse="csc", dtype=DTYPE)
    296         y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None)
    297         if sample_weight is not None:

~\machinelearning\sample-project\bulldozer-project\env\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    529                     array = array.astype(dtype, casting="unsafe", copy=False)
    530                 else:
--> 531                     array = np.asarray(array, order=order, dtype=dtype)
    532             except ComplexWarning:
    533                 raise ValueError("Complex data not supported\n"

~\machinelearning\sample-project\bulldozer-project\env\lib\site-packages\numpy\core\_asarray.py in asarray(a, dtype, order)
     83
     84     """
---> 85     return array(a, dtype, copy=False, order=order)
     86
     87

ValueError: could not convert string to float: 'Low'

Body:
Instead of converting all the categorical content into numbers, I had only done this conversion on the null data causing the problem.

Wrong code:

for cols in df_tmp.columns:
    if not pd.api.types.is_numeric_dtype(df_tmp[cols]) and df_tmp[cols].isnull().sum() >0:
        df_tmp[cols+"_is_missing"] = df_tmp[cols].isnull()
        df_tmp[cols] = pd.Categorical(df_tmp[cols]).codes + 1

Correct Code:

for labels,content in df_tmp.items():
    if not pd.api.types.is_numeric_dtype(content):
        df_tmp[labels+"is_missing"] = pd.isnull(content)
        df_tmp[labels] = pd.Categorical(content).codes + 1


问:
How to set the CCTransitionPageTurn orientation to vertical?
I used the code as follow to implement the effect of replace scenes:

[[CCDirector sharedDirector] replaceScene:[CCTransitionPageTurn transitionWithDuration:0.5f scene:alterScene backwards:NO]];

Then, the effect that is reversed to appear as if the incoming scene is being turned from left over the outgoing scene.

I want to get the effect turn from top over. how can I get this?

答:
Modify cocos2d/CCActionPageTurn3D.m to exchange x for y.

```<code>/*
 * cocos2d for iPhone: http://www.cocos2d-iphone.org
 *
 * Copyright (c) 2009 Sindesso Pty Ltd http://www.sindesso.com/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#import "CCActionPageTurn3D.h"

@implementation CCPageTurn3D

/*
 * Update each tick
 * Time is the percentage of the way through the duration
 */
-(void)update:(ccTime)time
{
    float tt = MAX( 0, time - 0.25f );
    float deltaAx = ( tt * tt * 500);
    float ax = -100 - deltaAx;

    float deltaTheta = - (float) M_PI_2 * sqrtf( time);
    float theta = /*0.01f*/ + (float) M_PI_2 +deltaTheta;

    float sinTheta = sinf(theta);
    float cosTheta = cosf(theta);

    for( int i = 0; i <=gridSize_.x; i++ )
    {
        for( int j = 0; j <= gridSize_.y; j++ )
        {
            // Get original vertex
            ccVertex3F    p = [self originalVertex:ccg(i,j)];

            float R = sqrtf(p.y*p.y + (p.x - ax) * (p.x - ax));
            float r = R * sinTheta;
            float alpha = asinf( p.y / R );
            float beta = alpha / sinTheta;
            float cosBeta = cosf( beta );

            // If beta > PI then we've wrapped around the cone
            // Reduce the radius to stop these points interfering with others
            if( beta <= M_PI)
                p.y = ( r * sinf(beta));
            else
            {
                // Force X = 0 to stop wrapped
                // points
                p.y = 0;
            }

            p.x = ( R + ax - ( r*(1 - cosBeta)*sinTheta));

            // We scale z here to avoid the animation being
            // too much bigger than the screen due to perspectve transform
            p.z = (r * ( 1 - cosBeta ) * cosTheta) / 7; // "100" didn't work for

            // Stop z coord from dropping beneath underlying page in a transition
            // issue #751
            if( p.z<0.5f )
                p.z = 0.5f;

            // Set new coords
            [self setVertex:ccg(i,j) vertex:p];
        }
    }
}
@end
</code>```

```<code>diff --git a/cocos2d/CCActionPageTurn3D.m b/cocos2d/CCActionPageTurn3D.m
index ee59500..ccd64eb 100644
--- a/cocos2d/CCActionPageTurn3D.m
+++ b/cocos2d/CCActionPageTurn3D.m
@@ -34,10 +34,10 @@
 -(void)update:(ccTime)time
 {
     float tt = MAX( 0, time - 0.25f );
-    float deltaAy = ( tt * tt * 500);
-    float ay = -100 - deltaAy;
+    float deltaAx = ( tt * tt * 500);
+    float ax = -100 - deltaAx;

     float deltaTheta = - (float) M_PI_2 * sqrtf( time) ;
     float theta = /*0.01f*/ + (float) M_PI_2 +deltaTheta;

     float sinTheta = sinf(theta);
@@ -50,24 +50,24 @@
             // Get original vertex
             ccVertex3F    p = [self originalVertex:ccg(i,j)];

-            float R = sqrtf(p.x*p.x + (p.y - ay) * (p.y - ay));
+            float R = sqrtf(p.y*p.y + (p.x - ax) * (p.x - ax));
             float r = R * sinTheta;
-            float alpha = asinf( p.x / R );
+            float alpha = asinf( p.y / R );
             float beta = alpha / sinTheta;
             float cosBeta = cosf( beta );

             // If beta > PI then we've wrapped around the cone
             // Reduce the radius to stop these points interfering with others
             if( beta <= M_PI)
-                p.x = ( r * sinf(beta));
+                p.y = ( r * sinf(beta));
             else
             {
                 // Force X = 0 to stop wrapped
                 // points
-                p.x = 0;
+                p.y = 0;
             }

-            p.y = ( R + ay - ( r*(1 - cosBeta)*sinTheta));
+            p.x = ( R + ax - ( r*(1 - cosBeta)*sinTheta));

             // We scale z here to avoid the animation being
             // too much bigger than the screen due to perspectve transform
</code>```

Body:
Modify cocos2d/CCActionPageTurn3D.m to exchange x for y.

/*
 * cocos2d for iPhone: http://www.cocos2d-iphone.org
 *
 * Copyright (c) 2009 Sindesso Pty Ltd http://www.sindesso.com/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#import "CCActionPageTurn3D.h"

@implementation CCPageTurn3D

/*
 * Update each tick
 * Time is the percentage of the way through the duration
 */
-(void)update:(ccTime)time
{
    float tt = MAX( 0, time - 0.25f );
    float deltaAx = ( tt * tt * 500);
    float ax = -100 - deltaAx;

    float deltaTheta = - (float) M_PI_2 * sqrtf( time);
    float theta = /*0.01f*/ + (float) M_PI_2 +deltaTheta;

    float sinTheta = sinf(theta);
    float cosTheta = cosf(theta);

    for( int i = 0; i <=gridSize_.x; i++ )
    {
        for( int j = 0; j <= gridSize_.y; j++ )
        {
            // Get original vertex
            ccVertex3F    p = [self originalVertex:ccg(i,j)];

            float R = sqrtf(p.y*p.y + (p.x - ax) * (p.x - ax));
            float r = R * sinTheta;
            float alpha = asinf( p.y / R );
            float beta = alpha / sinTheta;
            float cosBeta = cosf( beta );

            // If beta > PI then we've wrapped around the cone
            // Reduce the radius to stop these points interfering with others
            if( beta <= M_PI)
                p.y = ( r * sinf(beta));
            else
            {
                // Force X = 0 to stop wrapped
                // points
                p.y = 0;
            }

            p.x = ( R + ax - ( r*(1 - cosBeta)*sinTheta));

            // We scale z here to avoid the animation being
            // too much bigger than the screen due to perspectve transform
            p.z = (r * ( 1 - cosBeta ) * cosTheta) / 7; // "100" didn't work for

            // Stop z coord from dropping beneath underlying page in a transition
            // issue #751
            if( p.z<0.5f )
                p.z = 0.5f;

            // Set new coords
            [self setVertex:ccg(i,j) vertex:p];
        }
    }
}
@end

diff --git a/cocos2d/CCActionPageTurn3D.m b/cocos2d/CCActionPageTurn3D.m
index ee59500..ccd64eb 100644
--- a/cocos2d/CCActionPageTurn3D.m
+++ b/cocos2d/CCActionPageTurn3D.m
@@ -34,10 +34,10 @@
 -(void)update:(ccTime)time
 {
     float tt = MAX( 0, time - 0.25f );
-    float deltaAy = ( tt * tt * 500);
-    float ay = -100 - deltaAy;
+    float deltaAx = ( tt * tt * 500);
+    float ax = -100 - deltaAx;

     float deltaTheta = - (float) M_PI_2 * sqrtf( time) ;
     float theta = /*0.01f*/ + (float) M_PI_2 +deltaTheta;

     float sinTheta = sinf(theta);
@@ -50,24 +50,24 @@
             // Get original vertex
             ccVertex3F    p = [self originalVertex:ccg(i,j)];

-            float R = sqrtf(p.x*p.x + (p.y - ay) * (p.y - ay));
+            float R = sqrtf(p.y*p.y + (p.x - ax) * (p.x - ax));
             float r = R * sinTheta;
-            float alpha = asinf( p.x / R );
+            float alpha = asinf( p.y / R );
             float beta = alpha / sinTheta;
             float cosBeta = cosf( beta );

             // If beta > PI then we've wrapped around the cone
             // Reduce the radius to stop these points interfering with others
             if( beta <= M_PI)
-                p.x = ( r * sinf(beta));
+                p.y = ( r * sinf(beta));
             else
             {
                 // Force X = 0 to stop wrapped
                 // points
-                p.x = 0;
+                p.y = 0;
             }

-            p.y = ( R + ay - ( r*(1 - cosBeta)*sinTheta));
+            p.x = ( R + ax - ( r*(1 - cosBeta)*sinTheta));

             // We scale z here to avoid the animation being
             // too much bigger than the screen due to perspectve transform


问:
No matching record found for external id 'groups_group1' in field 'Group'
Please i want to establish access rights for my module, so I modify the file csv I try to install the module, but this error appears at the time of installation of the module:</p>

```<code>File "/home/omar/odoo/odoo11/odoo/modules/loading.py", line 95, in _load_data
    tools.convert_file(cr, module_name, filename, idref, mode, noupdate, kind, report)
  File "/home/omar/odoo/odoo11/odoo/tools/convert.py", line 785, in convert_file
    convert_csv_import(cr, module, pathname, fp.read(), idref, mode, noupdate)
  File "/home/omar/odoo/odoo11/odoo/tools/convert.py", line 832, in convert_csv_import
    raise Exception(_('Module loading %s failed: file %s could not be processed:\n %s') % (module, fname, warning_msg))
Exception: Module loading moduletest failed: file moduletest/security/ir.model.access.csv could not be processed:
 No matching record found for external id 'groups_group1' in field 'Group'
No matching record found for external id 'groups_group2' in field 'Group'
</code>```

答:
One of the things that make this error occur is when you don't respect the order of security files, you have to put your .xml file that is related to security before the .csv file in your __ manifest __.py

Here's a simple example:

    'data': [
        'views/security.xml',
        'security/ir.model.access.csv',
        # ... other includes ...
    ]
```

Body:
Please i want to establish access rights for my module, so I modify the file csv I try to install the module, but this error appears at the time of installation of the module:

File "/home/omar/odoo/odoo11/odoo/modules/loading.py", line 95, in _load_data
    tools.convert_file(cr, module_name, filename, idref, mode, noupdate, kind, report)
  File "/home/omar/odoo/odoo11/odoo/tools/convert.py", line 785, in convert_file
    convert_csv_import(cr, module, pathname, fp.read(), idref, mode, noupdate)
  File "/home/omar/odoo/odoo11/odoo/tools/convert.py", line 832, in convert_csv_import
    raise Exception(_('Module loading %s failed: file %s could not be processed:\n %s') % (module, fname, warning_msg))
Exception: Module loading moduletest failed: file moduletest/security/ir.model.access.csv could not be processed:
 No matching record found for external id 'groups_group1' in field 'Group'
No matching record found for external id 'groups_group2' in field 'Group'


问:
Problem in Punjabi font in the application?
I am developing an application in which i want Punjabi language text in my application.

Therefore i save (AnmolUni.ttf)font file in the assets folder in my application. But still i didn't get the proper view. The emulator shows me boxes somewhere.

here is my code

```<code>Typeface myfont;
        myfont=Typeface.createFromAsset(getAssets(),"AnmolUniHeavy.ttf");
        TextView textview = (TextView)findViewById(R.id.TextView01);
        //textview.setText("ਸਤਿਗੁਰ ਪ੍ਰਸਾਦਿ  ॥ਤਤਕਰ ");
        textview.setTypeface(myfont);
    }
</code>```

so can you give me any solution for it.

答: A lot of languages (especially Indian ones) are not supported as yet on Android. The problem arises because of that. You might just have to wait for the release that does support. There are some threads on the web that allow you install fonts once you have rooted your phone, but you may not be able to do that with your application. Check this link out for adding more resources to the android phone.</p>

Body:
I am developing an application in which i want Punjabi language text in my application.

Therefore i save (AnmolUni.ttf)font file in the assets folder in my application. But still i didn't get the proper view. The emulator shows me boxes somewhere.

here is my code

Typeface myfont;
        myfont=Typeface.createFromAsset(getAssets(),"AnmolUniHeavy.ttf");
        TextView textview = (TextView)findViewById(R.id.TextView01);
        //textview.setText("ਸਤਿਗੁਰ ਪ੍ਰਸਾਦਿ  ॥ਤਤਕਰ ");
        textview.setTypeface(myfont);
    }

so can you give me any solution for it.