问:
Updating table based on same table with a max value
Have a table data structure like below:

id
regid
docid
archived

1
1000
1
0

2
1000
2
0

3
1000
3
0

4
2000
1
0

5
2000
2
0

6
3000
1
0

7
3000
2
0

8
3000
3
0

9
3000
4
0

What I'm trying to do update the archived column to 1 where the docid is less than the max docid, by each regid group.

So I should end up with id's 3, 5 & 9 not being set to 1

Have tried:

```<code>update table t1
join (select max(docid) as maxdocid, regid from table) t2 on t1.docid < t2.maxdocid and t1.regid = t2.regid
set t1.archived = 1
</code>```

But doesn't work, only does the first regid group.

答:
In steps:

Create a query with the MAX value, per docid:

```<code>SELECT
  ID,
  regid,
  docid,
  (SELECT MAX(docid) FROM t1 te where te.regid=t.regid) as M
FROM t1 t
</code>```

Join the result, and update:

```<code>UPDATE t1
JOIN (

  SELECT
    ID,
    regid,
    docid,
    (SELECT MAX(docid) FROM t1 te where te.regid=t.regid) as M
  FROM t1 t

) x ON t1.id=x.id
SET archived = 1
WHERE t1.docid<x.M AND t1.archived=0;
</code>```

see: DBFIDDLE

Body:
Have a table data structure like below:

id
regid
docid
archived

1
1000
1
0

2
1000
2
0

3
1000
3
0

4
2000
1
0

5
2000
2
0

6
3000
1
0

7
3000
2
0

8
3000
3
0

9
3000
4
0

What I'm trying to do update the archived column to 1 where the docid is less than the max docid, by each regid group.

So I should end up with id's 3, 5 & 9 not being set to 1

Have tried:

update table t1
join (select max(docid) as maxdocid, regid from table) t2 on t1.docid < t2.maxdocid and t1.regid = t2.regid
set t1.archived = 1

But doesn't work, only does the first regid group.

Body:
In steps:

Create a query with the MAX value, per docid:

SELECT
  ID,
  regid,
  docid,
  (SELECT MAX(docid) FROM t1 te where te.regid=t.regid) as M
FROM t1 t

Join the result, and update:

UPDATE t1
JOIN (

  SELECT
    ID,
    regid,
    docid,
    (SELECT MAX(docid) FROM t1 te where te.regid=t.regid) as M
  FROM t1 t

) x ON t1.id=x.id
SET archived = 1
WHERE t1.docid<x.M AND t1.archived=0;

see: DBFIDDLE


来源: stackexchange

问:
Get the first character of the first string in a list?
How would I get the first character from the first string in a list in Python?

It seems that I could use mylist[0][1:] but that does not give me the first character.

```<code>>>> mylist = []
>>> mylist.append("asdf")
>>> mylist.append("jkl;")
>>> mylist[0][1:]
'sdf'
</code>```

答:
Indexing in python starting from 0. You wrote [1:] this would not return you a first char in any case - this will return you a rest(except first char) of string.

If you have the following structure:

```<code>mylist = ['base', 'sample', 'test']
</code>```

And want to get fist char for the first one string(item):

```<code>myList[0][0]
>>> b
</code>```

If all first chars:

```<code>[x[0] for x in myList]
>>> ['b', 's', 't']
</code>```

If you have a text:

```<code>text = 'base sample test'
text.split()[0][0]
>>> b
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How would I get the first character from the first string in a list in Python?

It seems that I could use mylist[0][1:] but that does not give me the first character.

>>> mylist = []
>>> mylist.append("asdf")
>>> mylist.append("jkl;")
>>> mylist[0][1:]
'sdf'

Body:
Indexing in python starting from 0. You wrote [1:] this would not return you a first char in any case - this will return you a rest(except first char) of string.

If you have the following structure:

mylist = ['base', 'sample', 'test']

And want to get fist char for the first one string(item):

myList[0][0]
>>> b

If all first chars:

[x[0] for x in myList]
>>> ['b', 's', 't']

If you have a text:

text = 'base sample test'
text.split()[0][0]
>>> b

ContentLicense: CC BY-SA 3.0


问:
How to make one class that shared with multiple obj
I am working in unity and I made a save system that saves to a public class PlayerStats this is not a MonoBehaviour but a class that has all the data init. My question is if there is a way if I change on var in the playerstats it change all the playerstats only having only one playerstats.</p>

答:
if this class is an exposed Serializable then not really as the Serializer will (de)serialize them all independent from another into their according serialized objects.

You might want to rather go for a ScriptableObject.

These are mainly data container assets (similar to prefabs) you can create and then reference in multiple places so each change within such a ScriptablObject is reflected everywhere where it is used.

E.g.

```<code>// This attribute is required so you can create instances of this ScriptableObject via
// RightClick in the Assets -> Create -> Example
[CreateAssetMenu]
public class Example : ScriptableObject
{
    // your public fields here like e.g.
    public int someInt;
}
</code>```

As an extra: ScriptableObject is a c# class -> They follow all the usual rules and can implement certain methods, interfaces, can be inherited etc.

Body:
if this class is an exposed Serializable then not really as the Serializer will (de)serialize them all independent from another into their according serialized objects.

You might want to rather go for a ScriptableObject.

These are mainly data container assets (similar to prefabs) you can create and then reference in multiple places so each change within such a ScriptablObject is reflected everywhere where it is used.

E.g.

// This attribute is required so you can create instances of this ScriptableObject via
// RightClick in the Assets -> Create -> Example
[CreateAssetMenu]
public class Example : ScriptableObject
{
    // your public fields here like e.g.
    public int someInt;
}

As an extra: ScriptableObject is a c# class -> They follow all the usual rules and can implement certain methods, interfaces, can be inherited etc.


问:
Cannot find module 'caniuse-lite/dist/unpacker/agents' when running create react app
I am trying to create a new react application.
I have node version 14.15.3 and npm version 6.14

```<code>Error: Cannot find module 'caniuse-lite/dist/unpacker/agents'
</code>```

when running npx create-react-app

issue screenshot

答:
```<code>npm update @babel/preset-env
</code>```

Works for me.

Body:
I am trying to create a new react application.
I have node version 14.15.3 and npm version 6.14

Error: Cannot find module 'caniuse-lite/dist/unpacker/agents'

when running npx create-react-app

issue screenshot

Body:
npm update @babel/preset-env

Works for me.


问:
How to set color of PageViewModel Title & body text in Flutter?
This is my introScreen.dart, I want to set a color of PageViewModel Title & body text in Flutter.

I am tried this line of code style: TextStyle(fontSize: 20, color: Colors.white), but it could be error.

how we can set the color of PageViewModel Title & body text in Flutter?

```<code>Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.only(top: 100),
        child: IntroductionScreen(
          pages: [
            PageViewModel(
              image: LottieBuilder.asset("assets/animations/1.json"),
              title: "Welcome to $appname",
              body: "I will take you around to see what's so exciting about $appname",
            ),
            PageViewModel(
              image: LottieBuilder.asset("assets/animations/2.json"),
              title: "Privacy Protection",
              body: "Internet access is mind-free, we'll keep you safe",
            ),
            PageViewModel(
              image: LottieBuilder.asset("assets/animations/3.json"),
              title: "Fast and Limitless!",
              body: "We provide you the without limits",
            ),
          ],
          showSkipButton: true,
          onDone: () {
            Preferences.init().then((value) {
              // ignore: invalid_use_of_protected_member
              rootState!.setState(() {
                value.saveFirstOpen();
              });
            });
          },
</code>```

答:
Try this inside PageViewModel:

titleWidget: Text(
            "Welcome to $appname",
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 18, color: appColorYellow),
          ),

bodyWidget: Text(
            "I will take you around to see what's so exciting about $appname",
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 18, color: appColorYellow),
          ),
```

Body:
This is my introScreen.dart, I want to set a color of PageViewModel Title & body text in Flutter.

I am tried this line of code style: TextStyle(fontSize: 20, color: Colors.white), but it could be error.

how we can set the color of PageViewModel Title & body text in Flutter?

Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.only(top: 100),
        child: IntroductionScreen(
          pages: [
            PageViewModel(
              image: LottieBuilder.asset("assets/animations/1.json"),
              title: "Welcome to $appname",
              body: "I will take you around to see what's so exciting about $appname",
            ),
            PageViewModel(
              image: LottieBuilder.asset("assets/animations/2.json"),
              title: "Privacy Protection",
              body: "Internet access is mind-free, we'll keep you safe",
            ),
            PageViewModel(
              image: LottieBuilder.asset("assets/animations/3.json"),
              title: "Fast and Limitless!",
              body: "We provide you the without limits",
            ),
          ],
          showSkipButton: true,
          onDone: () {
            Preferences.init().then((value) {
              // ignore: invalid_use_of_protected_member
              rootState!.setState(() {
                value.saveFirstOpen();
              });
            });
          },


问:
How to copy two sheets to a new workbook as value VBA
I am using the code below to copy two specific sheets to a new workbook. The code works, but only the first one is copied as value, the second one is copied ad formula.

Does anyone knows how can both sheets be copied as value? Many thanks!! =D

```<code>Sub CopyTabsToNewWorkbook()

Dim wbNew As Workbook
Dim path As String
Dim filename As String

     Application.ScreenUpdating = False
     Application.DisplayAlerts = False

    'To unhide the tab
     Worksheets("EMEA & AM").Visible = xlSheetVisible
     Worksheets("CAT").Visible = xlSheetVisible

     Worksheets(Array("EMEA & AM", "CAT")).Copy

    Set wbNew = ActiveWorkbook
    With wbNew
        With .Worksheets(1).UsedRange
        .Value = .Value
        End With

        path = "https://Shared Link Path/" & "\"
        filename = Range("AP1")

        .SaveAs filename:=path & filename
        .Close savechanges:=False
     End With

     'To hide the tab
      Worksheets("EMEA & AM").Visible = xlSheetHidden
      Worksheets("CAT").Visible = xlSheetHidden
End Sub
</code>```

答:
With .Worksheets(1).UsedRange
        .Value = .Value
End With

'convert the second sheet to value like you did for the first sheet
With .Worksheets(2).UsedRange
        .Value = .Value
End With

```

Body:
I am using the code below to copy two specific sheets to a new workbook. The code works, but only the first one is copied as value, the second one is copied ad formula.

Does anyone knows how can both sheets be copied as value? Many thanks!! =D

Sub CopyTabsToNewWorkbook()

Dim wbNew As Workbook
Dim path As String
Dim filename As String

     Application.ScreenUpdating = False
     Application.DisplayAlerts = False

    'To unhide the tab
     Worksheets("EMEA & AM").Visible = xlSheetVisible
     Worksheets("CAT").Visible = xlSheetVisible

     Worksheets(Array("EMEA & AM", "CAT")).Copy

    Set wbNew = ActiveWorkbook
    With wbNew
        With .Worksheets(1).UsedRange
        .Value = .Value
        End With

        path = "https://Shared Link Path/" & "\"
        filename = Range("AP1")

        .SaveAs filename:=path & filename
        .Close savechanges:=False
     End With

     'To hide the tab
      Worksheets("EMEA & AM").Visible = xlSheetHidden
      Worksheets("CAT").Visible = xlSheetHidden
End Sub


问:
Let an object move with AnimatedPositioned
I asked this question in this link Transition with futter move object

how i can make movig an object with AnimatedPositioned ? if i want an object move with a value = 1, or a value = 10

or something like that:

```<code>i = 0;
i++;
</code>```

or

```<code>i = 0;

i = i + 10;
</code>```

how i can do that with AnimatedPositioned

答:
You only need to update position value from your AnimatedPositioned:

```<code>AnimatedPositioned(
            width: selected ? 200.0 : 50.0,
            height: selected ? 50.0 : 200.0,
            top: selected ? 50.0 : 150.0,
            duration: const Duration(seconds: 2),
            curve: Curves.fastOutSlowIn,
            child: GestureDetector(
              onTap: () {
                setState(() {
                  selected = !selected;
                });
              },
              child: Container(
                color: Colors.blue,
                child: const Center(child: Text('Tap me')),
              ),
            ),
          )
</code>```

Just change that values to yours.

Full example:

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

void main() => runApp(const MyApp());

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

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  bool selected = false;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 200,
      height: 350,
      child: Stack(
        children: <Widget>[
          AnimatedPositioned(
            width: selected ? 200.0 : 50.0,
            height: selected ? 50.0 : 200.0,
            top: selected ? 50.0 : 150.0,
            duration: const Duration(seconds: 2),
            curve: Curves.fastOutSlowIn,
            child: GestureDetector(
              onTap: () {
                setState(() {
                  selected = !selected;
                });
              },
              child: Container(
                color: Colors.blue,
                child: const Center(child: Text('Tap me')),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

Info: https://api.flutter.dev/flutter/widgets/AnimatedPositioned-class.html

Body:
I asked this question in this link Transition with futter move object

how i can make movig an object with AnimatedPositioned ? if i want an object move with a value = 1, or a value = 10

or something like that:

i = 0;
i++;

or

i = 0;

i = i + 10;

how i can do that with AnimatedPositioned

Body:
You only need to update position value from your AnimatedPositioned:

AnimatedPositioned(
            width: selected ? 200.0 : 50.0,
            height: selected ? 50.0 : 200.0,
            top: selected ? 50.0 : 150.0,
            duration: const Duration(seconds: 2),
            curve: Curves.fastOutSlowIn,
            child: GestureDetector(
              onTap: () {
                setState(() {
                  selected = !selected;
                });
              },
              child: Container(
                color: Colors.blue,
                child: const Center(child: Text('Tap me')),
              ),
            ),
          )

Just change that values to yours.

Full example:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

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

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  bool selected = false;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 200,
      height: 350,
      child: Stack(
        children: <Widget>[
          AnimatedPositioned(
            width: selected ? 200.0 : 50.0,
            height: selected ? 50.0 : 200.0,
            top: selected ? 50.0 : 150.0,
            duration: const Duration(seconds: 2),
            curve: Curves.fastOutSlowIn,
            child: GestureDetector(
              onTap: () {
                setState(() {
                  selected = !selected;
                });
              },
              child: Container(
                color: Colors.blue,
                child: const Center(child: Text('Tap me')),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Info: https://api.flutter.dev/flutter/widgets/AnimatedPositioned-class.html


问:
user_data not getting executed over instance creation
I have provided an .sh file as user_data in my Terraform script:

```<code>resource "aws_instance" "alpha-terraform"{
    ami=var.amis[var.region]
    instance_type="t2.micro"
    vpc_security_group_ids=[aws_security_group.alpha-terraform-sg.id]
    user_data = file("user_data_bootstrap.sh")
    key_name = "alpha-terraform"

    tags={
        type="alpha"
        purpose="terraform"
    }
}
</code>```

The .sh file contains:

```<code>#Jenkins Installation:
sudo apt update
sudo apt install openjdk-8-jdk --yes
wget –q –O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add –
sudo sh -c 'echo deb https://pkg.jenkins.io/debian binary/ >> /etc/apt/sources.list'
sudo apt update
sudo apt install Jenkins
sudo systemctl status jenkins
find /usr/lib/jvm/java-1.8* | head -n 3
</code>```

My instance is getting created all right. However, I believe my user_data is not getting executed. I can see the user_data is being copied to /var/lib/cloud/instance/ as user-data.txt and user-data.txt.i but still not getting executed.

Why is this happening and how can I debug it further?

Update

I tried accessing the server through and executing each command one by one but getting following error while updating apt packages:

```<code>ubuntu@ip-172-31-52-**:~$ apt update
Reading package lists... Done
W: chmod 0700 of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (1: Operation not permitted)
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)
ubuntu@ip-172-31-52-**:~$ sudo apt update
Reading package lists... Done
E: Could not get lock /var/lib/apt/lists/lock - open (11: Resource temporarily unavailable)
E: Unable to lock directory /var/lib/apt/lists/
</code>```

答: To help troubleshooting, it's a good idea to SSH and check folder /var/lib/cloud/instances/instance-id/. You should find the data_user script there. Read it to check if everything is as expected.

Body:
I have provided an .sh file as user_data in my Terraform script:

resource "aws_instance" "alpha-terraform"{
    ami=var.amis[var.region]
    instance_type="t2.micro"
    vpc_security_group_ids=[aws_security_group.alpha-terraform-sg.id]
    user_data = file("user_data_bootstrap.sh")
    key_name = "alpha-terraform"

    tags={
        type="alpha"
        purpose="terraform"
    }
}

The .sh file contains:

#Jenkins Installation:
sudo apt update
sudo apt install openjdk-8-jdk --yes
wget –q –O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add –
sudo sh -c 'echo deb https://pkg.jenkins.io/debian binary/ >> /etc/apt/sources.list'
sudo apt update
sudo apt install Jenkins
sudo systemctl status jenkins
find /usr/lib/jvm/java-1.8* | head -n 3

My instance is getting created all right. However, I believe my user_data is not getting executed. I can see the user_data is being copied to /var/lib/cloud/instance/ as user-data.txt and user-data.txt.i but still not getting executed.

Why is this happening and how can I debug it further?

Update

I tried accessing the server through and executing each command one by one but getting following error while updating apt packages:

ubuntu@ip-172-31-52-**:~$ apt update
Reading package lists... Done
W: chmod 0700 of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (1: Operation not permitted)
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)
ubuntu@ip-172-31-52-**:~$ sudo apt update
Reading package lists... Done
E: Could not get lock /var/lib/apt/lists/lock - open (11: Resource temporarily unavailable)
E: Unable to lock directory /var/lib/apt/lists/


问:
MS Graph | PHP | GET Photo - Laravel 404 exception
I'm building a website with Azure authentication using MS Graph.
As you can see below I want to login and get my own data as well as my managers which is working fine, however the issue begins when I want to select the photo.

```<code>$graph = new Graph();
$graph->setAccessToken($accessToken->getToken());

$user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
   ->addHeaders(array("Content-Type" => "application/json"))
   ->setReturnType(Model\User::class)
   ->execute();

$photo = $graph->createRequest('GET', '/me/photo/$value')
   ->addHeaders(array("Content-Type" => "image/jpeg"))
   ->execute();

$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
</code>```

When a user does not have a profile photo set it will return a 404 Not Found which is ok, but I don't want my script to stop if there is no photo. What I want is something like this:

```<code>if($photo->getStatus(404)){
     $avatar = null;
}
else{
     $photo = $photo->getRawBody();
     $avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
}
</code>```

If there is no photo I want to set $avatar to null instead of getting the following error:

Thanks in advance!

FULL FUNCTION

```<code>public function callback(Request $request)
  {
    // Validate state
    $expectedState = session('oauthState');
    $request->session()->forget('oauthState');
    $providedState = $request->query('state');

    if (!isset($expectedState)) {
      // If there is no expected state in the session,
      // do nothing and redirect to the home page.
      return redirect('/');
    }

    if (!isset($providedState) || $expectedState != $providedState) {
      return redirect('/')
        ->with('error', 'Invalid auth state')
        ->with('errorDetail', 'The provided auth state did not match the expected value');
    }

    // Authorization code should be in the "code" query param
    $authCode = $request->query('code');
    if (isset($authCode)) {
      // Initialize the OAuth client
      $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
        'clientId'                => config('azure.appId'),
        'clientSecret'            => config('azure.appSecret'),
        'redirectUri'             => config('azure.redirectUri'),
        'urlAuthorize'            => config('azure.authority').config('azure.authorizeEndpoint'),
        'urlAccessToken'          => config('azure.authority').config('azure.tokenEndpoint'),
        'urlResourceOwnerDetails' => '',
        'scopes'                  => config('azure.scopes')
      ]);

      try {
        // Make the token request
        $accessToken = $oauthClient->getAccessToken('authorization_code', [
          'code' => $authCode
        ]);

        $graph = new Graph();
        $graph->setAccessToken($accessToken->getToken());

        $user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
          ->addHeaders(array("Content-Type" => "application/json"))
          ->setReturnType(Model\User::class)
          ->execute();

        $photo = $graph->createRequest('GET', '/me/photo/$value')
          ->addHeaders(array("Content-Type" => "image/jpeg"))
          ->execute();
          $photo = $photo->getRawBody();
          $avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';

        $manager = $user->getManager();

        $tokenCache = new TokenCache();
        $tokenCache->storeTokens($accessToken, $user, $manager, $avatar);

        // Define user details and manager details
        $userFirstName = $user->getGivenName();
        $userSurname = $user->getSurname();
        $userEmail = $user->getMail();

        $managerFirstName = $manager->getGivenName();
        $managerSurname = $manager->getSurname();
        $managerEmail = $manager->getMail();

        return redirect('/');
      }
      catch (Exception $e) {
        $avatar = null;
        return redirect('/')
          ->with('error', 'Error requesting access token')
          ->with('errorDetail', json_encode($e->getResponseBody()));
      }
    }

    return redirect('/')
      ->with('error', $request->query('error'))
      ->with('errorDetail', $request->query('error_description'));
  }
</code>```

答:
I am not familiar with the microsoft graph api, but a basic PHP Try - Catch block should do the trick here.

https://www.php.net/manual/en/language.exceptions.php

Try to fetch the image -> in case an exception occurs set $avatar to null

Body:
I'm building a website with Azure authentication using MS Graph.
As you can see below I want to login and get my own data as well as my managers which is working fine, however the issue begins when I want to select the photo.

$graph = new Graph();
$graph->setAccessToken($accessToken->getToken());

$user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
   ->addHeaders(array("Content-Type" => "application/json"))
   ->setReturnType(Model\User::class)
   ->execute();

$photo = $graph->createRequest('GET', '/me/photo/$value')
   ->addHeaders(array("Content-Type" => "image/jpeg"))
   ->execute();

$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';

When a user does not have a profile photo set it will return a 404 Not Found which is ok, but I don't want my script to stop if there is no photo. What I want is something like this:

if($photo->getStatus(404)){
     $avatar = null;
}
else{
     $photo = $photo->getRawBody();
     $avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
}

If there is no photo I want to set $avatar to null instead of getting the following error:

Thanks in advance!

FULL FUNCTION

public function callback(Request $request)
  {
    // Validate state
    $expectedState = session('oauthState');
    $request->session()->forget('oauthState');
    $providedState = $request->query('state');

    if (!isset($expectedState)) {
      // If there is no expected state in the session,
      // do nothing and redirect to the home page.
      return redirect('/');
    }

    if (!isset($providedState) || $expectedState != $providedState) {
      return redirect('/')
        ->with('error', 'Invalid auth state')
        ->with('errorDetail', 'The provided auth state did not match the expected value');
    }

    // Authorization code should be in the "code" query param
    $authCode = $request->query('code');
    if (isset($authCode)) {
      // Initialize the OAuth client
      $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
        'clientId'                => config('azure.appId'),
        'clientSecret'            => config('azure.appSecret'),
        'redirectUri'             => config('azure.redirectUri'),
        'urlAuthorize'            => config('azure.authority').config('azure.authorizeEndpoint'),
        'urlAccessToken'          => config('azure.authority').config('azure.tokenEndpoint'),
        'urlResourceOwnerDetails' => '',
        'scopes'                  => config('azure.scopes')
      ]);

      try {
        // Make the token request
        $accessToken = $oauthClient->getAccessToken('authorization_code', [
          'code' => $authCode
        ]);

        $graph = new Graph();
        $graph->setAccessToken($accessToken->getToken());

        $user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
          ->addHeaders(array("Content-Type" => "application/json"))
          ->setReturnType(Model\User::class)
          ->execute();

        $photo = $graph->createRequest('GET', '/me/photo/$value')
          ->addHeaders(array("Content-Type" => "image/jpeg"))
          ->execute();
          $photo = $photo->getRawBody();
          $avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';

        $manager = $user->getManager();

        $tokenCache = new TokenCache();
        $tokenCache->storeTokens($accessToken, $user, $manager, $avatar);

        // Define user details and manager details
        $userFirstName = $user->getGivenName();
        $userSurname = $user->getSurname();
        $userEmail = $user->getMail();

        $managerFirstName = $manager->getGivenName();
        $managerSurname = $manager->getSurname();
        $managerEmail = $manager->getMail();

        return redirect('/');
      }
      catch (Exception $e) {
        $avatar = null;
        return redirect('/')
          ->with('error', 'Error requesting access token')
          ->with('errorDetail', json_encode($e->getResponseBody()));
      }
    }

    return redirect('/')
      ->with('error', $request->query('error'))
      ->with('errorDetail', $request->query('error_description'));
  }


问:
How can I align a column heading and contact info in same row?
This might be silly question but yet I am stucked here.

There is A4 size paper in which I want Company Name at the center of the page and in the same row I want WhatsApp and contact number right aligned one after another. Below is my code attached.

Thanks in advance.

.invoice-title {
  font-size: 25px;
  text-align: center;
  font-weight: bold;
  color: #CD1818;
  padding-top: 10px;
}

.invoice-title small {
  font-size: 12px;
  text-align: right;
  padding-top: 10px;
  color: #262a2e;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="invoice-title"><span>COMPANY NAME</span>
  <small class="float-right"><i class="fab fa-whatsapp"></i> : 99887766655 \nCall : 5544332211</small>
</p></code>```

答:
You can do the following

Added a
 tag to add a new line on your html

Added the following styles

.invoice-title {
  width: 100%;
  border: 1px solid black;
  font-size: 25px;
  text-align: center;
  position: relative;
  padding: 10px;
}

.float-right {
  font-size: 12px;
  position: absolute;
  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;
  right: 0;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="invoice-title"><span>COMPANY NAME</span>
  <small class="float-right"><i class="fab fa-whatsapp"></i> : 99887766655 <br/>Call : 5544332211</small>
</p></code>```

Body:
This might be silly question but yet I am stucked here.

There is A4 size paper in which I want Company Name at the center of the page and in the same row I want WhatsApp and contact number right aligned one after another. Below is my code attached.

Thanks in advance.

.invoice-title {
  font-size: 25px;
  text-align: center;
  font-weight: bold;
  color: #CD1818;
  padding-top: 10px;
}

.invoice-title small {
  font-size: 12px;
  text-align: right;
  padding-top: 10px;
  color: #262a2e;
}

COMPANY NAME
   : 99887766655 \nCall : 5544332211

Body:
You can do the following

Added a <br/> tag to add a new line on your html

Added the following styles

.invoice-title {
  width: 100%;
  border: 1px solid black;
  font-size: 25px;
  text-align: center;
  position: relative;
  padding: 10px;
}

.float-right {
  font-size: 12px;
  position: absolute;
  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;
  right: 0;
  top: 0;
}

<p class="invoice-title"><span>COMPANY NAME</span>
  <small class="float-right"><i class="fab fa-whatsapp"></i> : 99887766655 <br/>Call : 5544332211</small>
</p>


问:
How to get camera device name in OpenCV?
There having these two ways to open the camera cv::VideoCapture:

```<code>CV_WRAP virtual bool open(const String& filename)

CV_WRAP virtual bool open(int index)
</code>```

Is possible open the camera using the index and get the filename(device name) from the VideoCapture object?

or How to find the device name of a USB webcam in Windows which pass to open function?

答:
This is more close to what you want(Note that, all STRING types are std::string):

```<code>int _GetUSBCameraDevicesList(std::vector<__STRING__>& list, std::vector<__STRING__>& devicePaths)
{
    //COM Library Initialization
    //comInit();

    ICreateDevEnum* pDevEnum = NULL;
    IEnumMoniker* pEnum = NULL;
    int deviceCounter = 0;
    CoInitialize(NULL);

    HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL,
        CLSCTX_INPROC_SERVER, IID_ICreateDevEnum,
        reinterpret_cast<void**>(&pDevEnum));

    if (SUCCEEDED(hr))
    {
        // Create an enumerator for the video capture category.
        hr = pDevEnum->CreateClassEnumerator(
            CLSID_VideoInputDeviceCategory,
            &pEnum, 0);

        if (hr == S_OK) {

            printf("SETUP: Looking For Capture Devices\n");
            IMoniker* pMoniker = NULL;

            while (pEnum->Next(1, &pMoniker, NULL) == S_OK) {

                IPropertyBag* pPropBag;
                hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
                    (void**)(&pPropBag));

                if (FAILED(hr)) {
                    pMoniker->Release();
                    continue;  // Skip this one, maybe the next one will work.
                }

                // Find the description or friendly name.
                VARIANT varName;
                VariantInit(&varName);
                hr = pPropBag->Read(L"Description", &varName, 0);

                if (FAILED(hr)) hr = pPropBag->Read(L"FriendlyName", &varName, 0);

                if (SUCCEEDED(hr))
                {

                    hr = pPropBag->Read(L"FriendlyName", &varName, 0);

                    int count = 0;
                    char tmp[255] = { 0 };
                    //int maxLen = sizeof(deviceNames[0]) / sizeof(deviceNames[0][0]) - 2;
                    while (varName.bstrVal[count] != 0x00 && count < 255)
                    {
                        tmp[count] = (char)varName.bstrVal[count];
                        count++;
                    }
                    list.emplace_back(tmp);
                    //deviceNames[deviceCounter][count] = 0;

                    //if (!silent) DebugPrintOut("SETUP: %i) %s\n", deviceCounter, deviceNames[deviceCounter]);

                    // then read Device Path
                    {
                        VARIANT DP_Path;
                        VariantInit(&DP_Path);

                        hr = pPropBag->Read(L"DevicePath", &DP_Path, 0);

                        if (SUCCEEDED(hr))
                        {
                            int __count = 0;
                            char __tmp[255] = { 0 };
                            while (DP_Path.bstrVal[__count] != 0x00 && __count < 255)
                            {
                                __tmp[__count] = (char)DP_Path.bstrVal[__count];
                                __count++;
                            }

                            devicePaths.emplace_back(__tmp);
                        }
                    }
                }

                pPropBag->Release();
                pPropBag = NULL;

                pMoniker->Release();
                pMoniker = NULL;

                deviceCounter++;
            }

            pDevEnum->Release();
            pDevEnum = NULL;

            pEnum->Release();
            pEnum = NULL;
        }

        //if (!silent) DebugPrintOut("SETUP: %i Device(s) found\n\n", deviceCounter);
    }

    //comUnInit();

    return deviceCounter;
}
</code>```

Just pass two std::vectorstd::string() to get the list of all connected devices and their paths(Paths may be used to compare device identity if two device have the same friendly name).

Body:
There having these two ways to open the camera cv::VideoCapture:

CV_WRAP virtual bool open(const String& filename)

CV_WRAP virtual bool open(int index)

Is possible open the camera using the index and get the filename(device name) from the VideoCapture object?

or How to find the device name of a USB webcam in Windows which pass to open function?

Body:
This is more close to what you want(Note that, all STRING types are std::string):

int _GetUSBCameraDevicesList(std::vector<__STRING__>& list, std::vector<__STRING__>& devicePaths)
{
    //COM Library Initialization
    //comInit();

    ICreateDevEnum* pDevEnum = NULL;
    IEnumMoniker* pEnum = NULL;
    int deviceCounter = 0;
    CoInitialize(NULL);

    HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL,
        CLSCTX_INPROC_SERVER, IID_ICreateDevEnum,
        reinterpret_cast<void**>(&pDevEnum));

    if (SUCCEEDED(hr))
    {
        // Create an enumerator for the video capture category.
        hr = pDevEnum->CreateClassEnumerator(
            CLSID_VideoInputDeviceCategory,
            &pEnum, 0);

        if (hr == S_OK) {

            printf("SETUP: Looking For Capture Devices\n");
            IMoniker* pMoniker = NULL;

            while (pEnum->Next(1, &pMoniker, NULL) == S_OK) {

                IPropertyBag* pPropBag;
                hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
                    (void**)(&pPropBag));

                if (FAILED(hr)) {
                    pMoniker->Release();
                    continue;  // Skip this one, maybe the next one will work.
                }

                // Find the description or friendly name.
                VARIANT varName;
                VariantInit(&varName);
                hr = pPropBag->Read(L"Description", &varName, 0);

                if (FAILED(hr)) hr = pPropBag->Read(L"FriendlyName", &varName, 0);

                if (SUCCEEDED(hr))
                {

                    hr = pPropBag->Read(L"FriendlyName", &varName, 0);

                    int count = 0;
                    char tmp[255] = { 0 };
                    //int maxLen = sizeof(deviceNames[0]) / sizeof(deviceNames[0][0]) - 2;
                    while (varName.bstrVal[count] != 0x00 && count < 255)
                    {
                        tmp[count] = (char)varName.bstrVal[count];
                        count++;
                    }
                    list.emplace_back(tmp);
                    //deviceNames[deviceCounter][count] = 0;

                    //if (!silent) DebugPrintOut("SETUP: %i) %s\n", deviceCounter, deviceNames[deviceCounter]);

                    // then read Device Path
                    {
                        VARIANT DP_Path;
                        VariantInit(&DP_Path);

                        hr = pPropBag->Read(L"DevicePath", &DP_Path, 0);

                        if (SUCCEEDED(hr))
                        {
                            int __count = 0;
                            char __tmp[255] = { 0 };
                            while (DP_Path.bstrVal[__count] != 0x00 && __count < 255)
                            {
                                __tmp[__count] = (char)DP_Path.bstrVal[__count];
                                __count++;
                            }

                            devicePaths.emplace_back(__tmp);
                        }
                    }
                }

                pPropBag->Release();
                pPropBag = NULL;

                pMoniker->Release();
                pMoniker = NULL;

                deviceCounter++;
            }

            pDevEnum->Release();
            pDevEnum = NULL;

            pEnum->Release();
            pEnum = NULL;
        }

        //if (!silent) DebugPrintOut("SETUP: %i Device(s) found\n\n", deviceCounter);
    }

    //comUnInit();

    return deviceCounter;
}

Just pass two std::vectorstd::string() to get the list of all connected devices and their paths(Paths may be used to compare device identity if two device have the same friendly name).


问:
React-Bootstrap - Card Component cannot be imported & Cannot install peer dependencies
I've been using react-bootstrap and so far most components are working except the Card component, and this is the error I've been getting:

Attempted import error: 'Card' is not exported from 'react-bootstrap'.

import React, {Component} from "react"
import {Button} from 'react-bootstrap'
import Card from "react-bootstrap/Card";

export default class NewsCard extends Component {
    render() {
        return (

                <Card style={{ width: '18rem' }}>
                <Card.Img variant="top" src="holder.js/100px180" />
                <Card.Body>
                    <Card.Title>Card Title</Card.Title>
                    <Card.Text>
                    Some quick example text to build on the card title and make up the bulk of
                    the card's content.
                    </Card.Text>
                    <Button variant="primary">Go somewhere</Button>
                </Card.Body>
                </Card>

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

<p>When I install React-Bootstrap, I get this warning error also so the Card Component is missing from the dependency:</p>

```npm WARN react-bootstrap-card@0.2.1 requires a peer of react-bootstrap@^0.30.7 but none is installed. You must install peer dependencies yourself.
```

Has anyone else encountered this issue or can lead me to the right direction? thanks

答:
I had a similar problem, with this error:

export 'carddeck' (imported as 'carddeck') was not found in 'react-bootstrap'

ante the problem was that whenever I do npm install react-bootstrap bootstrap@4.6.0 it will install react-bootstrap version: 2.1.2 which is not fully compatible with bootstrap@4.6.0.

So the solution is npm uninstall react-bootstrap bootstrap if you already installed react-bootstrap and bootstrap before and force the installation of the 1.6.4 version by

npm install react-bootstrap@1.6.4 bootstrap@4.6.0

I also experienced problems with the accordions because of the same versions mix problems.

Body:
I've been using react-bootstrap and so far most components are working except the Card component, and this is the error I've been getting:

Attempted import error: 'Card' is not exported from 'react-bootstrap'.

import React, {Component} from "react"
import {Button} from 'react-bootstrap'
import Card from "react-bootstrap/Card";

export default class NewsCard extends Component {
    render() {
        return (

                <Card style={{ width: '18rem' }}>
                <Card.Img variant="top" src="holder.js/100px180" />
                <Card.Body>
                    <Card.Title>Card Title</Card.Title>
                    <Card.Text>
                    Some quick example text to build on the card title and make up the bulk of
                    the card's content.
                    </Card.Text>
                    <Button variant="primary">Go somewhere</Button>
                </Card.Body>
                </Card>

        )
        }
    }

When I install React-Bootstrap, I get this warning error also so the Card Component is missing from the dependency:

npm WARN react-bootstrap-card@0.2.1 requires a peer of react-bootstrap@^0.30.7 but none is installed. You must install peer dependencies yourself.

Has anyone else encountered this issue or can lead me to the right direction? thanks


问:
React helmet inserting Scripts at end of rendered code
When i test my page in "Google Structured data testing tool" I find this at end of my code.
I am also sharing my component where data is being inserted in helmet:

```<code>   <!-- Inserted by webpack:///../node_modules/react-helmet/lib/HelmetUtils.js? -->
       <script type="application/ld+json">
       </script>
   <!-- Inserted by webpack:///../node_modules/react-helmet/lib/HelmetUtils.js? -->
      <script type="application/ld+json">
      </script>
</code>```

Please find the code below where data is inserted in helmet:

```<code>export const structuredDataSingle = (props) => {
  const arr = [];
  const {
    location: {
      pathname
    },
  } = props;
  const pathnames = pathname.split('/').filter(x => x);
  if(pathnames.length <= 1) {
    return JSON.stringify({
      "@context": "https://schema.org/",
      "@type": "BreadcrumbList",
      "itemListElement": [{
        "@type": "ListItem",
        "position": 1,
        "name": "Home",
        "item": `${BASE_URL}`
      }, {
        "@type": "ListItem",
        "position": 2,
        "name": props.title || props.pageTitle,
        "item": `${BASE_URL}/${pathnames[0]}`
      }]
    })
  }
  else{
    return JSON.stringify({
      "@context": "https://schema.org/",
      "@type": "BreadcrumbList",
      "itemListElement": [{
        "@type": "ListItem",
        "position": 1,
        "name": "Home",
        "item": `${BASE_URL}`
      }, {
        "@type": "ListItem",
        "position": 2,
        "name": props.title || props.pageTitle,
        "item": `${BASE_URL}/${pathnames[0]}`
      }, {
        "@type": "ListItem",
        "position": 3,
        "name": props.title || props.pageTitle,
        "item": `${BASE_URL}/${pathnames[0]}/${pathnames[1]}`
      }]
    })
  }
};

const MetaTag = (props) => {
  // console.log(props,'**********')
  const baseUrl = SHARING_URL;
  const noIndexDisabled= props.match.params.href === 'understanding-psychedelic-therapy-5186'
  || props.match.params.href === 'understanding-psychedelic-therapy-5186/7216'
  || props.location.pathname === ROUTE.WHY
  || props.location.pathname === ROUTE.PRIVACY_POLICY
  || props.location.pathname === ROUTE.TERMS
  || props.location.pathname === ROUTE.ACCEPTABLEUSE
  || props.location.pathname === ROUTE.SUPPORT
  || props.location.pathname === ROUTE.HOME_P
  || props.location.pathname === ROUTE.HOME_H
  || props.location.pathname === ROUTE.LEGAL
  || props.location.pathname === ROUTE.HOME || NODE_ENV != 'production' ? false : true;
  const href = `${BASE_URL}${props.location.pathname}`;
  const title= props.pageTitle ? props.pageTitle : props.ogTitle;
  const url= props.url ? props.url : href
  return (<Helmet>
    <title>{props.pageTitle}</title>
    <meta property="og:title" content={title} />
    <meta property="og:image" content={(props || {}).image} />
    <meta property="og:url" content={url} />
    <meta property="og:type" content={(props || {}).type}></meta>
    <meta property="og:description" content={(props || {}).description} />
    <meta property="og:image:width" content={props.ogWidth || "1200"} />
    <meta property="og:image:height" content={props.ogHeight || "630"} />
    <meta name="description" content={(props || {}).description} />
    {/* {
      !(JSON.stringify(props.match.params) === '{}' && NODE_ENV === 'production') && (
        <meta name="robots" content="-index, -follow" />)
    } */}
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:site" content="@dssd" />
    <meta name="twitter:title" content={props.pageTitle} />
    <meta name="twitter:image" content={props.image} />
    <meta name="twitter:description" content={props.description} />
    <meta name="twitter:app:name:iphone" content={props.appName} />
    <meta name="twitter:app:id:iphone" content="1540109137" />
    <meta name="twitter:app:url:iphone" content={props.appURL} />
    <meta name="twitter:app:name:googleplay" content={props.appName} />
    <meta name="twitter:app:id:googleplay" content='com.h.podcast' />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="facebook-domain-verification" content="8x06v66qga8w4c2ibizdz5i1lghaj6" />
    {noIndexDisabled && <meta name="robots" content="noindex, nofollow" />}
    <link rel="canonical" href={href} />
    {
      ![
        ROUTE.HOME,
        ROUTE.WHY_H
      ].includes(props.location.pathname) && (
        <script type="application/ld+json" data-react-helmet="true">{structuredDataSingle(props)}</script>
      )
    }
    {
      props.markup && (
        <script type="application/ld+json" data-react-helmet="true">{JSON.stringify({
          "@context": "https://schema.org",
          "@type": props.markup.type,
          "@id": props.markup.id,
          ...props.markup,
          "type": undefined,
          "id": undefined,
        })}</script>
      )
    }
    { <script type="application/ld+json" data-react-helmet="true" data-rh="true">
        {
          JSON.stringify({
            "@context": "https://schema.org",
            "@type": "Organization",
            "brand": {
              "@type": "Brand",
              "name": "klk",
            },
            "contactPoint": {
              "@type": "ContactPoint",
              "email": "ewe@gmail.com"
            },
            "email": "wew@gmail.com",
            "founder": {
              "@type": "Person",
              "givenName": "ahj"
            },
            "foundingDate": "2020-01-11",
            "legalName": "Hk",
            "location": "India",
            "logo": `${baseUrl}/public/assets/fullLogo.png`,
            "url": `${baseUrl}`
          })
        }
      </script>
      }
  </Helmet>);
}
</code>```

How can I fix this?

答:
I don't know if you are still in trouble but I had the same problem and I just found the solution. In my case the problem was a hydrated variable within a string, (like this ${process.env.METADATA_URL}/${data.slug}) which at the first turn of rendering was set undefined and then inserted by webpack at the bottom of the html file. Once I found another way to set it, the problem was solved.

I hope it was helpful.

Body:
When i test my page in "Google Structured data testing tool" I find this at end of my code.
I am also sharing my component where data is being inserted in helmet:

Please find the code below where data is inserted in helmet:

export const structuredDataSingle = (props) => {
  const arr = [];
  const {
    location: {
      pathname
    },
  } = props;
  const pathnames = pathname.split('/').filter(x => x);
  if(pathnames.length <= 1) {
    return JSON.stringify({
      "@context": "https://schema.org/",
      "@type": "BreadcrumbList",
      "itemListElement": [{
        "@type": "ListItem",
        "position": 1,
        "name": "Home",
        "item": `${BASE_URL}`
      }, {
        "@type": "ListItem",
        "position": 2,
        "name": props.title || props.pageTitle,
        "item": `${BASE_URL}/${pathnames[0]}`
      }]
    })
  }
  else{
    return JSON.stringify({
      "@context": "https://schema.org/",
      "@type": "BreadcrumbList",
      "itemListElement": [{
        "@type": "ListItem",
        "position": 1,
        "name": "Home",
        "item": `${BASE_URL}`
      }, {
        "@type": "ListItem",
        "position": 2,
        "name": props.title || props.pageTitle,
        "item": `${BASE_URL}/${pathnames[0]}`
      }, {
        "@type": "ListItem",
        "position": 3,
        "name": props.title || props.pageTitle,
        "item": `${BASE_URL}/${pathnames[0]}/${pathnames[1]}`
      }]
    })
  }
};

const MetaTag = (props) => {
  // console.log(props,'**********')
  const baseUrl = SHARING_URL;
  const noIndexDisabled= props.match.params.href === 'understanding-psychedelic-therapy-5186'
  || props.match.params.href === 'understanding-psychedelic-therapy-5186/7216'
  || props.location.pathname === ROUTE.WHY
  || props.location.pathname === ROUTE.PRIVACY_POLICY
  || props.location.pathname === ROUTE.TERMS
  || props.location.pathname === ROUTE.ACCEPTABLEUSE
  || props.location.pathname === ROUTE.SUPPORT
  || props.location.pathname === ROUTE.HOME_P
  || props.location.pathname === ROUTE.HOME_H
  || props.location.pathname === ROUTE.LEGAL
  || props.location.pathname === ROUTE.HOME || NODE_ENV != 'production' ? false : true;
  const href = `${BASE_URL}${props.location.pathname}`;
  const title= props.pageTitle ? props.pageTitle : props.ogTitle;
  const url= props.url ? props.url : href
  return (<Helmet>
    <title>{props.pageTitle}</title>
    <meta property="og:title" content={title} />
    <meta property="og:image" content={(props || {}).image} />
    <meta property="og:url" content={url} />
    <meta property="og:type" content={(props || {}).type}></meta>
    <meta property="og:description" content={(props || {}).description} />
    <meta property="og:image:width" content={props.ogWidth || "1200"} />
    <meta property="og:image:height" content={props.ogHeight || "630"} />
    <meta name="description" content={(props || {}).description} />
    {/* {
      !(JSON.stringify(props.match.params) === '{}' && NODE_ENV === 'production') && (
        <meta name="robots" content="-index, -follow" />)
    } */}
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:site" content="@dssd" />
    <meta name="twitter:title" content={props.pageTitle} />
    <meta name="twitter:image" content={props.image} />
    <meta name="twitter:description" content={props.description} />
    <meta name="twitter:app:name:iphone" content={props.appName} />
    <meta name="twitter:app:id:iphone" content="1540109137" />
    <meta name="twitter:app:url:iphone" content={props.appURL} />
    <meta name="twitter:app:name:googleplay" content={props.appName} />
    <meta name="twitter:app:id:googleplay" content='com.h.podcast' />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="facebook-domain-verification" content="8x06v66qga8w4c2ibizdz5i1lghaj6" />
    {noIndexDisabled && <meta name="robots" content="noindex, nofollow" />}
    <link rel="canonical" href={href} />
    {
      ![
        ROUTE.HOME,
        ROUTE.WHY_H
      ].includes(props.location.pathname) && (

      )
    }
    {
      props.markup && (

      )
    }
    {
      }
  </Helmet>);
}

How can I fix this?


问:
HTML - javascript appending a row into a complex table
this is my first question in here...

i have following code :

```<code><form action="{jurl 'fraisreels~default:test'}" method="post">
<div class="row">
    <div class="col-md-12">
        <div class="table-responsive">
            {foreach $attribs as $a}
                <table class="table table-sm table-bordered border-dark" id="">
                    <thead>
                    <tr>
                        <th style="width:5%;" class="text-center align-middle"></th>
                        <th style="width:20%;" class="text-center align-middle">Type de dépense</th>
                        <th style="width:50%;" class="text-center align-middle">Libellé</th>
                        <th style="width:10%;" class="text-center align-middle">€</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td colspan="2"
                            class="bg-primary bg-gradient fw-bold align-middle text-white">{$a[0]->ue_bloc} {$a[0]->ori_lib_court}</td>
                        <td class="bg-primary bg-gradient fw-bold text-center align-middle" colspan="2"><a href=""
                                                                                class="btn btn-warning btn-block"><i
                                        class="fa-solid fa-magnifying-glass"></i> Voir l'ensemble des frais réels
                                introduits par rapport à cette formation</a></td>
                    </tr>
                    {assign $pp = 90000}
                    {foreach $a as $aa}
                        <tr>
                            <td class="text-center align-middle">
                                <button type="button" class="btn btn-success btn-ajouter" data-act=""><i
                                            class="fa-solid fa-plus"></i></button>
                            </td>
                            <td colspan="3" class="align-middle">{$aa->aa_lib}</td>
                        </tr>
                        <tr>
                            <td class="text-center align-middle">
                                <button type="button" class="btn btn-danger btn-supprimer"><i
                                            class="fa-solid fa-trash-can"></i></button>
                                <input type="hidden" class="activite js-aaid" name="aaid[{$lids}]" id="aaid[]"
                                       value="{$aa->aa_id}"/>
                            </td>
                            <td><select name="typefrais[{$lids}]" id="typefrais[]" class="form-select js-typefrais">
                                    <option value="N/C"></option>
                                    <option value="M">Matériel didactique</option>
                                    <option value="O">Ouvrages de référence</option>
                                    <option value="S">Séminaires, visites, voyages</option>
                                </select></td>
                            <td><input type="text" class="form-control js-libelle"
                                       placeholder="exemple: Livre ... (avec références) - voyage - blouse de labo"
                                       id="libelle[]" name="libelle[{$lids}]">
                            </td>
                            <td><input type="text" class="form-control js-prix" placeholder="Prix approximatif"
                                       id="prix[]" name="prix[{$lids}]"></td>
                        </tr>
                    {/foreach}
                    </tbody>
                </table>
            {/foreach}
        </div>
    </div>
</div>
<button type="submit">test</button>
</code>```

I would like to append a line for each new entry that somebody would like to add.
Basicly this table receives data from a controller.

I'd like to add this line everytime a user adds a new record :

```<code><tr>
                            <td class="text-center align-middle">
                                <button type="button" class="btn btn-danger btn-supprimer"><i
                                            class="fa-solid fa-trash-can"></i></button>
                                <input type="hidden" class="activite js-aaid" name="aaid[{$lids}]" id="aaid[]"
                                       value="{$aa->aa_id}"/>
                            </td>
                            <td><select name="typefrais[{$lids}]" id="typefrais[]" class="form-select js-typefrais">
                                    <option value="N/C"></option>
                                    <option value="M">Matériel didactique</option>
                                    <option value="O">Ouvrages de référence</option>
                                    <option value="S">Séminaires, visites, voyages</option>
                                </select></td>
                            <td><input type="text" class="form-control js-libelle"
                                       placeholder="exemple: Livre ... (avec références) - voyage - blouse de labo"
                                       id="libelle[]" name="libelle[{$lids}]">
                            </td>
                            <td><input type="text" class="form-control js-prix" placeholder="Prix approximatif"
                                       id="prix[]" name="prix[{$lids}]"></td>
                        </tr>
</code>```

And here you have a sample pic :
what i want to do :
what i want to do

what i except to obtain :
result

Here you can find my current code:
My code on gitlab

Thank you very much for all your help...
if you need further detailed info i'd be glad to furnish it to you...

答:
        <input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
        <input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
        <input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
        <input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>

```

Body:
this is my first question in here...

i have following code :

<form action="{jurl 'fraisreels~default:test'}" method="post">

            {foreach $attribs as $a}

                        Type de dépense
                        Libellé
                        €

                        {$a[0]->ue_bloc} {$a[0]->ori_lib_court}
                         Voir l'ensemble des frais réels
                                introduits par rapport à cette formation

                    {assign $pp = 90000}
                    {foreach $a as $aa}

                                <button type="button" class="btn btn-success btn-ajouter" data-act=""></button>

                            {$aa->aa_lib}

                                <button type="button" class="btn btn-danger btn-supprimer"></button>
                                <input type="hidden" class="activite js-aaid" name="aaid[{$lids}]" id="aaid[]"
                                       value="{$aa->aa_id}"/>

                            <select name="typefrais[{$lids}]" id="typefrais[]" class="form-select js-typefrais">
                                    <option value="N/C"></option>
                                    <option value="M">Matériel didactique</option>
                                    <option value="O">Ouvrages de référence</option>
                                    <option value="S">Séminaires, visites, voyages</option>
                                </select>
                            <input type="text" class="form-control js-libelle"
                                       placeholder="exemple: Livre ... (avec références) - voyage - blouse de labo"
                                       id="libelle[]" name="libelle[{$lids}]">

                            <input type="text" class="form-control js-prix" placeholder="Prix approximatif"
                                       id="prix[]" name="prix[{$lids}]">

                    {/foreach}

            {/foreach}

<button type="submit">test</button>

I would like to append a line for each new entry that somebody would like to add.
Basicly this table receives data from a controller.

I'd like to add this line everytime a user adds a new record :

                                <button type="button" class="btn btn-danger btn-supprimer"></button>
                                <input type="hidden" class="activite js-aaid" name="aaid[{$lids}]" id="aaid[]"
                                       value="{$aa->aa_id}"/>

                            <select name="typefrais[{$lids}]" id="typefrais[]" class="form-select js-typefrais">
                                    <option value="N/C"></option>
                                    <option value="M">Matériel didactique</option>
                                    <option value="O">Ouvrages de référence</option>
                                    <option value="S">Séminaires, visites, voyages</option>
                                </select>
                            <input type="text" class="form-control js-libelle"
                                       placeholder="exemple: Livre ... (avec références) - voyage - blouse de labo"
                                       id="libelle[]" name="libelle[{$lids}]">

                            <input type="text" class="form-control js-prix" placeholder="Prix approximatif"
                                       id="prix[]" name="prix[{$lids}]">

And here you have a sample pic :
what i want to do :
what i want to do

what i except to obtain :
result

Here you can find my current code:
My code on gitlab

Thank you very much for all your help...
if you need further detailed info i'd be glad to furnish it to you...

Body:
<html>
    <script>
        function addRow() {
            var table = document.getElementById('myTable');
            //var row = document.getElementById("myTable");
            var x = table.insertRow(0);
            var e = table.rows.length-1;
            var l = table.rows[e].cells.length;
            //x.innerHTML = "&nbsp;";

            for (var c=0, m=l; c < m; c++) {
                table.rows[0].insertCell(c);
                table.rows[0].cells[c].innerHTML = "&nbsp;&nbsp;";
            }
        }

        function addColumn() {
            var table = document.getElementById('myTable');
            for (var r = 0, n = table.rows.length; r < n; r++) {
                table.rows[r].insertCell(0);
                table.rows[r].cells[0].innerHTML = "&nbsp;&nbsp;";
            }
        }

        function deleteRow() {
            document.getElementById("myTable").deleteRow(0);
        }

        function deleteColumn() {
            // var row = document.getElementById("myRow");
            var table = document.getElementById('myTable');
            for (var r = 0, n = table.rows.length; r < n; r++) {
                table.rows[r].deleteCell(0); // var table handle
            }
        }
    </script>

    <body>
        <input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
        <input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
        <input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
        <input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>

        <table  id='myTable' border=1 cellpadding=0 cellspacing=0>
            <tr id='myRow'>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
        </table>
    </body>
</html>


问:
How to get file from drive - swagger
So I use swagger and have manage to get link loaded into the system correct. Now I need to get a file from the drive but it seems I cant get it right. Below is both the code for a link and one of my many tries to get a file from a drive.

This is the code

```<code><script src="./swagger-ui-bundle.js"> </script>
<script src="./swagger-ui-standalone-preset.js"> </script>
<script>
     window.onload = function() {

  // Build a system
  const ui = SwaggerUIBundle({
  validatorUrl: null,
  docExpansion: 'none',
  operationsSorter: 'alpha',
   tagsSorter: 'alpha',
   urls: [{url: "C:/web/swagger/swaggerfiles//swagger.json", name: "Something"},
       {url: "http://worksjusstfine/swagger.json", name: "Something else"} ],

dom_id: '#swagger-ui',
deepLinking: true,
presets: [
  SwaggerUIBundle.presets.apis,
  SwaggerUIStandalonePreset
],
plugins: [
  SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
 })

 window.ui = ui
 }
</script>
</code>```

答: To get this working I had to add a directory in IIS and then point out where the files were on the computer. Then I was able to get a http link.</p>

Title: How to get file from drive - swagger


问:
Why does Visual Studio WebDev Not Load my StyleSheet?
So here's an interesting conundrum.

I have a page, default.aspx. It has a LINK tag to a stylesheet, located in the CSS subfolder:

```<code><link type="text/css" rel="Stylesheet" href="Css/Logon.css" media="all" />
</code>```

The folder structure is as follows:

```<code>[Root]
    [CSS]
    [Images]
        [Logon]
</code>```

No big surprises. (Our default.aspx page is our logon page. Again, no big surprises.)

Here's the problem. If you launch the page in IIS, the page renders beautifully. CSS loads, fonts appear, everything is positioned appropriately, and lions are laying down with lambs.

If you view the page in WebDev, the stylesheet isn't loaded. Since it specifies all the images, fonts, and positioning, everything is black on white, in Times New Roman, slammed left against the window border. Dogs are chasing cats in circles and causing traffic accidents. Chaos ensues.

Why? How do I fix it? What information do I need to provide to reach a happy conclusion?

P.S. I am aware of the URL differences between running it in IIS and Webdev, but the differences don't seem to make much sense to me, due to one simple fact: the path to the style sheet is relative to the location of the default.aspx page. The stylesheet isn't being loaded at all. I can see this because there's no font styling at all.

答: We eventually discovered the cause of this problem using Fiddler: HTTP 401 (Unauthorized). A little more research uncovered that we needed to add explicit <location/> entries for the stylesheet, and all the images it referenced, to our web.config file.

Body:
So here's an interesting conundrum.

I have a page, default.aspx. It has a LINK tag to a stylesheet, located in the CSS subfolder:

<link type="text/css" rel="Stylesheet" href="Css/Logon.css" media="all" />

The folder structure is as follows:

[Root]
    [CSS]
    [Images]
        [Logon]

No big surprises. (Our default.aspx page is our logon page. Again, no big surprises.)

Here's the problem. If you launch the page in IIS, the page renders beautifully. CSS loads, fonts appear, everything is positioned appropriately, and lions are laying down with lambs.

If you view the page in WebDev, the stylesheet isn't loaded. Since it specifies all the images, fonts, and positioning, everything is black on white, in Times New Roman, slammed left against the window border. Dogs are chasing cats in circles and causing traffic accidents. Chaos ensues.

Why? How do I fix it? What information do I need to provide to reach a happy conclusion?

P.S. I am aware of the URL differences between running it in IIS and Webdev, but the differences don't seem to make much sense to me, due to one simple fact: the path to the style sheet is relative to the location of the default.aspx page. The stylesheet isn't being loaded at all. I can see this because there's no font styling at all.


问:
Using normal classes with vue composition api
how can I use framework-independent JavaScript class instances with reactive state on vue-composition-api.

Given following class:

```<code>// CounterService / counter-service.ts
//
// this is a normal javascript class which is independent of vue
export const counterService = new (class CounterService {
  private count: number = 0;

  // should cause all components that use `getCount` to react.
  addOne(): void {
    this.count++;
  }

  // should be reactive
  getCount(): number {
    return this.count;
  }
})()
</code>```

Kind regards
Rozbeh Chiryai Sharahi

答:
most important hint: Use reactive or ref on all components involved (those that update and those that read).

```<code>// Component A / Counts.vue
<template>
  <div>{{services.counterService.getCount()}}</div>
</template>
<script lang="ts">
import { counterService } from 'counter-service.ts'
export default defineComponent({
  setup() {
    // You could also use ref, but i prefer to avoid the `.value`
    const services = reactive({
      counterService
    })

    return { services }
  }
});
</script>
</code>```
```<code>// Component B / IncrementCountButton.vue
<template>
  <div @click="services.counterService.addOne()">Increment</div>
</template>
<script lang="ts">
import { counterService } from 'counter-service.ts'
export default defineComponent({
  setup() {
    // You could also use ref, but i prefer to avoid the `.value`
    const services = reactive({
      counterService
    })

    return { services }

  }
});
</script>
</code>```

Kind regards
Rozbeh Chiryai Sharahi

Body:
how can I use framework-independent JavaScript class instances with reactive state on vue-composition-api.

Given following class:

// CounterService / counter-service.ts
//
// this is a normal javascript class which is independent of vue
export const counterService = new (class CounterService {
  private count: number = 0;

  // should cause all components that use `getCount` to react.
  addOne(): void {
    this.count++;
  }

  // should be reactive
  getCount(): number {
    return this.count;
  }
})()

Kind regards
Rozbeh Chiryai Sharahi

Body:
most important hint: Use reactive or ref on all components involved (those that update and those that read).

// Component A / Counts.vue
<template>
  <div>{{services.counterService.getCount()}}</div>
</template>
<script lang="ts">
import { counterService } from 'counter-service.ts'
export default defineComponent({
  setup() {
    // You could also use ref, but i prefer to avoid the `.value`
    const services = reactive({
      counterService
    })

    return { services }
  }
});
</script>

// Component B / IncrementCountButton.vue
<template>
  <div @click="services.counterService.addOne()">Increment</div>
</template>
<script lang="ts">
import { counterService } from 'counter-service.ts'
export default defineComponent({
  setup() {
    // You could also use ref, but i prefer to avoid the `.value`
    const services = reactive({
      counterService
    })

    return { services }

  }
});
</script>

Kind regards
Rozbeh Chiryai Sharahi


问:
How to preserve SQL performance that I get with IQueryable<Entity> with a IQueryable<DTO> when using oData?
I am using EF Core and oData.  I've noticed that oData "magically" updates my query when my controller returns an IQueryable that returns an EF Core entity, but as soon as I try to return a DTO of that Entity, all data is requested in the SQL query.

Examples:

This API Action:

```<code>    [EnableQuery]
    public ActionResult<IEnumerable<ProjectEntity>> Get()
    {
        return Ok(_db.Projects);
    }
</code>```

Generates this query:

```<code>SELECT [s].[Id], [s].[EndDate], [s].[StartDate], [p].[CustomerId], [p].[Name]
FROM [ScheduleEvents] AS [s] INNER JOIN [Projects] AS [p] ON [s].[Id] = [p].[Id]
</code>```

but if I return DTO's instead with this Action:

```<code>    [EnableQuery]
    public ActionResult<IEnumerable<ProjectDTO>> Get()
    {
        return Ok(_autoMapper.ProjectTo<ProjectDTO>(_db.Projects));
    }
</code>```

Then the SQL is this:

```<code>SELECT CAST(0 AS bit), [c].[Id], [c].[Name], [p].[CustomerId], [s].[EndDate],
[s].[Id],[p].[Name], [s].[StartDate] FROM [ScheduleEvents] AS [s]
INNER JOIN [Projects] AS [p] ON [s].[Id] = [p].[Id] INNER JOIN [Customers] AS [c]
ON [p].[CustomerId] = [c].[Id]
</code>```

OData magically knows how to add the join only when I use the $Expand syntax when using an Entity as the return type, but with a DTO the joins are made whether or not I requested them.

Is there something I can do in Automapper or oData to get the same SQL behavior with oData for both Entities and DTOs?

答:
Instead of .ProjectTo we need to use an additional package: AutoMapper.Extensions.ExpressionMapping that will give us access to the UseAsDataSource extension method.

UseAsDataSource

UseAsDataSource().For<DTO>() makes this translation clean by not having to explicitly map expressions. It also calls ProjectTo() for you as well, where applicable.

This changes your implementation to the following:

```<code>[EnableQuery]
public ActionResult<IQueryable<ProjectDTO>> Get()
{
    return Ok(_db.Projects.UseAsDataSource().For<ProjectDTO>());
}
</code>```

Though the question title is not related, the performance issue and reasoning is discussed in these two similar posts:

OData accent-insensitive filter

Automapper ProjectTo maps the subTypes also which not required while using OData

Body:
I am using EF Core and oData.  I've noticed that oData "magically" updates my query when my controller returns an IQueryable that returns an EF Core entity, but as soon as I try to return a DTO of that Entity, all data is requested in the SQL query.

Examples:

This API Action:

    [EnableQuery]
    public ActionResult<IEnumerable<ProjectEntity>> Get()
    {
        return Ok(_db.Projects);
    }

Generates this query:

SELECT [s].[Id], [s].[EndDate], [s].[StartDate], [p].[CustomerId], [p].[Name]
FROM [ScheduleEvents] AS [s] INNER JOIN [Projects] AS [p] ON [s].[Id] = [p].[Id]

but if I return DTO's instead with this Action:

    [EnableQuery]
    public ActionResult<IEnumerable<ProjectDTO>> Get()
    {
        return Ok(_autoMapper.ProjectTo<ProjectDTO>(_db.Projects));
    }

Then the SQL is this:

SELECT CAST(0 AS bit), [c].[Id], [c].[Name], [p].[CustomerId], [s].[EndDate],
[s].[Id],[p].[Name], [s].[StartDate] FROM [ScheduleEvents] AS [s]
INNER JOIN [Projects] AS [p] ON [s].[Id] = [p].[Id] INNER JOIN [Customers] AS [c]
ON [p].[CustomerId] = [c].[Id]

OData magically knows how to add the join only when I use the $Expand syntax when using an Entity as the return type, but with a DTO the joins are made whether or not I requested them.

Is there something I can do in Automapper or oData to get the same SQL behavior with oData for both Entities and DTOs?

Body:
Instead of .ProjectTo we need to use an additional package: AutoMapper.Extensions.ExpressionMapping that will give us access to the UseAsDataSource extension method.

UseAsDataSource

UseAsDataSource().For<DTO>() makes this translation clean by not having to explicitly map expressions. It also calls ProjectTo() for you as well, where applicable.

This changes your implementation to the following:

[EnableQuery]
public ActionResult<IQueryable<ProjectDTO>> Get()
{
    return Ok(_db.Projects.UseAsDataSource().For<ProjectDTO>());
}

Though the question title is not related, the performance issue and reasoning is discussed in these two similar posts:

OData accent-insensitive filter

Automapper ProjectTo maps the subTypes also which not required while using OData


答:
Because this part only replaces the formulas with values in the first sheet Worksheets(1)

```<code>With .Worksheets(1).UsedRange
    .Value = .Value
End With
</code>```

If you want to do that with all worksheets in the new workbook you need to loop

```<code>Dim ws As Worksheet
For Each ws In wbNew.Worksheets
    With ws.UsedRange
        .Value = .Value
    End With
Next ws
</code>```

This will replace formulas in all worksheets you copied into the wbNew no matter how many worksheets you copied.

Title: How to copy two sheets to a new workbook as value VBA

Body:
I am using the code below to copy two specific sheets to a new workbook. The code works, but only the first one is copied as value, the second one is copied ad formula.

Does anyone knows how can both sheets be copied as value? Many thanks!! =D

Sub CopyTabsToNewWorkbook()

Dim wbNew As Workbook
Dim path As String
Dim filename As String

     Application.ScreenUpdating = False
     Application.DisplayAlerts = False

    'To unhide the tab
     Worksheets("EMEA & AM").Visible = xlSheetVisible
     Worksheets("CAT").Visible = xlSheetVisible

     Worksheets(Array("EMEA & AM", "CAT")).Copy

    Set wbNew = ActiveWorkbook
    With wbNew
        With .Worksheets(1).UsedRange
        .Value = .Value
        End With

        path = "https://Shared Link Path/" & "\"
        filename = Range("AP1")

        .SaveAs filename:=path & filename
        .Close savechanges:=False
     End With

     'To hide the tab
      Worksheets("EMEA & AM").Visible = xlSheetHidden
      Worksheets("CAT").Visible = xlSheetHidden
End Sub

Body:
Because this part only replaces the formulas with values in the first sheet Worksheets(1)

With .Worksheets(1).UsedRange
    .Value = .Value
End With

If you want to do that with all worksheets in the new workbook you need to loop

Dim ws As Worksheet
For Each ws In wbNew.Worksheets
    With ws.UsedRange
        .Value = .Value
    End With
Next ws

This will replace formulas in all worksheets you copied into the wbNew no matter how many worksheets you copied.


问:
How can i mock datetime.utcnow()?
I have this code in my class.__init__():

self.timestamp = datetime.utcnow()
```

I want to mock this function for testing. I want to mock 3 different dates: 03.02.2022, 02.02.2022 and 01.02.2022. So how can i do it?

I use pytest

答:
this library could be help you https://github.com/spulec/freezegun/</p>
```<code>from freezegun import freeze_time
import datetime
import unittest

# Freeze time for a pytest style test:

@freeze_time("2012-01-14")
def test():
    assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
</code>```

Title: How can i mock datetime.utcnow()?

Body:
I have this code in my class.__init__():

self.timestamp = datetime.utcnow()

I want to mock this function for testing. I want to mock 3 different dates: 03.02.2022, 02.02.2022 and 01.02.2022. So how can i do it?

I use pytest

Body:
this library could be help you https://github.com/spulec/freezegun/

from freezegun import freeze_time
import datetime
import unittest

# Freeze time for a pytest style test:

@freeze_time("2012-01-14")
def test():
    assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)


问:
How to disable Qt (5) high-dpi scaling temporarily?
I know that I can disable DPI scaling for the entire application by calling QApplication::setAttribute( Qt::AA_DisableHighDpiScaling ); before creating the QApplication instance. But, is it possible to set a QPainter/QGraphicsScene/QGraphicsView to ignore DPI?

I want all the widgets in my application to behave normally. I just want to draw a grid, in a view, without DPI scaling. That setting fixes the grid, but it prevents the widgets from scaling.

Note: I cannot easily just clobbering the scale of the graphical items, because I don't know the exact DPI. I haven't been able to find a value, anywhere, that explains exactly how QPainter draws. It seems to be quite magical. I also don't want to try to do that, because of the potential numeric instability of just tacking on additional factors. I'd like to remove a factor, temporarily...

答:
Short answer is no; the high-dpi handling is all or nothing.

For stuff you paint yourself with QPainter, there are a couple of effective workarounds. The first is to apply the inverse scaling. I wouldn't worry much about numeric instability here; in practice the QPainter ends up with a unity transform internally. So like this:

```<code>QPainter p(myWidget);
qreal inverseDPR = 1.0 / myWidget->devicePixelRatio();
p.scale(inverseDPR, inverseDPR);
</code>```

The second way is to first render into a QImage, which by default has DPR==1. Then set the DPR of the image to the DPR of the widget before painting the image to the widget. That way, one avoids that the image gets scaled during painting. Like so:

```<code>QImage img(...);
// ... paint into image
img.setDevicePixelRatio(myWidget->devicePixelRatio());
QPainter p(myWidget);
p.drawImage(... image ...);
</code>```

Body:
Short answer is no; the high-dpi handling is all or nothing.

For stuff you paint yourself with QPainter, there are a couple of effective workarounds. The first is to apply the inverse scaling. I wouldn't worry much about numeric instability here; in practice the QPainter ends up with a unity transform internally. So like this:

QPainter p(myWidget);
qreal inverseDPR = 1.0 / myWidget->devicePixelRatio();
p.scale(inverseDPR, inverseDPR);

The second way is to first render into a QImage, which by default has DPR==1. Then set the DPR of the image to the DPR of the widget before painting the image to the widget. That way, one avoids that the image gets scaled during painting. Like so:

QImage img(...);
// ... paint into image
img.setDevicePixelRatio(myWidget->devicePixelRatio());
QPainter p(myWidget);
p.drawImage(... image ...);


问:
Babel get array element at index N
I am rebuilding a program's AST and one of the conditions I have is to obtain given array's element at index N. To see how I should build this I went to the AST Explorer as usual and saw how this statement is build:

```<code>arr[0];
</code>```

The output is:

```<code>{
        "type": "MemberExpression",
        "start": 0,
        "end": 4,
        "object": {
          "type": "Identifier",
          "start": 0,
          "end": 1,
          "name": "a"
        },
        "property": {
          "type": "Literal",
          "start": 2,
          "end": 3,
          "value": 0,
          "raw": "0"
        },
        "computed": true,
        "optional": false
      }
</code>```

Since in Babel for numeric literals we use numericLiteral I tried this:

```<code>memberExpression(identifier(<myArrayNameAsAString>), numericLiteral(0))
</code>```

Which surprisingly threw the error:

```<code>Error: Property property of MemberExpression expected node to be of a type ["Identifier","PrivateName"] but instead got "NumericLiteral"
</code>```

Now I started wondering how does Babel build such an AST in the first place. So I gave this expression:

```<code>arr[0]
</code>```

And got this output (from Babel):

```<code>MemberExpression: {
  {
    ...,
    type: 'Identifier',
    name: 'arr'
  },
  {
    ...,
    type: 'NumericLiteral',
    value: 0
  }
}
</code>```

It looks like Babel is able to build exactly what I want to build but when I do it it throws me an error.

As an alternative I looked at other ways to achieve this, such as using .at. However, the operation is not yet widely adopted and I would like to avoid it.

答:
After debugging deeper Babel requires the property computed to be true. It has an internal validator that looks like this:

```<code>const normal = (0, _utils.assertNodeType)("Identifier", "PrivateName");
const computed = (0, _utils.assertNodeType)("Expression");
</code>```

In the case that the property computed is not set the only 2 allowed options are Identifier and PrivateName.

Title: Babel get array element at index N

Body:
I am rebuilding a program's AST and one of the conditions I have is to obtain given array's element at index N. To see how I should build this I went to the AST Explorer as usual and saw how this statement is build:

arr[0];

The output is:

{
        "type": "MemberExpression",
        "start": 0,
        "end": 4,
        "object": {
          "type": "Identifier",
          "start": 0,
          "end": 1,
          "name": "a"
        },
        "property": {
          "type": "Literal",
          "start": 2,
          "end": 3,
          "value": 0,
          "raw": "0"
        },
        "computed": true,
        "optional": false
      }

Since in Babel for numeric literals we use numericLiteral I tried this:

memberExpression(identifier(<myArrayNameAsAString>), numericLiteral(0))

Which surprisingly threw the error:

Error: Property property of MemberExpression expected node to be of a type ["Identifier","PrivateName"] but instead got "NumericLiteral"

Now I started wondering how does Babel build such an AST in the first place. So I gave this expression:

arr[0]

And got this output (from Babel):

MemberExpression: {
  {
    ...,
    type: 'Identifier',
    name: 'arr'
  },
  {
    ...,
    type: 'NumericLiteral',
    value: 0
  }
}

It looks like Babel is able to build exactly what I want to build but when I do it it throws me an error.

As an alternative I looked at other ways to achieve this, such as using .at. However, the operation is not yet widely adopted and I would like to avoid it.

Body:
After debugging deeper Babel requires the property computed to be true. It has an internal validator that looks like this:

const normal = (0, _utils.assertNodeType)("Identifier", "PrivateName");
const computed = (0, _utils.assertNodeType)("Expression");

In the case that the property computed is not set the only 2 allowed options are Identifier and PrivateName.


问:
Recursion: Collatz sequence -Could someone please explain how this code returns the total number of steps?
```<code>#include <cs50.h>

int collatz(int n);

int main(void)
{
    int n = get_int("Enter int: ");
    int steps = collatz(n);
    printf("%i\n", steps);
}

int collatz(int n)
{
    if (n==1)
    {
        return 0;
    }

    else if ((n%2)==0)
    {
        return 1 + collatz(n/2);
    }

    else
    {
        return 1 + collatz(3 * n + 1);
    }
}
</code>```

I am geting stuck trying to visualise how the 'return 1' on each iteration of the function gets 'carried through'.

I can write the steps out on paper to show that it does work, however I am struggling to make clear in my mind without going through step-by-step, why you have to +1 on every iteration of collatz.

答:
Try to visualize it as follows:

starting number: 3

```<code>** collatz(3): return 1 + collatz(10); **

collatz(10): return 1 + collatz(5);

** collatz(3): return 1 + (1 + collatz(5)); **

collatz(5): return 1 + collatz(16);

** collatz(3): return 1 + (1 + (1 + collatz(16))); **

collatz(16): return 1 + collatz(8);

** collatz(3): return 1 + (1 + (1 + (1 + collatz(8)))); **

collatz(8): return 1 + collatz(4);

** collatz(3): return 1 + (1 + (1 + (1 + (1 + collatz(4))))); **

collatz(4): return 1 + collatz(2);

** collatz(3): return 1 + (1 + (1 + (1 + (1 + (1 + collatz(2)))))); **

collatz(2): return 1 + collatz(1);

collatz(1): return 0;

** collatz(3): return 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0; **
</code>```

Body:
#include <cs50.h>

int collatz(int n);

int main(void)
{
    int n = get_int("Enter int: ");
    int steps = collatz(n);
    printf("%i\n", steps);
}

int collatz(int n)
{
    if (n==1)
    {
        return 0;
    }

    else if ((n%2)==0)
    {
        return 1 + collatz(n/2);
    }

    else
    {
        return 1 + collatz(3 * n + 1);
    }
}

I am geting stuck trying to visualise how the 'return 1' on each iteration of the function gets 'carried through'.

I can write the steps out on paper to show that it does work, however I am struggling to make clear in my mind without going through step-by-step, why you have to +1 on every iteration of collatz.

Body:
Try to visualize it as follows:

starting number: 3

** collatz(3): return 1 + collatz(10); **

collatz(10): return 1 + collatz(5);

** collatz(3): return 1 + (1 + collatz(5)); **

collatz(5): return 1 + collatz(16);

** collatz(3): return 1 + (1 + (1 + collatz(16))); **

collatz(16): return 1 + collatz(8);

** collatz(3): return 1 + (1 + (1 + (1 + collatz(8)))); **

collatz(8): return 1 + collatz(4);

** collatz(3): return 1 + (1 + (1 + (1 + (1 + collatz(4))))); **

collatz(4): return 1 + collatz(2);

** collatz(3): return 1 + (1 + (1 + (1 + (1 + (1 + collatz(2)))))); **

collatz(2): return 1 + collatz(1);

collatz(1): return 0;

** collatz(3): return 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0; **


问:
Python function call with Class name instead of object
```<code>class MyClass:
    def func1(a,b):
         print(a,b)

MyClass.func1(4,5)
</code>```

I thought the above piece of code will throw error because we are accessing a method that is declared without @staticmethod decorator using class.

So does that mean the function called with class name will act like a static method ?

答:
You can access functions of a class from the class name itself, there is no need to create an object or use @staticmethod. MyClass is similar to str both are classes. Consider the following example:

```<code>class MyClass:
    def func1(a,b):
         print(a,b)

print(type(MyClass)) #types are the same
print(type(str)) #types are the same
x = str.__add__('test', " best") #you can use str.__add__ without using str objects
print(x) #output: test best
</code>```

The output in your example works for the same reason this does. 'test' + " best" just calls __add__ just like o = MyClass() would create an object that could call func1. You are just accessing the functions that are stored in these classes and calling the function directly without assigning an object first and using the method within that object.

In this case the class is just a holder for the function. If this was the intended use you would most likely want to use a normal function rather than making in a class attribute.

Body:
class MyClass:
    def func1(a,b):
         print(a,b)

MyClass.func1(4,5)

I thought the above piece of code will throw error because we are accessing a method that is declared without @staticmethod decorator using class.

So does that mean the function called with class name will act like a static method ?

Body:
You can access functions of a class from the class name itself, there is no need to create an object or use @staticmethod. MyClass is similar to str both are classes. Consider the following example:

class MyClass:
    def func1(a,b):
         print(a,b)

print(type(MyClass)) #types are the same
print(type(str)) #types are the same
x = str.__add__('test', " best") #you can use str.__add__ without using str objects
print(x) #output: test best

The output in your example works for the same reason this does. 'test' + " best" just calls __add__ just like o = MyClass() would create an object that could call func1. You are just accessing the functions that are stored in these classes and calling the function directly without assigning an object first and using the method within that object.

In this case the class is just a holder for the function. If this was the intended use you would most likely want to use a normal function rather than making in a class attribute.