问:
Vue.js src searching localhost instead of file system
I have an image whose src I'm trying to change when it is clicked.

```<code><b-img :id="favorite" src="~/static/svg/favorite.svg" @click="iconClicked(favorite)" right />
</code>```

And down under export default, I have

```<code>methods: {
        iconClicked(name: any) {
            (<HTMLImageElement> document.getElementById(name))!.src="~/static/svg/favoriteAlternate.svg";
        }
    }
</code>```

When I run my code at localhost:3000, I get a 404 error, and the code appears to be searching localhost:3000/~/static/svg/favoriteAlternate.svg instead of my local file system.

Why might this be? What should I do to fix this?

Thanks!

答:
There's a couple of things wrong here.

First, you shouldn't be manually interacting with the DOM like that – Vue "owns" the DOM and you should leave it to Vue to change.

When Vue compiles the template, it treats the src attribute specially by loading the file on disk it refers to through webpack. But then when you manually change the element's src attribute like that, the new file it references was never bundled by webpack so it won't load.

You need to require/import both images so they get bundled. Then swap between them using a binding on the src attribute.

Something like:

```
<pre class="lang-js prettyprint-override"><code>// These are not javascript files, however webpack will bundle them
// and export the correct src you should use to refer to them
import FavoriteImage from '~/static/svg/favorite.svg'
import FavoriteAltImage from '~/static/svg/favoriteAlternate.svg'

export default {
  data() {
    return {
      src: FavoriteImage,
    }
  },

  methods: {
    iconClicked() {
      this.src = FavoriteAltImage
    }
  }
}
</code>```

Body:
I have an image whose src I'm trying to change when it is clicked.

And down under export default, I have

methods: {
        iconClicked(name: any) {
            (<HTMLImageElement> document.getElementById(name))!.src="~/static/svg/favoriteAlternate.svg";
        }
    }

When I run my code at localhost:3000, I get a 404 error, and the code appears to be searching localhost:3000/~/static/svg/favoriteAlternate.svg instead of my local file system.

Why might this be? What should I do to fix this?

Thanks!

Body:
There's a couple of things wrong here.

First, you shouldn't be manually interacting with the DOM like that – Vue "owns" the DOM and you should leave it to Vue to change.

When Vue compiles the template, it treats the src attribute specially by loading the file on disk it refers to through webpack. But then when you manually change the element's src attribute like that, the new file it references was never bundled by webpack so it won't load.

You need to require/import both images so they get bundled. Then swap between them using a binding on the src attribute.

Something like:

<img :src="src">

// These are not javascript files, however webpack will bundle them
// and export the correct src you should use to refer to them
import FavoriteImage from '~/static/svg/favorite.svg'
import FavoriteAltImage from '~/static/svg/favoriteAlternate.svg'

export default {
  data() {
    return {
      src: FavoriteImage,
    }
  },

  methods: {
    iconClicked() {
      this.src = FavoriteAltImage
    }
  }
}


来源: stackexchange

问:
Nrwl nx command to generate lib for nest module
I am new to nrwl nx cli and extensively searched through their documentation and could not find the command to generate the nestjs module as lib rather than the actual module within app.

The reason why I want to create the nestjs module as lib is becuase I have got several nestjs applications in my mono repo and as per nrwl nx guidelines if I have to share code, which is module in my case, it has to be a lib.

Can anyone please share the command to do the following thing:-

Generate nestsjs module in libs

Create nestjs service for that module in libs folder

Any help is much appreciated.

答:
I've came across the same problematic lately.

While @Atul Chaudhary can solve the issue in a different way,
I could solve my problem following this comment

So basically, you just have to add a new nest-cli.json file to your nx workspace root folder and specify these basic informations according to your project's structure.

nest-cli.json basic example

{
  "collection": "@nestjs/schematics",
  "sourceRoot": "apps/api/src"
}
```

Hope it can help some people :)

ContentLicense: CC BY-SA 4.0

Body:
I've came across the same problematic lately.

While @Atul Chaudhary can solve the issue in a different way,
I could solve my problem following this comment

So basically, you just have to add a new nest-cli.json file to your nx workspace root folder and specify these basic informations according to your project's structure.

nest-cli.json basic example

{
  "collection": "@nestjs/schematics",
  "sourceRoot": "apps/api/src"
}

Hope it can help some people :)


问:
Laravel isn't downloading on GIT BASH
I am trying to download laravel using GIT BASH, with the prompt

```<code>    laravel new laravel
</code>```

This is what it keeps showing me. And Yes! I have composer and its installed in the same directory I tried to download laravel into.

答:
Check that you have added laravel is added to your path so its accessible from anywhere.

To test it try running the command like
path/to/installation/folder/laravel new laravel

If that works then you need to move the installation folder to /usr/local/bin/laravel so that its globally accessible

Title: Laravel isn't downloading on GIT BASH

Body:
I am trying to download laravel using GIT BASH, with the prompt

    laravel new laravel

This is what it keeps showing me. And Yes! I have composer and its installed in the same directory I tried to download laravel into.


问:
How to get table structure in CodeIgniter
I want to know the structure of a table. How I can do it in CodeIgniter. Using database class I got 'Invalid SQL Statement' error when I ran $this->db->query('desc mytable');

答:
Try:

```<code>$fields = $this->db->list_fields('table_name');
foreach ($fields as $field)
{
   echo $field;
}
</code>```

From manual

ContentLicense: CC BY-SA 3.0

Body:
Try:

$fields = $this->db->list_fields('table_name');
foreach ($fields as $field)
{
   echo $field;
}

From manual


问:
flutter: type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>'
I get this error while serializing my json.
I am not sure I understand the error, but I have figured out that the code never reaches Prices.fromJson if I try to print something there. As you can see I am using Firebase Cloud Functions to return a data with nested data objects, and I struggle to get them serialized.

Code:

```<code>class Price {
  final DateTime validFrom;
  final DateTime validTo;
  final double nokPerKwh;

  const Price({
    required this.validFrom,
    required this.validTo,
    required this.nokPerKwh,
  });

  factory Price.fromJson(Map<String, dynamic> json) {
    return Price(
      validFrom: DateTime.parse(json['validFrom']),
      validTo: DateTime.parse(json['validTo']),
      nokPerKwh: json['nokPerKwh'],
    );
  }
}

class Prices {
  final double now;
  final Price lowest;
  final Price highest;

  const Prices({
    required this.now,
    required this.lowest,
    required this.highest,
  });

  factory Prices.fromJson(Map<String, dynamic> json) {
    return Prices(
      now: json['now'],
      lowest: Price.fromJson(json['lowest']),
      highest: Price.fromJson(json['highest']),
    );
  }
}

class ShowerCost {
  final DateTime time;
  final int minutes;
  final Prices prices;

  const ShowerCost({
    required this.time,
    required this.minutes,
    required this.prices,
  });

  factory ShowerCost.fromJson(Map<String, dynamic> json) {
    print(json); <--- {minutes: 20, time: 2022-02-07T23:46:41.625Z, prices: {now: 11.848, highest: null, lowest: {nokPerKwh: 1.1848, validFrom: 2022-02-08T00:00:00+01:00, validTo: 2022-02-08T01:00:00+01:00}}}
    return ShowerCost(
      time: DateTime.parse(json['time']),
      minutes: json['minutes'],
      prices: Prices.fromJson(json['prices']),
    );
  }
}

Future<ShowerCost> getShowerCost() async {
  try {
    HttpsCallable callable =
        FirebaseFunctions.instance.httpsCallable('getShowerCost');
    final results = await callable.call(<String, dynamic>{
      'minutes': 20,
      'time': DateTime.now().toIso8601String(),
      'minHour': DateTime(2022, 2, 7, 0).toIso8601String(),
      'maxHour': DateTime(2022, 2, 7, 23).toIso8601String()
    });
    return ShowerCost.fromJson(results.data);
  } catch (error) {
    print(error);
    return Future.error(error);
  }
}
</code>```

答:
use this:</p>
```<code>final myMap = Map<String, dynamic>.from(results.data);
return Prices.fromJson(myMap);
</code>```

Body:
I get this error while serializing my json.
I am not sure I understand the error, but I have figured out that the code never reaches Prices.fromJson if I try to print something there. As you can see I am using Firebase Cloud Functions to return a data with nested data objects, and I struggle to get them serialized.

Code:

class Price {
  final DateTime validFrom;
  final DateTime validTo;
  final double nokPerKwh;

  const Price({
    required this.validFrom,
    required this.validTo,
    required this.nokPerKwh,
  });

  factory Price.fromJson(Map<String, dynamic> json) {
    return Price(
      validFrom: DateTime.parse(json['validFrom']),
      validTo: DateTime.parse(json['validTo']),
      nokPerKwh: json['nokPerKwh'],
    );
  }
}

class Prices {
  final double now;
  final Price lowest;
  final Price highest;

  const Prices({
    required this.now,
    required this.lowest,
    required this.highest,
  });

  factory Prices.fromJson(Map<String, dynamic> json) {
    return Prices(
      now: json['now'],
      lowest: Price.fromJson(json['lowest']),
      highest: Price.fromJson(json['highest']),
    );
  }
}

class ShowerCost {
  final DateTime time;
  final int minutes;
  final Prices prices;

  const ShowerCost({
    required this.time,
    required this.minutes,
    required this.prices,
  });

  factory ShowerCost.fromJson(Map<String, dynamic> json) {
    print(json); <--- {minutes: 20, time: 2022-02-07T23:46:41.625Z, prices: {now: 11.848, highest: null, lowest: {nokPerKwh: 1.1848, validFrom: 2022-02-08T00:00:00+01:00, validTo: 2022-02-08T01:00:00+01:00}}}
    return ShowerCost(
      time: DateTime.parse(json['time']),
      minutes: json['minutes'],
      prices: Prices.fromJson(json['prices']),
    );
  }
}

Future<ShowerCost> getShowerCost() async {
  try {
    HttpsCallable callable =
        FirebaseFunctions.instance.httpsCallable('getShowerCost');
    final results = await callable.call(<String, dynamic>{
      'minutes': 20,
      'time': DateTime.now().toIso8601String(),
      'minHour': DateTime(2022, 2, 7, 0).toIso8601String(),
      'maxHour': DateTime(2022, 2, 7, 23).toIso8601String()
    });
    return ShowerCost.fromJson(results.data);
  } catch (error) {
    print(error);
    return Future.error(error);
  }
}

Body:
use this:

final myMap = Map<String, dynamic>.from(results.data);
return Prices.fromJson(myMap);


问:
IndexError in a recursive function inside a Class
I am having issues where I want the user to input a number that is 1-9. If they enter a number outside the range, I want them to get a message "Please enter a valid number" and to be able to enter another number. If they enter say "145" it will ask them to enter a valid number just like I want (yay!). Then when they enter, lets say "4", an IndexError: list out of range pops up. self.board is a list with 9 elements.

My thought is that python still trying to use the first number, but if I print the number before IndexError line, it shows the correct number, '4'. Any help is appreciated!

Here is my code:

```<code>    self.board=[
        " "," "," ",
        " "," "," ",
        " "," "," "
    ]
def turn(self, player):
   result=int(input("Choose your next move \n"))
   if result < 1 or result>9:
        print("Please enter a valid number (1-9)")
        self.turn(player)

   if self.board[result-1] == " ":
        self.board[result-1] = player
   else:
        print("This spot has already been chosen. Please choose another place for your next move")
        self.turn(player)
</code>```

答:
The problem here is that your method is recursive and execution continues after your recursion collapses. You have two if statements in a row. When the first one is true, it recurses but when that recursed call finishes it continues execution with the bad input. You need to make the second if statement an elif instead. That way after your recursed function call finishes nothing else is executed.

Try this instead:

    self.board=[
        " "," "," ",
        " "," "," ",
        " "," "," "
    ]
def turn(self, player):
   result=int(input("Choose your next move \n"))
   if result < 1 or result>9:
        print("Please enter a valid number (1-9)")
        self.turn(player)

   elif self.board[result-1] == " ":
        self.board[result-1] = player
   else:
        print("This spot has already been chosen. Please choose another place for your next move")
        self.turn(player)
```

Body:
I am having issues where I want the user to input a number that is 1-9. If they enter a number outside the range, I want them to get a message "Please enter a valid number" and to be able to enter another number. If they enter say "145" it will ask them to enter a valid number just like I want (yay!). Then when they enter, lets say "4", an IndexError: list out of range pops up. self.board is a list with 9 elements.

My thought is that python still trying to use the first number, but if I print the number before IndexError line, it shows the correct number, '4'. Any help is appreciated!

Here is my code:

    self.board=[
        " "," "," ",
        " "," "," ",
        " "," "," "
    ]
def turn(self, player):
   result=int(input("Choose your next move \n"))
   if result < 1 or result>9:
        print("Please enter a valid number (1-9)")
        self.turn(player)

   if self.board[result-1] == " ":
        self.board[result-1] = player
   else:
        print("This spot has already been chosen. Please choose another place for your next move")
        self.turn(player)


问:
Is F# Constructed Type syntax special?
I was curious about F#'s "constructed type" syntax. It's documented here.

type-argument generic-type-name

or

generic-type-name

With the following examples:

int option

string list

int ref

option<int>

list<string>

ref<int>

Dictionary<int, string>

I was curious if there's anything special about the "backwards" syntax, with the parameter before the type, or if it's just sugar for generic types with one parameter. The following is valid:

type 'a MyOption = // MyOption<'a> also works
  | MySome of 'a
  | MyNone
```

But I could not get it to work with multiple type parameters. Why do F# developers prefer this syntax for types with one parameter? Is it possible or desirable to make it work with two?

答:
The backwards syntax is a legacy from OCaml. Personally, I never use it. If you really want to, you can make it work with multiple type arguments like this:

type MyMap = (int, string) Map
```

However, this generates a pointed warning (that might soon become an error):

This construct is for ML compatibility. The syntax '(typ,...,typ) ident' is not used in F# code. Consider using 'ident<typ,...,typ>' instead. You can disable this warning by using '--mlcompatibility' or '--nowarn:62'.

Bottom line, I would recommend always using .NET syntax instead: MyOption<'a> instead of 'a MyOption.

Title: Is F# Constructed Type syntax special?

Body:
I was curious about F#'s "constructed type" syntax. It's documented here.

type-argument generic-type-name

or

generic-type-name

With the following examples:

int option

string list

int ref

option<int>

list<string>

ref<int>

Dictionary<int, string>

I was curious if there's anything special about the "backwards" syntax, with the parameter before the type, or if it's just sugar for generic types with one parameter. The following is valid:

type 'a MyOption = // MyOption<'a> also works
  | MySome of 'a
  | MyNone

But I could not get it to work with multiple type parameters. Why do F# developers prefer this syntax for types with one parameter? Is it possible or desirable to make it work with two?

Body:
The backwards syntax is a legacy from OCaml. Personally, I never use it. If you really want to, you can make it work with multiple type arguments like this:

type MyMap = (int, string) Map

However, this generates a pointed warning (that might soon become an error):

This construct is for ML compatibility. The syntax '(typ,...,typ) ident' is not used in F# code. Consider using 'ident<typ,...,typ>' instead. You can disable this warning by using '--mlcompatibility' or '--nowarn:62'.

Bottom line, I would recommend always using .NET syntax instead: MyOption<'a> instead of 'a MyOption.


问:
Can't provide version ranges in the maven dependency management import scope
I have a large java project managed using maven.
We are using Maven 3 for management (specifically  3.6.0).

In the project, there is a sub=project with a runtime-v5.pom.xml.
In said pom, there is a version property

```<code><properties>
    <platform-v5.version>73.2.05</platform-v5.version>
</properties>
</code>```

Which is used later in the file

```<code><dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.company.thing.platform</groupId>
            <artifactId>platform-parent</artifactId>
            <version>${platform-v5.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>com.company.release</groupId>
            <artifactId>platform-v5</artifactId>
            <version>${platform-v5.version}</version>
            <type>resolved-pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

My goal is to get maven to pull in the most recent version of platform and I don't want to update the version in this file every time. I thought that changing the specific version to a range would allow the project to always pull in the most recent version in accordance with the given range.

When the platform-v5.version is set to a specific existing version, it builds just fine, but when setting the version to a range such as [73.2.05,), I get errors such as

```<code>[INFO] Scanning for projects...
[INFO] Downloading from all_global_universal: https://nexus.company/platform-parent/%5B73.2.05,).pom
[ERROR] Some problems were encountered while processing the POMs:
[ERROR] Non-resolvable import POM: Could not find artifact com.company.thing.platform:platform-parent:pom:[73.2.05,) in all_global_universal (https://nexus.company/content/groups/all_global_universal) @ com.company:runtime-v5:[unknown-version], path/to/runtime-v5.pom.xml, line XX, column YY
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.company:runtime-v5:1.0.2 (path/to/runtime-v5.pom.xml) has 1 error
[ERROR]     Non-resolvable import POM: Could not find artifact com.company.thing.platform:platform-parent:pom:[73.2.05,) in all_global_universal (https://nexus.company/content/groups/all_global_universal) @ com.company:runtime-v5:[unknown-version], path/to/runtime-v5.pom.xml, line XX, column YY -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
</code>```

Essentially, I want to know: Why can't you provide version ranges in the maven dependency management import scope?

答:
This is a duplicate of Using maven dependency management import scope with version ranges

This Maven issue was resolved and will be released in Maven 4.0.0: https://issues.apache.org/jira/browse/MNG-4463

Body:
I have a large java project managed using maven.
We are using Maven 3 for management (specifically  3.6.0).

In the project, there is a sub=project with a runtime-v5.pom.xml.
In said pom, there is a version property

<properties>
    <platform-v5.version>73.2.05</platform-v5.version>
</properties>

Which is used later in the file

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.company.thing.platform</groupId>
            <artifactId>platform-parent</artifactId>
            <version>${platform-v5.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>com.company.release</groupId>
            <artifactId>platform-v5</artifactId>
            <version>${platform-v5.version}</version>
            <type>resolved-pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

My goal is to get maven to pull in the most recent version of platform and I don't want to update the version in this file every time. I thought that changing the specific version to a range would allow the project to always pull in the most recent version in accordance with the given range.

When the platform-v5.version is set to a specific existing version, it builds just fine, but when setting the version to a range such as [73.2.05,), I get errors such as

[INFO] Scanning for projects...
[INFO] Downloading from all_global_universal: https://nexus.company/platform-parent/%5B73.2.05,).pom
[ERROR] Some problems were encountered while processing the POMs:
[ERROR] Non-resolvable import POM: Could not find artifact com.company.thing.platform:platform-parent:pom:[73.2.05,) in all_global_universal (https://nexus.company/content/groups/all_global_universal) @ com.company:runtime-v5:[unknown-version], path/to/runtime-v5.pom.xml, line XX, column YY
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.company:runtime-v5:1.0.2 (path/to/runtime-v5.pom.xml) has 1 error
[ERROR]     Non-resolvable import POM: Could not find artifact com.company.thing.platform:platform-parent:pom:[73.2.05,) in all_global_universal (https://nexus.company/content/groups/all_global_universal) @ com.company:runtime-v5:[unknown-version], path/to/runtime-v5.pom.xml, line XX, column YY -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException

Essentially, I want to know: Why can't you provide version ranges in the maven dependency management import scope?


问:
How do I start with A-Frame?
I have understanding of how to start a basic scene but, have NO clue on how to start coding within the browser as suggested in installation process.  Can you please kindly get back to me and tell me how I am able to edit my work on browser and see changes in real time?  Thanks</p>

答:
I recommend reading the Getting Stared section in the docs:

https://aframe.io/docs/1.3.0/introduction/

Easiest way to start in browser is by remixing the Glitch hello world as described in the link above.

Title: How do I start with A-Frame?


问:
Visual Web Part with referenced DLL not checking GAC
I have a SharePoint project with a visual web part (WebPartA inherits from OtherWebPartC) - the web part references two DLL's, (ClassLibraryB and OtherWebPartC), and they are included in the package, set to be deployed to GAC.

When I deploy the project, the DLL's are successfully deployed to GAC, and the web part successfully shows up in the gallery in SharePoint.

However, when I try to add the visual web part (WebPartA) to a page, the page breaks - I enabled error display and stack trace - it says it can't find ClassLibraryB.dll.  I used fuslogvw and procmon to determine that it was trying to load the DLL from typical locations (Virtual directory/bin, temporary asp.net folders), even though the DLL was not in these locations (but as I said, it was successfully deployed to GAC).

So I manually added ClassLibraryB.dll and OtherWebPart.dll to virtual directory/bin, and it worked successfully.

How do I get SharePoint to see the ClassLibraryB.dll and OtherWebPart.dll in the GAC?  Or do I have to manually deploy the DLL to the site's Virtual Directory/bin?

答:
Just a heads up to all of you digging through these ancient questions...
I stumbled upon this issue today, so i decided to leave a comment in order to claridy things.
Most of the info can be taken from this great article by Waldek Mastykarz

Using the Project you would like to package the Controls project including the SafeControls entries.

Double click on the Package project item and the Package Designer will open.

In the Package Designer you click the Advanced button. In the Advanced view you click the Add button and choose the Add Assembly from Project Output (the options are different in VS17 but they are similar)… menu option.

From the Source Project dropdown list you choose your other Project.

Then in the Safe Controls section, you click the Click here to add a new item button to add a new Safe Controls entry.

Use the $SharePoint.Project.AssemblyFullName$ token so that you can specify that you want to include the fully qualified name of your assembly.


问:
why some textures did not load correctly in vedo library in python?
I'm trying to load some .obj files with their texture by vedo lib:

```<code>from vedo import *
from transparent import *

mesh = Mesh("3d/gol1/raw_model.obj")#load 3d model
mesh.texture("3d/gol1/texture.png")#load texture on 3d mode

plt = Plotter(offscreen=True)
plt += mesh
plt.show().screenshot("hi.png")#save as png
</code>```

but in some cases, like the image below, the texture did not load correctly:
the correct one:

and we see here the result after loading texture:

答:
I'm not completely sure why that happens but depth peeling fixes it..:

from vedo import *
settings.useDepthPeeling = True
msh = Mesh("normalized_model.obj").texture("texture.png")
show(msh, axes=1)
```

Body:
I'm trying to load some .obj files with their texture by vedo lib:

from vedo import *
from transparent import *

mesh = Mesh("3d/gol1/raw_model.obj")#load 3d model
mesh.texture("3d/gol1/texture.png")#load texture on 3d mode

plt = Plotter(offscreen=True)
plt += mesh
plt.show().screenshot("hi.png")#save as png

but in some cases, like the image below, the texture did not load correctly:
the correct one:

and we see here the result after loading texture:


问:
Why is this not outside of the nav Bar
so I am pretty new to development and come across a problem, I think I am missing somthing but I can't tell. So I am building a nav bar and then a drop down menu. I believe that the li is in the ul so that why it is not coming out of it. So how could I fix this. If you know any website that would be good let me know thank you

Code:
https://codepen.io/Giannilmgc/pen/JjrgZdr?editors=1111
Output:
https://codepen.io/Giannilmgc/full/JjrgZdr

To see what wrong keep your cursor over the to do tab and scroll down

@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300&display=swap");

/* Here is the body style where we change the background */
body {
  background: linear-gradient(135deg, #36454f 0%, #ffdd3c 100%);
  margin: 5px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: auto;
  background-color: white;
  border-radius: 50px;
}

li {
  float: left;
  width: 16.667%;
  transition-duration: 1s;
}

li a {
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  transition-duration: 1s;
}
li:hover {
  background-color: black;
}

li a:hover {
  background-color: #36454f;
  color: white;
}
#homepageLink {
  background-color: #cccccc;
}

.dropdown {
  position: relative;
  display: inline-block;
}

ul li ul {
  display: none;
  position: absolute;
  background-color: #cccccc;
  width: 20%;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 10;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #36454f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>

  <title> My Site </title>
  <link rel="stylesheet" href="CSS/Homepage-Css.css" />
</head>

<body>

  <body>

    <div>
      <ul>
        <li>HomePage</li>
        <li>Journal</li>
        <li>Calander </li>
        <li class="dropdown">To do
          <ul class="dropdown-content">
            Latin
            Scince
            Ela

          </ul>
        </li>
        <li>Service</li>
        <li>Contact</li>

      </ul>
    </div>

    <div class="time">
      <span id="display_ct"></span>
  </body>
  <!-- Adding Script to the bottom ... Very Imporantent  -->
  <script src="Javascript/Homepage-Java.js"></script></code>```

Thank you

答:
you put display none on the dropdown and try to show it when its hover on li.
but when the mouse go out from li the display:none on dropdown is return.
try to make it with after pseudo element and change the code from .dropdown { position: relative; display: inline-block; }
to:li:after.dropdown { position: relative; display: inline-block; }
it will work but not an ideal, improve it with css

Title: Why is this not outside of the nav Bar

Body:
so I am pretty new to development and come across a problem, I think I am missing somthing but I can't tell. So I am building a nav bar and then a drop down menu. I believe that the li is in the ul so that why it is not coming out of it. So how could I fix this. If you know any website that would be good let me know thank you

Code:
https://codepen.io/Giannilmgc/pen/JjrgZdr?editors=1111
Output:
https://codepen.io/Giannilmgc/full/JjrgZdr

To see what wrong keep your cursor over the to do tab and scroll down

@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300&display=swap");

/* Here is the body style where we change the background */
body {
  background: linear-gradient(135deg, #36454f 0%, #ffdd3c 100%);
  margin: 5px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: auto;
  background-color: white;
  border-radius: 50px;
}

li {
  float: left;
  width: 16.667%;
  transition-duration: 1s;
}

li a {
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  transition-duration: 1s;
}
li:hover {
  background-color: black;
}

li a:hover {
  background-color: #36454f;
  color: white;
}
#homepageLink {
  background-color: #cccccc;
}

.dropdown {
  position: relative;
  display: inline-block;
}

ul li ul {
  display: none;
  position: absolute;
  background-color: #cccccc;
  width: 20%;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 10;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #36454f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}

  <title> My Site </title>
  <link rel="stylesheet" href="CSS/Homepage-Css.css" />

HomePage

Journal

Calander

To do

            Latin
            Scince
            Ela

Service

Contact

Thank you


问:
preg_match words followed by numbers
I've got the following string:

```<code>Query_time: 77.571216 Lock_time: 2.793139 Rows_sent: 20 Rows_examined: 4654071
</code>```

How would i go about placing each number into a variable?
eg:

```<code>$query_time    = 77.571216;
$lock_time     = 2.793139;
$rows_sent     = 20;
$rows_examined = 4654071;
</code>```

答:
```<code>$str = 'Query_time: 77.571216 Lock_time: 2.793139 Rows_sent: 20 Rows_examined: 4654071';
list($null, $query_time, $lock_time, $rows_sent, $rows_examined) = preg_split('/\S+:/',$str);
</code>```

Title: preg_match words followed by numbers

Body:
I've got the following string:

Query_time: 77.571216 Lock_time: 2.793139 Rows_sent: 20 Rows_examined: 4654071

How would i go about placing each number into a variable?
eg:

$query_time    = 77.571216;
$lock_time     = 2.793139;
$rows_sent     = 20;
$rows_examined = 4654071;


问:
JavaScript: How can you select random elements from an array without allowing duplicates?
I am looking to randomly select a number from this array WITHOUT duplicates. There can only be two possibilities for each number as shown in the array, select up to a maximum of 6.
This works to select a random number but allows duplicates...

```<code>const smallNums = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10];

const randomSmallNumArr = smallNums[Math.floor(Math.random() * smallNums.length)];
</code>```

When using the splice() method, each time I generate a number based on a random index, it's removed but shows up again in the array the next time a random is generated

答:
Use a Set to get the unique items in the array.

const smallNums = [...new Set([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10])]

const randomSmallNumArr = smallNums[Math.floor(Math.random() * smallNums.length)];
console.log(randomSmallNumArr)```

Body:
I am looking to randomly select a number from this array WITHOUT duplicates. There can only be two possibilities for each number as shown in the array, select up to a maximum of 6.
This works to select a random number but allows duplicates...

const smallNums = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10];

const randomSmallNumArr = smallNums[Math.floor(Math.random() * smallNums.length)];

When using the splice() method, each time I generate a number based on a random index, it's removed but shows up again in the array the next time a random is generated


问:
Make CSS Background disappear onclick with React
The style within the div creates a red box. Upon clicking I want to remove it. Have tried implementing state but it wasn't working.

import React, { Component } from "react";

class ClickMe extends Component {
  render() {
    return (

Disapearing Box

Click the Box, I dare you

    );
  }
}
export default ClickMe;```
</div>
</div>
</p>
```    );
  }
}
export default ClickMe;
```

答:
try it:</p>
```<code>import React, { useState } from "react";

const ClickMe =() => {
  const [active, setActive] = useState(false)

  return (
    <div onClick={() => setActive(!active)}>
      <h1>Disapearing Box</h1>
      <h3>Click the Box, I dare you</h3>
      <div
        style={{
          height: "400px",
          width: "400px",
          background: active ? "none" : "#ef8989",
          margin: "auto",
        }}
      ></div>
    </div>
  );
}

export default ClickMe;
</code>```

Body:
The style within the div creates a red box. Upon clicking I want to remove it. Have tried implementing state but it wasn't working.

import React, { Component } from "react";

class ClickMe extends Component {
  render() {
    return (

Disapearing Box

Click the Box, I dare you

    );
  }
}
export default ClickMe;

    );
  }
}
export default ClickMe;

Body:
try it:

import React, { useState } from "react";

const ClickMe =() => {
  const [active, setActive] = useState(false)

  return (
    <div onClick={() => setActive(!active)}>
      <h1>Disapearing Box</h1>
      <h3>Click the Box, I dare you</h3>
      <div
        style={{
          height: "400px",
          width: "400px",
          background: active ? "none" : "#ef8989",
          margin: "auto",
        }}
      ></div>
    </div>
  );
}

export default ClickMe;


问:
How would i make it so that when i copy and paste the command button it will make the code apply to the newly pasted section instead of the older one?
In excel
For exampple: the code i have currently is as you see below.

I want to be able to copy and paste this form:

into the next rows and have the code apply in those new rows as well (when i click the macro button). Currently if i paste the form to a new row and use the buttons, it will only apply to the first form that i made these buttons on.

```<code>Sub APPROVED5K()
' APPROVED5K Macro

    Range("O5:Q7").Select
    ActiveCell.FormulaR1C1 = "APPROVED"
    Range("O9:Q9").Select
    ActiveCell.FormulaR1C1 = "5000"
    Range("O5:Q7").Select
End Sub
</code>```

答:
It's sometimes easier to use hyperlinks instead of buttons if you want to be able to have multiple copies and easily be able to copy/paste existing ranges with buttons (ie. without the buttons drifting off their locations, or if you want to be able to handle sorting of the data for example).

Eg: insert this function in a regular module

```<code>Function LinkMe()
    Set LinkMe = Application.ThisCell
End Function
</code>```

All this does is serve as a Target for the hyperlink, so the selection doesn't jump around when the user clicks on a link. Hyperlinks need to link to something, so this just returns the range for the clicked-on link.

Create your "action" links in place of buttons, using Insert > Link with appropriate Text to display values ("Approve", 'Deny" etc) and use #LinkMe for the Address.  Note you can't use the HYPERLINK() formula to create links if you want to use them this way.

Now you can set up the code to respond to click on the links. Right-click the tab for the sheet where your links will be, and select "View Code". Paste the Sub below into that code module:

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    HandleLink Target 'call the handler in a regular module
End Sub
```
<p>Note <em>as an alternative to the above</em>, there's also a Workbook-level event handler if you want to handle link clicks regardless of the worksheet, so in the <code>ThisWorkbook</code> code module you could put this:</p>
<pre class="lang-vb prettyprint-override"><code>Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
    HandleLink Target 'call the handler
End Sub
</code>```

Then in a regular module you create the HandleLink method called by the event handler above. This method get the clicked link and decides what action should be taken, using the link's TextToDisplay (eg. "Approve" etc) and Range properties.

'Called from `Worksheet_FollowHyperlink`
Sub HandleLink(lnk As Hyperlink)
    Dim txt As String, c As Range, rng As Range

    txt = lnk.TextToDisplay    'what's the link disply text
    Set c = lnk.Range.Cells(1) 'and where is it located

    Debug.Print "Clicked link '" & txt & "' in " & c.Address & _
                " on " & c.Parent.Name

    If txt = "Approve" Then
        'locate a range *relative to the link cell* and do something
        '  eg: two columns to the right and 2 rows x 5 columns
        Set rng = c.Offset(0, 2).Resize(2, 5)
        rng.Value = "OK" 'populate that range
    End If

    If txt = "Deny" Then
        'take some other action here...
    End If

    'etc etc for other link texts

End Sub
```

Body:
In excel
For exampple: the code i have currently is as you see below.

I want to be able to copy and paste this form:

into the next rows and have the code apply in those new rows as well (when i click the macro button). Currently if i paste the form to a new row and use the buttons, it will only apply to the first form that i made these buttons on.

Sub APPROVED5K()
' APPROVED5K Macro

    Range("O5:Q7").Select
    ActiveCell.FormulaR1C1 = "APPROVED"
    Range("O9:Q9").Select
    ActiveCell.FormulaR1C1 = "5000"
    Range("O5:Q7").Select
End Sub

Body:
It's sometimes easier to use hyperlinks instead of buttons if you want to be able to have multiple copies and easily be able to copy/paste existing ranges with buttons (ie. without the buttons drifting off their locations, or if you want to be able to handle sorting of the data for example).

Eg: insert this function in a regular module

Function LinkMe()
    Set LinkMe = Application.ThisCell
End Function

All this does is serve as a Target for the hyperlink, so the selection doesn't jump around when the user clicks on a link. Hyperlinks need to link to something, so this just returns the range for the clicked-on link.

Create your "action" links in place of buttons, using Insert > Link with appropriate Text to display values ("Approve", 'Deny" etc) and use #LinkMe for the Address.  Note you can't use the HYPERLINK() formula to create links if you want to use them this way.

Now you can set up the code to respond to click on the links. Right-click the tab for the sheet where your links will be, and select "View Code". Paste the Sub below into that code module:

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    HandleLink Target 'call the handler in a regular module
End Sub

Note as an alternative to the above, there's also a Workbook-level event handler if you want to handle link clicks regardless of the worksheet, so in the ThisWorkbook code module you could put this:

Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
    HandleLink Target 'call the handler
End Sub

Then in a regular module you create the HandleLink method called by the event handler above. This method get the clicked link and decides what action should be taken, using the link's TextToDisplay (eg. "Approve" etc) and Range properties.

'Called from `Worksheet_FollowHyperlink`
Sub HandleLink(lnk As Hyperlink)
    Dim txt As String, c As Range, rng As Range

    txt = lnk.TextToDisplay    'what's the link disply text
    Set c = lnk.Range.Cells(1) 'and where is it located

    Debug.Print "Clicked link '" & txt & "' in " & c.Address & _
                " on " & c.Parent.Name

    If txt = "Approve" Then
        'locate a range *relative to the link cell* and do something
        '  eg: two columns to the right and 2 rows x 5 columns
        Set rng = c.Offset(0, 2).Resize(2, 5)
        rng.Value = "OK" 'populate that range
    End If

    If txt = "Deny" Then
        'take some other action here...
    End If

    'etc etc for other link texts

End Sub


问:
Improving handwriting OCR on cloud vision?
I was trying to analyze the following image, and convert it to text, using Google Cloud Vision

I realize that it has low quality, and that some words aren't exactly uniquely identifiable. My current strategy was to threshold and splice into sections using numpy and opencv. Then, for each section I use the document_text_detection function to get the results for each section of the sentence above. However, this gives extremely poor quality. I am not looking for 100% accuracy, but just something that looks fairly close to what is written in this line. Any suggestions to improve the result? Are there other tools than GCV that could be useful?

答:
Vision API has a new OCR model available for opt-in. You can try it out by specifying the model "builtin/latest".

More info here: https://cloud.google.com/vision/docs/release-notes#January_21_2022


问:
Log4j2.xml - Queue size and discardingThreshold
how can we specify the queue size and discardingThreshold for Asynchronous appenders in log4j2.xml

Below is sample snippet from logback.xml.

```<code> <appender name="appender1" class="ch.qos.logback.classic.AsyncAppender">
     <queueSize>500</queueSize>
     <discardingThreshold>0</discardingThreshold>
     <appender-ref ref="one" />
    </appender>
</code>```

I need to implement similar functionality in log4j2.xml

答:
You can configure the queue size on property bufferSize of AsyncAppender.

log4j2.yaml

```<code>Configuration:
  appenders:
    Console:
      name: CONSOLE
      PatternLayout:
        Pattern: %d{yyyy/MM/dd HH:mm:ss.SSS} [%t] [%-5p] %c{36} - %m%n
    Async:
      name: ASYNC-CONSOLE
      bufferSize: 1
      blocking: false
      AppenderRef:
        ref: CONSOLE
      ...
</code>```

or

log4j2.xml

```<code><Configuration>
  <Appenders>
    <Console name="CONSOLE">
      <PatternLayout>
        <Pattern>%d{yyyy/MM/dd HH:mm:ss.SSS} [%t] [%-5p] %c{36} - %m%n</Pattern>
      </PatternLayout>
    </File>
    <Async name="ASYNC-CONSOLE" bufferSize="1">
      <AppenderRef ref="CONSOLE"/>
    </Async>
  </Appenders>
  ...
</code>```

With other property, discardingThreshold, this behavior on log4j2 is log synchronously going direct to appender when the queue is full, you can set the propertiess log4j2.AsyncQueueFullPolicy with "Discard", in other words, log4j since 2.10, doesn't discard events by default, like      <discardingThreshold>0</discardingThreshold> on logback.

See log4j2 docs.

Body:
how can we specify the queue size and discardingThreshold for Asynchronous appenders in log4j2.xml

Below is sample snippet from logback.xml.

 <appender name="appender1" class="ch.qos.logback.classic.AsyncAppender">
     <queueSize>500</queueSize>
     <discardingThreshold>0</discardingThreshold>
     <appender-ref ref="one" />
    </appender>

I need to implement similar functionality in log4j2.xml

Body:
You can configure the queue size on property bufferSize of AsyncAppender.

log4j2.yaml

Configuration:
  appenders:
    Console:
      name: CONSOLE
      PatternLayout:
        Pattern: %d{yyyy/MM/dd HH:mm:ss.SSS} [%t] [%-5p] %c{36} - %m%n
    Async:
      name: ASYNC-CONSOLE
      bufferSize: 1
      blocking: false
      AppenderRef:
        ref: CONSOLE
      ...

or

log4j2.xml

<Configuration>
  <Appenders>
    <Console name="CONSOLE">
      <PatternLayout>
        <Pattern>%d{yyyy/MM/dd HH:mm:ss.SSS} [%t] [%-5p] %c{36} - %m%n</Pattern>
      </PatternLayout>
    </File>
    <Async name="ASYNC-CONSOLE" bufferSize="1">
      <AppenderRef ref="CONSOLE"/>
    </Async>
  </Appenders>
  ...

With other property, discardingThreshold, this behavior on log4j2 is log synchronously going direct to appender when the queue is full, you can set the propertiess log4j2.AsyncQueueFullPolicy with "Discard", in other words, log4j since 2.10, doesn't discard events by default, like      <discardingThreshold>0</discardingThreshold> on logback.

See log4j2 docs.


问:
If a variable is created within the scope of a function that returns a function that uses that variable. Is it possible to acces that variable outside
```<code>function creatPrintNumFunction()
{
  var num= 12;
  return function printNum()
  {
     console.log(num);
  }
}

 var printer = creatPrintNumFunction();
printer.num =13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();

</code>```

So how can I get this code to print 13 instead of 12 most importantly with out changing any of the code of the createPrintNumFunction().

For more context on what I really need to use this theory for. I'm using an external module express-sessions in node.js that I don't want to change. There is this 'store' variable where all the sessions are stored that I need to access only problem is that it's created within a function.There is another way i could access it but it's not really convenient

答:
There is this 'store' variable where all the sessions are stored that I need to access only problem is that it's created within a function. There is another way i could access it but it's not really convenient

No there is no way to access store without modifying the code. And you shouldn't modify the code of an external module, because store is likely made inaccessible for a reason. Changing the code might result in a code base that would prevent you from updating the express-sessions.

Having the need to do that sounds like an XY-Problem.

If it is your code and you want to allow the variable to be accessed there are different ways to do that. You for sure could move var num outside of creatPrintNumFunction (as described in the answer of alonealgorithm but that breaks the encapsulation you had before. Whether that is a good idea or not depends on the actual use case. But you need to be aware that if you do that that every "print" function returned from creatPrintNumFunction then uses the same variable.

Let's say you don't want to move num out of the scope of creatPrintNumFunction because every "print" function returned from creatPrintNumFunction should have its own num variable.

What then you could do is to create another function (e.g. set) within creatPrintNumFunction that can change num and assign this function as a property to the function you return from creatPrintNumFunction.

function creatPrintNumFunction() {
  var num = 12;

  // both "set" and "printNum" create here
  // have a closure over the same "num" variable
  function set(val) {
    num = val;
  }

  function printNum() {
    console.log(num);
  }

  // the "set" function is assigned as a parameter to your
  // printNum function
  printNum.set = set;

  return printNum;
}

var printerA = creatPrintNumFunction();
var printerB = creatPrintNumFunction();
printerA.set(13)
printerB.set(23)
printerA();
printerB();```

The advantage of this approach is that you don't expose num and you can control in your set function how/if num can be changed.

Body:
function creatPrintNumFunction()
{
  var num= 12;
  return function printNum()
  {
     console.log(num);
  }
}

 var printer = creatPrintNumFunction();
printer.num =13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();

So how can I get this code to print 13 instead of 12 most importantly with out changing any of the code of the createPrintNumFunction().

For more context on what I really need to use this theory for. I'm using an external module express-sessions in node.js that I don't want to change. There is this 'store' variable where all the sessions are stored that I need to access only problem is that it's created within a function.There is another way i could access it but it's not really convenient

Body:
There is this 'store' variable where all the sessions are stored that I need to access only problem is that it's created within a function. There is another way i could access it but it's not really convenient

No there is no way to access store without modifying the code. And you shouldn't modify the code of an external module, because store is likely made inaccessible for a reason. Changing the code might result in a code base that would prevent you from updating the express-sessions.

Having the need to do that sounds like an XY-Problem.

If it is your code and you want to allow the variable to be accessed there are different ways to do that. You for sure could move var num outside of creatPrintNumFunction (as described in the answer of alonealgorithm but that breaks the encapsulation you had before. Whether that is a good idea or not depends on the actual use case. But you need to be aware that if you do that that every "print" function returned from creatPrintNumFunction then uses the same variable.

Let's say you don't want to move num out of the scope of creatPrintNumFunction because every "print" function returned from creatPrintNumFunction should have its own num variable.

What then you could do is to create another function (e.g. set) within creatPrintNumFunction that can change num and assign this function as a property to the function you return from creatPrintNumFunction.

function creatPrintNumFunction() {
  var num = 12;

  // both "set" and "printNum" create here
  // have a closure over the same "num" variable
  function set(val) {
    num = val;
  }

  function printNum() {
    console.log(num);
  }

  // the "set" function is assigned as a parameter to your
  // printNum function
  printNum.set = set;

  return printNum;
}

var printerA = creatPrintNumFunction();
var printerB = creatPrintNumFunction();
printerA.set(13)
printerB.set(23)
printerA();
printerB();

The advantage of this approach is that you don't expose num and you can control in your set function how/if num can be changed.


问:
Expo authentication receiving invalid JWT from Azure AD
I've been trying to add Azure authentication to a React Native Expo project, however, the JWT returned is invalid this is because the JWT's header only consists of 0.

Here is an example of the JWT

```<code>0.ATEA7JbGdftbkkiaDJGHqQYc1kmK7JAYxvNBniuMLWgKB107AAA.AQABAAIAAAD--DLA3VO7QrddgJg7WevrakIcp8mdE4FP9aquQ15XWxHqu9XpsspJ7wrvbA6uOzmrmTbqH-Orxxa9yI6KOYbBjPyVrQ49tHg-HLGFip2g4l_J82odcLMz6yTiHRnOPbnZZtsM8k_HQDUxJ7vsgCwmGkmhYmMcyT5QIrgRjn6HmYK9cPAsqQBF6KfQcFDdslvkRwCyqYWHNapF3oRnhwvQys2LYqcQhujFJngGqcMjdBmxpx0S2LsGlI49uG49Eonxm8T1Epb21qfA6U-gGsdW5LElm8fI4TmpAHtQzy4rhJf75pmkCq7WJV8XuOs4WdB03LWUgs5cDZR7JFpIvbyhcQPYzVspg-6DpwVxhtMpUegEapOLMjRHJQIOCMDs2p_Uk1cz1Qd52fRGD9JH_TNC0Qi0_eFHAlZyQUDvI19-dCUat51aYM2T84rKJXFMOscqnrvtqZSdwZvJYSLLv--YwmBskLXte1BdSIDJ43AtCPprUIM71jNkcX-BwcSqmcVdqcWhqZPf3T01E-u8fnuvGFkooAzT5omER4C9Mt5XqcbQ8phr-ig4j-hQEKU_bE8_2U9jVqdK0hzL1ylPko1c_aohAZrmyyB_hfCOvdPDsUm5_EEN9JUI0Jawl_XM2DSVMyrPzwTp8CiR6VDcAhednqVsFz3wHsQMbaqFeNPqELp9nq9i9J1TRltUXvTCY2r692By4CzDTe2HpM0633fhLPe6PHR7PZLq0ILSyBBx5nCq2Z4-xotlw4LDC88ocuggAA
</code>```

Here is my code that requests users to authenticate themselves, it uses the expo-auth-session package (Original source: https://docs.expo.dev/guides/authentication/#azure)

const config = {
    clientId: '<ClientID>',
    scopes: ['openid', 'profile', 'email', 'offline_access'],
    redirectUri: AuthSession.makeRedirectUri({
      scheme: 'com.app.scheme'
    }),
};

//AuthSession.fetchDiscoveryAsync('https://login.microsoftonline.com/common/v2.0')
AuthSession.fetchDiscoveryAsync('https://login.microsoftonline.com/<TenentID>/oauth2/v2.0/token')
.then((discovery: any) => {
    AuthSession.loadAsync(config, discovery).then(async (session: any) => {
      // Create a request.
      const request = new AuthSession.AuthRequest(config);

      // Prompt for an auth code
      const authResponse = await request.promptAsync(discovery, { useProxy: false });

      if(authResponse.type == "success"){
        console.log(authResponse); // Output response
      }
    });
});
```
<p>Actual response</p>
```Object {
  "authentication": null,
  "error": null,
  "errorCode": null,
  "params": Object {
    "code": "0.ATEA7JbGdftbkkiaDJGHqQYc1kmK7JAYxvNBniuMLWgKB107AAA.AQABAAIAAAD--DLA3VO7QrddgJg7WevrakIcp8mdE4FP9aquQ15XWxHqu9XpsspJ7wrvbA6uOzmrmTbqH-Orxxa9yI6KOYbBjPyVrQ49tHg-HLGFip2g4l_J82odcLMz6yTiHRnOPbnZZtsM8k_HQDUxJ7vsgCwmGkmhYmMcyT5QIrgRjn6HmYK9cPAsqQBF6KfQcFDdslvkRwCyqYWHNapF3oRnhwvQys2LYqcQhujFJngGqcMjdBmxpx0S2LsGlI49uG49Eonxm8T1Epb21qfA6U-gGsdW5LElm8fI4TmpAHtQzy4rhJf75pmkCq7WJV8XuOs4WdB03LWUgs5cDZR7JFpIvbyhcQPYzVspg-6DpwVxhtMpUegEapOLMjRHJQIOCMDs2p_Uk1cz1Qd52fRGD9JH_TNC0Qi0_eFHAlZyQUDvI19-dCUat51aYM2T84rKJXFMOscqnrvtqZSdwZvJYSLLv--YwmBskLXte1BdSIDJ43AtCPprUIM71jNkcX-BwcSqmcVdqcWhqZPf3T01E-u8fnuvGFkooAzT5omER4C9Mt5XqcbQ8phr-ig4j-hQEKU_bE8_2U9jVqdK0hzL1ylPko1c_aohAZrmyyB_hfCOvdPDsUm5_EEN9JUI0Jawl_XM2DSVMyrPzwTp8CiR6VDcAhednqVsFz3wHsQMbaqFeNPqELp9nq9i9J1TRltUXvTCY2r692By4CzDTe2HpM0633fhLPe6PHR7PZLq0ILSyBBx5nCq2Z4-xotlw4LDC88ocuggAA",
    "session_state": "3a4dd9ab-dc3e-4843-a83b-092508291eb3",
    "state": "S4L5Zv3s2e",
  },
  "type": "success",
  "url": "exp://127.0.0.1:19000/?code=0.ATEA7JbGdftbkkiaDJGHqQYc1kmK7JAYxvNBniuMLWgKB107AAA.AQABAAIAAAD--DLA3VO7QrddgJg7WevrakIcp8mdE4FP9aquQ15XWxHqu9XpsspJ7wrvbA6uOzmrmTbqH-Orxxa9yI6KOYbBjPyVrQ49tHg-HLGFip2g4l_J82odcLMz6yTiHRnOPbnZZtsM8k_HQDUxJ7vsgCwmGkmhYmMcyT5QIrgRjn6HmYK9cPAsqQBF6KfQcFDdslvkRwCyqYWHNapF3oRnhwvQys2LYqcQhujFJngGqcMjdBmxpx0S2LsGlI49uG49Eonxm8T1Epb21qfA6U-gGsdW5LElm8fI4TmpAHtQzy4rhJf75pmkCq7WJV8XuOs4WdB03LWUgs5cDZR7JFpIvbyhcQPYzVspg-6DpwVxhtMpUegEapOLMjRHJQIOCMDs2p_Uk1cz1Qd52fRGD9JH_TNC0Qi0_eFHAlZyQUDvI19-dCUat51aYM2T84rKJXFMOscqnrvtqZSdwZvJYSLLv--YwmBskLXte1BdSIDJ43AtCPprUIM71jNkcX-BwcSqmcVdqcWhqZPf3T01E-u8fnuvGFkooAzT5omER4C9Mt5XqcbQ8phr-ig4j-hQEKU_bE8_2U9jVqdK0hzL1ylPko1c_aohAZrmyyB_hfCOvdPDsUm5_EEN9JUI0Jawl_XM2DSVMyrPzwTp8CiR6VDcAhednqVsFz3wHsQMbaqFeNPqELp9nq9i9J1TRltUXvTCY2r692By4CzDTe2HpM0633fhLPe6PHR7PZLq0ILSyBBx5nCq2Z4-xotlw4LDC88ocuggAA&state=S4L5Zv3s2e&session_state=3a4dd9ab-dc3e-4843-a83b-092508291eb3",
}
```

Has anyone else experienced this issue?

答: You're requesting back only the code, which should then call exchangeCodeAsync to get the actual token. If you want the access token up front, then you need to add responseType: ResponseType.Token to your Auth Request.

Body:
I've been trying to add Azure authentication to a React Native Expo project, however, the JWT returned is invalid this is because the JWT's header only consists of 0.

Here is an example of the JWT

0.ATEA7JbGdftbkkiaDJGHqQYc1kmK7JAYxvNBniuMLWgKB107AAA.AQABAAIAAAD--DLA3VO7QrddgJg7WevrakIcp8mdE4FP9aquQ15XWxHqu9XpsspJ7wrvbA6uOzmrmTbqH-Orxxa9yI6KOYbBjPyVrQ49tHg-HLGFip2g4l_J82odcLMz6yTiHRnOPbnZZtsM8k_HQDUxJ7vsgCwmGkmhYmMcyT5QIrgRjn6HmYK9cPAsqQBF6KfQcFDdslvkRwCyqYWHNapF3oRnhwvQys2LYqcQhujFJngGqcMjdBmxpx0S2LsGlI49uG49Eonxm8T1Epb21qfA6U-gGsdW5LElm8fI4TmpAHtQzy4rhJf75pmkCq7WJV8XuOs4WdB03LWUgs5cDZR7JFpIvbyhcQPYzVspg-6DpwVxhtMpUegEapOLMjRHJQIOCMDs2p_Uk1cz1Qd52fRGD9JH_TNC0Qi0_eFHAlZyQUDvI19-dCUat51aYM2T84rKJXFMOscqnrvtqZSdwZvJYSLLv--YwmBskLXte1BdSIDJ43AtCPprUIM71jNkcX-BwcSqmcVdqcWhqZPf3T01E-u8fnuvGFkooAzT5omER4C9Mt5XqcbQ8phr-ig4j-hQEKU_bE8_2U9jVqdK0hzL1ylPko1c_aohAZrmyyB_hfCOvdPDsUm5_EEN9JUI0Jawl_XM2DSVMyrPzwTp8CiR6VDcAhednqVsFz3wHsQMbaqFeNPqELp9nq9i9J1TRltUXvTCY2r692By4CzDTe2HpM0633fhLPe6PHR7PZLq0ILSyBBx5nCq2Z4-xotlw4LDC88ocuggAA

Here is my code that requests users to authenticate themselves, it uses the expo-auth-session package (Original source: https://docs.expo.dev/guides/authentication/#azure)

const config = {
    clientId: '<ClientID>',
    scopes: ['openid', 'profile', 'email', 'offline_access'],
    redirectUri: AuthSession.makeRedirectUri({
      scheme: 'com.app.scheme'
    }),
};

//AuthSession.fetchDiscoveryAsync('https://login.microsoftonline.com/common/v2.0')
AuthSession.fetchDiscoveryAsync('https://login.microsoftonline.com/<TenentID>/oauth2/v2.0/token')
.then((discovery: any) => {
    AuthSession.loadAsync(config, discovery).then(async (session: any) => {
      // Create a request.
      const request = new AuthSession.AuthRequest(config);

      // Prompt for an auth code
      const authResponse = await request.promptAsync(discovery, { useProxy: false });

      if(authResponse.type == "success"){
        console.log(authResponse); // Output response
      }
    });
});

Actual response

Object {
  "authentication": null,
  "error": null,
  "errorCode": null,
  "params": Object {
    "code": "0.ATEA7JbGdftbkkiaDJGHqQYc1kmK7JAYxvNBniuMLWgKB107AAA.AQABAAIAAAD--DLA3VO7QrddgJg7WevrakIcp8mdE4FP9aquQ15XWxHqu9XpsspJ7wrvbA6uOzmrmTbqH-Orxxa9yI6KOYbBjPyVrQ49tHg-HLGFip2g4l_J82odcLMz6yTiHRnOPbnZZtsM8k_HQDUxJ7vsgCwmGkmhYmMcyT5QIrgRjn6HmYK9cPAsqQBF6KfQcFDdslvkRwCyqYWHNapF3oRnhwvQys2LYqcQhujFJngGqcMjdBmxpx0S2LsGlI49uG49Eonxm8T1Epb21qfA6U-gGsdW5LElm8fI4TmpAHtQzy4rhJf75pmkCq7WJV8XuOs4WdB03LWUgs5cDZR7JFpIvbyhcQPYzVspg-6DpwVxhtMpUegEapOLMjRHJQIOCMDs2p_Uk1cz1Qd52fRGD9JH_TNC0Qi0_eFHAlZyQUDvI19-dCUat51aYM2T84rKJXFMOscqnrvtqZSdwZvJYSLLv--YwmBskLXte1BdSIDJ43AtCPprUIM71jNkcX-BwcSqmcVdqcWhqZPf3T01E-u8fnuvGFkooAzT5omER4C9Mt5XqcbQ8phr-ig4j-hQEKU_bE8_2U9jVqdK0hzL1ylPko1c_aohAZrmyyB_hfCOvdPDsUm5_EEN9JUI0Jawl_XM2DSVMyrPzwTp8CiR6VDcAhednqVsFz3wHsQMbaqFeNPqELp9nq9i9J1TRltUXvTCY2r692By4CzDTe2HpM0633fhLPe6PHR7PZLq0ILSyBBx5nCq2Z4-xotlw4LDC88ocuggAA",
    "session_state": "3a4dd9ab-dc3e-4843-a83b-092508291eb3",
    "state": "S4L5Zv3s2e",
  },
  "type": "success",
  "url": "exp://127.0.0.1:19000/?code=0.ATEA7JbGdftbkkiaDJGHqQYc1kmK7JAYxvNBniuMLWgKB107AAA.AQABAAIAAAD--DLA3VO7QrddgJg7WevrakIcp8mdE4FP9aquQ15XWxHqu9XpsspJ7wrvbA6uOzmrmTbqH-Orxxa9yI6KOYbBjPyVrQ49tHg-HLGFip2g4l_J82odcLMz6yTiHRnOPbnZZtsM8k_HQDUxJ7vsgCwmGkmhYmMcyT5QIrgRjn6HmYK9cPAsqQBF6KfQcFDdslvkRwCyqYWHNapF3oRnhwvQys2LYqcQhujFJngGqcMjdBmxpx0S2LsGlI49uG49Eonxm8T1Epb21qfA6U-gGsdW5LElm8fI4TmpAHtQzy4rhJf75pmkCq7WJV8XuOs4WdB03LWUgs5cDZR7JFpIvbyhcQPYzVspg-6DpwVxhtMpUegEapOLMjRHJQIOCMDs2p_Uk1cz1Qd52fRGD9JH_TNC0Qi0_eFHAlZyQUDvI19-dCUat51aYM2T84rKJXFMOscqnrvtqZSdwZvJYSLLv--YwmBskLXte1BdSIDJ43AtCPprUIM71jNkcX-BwcSqmcVdqcWhqZPf3T01E-u8fnuvGFkooAzT5omER4C9Mt5XqcbQ8phr-ig4j-hQEKU_bE8_2U9jVqdK0hzL1ylPko1c_aohAZrmyyB_hfCOvdPDsUm5_EEN9JUI0Jawl_XM2DSVMyrPzwTp8CiR6VDcAhednqVsFz3wHsQMbaqFeNPqELp9nq9i9J1TRltUXvTCY2r692By4CzDTe2HpM0633fhLPe6PHR7PZLq0ILSyBBx5nCq2Z4-xotlw4LDC88ocuggAA&state=S4L5Zv3s2e&session_state=3a4dd9ab-dc3e-4843-a83b-092508291eb3",
}

Has anyone else experienced this issue?


问:
C# & PLSQL - Finding Comments and Strings by RegExp
Is it possible to distinguish between code, strings and comments by using regular expressions?
I'm trying to build a formatter for PLSQL-Code in C# and I can't manage to solve the problem, that strings, respectively quotes ( " or ' ) can also appear in comments, negating their special character and vice versa, comment indicators ( -- or /* ) appearing in strings, being nullified as a special character sequence.
Is there a solution, or are regular expressions simply the wrong way to handle this?

Best regards,
Philipp

答: You might find an idea how to reliably identify comments by studying a source code of Perl module Regexp::Common::comment. The module supports matching also PL/SQL comments.</p>


问:
Error catch... The argument type 'Object' can't be assigned t
I"m tring to catch standard exception with the following code:

```<code> @override
  Stream<LoginState> mapEventToState(LoginEvent event) async* {
    if (event is LoginUsernameChanged) {
      yield state.copyWith(username: event.username);
    } else if (event is LoginPasswordChanged) {
      yield state.copyWith(password: event.password);
    } else if (event is Loginsubmitted) {
      yield state.copyWith(formStatus: state.formStatus);
      try {
        await authRepo.login();
        yield state.copyWith(formStatus: SubmissionSuccess());

      } catch (e) {
        yield state.copyWith(formStatus:  SubmissionFailed(e));
      }
    }
  }
</code>```

The SubmissionFailed class code is :

```<code>class SubmissionFailed extends FromSubmissionStatus {
  final Exception exception;
  **SubmissionFailed(this.exception);**
}
</code>```

How ever the compiler say:

```<code>The argument type 'Object' can't be assigned to the parameter type 'Exception'.
</code>```

Why?
Thank you !

答:
The parameter in try-catch is an Object, not necessarily an exception. Depending on how await authRepo.login(); handles exceptions, that will be the type of e in the try-catch

In one of the examples here, you can see it throws a String instead of an exception

```<code>Future<void> printOrderMessage() async {
  try {
    print('Awaiting user order...');
    var order = await fetchUserOrder();
    print(order);
  } catch (err) {

    // You can see the runtimeType of err is a String
    // because fetchUserOrder throws a String

    print('Caught error: $err');
  }
}

Future<String> fetchUserOrder() {
  // Imagine that this function is more complex.
  var str = Future.delayed(
      const Duration(seconds: 4),

      // Here it throws a string, not an exception.
      // You could throw the exception here

      () => throw 'Cannot locate user order');
  return str;
}

Future<void> main() async {
  await printOrderMessage();
}
</code>```

Body:
I"m tring to catch standard exception with the following code:

 @override
  Stream<LoginState> mapEventToState(LoginEvent event) async* {
    if (event is LoginUsernameChanged) {
      yield state.copyWith(username: event.username);
    } else if (event is LoginPasswordChanged) {
      yield state.copyWith(password: event.password);
    } else if (event is Loginsubmitted) {
      yield state.copyWith(formStatus: state.formStatus);
      try {
        await authRepo.login();
        yield state.copyWith(formStatus: SubmissionSuccess());

      } catch (e) {
        yield state.copyWith(formStatus:  SubmissionFailed(e));
      }
    }
  }

The SubmissionFailed class code is :

class SubmissionFailed extends FromSubmissionStatus {
  final Exception exception;
  **SubmissionFailed(this.exception);**
}

How ever the compiler say:

The argument type 'Object' can't be assigned to the parameter type 'Exception'.

Why?
Thank you !

Body:
The parameter in try-catch is an Object, not necessarily an exception. Depending on how await authRepo.login(); handles exceptions, that will be the type of e in the try-catch

In one of the examples here, you can see it throws a String instead of an exception

Future<void> printOrderMessage() async {
  try {
    print('Awaiting user order...');
    var order = await fetchUserOrder();
    print(order);
  } catch (err) {

    // You can see the runtimeType of err is a String
    // because fetchUserOrder throws a String

    print('Caught error: $err');
  }
}

Future<String> fetchUserOrder() {
  // Imagine that this function is more complex.
  var str = Future.delayed(
      const Duration(seconds: 4),

      // Here it throws a string, not an exception.
      // You could throw the exception here

      () => throw 'Cannot locate user order');
  return str;
}

Future<void> main() async {
  await printOrderMessage();
}


问:
Android Studio does not find cocoapods in console
Somehow Android Studio does not find cocoapods, even though it is correctly installed in the system via brew install coocapods. The Android Studio console looks like it doesn't get the correct PATH.

Note: Starting Android Studio through a terminal / iTerm with

```<code>open /Applications/Android\ Studio.app
</code>```

does mitigate the issue, Android Studio then somehow gets the right path. But im wondering how i can archieve the same result for a start directly from the application directory / spotlight-search? Why does Android Studio not resolve the right PATH?

Android Studio Version 2021.1.1, macOS

Console output after click on "Flutter doctor":

```<code>/Users/[...]/flutter/bin/flutter doctor --verbose
[✓] Flutter (Channel stable, 2.8.1, on macOS 12.1 21C52 darwin-x64, locale de-DE)
    • Flutter version 2.8.1 at /Users/[...]/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 77d935af4d (6 weeks ago), 2021-12-16 08:37:33 -0800
    • Engine revision 890a5fca2e
    • Dart version 2.15.1

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/[...]/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    • All Android licenses accepted.

[!] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    ✗ CocoaPods not installed.
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

...

</code>```

Starting a terminal in Android Studio or starting iTerm, output:

```<code>flutter doctor -v
[✓] Flutter (Channel stable, 2.8.1, on macOS 12.1 21C52 darwin-x64, locale de-DE)
    • Flutter version 2.8.1 at /Users/[...]/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 77d935af4d (6 weeks ago), 2021-12-16 08:37:33 -0800
    • Engine revision 890a5fca2e
    • Dart version 2.15.1

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/[...]/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.2

...

</code>```

答:
Android Studio Bumblebee 2021.1.1.1.21 Patch 1 seems to have fixed this issue. In the release notes there is a similar issue mentioned:

Issue #216364005:  Env variables not sourced when launched from Mac OS X to Monterey Dock

Body:
Somehow Android Studio does not find cocoapods, even though it is correctly installed in the system via brew install coocapods. The Android Studio console looks like it doesn't get the correct PATH.

Note: Starting Android Studio through a terminal / iTerm with

open /Applications/Android\ Studio.app

does mitigate the issue, Android Studio then somehow gets the right path. But im wondering how i can archieve the same result for a start directly from the application directory / spotlight-search? Why does Android Studio not resolve the right PATH?

Android Studio Version 2021.1.1, macOS

Console output after click on "Flutter doctor":

/Users/[...]/flutter/bin/flutter doctor --verbose
[✓] Flutter (Channel stable, 2.8.1, on macOS 12.1 21C52 darwin-x64, locale de-DE)
    • Flutter version 2.8.1 at /Users/[...]/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 77d935af4d (6 weeks ago), 2021-12-16 08:37:33 -0800
    • Engine revision 890a5fca2e
    • Dart version 2.15.1

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/[...]/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    • All Android licenses accepted.

[!] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    ✗ CocoaPods not installed.
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

...

Starting a terminal in Android Studio or starting iTerm, output:

flutter doctor -v
[✓] Flutter (Channel stable, 2.8.1, on macOS 12.1 21C52 darwin-x64, locale de-DE)
    • Flutter version 2.8.1 at /Users/[...]/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 77d935af4d (6 weeks ago), 2021-12-16 08:37:33 -0800
    • Engine revision 890a5fca2e
    • Dart version 2.15.1

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/[...]/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.2

...


问:
How can I set a nested recoil state?
I have a nested plan list. And I want to add plans and display it using recoil. But I don't need to add the name attribute but only plans by inputs.

```<code>import React, { useState } from "react";
import "./styles.css";
import { RecoilRoot, atom, useRecoilState } from "recoil";

const todoListState = atom({
  key: "TodoList",
  default: {
    name: "Lee",
    plans: [
      {
        plan: "",
        price: ""
      }
    ]
  }
});

export function TodoApp() {
  const [list, setList] = useRecoilState(todoListState);
  const [input, setInput] = useState({
    plan: "",
    price: ""
  });

  const handleChange = (e) => {
    setInput({
      ...input,
      [e.target.name]: e.target.value
    });
  };

  const handleClick = async (e) => {
    e.preventDefault();
    setList({
      plan: input.plan,
      price: parseInt(input.price)
    });
    setInput({
      plan: "",
      price: ""
    });
  };

  return (
    <>
      <div>Plans</div>
      {list.plans.map((x, i) => {
        return (
          <div key={i}>
            <div>{x.plan}</div>
            <div>{x.price}</div>
          </div>
        );
      })}
      <div>
        <label htmlFor="plan">plan</label>
        <input
          type="text"
          value={input.plan}
          onChange={handleChange}
          name="plan"
        />
      </div>
      <div>
        <label htmlFor="price">price</label>
        <input
          type="text"
          value={input.price}
          onChange={handleChange}
          name="price"
        />
      </div>
      <button onClick={handleClick}>Add Item</button>
    </>
  );
}

export default function App() {
  return (
    <RecoilRoot>
      <div className="App">
        <TodoApp />
      </div>
    </RecoilRoot>
  );
}

</code>```

To implement this, what do I need to use or fix?
The code is below:

https://codesandbox.io/embed/nested-arrays-forked-49idv?fontsize=14&hidenavigation=1&theme=dark

答:
You just need to refactor your click handler so that when you update your recoil atom, you spread in the existing parts of the object, effectively appending to the array:

const handleClick = async (e) => {
  e.preventDefault();

  setList(list => ({
    ...list,
    plans: [
      ...list.plans,
      {
        plan: input.plan,
        price: parseInt(input.price),
      },
    ],
  }));

  setInput({plan: "", price: ""});
};
```

Title: How can I set a nested recoil state?

Body:
I have a nested plan list. And I want to add plans and display it using recoil. But I don't need to add the name attribute but only plans by inputs.

import React, { useState } from "react";
import "./styles.css";
import { RecoilRoot, atom, useRecoilState } from "recoil";

const todoListState = atom({
  key: "TodoList",
  default: {
    name: "Lee",
    plans: [
      {
        plan: "",
        price: ""
      }
    ]
  }
});

export function TodoApp() {
  const [list, setList] = useRecoilState(todoListState);
  const [input, setInput] = useState({
    plan: "",
    price: ""
  });

  const handleChange = (e) => {
    setInput({
      ...input,
      [e.target.name]: e.target.value
    });
  };

  const handleClick = async (e) => {
    e.preventDefault();
    setList({
      plan: input.plan,
      price: parseInt(input.price)
    });
    setInput({
      plan: "",
      price: ""
    });
  };

  return (
    <>

Plans

      {list.plans.map((x, i) => {
        return (

{x.plan}

{x.price}

        );
      })}

        plan
        <input
          type="text"
          value={input.plan}
          onChange={handleChange}
          name="plan"
        />

        price
        <input
          type="text"
          value={input.price}
          onChange={handleChange}
          name="price"
        />

      <button onClick={handleClick}>Add Item</button>
    </>
  );
}

export default function App() {
  return (
    <RecoilRoot>

        <TodoApp />

    </RecoilRoot>
  );
}

To implement this, what do I need to use or fix?
The code is below:

https://codesandbox.io/embed/nested-arrays-forked-49idv?fontsize=14&hidenavigation=1&theme=dark


问:
Blazor WASM authorisation failure trying to access Register Page: DenyAnonymousAuthorizationRequirement: Requires an authenticated user
I have been creating a project in Blazor WASM and using Identity Server

all was working fine and Solution was being built up. however at some stage i must have altered a setting on Identity server as this is now preventing non-logged in users from REgistering or accessing logon pages.

trying to navigate to https://localhost:44351/authentication/register
i get the below console message in developer tools

```<code>info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed. These requirements were not met:
      DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
</code>```

as far as i can tell all is fairly standard

Login Partial

```<code>@using Microsoft.AspNetCore.Identity
@using MDIS.SAW.Server.Models
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@{
    var returnUrl = "/";
    if (Context.Request.Query.TryGetValue("returnUrl", out var existingUrl)) {
        returnUrl = existingUrl;
    }
}

<ul class="navbar-nav">
@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
        <a  class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.Name!</a>
    </li>
    <li class="nav-item">
        <form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="/" method="post">
            <button  type="submit" class="nav-link btn btn-link text-dark">Logout</button>
        </form>
    </li>
}
else
{
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register" asp-route-returnUrl="@returnUrl">Register</a>
    </li>
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login" asp-route-returnUrl="@returnUrl">Login</a>
    </li>
}
</ul>
</code>```

Login Display

```<code><AuthorizeView>
    <Authorized>
        <a href="authentication/profile">Hello, @context.User.Identity.Name!</a>
        <button class="nav-link btn btn-link" @onclick="BeginSignOut">Log out</button>
    </Authorized>
    <NotAuthorized>
        <a href="authentication/register">Register</a>
        <a href="authentication/login">Log in</a>
    </NotAuthorized>
</AuthorizeView>
</code>```

St artup.cs

```<code>using MDIS.SAW.Server.Data;
using MDIS.SAW.Server.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MDIS.SAW.Server
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<SawDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<SawDbContext>( );

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, SawDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.AddControllersWithViews();
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseIdentityServer();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });
        }
    }
}
</code>```

Not sure what else i need to share

答: This happened to me when my client_secret expired.  I issued a new secret and it worked.  Remember if you are using secrets.json for running locally you need to right click on your blazor server project and go to "Manage User Secrets" and update it there.</p>

Body:
I have been creating a project in Blazor WASM and using Identity Server

all was working fine and Solution was being built up. however at some stage i must have altered a setting on Identity server as this is now preventing non-logged in users from REgistering or accessing logon pages.

trying to navigate to https://localhost:44351/authentication/register
i get the below console message in developer tools

info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed. These requirements were not met:
      DenyAnonymousAuthorizationRequirement: Requires an authenticated user.

as far as i can tell all is fairly standard

Login Partial

@using Microsoft.AspNetCore.Identity
@using MDIS.SAW.Server.Models
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@{
    var returnUrl = "/";
    if (Context.Request.Query.TryGetValue("returnUrl", out var existingUrl)) {
        returnUrl = existingUrl;
    }
}

@if (SignInManager.IsSignedIn(User))
{

        Hello @User.Identity.Name!

        <form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="/" method="post">
            <button  type="submit" class="nav-link btn btn-link text-dark">Logout</button>
        </form>

}
else
{

        Register

        Login

}

Login Display

<AuthorizeView>
    <Authorized>
        Hello, @context.User.Identity.Name!
        <button class="nav-link btn btn-link" @onclick="BeginSignOut">Log out</button>
    </Authorized>
    <NotAuthorized>
        Register
        Log in
    </NotAuthorized>
</AuthorizeView>

St artup.cs

using MDIS.SAW.Server.Data;
using MDIS.SAW.Server.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MDIS.SAW.Server
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<SawDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<SawDbContext>( );

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, SawDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.AddControllersWithViews();
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseIdentityServer();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });
        }
    }
}

Not sure what else i need to share


问:
Drop rows entries if a column values are all equal in grouped subset
I have this example df:

```<code>info = {'name': ['Jason', 'Jason', 'Jason', 'Jason','Molly', 'Molly', 'Molly', 'Molly','Nicky', 'Nicky', 'Nicky', 'Nicky'],
'city': ['Las Vegas', 'New York', 'Dallas', 'Los Angeles','Las Vegas', 'New York', 'Dallas', 'Los Angeles','Las Vegas', 'New York', 'Dallas', 'Los Angeles'],
'Visits' :[2,2,2,2,1,3,4,1,2,8,2,8]}
df = pd.DataFrame(data=info)
df
</code>```

gives:

```<code>    name    city        Visits
0   Jason   Las Vegas     2
1   Jason   New York      2
2   Jason   Dallas        2
3   Jason   Los Angeles   2
4   Molly   Las Vegas     1
5   Molly   New York      3
6   Molly   Dallas        4
7   Molly   Los Angeles   1
8   Nicky   Las Vegas     2
9   Nicky   New York      8
10  Nicky   Dallas        2
11  Nicky   Los Angeles   8
</code>```

I want to drop entries from names if all values under Visits are equivalent which is true in case of the df['name']== jason. I used drop_duplicates of two subsets name and Visits but the output drops also other duplicated values under other names.

```<code>df.drop_duplicates(['name','Visits'], keep=False)
</code>```

This gives:

```<code>    name    city     Visits
5   Molly   New York    3
6   Molly   Dallas      4
</code>```

output should be:

```<code>4   Molly   Las Vegas     1
5   Molly   New York      3
6   Molly   Dallas        4
7   Molly   Los Angeles   1
8   Nicky   Las Vegas     2
9   Nicky   New York      8
10  Nicky   Dallas        2
11  Nicky   Los Angeles   8
</code>```

What is the best approach to achieve this?

答:
Use nunique:

```<code>df = df[df.groupby('name')['Visits'].transform('nunique').ne(1)]
</code>```

Or

```<code>df = df.groupby('name').filter(lambda x: x['Visits'].nunique() != 1)
</code>```

Output:

```<code>>>> df
     name         city  Visits
4   Molly    Las Vegas       1
5   Molly     New York       3
6   Molly       Dallas       4
7   Molly  Los Angeles       1
8   Nicky    Las Vegas       2
9   Nicky     New York       8
10  Nicky       Dallas       2
11  Nicky  Los Angeles       8
</code>```

Body:
I have this example df:

info = {'name': ['Jason', 'Jason', 'Jason', 'Jason','Molly', 'Molly', 'Molly', 'Molly','Nicky', 'Nicky', 'Nicky', 'Nicky'],
'city': ['Las Vegas', 'New York', 'Dallas', 'Los Angeles','Las Vegas', 'New York', 'Dallas', 'Los Angeles','Las Vegas', 'New York', 'Dallas', 'Los Angeles'],
'Visits' :[2,2,2,2,1,3,4,1,2,8,2,8]}
df = pd.DataFrame(data=info)
df

gives:

    name    city        Visits
0   Jason   Las Vegas     2
1   Jason   New York      2
2   Jason   Dallas        2
3   Jason   Los Angeles   2
4   Molly   Las Vegas     1
5   Molly   New York      3
6   Molly   Dallas        4
7   Molly   Los Angeles   1
8   Nicky   Las Vegas     2
9   Nicky   New York      8
10  Nicky   Dallas        2
11  Nicky   Los Angeles   8

I want to drop entries from names if all values under Visits are equivalent which is true in case of the df['name']== jason. I used drop_duplicates of two subsets name and Visits but the output drops also other duplicated values under other names.

df.drop_duplicates(['name','Visits'], keep=False)

This gives:

    name    city     Visits
5   Molly   New York    3
6   Molly   Dallas      4

output should be:

4   Molly   Las Vegas     1
5   Molly   New York      3
6   Molly   Dallas        4
7   Molly   Los Angeles   1
8   Nicky   Las Vegas     2
9   Nicky   New York      8
10  Nicky   Dallas        2
11  Nicky   Los Angeles   8

What is the best approach to achieve this?

Body:
Use nunique:

df = df[df.groupby('name')['Visits'].transform('nunique').ne(1)]

Or

df = df.groupby('name').filter(lambda x: x['Visits'].nunique() != 1)

Output:

>>> df
     name         city  Visits
4   Molly    Las Vegas       1
5   Molly     New York       3
6   Molly       Dallas       4
7   Molly  Los Angeles       1
8   Nicky    Las Vegas       2
9   Nicky     New York       8
10  Nicky       Dallas       2
11  Nicky  Los Angeles       8


问:
Loop through associative array resulting from mysqli_fetch_assoc
I am new in the web development family and I really need help on that problem.
The requirement is to get a list of video with their tags.
I have 3 tables in the DB - one for videos, one for tags, and one intermediate table video_tags.

Here is my query to get datas from DB tables in order to list videos with their tags:

```<code>$query = "SELECT * FROM video_tags VT
        INNER JOIN videos V ON V.id_video = VT.id_video
        INNER JOIN tags T ON T.id_tag = VT.id_tag
        ORDER BY VT.id_video";
</code>```

Then I execute this query:

```<code>$prepare = mysqli_prepare( $connexion, $query );
mysqli_stmt_execute( $prepare );
$item = mysqli_stmt_get_result( $prepare );
$item_row = mysqli_fetch_assoc( $item );
$item_numrows = mysqli_num_rows( $item );
</code>```

So I got an associative array $item_row. Finally, I organize all the data in html table with a do/while loop:

```<code><tbody>
 <?php
   if( $item_numrows > 0 ){
     $cnt = 0;
        do{
 ?>
 <tr id="id_video_tag_<?= $item_row["id_video_tags"]?>">
    <th scope="row"><?= $item_row["id_video"]?></th>
    <td><?= $item_row["video_title"]?></td>
    <td><?= $item_row["tag"]?></td>
 </tr>
 <?php
    $cnt++;
    }
   while($item_row = mysqli_fetch_assoc( $item ))
  }
 ?>
</tbody>
</code>```

However, the list has repetitive lines coz' there are several tags for one video so you will get as many lines for one video as the tags that video has.
I tried a foreach loop on the associative array.

```<code>do{
 foreach ($item_row as $key => $value){
</code>```

But when I dumps information on the variable, I can see that the $key lists all the fields available from the DB in a row for all the 374 rows, and $value lists all the values in succession too.
Exemple of the var_dump($item_row)

```<code>array(18){["id_video_tags"]=> int(435) ["id_video"]=> int(143) ["id_tag"]=> int(12) ["video_title"]=> string(16) "" ["video_description"]=> string(0) "" ["video_url"]=> string(45) ["tag"]=> string(0) "" }
array(18){["id_video_tags"]=> int(503) ["id_video"]=> int(143) ["id_tag"]=> int(50) ["video_title"]=> string(16) "" ["video_description"]=> string(0) "" ["video_url"]=> string(45) ["tag"]=> string(0) "" }
</code>```

Is it possible to get an associative array like the following one:

```<code>$item = [
 [
  "id_video_tags" => 435,
  "id_video => 143,
  ...
  "tag" => "",
 ],
 [
  "id_video_tags" => 503,
  "id_video => 143,
  ...
  "tag" => "",
 ],
</code>```

Otherwise, I don't see how I can do to avoid lines repetition for each tag of each video.

Thanks a lot for an answer.

答:
To solve this you can manipulate your data to get something like a "parent => child" relationship (movies as parents and tags as children). Like so

```<code>$query = "
    SELECT * FROM video_tags VT
    INNER JOIN videos V ON V.id_video = VT.id_video
    INNER JOIN tags T ON T.id_tag = VT.id_tag
    ORDER BY VT.id_video
";

$prepare      = mysqli_prepare($connexion, $query);
mysqli_stmt_execute($prepare);
$stmt         = mysqli_stmt_get_result($prepare);

$videos = [];
while($row=mysqli_fetch_assoc($stmt)){
    if( !isset($videos[$row['id_video']]) ){
        $videos[$row['id_video']] = [
            'id_video'          => $row['id_video'],
            'video_title'       => $row['video_title'],
            'video_description' => $row['video_description'],
            'video_url'         => $row['video_url'],
            'tags'              => []
        ];
    }

    $videos[$row['id_video']]['tags'][] = [
        "id_video_tags" => $row['id_video_tags'],
        "id_tag"        => $row['id_tag'],
        "tag"           => $row['tag']
    ];
}

// print_r($videos);
</code>```

And use it like so

```<code><tbody>
    <?php foreach($videos as $video): ?>
        <tr id="id_video_<?= $video["id_video"]; ?>">
           <th scope="row"><?= $video["id_video"]; ?></th>
           <td><?= $video["video_title"]; ?></td>
           <td><?= implode(', ', array_column($video["tags"], 'tag')); ?></td>
        </tr>
    <?php endforeach; ?>
</tbody>
</code>```

Body:
I am new in the web development family and I really need help on that problem.
The requirement is to get a list of video with their tags.
I have 3 tables in the DB - one for videos, one for tags, and one intermediate table video_tags.

Here is my query to get datas from DB tables in order to list videos with their tags:

$query = "SELECT * FROM video_tags VT
        INNER JOIN videos V ON V.id_video = VT.id_video
        INNER JOIN tags T ON T.id_tag = VT.id_tag
        ORDER BY VT.id_video";

Then I execute this query:

$prepare = mysqli_prepare( $connexion, $query );
mysqli_stmt_execute( $prepare );
$item = mysqli_stmt_get_result( $prepare );
$item_row = mysqli_fetch_assoc( $item );
$item_numrows = mysqli_num_rows( $item );

So I got an associative array $item_row. Finally, I organize all the data in html table with a do/while loop:

 <?php
   if( $item_numrows > 0 ){
     $cnt = 0;
        do{
 ?>
 <tr id="id_video_tag_<?= $item_row["id_video_tags"]?>">
    <?= $item_row["id_video"]?>
    <?= $item_row["video_title"]?>
    <?= $item_row["tag"]?>

 <?php
    $cnt++;
    }
   while($item_row = mysqli_fetch_assoc( $item ))
  }
 ?>

However, the list has repetitive lines coz' there are several tags for one video so you will get as many lines for one video as the tags that video has.
I tried a foreach loop on the associative array.

do{
 foreach ($item_row as $key => $value){

But when I dumps information on the variable, I can see that the $key lists all the fields available from the DB in a row for all the 374 rows, and $value lists all the values in succession too.
Exemple of the var_dump($item_row)

array(18){["id_video_tags"]=> int(435) ["id_video"]=> int(143) ["id_tag"]=> int(12) ["video_title"]=> string(16) "" ["video_description"]=> string(0) "" ["video_url"]=> string(45) ["tag"]=> string(0) "" }
array(18){["id_video_tags"]=> int(503) ["id_video"]=> int(143) ["id_tag"]=> int(50) ["video_title"]=> string(16) "" ["video_description"]=> string(0) "" ["video_url"]=> string(45) ["tag"]=> string(0) "" }

Is it possible to get an associative array like the following one:

$item = [
 [
  "id_video_tags" => 435,
  "id_video => 143,
  ...
  "tag" => "",
 ],
 [
  "id_video_tags" => 503,
  "id_video => 143,
  ...
  "tag" => "",
 ],

Otherwise, I don't see how I can do to avoid lines repetition for each tag of each video.

Thanks a lot for an answer.

Body:
To solve this you can manipulate your data to get something like a "parent => child" relationship (movies as parents and tags as children). Like so

$query = "
    SELECT * FROM video_tags VT
    INNER JOIN videos V ON V.id_video = VT.id_video
    INNER JOIN tags T ON T.id_tag = VT.id_tag
    ORDER BY VT.id_video
";

$prepare      = mysqli_prepare($connexion, $query);
mysqli_stmt_execute($prepare);
$stmt         = mysqli_stmt_get_result($prepare);

$videos = [];
while($row=mysqli_fetch_assoc($stmt)){
    if( !isset($videos[$row['id_video']]) ){
        $videos[$row['id_video']] = [
            'id_video'          => $row['id_video'],
            'video_title'       => $row['video_title'],
            'video_description' => $row['video_description'],
            'video_url'         => $row['video_url'],
            'tags'              => []
        ];
    }

    $videos[$row['id_video']]['tags'][] = [
        "id_video_tags" => $row['id_video_tags'],
        "id_tag"        => $row['id_tag'],
        "tag"           => $row['tag']
    ];
}

// print_r($videos);

And use it like so

<tbody>
    <?php foreach($videos as $video): ?>
        <tr id="id_video_<?= $video["id_video"]; ?>">
           <th scope="row"><?= $video["id_video"]; ?></th>
           <td><?= $video["video_title"]; ?></td>
           <td><?= implode(', ', array_column($video["tags"], 'tag')); ?></td>
        </tr>
    <?php endforeach; ?>
</tbody>