问:
I want one character at a time on html page. After completion load next one
I am developing a javascript app.
I have stuck to implementing this.
I am able to load all characters but I want to implement :- load one characters after on completion load next characters.
One characters at a time.

I want to load one character. After completion load next then again after completion next but one character at a time.
 https://hanziwriter.org/docs.html

var chars = new Array('我','很','爱');

console.log(chars);

for(i=0; i< chars.length; i++){
     console.log(chars[i]);
    writeFunction(chars[i])
}

//c = '我';

function writeFunction(c){

    var writer = HanziWriter.create('character-target-div' , c , {
        width: 150,
        height: 150,
        showCharacter: false,
        padding: 5
      });
      writer.quiz({
        onMistake: function(strokeData) {
          console.log('Oh no! you made a mistake on stroke ' + strokeData.strokeNum);
          console.log("You've made " + strokeData.mistakesOnStroke + " mistakes on this stroke so far");
          console.log("You've made " + strokeData.totalMistakes + " total mistakes on this quiz");
          console.log("There are " + strokeData.strokesRemaining + " strokes remaining in this character");
        },
        onCorrectStroke: function(strokeData) {
          console.log('Yes!!! You got stroke ' + strokeData.strokeNum + ' correct!');
          console.log('You made ' + strokeData.mistakesOnStroke + ' mistakes on this stroke');
          console.log("You've made " + strokeData.totalMistakes + ' total mistakes on this quiz');
          console.log('There are ' + strokeData.strokesRemaining + ' strokes remaining in this character');
        },
        onComplete: function(summaryData) {
          console.log('You did it! You finished drawing ' + summaryData.character);
          console.log('You made ' + summaryData.totalMistakes + ' total mistakes on this quiz');

          flagComplete = true;

        }
      });

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/hanzi-writer@2.2/dist/hanzi-writer.min.js"></script>

<div id="character-target-div"></div></code>```

答:
Like this?

I cannot test it since I have no idea how to correctly stroke  any of these

You can change

setTimeout(writeFunction, 1000)

to

writeFunction();

if you do not want a pause

var chars = new Array('我', '很', '爱'),
  cnt = 0;
writeFunction()

//c = '我';

function writeFunction() {
  if (cnt >= chars.length) return
  c = chars[cnt]

  var writer = HanziWriter.create('character-target-div', c, {
    width: 150,
    height: 150,
    showCharacter: false,
    padding: 5
  });
  writer.quiz({
    onMistake: function(strokeData) {
      console.log('Oh no! you made a mistake on stroke ' + strokeData.strokeNum);
      console.log("You've made " + strokeData.mistakesOnStroke + " mistakes on this stroke so far");
      console.log("You've made " + strokeData.totalMistakes + " total mistakes on this quiz");
      console.log("There are " + strokeData.strokesRemaining + " strokes remaining in this character");
    },
    onCorrectStroke: function(strokeData) {
      console.log('Yes!!! You got stroke ' + strokeData.strokeNum + ' correct!');
      console.log('You made ' + strokeData.mistakesOnStroke + ' mistakes on this stroke');
      console.log("You've made " + strokeData.totalMistakes + ' total mistakes on this quiz');
      console.log('There are ' + strokeData.strokesRemaining + ' strokes remaining in this character');
    },
    onComplete: function(summaryData) {
      console.log('You did it! You finished drawing ' + summaryData.character);
      console.log('You made ' + summaryData.totalMistakes + ' total mistakes on this quiz');

      flagComplete = true;
      cnt++
      setTimeout(writeFunction, 1000)

    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/hanzi-writer@2.2/dist/hanzi-writer.min.js"></script>

<div id="character-target-div"></div></code>```

Body:
Like this?

I cannot test it since I have no idea how to correctly stroke  any of these

You can change

setTimeout(writeFunction, 1000)

to

writeFunction();

if you do not want a pause

var chars = new Array('我', '很', '爱'),
  cnt = 0;
writeFunction()

//c = '我';

function writeFunction() {
  if (cnt >= chars.length) return
  c = chars[cnt]

  var writer = HanziWriter.create('character-target-div', c, {
    width: 150,
    height: 150,
    showCharacter: false,
    padding: 5
  });
  writer.quiz({
    onMistake: function(strokeData) {
      console.log('Oh no! you made a mistake on stroke ' + strokeData.strokeNum);
      console.log("You've made " + strokeData.mistakesOnStroke + " mistakes on this stroke so far");
      console.log("You've made " + strokeData.totalMistakes + " total mistakes on this quiz");
      console.log("There are " + strokeData.strokesRemaining + " strokes remaining in this character");
    },
    onCorrectStroke: function(strokeData) {
      console.log('Yes!!! You got stroke ' + strokeData.strokeNum + ' correct!');
      console.log('You made ' + strokeData.mistakesOnStroke + ' mistakes on this stroke');
      console.log("You've made " + strokeData.totalMistakes + ' total mistakes on this quiz');
      console.log('There are ' + strokeData.strokesRemaining + ' strokes remaining in this character');
    },
    onComplete: function(summaryData) {
      console.log('You did it! You finished drawing ' + summaryData.character);
      console.log('You made ' + summaryData.totalMistakes + ' total mistakes on this quiz');

      flagComplete = true;
      cnt++
      setTimeout(writeFunction, 1000)

    }
  });
}

<script src="https://cdn.jsdelivr.net/npm/hanzi-writer@2.2/dist/hanzi-writer.min.js"></script>

<div id="character-target-div"></div>


来源: stackexchange

问:
friendly id and devise error when using reserved word
I used friendly id to allow user access profile with their login name, but when I try to sign up with login name that has been reserved by the friendly Id, I got an error. It seems devise can't render the error message properly. The error just works fine when I'm using authlogic.

Friendly_id Config:

```<code>:reserved_words => ["index", "new", "users", "admin", "login", "logout", "books",
                    "administrator", "signup"],
</code>```

Error:

```<code>FriendlyId::ReservedError in Devise::RegistrationsController#create
FriendlyId::ReservedError
</code>```

I'm using:

```<code>gem 'devise', '1.3.4'
gem 'friendly_id', '3.2.1.1'
</code>```

答:
Thanks @Jerome it fixes my error
<%= link_to 'Surt', destroy_user_session_path, method: :delete %>
Not route user/sign_out simply adding sign_out to friendly_id reserved words</p>

```<code>config/initilaizers/friendly_id.rb
config.reserved_words = %w(new edit index session login logout sign_out users admin
    stylesheets assets javascripts images)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I used friendly id to allow user access profile with their login name, but when I try to sign up with login name that has been reserved by the friendly Id, I got an error. It seems devise can't render the error message properly. The error just works fine when I'm using authlogic.

Friendly_id Config:

:reserved_words => ["index", "new", "users", "admin", "login", "logout", "books",
                    "administrator", "signup"],

Error:

FriendlyId::ReservedError in Devise::RegistrationsController#create
FriendlyId::ReservedError

I'm using:

gem 'devise', '1.3.4'
gem 'friendly_id', '3.2.1.1'

Body:
Thanks @Jerome it fixes my error
<%= link_to 'Surt', destroy_user_session_path, method: :delete %>
Not route user/sign_out simply adding sign_out to friendly_id reserved words

config/initilaizers/friendly_id.rb
config.reserved_words = %w(new edit index session login logout sign_out users admin
    stylesheets assets javascripts images)

ContentLicense: CC BY-SA 4.0


问:
Make a wall that boost speed unity
So... I know it must be a pretty straight forward kind of thing, but I'm stuck on that for days, basically what I need, is that when a ball hit a wall (collider), it starts accelerating towards a direction, as picture bellow, but I need to do it using physics, I can't just interpolate the position.

答:
You would first need a vector parallel to the ground!

You can use Collider.ClosestPoint in order to find the closest point on the walls collider to the ball Position.

From this you then know a plane normal for your ground/wall so you can then use Vector3.ProjectOnPlane in order to convert the usual move direction into one parallel to the ground.

private void FixedUpdate ()
{
    var ballRb = ball.GetComponent<Rigidbody>();
    var wallCollider = Wall.GetComponent<Collider>();
    var hitPoint = wallCollider.ClosestPoint(ballRb.position);

    // normal of ground (= vector from hitPoint to ball)
    var groundNormal = (ballRb.position - hitPoint).normalized;

    // project the given velocity onto the ground
    var newVelocity = Vector3.ProjectOnPlane(ballRb.velocity, groundNormal);

    // optionally increase the speed of needed e.g.
    //var newDirection = newVelocity.normalized;
    //var newMagnitude = newVelocity.magnitude * 1.1f; // or any multiplication or addition factor
    //newVelocity = newDirection * newMagnitude;

    // and finally reassign the new velocity
    ballRb.velocity = newVelocity;
}
```

Note: Typed on smartphone but I hope the idea gets clear and this provides a good start point

Title: Make a wall that boost speed unity

Body:
You would first need a vector parallel to the ground!

You can use Collider.ClosestPoint in order to find the closest point on the walls collider to the ball Position.

From this you then know a plane normal for your ground/wall so you can then use Vector3.ProjectOnPlane in order to convert the usual move direction into one parallel to the ground.

private void FixedUpdate ()
{
    var ballRb = ball.GetComponent<Rigidbody>();
    var wallCollider = Wall.GetComponent<Collider>();
    var hitPoint = wallCollider.ClosestPoint(ballRb.position);

    // normal of ground (= vector from hitPoint to ball)
    var groundNormal = (ballRb.position - hitPoint).normalized;

    // project the given velocity onto the ground
    var newVelocity = Vector3.ProjectOnPlane(ballRb.velocity, groundNormal);

    // optionally increase the speed of needed e.g.
    //var newDirection = newVelocity.normalized;
    //var newMagnitude = newVelocity.magnitude * 1.1f; // or any multiplication or addition factor
    //newVelocity = newDirection * newMagnitude;

    // and finally reassign the new velocity
    ballRb.velocity = newVelocity;
}

Note: Typed on smartphone but I hope the idea gets clear and this provides a good start point


问:
Minesweeper - Angular
I'm making angular version of MineSweeper, but I've got the problem with event. I mean, I've got my field component like that:

```<code>import {Component, Input, OnInit} from '@angular/core';
import {style} from '@angular/animations';

@Component({
  selector: 'app-pool',
  templateUrl: './field.component.html',
  styleUrls: ['./field.component.sass']
})

export class FieldComponent implements OnInit {
  isBomb = false;
  isInfo = false;
  isClickable = true;
  touchesBombCount = 0;
  isMarkedAsBomb = false;
  isExpanded = false;
  poolID: number;
  isBombExpanded = false;

  @Input() display: string;

  constructor() {
  }

  ngOnInit() {
  }

  expandMe() {
    this.isExpanded = !this.isExpanded;
    if (this.isBomb && this.isExpanded) {
      this.isBombExpanded = !this.isBombExpanded;
    }
    console.log(this);
  }

  onFieldClick(event: any) {
    this.expandMe();
    this.isClickable = false;
    console.log(event);
  }

  onRightClick(event: any) {
    event.preventDefault();
    this.isMarkedAsBomb = !this.isMarkedAsBomb;
  }

}
</code>```

Then I'm creating fields in board component:

```<code>import {Component, Input, OnInit} from '@angular/core';
import {FieldComponent} from '../field/field.component';

@Component({
  selector: 'app-board',
  templateUrl: './board.component.html',
  styleUrls: ['./board.component.sass']
})
export class BoardComponent implements OnInit {
  fieldList: FieldComponent[] = [];
  bombCount: number = 10;
  poolBombList: FieldComponent[] = [];
  private allBombsPlanted = false;
  isGameOver = false;

  @Input() poolCount: number;

  constructor() {
  }

  ngOnInit() {
    this.createBoardFromPools();
    while (!this.allBombsPlanted) {
      this.plantTheBombs();
    }
    console.log(this);
  }

  createBoardFromPools() {
    for (let i = 0; i < this.poolCount; i++) {
      const pool = new FieldComponent();
      pool.poolID = i;
      this.fieldList.push(pool);
    }
  }

  plantTheBombs() {
    const poolCount = this.fieldList.length - 1;
    const poolToPlant = Math.floor((Math.random() * poolCount));
    if (!this.checkIfHasBomb(poolToPlant)) {
      this.poolBombList.push(this.fieldList[poolToPlant]);
      this.fieldList[poolToPlant].isBomb = true;
    }
    if (this.poolBombList.length === this.bombCount) {
      this.allBombsPlanted = true;
    }
  }

  checkIfHasBomb(poolToPlant): boolean {

    for (let i = 0, iMax = this.poolBombList.length; i < iMax; i++) {
      if (this.poolBombList[i].poolID === poolToPlant.poolID) {
        return true;
      }
    }
    return false;
  }

}
</code>```

My question is:

why when I console.log (this) of field component, then the bomb is marked as false, even, when on my general list of fields in board component (  fieldList: FieldComponent[] = []) shows it is a bomb actually?

I'm moving from vanilla to angular, maybe I've created fields in board component not correctly?

答:
I've managed it by 'mapping' my fieldList to fieldComponent like this:

Field component:

```<code>@Input() isBomb: boolean;
</code>```

And then in board component template:

```<code><div [className]="'board'">
<app-pool *ngFor="let field of fieldList" [isBomb]="field.isBomb"></app-pool>
</div>
</code>```

It's doing the job, but I don't think so it is the best way to do it in Angular.

Title: Minesweeper - Angular

Body:
I'm making angular version of MineSweeper, but I've got the problem with event. I mean, I've got my field component like that:

import {Component, Input, OnInit} from '@angular/core';
import {style} from '@angular/animations';

@Component({
  selector: 'app-pool',
  templateUrl: './field.component.html',
  styleUrls: ['./field.component.sass']
})

export class FieldComponent implements OnInit {
  isBomb = false;
  isInfo = false;
  isClickable = true;
  touchesBombCount = 0;
  isMarkedAsBomb = false;
  isExpanded = false;
  poolID: number;
  isBombExpanded = false;

  @Input() display: string;

  constructor() {
  }

  ngOnInit() {
  }

  expandMe() {
    this.isExpanded = !this.isExpanded;
    if (this.isBomb && this.isExpanded) {
      this.isBombExpanded = !this.isBombExpanded;
    }
    console.log(this);
  }

  onFieldClick(event: any) {
    this.expandMe();
    this.isClickable = false;
    console.log(event);
  }

  onRightClick(event: any) {
    event.preventDefault();
    this.isMarkedAsBomb = !this.isMarkedAsBomb;
  }

}

Then I'm creating fields in board component:

import {Component, Input, OnInit} from '@angular/core';
import {FieldComponent} from '../field/field.component';

@Component({
  selector: 'app-board',
  templateUrl: './board.component.html',
  styleUrls: ['./board.component.sass']
})
export class BoardComponent implements OnInit {
  fieldList: FieldComponent[] = [];
  bombCount: number = 10;
  poolBombList: FieldComponent[] = [];
  private allBombsPlanted = false;
  isGameOver = false;

  @Input() poolCount: number;

  constructor() {
  }

  ngOnInit() {
    this.createBoardFromPools();
    while (!this.allBombsPlanted) {
      this.plantTheBombs();
    }
    console.log(this);
  }

  createBoardFromPools() {
    for (let i = 0; i < this.poolCount; i++) {
      const pool = new FieldComponent();
      pool.poolID = i;
      this.fieldList.push(pool);
    }
  }

  plantTheBombs() {
    const poolCount = this.fieldList.length - 1;
    const poolToPlant = Math.floor((Math.random() * poolCount));
    if (!this.checkIfHasBomb(poolToPlant)) {
      this.poolBombList.push(this.fieldList[poolToPlant]);
      this.fieldList[poolToPlant].isBomb = true;
    }
    if (this.poolBombList.length === this.bombCount) {
      this.allBombsPlanted = true;
    }
  }

  checkIfHasBomb(poolToPlant): boolean {

    for (let i = 0, iMax = this.poolBombList.length; i < iMax; i++) {
      if (this.poolBombList[i].poolID === poolToPlant.poolID) {
        return true;
      }
    }
    return false;
  }

}

My question is:

why when I console.log (this) of field component, then the bomb is marked as false, even, when on my general list of fields in board component (  fieldList: FieldComponent[] = []) shows it is a bomb actually?

I'm moving from vanilla to angular, maybe I've created fields in board component not correctly?

Body:
I've managed it by 'mapping' my fieldList to fieldComponent like this:

Field component:

@Input() isBomb: boolean;

And then in board component template:

<div [className]="'board'">
<app-pool *ngFor="let field of fieldList" [isBomb]="field.isBomb"></app-pool>
</div>

It's doing the job, but I don't think so it is the best way to do it in Angular.


问:
Is there a function to filter rows that contains a string, but on chosen columns names that contains a given string in R?
i will try to be as specific as possible.
I get chunks of datasets from web application. Number of columns may vary for each dataset i download. I want to filter my data for outliers. So i prepared a list:

```<code>outl <- c("God","Devil","Priest")
</code>```

Now lets assume this is my df:

```<code>ID <- c(1,2,3,4)
Actor1<- c("Driver","","","")
Actor2<- c("President","Zombie","","")
Actor3<- c("CEO","Devil","","")
Actor4<-c("Priest","","Killer","Mayor")
Leng<- c(12,42,42,22)
Genre<-c("horror","criminal","drama","comedy")
df_ex <-data.frame(ID, Actor1, Actor2, Actor3, Actor4, Leng, Genre)
</code>```

i would like to filter for the rows ids that contains names from outlier in ANY column that has "Actor" in name (there could be 100 of them thats why i cant do it with OR operator), so something like:

```<code>df_ex %>%
  filter(*anycolumn that contains string "Actor"* %in% outl)
</code>```

and i would expect to get rows with ids 1 & 2

hope thats clear enough,
thanks in advance

答:
In base R, we can do

```<code>df_ex[Reduce(`|`, lapply(df_ex[startsWith(names(df_ex), "Actor")], `%in%`, outl)), ]
#   ID Actor1    Actor2 Actor3 Actor4 Leng    Genre
#1  1 Driver President    CEO Priest   12   horror
#2  2           Zombie  Devil          42 criminal
</code>```

Body:
i will try to be as specific as possible.
I get chunks of datasets from web application. Number of columns may vary for each dataset i download. I want to filter my data for outliers. So i prepared a list:

outl <- c("God","Devil","Priest")

Now lets assume this is my df:

ID <- c(1,2,3,4)
Actor1<- c("Driver","","","")
Actor2<- c("President","Zombie","","")
Actor3<- c("CEO","Devil","","")
Actor4<-c("Priest","","Killer","Mayor")
Leng<- c(12,42,42,22)
Genre<-c("horror","criminal","drama","comedy")
df_ex <-data.frame(ID, Actor1, Actor2, Actor3, Actor4, Leng, Genre)

i would like to filter for the rows ids that contains names from outlier in ANY column that has "Actor" in name (there could be 100 of them thats why i cant do it with OR operator), so something like:

df_ex %>%
  filter(*anycolumn that contains string "Actor"* %in% outl)

and i would expect to get rows with ids 1 & 2

hope thats clear enough,
thanks in advance

Body:
In base R, we can do

df_ex[Reduce(`|`, lapply(df_ex[startsWith(names(df_ex), "Actor")], `%in%`, outl)), ]
#   ID Actor1    Actor2 Actor3 Actor4 Leng    Genre
#1  1 Driver President    CEO Priest   12   horror
#2  2           Zombie  Devil          42 criminal


问:
How do I modify my SQL Statement so each Project has (x) Judges and each Judge participates evenly among their population?

Question

How do I modify my SQL Statement so each Project has 4 unique judges and each Judge evenly judges the same number of projects for their assigned division and category?

Requirements

Population Project needs to be reviewed by Population Judge (x) times.
x = 4

Each Project is grouped by Division and Category.

Each Judge is grouped by Division and Category.

Each Project must be reviewed by (x) unique Judges.

Each Judge should never review the same project twice.

Each Judge should be assigned an equal number of projects to review as the other judges in their division and category grouping.

Sample Source Judge Table

```<code>create table judges(judge_id, division, category) as (
    select 68, 'Elementary', 'ANY' from dual union all
    select 19, 'Elementary', 'ANY' from dual union all
    select 22, 'Elementary', 'ANY' from dual union all
    select 32, 'Elementary', 'ANY' from dual union all
    select 33, 'Elementary', 'ANY' from dual union all
    select 37, 'Elementary', 'ANY' from dual union all
    select 38, 'Elementary', 'ANY' from dual union all
    select 40, 'Elementary', 'ANY' from dual union all
    select 47, 'Elementary', 'ANY' from dual union all
    select 62, 'Elementary', 'ANY' from dual union all
    select 63, 'Elementary', 'ANY' from dual union all
    select 13, 'Elementary', 'ANY' from dual union all
    select 36, 'Elementary', 'ANY' from dual union all
    select 55, 'Elementary', 'ANY' from dual union all
    select 59, 'Elementary', 'ANY' from dual union all
    select 60, 'Elementary', 'ANY' from dual union all
    select 9, 'Junior', 'EC' from dual union all
    select 10, 'Junior', 'EC' from dual union all
    select 48, 'Junior', 'EC' from dual union all
    select 11, 'Junior', 'LS' from dual union all
    select 21, 'Junior', 'LS' from dual union all
    select 23, 'Junior', 'LS' from dual union all
    select 26, 'Junior', 'LS' from dual union all
    select 31, 'Junior', 'LS' from dual union all
    select 80, 'Junior', 'LS' from dual union all
    select 14, 'Junior', 'PE' from dual union all
    select 15, 'Junior', 'PE' from dual union all
    select 24, 'Junior', 'PE' from dual union all
    select 29, 'Junior', 'PE' from dual union all
    select 30, 'Junior', 'PE' from dual union all
    select 43, 'Junior', 'PE' from dual union all
    select 53, 'Junior', 'PE' from dual union all
    select 56, 'Junior', 'PE' from dual union all
    select 57, 'Junior', 'PE' from dual union all
    select 58, 'Junior', 'PE' from dual union all
    select 65, 'Junior', 'PE' from dual union all
    select 67, 'Junior', 'PE' from dual union all
    select 69, 'Junior', 'PE' from dual union all
    select 8, 'Senior', 'ANY' from dual union all
    select 18, 'Senior', 'ANY' from dual union all
    select 20, 'Senior', 'ANY' from dual union all
    select 35, 'Senior', 'ANY' from dual union all
    select 66, 'Senior', 'ANY' from dual union all
    select 39, 'Senior', 'ANY' from dual union all
    select 70, 'Senior', 'ANY' from dual union all
    select 71, 'Senior', 'ANY' from dual union all
    select 74, 'Senior', 'ANY' from dual union all
    select 6, 'Senior', 'ANY' from dual union all
    select 44, 'Senior', 'ANY' from dual union all
    select 45, 'Senior', 'ANY' from dual union all
    select 49, 'Senior', 'ANY' from dual union all
    select 61, 'Senior', 'ANY' from dual union all
    select 64, 'Senior', 'ANY' from dual union all
    select 72, 'Senior', 'ANY' from dual union all
    select 75, 'Senior', 'ANY' from dual union all
    select 79, 'Senior', 'ANY' from dual union all
    select 82, 'Senior', 'ANY' from dual
);
</code>```

Sample Source Project Table

```<code>create table projects(project_id, division, category) as (
     select 39, 'Elementary', 'ANY' from dual union all
    select 40, 'Elementary', 'ANY' from dual union all
    select 47, 'Elementary', 'ANY' from dual union all
    select 48, 'Elementary', 'ANY' from dual union all
    select 56, 'Elementary', 'ANY' from dual union all
    select 57, 'Elementary', 'ANY' from dual union all
    select 58, 'Elementary', 'ANY' from dual union all
    select 60, 'Elementary', 'ANY' from dual union all
    select 65, 'Elementary', 'ANY' from dual union all
    select 66, 'Elementary', 'ANY' from dual union all
    select 93, 'Elementary', 'ANY' from dual union all
    select 94, 'Elementary', 'ANY' from dual union all
    select 97, 'Elementary', 'ANY' from dual union all
    select 104, 'Elementary', 'ANY' from dual union all
    select 105, 'Elementary', 'ANY' from dual union all
    select 107, 'Elementary', 'ANY' from dual union all
    select 110, 'Elementary', 'ANY' from dual union all
    select 112, 'Elementary', 'ANY' from dual union all
    select 114, 'Elementary', 'ANY' from dual union all
    select 117, 'Elementary', 'ANY' from dual union all
    select 120, 'Elementary', 'ANY' from dual union all
    select 121, 'Elementary', 'ANY' from dual union all
    select 123, 'Elementary', 'ANY' from dual union all
    select 124, 'Elementary', 'ANY' from dual union all
    select 126, 'Elementary', 'ANY' from dual union all
    select 127, 'Elementary', 'ANY' from dual union all
    select 128, 'Elementary', 'ANY' from dual union all
    select 133, 'Elementary', 'ANY' from dual union all
    select 134, 'Elementary', 'ANY' from dual union all
    select 136, 'Elementary', 'ANY' from dual union all
    select 140, 'Elementary', 'ANY' from dual union all
    select 142, 'Elementary', 'ANY' from dual union all
    select 152, 'Elementary', 'ANY' from dual union all
    select 153, 'Elementary', 'ANY' from dual union all
    select 162, 'Elementary', 'ANY' from dual union all
    select 167, 'Elementary', 'ANY' from dual union all
    select 173, 'Elementary', 'ANY' from dual union all
    select 174, 'Elementary', 'ANY' from dual union all
    select 188, 'Elementary', 'ANY' from dual union all
    select 27, 'Junior', 'EC' from dual union all
    select 67, 'Junior', 'EC' from dual union all
    select 82, 'Junior', 'EC' from dual union all
    select 83, 'Junior', 'EC' from dual union all
    select 99, 'Junior', 'EC' from dual union all
    select 113, 'Junior', 'EC' from dual union all
    select 115, 'Junior', 'EC' from dual union all
    select 149, 'Junior', 'EC' from dual union all
    select 164, 'Junior', 'EC' from dual union all
    select 169, 'Junior', 'EC' from dual union all
    select 185, 'Junior', 'EC' from dual union all
    select 189, 'Junior', 'EC' from dual union all
    select 18, 'Junior', 'LS' from dual union all
    select 19, 'Junior', 'LS' from dual union all
    select 20, 'Junior', 'LS' from dual union all
    select 21, 'Junior', 'LS' from dual union all
    select 23, 'Junior', 'LS' from dual union all
    select 24, 'Junior', 'LS' from dual union all
    select 26, 'Junior', 'LS' from dual union all
    select 28, 'Junior', 'LS' from dual union all
    select 29, 'Junior', 'LS' from dual union all
    select 30, 'Junior', 'LS' from dual union all
    select 78, 'Junior', 'LS' from dual union all
    select 80, 'Junior', 'LS' from dual union all
    select 90, 'Junior', 'LS' from dual union all
    select 91, 'Junior', 'LS' from dual union all
    select 106, 'Junior', 'LS' from dual union all
    select 144, 'Junior', 'LS' from dual union all
    select 150, 'Junior', 'LS' from dual union all
    select 151, 'Junior', 'LS' from dual union all
    select 156, 'Junior', 'LS' from dual union all
    select 157, 'Junior', 'LS' from dual union all
    select 159, 'Junior', 'LS' from dual union all
    select 161, 'Junior', 'LS' from dual union all
    select 165, 'Junior', 'LS' from dual union all
    select 166, 'Junior', 'LS' from dual union all
    select 168, 'Junior', 'LS' from dual union all
    select 178, 'Junior', 'LS' from dual union all
    select 180, 'Junior', 'LS' from dual union all
    select 187, 'Junior', 'LS' from dual union all
    select 22, 'Junior', 'PE' from dual union all
    select 59, 'Junior', 'PE' from dual union all
    select 61, 'Junior', 'PE' from dual union all
    select 74, 'Junior', 'PE' from dual union all
    select 81, 'Junior', 'PE' from dual union all
    select 95, 'Junior', 'PE' from dual union all
    select 96, 'Junior', 'PE' from dual union all
    select 116, 'Junior', 'PE' from dual union all
    select 145, 'Junior', 'PE' from dual union all
    select 148, 'Junior', 'PE' from dual union all
    select 158, 'Junior', 'PE' from dual union all
    select 160, 'Junior', 'PE' from dual union all
    select 172, 'Junior', 'PE' from dual union all
    select 176, 'Junior', 'PE' from dual union all
    select 181, 'Junior', 'PE' from dual union all
    select 186, 'Junior', 'PE' from dual union all
    select 14, 'Senior', 'ANY' from dual union all
    select 15, 'Senior', 'ANY' from dual union all
    select 42, 'Senior', 'ANY' from dual union all
    select 43, 'Senior', 'ANY' from dual union all
    select 44, 'Senior', 'ANY' from dual union all
    select 45, 'Senior', 'ANY' from dual union all
    select 46, 'Senior', 'ANY' from dual union all
    select 49, 'Senior', 'ANY' from dual union all
    select 51, 'Senior', 'ANY' from dual union all
    select 52, 'Senior', 'ANY' from dual union all
    select 53, 'Senior', 'ANY' from dual union all
    select 54, 'Senior', 'ANY' from dual union all
    select 75, 'Senior', 'ANY' from dual union all
    select 76, 'Senior', 'ANY' from dual union all
    select 77, 'Senior', 'ANY' from dual union all
    select 92, 'Senior', 'ANY' from dual union all
    select 108, 'Senior', 'ANY' from dual union all
    select 118, 'Senior', 'ANY' from dual union all
    select 119, 'Senior', 'ANY' from dual union all
    select 125, 'Senior', 'ANY' from dual union all
    select 131, 'Senior', 'ANY' from dual union all
    select 132, 'Senior', 'ANY' from dual union all
    select 135, 'Senior', 'ANY' from dual union all
    select 137, 'Senior', 'ANY' from dual union all
    select 138, 'Senior', 'ANY' from dual union all
    select 139, 'Senior', 'ANY' from dual union all
    select 141, 'Senior', 'ANY' from dual union all
    select 143, 'Senior', 'ANY' from dual union all
    select 146, 'Senior', 'ANY' from dual union all
    select 154, 'Senior', 'ANY' from dual union all
    select 171, 'Senior', 'ANY' from dual
);
</code>```

Oracle SQL Code

```<code>select
     project_id
    ,division
    ,category
    ,judge_id
    ,best_match
from(
    select
         project.project_id
        ,project.division
        ,project.category
        ,judge.judge_id
        ,row_number() over(
            partition by project.project_id
            order by dbms_random.value
        ) as best_match
    from frsf_fair.project_division_category project
    left join (
        select
            judge_id
            ,division
            ,category
            ,row_number() over(
                partition by division
                order by dbms_random.value
            ) as r
        from frsf_fair.judge_division_category
        ) judge on project.division = judge.division
            and project.category = judge.category
) assignment
where best_match <= 4
</code>```

Data Output Example

```<code>PROJECT_ID  DIVISION    CATEGORY    JUDGE_ID    BEST_MATCH
14  Senior  ANY 72  1
14  Senior  ANY 74  2
14  Senior  ANY 20  3
14  Senior  ANY 44  4

15  Senior  ANY 79  1
15  Senior  ANY 39  2
15  Senior  ANY 75  3
15  Senior  ANY 20  4

18  Junior  LS  23  1
18  Junior  LS  31  2
18  Junior  LS  26  3
18  Junior  LS  21  4
</code>```

Problem

The number of count(*)/projects should be distributed evenly among the Division and Category for a pool a judge. Instead, some judges are assigned to 20 projects while others are assigned to very few. I don't know how to modify my query so each judge must be reference an equal number of times amongst the Project Division and Category grouping. I want to ensure equal participation.

```<code>JUDGE_ID    COUNT(*)
64  8
72  16
23  20
57  4
14  4
6   4
58  9
</code>```

答:
The best I could do is this query:

```<code>with
  t as (select judge_id jid, project_id pid, category cat, division div,
               dense_rank() over (order by project_id) rp,
               dense_rank() over (order by judge_id) rj,
               count(1) over (partition by project_id) cnt
          from judges join projects using (division, category)),
  c(pid, jid, cat, div, rn, rp) as (
    select pid, jid, cat, div, 1, rp from t where mod(rp, cnt) = mod(rj, cnt)
    union all
    select c.pid, t.jid, c.cat, c.div, rn + 1, c.rp
      from c join t on c.rp = t.rp and c.jid <> t.jid
                   and mod(t.rp, t.cnt) = mod(t.rj + c.rn, t.cnt)
      where rn < 3)
select * from c
</code>```

What it does? At first basic join with added row numbers and counts (rp, rj, cnt). These columns are then used by mod() to join rows in anchor query where mod(rp, cnt) = mod(rj, cnt). Then recursive part which only adds required number of judges to each project. Probably someone can do it without recursion, but I was not able. You can randomize output somewhat by assigning random ids to judges and use them in query instead of real ids. Replace 3 with required number of reviews.

This dbfiddle shows 5 projects, 5 judges, 3 reviews per project. Judges do not repeat, are distributed equally.

Edit: This is corrected basic query:

```<code>with t as (
    select category, division, project_id, judge_id,
           dense_rank() over (partition by category, division
                              order by project_id) rp,
           dense_rank() over (partition by category, division, project_id
                              order by judge_id) rj,
           count(1) over (partition by project_id) cnt
      from projects join judges using (category, division) )
select * from t
  join (select level lvl from dual connect by level <= 3)
    on mod(rj, cnt) =  mod((rp -1) * 3 + lvl, cnt)
</code>```

I checked results for projects (group by project_id) and every project has 3 distinct judges.
I checked results for judges (group by category, division, judge_id) and every judge in his class has same number of cases (differs by one if there is not enough projects for equal distribution).

Logic is the same as in my first query. As I said you can randomize judges at first:

```<code>select row_number() over (order by dbms_random.value) rnd_jdg_id, judges.* from judges
</code>```

and use this fake id as input in main query to get totally random assignment.

Body:
Question

How do I modify my SQL Statement so each Project has 4 unique judges and each Judge evenly judges the same number of projects for their assigned division and category?

Requirements

Population Project needs to be reviewed by Population Judge (x) times.
x = 4

Each Project is grouped by Division and Category.

Each Judge is grouped by Division and Category.

Each Project must be reviewed by (x) unique Judges.

Each Judge should never review the same project twice.

Each Judge should be assigned an equal number of projects to review as the other judges in their division and category grouping.

Sample Source Judge Table

create table judges(judge_id, division, category) as (
    select 68, 'Elementary', 'ANY' from dual union all
    select 19, 'Elementary', 'ANY' from dual union all
    select 22, 'Elementary', 'ANY' from dual union all
    select 32, 'Elementary', 'ANY' from dual union all
    select 33, 'Elementary', 'ANY' from dual union all
    select 37, 'Elementary', 'ANY' from dual union all
    select 38, 'Elementary', 'ANY' from dual union all
    select 40, 'Elementary', 'ANY' from dual union all
    select 47, 'Elementary', 'ANY' from dual union all
    select 62, 'Elementary', 'ANY' from dual union all
    select 63, 'Elementary', 'ANY' from dual union all
    select 13, 'Elementary', 'ANY' from dual union all
    select 36, 'Elementary', 'ANY' from dual union all
    select 55, 'Elementary', 'ANY' from dual union all
    select 59, 'Elementary', 'ANY' from dual union all
    select 60, 'Elementary', 'ANY' from dual union all
    select 9, 'Junior', 'EC' from dual union all
    select 10, 'Junior', 'EC' from dual union all
    select 48, 'Junior', 'EC' from dual union all
    select 11, 'Junior', 'LS' from dual union all
    select 21, 'Junior', 'LS' from dual union all
    select 23, 'Junior', 'LS' from dual union all
    select 26, 'Junior', 'LS' from dual union all
    select 31, 'Junior', 'LS' from dual union all
    select 80, 'Junior', 'LS' from dual union all
    select 14, 'Junior', 'PE' from dual union all
    select 15, 'Junior', 'PE' from dual union all
    select 24, 'Junior', 'PE' from dual union all
    select 29, 'Junior', 'PE' from dual union all
    select 30, 'Junior', 'PE' from dual union all
    select 43, 'Junior', 'PE' from dual union all
    select 53, 'Junior', 'PE' from dual union all
    select 56, 'Junior', 'PE' from dual union all
    select 57, 'Junior', 'PE' from dual union all
    select 58, 'Junior', 'PE' from dual union all
    select 65, 'Junior', 'PE' from dual union all
    select 67, 'Junior', 'PE' from dual union all
    select 69, 'Junior', 'PE' from dual union all
    select 8, 'Senior', 'ANY' from dual union all
    select 18, 'Senior', 'ANY' from dual union all
    select 20, 'Senior', 'ANY' from dual union all
    select 35, 'Senior', 'ANY' from dual union all
    select 66, 'Senior', 'ANY' from dual union all
    select 39, 'Senior', 'ANY' from dual union all
    select 70, 'Senior', 'ANY' from dual union all
    select 71, 'Senior', 'ANY' from dual union all
    select 74, 'Senior', 'ANY' from dual union all
    select 6, 'Senior', 'ANY' from dual union all
    select 44, 'Senior', 'ANY' from dual union all
    select 45, 'Senior', 'ANY' from dual union all
    select 49, 'Senior', 'ANY' from dual union all
    select 61, 'Senior', 'ANY' from dual union all
    select 64, 'Senior', 'ANY' from dual union all
    select 72, 'Senior', 'ANY' from dual union all
    select 75, 'Senior', 'ANY' from dual union all
    select 79, 'Senior', 'ANY' from dual union all
    select 82, 'Senior', 'ANY' from dual
);

Sample Source Project Table

create table projects(project_id, division, category) as (
     select 39, 'Elementary', 'ANY' from dual union all
    select 40, 'Elementary', 'ANY' from dual union all
    select 47, 'Elementary', 'ANY' from dual union all
    select 48, 'Elementary', 'ANY' from dual union all
    select 56, 'Elementary', 'ANY' from dual union all
    select 57, 'Elementary', 'ANY' from dual union all
    select 58, 'Elementary', 'ANY' from dual union all
    select 60, 'Elementary', 'ANY' from dual union all
    select 65, 'Elementary', 'ANY' from dual union all
    select 66, 'Elementary', 'ANY' from dual union all
    select 93, 'Elementary', 'ANY' from dual union all
    select 94, 'Elementary', 'ANY' from dual union all
    select 97, 'Elementary', 'ANY' from dual union all
    select 104, 'Elementary', 'ANY' from dual union all
    select 105, 'Elementary', 'ANY' from dual union all
    select 107, 'Elementary', 'ANY' from dual union all
    select 110, 'Elementary', 'ANY' from dual union all
    select 112, 'Elementary', 'ANY' from dual union all
    select 114, 'Elementary', 'ANY' from dual union all
    select 117, 'Elementary', 'ANY' from dual union all
    select 120, 'Elementary', 'ANY' from dual union all
    select 121, 'Elementary', 'ANY' from dual union all
    select 123, 'Elementary', 'ANY' from dual union all
    select 124, 'Elementary', 'ANY' from dual union all
    select 126, 'Elementary', 'ANY' from dual union all
    select 127, 'Elementary', 'ANY' from dual union all
    select 128, 'Elementary', 'ANY' from dual union all
    select 133, 'Elementary', 'ANY' from dual union all
    select 134, 'Elementary', 'ANY' from dual union all
    select 136, 'Elementary', 'ANY' from dual union all
    select 140, 'Elementary', 'ANY' from dual union all
    select 142, 'Elementary', 'ANY' from dual union all
    select 152, 'Elementary', 'ANY' from dual union all
    select 153, 'Elementary', 'ANY' from dual union all
    select 162, 'Elementary', 'ANY' from dual union all
    select 167, 'Elementary', 'ANY' from dual union all
    select 173, 'Elementary', 'ANY' from dual union all
    select 174, 'Elementary', 'ANY' from dual union all
    select 188, 'Elementary', 'ANY' from dual union all
    select 27, 'Junior', 'EC' from dual union all
    select 67, 'Junior', 'EC' from dual union all
    select 82, 'Junior', 'EC' from dual union all
    select 83, 'Junior', 'EC' from dual union all
    select 99, 'Junior', 'EC' from dual union all
    select 113, 'Junior', 'EC' from dual union all
    select 115, 'Junior', 'EC' from dual union all
    select 149, 'Junior', 'EC' from dual union all
    select 164, 'Junior', 'EC' from dual union all
    select 169, 'Junior', 'EC' from dual union all
    select 185, 'Junior', 'EC' from dual union all
    select 189, 'Junior', 'EC' from dual union all
    select 18, 'Junior', 'LS' from dual union all
    select 19, 'Junior', 'LS' from dual union all
    select 20, 'Junior', 'LS' from dual union all
    select 21, 'Junior', 'LS' from dual union all
    select 23, 'Junior', 'LS' from dual union all
    select 24, 'Junior', 'LS' from dual union all
    select 26, 'Junior', 'LS' from dual union all
    select 28, 'Junior', 'LS' from dual union all
    select 29, 'Junior', 'LS' from dual union all
    select 30, 'Junior', 'LS' from dual union all
    select 78, 'Junior', 'LS' from dual union all
    select 80, 'Junior', 'LS' from dual union all
    select 90, 'Junior', 'LS' from dual union all
    select 91, 'Junior', 'LS' from dual union all
    select 106, 'Junior', 'LS' from dual union all
    select 144, 'Junior', 'LS' from dual union all
    select 150, 'Junior', 'LS' from dual union all
    select 151, 'Junior', 'LS' from dual union all
    select 156, 'Junior', 'LS' from dual union all
    select 157, 'Junior', 'LS' from dual union all
    select 159, 'Junior', 'LS' from dual union all
    select 161, 'Junior', 'LS' from dual union all
    select 165, 'Junior', 'LS' from dual union all
    select 166, 'Junior', 'LS' from dual union all
    select 168, 'Junior', 'LS' from dual union all
    select 178, 'Junior', 'LS' from dual union all
    select 180, 'Junior', 'LS' from dual union all
    select 187, 'Junior', 'LS' from dual union all
    select 22, 'Junior', 'PE' from dual union all
    select 59, 'Junior', 'PE' from dual union all
    select 61, 'Junior', 'PE' from dual union all
    select 74, 'Junior', 'PE' from dual union all
    select 81, 'Junior', 'PE' from dual union all
    select 95, 'Junior', 'PE' from dual union all
    select 96, 'Junior', 'PE' from dual union all
    select 116, 'Junior', 'PE' from dual union all
    select 145, 'Junior', 'PE' from dual union all
    select 148, 'Junior', 'PE' from dual union all
    select 158, 'Junior', 'PE' from dual union all
    select 160, 'Junior', 'PE' from dual union all
    select 172, 'Junior', 'PE' from dual union all
    select 176, 'Junior', 'PE' from dual union all
    select 181, 'Junior', 'PE' from dual union all
    select 186, 'Junior', 'PE' from dual union all
    select 14, 'Senior', 'ANY' from dual union all
    select 15, 'Senior', 'ANY' from dual union all
    select 42, 'Senior', 'ANY' from dual union all
    select 43, 'Senior', 'ANY' from dual union all
    select 44, 'Senior', 'ANY' from dual union all
    select 45, 'Senior', 'ANY' from dual union all
    select 46, 'Senior', 'ANY' from dual union all
    select 49, 'Senior', 'ANY' from dual union all
    select 51, 'Senior', 'ANY' from dual union all
    select 52, 'Senior', 'ANY' from dual union all
    select 53, 'Senior', 'ANY' from dual union all
    select 54, 'Senior', 'ANY' from dual union all
    select 75, 'Senior', 'ANY' from dual union all
    select 76, 'Senior', 'ANY' from dual union all
    select 77, 'Senior', 'ANY' from dual union all
    select 92, 'Senior', 'ANY' from dual union all
    select 108, 'Senior', 'ANY' from dual union all
    select 118, 'Senior', 'ANY' from dual union all
    select 119, 'Senior', 'ANY' from dual union all
    select 125, 'Senior', 'ANY' from dual union all
    select 131, 'Senior', 'ANY' from dual union all
    select 132, 'Senior', 'ANY' from dual union all
    select 135, 'Senior', 'ANY' from dual union all
    select 137, 'Senior', 'ANY' from dual union all
    select 138, 'Senior', 'ANY' from dual union all
    select 139, 'Senior', 'ANY' from dual union all
    select 141, 'Senior', 'ANY' from dual union all
    select 143, 'Senior', 'ANY' from dual union all
    select 146, 'Senior', 'ANY' from dual union all
    select 154, 'Senior', 'ANY' from dual union all
    select 171, 'Senior', 'ANY' from dual
);

Oracle SQL Code

select
     project_id
    ,division
    ,category
    ,judge_id
    ,best_match
from(
    select
         project.project_id
        ,project.division
        ,project.category
        ,judge.judge_id
        ,row_number() over(
            partition by project.project_id
            order by dbms_random.value
        ) as best_match
    from frsf_fair.project_division_category project
    left join (
        select
            judge_id
            ,division
            ,category
            ,row_number() over(
                partition by division
                order by dbms_random.value
            ) as r
        from frsf_fair.judge_division_category
        ) judge on project.division = judge.division
            and project.category = judge.category
) assignment
where best_match <= 4

Data Output Example

PROJECT_ID  DIVISION    CATEGORY    JUDGE_ID    BEST_MATCH
14  Senior  ANY 72  1
14  Senior  ANY 74  2
14  Senior  ANY 20  3
14  Senior  ANY 44  4

15  Senior  ANY 79  1
15  Senior  ANY 39  2
15  Senior  ANY 75  3
15  Senior  ANY 20  4

18  Junior  LS  23  1
18  Junior  LS  31  2
18  Junior  LS  26  3
18  Junior  LS  21  4

Problem

The number of count(*)/projects should be distributed evenly among the Division and Category for a pool a judge. Instead, some judges are assigned to 20 projects while others are assigned to very few. I don't know how to modify my query so each judge must be reference an equal number of times amongst the Project Division and Category grouping. I want to ensure equal participation.

JUDGE_ID    COUNT(*)
64  8
72  16
23  20
57  4
14  4
6   4
58  9

Body:
The best I could do is this query:

with
  t as (select judge_id jid, project_id pid, category cat, division div,
               dense_rank() over (order by project_id) rp,
               dense_rank() over (order by judge_id) rj,
               count(1) over (partition by project_id) cnt
          from judges join projects using (division, category)),
  c(pid, jid, cat, div, rn, rp) as (
    select pid, jid, cat, div, 1, rp from t where mod(rp, cnt) = mod(rj, cnt)
    union all
    select c.pid, t.jid, c.cat, c.div, rn + 1, c.rp
      from c join t on c.rp = t.rp and c.jid <> t.jid
                   and mod(t.rp, t.cnt) = mod(t.rj + c.rn, t.cnt)
      where rn < 3)
select * from c

What it does? At first basic join with added row numbers and counts (rp, rj, cnt). These columns are then used by mod() to join rows in anchor query where mod(rp, cnt) = mod(rj, cnt). Then recursive part which only adds required number of judges to each project. Probably someone can do it without recursion, but I was not able. You can randomize output somewhat by assigning random ids to judges and use them in query instead of real ids. Replace 3 with required number of reviews.

This dbfiddle shows 5 projects, 5 judges, 3 reviews per project. Judges do not repeat, are distributed equally.

Edit: This is corrected basic query:

with t as (
    select category, division, project_id, judge_id,
           dense_rank() over (partition by category, division
                              order by project_id) rp,
           dense_rank() over (partition by category, division, project_id
                              order by judge_id) rj,
           count(1) over (partition by project_id) cnt
      from projects join judges using (category, division) )
select * from t
  join (select level lvl from dual connect by level <= 3)
    on mod(rj, cnt) =  mod((rp -1) * 3 + lvl, cnt)

I checked results for projects (group by project_id) and every project has 3 distinct judges.
I checked results for judges (group by category, division, judge_id) and every judge in his class has same number of cases (differs by one if there is not enough projects for equal distribution).

Logic is the same as in my first query. As I said you can randomize judges at first:

select row_number() over (order by dbms_random.value) rnd_jdg_id, judges.* from judges

and use this fake id as input in main query to get totally random assignment.


问:
Why does my mocking of an URL with requests not work?
I tried to mock a specific URL as shown in this example:
How can I mock requests and the response?
to test my own function:

```<code>class URLStatus():
  @staticmethod
  def check(url, redirects):
    try:
      session = requests.Session()
      session.max_redirects = redirects
      urlcheck = session.get(url)
      return urlcheck.status_code
</code>```

The issue is that it never takes the mocked url, but instead only takes real ones.

```<code>import requests

from unittest import TestCase, mock
from unittest.mock import patch

from lib.checks.url_status import URLStatus

def mocked_requests_get(*args, **kwargs):
  class MockResponse:
    def __init__(self, json_data, status_code):
      self.json_data = json_data
      self.status_code = status_code

    def json(self):
      return self.json_data

  if args[0] == 'http://someurl.com/test.json':
    return MockResponse({"key1": "value1"}, 200)
  elif args[0] == 'http://someotherurl.com/anothertest.json':
    return MockResponse({"key2": "value2"}, 200)

  return MockResponse(None, 404)

class URLStatusTestCase(TestCase):

  @mock.patch('lib.checks.url_status.requests.get', side_effect=mocked_requests_get)
  def test_check(self, mock_get):

    url_status = URLStatus()
    test_data = url_status.check('http://someurl.com/test.json', 5)
    self.assertEqual(test_data, 200)

if __name__ == '__main__':
  unittest.main()
</code>```

This one, for example, fails because it sees 'http://someurl.com/test.json' as a 404, not a 200. I have no idea why this is happening.

How do I make it take the mocked URL?

答:
You are mocking the wrong function. requests.get is a convenience function that creates its own, one-use Session, then uses its get method to provide the result. Your check method is using its own Session object; you need to at least mock that object's get method.

Given that you aren't reusing this session elsewhere, it would probably be simplest to change its implementation to take advantage of requests.get:

```<code>class URLStatus():
    @staticmethod
    def check(url, redirects):
        return requests.get(url, max_redirects=redirects).status_code
</code>```

Body:
I tried to mock a specific URL as shown in this example:
How can I mock requests and the response?
to test my own function:

class URLStatus():
  @staticmethod
  def check(url, redirects):
    try:
      session = requests.Session()
      session.max_redirects = redirects
      urlcheck = session.get(url)
      return urlcheck.status_code

The issue is that it never takes the mocked url, but instead only takes real ones.

import requests

from unittest import TestCase, mock
from unittest.mock import patch

from lib.checks.url_status import URLStatus

def mocked_requests_get(*args, **kwargs):
  class MockResponse:
    def __init__(self, json_data, status_code):
      self.json_data = json_data
      self.status_code = status_code

    def json(self):
      return self.json_data

  if args[0] == 'http://someurl.com/test.json':
    return MockResponse({"key1": "value1"}, 200)
  elif args[0] == 'http://someotherurl.com/anothertest.json':
    return MockResponse({"key2": "value2"}, 200)

  return MockResponse(None, 404)

class URLStatusTestCase(TestCase):

  @mock.patch('lib.checks.url_status.requests.get', side_effect=mocked_requests_get)
  def test_check(self, mock_get):

    url_status = URLStatus()
    test_data = url_status.check('http://someurl.com/test.json', 5)
    self.assertEqual(test_data, 200)

if __name__ == '__main__':
  unittest.main()

This one, for example, fails because it sees 'http://someurl.com/test.json' as a 404, not a 200. I have no idea why this is happening.

How do I make it take the mocked URL?

Body:
You are mocking the wrong function. requests.get is a convenience function that creates its own, one-use Session, then uses its get method to provide the result. Your check method is using its own Session object; you need to at least mock that object's get method.

Given that you aren't reusing this session elsewhere, it would probably be simplest to change its implementation to take advantage of requests.get:

class URLStatus():
    @staticmethod
    def check(url, redirects):
        return requests.get(url, max_redirects=redirects).status_code


问:
Change output filename in setup.py (distutils.extension)
Here's my setup.py

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

wrapper = Extension(
    name="libwrapper",
    ...
)
setup(
    name="libwrapper",
    ext_modules=cythonize([wrapper])
)
```

When I run python3 setup.py build_ext the output file is called libwrapper.cpython-36m-x86_64-linux-gnu.so, but I want to name it only libwrapper.so, how can I do that?

答:
Try the following code. sysconfig.get_config_var('EXT_SUFFIX') returns platform-specific suffix which can be removed from the final filename by subclassing build_ext and overriding get_ext_filename.

from distutils import sysconfig
from Cython.Distutils import build_ext
from distutils.core import setup
import os

class NoSuffixBuilder(build_ext):
    def get_ext_filename(self, ext_name):
        filename = super().get_ext_filename(ext_name)
        suffix = sysconfig.get_config_var('EXT_SUFFIX')
        ext = os.path.splitext(filename)[1]
        return filename.replace(suffix, "") + ext

setup(
    ....
    cmdclass={"build_ext": NoSuffixBuilder},
)
```

Final filename will be test.so

Body:
Here's my setup.py

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

wrapper = Extension(
    name="libwrapper",
    ...
)
setup(
    name="libwrapper",
    ext_modules=cythonize([wrapper])
)

When I run python3 setup.py build_ext the output file is called libwrapper.cpython-36m-x86_64-linux-gnu.so, but I want to name it only libwrapper.so, how can I do that?

Body:
Try the following code. sysconfig.get_config_var('EXT_SUFFIX') returns platform-specific suffix which can be removed from the final filename by subclassing build_ext and overriding get_ext_filename.

from distutils import sysconfig
from Cython.Distutils import build_ext
from distutils.core import setup
import os

class NoSuffixBuilder(build_ext):
    def get_ext_filename(self, ext_name):
        filename = super().get_ext_filename(ext_name)
        suffix = sysconfig.get_config_var('EXT_SUFFIX')
        ext = os.path.splitext(filename)[1]
        return filename.replace(suffix, "") + ext

setup(
    ....
    cmdclass={"build_ext": NoSuffixBuilder},
)

Final filename will be test.so


问:
Food menu list automatically split into 2 columns
I want to achieve a food menu that looks like this (screenshot), split into 2 columns.

So the question is: Is there any possible way to automate it? A la just insert foods into one list and it automatically splits it into 2 columns.

Best Regards

答:
Yes, if this was a React Project for example, you just make a component for the menu Item, and you make the container flex.

Either way, in HTML, lets say your structure is like this:

```<code><div class="menu-container">
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>
</code>```

Then, for css you just need:

```<code>   .menu-container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;

}

.menu-item {
    flex-basis: 50%;
}
</code>```

The explanation is the following, the parent is a flexbox, which will display elements in a row fashion.

Each child has a flex-basis of 50%, meaning that each item will ocupy a 50% of the parent container and after that it will break a new row.

I recommend this useful site which has all of the most important properties of flexbox very well explained

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Body:
Yes, if this was a React Project for example, you just make a component for the menu Item, and you make the container flex.

Either way, in HTML, lets say your structure is like this:

<div class="menu-container">
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>
<div class="menu-item">

</div>

Then, for css you just need:

   .menu-container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;

}

.menu-item {
    flex-basis: 50%;
}

The explanation is the following, the parent is a flexbox, which will display elements in a row fashion.

Each child has a flex-basis of 50%, meaning that each item will ocupy a 50% of the parent container and after that it will break a new row.

I recommend this useful site which has all of the most important properties of flexbox very well explained

https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
How compare third one in each array in each line?
If I have two array

```<code>A = [ "B,C,D"
      "W,F,G"
      "M,S,E"
    ]
D = [E]
</code>```

and want to compare D OR G with E (I mean the third one in each line)and If they are equal can show all the line for me. The third one in each line a part of each line and I want just compare the third one If it is equal show that line have equal variable .
I wrote this code but didn't give me the response that I need have :

```<code> for(var k=0 ; k<A.length ; k++){
    if(A[k].split(",")[2] === E) {
       finalSuccessServices = A;
       console.log(finalSuccessServices );
     }
</code>```

How can I improve my code to get that line that have my equal variable?

答:
Use split and destructure to get third element

Compare third value and first (from array D)

Console log and push to finalSuccessServices array.

const A = ["B,C,D", "W,F,G", "M,S,E"];
const D = ["E"];

const [first] = D;
const finalSuccessServices = [];
A.forEach(line => {
  const [,, third] = line.split(",");
  if (third === first) {
    console.log(line);
    finalSuccessServices.push(line);
  }
});

console.log("finalSuccessServices", finalSuccessServices);```

Body:
If I have two array

A = [ "B,C,D"
      "W,F,G"
      "M,S,E"
    ]
D = [E]

and want to compare D OR G with E (I mean the third one in each line)and If they are equal can show all the line for me. The third one in each line a part of each line and I want just compare the third one If it is equal show that line have equal variable .
I wrote this code but didn't give me the response that I need have :

 for(var k=0 ; k<A.length ; k++){
    if(A[k].split(",")[2] === E) {
       finalSuccessServices = A;
       console.log(finalSuccessServices );
     }

How can I improve my code to get that line that have my equal variable?


问:
having two or more worker queues in python
So I have 2 main worker processes one is supposed to fetch content of a URL and the other
will insert each of the anchor links into a postgre table. Now I am running
12 instances of the first process all of which taking their URL from a single URL queue, and then placing the anchors in a second queue but how do I have an other set of threads trying to push the Anchors into the table? when I start the threads the find their queue empty and they die, if I disable that feature they wont die when the work is done, how do I manage this, and by the way is it better to use process instead of thread because of presumably intensive IO interaction involved?  </p>

答:
you need two queues the URLFetchers will pop URLs from one queue and push into a second one, then the AnchorInserters should pop from this second queue to process the data. This organisation should give you a good sync mechanism for your problem.

Edit: to avoid worker exiting

You need to block till one element is available.

```<code>while True:
   element = queue.get(block=True, timeout=None)
   #do worker's task
</code>```

From python's queue.get doc ...

If optional args block is true and
  timeout is None (the default), block
  if necessary until an item is
  available.

Body:
you need two queues the URLFetchers will pop URLs from one queue and push into a second one, then the AnchorInserters should pop from this second queue to process the data. This organisation should give you a good sync mechanism for your problem.

Edit: to avoid worker exiting

You need to block till one element is available.

while True:
   element = queue.get(block=True, timeout=None)
   #do worker's task

From python's queue.get doc ...

If optional args block is true and
  timeout is None (the default), block
  if necessary until an item is
  available.


问:
Empty PDF's with Dompdf
I am making an integration of invoices to a wordpress site, in which I have to generate a pdf of the invoices that are stamped, so several PDF's have to be done at the same time, so in a foreach cycle I am making the call of the class I did with dompdf, in my tests I am trying to generate 9 PDF's at a time, and the files are created correctly, but the detail is that only the first PDF has content, the other 8 PDF's are empty, some will have an idea of what pass? Here I leave the code</p>

```<code>class genera_pdf{
 public function genera($path){
        $fechaHoy= date( 'Y-m-d');
        ob_start();
        require_once plugin_dir_path(__DIR__) . 'templates/pdf/factura.php';
        $codigoHTML=ob_get_clean();
        $pdf= new Dompdf();
        $pdf->load_html($codigoHTML);
        $pdf->setPaper('A4', 'portrait');
        $pdf->render();
        $salida = $pdf->output()
        file_put_contents($path['basedir'].'/profact/FacturaRetenciones-'.$fechaHoy.'.pdf', $salida);
    }
}
</code>```

答:
I already solved it, the problem was with the line:

```<code>require_once plugin_dir_path (__ DIR__). 'templates / pdf / invoice.php';
</code>```

Since it requires_once, it includes the file only if it was not included before, as in the first route of the cycle it had already been included, the following ones did not already do it and as everything was saved in the buffer with ob_get_clean (), at the same time it is deleted at the end, that's why it was completely blank, all I did was change to:

```<code>include (plugin_dir_path (__ DIR__). 'templates / pdf / invoice.php');
</code>```

With that my problem was solved and all the PDF's already have the content I wanted

Title: Empty PDF's with Dompdf

Body:
I am making an integration of invoices to a wordpress site, in which I have to generate a pdf of the invoices that are stamped, so several PDF's have to be done at the same time, so in a foreach cycle I am making the call of the class I did with dompdf, in my tests I am trying to generate 9 PDF's at a time, and the files are created correctly, but the detail is that only the first PDF has content, the other 8 PDF's are empty, some will have an idea of what pass? Here I leave the code

class genera_pdf{
 public function genera($path){
        $fechaHoy= date( 'Y-m-d');
        ob_start();
        require_once plugin_dir_path(__DIR__) . 'templates/pdf/factura.php';
        $codigoHTML=ob_get_clean();
        $pdf= new Dompdf();
        $pdf->load_html($codigoHTML);
        $pdf->setPaper('A4', 'portrait');
        $pdf->render();
        $salida = $pdf->output()
        file_put_contents($path['basedir'].'/profact/FacturaRetenciones-'.$fechaHoy.'.pdf', $salida);
    }
}

Body:
I already solved it, the problem was with the line:

require_once plugin_dir_path (__ DIR__). 'templates / pdf / invoice.php';

Since it requires_once, it includes the file only if it was not included before, as in the first route of the cycle it had already been included, the following ones did not already do it and as everything was saved in the buffer with ob_get_clean (), at the same time it is deleted at the end, that's why it was completely blank, all I did was change to:

include (plugin_dir_path (__ DIR__). 'templates / pdf / invoice.php');

With that my problem was solved and all the PDF's already have the content I wanted


问:
Optimizing a systemd service taking too long
I have this udhcpc service in my system:

```<code>[Unit]
Description=uDHCP Client Service
After=network.target
Conflicts=systemd-resolved.service

[Service]
Type=forking
ExecStart=/sbin/udhcpc -p /var/run/udhcpc.brg0.pid -i brg0 -R -b
ExecStop=/bin/sh -c 'test -f /var/run/udhcpc.brg0.pid && kill $(cat /var/run/udhcpc.brg0.pid)'

[Install]
WantedBy=multi-user.target
</code>```

It's been working well, except systemd-analyze is showing that it is adding about 7 seconds to the boot time:

```<code>          7.388s udhcpc.service
          4.946s dev-mmcblk1p2.device
          1.303s uim-sysfs.service
           959ms dev-mmcblk1p4.device
           752ms dev-mmcblk1p3.device
           739ms dev-mmcblk1p1.device
           718ms systemd-hwdb-update.service
           .
           .

</code>```

And here is the output of systemd-analyze critical-chain:

```<code>multi-user.target @15.164s
[[0;1;31mudhcpc.service @7.773s +7.388s[[0m
  network.target @7.551s
    [[0;1;31msystemd-networkd.service @6.724s +668ms[[0m
      [[0;1;31msystemd-udevd.service @1.854s +87ms[[0m
        [[0;1;31msystemd-tmpfiles-setup-dev.service @1.662s +70ms[[0m
          [[0;1;31msystemd-sysusers.service @1.353s +229ms[[0m
            [[0;1;31msystemd-remount-fs.service @1.044s +238ms[[0m
              systemd-journald.socket @911ms
                -.slice @281ms
</code>```

I suppose the right way to fix this is to avoid using udhcpc and stick to the mechanism built into systemd, but unfortunately that's not my call. I'd like to at least optimize the boot time though. What are some things I can do?

答:
The "problem" is systemd-networkd, which stops the boot until the network is configured -- and this is what you want to replace, not systemd-resolved.

Network autoconfiguration cannot be made any faster, because, when properly implemented, DHCP needs to check that the address isn't already in use, which involves sending a bunch of ARP packets and waiting for the timeout.

Since you insert your service between "network is configured" and "multi-user boot is complete" targets, you introduce a dependency where there was none before.

Network configuration is normally asynchronous, because any service that fails when the network is unconfigured at start would also fail when the network goes down later.

Body:
I have this udhcpc service in my system:

[Unit]
Description=uDHCP Client Service
After=network.target
Conflicts=systemd-resolved.service

[Service]
Type=forking
ExecStart=/sbin/udhcpc -p /var/run/udhcpc.brg0.pid -i brg0 -R -b
ExecStop=/bin/sh -c 'test -f /var/run/udhcpc.brg0.pid && kill $(cat /var/run/udhcpc.brg0.pid)'

[Install]
WantedBy=multi-user.target

It's been working well, except systemd-analyze is showing that it is adding about 7 seconds to the boot time:

          7.388s udhcpc.service
          4.946s dev-mmcblk1p2.device
          1.303s uim-sysfs.service
           959ms dev-mmcblk1p4.device
           752ms dev-mmcblk1p3.device
           739ms dev-mmcblk1p1.device
           718ms systemd-hwdb-update.service
           .
           .

And here is the output of systemd-analyze critical-chain:

multi-user.target @15.164s
[[0;1;31mudhcpc.service @7.773s +7.388s[[0m
  network.target @7.551s
    [[0;1;31msystemd-networkd.service @6.724s +668ms[[0m
      [[0;1;31msystemd-udevd.service @1.854s +87ms[[0m
        [[0;1;31msystemd-tmpfiles-setup-dev.service @1.662s +70ms[[0m
          [[0;1;31msystemd-sysusers.service @1.353s +229ms[[0m
            [[0;1;31msystemd-remount-fs.service @1.044s +238ms[[0m
              systemd-journald.socket @911ms
                -.slice @281ms

I suppose the right way to fix this is to avoid using udhcpc and stick to the mechanism built into systemd, but unfortunately that's not my call. I'd like to at least optimize the boot time though. What are some things I can do?


问:
Visualize Kafka Logs in Kibana
I am trying to visualise Kafka logs through ELK stack. I particularly need to see number of messages unread by consumers in real-time. I have seen the log folder in Kafka but wasn't able to understand.

Where would I find information related to offsets to consumers and how do i upload it in elasticsearch ?

Is there a documentation about logs in kafka (e.g server.log, controller.log)

答:
Log folder of Kafka doesn't hold consumer lag.

You'll want to export this data from consumer applications themselves or install external monitoring like Prometheus, Burrow, or Remora, then scrape and index into Elasticsearch

Title: Visualize Kafka Logs in Kibana


问:
Get value of one column based on another column in same table
Here is what I am trying to do: Get all people with the same boss and email the boss. I can only use the table below and I would like to add another column showing the boss email which is found in the table.

```<code>id      name       email            boss
-------------------------------------------
1       Apple      Apple@alo.com    Rita
2       Bob        Bob@alo.com      Rita
3       Charlie    Charlie@alo.com  Nuna
4       Dan        Dan@alo.com      Rita
5       Rita       Rita@alo.com     Sheeba
6       Nuna       Nuna@alo.com     Sheeba
</code>```

Thanks for any help.

答:
You use a join to do that.  It looks like the code below.  When joining to the same table you have to use an alias.

```<code>SELECT base.name, boss.email as boss_email
from the_table_name_you_did_not_say as base
join the_table_name_you_did_not_say as boss on base.boss = boss.name
</code>```

Technically you don't have to use an alias on the base table if you select a wildcard * for some platforms

Body:
Here is what I am trying to do: Get all people with the same boss and email the boss. I can only use the table below and I would like to add another column showing the boss email which is found in the table.

id      name       email            boss
-------------------------------------------
1       Apple      Apple@alo.com    Rita
2       Bob        Bob@alo.com      Rita
3       Charlie    Charlie@alo.com  Nuna
4       Dan        Dan@alo.com      Rita
5       Rita       Rita@alo.com     Sheeba
6       Nuna       Nuna@alo.com     Sheeba

Thanks for any help.

Body:
You use a join to do that.  It looks like the code below.  When joining to the same table you have to use an alias.

SELECT base.name, boss.email as boss_email
from the_table_name_you_did_not_say as base
join the_table_name_you_did_not_say as boss on base.boss = boss.name

Technically you don't have to use an alias on the base table if you select a wildcard * for some platforms


问:
What are types of Load Balancers involved in the Snowflake Multi-AZ architecture hosted on AWS
reading through the page on our community detailing about the multi-az snowflake architecture -

https://support.snowflake.net/s/article/snowflake-delivers-high-availability-by-using-aws-availability-zones

there is a mention on Load balancers.

my question is what type of load balancer is that - network, application or combination of both.

答:
The Snowflake uses load balancer service provided by the hosting Cloud Service. For example, on AWS, Snowflake uses ELB (elastic load balancer):

https://support.snowflake.net/s/article/faq-what-ip-address-range-does-snowflake-use


问:
How to Hide part of URL?
Is there a way to hide part of the URL?

For example instead of https://progx.firebaseio.com/progx1.json

to show only https://progx/progx1.json

I am using this link in IFTTT's webhook to connect it with firebase and I don't want to expose/share the complete URL with others.

Any help will be appreciated! Thanks in advance!

答:
There is no way to set a custom URL for your Firebase Realtime Database. See Use custom domain name as firebase database/auth/storage URL and Firebase custom domain name for database

If you want to simplify the URL, you will have to set up your own server on a custom/simpler domain. So your IFTTT then writes to that server, which in turn writes to Firebase.

Title: How to Hide part of URL?


问:
How to create tabs inside a tab in ionic 3
I am trying to create three tabs inside a tab in ionic 3 but, i can't get it working.

Here is an example of what i trying to do, but it seems to have been achieved with an earlier version of ionic. i am using ionic 3.10.3

ionic -v from the CLI prints 3.10.3

Here are some information from my project.

I have a main page with three tabs (Home, Message, Setting) and i want to create three other tabs(All, Read, Unread) inside the Message tab content.

Here are the content of my projet

main

```<code>/src/pages/main/main.ts
</code>```

import { Component } from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';

import { HomePage } from '../home/home';
import { SettingPage } from '../setting/setting';
import { MessagePage } from '../message/message';

@Component({
 selector: 'page-main',
 templateUrl: 'main.html'

})

export class MainPage {
 tabHomeRoot : HomePage;
 tabSettingRoot: SettingPage;
 tabMessageRoot: MessagePage;

 constructor(){

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

```/src/pages/main/main.html
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ion-tabs>
  <ion-tab [root]="tabHomeRoot" tabTitle="Home"></ion-tab>
  <ion-tab [root]="tabMessageRoot" tabTitle="Message" tabIcon="information-circle"></ion-tab>
  <ion-tab [root]="tabSettingRoot" tabTitle="Setting" tabIcon="gear"></ion-tab>
 </ion-tabs></code>```

The content of the other tabs are basic, so i am only going to put the content of The message tab

message

```<code>/src/pages/message/message.ts
</code>```

import { Component } from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';

import { AllMessagePage } from '../all-message/all-message';
import { ReadMessagePage } from '../read-message/read-message';
import { UnreadMessagePage } from '../unread-messag/unread-message';

@Component({
 selector: 'page-message',
 templateUrl: 'message.html'

})

export class MessagePage {
 tabAllMessageRoot : AllMessagePage;
 tabUnreadMessageRoot: UnreadMessagePage;
 tabReadMessageRoot: ReadMessagePage;

 constructor(){

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

```/src/pages/message/message.html
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ion-content>

 <ion-tabs>
  <ion-tab [root]="tabAllMessageRoot" tabTitle="All"></ion-tab>
  <ion-tab [root]="tabUnreadMessageRoot" tabTitle="Unread" tabIcon="information-circle"></ion-tab>
  <ion-tab [root]="tabReadMessageRoot" tabTitle="Read" tabIcon="contacts"></ion-tab>
 </ion-tabs>

</ion-content></code>```

Any help will be appreciate, Thanks

答:
This question shows up as #3 on Google search when searching for "ionic 3 tabs example". Since there is no answer, I can't imagine how much time it has wasted people coming here hoping for an example.

I've wasted hours because I took some what I assume was ok looking code from you original question. It probably doesn't matter to you now but for whomever Google sends here, one of the major problem was:

You need add “=” sign instead of “:” ,

```<code>export class MessagePage {
tabAllMessageRoot : AllMessagePage;
tabUnreadMessageRoot: UnreadMessagePage;
tabReadMessageRoot: ReadMessagePage;
</code>```

should be

```<code>export class MessagePage {
tabAllMessageRoot = AllMessagePage;
tabUnreadMessageRoot = UnreadMessagePage;
tabReadMessageRoot = ReadMessagePage;
</code>```

I've wasted hours of my time, hopefully this helps someone else.

Lesson learned about taking code from unanswered questions!

Body:
I am trying to create three tabs inside a tab in ionic 3 but, i can't get it working.

Here is an example of what i trying to do, but it seems to have been achieved with an earlier version of ionic. i am using ionic 3.10.3

ionic -v from the CLI prints 3.10.3

Here are some information from my project.

I have a main page with three tabs (Home, Message, Setting) and i want to create three other tabs(All, Read, Unread) inside the Message tab content.

Here are the content of my projet

main

/src/pages/main/main.ts

import { Component } from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';

import { HomePage } from '../home/home';
import { SettingPage } from '../setting/setting';
import { MessagePage } from '../message/message';

@Component({
 selector: 'page-main',
 templateUrl: 'main.html'

})

export class MainPage {
 tabHomeRoot : HomePage;
 tabSettingRoot: SettingPage;
 tabMessageRoot: MessagePage;

 constructor(){

 }
}

/src/pages/main/main.html

 <ion-tabs>
  <ion-tab [root]="tabHomeRoot" tabTitle="Home"></ion-tab>
  <ion-tab [root]="tabMessageRoot" tabTitle="Message" tabIcon="information-circle"></ion-tab>
  <ion-tab [root]="tabSettingRoot" tabTitle="Setting" tabIcon="gear"></ion-tab>
 </ion-tabs>

The content of the other tabs are basic, so i am only going to put the content of The message tab

message

/src/pages/message/message.ts

import { Component } from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';

import { AllMessagePage } from '../all-message/all-message';
import { ReadMessagePage } from '../read-message/read-message';
import { UnreadMessagePage } from '../unread-messag/unread-message';

@Component({
 selector: 'page-message',
 templateUrl: 'message.html'

})

export class MessagePage {
 tabAllMessageRoot : AllMessagePage;
 tabUnreadMessageRoot: UnreadMessagePage;
 tabReadMessageRoot: ReadMessagePage;

 constructor(){

 }
}

/src/pages/message/message.html

<ion-content>

 <ion-tabs>
  <ion-tab [root]="tabAllMessageRoot" tabTitle="All"></ion-tab>
  <ion-tab [root]="tabUnreadMessageRoot" tabTitle="Unread" tabIcon="information-circle"></ion-tab>
  <ion-tab [root]="tabReadMessageRoot" tabTitle="Read" tabIcon="contacts"></ion-tab>
 </ion-tabs>

</ion-content>

Any help will be appreciate, Thanks

Body:
This question shows up as #3 on Google search when searching for "ionic 3 tabs example". Since there is no answer, I can't imagine how much time it has wasted people coming here hoping for an example.

I've wasted hours because I took some what I assume was ok looking code from you original question. It probably doesn't matter to you now but for whomever Google sends here, one of the major problem was:

You need add “=” sign instead of “:” ,

export class MessagePage {
tabAllMessageRoot : AllMessagePage;
tabUnreadMessageRoot: UnreadMessagePage;
tabReadMessageRoot: ReadMessagePage;

should be

export class MessagePage {
tabAllMessageRoot = AllMessagePage;
tabUnreadMessageRoot = UnreadMessagePage;
tabReadMessageRoot = ReadMessagePage;

I've wasted hours of my time, hopefully this helps someone else.

Lesson learned about taking code from unanswered questions!


问:
Using javascript variables from another function

Possible Duplicate:

  How to know variables from different…“namespaces” ?

I have a webphone integrated into our webpage, and when a call comes in, a javascript function records the caller's number (e.g. 01234 123456) and saves it as the variable inCallingNum.

I need to use this variable in a different function which sends information to a php page and stores it on our database.

Is it possible to access the javascript variable from another function at all, and if not what is the easiest way to get around it?

Edit: This is the code I have, which currently captures the inCallingNum variable

```<code>    function webphonetojs(varr)
        {
            var eventNotify = '' + varr;
            //alert("eventNotify = "+eventNotify);
            displaystatus('WEBPHONE SAY: '+eventNotify);

            initcheck();
            var chanelStat = applethandle.API_GetStatus(1); //  get line status
            var chanelStatus = chanelStat.replace(/\s+/g,'');
            if (chanelStatus == 'Ringing')
            {
                var incomming = eventNotify.slice(eventNotify.lastIndexOf(",")+1, eventNotify.length);
                if (incomming == '2')
                {
                    var inCallingNum = eventNotify.split(",", 4); inCallingNum = inCallingNum.toString();
                    inCallingNum = inCallingNum.slice(inCallingNum.lastIndexOf(",")+1, inCallingNum.length);
                    displaystatus('CALLER IS: '+inCallingNum);

}
}
}
</code>```

答:
This depends on the scope of the variable inCallingNum.

If it has public scope then you could be able to access it in another function.

If it has private scope then you need to either change it to public (or global) or add getter method to it.

Body:
Possible Duplicate:

  How to know variables from different…“namespaces” ?

I have a webphone integrated into our webpage, and when a call comes in, a javascript function records the caller's number (e.g. 01234 123456) and saves it as the variable inCallingNum.

I need to use this variable in a different function which sends information to a php page and stores it on our database.

Is it possible to access the javascript variable from another function at all, and if not what is the easiest way to get around it?

Edit: This is the code I have, which currently captures the inCallingNum variable

    function webphonetojs(varr)
        {
            var eventNotify = '' + varr;
            //alert("eventNotify = "+eventNotify);
            displaystatus('WEBPHONE SAY: '+eventNotify);

            initcheck();
            var chanelStat = applethandle.API_GetStatus(1); //  get line status
            var chanelStatus = chanelStat.replace(/\s+/g,'');
            if (chanelStatus == 'Ringing')
            {
                var incomming = eventNotify.slice(eventNotify.lastIndexOf(",")+1, eventNotify.length);
                if (incomming == '2')
                {
                    var inCallingNum = eventNotify.split(",", 4); inCallingNum = inCallingNum.toString();
                    inCallingNum = inCallingNum.slice(inCallingNum.lastIndexOf(",")+1, inCallingNum.length);
                    displaystatus('CALLER IS: '+inCallingNum);

}
}
}


问:
ASP.NET Core: Custom authentication and authorization
Let's consider that I already have a package that returns UserIdentity based on HttpRequest. I want to create an ASP.NET Core project that uses my package in order to get ClaimIdentity object. How it could be done?

答:
I think you can tell Asp.NET Core to use your custom Identity by applying it on the services middleware registration. Something like

```<code>services.AddDefaultIdentity<MyIdentityClass>()
</code>```

Supposing that MyIdentityClass extends the IdentityUser class.
You can find more informations about how to customize the Identity [https://learn.microsoft.com/it-it/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-3.1](here in the Asp.NET Core documentation)

Body:
I think you can tell Asp.NET Core to use your custom Identity by applying it on the services middleware registration. Something like

services.AddDefaultIdentity<MyIdentityClass>()

Supposing that MyIdentityClass extends the IdentityUser class.
You can find more informations about how to customize the Identity [https://learn.microsoft.com/it-it/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-3.1](here in the Asp.NET Core documentation)


问:
I want one character at a time on html page. After completion load next one
I am developing a javascript app.
I have stuck to implementing this.
I am able to load all characters but I want to implement :- load one characters after on completion load next characters.
One characters at a time.

I want to load one character. After completion load next then again after completion next but one character at a time.
 https://hanziwriter.org/docs.html

var chars = new Array('我','很','爱');

console.log(chars);

for(i=0; i< chars.length; i++){
     console.log(chars[i]);
    writeFunction(chars[i])
}

//c = '我';

function writeFunction(c){

    var writer = HanziWriter.create('character-target-div' , c , {
        width: 150,
        height: 150,
        showCharacter: false,
        padding: 5
      });
      writer.quiz({
        onMistake: function(strokeData) {
          console.log('Oh no! you made a mistake on stroke ' + strokeData.strokeNum);
          console.log("You've made " + strokeData.mistakesOnStroke + " mistakes on this stroke so far");
          console.log("You've made " + strokeData.totalMistakes + " total mistakes on this quiz");
          console.log("There are " + strokeData.strokesRemaining + " strokes remaining in this character");
        },
        onCorrectStroke: function(strokeData) {
          console.log('Yes!!! You got stroke ' + strokeData.strokeNum + ' correct!');
          console.log('You made ' + strokeData.mistakesOnStroke + ' mistakes on this stroke');
          console.log("You've made " + strokeData.totalMistakes + ' total mistakes on this quiz');
          console.log('There are ' + strokeData.strokesRemaining + ' strokes remaining in this character');
        },
        onComplete: function(summaryData) {
          console.log('You did it! You finished drawing ' + summaryData.character);
          console.log('You made ' + summaryData.totalMistakes + ' total mistakes on this quiz');

          flagComplete = true;

        }
      });

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/hanzi-writer@2.2/dist/hanzi-writer.min.js"></script>

<div id="character-target-div"></div></code>```

答:
So you want to only continue your loop when the user has completed the character. That means your loop must become asynchronous.

JavaScript offers async and await for that purpose. The only requirement is that you provide a promise that resolves when the character is completed.

Here is how it could work (untested):

```<code>(async function() { // <-- add this wrapper
    var chars = new Array('我','很','爱');

    console.log(chars);

    for(i=0; i< chars.length; i++){
         console.log(chars[i]);

        await writeFunction(chars[i]);
    //  ^^^^^
    }
})(); // execute immediately

//c = '我';

// Make the function async, so it returns a promise
async function writeFunction(c) {
    // Wrap the code inside a Promise constructor callback:
    return new Promise(function (resolve, reject) {
        var writer = HanziWriter.create('character-target-div' , c , {
            width: 150,
            height: 150,
            showCharacter: false,
            padding: 5
        });
        writer.quiz({
            onMistake: function(strokeData) {
                console.log('Oh no! you made a mistake on stroke ' + strokeData.strokeNum);
                console.log("You've made " + strokeData.mistakesOnStroke + " mistakes on this stroke so far");
                console.log("You've made " + strokeData.totalMistakes + " total mistakes on this quiz");
                console.log("There are " + strokeData.strokesRemaining + " strokes remaining in this character");
            },
            onCorrectStroke: function(strokeData) {
                console.log('Yes!!! You got stroke ' + strokeData.strokeNum + ' correct!');
                console.log('You made ' + strokeData.mistakesOnStroke + ' mistakes on this stroke');
                console.log("You've made " + strokeData.totalMistakes + ' total mistakes on this quiz');
                console.log('There are ' + strokeData.strokesRemaining + ' strokes remaining in this character');
            },
            onComplete: function(summaryData) {
                console.log('You did it! You finished drawing ' + summaryData.character);
                console.log('You made ' + summaryData.totalMistakes + ' total mistakes on this quiz');
              // call resolve: that does the magic!
                resolve();
            }
        });
    });
}
</code>```

Body:
So you want to only continue your loop when the user has completed the character. That means your loop must become asynchronous.

JavaScript offers async and await for that purpose. The only requirement is that you provide a promise that resolves when the character is completed.

Here is how it could work (untested):

(async function() { // <-- add this wrapper
    var chars = new Array('我','很','爱');

    console.log(chars);

    for(i=0; i< chars.length; i++){
         console.log(chars[i]);

        await writeFunction(chars[i]);
    //  ^^^^^
    }
})(); // execute immediately

//c = '我';

// Make the function async, so it returns a promise
async function writeFunction(c) {
    // Wrap the code inside a Promise constructor callback:
    return new Promise(function (resolve, reject) {
        var writer = HanziWriter.create('character-target-div' , c , {
            width: 150,
            height: 150,
            showCharacter: false,
            padding: 5
        });
        writer.quiz({
            onMistake: function(strokeData) {
                console.log('Oh no! you made a mistake on stroke ' + strokeData.strokeNum);
                console.log("You've made " + strokeData.mistakesOnStroke + " mistakes on this stroke so far");
                console.log("You've made " + strokeData.totalMistakes + " total mistakes on this quiz");
                console.log("There are " + strokeData.strokesRemaining + " strokes remaining in this character");
            },
            onCorrectStroke: function(strokeData) {
                console.log('Yes!!! You got stroke ' + strokeData.strokeNum + ' correct!');
                console.log('You made ' + strokeData.mistakesOnStroke + ' mistakes on this stroke');
                console.log("You've made " + strokeData.totalMistakes + ' total mistakes on this quiz');
                console.log('There are ' + strokeData.strokesRemaining + ' strokes remaining in this character');
            },
            onComplete: function(summaryData) {
                console.log('You did it! You finished drawing ' + summaryData.character);
                console.log('You made ' + summaryData.totalMistakes + ' total mistakes on this quiz');
              // call resolve: that does the magic!
                resolve();
            }
        });
    });
}


问:
How can I count the number of results from another count clause?
I am new to mysql and I am trying to work out the following mysql query in MAMP.

How many departments have more than 5 employees?

```<code>SELECT DEPid, COUNT(employeeID) AS Employees
FROM dep2emp
GROUP BY DEPid
HAVING Employees > 5;
</code>```

Giving

```<code>+---------+---------------+
| DEPid   |  Employees
+---------+---------------+
| 1753348 |             7 |
| 1757423 |             6 |
| 1894619 |             7 |
| 1895159 |             7 |
| 1930793 |            11 |
| 1930810 |             8 |
| 2261598 |             7 |
| 2357543 |             6 |
+---------+---------------+`
</code>```

I cannot count the number of results from the other count statement. This is what I've come up with so far and I have tried to use the count clause on the DEPid attribute but it gives me a completely wrong answer of 4141 the answer I am trying to achieve is 8, the number of rows in the result

答:
Count(employeeID) return the number of rows where the value of employeeID is not null so

Could be you need  just the count of distinct employeeID

```<code>SELECT DEPid, COUNT(distinct employeeID) AS Employees
FROM dep2emp
GROUP BY DEPid
HAVING  COUNT(distinct employeeID) > 5;
</code>```

count(distinct colname) return the number of distinct value for your colname

Body:
I am new to mysql and I am trying to work out the following mysql query in MAMP.

How many departments have more than 5 employees?

SELECT DEPid, COUNT(employeeID) AS Employees
FROM dep2emp
GROUP BY DEPid
HAVING Employees > 5;

Giving

+---------+---------------+
| DEPid   |  Employees
+---------+---------------+
| 1753348 |             7 |
| 1757423 |             6 |
| 1894619 |             7 |
| 1895159 |             7 |
| 1930793 |            11 |
| 1930810 |             8 |
| 2261598 |             7 |
| 2357543 |             6 |
+---------+---------------+`

I cannot count the number of results from the other count statement. This is what I've come up with so far and I have tried to use the count clause on the DEPid attribute but it gives me a completely wrong answer of 4141 the answer I am trying to achieve is 8, the number of rows in the result

Body:
Count(employeeID) return the number of rows where the value of employeeID is not null so

Could be you need  just the count of distinct employeeID

SELECT DEPid, COUNT(distinct employeeID) AS Employees
FROM dep2emp
GROUP BY DEPid
HAVING  COUNT(distinct employeeID) > 5;

count(distinct colname) return the number of distinct value for your colname


问:
call method with parameter of type class and check class type
I have the following classes:

```<code>class Permission {
  name: string;
}

class EditBasketPermission extends Permission {
  basketId: number;
}

class EditProductPermission extends Permission {
  basketId: number;
  projectId: number;
}
</code>```

Then I have a method that authorizes, or not, the permission:

```<code>authorize(permission: Permission) : boolean {

  // 1 - Check the permission type
  // 2 - Authorize the request based on the permission data

}
</code>```

How to check the permission type so I can decide how to evaluate it?

And in my HTML I have the following:

```<code><button *ngIf="authorize(???)">Edit</button>
</code>```

How to pass an EditProductPermission when calling the method authorised?

The problem is that permission type has different types of inputs.

答:
There are a few ways you can go about this.

You can use JavaScript's instanceof operator to detect the type of object you're given.

You can add a permissionType property (maybe a string or an enum?) and expect each extending class to return some corresponding value for you to switch on.

If the shape of each permission type is enough to tell you which kind it is, you could check for things like the presence of a basketId and projectId to deduce which type you're looking at.

Typescript has type guards which can be based on instanceof or your own custom logic, allowing you to have variables be strongly typed once you've determined that they're of a given type.

Finally, depending on your architecture, it may be worth considering taking an object-oriented approach by associating the authorize logic with the Permission class itself, so instead of calling authorize(permission) you would call permission.authorize().

Body:
I have the following classes:

class Permission {
  name: string;
}

class EditBasketPermission extends Permission {
  basketId: number;
}

class EditProductPermission extends Permission {
  basketId: number;
  projectId: number;
}

Then I have a method that authorizes, or not, the permission:

authorize(permission: Permission) : boolean {

  // 1 - Check the permission type
  // 2 - Authorize the request based on the permission data

}

How to check the permission type so I can decide how to evaluate it?

And in my HTML I have the following:

<button *ngIf="authorize(???)">Edit</button>

How to pass an EditProductPermission when calling the method authorised?

The problem is that permission type has different types of inputs.


问:
Kafka console Consume Command not accepting bootstrap-servers
I have installed Kafka on my windows machine. My Kafka version is kafka_2.12-2.4.0.
I have started the Zookeeper server, then Kafka server then creates the topic and then produces the message to created Topic. Till here everything is fine.
But when I run the Consume command, it is giving me below error.

'--bootstrap-servers' is not recognized as an internal or external
  command, operable program or batch file.

I am using the below command.

```<code>.\bin\windows\kafka-console-consumer.bat --bootstrap-servers localhost:9092 --topic TEST_TOPIC --from-beginning
</code>```

Please suggest me what could be the problem.

答:
I resolved the issue on my side. The issue was that in the command prompt, for some reason, I had a double arrow >>:

C:\kafka_2.13-2.4.0>> .\bin\windows\kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic myTopic
'--bootstrap-server' is not recognized as an internal or external command,
operable program or batch file.

Once I removed the double arrow, the error went away. Now I appear to have other issues where Kafka is not running on the port I thought it was, but that is a separate issue.

Body:
I have installed Kafka on my windows machine. My Kafka version is kafka_2.12-2.4.0.
I have started the Zookeeper server, then Kafka server then creates the topic and then produces the message to created Topic. Till here everything is fine.
But when I run the Consume command, it is giving me below error.

'--bootstrap-servers' is not recognized as an internal or external
  command, operable program or batch file.

I am using the below command.

.\bin\windows\kafka-console-consumer.bat --bootstrap-servers localhost:9092 --topic TEST_TOPIC --from-beginning

Please suggest me what could be the problem.