问:
Value of a state variable different in a different function
I'm confused how scope works in React.

I want to pass a value of a state to another state but what I'm finding is that in one function it prints the right value and in another it does not.

It's a countdown where a timer counts down and counts clicks, and at the very end, I want to get the total amount of clicks and send it to a state of total. So the states are:

```<code>  const [strokeScore, setStrokeScore] = useState(1);

  const [totalStrokeScore, setTotalStrokeScore] = useState(1);

  const [strokeCountdown, setStrokeCountdown] = useState();
</code>```

With strokeScore being the clicks of the game - and I want to get that total and shoot it over to total stroke score.

For some reason I can't do that - what is going on here?

```<code>import React, { useEffect, useState } from 'react';

function ScoreCard() {

  const [strokeScore, setStrokeScore] = useState(1);

  const [totalStrokeScore, setTotalStrokeScore] = useState(1);

  const [strokeCountdown, setStrokeCountdown] = useState();

  const strokeCountdownDing = new Audio('/sounds/round-complete.mp3');

  const endOfGameRound = () => {
    strokeCountdownDing.play();
    document.getElementById('stroke-counter-button').disabled = true;
  }

  const addToStrokeScore = () => {
    setStrokeScore(strokeScore + 1);
    // prints the correct number
    console.log(strokeScore)
    if (strokeCountdown === 0) {
        endOfGameRound()
    }
  }

  const subtractStrokeScore = () => {
    setStrokeScore(strokeScore - 1);
  }

  const countDown = () => {
    // let strokeCountdown = Math.floor(Math.random() * 31) + 100;
    let strokeCountdown = 10
    let strokeCountdownSpeedOptions = [1000, 500, 300, 200];
    let strokeCountDownSpeed = strokeCountdownSpeedOptions[Math.floor(Math.random()*strokeCountdownSpeedOptions.length)];
    let strokeCounter = setInterval(() => {
        strokeCountdown--
        // this is always giving me...1...?
        console.log('the score is: ' + strokeScore)
        setStrokeCountdown(strokeCountdown)
        if (strokeCountdown === 0) {
            endOfGameRound()
            clearInterval(strokeCounter)
            setTotalStrokeScore(strokeScore);
        }
    }, strokeCountDownSpeed)
  }

  useEffect(() => {
    countDown();
  }, []);

  return (
    <div className="gane__score-card">
      <div className="gane__speed-level">
          Speed: idk
      </div>
      <div className="gane__stroke-countdown">
          Countdown: {strokeCountdown}
      </div>
      <p>Score: {strokeScore}</p>
      <button id="stroke-counter-button" onClick={addToStrokeScore}>
          {strokeCountdown === 0 ? 'Game Over' : 'Stroke'}
      </button>
      {/* window.location just temp for now */}
      {strokeCountdown === 0
        ? <button onClick={() => window.location.reload(false)}>Play Again</button>
        : <button disabled>Game in Progress</button>
      }
      <div className="gane__total-score">
          Total score: {totalStrokeScore}
      </div>
    </div>
  );
}

export default ScoreCard;
</code>```

If you look at the sample above, I comment where it gives the correct number and where it seems to be stuck at "1" - why is this?

I tried as a different variable too.

```<code>import React, { useEffect, useState } from 'react';

function ScoreCard() {

  const [strokeScore, setStrokeScore] = useState(1);

  const [totalStrokeScore, setTotalStrokeScore] = useState(1);

  const [strokeCountdown, setStrokeCountdown] = useState();

  const strokeCountdownDing = new Audio('/sounds/round-complete.mp3');

  // make new variable, maybe?
  let strokeScoreCount = 0;

  const endOfGameRound = () => {
    strokeCountdownDing.play();
    document.getElementById('stroke-counter-button').disabled = true;
  }

  const addToStrokeScore = () => {
    setStrokeScore(strokeScore + 1);
    // prints the correct number
    console.log(strokeScore)
    // but this just gives me zero?
    strokeScoreCount = strokeScoreCount + 1;
    console.log('maybe do a different var? : ' + strokeScoreCount)
    if (strokeCountdown === 0) {
        endOfGameRound()
    }
  }

  const subtractStrokeScore = () => {
    setStrokeScore(strokeScore - 1);
  }

  const countDown = () => {
    // let strokeCountdown = Math.floor(Math.random() * 31) + 100;
    let strokeCountdown = 10
    let strokeCountdownSpeedOptions = [1000, 500, 300, 200];
    let strokeCountDownSpeed = strokeCountdownSpeedOptions[Math.floor(Math.random()*strokeCountdownSpeedOptions.length)];
    let strokeCounter = setInterval(() => {
        strokeCountdown--
        // this is always giving me...1...?
        console.log('the score is: ' + strokeScore)
        // this just gives me zero all the time? why?
        console.log('the new variable to use is: ' + strokeScoreCount)
        setStrokeCountdown(strokeCountdown)
        if (strokeCountdown === 0) {
            endOfGameRound()
            clearInterval(strokeCounter)
            setTotalStrokeScore(strokeScore);
        }
    }, strokeCountDownSpeed)
  }

  useEffect(() => {
    countDown();
  }, []);

  return (
    <div className="game__score-card">
      <div className="game__speed-level">
          Speed: idk
      </div>
      <div className="game__stroke-countdown">
          Countdown: {strokeCountdown}
      </div>
      <p>Score: {strokeScore}</p>
      <button id="stroke-counter-button" onClick={addToStrokeScore}>
          {strokeCountdown === 0 ? 'Game Over' : 'Stroke'}
      </button>
      {/* window.location just temp for now */}
      {strokeCountdown === 0
        ? <button onClick={() => window.location.reload(false)}>Play Again</button>
        : <button disabled>Game in Progress</button>
      }
      <div className="game__total-score">
          Total score: {totalStrokeScore}
      </div>
    </div>
  );
}

export default ScoreCard;
</code>```

Using a new variable just gives me zero all the time, and strokeScore is just permanently stuck at one in that function. But it's a state, can't you get state anywhere?

How do take value from one state, ensure it's correct in all scopes, and pass it to another state?

Note: the answer below explains state and scope but code breaks the setInterval. That question is here: useState with an argument in it's array is breaking a setInterval and makes it glitchy and erratic

答:
If you do setState(somevalue); console.log(state), the state will show the old value instead of the new one because it is yet updated.

if you do the following, strokeScore will reflect old value because it's yet updated.

```<code>    setStrokeScore(strokeScore + 1);
    console.log(strokeScore)
</code>```

You can see the updated score in a useEffect call. Try to do the following then you know what i am talking about.

```<code>  useEffect(() => {
          console.log('Score in useeffect', strokeScore);
  }, [strokeScore])

  const addToStrokeScore = () => {
         setStrokeScore(strokeScore + 1);
         console.log('Score in function', strokeScore);
  }
</code>```

In addition, if your new value is dependent on old value, the correct way to set state is

```<code>         setStrokeScore( prev => prev + 1);
</code>```

So the final codes should be similar to the following

```<code> useEffect(() => {
          console.log('Score in useeffect', strokeScore); //shows new value
  }, [strokeScore])

  const addToStrokeScore = () => {
         setStrokeScore(prev => prev + 1);
         console.log('Score in function', strokeScore); //shows old value
  }
</code>```

Or even better, to take things one set step up.

```<code>  const addToStrokeScore = () => {
         const newScore = strokeScore + 1;
         // do whatever you need with the new score, then update state when done.
         setStrokeScore(newScore);
         console.log('Score in function', newScore);
   }
</code>```

Body:
I'm confused how scope works in React.

I want to pass a value of a state to another state but what I'm finding is that in one function it prints the right value and in another it does not.

It's a countdown where a timer counts down and counts clicks, and at the very end, I want to get the total amount of clicks and send it to a state of total. So the states are:

  const [strokeScore, setStrokeScore] = useState(1);

  const [totalStrokeScore, setTotalStrokeScore] = useState(1);

  const [strokeCountdown, setStrokeCountdown] = useState();

With strokeScore being the clicks of the game - and I want to get that total and shoot it over to total stroke score.

For some reason I can't do that - what is going on here?

import React, { useEffect, useState } from 'react';

function ScoreCard() {

  const [strokeScore, setStrokeScore] = useState(1);

  const [totalStrokeScore, setTotalStrokeScore] = useState(1);

  const [strokeCountdown, setStrokeCountdown] = useState();

  const strokeCountdownDing = new Audio('/sounds/round-complete.mp3');

  const endOfGameRound = () => {
    strokeCountdownDing.play();
    document.getElementById('stroke-counter-button').disabled = true;
  }

  const addToStrokeScore = () => {
    setStrokeScore(strokeScore + 1);
    // prints the correct number
    console.log(strokeScore)
    if (strokeCountdown === 0) {
        endOfGameRound()
    }
  }

  const subtractStrokeScore = () => {
    setStrokeScore(strokeScore - 1);
  }

  const countDown = () => {
    // let strokeCountdown = Math.floor(Math.random() * 31) + 100;
    let strokeCountdown = 10
    let strokeCountdownSpeedOptions = [1000, 500, 300, 200];
    let strokeCountDownSpeed = strokeCountdownSpeedOptions[Math.floor(Math.random()*strokeCountdownSpeedOptions.length)];
    let strokeCounter = setInterval(() => {
        strokeCountdown--
        // this is always giving me...1...?
        console.log('the score is: ' + strokeScore)
        setStrokeCountdown(strokeCountdown)
        if (strokeCountdown === 0) {
            endOfGameRound()
            clearInterval(strokeCounter)
            setTotalStrokeScore(strokeScore);
        }
    }, strokeCountDownSpeed)
  }

  useEffect(() => {
    countDown();
  }, []);

  return (

          Speed: idk

          Countdown: {strokeCountdown}

Score: {strokeScore}

      <button id="stroke-counter-button" onClick={addToStrokeScore}>
          {strokeCountdown === 0 ? 'Game Over' : 'Stroke'}
      </button>
      {/* window.location just temp for now */}
      {strokeCountdown === 0
        ? <button onClick={() => window.location.reload(false)}>Play Again</button>
        : <button disabled>Game in Progress</button>
      }

          Total score: {totalStrokeScore}

  );
}

export default ScoreCard;

If you look at the sample above, I comment where it gives the correct number and where it seems to be stuck at "1" - why is this?

I tried as a different variable too.

import React, { useEffect, useState } from 'react';

function ScoreCard() {

  const [strokeScore, setStrokeScore] = useState(1);

  const [totalStrokeScore, setTotalStrokeScore] = useState(1);

  const [strokeCountdown, setStrokeCountdown] = useState();

  const strokeCountdownDing = new Audio('/sounds/round-complete.mp3');

  // make new variable, maybe?
  let strokeScoreCount = 0;

  const endOfGameRound = () => {
    strokeCountdownDing.play();
    document.getElementById('stroke-counter-button').disabled = true;
  }

  const addToStrokeScore = () => {
    setStrokeScore(strokeScore + 1);
    // prints the correct number
    console.log(strokeScore)
    // but this just gives me zero?
    strokeScoreCount = strokeScoreCount + 1;
    console.log('maybe do a different var? : ' + strokeScoreCount)
    if (strokeCountdown === 0) {
        endOfGameRound()
    }
  }

  const subtractStrokeScore = () => {
    setStrokeScore(strokeScore - 1);
  }

  const countDown = () => {
    // let strokeCountdown = Math.floor(Math.random() * 31) + 100;
    let strokeCountdown = 10
    let strokeCountdownSpeedOptions = [1000, 500, 300, 200];
    let strokeCountDownSpeed = strokeCountdownSpeedOptions[Math.floor(Math.random()*strokeCountdownSpeedOptions.length)];
    let strokeCounter = setInterval(() => {
        strokeCountdown--
        // this is always giving me...1...?
        console.log('the score is: ' + strokeScore)
        // this just gives me zero all the time? why?
        console.log('the new variable to use is: ' + strokeScoreCount)
        setStrokeCountdown(strokeCountdown)
        if (strokeCountdown === 0) {
            endOfGameRound()
            clearInterval(strokeCounter)
            setTotalStrokeScore(strokeScore);
        }
    }, strokeCountDownSpeed)
  }

  useEffect(() => {
    countDown();
  }, []);

  return (

          Speed: idk

          Countdown: {strokeCountdown}

Score: {strokeScore}

      <button id="stroke-counter-button" onClick={addToStrokeScore}>
          {strokeCountdown === 0 ? 'Game Over' : 'Stroke'}
      </button>
      {/* window.location just temp for now */}
      {strokeCountdown === 0
        ? <button onClick={() => window.location.reload(false)}>Play Again</button>
        : <button disabled>Game in Progress</button>
      }

          Total score: {totalStrokeScore}

  );
}

export default ScoreCard;

Using a new variable just gives me zero all the time, and strokeScore is just permanently stuck at one in that function. But it's a state, can't you get state anywhere?

How do take value from one state, ensure it's correct in all scopes, and pass it to another state?

Note: the answer below explains state and scope but code breaks the setInterval. That question is here: useState with an argument in it's array is breaking a setInterval and makes it glitchy and erratic

Body:
If you do setState(somevalue); console.log(state), the state will show the old value instead of the new one because it is yet updated.

if you do the following, strokeScore will reflect old value because it's yet updated.

    setStrokeScore(strokeScore + 1);
    console.log(strokeScore)

You can see the updated score in a useEffect call. Try to do the following then you know what i am talking about.

  useEffect(() => {
          console.log('Score in useeffect', strokeScore);
  }, [strokeScore])

  const addToStrokeScore = () => {
         setStrokeScore(strokeScore + 1);
         console.log('Score in function', strokeScore);
  }

In addition, if your new value is dependent on old value, the correct way to set state is

         setStrokeScore( prev => prev + 1);

So the final codes should be similar to the following

 useEffect(() => {
          console.log('Score in useeffect', strokeScore); //shows new value
  }, [strokeScore])

  const addToStrokeScore = () => {
         setStrokeScore(prev => prev + 1);
         console.log('Score in function', strokeScore); //shows old value
  }

Or even better, to take things one set step up.

  const addToStrokeScore = () => {
         const newScore = strokeScore + 1;
         // do whatever you need with the new score, then update state when done.
         setStrokeScore(newScore);
         console.log('Score in function', newScore);
   }


来源: stackexchange

问:
Angular/RxJs - Calling next() on Observable in service after component was unsubscribe() cause ObjectUnsubscribedError
I have an Angular Service that defines a public Subject. Later under some condition, the service will call .next() on this Subject.

In addition, I have an Angular component that .subscribe() to this Subject in it's ngOnInit() method, and call .unsubscribe() in it's ngOnDestroy() method.

While both the service and the component are alive my code works fine. However, the user can click on a different tab in my app. Which cause my component to unload and call its ngOnDestroy() method, meaning the Observable was unsubscribed.

Starting from this point, the component no longer exists however the service is still alive - other components still use it. When the service calling .next() method after the component called .unsubscribe(), this error is thrown ObjectUnsubscribedError.
ERROR Error: Uncaught (in promise): ObjectUnsubscribedError: object unsubscribed

In addition, later if the user goes back to the tab that contains the component, the ngOnInit() is executed and the re-subscription to this observable throws the same error again.

What am I doing wrong, how can I resolve these errors?

```<code>import { Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class StatusService {
  public statusChange$: Subject<number>;

  public constructor(...) {
    this.statusChange$ = new Subject<number>();
  }

  public someInternalLogic(someNumber: number): void {
    this.statusChange$.next(someNumber);
    // this will throw an error if StatusComponent call .unsubscribe()
  }
}

@Component({
  selector: 'app-status',
  templateUrl: './status.component.html',
  styleUrls: ['./status.component.scss']
})
export class StatusComponent implements OnInit, OnDestroy {
  public constructor(
    private _statusService: StatusService) {}

    public ngOnInit(): void {
      this._statusService.statusChange$.subscribe(value => this._onStatusChange(value));
  }

  public ngOnDestroy(): void {
    this._statusService.statusChange$.unsubscribe();
    // after this point if the StatusService calling .next() an error will be thrown
  }

  private _onStatusChange(value: number): void {
    // ....
  }
}

</code>```

答:
Another way to collectively unsubscribe on the OnDestroy event is the usage of the takeUntil operator. So you don't have to store each of your subscriptions, instead you can create a subject and trigger it when the component gets destroyed.

Imagine your service has multiple Subjects and your component subscribes to each of them. In this case you would have to store all of your subscriptions via class properties (or an array of subscriptions for that matter) and you would have to unsubscribe manually from each of them.

```<code>class myComponent {

  // create any subject which allows you to push into
  // when your component gets destroyed
  private onDestroy = new Subject<void>();

  public ngOnInit(): void {
    // Subscription #1
    this._statusService.statusChange_1$.pipe(
      tap(() => /* do something */),
      // takeUntil will listen to changes of the onDestroy subject
      // and whenever you trigger it by this.onDestroy.next() it will
      // automatically unsubsribe for you
      takeUntil(this.onDestroy)
    ).subscribe();

    // Subscription #2
    this._statusService.statusChange_2$.pipe(
      takeUntil(this.onDestroy)
    ).subscribe(value => {
      /* do something else */
      // you can put your logic into your subscribe method as well
      // like you did in your question
    });

    // Any number of more subscriptions...
    // ...
  }

  public ngOndestroy(): void {
    // Notify the observers to unsibscribe
    this.onDestroy.next();
  }
}
</code>```

This approach works with any observable.

ContentLicense: CC BY-SA 4.0

Body:
I have an Angular Service that defines a public Subject. Later under some condition, the service will call .next() on this Subject.

In addition, I have an Angular component that .subscribe() to this Subject in it's ngOnInit() method, and call .unsubscribe() in it's ngOnDestroy() method.

While both the service and the component are alive my code works fine. However, the user can click on a different tab in my app. Which cause my component to unload and call its ngOnDestroy() method, meaning the Observable was unsubscribed.

Starting from this point, the component no longer exists however the service is still alive - other components still use it. When the service calling .next() method after the component called .unsubscribe(), this error is thrown ObjectUnsubscribedError.
ERROR Error: Uncaught (in promise): ObjectUnsubscribedError: object unsubscribed

In addition, later if the user goes back to the tab that contains the component, the ngOnInit() is executed and the re-subscription to this observable throws the same error again.

What am I doing wrong, how can I resolve these errors?

import { Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class StatusService {
  public statusChange$: Subject<number>;

  public constructor(...) {
    this.statusChange$ = new Subject<number>();
  }

  public someInternalLogic(someNumber: number): void {
    this.statusChange$.next(someNumber);
    // this will throw an error if StatusComponent call .unsubscribe()
  }
}

@Component({
  selector: 'app-status',
  templateUrl: './status.component.html',
  styleUrls: ['./status.component.scss']
})
export class StatusComponent implements OnInit, OnDestroy {
  public constructor(
    private _statusService: StatusService) {}

    public ngOnInit(): void {
      this._statusService.statusChange$.subscribe(value => this._onStatusChange(value));
  }

  public ngOnDestroy(): void {
    this._statusService.statusChange$.unsubscribe();
    // after this point if the StatusService calling .next() an error will be thrown
  }

  private _onStatusChange(value: number): void {
    // ....
  }
}

Body:
Another way to collectively unsubscribe on the OnDestroy event is the usage of the takeUntil operator. So you don't have to store each of your subscriptions, instead you can create a subject and trigger it when the component gets destroyed.

Imagine your service has multiple Subjects and your component subscribes to each of them. In this case you would have to store all of your subscriptions via class properties (or an array of subscriptions for that matter) and you would have to unsubscribe manually from each of them.

class myComponent {

  // create any subject which allows you to push into
  // when your component gets destroyed
  private onDestroy = new Subject<void>();

  public ngOnInit(): void {
    // Subscription #1
    this._statusService.statusChange_1$.pipe(
      tap(() => /* do something */),
      // takeUntil will listen to changes of the onDestroy subject
      // and whenever you trigger it by this.onDestroy.next() it will
      // automatically unsubsribe for you
      takeUntil(this.onDestroy)
    ).subscribe();

    // Subscription #2
    this._statusService.statusChange_2$.pipe(
      takeUntil(this.onDestroy)
    ).subscribe(value => {
      /* do something else */
      // you can put your logic into your subscribe method as well
      // like you did in your question
    });

    // Any number of more subscriptions...
    // ...
  }

  public ngOndestroy(): void {
    // Notify the observers to unsibscribe
    this.onDestroy.next();
  }
}

This approach works with any observable.


问:
why the unless function in perl isn't working
I was writing a simple perl script which calculates payment based on the hours given by the user and the program mustn't allow payments above 500 hrs but has to allow upto 600 for females, and I was using the unless function but it is not working it allows more than 600 hrs for females.

here is the code I used

```<code>print("Enter your working hours");
    $hours=<stdin>;
    print("Enter your gender");
    $gender=<stdin>;
    chomp($gender);
    unless($gender ne "f" && $hours>=600){
        print("Your have earned ",$hours*10," Birr \n");
    }
    else{
         unless($hours>=500){
            print("Your have earned ",$hours*10," Birr \n");
        }
        else{
            print("You have worked beyond the payable hrs!");
        }
    }
</code>```

答:
Break it down.

it allows more than 600 hrs for females.

Let's try some test data.

```<code>$gender = "f";
$hours = 750;
</code>```

Feed that into your test:

```<code>unless($gender ne "f" && $hours>=600){
</code>```

Replace the variables with the values

```<code>unless("f" ne "f" && 750>=600){
</code>```

Convert the tests to booleans

```<code>unless(false && true){
</code>```

Resolve the logical operator

```<code>unless(false);
</code>```

Which means it runs the expression.

You're confusing yourself with a double negative.

Try to simplify the logic by splitting it apart and avoiding negatives.

```<code>my $allowedHours = 500;
if ($gender eq "f") {
    $allowedHours = 600;
}
if ($hours <= $allowedHours) {
    # report
} else {
    # error
}
</code>```

Body:
I was writing a simple perl script which calculates payment based on the hours given by the user and the program mustn't allow payments above 500 hrs but has to allow upto 600 for females, and I was using the unless function but it is not working it allows more than 600 hrs for females.

here is the code I used

print("Enter your working hours");
    $hours=<stdin>;
    print("Enter your gender");
    $gender=<stdin>;
    chomp($gender);
    unless($gender ne "f" && $hours>=600){
        print("Your have earned ",$hours*10," Birr \n");
    }
    else{
         unless($hours>=500){
            print("Your have earned ",$hours*10," Birr \n");
        }
        else{
            print("You have worked beyond the payable hrs!");
        }
    }

Body:
Break it down.

it allows more than 600 hrs for females.

Let's try some test data.

$gender = "f";
$hours = 750;

Feed that into your test:

unless($gender ne "f" && $hours>=600){

Replace the variables with the values

unless("f" ne "f" && 750>=600){

Convert the tests to booleans

unless(false && true){

Resolve the logical operator

unless(false);

Which means it runs the expression.

You're confusing yourself with a double negative.

Try to simplify the logic by splitting it apart and avoiding negatives.

my $allowedHours = 500;
if ($gender eq "f") {
    $allowedHours = 600;
}
if ($hours <= $allowedHours) {
    # report
} else {
    # error
}


问:
Powershell difference Add-ADGroupMember and Add-ADPrincipalGroupMembership
What is in powershell the difference between Add-ADGroupMember and Add-ADPrincipalGroupMembership?

According to this Website:
You can only pass group objects to this cmdlet (Add-ADGroupMember) through the pipeline. To pass user objects through the pipeline, use Add-ADPrincipalGroupMembership

Is there more to think of?

答:
Thanks to @Olaf, here is the answer:

Add-ADGroupMember

you can add one or more members to one group

Add-ADPrincipalGroupMembership

you can add one member to one or more groups


问:
How to dismiss keyboard after pressing the "X" in searchview? (Android Studio Java)
I want to dismiss the keyboard upon entering the activity and after the person searches and press "X" on the searchview. how do i do that?</p>

答:
you can set searchView close button OnClickListener using this code:-</p>
```<code>//finding the close button Id
int ClsBtn = searchView.getContext().getResources()
                .getIdentifier("android:id/search_close_btn", null, null);
//Get close button by its id
ImageView ClsImg = (ImageView) this.searchView.findViewById(ClsBtn);
//Onclick listener
ClsImg.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       //hide the keyboard
InputMethodManager inputM = (InputMethodManager)                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(inputM != null){
        inputM.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
    }
});
</code>```

Body:
you can set searchView close button OnClickListener using this code:-

//finding the close button Id
int ClsBtn = searchView.getContext().getResources()
                .getIdentifier("android:id/search_close_btn", null, null);
//Get close button by its id
ImageView ClsImg = (ImageView) this.searchView.findViewById(ClsBtn);
//Onclick listener
ClsImg.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       //hide the keyboard
InputMethodManager inputM = (InputMethodManager)                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(inputM != null){
        inputM.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
    }
});


问:
HP Quality Center API + ASP.NET
Has anyone ever used ASP or ASP.NET to connect to HPQC via the API? Where can I find some examples of this interaction? Any direction on the matter would be greatly appreciated.</p>

答: The Open Test Architecture (OTA) API is supplied as a COM library in OTAClient.dll (which is included when you install the HP Quality Center Client Side Setup Add-in -- QCExplorer.)  You can reference the DLL as a COM object with .NET wrapper.</p>

OwnerDisplayName: ricbax

ContentLicense: CC BY-SA 2.5

Title: HP Quality Center API + ASP.NET

ContentLicense: CC BY-SA 3.0


问:
error with PhotoView : Looking up a deactivated widget's ancestor is unsafe
I have read few stackoverflow posts about "Looking up a deactivated widget's ancestor is unsafe" error but couldn't find an answer which work.

I've tried to set a global key with the scaffold, and to use WidgetsBinding.instance.addPostFrameCallback() without success.

I'm pretty sure I'm doing something stupid and easy to fix, but I can't figure out what.

This is a simple version of the code which replicates the error when you go back from PhotoViewPage (photo_view package) :

my_home_page.dart

```<code>import 'package:flutter/material.dart';
import 'package:phototest/photo_view_page.dart';

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextButton(
      child: const Text("to PhotoView"),
      onPressed: () => _toPhotoView(context),
    );
  }

  void _toPhotoView(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute<dynamic>(
        builder: (BuildContext context) => const PhotoViewPage(),
      ),
    );
  }
}
</code>```

photo_view_page.dart

```<code>import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';

class PhotoViewPage extends StatelessWidget {
  const PhotoViewPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return PhotoView(imageProvider: AssetImage("assets/image.png"));
  }
}
</code>```

答:
UPDATE - Fixed in photo_view 0.14.

The problem is coming from photo_view package.

In pubspec.yaml remove photo_view from dependecies

```<code>dependencies:
  photo_view: ^0.13.0
</code>```

Add:

```<code>dependency_overrides:
  photo_view:
    git:
      url: https://github.com/bluefireteam/photo_view
      ref: master
</code>```

This way you will avoid errors in dependencies that come from the same version.

Body:
I have read few stackoverflow posts about "Looking up a deactivated widget's ancestor is unsafe" error but couldn't find an answer which work.

I've tried to set a global key with the scaffold, and to use WidgetsBinding.instance.addPostFrameCallback() without success.

I'm pretty sure I'm doing something stupid and easy to fix, but I can't figure out what.

This is a simple version of the code which replicates the error when you go back from PhotoViewPage (photo_view package) :

my_home_page.dart

import 'package:flutter/material.dart';
import 'package:phototest/photo_view_page.dart';

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextButton(
      child: const Text("to PhotoView"),
      onPressed: () => _toPhotoView(context),
    );
  }

  void _toPhotoView(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute<dynamic>(
        builder: (BuildContext context) => const PhotoViewPage(),
      ),
    );
  }
}

photo_view_page.dart

import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';

class PhotoViewPage extends StatelessWidget {
  const PhotoViewPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return PhotoView(imageProvider: AssetImage("assets/image.png"));
  }
}

Body:
UPDATE - Fixed in photo_view 0.14.

The problem is coming from photo_view package.

In pubspec.yaml remove photo_view from dependecies

dependencies:
  photo_view: ^0.13.0

Add:

dependency_overrides:
  photo_view:
    git:
      url: https://github.com/bluefireteam/photo_view
      ref: master

This way you will avoid errors in dependencies that come from the same version.


问:
How to lookup for nested property?
Let's say i have 2 collections

```<code>// Post collection:
{
    "_id": "post1",
    "title": "Some title"
}

</code>```
```<code>// User collection:

{
    "_id": "user1",
    "posts": {
        "voted": [
            {
                 "_id": "post1",
                 "vote": 3
            },
            {
                 "_id": "post2",
                 "vote": 2
            }
        ]
    }
}
</code>```

And i need to get this result:

```<code>{
    "_id": "post1",
    "title": "Some title",
    "voted": 3
}
</code>```

How can i make a request with aggregation, which will display this output ?

Here what i've tried: https://mongoplayground.net/p/oeKpVHo0uRe

答:
simple option:

```<code> db.post.aggregate([
 {
   $match: {
  _id: "post1"
 }
 },
 {
  $lookup: {
  from: "user",
  localField: "_id",
  foreignField: "posts.voted._id",
  as: "Results"
 }
 },
 {
  $unwind: "$Results"
 },
 {
  $unwind: "$Results.posts.voted"
 },
 {
  $match: {
   "Results.posts.voted._id": "post1"
 }
 },
 {
  $project: {
   "voted": "$Results.posts.voted.vote",
   title: 1
 }
 }
 ])
</code>```

explained:

$match the posts for post1 only

$join(lookup) with the users collection

$unwind the arrays.

$match only the voted for post1

$project the needed fields.

playground

Title: How to lookup for nested property?

Body:
Let's say i have 2 collections

// Post collection:
{
    "_id": "post1",
    "title": "Some title"
}

// User collection:

{
    "_id": "user1",
    "posts": {
        "voted": [
            {
                 "_id": "post1",
                 "vote": 3
            },
            {
                 "_id": "post2",
                 "vote": 2
            }
        ]
    }
}

And i need to get this result:

{
    "_id": "post1",
    "title": "Some title",
    "voted": 3
}

How can i make a request with aggregation, which will display this output ?

Here what i've tried: https://mongoplayground.net/p/oeKpVHo0uRe

Body:
simple option:

 db.post.aggregate([
 {
   $match: {
  _id: "post1"
 }
 },
 {
  $lookup: {
  from: "user",
  localField: "_id",
  foreignField: "posts.voted._id",
  as: "Results"
 }
 },
 {
  $unwind: "$Results"
 },
 {
  $unwind: "$Results.posts.voted"
 },
 {
  $match: {
   "Results.posts.voted._id": "post1"
 }
 },
 {
  $project: {
   "voted": "$Results.posts.voted.vote",
   title: 1
 }
 }
 ])

explained:

$match the posts for post1 only

$join(lookup) with the users collection

$unwind the arrays.

$match only the voted for post1

$project the needed fields.

playground


问:
Oracle APEX User Rights and Previleges
I do not have much experience and I would like to know if there is an easy way to create user rights and privileges, so that each user can access only specific records from the database tables, based on the level he belongs to.

More specifically, suppose we have a group of companies where this group has some companies and these companies have some branches and the branches have some users.

I want the user belonging to the "group of companies" level to have access to and view all the entries in the database related to that group and what is below it (its companies and the branches of these companies).

The user who belongs to the "company" level should have access and see only the files of this company and the branches that this company may have in the database.

The user belonging to the "Branch" level should only be able to access and view this barnch records in the database.

And finally the user belonging to the "End User" level to have access and see only the records created by the user in the database.

Of course level "administrator" will have access to all records in the database.

I thought of creating a user table with a field "User_Level" and in each table to enter USER_ID where based on this I can find the level of a user but how can I restrict access based on the Group of Companies or the Company or the Branch where it belongs?

答:
you can create a procedure or function and in your app's shared components -> authorization scheme use that such as pl/sql function/procedure returning boolean and return true for  the users you want to see the things and false for hiding.
In Apex components, select this authorization scheme like in items, pages etc.</p>

Title: Oracle APEX User Rights and Previleges


问:
How can I save one Entity containing another entity so they are linked together?
I have a simple Order entity that contains OneToMany relation with a list of Dishes.

Order entity:

```<code>@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Table(name = "orders")
@ToString
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Enumerated(EnumType.STRING)
    private Status status;
    private LocalDateTime creationDate;
    private LocalDateTime updateDate;
    private BigDecimal totalPrice;
    private String address;
    @ManyToOne(fetch = FetchType.LAZY)
    @ToString.Exclude
    private User user;

    @OnDelete(action = OnDeleteAction.CASCADE)
    @OneToMany(
            mappedBy = "order",
            cascade = CascadeType.ALL,
            orphanRemoval = true)
    @ToString.Exclude
    private List<Dish> dishes;

    public Order(long id, Status status, BigDecimal totalPrice, String address, List<Dish> dishes) {
        this.id = id;
        this.status = status;
        this.creationDate = LocalDateTime.now();
        this.updateDate = LocalDateTime.now();
        this.totalPrice = totalPrice;
        this.address = address;
        this.dishes = dishes;
    }
}
</code>```

Dish entity:

```<code>@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Dish {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
    private String description;
    private Category category;
    BigDecimal price;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @ToString.Exclude
    private Order order;

    public Dish(long id, String name, String description, Category category, BigDecimal price) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.category = category;
        this.price = price;
    }

    public void setOrder(Order order) {
        this.order = order;
        order.addDish(this);
    }
}
</code>```

Here I try to save Orders containg these dishes

```<code>Dish dish1 = new Dish(0, "Dish first", "Description of first Dish", Category.SNACKS, BigDecimal.valueOf(100));
Dish dish2 = new Dish(0, "Dish second", "Description of second Dish", Category.BURGERS, BigDecimal.valueOf(100));

List<Dish> dishes1 = Arrays.asList(dish1, dish2);
List<Dish> dishes2 = Arrays.asList(dish2);
Order order1 = new Order(0, Status.PENDING, BigDecimal.valueOf(150), "Address 1", dishes1);
Order order2 = new Order(0, Status.COMPLETED, BigDecimal.valueOf(150), "Address 2", dishes2);
</code>```

Here is the problem, Dishes are persisted together with orders, but not associated with the Order Entity.
Id is null

I know I didn't set order field when I created dishes, but how to do this If I need save both Order and Dishes at the same time.

答:
You have the wrong model, what id do you expect to be in dish2?
Relation between Order and Dish is NOT one-to-many, but many-to-many. Hibernate does not know what to enter in the column.</p>

Body:
I have a simple Order entity that contains OneToMany relation with a list of Dishes.

Order entity:

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Table(name = "orders")
@ToString
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Enumerated(EnumType.STRING)
    private Status status;
    private LocalDateTime creationDate;
    private LocalDateTime updateDate;
    private BigDecimal totalPrice;
    private String address;
    @ManyToOne(fetch = FetchType.LAZY)
    @ToString.Exclude
    private User user;

    @OnDelete(action = OnDeleteAction.CASCADE)
    @OneToMany(
            mappedBy = "order",
            cascade = CascadeType.ALL,
            orphanRemoval = true)
    @ToString.Exclude
    private List<Dish> dishes;

    public Order(long id, Status status, BigDecimal totalPrice, String address, List<Dish> dishes) {
        this.id = id;
        this.status = status;
        this.creationDate = LocalDateTime.now();
        this.updateDate = LocalDateTime.now();
        this.totalPrice = totalPrice;
        this.address = address;
        this.dishes = dishes;
    }
}

Dish entity:

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Dish {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
    private String description;
    private Category category;
    BigDecimal price;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @ToString.Exclude
    private Order order;

    public Dish(long id, String name, String description, Category category, BigDecimal price) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.category = category;
        this.price = price;
    }

    public void setOrder(Order order) {
        this.order = order;
        order.addDish(this);
    }
}

Here I try to save Orders containg these dishes

Dish dish1 = new Dish(0, "Dish first", "Description of first Dish", Category.SNACKS, BigDecimal.valueOf(100));
Dish dish2 = new Dish(0, "Dish second", "Description of second Dish", Category.BURGERS, BigDecimal.valueOf(100));

List<Dish> dishes1 = Arrays.asList(dish1, dish2);
List<Dish> dishes2 = Arrays.asList(dish2);
Order order1 = new Order(0, Status.PENDING, BigDecimal.valueOf(150), "Address 1", dishes1);
Order order2 = new Order(0, Status.COMPLETED, BigDecimal.valueOf(150), "Address 2", dishes2);

Here is the problem, Dishes are persisted together with orders, but not associated with the Order Entity.
Id is null

I know I didn't set order field when I created dishes, but how to do this If I need save both Order and Dishes at the same time.


问:
MKMapView: how to bring MKUserLocationView (The blue dot) to front?
I am adding a custom annotation instead of the pin annotation.
Basically, I draw a circle in these annotations and add them to the map.
THe problem these custom annotations obscure the user location view ( the blue dot)
How do I bring the blue dot to the front.

   ```- (void)mapView:(MKMapView *)mapView
didUpdateUserLocation:(MKUserLocation *)userLocation
{
UIView *user = [mapView viewForAnnotation:userLocation];
[mapView bringSubviewToFront:user];
}
```

However, this is not working for me. The blue user dot is still being covered by my custom annotations.
Any ideas how I can get the user location view to appear in front?
Cheers

答:
Try this, it works.:

```<code>MKAnnotationView *userLocationView = [self.mapView viewForAnnotation:self.mapView.userLocation];
[userLocationView.superview bringSubviewToFront:userLocationView];
</code>```

Body:
I am adding a custom annotation instead of the pin annotation.
Basically, I draw a circle in these annotations and add them to the map.
THe problem these custom annotations obscure the user location view ( the blue dot)
How do I bring the blue dot to the front.

- (void)mapView:(MKMapView *)mapView
didUpdateUserLocation:(MKUserLocation *)userLocation
{
UIView *user = [mapView viewForAnnotation:userLocation];
[mapView bringSubviewToFront:user];
}

However, this is not working for me. The blue user dot is still being covered by my custom annotations.
Any ideas how I can get the user location view to appear in front?
Cheers

Body:
Try this, it works.:

MKAnnotationView *userLocationView = [self.mapView viewForAnnotation:self.mapView.userLocation];
[userLocationView.superview bringSubviewToFront:userLocationView];


问:
compare two values of cell then send email
```<code>function myFunction() {

  const minimumLevel = [0,5,10,15,20,25,30];
  var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
  var data = sheet.getRange(2,1,data.getLastRow() - 1, data.getLastColumn()).getValues();
  data.forEach((r,i) => {
      if(r[9] < minimumLevel[1]){
        console.log("true");

        // Fetch the email address
       var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("B2");
       var emailAddress = emailRange.getValues();
       // Send Alert Email.
       var message = 'This is your Alert email!'; // Second column
       var subject = 'Your Google Spreadsheet Alert';
        MailApp.sendEmail(emailAddress, subject, message);

      }
  })

}
</code>```

I am trying to compare to values of cell and then if the value of that cell goes below minimum level it will send an email to someone, however I think i am stuck? please can someone help?

答:
Try it this way:

```<code>function myFunction() {
  const minimumLevel = [0,5,10,15,20,25,30];
  var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
  var data = sheet.getRange(2,1,sheet.getLastRow() - 1, sheet.getLastColumn()).getValues();
  data.forEach((r,i) => {
      if(r[9] < minimumLevel[1]){
        console.log("true");
        //send email code here
      }
  });
}
</code>```

Body:
function myFunction() {

  const minimumLevel = [0,5,10,15,20,25,30];
  var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
  var data = sheet.getRange(2,1,data.getLastRow() - 1, data.getLastColumn()).getValues();
  data.forEach((r,i) => {
      if(r[9] < minimumLevel[1]){
        console.log("true");

        // Fetch the email address
       var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("B2");
       var emailAddress = emailRange.getValues();
       // Send Alert Email.
       var message = 'This is your Alert email!'; // Second column
       var subject = 'Your Google Spreadsheet Alert';
        MailApp.sendEmail(emailAddress, subject, message);

      }
  })

}

I am trying to compare to values of cell and then if the value of that cell goes below minimum level it will send an email to someone, however I think i am stuck? please can someone help?

Body:
Try it this way:

function myFunction() {
  const minimumLevel = [0,5,10,15,20,25,30];
  var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
  var data = sheet.getRange(2,1,sheet.getLastRow() - 1, sheet.getLastColumn()).getValues();
  data.forEach((r,i) => {
      if(r[9] < minimumLevel[1]){
        console.log("true");
        //send email code here
      }
  });
}


问:
Discord.js isnt sending the embed due to non-empty string error
```<code>const { SlashCommandBuilder } = require('@discordjs/builders')
const discord = require('discord.js')
const open = require('openweather-api-node');
module.exports = {
    data: new SlashCommandBuilder()
        .setName('weather')
        .setDescription('Shows the Weather condition of a place')
        .addStringOption(option =>
            option.setName('city')
                .setDescription('Name of the city')
                .setRequired(true)),

    async execute(Discord, client, interaction) {

        let city = interaction.options.getString('city');

        let weather = new open({
            key: process.env.WEATHER,

            units: 'metric'
        })

        weather.setLanguage('en')
     let info = await   weather.getCurrent({ locationName: city })

      if(!info) return interaction.reply({content:"Oops "})
            //location
            var lon = info.lon.toString()
            var lat = info.lat.toString()
            let Timezone = info.timezone

            //Temperature
            var temp =  info.weather.temp.cur.toString()
            let feel_like = info.weather.feels_like.cur
            let min = info.weather.temp.min
            let max =info.weather.temp.max

            //air condition
            let pressure = info.weather.pressure
            let humidity = info.weather.humidity + '%'
            let wind = info.weather.wind.speed + 'km/h'

            //description

            let sky = info.weather.description
            let status = info.weather.main

        console.log(temp)
        console.log(lon)
        console.log(lat)

            let new1 = new discord.MessageEmbed()
            new1.setTitle(city + `'s Weather`)
            new1.setDescription('bruh pls work')
            new1.setColor('#0099ff')
            new1.addFields('**Location**', `Latitude:`+ lat,true)
            new1.addFields('**Temperature**', `${temp}℃`,true)
            new1.setTimestamp()
            new1.setFooter({ text: 'Information by Open-Weather' })

            interaction.reply({embeds:[new1]})

    }
}
</code>```

So this is my code
the temp,lan,lat variables were number but i changed them into string
and even checked with the typeof method
It gave me a string

But still i'm facing out this error called RangeError [EMBED_FIELD_NAME]: MessageEmbed field names must be non-empty string

Please help me if you know whats the solution

答:
You're trying to add one field using Embed#addFields. Embed#addFields takes in an 25 parameters of EmbedFieldData. The correct syntax using Embed#addFields would be:

foo.addFields(
   { name: 'foo', value: 'bar' },
   { name: 'egg', value: 'spam' }
)
```
<p>You can also use Embed#addField to add one field.</p>
<pre class="lang-js prettyprint-override"><code>foo.addField('bar', 'baz')
</code>```

Body:
const { SlashCommandBuilder } = require('@discordjs/builders')
const discord = require('discord.js')
const open = require('openweather-api-node');
module.exports = {
    data: new SlashCommandBuilder()
        .setName('weather')
        .setDescription('Shows the Weather condition of a place')
        .addStringOption(option =>
            option.setName('city')
                .setDescription('Name of the city')
                .setRequired(true)),

    async execute(Discord, client, interaction) {

        let city = interaction.options.getString('city');

        let weather = new open({
            key: process.env.WEATHER,

            units: 'metric'
        })

        weather.setLanguage('en')
     let info = await   weather.getCurrent({ locationName: city })

      if(!info) return interaction.reply({content:"Oops "})
            //location
            var lon = info.lon.toString()
            var lat = info.lat.toString()
            let Timezone = info.timezone

            //Temperature
            var temp =  info.weather.temp.cur.toString()
            let feel_like = info.weather.feels_like.cur
            let min = info.weather.temp.min
            let max =info.weather.temp.max

            //air condition
            let pressure = info.weather.pressure
            let humidity = info.weather.humidity + '%'
            let wind = info.weather.wind.speed + 'km/h'

            //description

            let sky = info.weather.description
            let status = info.weather.main

        console.log(temp)
        console.log(lon)
        console.log(lat)

            let new1 = new discord.MessageEmbed()
            new1.setTitle(city + `'s Weather`)
            new1.setDescription('bruh pls work')
            new1.setColor('#0099ff')
            new1.addFields('**Location**', `Latitude:`+ lat,true)
            new1.addFields('**Temperature**', `${temp}℃`,true)
            new1.setTimestamp()
            new1.setFooter({ text: 'Information by Open-Weather' })

            interaction.reply({embeds:[new1]})

    }
}

So this is my code
the temp,lan,lat variables were number but i changed them into string
and even checked with the typeof method
It gave me a string

But still i'm facing out this error called RangeError [EMBED_FIELD_NAME]: MessageEmbed field names must be non-empty string

Please help me if you know whats the solution

Body:
You're trying to add one field using Embed#addFields. Embed#addFields takes in an 25 parameters of EmbedFieldData. The correct syntax using Embed#addFields would be:

foo.addFields(
   { name: 'foo', value: 'bar' },
   { name: 'egg', value: 'spam' }
)

You can also use Embed#addField to add one field.

foo.addField('bar', 'baz')


问:
Image resizing not working with Intervention image Package
The photo is saved, but without resizing, the original photo is actually saved</p>
```<code>protected function uploadImage($images = '') {
    $path = 'upload/images';
    if (request()->hasFile('image') && $files = request()->file('image'))
        $images = Image::make($files->store($path, 'public_files'))->resize(320, 240);
    return $images;
}
</code>```
```<code>public function store(CreateGalleryRequest $request, Job $job) {
    $image = $this->uploadImage();
    if ($request->hasFile('image')) {
        $data['image'] = $image . $image->dirname . '/' . $image->basename;
    } else
        $data['image'] = null;
    $job->gallery()->create($data);
    return redirect(route('jobs.gallery.index' , ['job' => $job->id]));
}
</code>```

答:
wrote:

```<code>$images = Image::make($files->store($path, 'public_files'))->resize(320, 240)->save($files->store($path, 'public_files'));
</code>```

error:

```<code>Illuminate\Database\QueryException
</code>```

actually there is an error in the following code:

```<code>$job->gallery()->create($data);
</code>```

Body:
The photo is saved, but without resizing, the original photo is actually saved

protected function uploadImage($images = '') {
    $path = 'upload/images';
    if (request()->hasFile('image') && $files = request()->file('image'))
        $images = Image::make($files->store($path, 'public_files'))->resize(320, 240);
    return $images;
}

public function store(CreateGalleryRequest $request, Job $job) {
    $image = $this->uploadImage();
    if ($request->hasFile('image')) {
        $data['image'] = $image . $image->dirname . '/' . $image->basename;
    } else
        $data['image'] = null;
    $job->gallery()->create($data);
    return redirect(route('jobs.gallery.index' , ['job' => $job->id]));
}

Body:
wrote:

$images = Image::make($files->store($path, 'public_files'))->resize(320, 240)->save($files->store($path, 'public_files'));

error:

Illuminate\Database\QueryException

actually there is an error in the following code:

$job->gallery()->create($data);


问:
Fill a 6x6 grid with 6 colors without same colors touching each other
I'm trying to create a board game with p5.js (Javascript)

To set up the game board which is a 6 by 6 grid, I have to fill the grid with 6 colors in a way that no horizontal or vertical touching cells have the same color. And all 6 colors have to be used in 6 cells.

But now I'm struggling a bit creating an algorithm that places the colors randomly but keeping the rules.

I tried to start at the top left corner, filling with a random color.
Then I start to fill the cell to the left and the bottom with a different color.

The problem is, that when the script wants to fill the last few cells, there are no colors left to use (either already 6 cells filled or a remaining color is a neighbor)

Example:
Still two cells need to be red, but only one place is left for red (under white):

```<code>//fill placedColors Array with zeros
placedColors = [];
for(let i=0; i<6; i++) {
    placedColors[i] = 0;
}

//fill allIndexes Array with indizies to keep control of visited cells
let allIndexes = [];
for(let i=0; i<36; i++) {
    allIndexes.push(i);
}

//build board
//when I set the limit to 36 the script runs forever because no solution is found
for(let i=0; i<33; i++) {
    fillCells(i);
}

function fillCells(index) {
    //get top and left color
    let topColor = false;
    //index is in the second row
    if(index >= 6) {
        topColor = cells[index-6].color;
    }

    let leftColor = false;
    //index is not in the first column
    if(index % 6 > 0 && index > 0) {
        leftColor = cells[index-1].color;
    }

    if(allIndexes.indexOf(index) > -1) {
        cells.push(new Cell(index, pickColor(topColor, leftColor)));
    }

    //mark index as visited
    var allIndexesIndex = allIndexes.indexOf(index);
    if (allIndexesIndex !== -1) {
        allIndexes.splice(allIndexesIndex, 1);
    }
}

function pickColor(invalidColor1,invalidColor2) {
    let colorFound = false;
    do {
        randColor = floor(random(6));

        if(placedColors[randColor] < 6 && randColor!=invalidColor1 && randColor!=invalidColor2) {
            placedColors[randColor]++;
            colorFound = true;
        }
    } while(!colorFound);

    return randColor;
}

</code>```

答:
One way to look at this would be as searching for a path through a tree where each node has 6 possible children for the six colours which could come next. Ignoring all the constraints initially, you pick one of these at random 36 times, and have your order of placements.

Using a recursive function (which will be useful in a moment), an unconstrained search would look like this:

function randomChoice(list) {
  return list[Math.floor(Math.random() * list.length)];
}

function placeNext(sequenceSoFar) {
    const availableColours = [0,1,2,3,4,5];
    let chosenColour = randomChoice(availableColours);
    sequenceSoFar = [...sequenceSoFar, colourToAdd];

    if ( sequenceSoFar.length == 36 ) {
        // Completed sequence!
        return sequenceSoFar;
    }
    else {
        // Recurse to make next choice
        return placeNext(sequenceSoFar);
    }
}

// Start with an empty array
let sequence = placeNext([]);
console.log(sequence);```
</div>
</div>
</p>
<p>Next, we need to eliminate choices that would violate the constraints of the problem:</p>
<ul>
<li>The cell to the left isn't the same colour, i.e. <code>chosenColour !== sequenceSoFar[nextIndex-1]</code></li>
<li>The cell above isn't the same colour, i.e. <code>chosenColour !== sequenceSoFar[nextIndex-6]</code></li>
<li>The colour doesn't already occur six times in the sequence, i.e. <code>sequenceSoFar.filter((element) => element === chosenColour).length < 6</code></li>
</ul>
<p>If the chosen colour doesn't meet these requirements, we remove it from the list of candidates and try again:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function randomChoice(list) {
  return list[Math.floor(Math.random() * list.length)];
}

function newColourIsValid(sequenceSoFar, chosenColour) {
   // We haven't added the next colour yet, but know where it *will* be
   let nextIndex = sequenceSoFar.length;

   return (
       // The cell to the left isn't the same colour
       ( nextIndex < 1 || chosenColour !== sequenceSoFar[nextIndex-1] )
       &&
       // The cell above isn't the same colour
       ( nextIndex < 6 || chosenColour !== sequenceSoFar[nextIndex-6] )
       &&
       // The colour doesn't already occur six times in the sequence
       sequenceSoFar.filter((element) => element === chosenColour).length < 6
   );
}

function placeNext(sequenceSoFar) {
    let availableColours = [0,1,2,3,4,5];
    let chosenColour;

    do {
        // If we run out of possible colours, then ... panic?
        if ( availableColours.length === 0 ) {
            console.log(sequenceSoFar);
            throw 'No sequence possible from here!';
        }

        chosenColour = randomChoice(availableColours);

        // Eliminate the colour from the list of choices for next iteration
        availableColours = availableColours.filter((element) => element !== chosenColour);
    } while ( ! newColourIsValid(sequenceSoFar, chosenColour) );

    sequenceSoFar = [...sequenceSoFar, colourToAdd];

    if ( sequenceSoFar.length == 36 ) {
        // Completed sequence!
        return sequenceSoFar;
    }
    else {
        // Recurse to make next choice
        return placeNext(sequenceSoFar);
    }
}

// Start with an empty array
let sequence = placeNext([]);
console.log(sequence);</code>```

So far, this has the same problem as your original code - if it hits a dead end, it doesn't know what to do. To solve this, we can use a backtracking algorithm. The idea is that if we run out of candidates for position n, we reject the choice at position n-1 and try a different one.

Instead of placeNext, we need our function to be tryPlaceNext, which can return false if the sequence hits a dead end:

function randomChoice(list) {
  return list[Math.floor(Math.random() * list.length)];
}

function newColourIsValid(sequenceSoFar, chosenColour) {
   // We haven't added the next colour yet, but know where it *will* be
   let nextIndex = sequenceSoFar.length;

   return (
       // The cell to the left isn't the same colour
       ( nextIndex < 1 || chosenColour !== sequenceSoFar[nextIndex-1] )
       &&
       // The cell above isn't the same colour
       ( nextIndex < 6 || chosenColour !== sequenceSoFar[nextIndex-6] )
       &&
       // The colour doesn't already occur six times in the sequence
       sequenceSoFar.filter((element) => element === chosenColour).length < 6
   );
}

function tryPlaceNext(sequenceSoFar, colourToAdd) {
    let availableColours = [0,1,2,3,4,5];

    if ( ! newColourIsValid(sequenceSoFar, colourToAdd) ) {
        // Invalid choice, indicate to caller to try again
        return false;
    }

    // Valid choice, add to sequence, and find the next
    sequenceSoFar = [...sequenceSoFar, colourToAdd];

    if ( sequenceSoFar.length === 36 ) {
        // Completed sequence!
        return sequenceSoFar;
    }

    while ( availableColours.length > 0 ) {
        // Otherwise, pick one and see if we can continue the sequence with it
        let chosenColour = randomChoice(availableColours);

        // Recurse to make next choice
        let continuedSequence = tryPlaceNext(sequenceSoFar, chosenColour);

        if ( continuedSequence !== false ) {
            // Recursive call found a valid sequence, return it
            return continuedSequence;
        }

        // Eliminate the colour from the list of choices for next iteration
        availableColours = availableColours.filter((element) => element !== chosenColour);
    }

    // If we get here, we ran out of possible colours, so indicate a dead end to caller
    return false;
}

// Root function to start an array with any first element
function generateSequence() {
    let availableColours = [0,1,2,3,4,5];
    let chosenColour = randomChoice(availableColours);
    return tryPlaceNext([], chosenColour);
}

let sequence = generateSequence();
console.log(sequence);```

Body:
I'm trying to create a board game with p5.js (Javascript)

To set up the game board which is a 6 by 6 grid, I have to fill the grid with 6 colors in a way that no horizontal or vertical touching cells have the same color. And all 6 colors have to be used in 6 cells.

But now I'm struggling a bit creating an algorithm that places the colors randomly but keeping the rules.

I tried to start at the top left corner, filling with a random color.
Then I start to fill the cell to the left and the bottom with a different color.

The problem is, that when the script wants to fill the last few cells, there are no colors left to use (either already 6 cells filled or a remaining color is a neighbor)

Example:
Still two cells need to be red, but only one place is left for red (under white):

//fill placedColors Array with zeros
placedColors = [];
for(let i=0; i<6; i++) {
    placedColors[i] = 0;
}

//fill allIndexes Array with indizies to keep control of visited cells
let allIndexes = [];
for(let i=0; i<36; i++) {
    allIndexes.push(i);
}

//build board
//when I set the limit to 36 the script runs forever because no solution is found
for(let i=0; i<33; i++) {
    fillCells(i);
}

function fillCells(index) {
    //get top and left color
    let topColor = false;
    //index is in the second row
    if(index >= 6) {
        topColor = cells[index-6].color;
    }

    let leftColor = false;
    //index is not in the first column
    if(index % 6 > 0 && index > 0) {
        leftColor = cells[index-1].color;
    }

    if(allIndexes.indexOf(index) > -1) {
        cells.push(new Cell(index, pickColor(topColor, leftColor)));
    }

    //mark index as visited
    var allIndexesIndex = allIndexes.indexOf(index);
    if (allIndexesIndex !== -1) {
        allIndexes.splice(allIndexesIndex, 1);
    }
}

function pickColor(invalidColor1,invalidColor2) {
    let colorFound = false;
    do {
        randColor = floor(random(6));

        if(placedColors[randColor] < 6 && randColor!=invalidColor1 && randColor!=invalidColor2) {
            placedColors[randColor]++;
            colorFound = true;
        }
    } while(!colorFound);

    return randColor;
}

Body:
One way to look at this would be as searching for a path through a tree where each node has 6 possible children for the six colours which could come next. Ignoring all the constraints initially, you pick one of these at random 36 times, and have your order of placements.

Using a recursive function (which will be useful in a moment), an unconstrained search would look like this:

function randomChoice(list) {
  return list[Math.floor(Math.random() * list.length)];
}

function placeNext(sequenceSoFar) {
    const availableColours = [0,1,2,3,4,5];
    let chosenColour = randomChoice(availableColours);
    sequenceSoFar = [...sequenceSoFar, colourToAdd];

    if ( sequenceSoFar.length == 36 ) {
        // Completed sequence!
        return sequenceSoFar;
    }
    else {
        // Recurse to make next choice
        return placeNext(sequenceSoFar);
    }
}

// Start with an empty array
let sequence = placeNext([]);
console.log(sequence);

Next, we need to eliminate choices that would violate the constraints of the problem:

The cell to the left isn't the same colour, i.e. chosenColour !== sequenceSoFar[nextIndex-1]

The cell above isn't the same colour, i.e. chosenColour !== sequenceSoFar[nextIndex-6]

The colour doesn't already occur six times in the sequence, i.e. sequenceSoFar.filter((element) => element === chosenColour).length < 6

If the chosen colour doesn't meet these requirements, we remove it from the list of candidates and try again:

function randomChoice(list) {
  return list[Math.floor(Math.random() * list.length)];
}

function newColourIsValid(sequenceSoFar, chosenColour) {
   // We haven't added the next colour yet, but know where it *will* be
   let nextIndex = sequenceSoFar.length;

   return (
       // The cell to the left isn't the same colour
       ( nextIndex < 1 || chosenColour !== sequenceSoFar[nextIndex-1] )
       &&
       // The cell above isn't the same colour
       ( nextIndex < 6 || chosenColour !== sequenceSoFar[nextIndex-6] )
       &&
       // The colour doesn't already occur six times in the sequence
       sequenceSoFar.filter((element) => element === chosenColour).length < 6
   );
}

function placeNext(sequenceSoFar) {
    let availableColours = [0,1,2,3,4,5];
    let chosenColour;

    do {
        // If we run out of possible colours, then ... panic?
        if ( availableColours.length === 0 ) {
            console.log(sequenceSoFar);
            throw 'No sequence possible from here!';
        }

        chosenColour = randomChoice(availableColours);

        // Eliminate the colour from the list of choices for next iteration
        availableColours = availableColours.filter((element) => element !== chosenColour);
    } while ( ! newColourIsValid(sequenceSoFar, chosenColour) );

    sequenceSoFar = [...sequenceSoFar, colourToAdd];

    if ( sequenceSoFar.length == 36 ) {
        // Completed sequence!
        return sequenceSoFar;
    }
    else {
        // Recurse to make next choice
        return placeNext(sequenceSoFar);
    }
}

// Start with an empty array
let sequence = placeNext([]);
console.log(sequence);

So far, this has the same problem as your original code - if it hits a dead end, it doesn't know what to do. To solve this, we can use a backtracking algorithm. The idea is that if we run out of candidates for position n, we reject the choice at position n-1 and try a different one.

Instead of placeNext, we need our function to be tryPlaceNext, which can return false if the sequence hits a dead end:

function randomChoice(list) {
  return list[Math.floor(Math.random() * list.length)];
}

function newColourIsValid(sequenceSoFar, chosenColour) {
   // We haven't added the next colour yet, but know where it *will* be
   let nextIndex = sequenceSoFar.length;

   return (
       // The cell to the left isn't the same colour
       ( nextIndex < 1 || chosenColour !== sequenceSoFar[nextIndex-1] )
       &&
       // The cell above isn't the same colour
       ( nextIndex < 6 || chosenColour !== sequenceSoFar[nextIndex-6] )
       &&
       // The colour doesn't already occur six times in the sequence
       sequenceSoFar.filter((element) => element === chosenColour).length < 6
   );
}

function tryPlaceNext(sequenceSoFar, colourToAdd) {
    let availableColours = [0,1,2,3,4,5];

    if ( ! newColourIsValid(sequenceSoFar, colourToAdd) ) {
        // Invalid choice, indicate to caller to try again
        return false;
    }

    // Valid choice, add to sequence, and find the next
    sequenceSoFar = [...sequenceSoFar, colourToAdd];

    if ( sequenceSoFar.length === 36 ) {
        // Completed sequence!
        return sequenceSoFar;
    }

    while ( availableColours.length > 0 ) {
        // Otherwise, pick one and see if we can continue the sequence with it
        let chosenColour = randomChoice(availableColours);

        // Recurse to make next choice
        let continuedSequence = tryPlaceNext(sequenceSoFar, chosenColour);

        if ( continuedSequence !== false ) {
            // Recursive call found a valid sequence, return it
            return continuedSequence;
        }

        // Eliminate the colour from the list of choices for next iteration
        availableColours = availableColours.filter((element) => element !== chosenColour);
    }

    // If we get here, we ran out of possible colours, so indicate a dead end to caller
    return false;
}

// Root function to start an array with any first element
function generateSequence() {
    let availableColours = [0,1,2,3,4,5];
    let chosenColour = randomChoice(availableColours);
    return tryPlaceNext([], chosenColour);
}

let sequence = generateSequence();
console.log(sequence);


问:
Sequence contains no elements when comparing Guid in predicate with MySql.Data.Entity
I am using the Entity Framework with MySQL, and every table has a ID column that is of type CHAR(36). In the EDMX file they are all of type System.Guid, and the SSDL xml looks like:

```<code><EntityType Name="Accounts">
  <Key>
    <PropertyRef Name="ID" />
  </Key>
  <Property Name="ID" Type="guid" Nullable="false" />
  ...
</code>```

When I try to use any method (Single, Where, Any, etc), it throws an InvalidOperationException stating that the sequence contains no elements. Here's the weird part, if I expand the results view in the debugger, it does show the elements. The GUID values are the same, so it should be returning exactly one element. I have included a picture below (right click save as to see larger), but can anyone explain what is going on here? The GUID's do match:

```<code>(method argument) accountID:
{7767402f-9b29-4026-b40d-6eb991748f8c}
(should match) element in results view:
{7767402f-9b29-4026-b40d-6eb991748f8c}
</code>```

答:
My bet is that it's a bug in the MySQL connector and that it has to do with how the GUID is stored in the DB. For some reason the comparison is not working. I think you should use BINARY(16) instead of CHAR(36).

Check out the answer to this question: Storing MySQL GUID/UUIDs

Body:
I am using the Entity Framework with MySQL, and every table has a ID column that is of type CHAR(36). In the EDMX file they are all of type System.Guid, and the SSDL xml looks like:

<EntityType Name="Accounts">
  <Key>
    <PropertyRef Name="ID" />
  </Key>
  <Property Name="ID" Type="guid" Nullable="false" />
  ...

When I try to use any method (Single, Where, Any, etc), it throws an InvalidOperationException stating that the sequence contains no elements. Here's the weird part, if I expand the results view in the debugger, it does show the elements. The GUID values are the same, so it should be returning exactly one element. I have included a picture below (right click save as to see larger), but can anyone explain what is going on here? The GUID's do match:

(method argument) accountID:
{7767402f-9b29-4026-b40d-6eb991748f8c}
(should match) element in results view:
{7767402f-9b29-4026-b40d-6eb991748f8c}


问:
Cant upload multilple images using django
I'm trying to create page to add new product with it's images in other model on my website using Djnago.
The length of the list of images I get is always 0 and i'm getting IndexError: list index out of range. I guess that i'm getting files from request not properly using images = request.FILES.getlist('images')

models.py

```<code>class Products(models.Model):
    product_name = models.CharField(
        max_length=255, verbose_name='Product name')
    product_slug = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    product_image = models.ImageField(
        default='image-placeholder.png', verbose_name='Image')
    creaton_date = models.DateTimeField(auto_now_add=True)
    brand = models.ForeignKey(
        Brands, verbose_name='Brand', on_delete=models.PROTECT)
    price = models.FloatField(verbose_name='Price')
    description = models.TextField(null=True, verbose_name='Description')
    category = models.ForeignKey(
        Categories, on_delete=models.CASCADE, verbose_name='Category')
    bought_count = models.IntegerField(null=True, default=0)

class ProductImage(models.Model):
    product = models.ForeignKey(Products, on_delete=models.CASCADE)
    image = models.ImageField()
    default = models.BooleanField(default=False)

    def __str__(self):
        return str(self.product)
</code>```

template.html

```<code><form id="checkoutform" action="" method="post">
{% csrf_token %}
<div class="caption">
    <div class="form-group">
        <input class="input" type="text" name="product-name" placeholder="Product name">
    </div>
    <div class="form-group">
        <input class="input" type="text" name="brand" placeholder="Brand">
    </div>
    <div class="form-group">
        <input class="input" type="number" name="price" placeholder="Price">
    </div>
    <div class="form-group">
        <input class="input" type="file" multiple name="images" placeholder="Images">
    </div>
    <div class="form-group">
        <input class="input" type="text" name="desc" placeholder="Description">
    </div>
    <div class="form-group">
        <input class="input" type="text" name="category" placeholder="Category">
    </div>
    <input type="submit" value="Submit">
</form>
</code>```

views.py

```<code>def create_product(request):
    if request.user.is_superuser:
        if request.method == 'POST':
            data = request.POST
            images = request.FILES.getlist('images')
            brand = Brands.objects.get(name=data['brand'])
            category =  Categories.objects.get(name=data['category'])
            product = Products.objects.create(
                product_name = data['product-name'],
                brand=brand,
                price = data['price'],
                description = data['desc'],
                category = category,
                image = images[0],
            )
            for i in range (1, len(images)):
                image = ProductImage.objects.create(
                    product = product,
                    image = images[i]
            )

        return render(request, 'store/create_product.html')
    else:
        return HttpResponse("You are not allowed here")
</code>```

答:
For those who may have encountered a similar problem, the solution was incredibly obvious. I just forgot to add enctype="multipart/form-data" to my form (for uploading media files)</p>
```<code><form id="checkoutform" action="" method="post" enctype="multipart/form-data">
</code>```

Body:
I'm trying to create page to add new product with it's images in other model on my website using Djnago.
The length of the list of images I get is always 0 and i'm getting IndexError: list index out of range. I guess that i'm getting files from request not properly using images = request.FILES.getlist('images')

models.py

class Products(models.Model):
    product_name = models.CharField(
        max_length=255, verbose_name='Product name')
    product_slug = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    product_image = models.ImageField(
        default='image-placeholder.png', verbose_name='Image')
    creaton_date = models.DateTimeField(auto_now_add=True)
    brand = models.ForeignKey(
        Brands, verbose_name='Brand', on_delete=models.PROTECT)
    price = models.FloatField(verbose_name='Price')
    description = models.TextField(null=True, verbose_name='Description')
    category = models.ForeignKey(
        Categories, on_delete=models.CASCADE, verbose_name='Category')
    bought_count = models.IntegerField(null=True, default=0)

class ProductImage(models.Model):
    product = models.ForeignKey(Products, on_delete=models.CASCADE)
    image = models.ImageField()
    default = models.BooleanField(default=False)

    def __str__(self):
        return str(self.product)

template.html

<form id="checkoutform" action="" method="post">
{% csrf_token %}

        <input class="input" type="text" name="product-name" placeholder="Product name">

        <input class="input" type="text" name="brand" placeholder="Brand">

        <input class="input" type="number" name="price" placeholder="Price">

        <input class="input" type="file" multiple name="images" placeholder="Images">

        <input class="input" type="text" name="desc" placeholder="Description">

        <input class="input" type="text" name="category" placeholder="Category">

    <input type="submit" value="Submit">
</form>

views.py

def create_product(request):
    if request.user.is_superuser:
        if request.method == 'POST':
            data = request.POST
            images = request.FILES.getlist('images')
            brand = Brands.objects.get(name=data['brand'])
            category =  Categories.objects.get(name=data['category'])
            product = Products.objects.create(
                product_name = data['product-name'],
                brand=brand,
                price = data['price'],
                description = data['desc'],
                category = category,
                image = images[0],
            )
            for i in range (1, len(images)):
                image = ProductImage.objects.create(
                    product = product,
                    image = images[i]
            )

        return render(request, 'store/create_product.html')
    else:
        return HttpResponse("You are not allowed here")

Body:
For those who may have encountered a similar problem, the solution was incredibly obvious. I just forgot to add enctype="multipart/form-data" to my form (for uploading media files)

<form id="checkoutform" action="" method="post" enctype="multipart/form-data">


问:
Only accept integer (1 to 10) in user input (and give error if something else is written)
How can i secure that error will be presented if answer is something else than 1 to 10 in the first input "nr of cost items to be added" is written? (and promt should go back to "nr of cost items to be added").</p>
```<code>message_error = "Not correct input."

num = int(input("Nr of cost items to be added: ") or "3")

for n in range(num):

    while True:
        try:
            cost_items = int(input("Cost per item: "))
            break
        except ValueError:
            print(message_error)
            continue
</code>```

答:
Given that you have a small number of valid responses, you could check the input string against a set of valid string responses and only convert it to int once the input is one of the expected values:

```<code>while True:
    cost_item = input("Cost per item: ")
    if cost_item in map(str,range(1,11)):
        cost_item = int(cost_item)
        break
    print(message_error)
</code>```

Alternatively, you could modify the loop you already have so that it only exits when the number is in the expected range and gives the error messages for both an out-of-range and an invalid number:

```<code>while True:
    try:
        cost_items = int(input("Cost per item: "))
        if cost_items in range(1,11): break
    except ValueError: pass
    print(message_error)
</code>```

Body:
How can i secure that error will be presented if answer is something else than 1 to 10 in the first input "nr of cost items to be added" is written? (and promt should go back to "nr of cost items to be added").

message_error = "Not correct input."

num = int(input("Nr of cost items to be added: ") or "3")

for n in range(num):

    while True:
        try:
            cost_items = int(input("Cost per item: "))
            break
        except ValueError:
            print(message_error)
            continue

Body:
Given that you have a small number of valid responses, you could check the input string against a set of valid string responses and only convert it to int once the input is one of the expected values:

while True:
    cost_item = input("Cost per item: ")
    if cost_item in map(str,range(1,11)):
        cost_item = int(cost_item)
        break
    print(message_error)

Alternatively, you could modify the loop you already have so that it only exits when the number is in the expected range and gives the error messages for both an out-of-range and an invalid number:

while True:
    try:
        cost_items = int(input("Cost per item: "))
        if cost_items in range(1,11): break
    except ValueError: pass
    print(message_error)


问:
React/Typescript /VScode - an import path cannot end with a '.tsx' extension
I have a series of react projects which I have converted to typescript. Some of these use webpack, and some of them just use babel as they're libraries which are consumed by the other (webpack) projects/actual applications.

I've converted everything to typescript without problems, except in one non-webpack project, where I receive the error 'an import path cannot end with a .tsx extension', for example on

```<code>import LoadingLogo from '../ui/LoadingLogo.tsx';

</code>```

I can get round this by omitting the extension, or using // @ts-ignore, but neither of these are optimal solutions, since the project will be a mix of jsx and tsx while it is being refactored and I'd like to be able to see at a glance which file type is being used in the import.

The steps I've taken to convert the project to typescript are

Install typescript

Install @babel/preset-typescript

add

```<code>presets: [ @babel/preset-typescript ]
</code>```

to my babel.config.js

To make matters even more confusing, in one of the other (non-webpack) apps, I've got the same babel setup running and I'm not seeing this issue. Is there something obvious I'm missing? For reference, my babel.config in the project with the issue looks like this

```<code>module.exports = function(api) {
  api.cache(true);

  return {
    ignore: ['node_modules/**/*'],
    presets: [
      ['@babel/preset-typescript'],
      [
        '@babel/preset-env',
        {
          loose: true,
          targets: {
            node: 'current'
          }
        }
      ],
      '@babel/preset-react'
    ],
    env: {
      translations: {
        plugins: [
          'syntax-async-functions',
          '@babel/plugin-syntax-dynamic-import',
          'dynamic-import-node',
          [
            'react-intl',
            {
              messagesDir: './messages',
              enforceDescriptions: false
            }
          ]
        ]
      },
      production: {
        plugins: [
          'jsx-strip-ext',
          [
            'babel-plugin-styled-components',
            {
              ssr: true
            }
          ],
          'syntax-async-functions',
          '@babel/plugin-syntax-dynamic-import',
          'dynamic-import-node'
        ]
      },
      development: {
        plugins: [
          [
            'babel-plugin-styled-components',
            {
              ssr: true
            }
          ],
          'syntax-async-functions',
          '@babel/plugin-syntax-dynamic-import',
          'dynamic-import-node'
        ]
      }
    },
    plugins: [
      '@babel/plugin-transform-runtime',
      '@babel/plugin-syntax-dynamic-import',
      '@babel/plugin-syntax-import-meta',
      '@babel/plugin-proposal-class-properties',
      '@babel/plugin-proposal-json-strings',
      '@babel/plugin-transform-classes'
    ]
  };
};
</code>```

and my babel config in the non-webpack project without the issue looks like this

```<code>module.exports = function(api) {
  api.cache(true);

  return {
    presets: ['@babel/preset-typescript'],
    ignore: ['node_modules/**/*'],
    extends: 'myProject/babel.config.js',
    env: {
      production: {
        plugins: [
          [
            'module-resolver',
            {
              alias: {
                '^myProject/src/(.+)': 'myProject/lib/\\1'
              },
              extensions: ['.js', '.jsx'],
              stripExtensions: ['.js', '.jsx']
            }
          ],
          [
            'babel-plugin-styled-components',
            {
              ssr: true
            }
          ],
          'syntax-async-functions',
          '@babel/plugin-syntax-dynamic-import',
          'dynamic-import-node'
        ]
      },
      development: {
        plugins: [
          [
            'babel-plugin-styled-components',
            {
              ssr: true
            }
          ],
          'syntax-async-functions',
          '@babel/plugin-syntax-dynamic-import',
          'dynamic-import-node'
        ]
      }
    }
  };
};

</code>```

tsconfig.json for both projects looks like this

```<code>{
  "compilerOptions": {
    "module": "esnext",
    "outDir": "dist/",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "target": "ESNext",
    "allowJs": true,
    "checkJs": false,
    "jsx": "react",
    "pretty": true,
    "skipLibCheck": true,
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "lib": ["dom", "dom.iterable", "ESNext"],
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}
</code>```

My first instinct was to look at the module resolver plugin, but that didn't seem to make any difference. Is there something obvious I'm missing?

答: Sometimes this can be fixed by creating a next.config.js and a tsconfig.json at root level and re-run the application.</p>

Body:
I have a series of react projects which I have converted to typescript. Some of these use webpack, and some of them just use babel as they're libraries which are consumed by the other (webpack) projects/actual applications.

I've converted everything to typescript without problems, except in one non-webpack project, where I receive the error 'an import path cannot end with a .tsx extension', for example on

import LoadingLogo from '../ui/LoadingLogo.tsx';

I can get round this by omitting the extension, or using // @ts-ignore, but neither of these are optimal solutions, since the project will be a mix of jsx and tsx while it is being refactored and I'd like to be able to see at a glance which file type is being used in the import.

The steps I've taken to convert the project to typescript are

Install typescript

Install @babel/preset-typescript

add

presets: [ @babel/preset-typescript ]

to my babel.config.js

To make matters even more confusing, in one of the other (non-webpack) apps, I've got the same babel setup running and I'm not seeing this issue. Is there something obvious I'm missing? For reference, my babel.config in the project with the issue looks like this

module.exports = function(api) {
  api.cache(true);

  return {
    ignore: ['node_modules/**/*'],
    presets: [
      ['@babel/preset-typescript'],
      [
        '@babel/preset-env',
        {
          loose: true,
          targets: {
            node: 'current'
          }
        }
      ],
      '@babel/preset-react'
    ],
    env: {
      translations: {
        plugins: [
          'syntax-async-functions',
          '@babel/plugin-syntax-dynamic-import',
          'dynamic-import-node',
          [
            'react-intl',
            {
              messagesDir: './messages',
              enforceDescriptions: false
            }
          ]
        ]
      },
      production: {
        plugins: [
          'jsx-strip-ext',
          [
            'babel-plugin-styled-components',
            {
              ssr: true
            }
          ],
          'syntax-async-functions',
          '@babel/plugin-syntax-dynamic-import',
          'dynamic-import-node'
        ]
      },
      development: {
        plugins: [
          [
            'babel-plugin-styled-components',
            {
              ssr: true
            }
          ],
          'syntax-async-functions',
          '@babel/plugin-syntax-dynamic-import',
          'dynamic-import-node'
        ]
      }
    },
    plugins: [
      '@babel/plugin-transform-runtime',
      '@babel/plugin-syntax-dynamic-import',
      '@babel/plugin-syntax-import-meta',
      '@babel/plugin-proposal-class-properties',
      '@babel/plugin-proposal-json-strings',
      '@babel/plugin-transform-classes'
    ]
  };
};

and my babel config in the non-webpack project without the issue looks like this

module.exports = function(api) {
  api.cache(true);

  return {
    presets: ['@babel/preset-typescript'],
    ignore: ['node_modules/**/*'],
    extends: 'myProject/babel.config.js',
    env: {
      production: {
        plugins: [
          [
            'module-resolver',
            {
              alias: {
                '^myProject/src/(.+)': 'myProject/lib/\\1'
              },
              extensions: ['.js', '.jsx'],
              stripExtensions: ['.js', '.jsx']
            }
          ],
          [
            'babel-plugin-styled-components',
            {
              ssr: true
            }
          ],
          'syntax-async-functions',
          '@babel/plugin-syntax-dynamic-import',
          'dynamic-import-node'
        ]
      },
      development: {
        plugins: [
          [
            'babel-plugin-styled-components',
            {
              ssr: true
            }
          ],
          'syntax-async-functions',
          '@babel/plugin-syntax-dynamic-import',
          'dynamic-import-node'
        ]
      }
    }
  };
};

tsconfig.json for both projects looks like this

{
  "compilerOptions": {
    "module": "esnext",
    "outDir": "dist/",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "target": "ESNext",
    "allowJs": true,
    "checkJs": false,
    "jsx": "react",
    "pretty": true,
    "skipLibCheck": true,
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "lib": ["dom", "dom.iterable", "ESNext"],
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

My first instinct was to look at the module resolver plugin, but that didn't seem to make any difference. Is there something obvious I'm missing?


问:
Mongoose pass req object to middleware
I am writing  a middleware for mongoose that gets executed for every find object using pre query hook.

```<code>postSchema.pre('query', function(query, next) {
// I want to access the req.user object here
    query.populate('Category');
    next();
});
</code>```

I want to access req.user object inside the pre for every request made to the api server. How can i pass the object to the middleware?

Is it even possible?

https://github.com/Automattic/mongoose/issues/1931

I found the above but it doesnt talk about passing req object.

====================

Edit after some confusion about the question.

What i am trying to accomplish is to get the req.user role and the model name pass it to another function to get the query condition for find. So depending on the user role and the type of model accessed the query condition will change.

答:
Use

query.op to get the type of query

query.options  to get other options like {runValidators: true}

query._condition to get the conditions of the query

query._update  to get the incoming body

query._fields to get the selected fields,

You can also log the query to the terminal to see various options

Title: Mongoose pass req object to middleware

Body:
I am writing  a middleware for mongoose that gets executed for every find object using pre query hook.

postSchema.pre('query', function(query, next) {
// I want to access the req.user object here
    query.populate('Category');
    next();
});

I want to access req.user object inside the pre for every request made to the api server. How can i pass the object to the middleware?

Is it even possible?

https://github.com/Automattic/mongoose/issues/1931

I found the above but it doesnt talk about passing req object.

====================

Edit after some confusion about the question.

What i am trying to accomplish is to get the req.user role and the model name pass it to another function to get the query condition for find. So depending on the user role and the type of model accessed the query condition will change.


问:
How to reuse an existing python Enum in Django for choices?
Django has its own Enumeration types like model.TextChoices.

However, if you already use traditional python Enum objects in your codebase, it would be nice to reuse them for fields definition without redefining all the values.

Is there an elegant straightforward way to do this without too much boilerplate?

What I tried:

building a models.TextChoices class from the Enum seems impossible without manually declaring the values

building the choices parameter from the Enum instead of dealing with models.TextChoices but then things like obj.field == ENUM.XXX won't work because Enums don't do value comparisons like models.TextChoices does among other things.

Any elegant way to do this?

form enum import Enum

class YEAR_IN_SCHOOL(Enum):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    GRADUATE = 'GR'

class MyModel(models.Model):
    year_in_school = django_model_field_choices_using_enum(YEAR_IN_SCHOOL)

```
<p>So that:</p>
<ul>
<li>Comparaison with the ENUM works</li>
</ul>
<pre class="lang-py prettyprint-override"><code>my_model.year_in_school == YEAR_IN_SCHOOL.FRESHMAN
</code>```

Saving using the Enum works

my_model.year_in_school = YEAR_IN_SCHOOL.FRESHMAN
my_model.save()
```

答:
You can define it as regular django models.CharField with choices from your Enum

I.e:

```<code>class MyModel(models.Model):
    year_in_school = models.CharField(max_length=2,
        choices=[(x.value, x.name) for x in YEAR_IN_SCHOOL]
    )
</code>```

However, usage in this case will be a bit different (you need to specify .value on comparison/saving:

```<code>my_model.year_in_school == YEAR_IN_SCHOOL.FRESHMAN.value
</code>```

If you want to have it without .value - then remove Enum - i.e. make a plain class.

Then retrieving choices will be with inspect:

```<code>import inspect

class YEAR_IN_SCHOOL:
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    GRADUATE = 'GR'

choices = [(y, x) for x, y in inspect.getmembers(YEAR_IN_SCHOOL)]
</code>```

And assign/comparison will be the same as in your question

Body:
Django has its own Enumeration types like model.TextChoices.

However, if you already use traditional python Enum objects in your codebase, it would be nice to reuse them for fields definition without redefining all the values.

Is there an elegant straightforward way to do this without too much boilerplate?

What I tried:

building a models.TextChoices class from the Enum seems impossible without manually declaring the values

building the choices parameter from the Enum instead of dealing with models.TextChoices but then things like obj.field == ENUM.XXX won't work because Enums don't do value comparisons like models.TextChoices does among other things.

Any elegant way to do this?

form enum import Enum

class YEAR_IN_SCHOOL(Enum):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    GRADUATE = 'GR'

class MyModel(models.Model):
    year_in_school = django_model_field_choices_using_enum(YEAR_IN_SCHOOL)

So that:

Comparaison with the ENUM works

my_model.year_in_school == YEAR_IN_SCHOOL.FRESHMAN

Saving using the Enum works

my_model.year_in_school = YEAR_IN_SCHOOL.FRESHMAN
my_model.save()

Body:
You can define it as regular django models.CharField with choices from your Enum

I.e:

class MyModel(models.Model):
    year_in_school = models.CharField(max_length=2,
        choices=[(x.value, x.name) for x in YEAR_IN_SCHOOL]
    )

However, usage in this case will be a bit different (you need to specify .value on comparison/saving:

my_model.year_in_school == YEAR_IN_SCHOOL.FRESHMAN.value

If you want to have it without .value - then remove Enum - i.e. make a plain class.

Then retrieving choices will be with inspect:

import inspect

class YEAR_IN_SCHOOL:
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    GRADUATE = 'GR'

choices = [(y, x) for x, y in inspect.getmembers(YEAR_IN_SCHOOL)]

And assign/comparison will be the same as in your question


问:
Generating a random planar graph in python
I am looking to generate a random planar graph in python with around 20 vertices. I checked out this planar graph generator but two problems emerged:

The algorithm on the aforementioned GitHub project seems a bit too overkill to generate a random planar graph that doesn’t have those many edges

Because it’s meant to generate massive graph, that algorithm is very complex, and therefore also a bit clunky and difficult to use

With that said, is there a simpler way to randomly generate a relatively small planar graph in python?

答:
```<code>Create required number of nodes
Assign random x,y locations to the nodes.
WHILE nodes with no connected edges
    Select N a random node with no edge
    LOOP select M a different node at random
        IF edge N-M does NOT intersect previous edges
             Add N-M edge to graph
             BREAK out of LOOP
</code>```